datalad-core/datalad_core/git_utils/parsers.py
Michael Hanke 5660e2d662
All checks were successful
Codespell / Check for spelling errors (push) Successful in 32s
Ruff / Code linting (push) Successful in 39s
Type annotation (project) / check (push) Successful in 1m22s
Unit tests (Linux) / check (push) Successful in 2m7s
rf: use type alias to fully detail type of a parsed Git config
2026-06-03 13:26:18 +02:00

88 lines
3.5 KiB
Python

from collections.abc import Iterator
ParsedGitConfig = dict[str, dict[str, str | list[str] | dict[str, str | list[str]]]]
def parse_gitconfig_zlines(
lines: Iterator[str],
) -> ParsedGitConfig:
"""Parse lines produced by `iter_git_subproc_zlines()`
``lines`` is an iterable with individual items matching the output
of ``git config list --null``, after null-byte-based splitting.
`iter_git_subproc_zlines()` takes care of removing any trailing
null-byte separators. If another source is used, it is the callers
responsibility to ensure this.
A (nested) dictionary is returned. The structure depends on the
nature of ``lines``. If they contain scope-information
(``git config list --show-scope``) the keys of the first level represent
scopes (``global``, ``local``, etc.). If origin-information is included,
the form the keys of any following nesting level (``command line``,
``file:...``). The next, up to 2-to-3 levels, represent the actual
configuration keys. The key until the first dot forms the top-level. The
key after the last dot creates the last level. Any additional "dotted"
components jointly (concatenated) for a middle level. For example,
a key ``url.git@codeberg.org:.insteadof`` translates to
``{'url': {'git@codeberg.org': {'insteadof': ... }}}``.
A single value for a key is stored as a ``str``. When multiple values
are found, they are returned as a list of ``str``.
A ``ValueError`` is raised for malformed keys (missing top-level section
or single-part keys).
"""
res: ParsedGitConfig = {}
def _ensure_key(
d: ParsedGitConfig,
key: str,
default,
):
val = d.get(key, default)
d[key] = val
return val
# curr will be the dict that is the current scope of a value assignment.
# it will become a scope or origin container, or nested key container as
# necessary, depending on the received output from git-config
curr = res
for line in lines:
if '\n' not in line:
# this is not a key-value specification, but an origin/scope
# declaration -> create/enter the respective nested object
curr = _ensure_key(curr, line, {})
continue
# this is a key-value specification. the key has at least one
# "dot" and there is at least one newline, separating key and value
key, value = line.split('\n', maxsplit=1)
key_l = key.split('.')
# there will always be at least one item in the list given by split()
# if that value is empty, we have an issue.
# likewise, we expect a section+key at all time.
min_dotted_components = 2
if not len(key_l[0]) or len(key_l) < min_dotted_components:
msg = f'Expected config item key, got {key!r} from {line!r}'
raise ValueError(msg)
# there will always be a top-level key
curr = _ensure_key(curr, key_l[0], {})
if len(key_l) > min_dotted_components:
# it makes no sense to split by any intermediate dots, everything
# but the last element is the "middle key"
curr = _ensure_key(curr, '.'.join(key_l[1:-1]), {})
name = key_l[-1]
v = curr.get(name)
if v is None:
curr[name] = value
elif isinstance(v, list):
curr[name].append(value)
else:
curr[name] = [curr[name], value]
# value assignment is done, exit to top, expecting the next
# sequence
curr = res
return res