Skip to content

Commit cc7b973

Browse files
Byroncodex
andcommitted
Preserve Git config value semantics
<!-- agent --> Decode Git-supported quoted value escapes directly instead of routing UTF-8 text through Python unicode_escape. This preserves newlines, quotes, backslashes, and non-ASCII text when an unrelated config update rewrites existing values. Quote values containing Git comment delimiters (# and ;) or leading/trailing whitespace so Git does not truncate or trim their data. Escape LF, tab, backspace, quote, and backslash, while rejecting carriage returns and NULs before opening the destination. Regression coverage round-trips these values through both GitPython and git config and verifies unsafe control characters cannot alter the original file. Behavior follows Git config.c parse_value() and write_pair(). Assisted-by: GPT 5.6 Co-authored-by: GPT 5.6 <codex@openai.com>
1 parent 52a6cba commit cc7b973

2 files changed

Lines changed: 100 additions & 14 deletions

File tree

git/config.py

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -462,7 +462,8 @@ def string_decode(v: str) -> str:
462462
v = v[:-1]
463463
# END cut trailing escapes to prevent decode error
464464

465-
return v.encode(defenc).decode("unicode_escape")
465+
escapes = {"b": "\b", "n": "\n", "r": "\r", "t": "\t", '"': '"', "\\": "\\"}
466+
return re.sub(r"\\(.)", lambda match: escapes.get(match.group(1), match.group(0)), v)
466467

467468
# END string_decode
468469

@@ -517,10 +518,12 @@ def string_decode(v: str) -> str:
517518
# Opens quoting and does not close: appears to start multi-line quoting.
518519
is_multi_line = True
519520
optval = string_decode(optval[1:])
520-
elif optval.find("\\", 1, -1) == -1 and optval.find('"', 1, -1) == -1:
521-
# Opens and closes quoting. Single line, and all we need is quote removal.
522-
optval = optval[1:-1]
523-
# TODO: Handle other quoted content, especially well-formed backslash escapes.
521+
elif re.search(r'(?:^|[^\\])(?:\\\\)*"', optval[1:-1]):
522+
# Preserve malformed values containing unescaped quotes.
523+
pass
524+
else:
525+
# Opens and closes quoting.
526+
optval = string_decode(optval[1:-1])
524527

525528
# Preserves multiple values for duplicate optnames.
526529
cursect.add(optname, optval)
@@ -706,7 +709,7 @@ def write_section(name: str, section_dict: _OMD) -> None:
706709

707710
for v in values:
708711
value = self._value_to_string(v)
709-
if any(char in value for char in '\n\t\b\\"'):
712+
if any(char in value for char in '\n\t\b\\"#;') or value[:1].isspace() or value[-1:].isspace():
710713
value = value.replace("\\", "\\\\").replace('"', '\\"')
711714
value = '"%s\\\n"' % value.replace("\n", "\\n").replace("\t", "\\t").replace("\b", "\\b")
712715
fp.write(("\t%s = %s\n" % (key, value)).encode(defenc))
@@ -768,6 +771,20 @@ def write(self) -> None:
768771
return
769772
# END stop if we have include files
770773

774+
sections: List[_OMD] = [self._defaults]
775+
section: _OMD
776+
stored_section: _OMD
777+
values: List[Any]
778+
raw_value: Any
779+
for _, stored_section in self._sections.items():
780+
sections.append(stored_section)
781+
for section in sections:
782+
for key, values in section.items_all():
783+
if key != "__name__":
784+
for raw_value in values:
785+
if "\r" in self._value_to_string(raw_value) or "\x00" in self._value_to_string(raw_value):
786+
raise ValueError("Git config values must not contain CR or NUL")
787+
771788
fp = self._file_or_files
772789

773790
# We have a physical file on disk, so get a lock.

test/test_config.py

Lines changed: 77 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,16 @@ def test_rewriting_multiline_value_does_not_create_option(self, rw_dir):
170170
@with_rw_directory
171171
def test_writer_escapes_special_characters_without_newline(self, rw_dir):
172172
config_path = osp.join(rw_dir, "config")
173-
values = {"tab": "\tvalue\t", "backspace": "a\bb", "quote": 'a"b', "backslash": "a\\qb"}
173+
values = {
174+
"tab": "\tvalue\t",
175+
"backspace": "a\bb",
176+
"quote": 'a"b',
177+
"backslash": "a\\qb",
178+
"hash": "value#fragment",
179+
"semicolon": "value;fragment",
180+
"leading": " value",
181+
"trailing": "value ",
182+
}
174183

175184
with GitConfigParser(config_path, read_only=False) as git_config:
176185
for key, value in values.items():
@@ -190,6 +199,67 @@ def test_writer_escapes_special_characters_without_newline(self, rw_dir):
190199
with open(config_path, "rb") as config_file:
191200
self.assertNotIn(b"\x08", config_file.read())
192201

202+
@with_rw_directory
203+
def test_writer_preserves_escaped_and_non_ascii_values_safely(self, rw_dir):
204+
config_path = osp.join(rw_dir, "config")
205+
with open(config_path, "wb") as config_file:
206+
config_file.write(
207+
(
208+
'[section]\nnewline = "first\\nsecond"\nquote = "a\\"b"\nbackslash = "a\\\\b"\n'
209+
'unicode = "café\\\\path"\n'
210+
).encode()
211+
)
212+
213+
with GitConfigParser(config_path, read_only=False) as config:
214+
config.set_value("unrelated", "key", "value")
215+
216+
expected = {
217+
"newline": "first\nsecond",
218+
"quote": 'a"b',
219+
"backslash": "a\\b",
220+
"unicode": "café\\path",
221+
}
222+
with GitConfigParser(config_path, read_only=True) as config:
223+
for key, value in expected.items():
224+
self.assertEqual(
225+
config.get_value("section", key),
226+
value,
227+
"GitPython should preserve values when rewriting unrelated entries",
228+
)
229+
self.assertEqual(
230+
subprocess.run(
231+
["git", "config", "--file", config_path, "--get", "section.%s" % key],
232+
stdout=subprocess.PIPE,
233+
check=True,
234+
).stdout,
235+
value.encode() + b"\n",
236+
"git should read rewritten values with the same semantics",
237+
)
238+
239+
with open(config_path, "rb") as config_file:
240+
contents = config_file.read()
241+
self.assertNotIn(b"\r", contents, "the writer should never emit carriage returns")
242+
self.assertNotIn(b"\x00", contents, "the writer should never emit NUL bytes")
243+
244+
for name, value in (("return", b"first\\rsecond"), ("nul", b"first\x00second")):
245+
unsafe_path = osp.join(rw_dir, "%s-config" % name)
246+
unsafe_contents = b'[section]\nvalue = "' + value + b'"\n'
247+
with open(unsafe_path, "wb") as config_file:
248+
config_file.write(unsafe_contents)
249+
with self.assertRaisesRegex(
250+
ValueError,
251+
"CR or NUL",
252+
msg="unsafe existing values should abort rewrites",
253+
):
254+
with GitConfigParser(unsafe_path, read_only=False) as config:
255+
config.set_value("unrelated", "key", "value")
256+
with open(unsafe_path, "rb") as config_file:
257+
self.assertEqual(
258+
config_file.read(),
259+
unsafe_contents,
260+
"rejected rewrites should leave the original file unchanged",
261+
)
262+
193263
@with_rw_directory
194264
def test_set_value_rejects_config_injection(self, rw_dir):
195265
config_path = osp.join(rw_dir, "config")
@@ -745,15 +815,14 @@ def test_config_with_quotes_with_whitespace_outside_value(self):
745815
self.assertEqual(cr.get("init", "defaultBranch"), "trunk")
746816

747817
def test_config_with_quotes_containing_escapes(self):
748-
"""For now just suppress quote removal. But it would be good to interpret most of these."""
818+
"""Interpret Git's quoted escapes without changing malformed values."""
749819
cr = GitConfigParser(fixture_path("git_config_with_quotes_escapes"), read_only=True)
750820

751-
# These can eventually be supported by substituting the represented character.
752-
self.assertEqual(cr.get("custom", "hasnewline"), R'"first\nsecond"')
753-
self.assertEqual(cr.get("custom", "hasbackslash"), R'"foo\\bar"')
754-
self.assertEqual(cr.get("custom", "hasquote"), R'"ab\"cd"')
755-
self.assertEqual(cr.get("custom", "hastrailingbackslash"), R'"word\\"')
756-
self.assertEqual(cr.get("custom", "hasunrecognized"), R'"p\qrs"')
821+
self.assertEqual(cr.get("custom", "hasnewline"), "first\nsecond")
822+
self.assertEqual(cr.get("custom", "hasbackslash"), R"foo\bar")
823+
self.assertEqual(cr.get("custom", "hasquote"), 'ab"cd')
824+
self.assertEqual(cr.get("custom", "hastrailingbackslash"), "word\\")
825+
self.assertEqual(cr.get("custom", "hasunrecognized"), R"p\qrs")
757826

758827
# It is less obvious whether and what to eventually do with this.
759828
self.assertEqual(cr.get("custom", "hasunescapedquotes"), '"ab"cd"e"')

0 commit comments

Comments
 (0)