Commit eefa7e4

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 eefa7e4

2 files changed

Lines changed: 102 additions & 15 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-
returnv.encode(defenc).decode("unicode_escape")
465+
escapes= {"b": "\b", "n": "\n", "r": "\r", "t": "\t", '"': '"', "\\": "\\"}
466+
returnre.sub(r"\\(.)", lambdamatch: 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-
elifoptval.find("\\", 1, -1) ==-1andoptval.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+
elifre.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
forvinvalues:
708711
value=self._value_to_string(v)
709-
ifany(charinvalueforcharin'\n\t\b\\"'):
712+
ifany(charinvalueforcharin'\n\t\b\\"#;') orvalue[:1].isspace() orvalue[-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_sectioninself._sections.items():
780+
sections.append(stored_section)
781+
forsectioninsections:
782+
forkey, valuesinsection.items_all():
783+
ifkey!="__name__":
784+
forraw_valueinvalues:
785+
if"\r"inself._value_to_string(raw_value) or"\x00"inself._value_to_string(raw_value):
786+
raiseValueError("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: 79 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
importpytest
1515

1616
fromgitimportGitConfigParser
17+
fromgit.compatimportdefenc
1718
fromgit.configimport_OMD, cp
1819
fromgit.utilimportcwd, rmfile
1920
fromtest.libimportSkipTest, TestCase, fixture_path, with_rw_directory
@@ -170,7 +171,16 @@ def test_rewriting_multiline_value_does_not_create_option(self, rw_dir):
170171
@with_rw_directory
171172
deftest_writer_escapes_special_characters_without_newline(self, rw_dir):
172173
config_path=osp.join(rw_dir, "config")
173-
values= {"tab": "\tvalue\t", "backspace": "a\bb", "quote": 'a"b', "backslash": "a\\qb"}
174+
values= {
175+
"tab": "\tvalue\t",
176+
"backspace": "a\bb",
177+
"quote": 'a"b',
178+
"backslash": "a\\qb",
179+
"hash": "value#fragment",
180+
"semicolon": "value;fragment",
181+
"leading": " value",
182+
"trailing": "value ",
183+
}
174184

175185
withGitConfigParser(config_path, read_only=False) asgit_config:
176186
forkey, valueinvalues.items():
@@ -185,11 +195,72 @@ def test_writer_escapes_special_characters_without_newline(self, rw_dir):
185195
stdout=subprocess.PIPE,
186196
check=True,
187197
).stdout,
188-
value.encode() +b"\n",
198+
value.encode(defenc) +b"\n",
189199
)
190200
withopen(config_path, "rb") asconfig_file:
191201
self.assertNotIn(b"\x08", config_file.read())
192202

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

747818
deftest_config_with_quotes_containing_escapes(self):
748-
"""For now just suppress quote removal. But it would be good to interpret most of these."""
819+
"""Interpret Git's quoted escapes without changing malformed values."""
749820
cr=GitConfigParser(fixture_path("git_config_with_quotes_escapes"), read_only=True)
750821

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"')
822+
self.assertEqual(cr.get("custom", "hasnewline"), "first\nsecond")
823+
self.assertEqual(cr.get("custom", "hasbackslash"), R"foo\bar")
824+
self.assertEqual(cr.get("custom", "hasquote"), 'ab"cd')
825+
self.assertEqual(cr.get("custom", "hastrailingbackslash"), "word\\")
826+
self.assertEqual(cr.get("custom", "hasunrecognized"), R"p\qrs")
757827

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

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit eefa7e4

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 eefa7e4

2 files changed

Lines changed: 102 additions & 15 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-
returnv.encode(defenc).decode("unicode_escape")
465+
escapes= {"b": "\b", "n": "\n", "r": "\r", "t": "\t", '"': '"', "\\": "\\"}
466+
returnre.sub(r"\\(.)", lambdamatch: 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-
elifoptval.find("\\", 1, -1) ==-1andoptval.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+
elifre.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
forvinvalues:
708711
value=self._value_to_string(v)
709-
ifany(charinvalueforcharin'\n\t\b\\"'):
712+
ifany(charinvalueforcharin'\n\t\b\\"#;') orvalue[:1].isspace() orvalue[-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_sectioninself._sections.items():
780+
sections.append(stored_section)
781+
forsectioninsections:
782+
forkey, valuesinsection.items_all():
783+
ifkey!="__name__":
784+
forraw_valueinvalues:
785+
if"\r"inself._value_to_string(raw_value) or"\x00"inself._value_to_string(raw_value):
786+
raiseValueError("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: 79 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
importpytest
1515

1616
fromgitimportGitConfigParser
17+
fromgit.compatimportdefenc
1718
fromgit.configimport_OMD, cp
1819
fromgit.utilimportcwd, rmfile
1920
fromtest.libimportSkipTest, TestCase, fixture_path, with_rw_directory
@@ -170,7 +171,16 @@ def test_rewriting_multiline_value_does_not_create_option(self, rw_dir):
170171
@with_rw_directory
171172
deftest_writer_escapes_special_characters_without_newline(self, rw_dir):
172173
config_path=osp.join(rw_dir, "config")
173-
values= {"tab": "\tvalue\t", "backspace": "a\bb", "quote": 'a"b', "backslash": "a\\qb"}
174+
values= {
175+
"tab": "\tvalue\t",
176+
"backspace": "a\bb",
177+
"quote": 'a"b',
178+
"backslash": "a\\qb",
179+
"hash": "value#fragment",
180+
"semicolon": "value;fragment",
181+
"leading": " value",
182+
"trailing": "value ",
183+
}
174184

175185
withGitConfigParser(config_path, read_only=False) asgit_config:
176186
forkey, valueinvalues.items():
@@ -185,11 +195,72 @@ def test_writer_escapes_special_characters_without_newline(self, rw_dir):
185195
stdout=subprocess.PIPE,
186196
check=True,
187197
).stdout,
188-
value.encode() +b"\n",
198+
value.encode(defenc) +b"\n",
189199
)
190200
withopen(config_path, "rb") asconfig_file:
191201
self.assertNotIn(b"\x08", config_file.read())
192202

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

747818
deftest_config_with_quotes_containing_escapes(self):
748-
"""For now just suppress quote removal. But it would be good to interpret most of these."""
819+
"""Interpret Git's quoted escapes without changing malformed values."""
749820
cr=GitConfigParser(fixture_path("git_config_with_quotes_escapes"), read_only=True)
750821

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"')
822+
self.assertEqual(cr.get("custom", "hasnewline"), "first\nsecond")
823+
self.assertEqual(cr.get("custom", "hasbackslash"), R"foo\bar")
824+
self.assertEqual(cr.get("custom", "hasquote"), 'ab"cd')
825+
self.assertEqual(cr.get("custom", "hastrailingbackslash"), "word\\")
826+
self.assertEqual(cr.get("custom", "hasunrecognized"), R"p\qrs")
757827

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

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit eefa7e4

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 eefa7e4

2 files changed

Lines changed: 102 additions & 15 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-
returnv.encode(defenc).decode("unicode_escape")
465+
escapes= {"b": "\b", "n": "\n", "r": "\r", "t": "\t", '"': '"', "\\": "\\"}
466+
returnre.sub(r"\\(.)", lambdamatch: 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-
elifoptval.find("\\", 1, -1) ==-1andoptval.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+
elifre.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
forvinvalues:
708711
value=self._value_to_string(v)
709-
ifany(charinvalueforcharin'\n\t\b\\"'):
712+
ifany(charinvalueforcharin'\n\t\b\\"#;') orvalue[:1].isspace() orvalue[-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_sectioninself._sections.items():
780+
sections.append(stored_section)
781+
forsectioninsections:
782+
forkey, valuesinsection.items_all():
783+
ifkey!="__name__":
784+
forraw_valueinvalues:
785+
if"\r"inself._value_to_string(raw_value) or"\x00"inself._value_to_string(raw_value):
786+
raiseValueError("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: 79 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
importpytest
1515

1616
fromgitimportGitConfigParser
17+
fromgit.compatimportdefenc
1718
fromgit.configimport_OMD, cp
1819
fromgit.utilimportcwd, rmfile
1920
fromtest.libimportSkipTest, TestCase, fixture_path, with_rw_directory
@@ -170,7 +171,16 @@ def test_rewriting_multiline_value_does_not_create_option(self, rw_dir):
170171
@with_rw_directory
171172
deftest_writer_escapes_special_characters_without_newline(self, rw_dir):
172173
config_path=osp.join(rw_dir, "config")
173-
values= {"tab": "\tvalue\t", "backspace": "a\bb", "quote": 'a"b', "backslash": "a\\qb"}
174+
values= {
175+
"tab": "\tvalue\t",
176+
"backspace": "a\bb",
177+
"quote": 'a"b',
178+
"backslash": "a\\qb",
179+
"hash": "value#fragment",
180+
"semicolon": "value;fragment",
181+
"leading": " value",
182+
"trailing": "value ",
183+
}
174184

175185
withGitConfigParser(config_path, read_only=False) asgit_config:
176186
forkey, valueinvalues.items():
@@ -185,11 +195,72 @@ def test_writer_escapes_special_characters_without_newline(self, rw_dir):
185195
stdout=subprocess.PIPE,
186196
check=True,
187197
).stdout,
188-
value.encode() +b"\n",
198+
value.encode(defenc) +b"\n",
189199
)
190200
withopen(config_path, "rb") asconfig_file:
191201
self.assertNotIn(b"\x08", config_file.read())
192202

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

747818
deftest_config_with_quotes_containing_escapes(self):
748-
"""For now just suppress quote removal. But it would be good to interpret most of these."""
819+
"""Interpret Git's quoted escapes without changing malformed values."""
749820
cr=GitConfigParser(fixture_path("git_config_with_quotes_escapes"), read_only=True)
750821

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"')
822+
self.assertEqual(cr.get("custom", "hasnewline"), "first\nsecond")
823+
self.assertEqual(cr.get("custom", "hasbackslash"), R"foo\bar")
824+
self.assertEqual(cr.get("custom", "hasquote"), 'ab"cd')
825+
self.assertEqual(cr.get("custom", "hastrailingbackslash"), "word\\")
826+
self.assertEqual(cr.get("custom", "hasunrecognized"), R"p\qrs")
757827

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

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit eefa7e4

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 eefa7e4

2 files changed

Lines changed: 102 additions & 15 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-
returnv.encode(defenc).decode("unicode_escape")
465+
escapes= {"b": "\b", "n": "\n", "r": "\r", "t": "\t", '"': '"', "\\": "\\"}
466+
returnre.sub(r"\\(.)", lambdamatch: 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-
elifoptval.find("\\", 1, -1) ==-1andoptval.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+
elifre.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
forvinvalues:
708711
value=self._value_to_string(v)
709-
ifany(charinvalueforcharin'\n\t\b\\"'):
712+
ifany(charinvalueforcharin'\n\t\b\\"#;') orvalue[:1].isspace() orvalue[-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_sectioninself._sections.items():
780+
sections.append(stored_section)
781+
forsectioninsections:
782+
forkey, valuesinsection.items_all():
783+
ifkey!="__name__":
784+
forraw_valueinvalues:
785+
if"\r"inself._value_to_string(raw_value) or"\x00"inself._value_to_string(raw_value):
786+
raiseValueError("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: 79 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
importpytest
1515

1616
fromgitimportGitConfigParser
17+
fromgit.compatimportdefenc
1718
fromgit.configimport_OMD, cp
1819
fromgit.utilimportcwd, rmfile
1920
fromtest.libimportSkipTest, TestCase, fixture_path, with_rw_directory
@@ -170,7 +171,16 @@ def test_rewriting_multiline_value_does_not_create_option(self, rw_dir):
170171
@with_rw_directory
171172
deftest_writer_escapes_special_characters_without_newline(self, rw_dir):
172173
config_path=osp.join(rw_dir, "config")
173-
values= {"tab": "\tvalue\t", "backspace": "a\bb", "quote": 'a"b', "backslash": "a\\qb"}
174+
values= {
175+
"tab": "\tvalue\t",
176+
"backspace": "a\bb",
177+
"quote": 'a"b',
178+
"backslash": "a\\qb",
179+
"hash": "value#fragment",
180+
"semicolon": "value;fragment",
181+
"leading": " value",
182+
"trailing": "value ",
183+
}
174184

175185
withGitConfigParser(config_path, read_only=False) asgit_config:
176186
forkey, valueinvalues.items():
@@ -185,11 +195,72 @@ def test_writer_escapes_special_characters_without_newline(self, rw_dir):
185195
stdout=subprocess.PIPE,
186196
check=True,
187197
).stdout,
188-
value.encode() +b"\n",
198+
value.encode(defenc) +b"\n",
189199
)
190200
withopen(config_path, "rb") asconfig_file:
191201
self.assertNotIn(b"\x08", config_file.read())
192202

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

747818
deftest_config_with_quotes_containing_escapes(self):
748-
"""For now just suppress quote removal. But it would be good to interpret most of these."""
819+
"""Interpret Git's quoted escapes without changing malformed values."""
749820
cr=GitConfigParser(fixture_path("git_config_with_quotes_escapes"), read_only=True)
750821

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"')
822+
self.assertEqual(cr.get("custom", "hasnewline"), "first\nsecond")
823+
self.assertEqual(cr.get("custom", "hasbackslash"), R"foo\bar")
824+
self.assertEqual(cr.get("custom", "hasquote"), 'ab"cd')
825+
self.assertEqual(cr.get("custom", "hastrailingbackslash"), "word\\")
826+
self.assertEqual(cr.get("custom", "hasunrecognized"), R"p\qrs")
757827

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

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit eefa7e4

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 eefa7e4

2 files changed

Lines changed: 102 additions & 15 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-
returnv.encode(defenc).decode("unicode_escape")
465+
escapes= {"b": "\b", "n": "\n", "r": "\r", "t": "\t", '"': '"', "\\": "\\"}
466+
returnre.sub(r"\\(.)", lambdamatch: 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-
elifoptval.find("\\", 1, -1) ==-1andoptval.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+
elifre.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
forvinvalues:
708711
value=self._value_to_string(v)
709-
ifany(charinvalueforcharin'\n\t\b\\"'):
712+
ifany(charinvalueforcharin'\n\t\b\\"#;') orvalue[:1].isspace() orvalue[-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_sectioninself._sections.items():
780+
sections.append(stored_section)
781+
forsectioninsections:
782+
forkey, valuesinsection.items_all():
783+
ifkey!="__name__":
784+
forraw_valueinvalues:
785+
if"\r"inself._value_to_string(raw_value) or"\x00"inself._value_to_string(raw_value):
786+
raiseValueError("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: 79 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
importpytest
1515

1616
fromgitimportGitConfigParser
17+
fromgit.compatimportdefenc
1718
fromgit.configimport_OMD, cp
1819
fromgit.utilimportcwd, rmfile
1920
fromtest.libimportSkipTest, TestCase, fixture_path, with_rw_directory
@@ -170,7 +171,16 @@ def test_rewriting_multiline_value_does_not_create_option(self, rw_dir):
170171
@with_rw_directory
171172
deftest_writer_escapes_special_characters_without_newline(self, rw_dir):
172173
config_path=osp.join(rw_dir, "config")
173-
values= {"tab": "\tvalue\t", "backspace": "a\bb", "quote": 'a"b', "backslash": "a\\qb"}
174+
values= {
175+
"tab": "\tvalue\t",
176+
"backspace": "a\bb",
177+
"quote": 'a"b',
178+
"backslash": "a\\qb",
179+
"hash": "value#fragment",
180+
"semicolon": "value;fragment",
181+
"leading": " value",
182+
"trailing": "value ",
183+
}
174184

175185
withGitConfigParser(config_path, read_only=False) asgit_config:
176186
forkey, valueinvalues.items():
@@ -185,11 +195,72 @@ def test_writer_escapes_special_characters_without_newline(self, rw_dir):
185195
stdout=subprocess.PIPE,
186196
check=True,
187197
).stdout,
188-
value.encode() +b"\n",
198+
value.encode(defenc) +b"\n",
189199
)
190200
withopen(config_path, "rb") asconfig_file:
191201
self.assertNotIn(b"\x08", config_file.read())
192202

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

747818
deftest_config_with_quotes_containing_escapes(self):
748-
"""For now just suppress quote removal. But it would be good to interpret most of these."""
819+
"""Interpret Git's quoted escapes without changing malformed values."""
749820
cr=GitConfigParser(fixture_path("git_config_with_quotes_escapes"), read_only=True)
750821

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"')
822+
self.assertEqual(cr.get("custom", "hasnewline"), "first\nsecond")
823+
self.assertEqual(cr.get("custom", "hasbackslash"), R"foo\bar")
824+
self.assertEqual(cr.get("custom", "hasquote"), 'ab"cd')
825+
self.assertEqual(cr.get("custom", "hastrailingbackslash"), "word\\")
826+
self.assertEqual(cr.get("custom", "hasunrecognized"), R"p\qrs")
757827

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

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit eefa7e4

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 eefa7e4

2 files changed

Lines changed: 102 additions & 15 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-
returnv.encode(defenc).decode("unicode_escape")
465+
escapes= {"b": "\b", "n": "\n", "r": "\r", "t": "\t", '"': '"', "\\": "\\"}
466+
returnre.sub(r"\\(.)", lambdamatch: 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-
elifoptval.find("\\", 1, -1) ==-1andoptval.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+
elifre.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
forvinvalues:
708711
value=self._value_to_string(v)
709-
ifany(charinvalueforcharin'\n\t\b\\"'):
712+
ifany(charinvalueforcharin'\n\t\b\\"#;') orvalue[:1].isspace() orvalue[-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_sectioninself._sections.items():
780+
sections.append(stored_section)
781+
forsectioninsections:
782+
forkey, valuesinsection.items_all():
783+
ifkey!="__name__":
784+
forraw_valueinvalues:
785+
if"\r"inself._value_to_string(raw_value) or"\x00"inself._value_to_string(raw_value):
786+
raiseValueError("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: 79 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
importpytest
1515

1616
fromgitimportGitConfigParser
17+
fromgit.compatimportdefenc
1718
fromgit.configimport_OMD, cp
1819
fromgit.utilimportcwd, rmfile
1920
fromtest.libimportSkipTest, TestCase, fixture_path, with_rw_directory
@@ -170,7 +171,16 @@ def test_rewriting_multiline_value_does_not_create_option(self, rw_dir):
170171
@with_rw_directory
171172
deftest_writer_escapes_special_characters_without_newline(self, rw_dir):
172173
config_path=osp.join(rw_dir, "config")
173-
values= {"tab": "\tvalue\t", "backspace": "a\bb", "quote": 'a"b', "backslash": "a\\qb"}
174+
values= {
175+
"tab": "\tvalue\t",
176+
"backspace": "a\bb",
177+
"quote": 'a"b',
178+
"backslash": "a\\qb",
179+
"hash": "value#fragment",
180+
"semicolon": "value;fragment",
181+
"leading": " value",
182+
"trailing": "value ",
183+
}
174184

175185
withGitConfigParser(config_path, read_only=False) asgit_config:
176186
forkey, valueinvalues.items():
@@ -185,11 +195,72 @@ def test_writer_escapes_special_characters_without_newline(self, rw_dir):
185195
stdout=subprocess.PIPE,
186196
check=True,
187197
).stdout,
188-
value.encode() +b"\n",
198+
value.encode(defenc) +b"\n",
189199
)
190200
withopen(config_path, "rb") asconfig_file:
191201
self.assertNotIn(b"\x08", config_file.read())
192202

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

747818
deftest_config_with_quotes_containing_escapes(self):
748-
"""For now just suppress quote removal. But it would be good to interpret most of these."""
819+
"""Interpret Git's quoted escapes without changing malformed values."""
749820
cr=GitConfigParser(fixture_path("git_config_with_quotes_escapes"), read_only=True)
750821

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"')
822+
self.assertEqual(cr.get("custom", "hasnewline"), "first\nsecond")
823+
self.assertEqual(cr.get("custom", "hasbackslash"), R"foo\bar")
824+
self.assertEqual(cr.get("custom", "hasquote"), 'ab"cd')
825+
self.assertEqual(cr.get("custom", "hastrailingbackslash"), "word\\")
826+
self.assertEqual(cr.get("custom", "hasunrecognized"), R"p\qrs")
757827

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

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit eefa7e4

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 eefa7e4

2 files changed

Lines changed: 102 additions & 15 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-
returnv.encode(defenc).decode("unicode_escape")
465+
escapes= {"b": "\b", "n": "\n", "r": "\r", "t": "\t", '"': '"', "\\": "\\"}
466+
returnre.sub(r"\\(.)", lambdamatch: 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-
elifoptval.find("\\", 1, -1) ==-1andoptval.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+
elifre.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
forvinvalues:
708711
value=self._value_to_string(v)
709-
ifany(charinvalueforcharin'\n\t\b\\"'):
712+
ifany(charinvalueforcharin'\n\t\b\\"#;') orvalue[:1].isspace() orvalue[-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_sectioninself._sections.items():
780+
sections.append(stored_section)
781+
forsectioninsections:
782+
forkey, valuesinsection.items_all():
783+
ifkey!="__name__":
784+
forraw_valueinvalues:
785+
if"\r"inself._value_to_string(raw_value) or"\x00"inself._value_to_string(raw_value):
786+
raiseValueError("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: 79 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
importpytest
1515

1616
fromgitimportGitConfigParser
17+
fromgit.compatimportdefenc
1718
fromgit.configimport_OMD, cp
1819
fromgit.utilimportcwd, rmfile
1920
fromtest.libimportSkipTest, TestCase, fixture_path, with_rw_directory
@@ -170,7 +171,16 @@ def test_rewriting_multiline_value_does_not_create_option(self, rw_dir):
170171
@with_rw_directory
171172
deftest_writer_escapes_special_characters_without_newline(self, rw_dir):
172173
config_path=osp.join(rw_dir, "config")
173-
values= {"tab": "\tvalue\t", "backspace": "a\bb", "quote": 'a"b', "backslash": "a\\qb"}
174+
values= {
175+
"tab": "\tvalue\t",
176+
"backspace": "a\bb",
177+
"quote": 'a"b',
178+
"backslash": "a\\qb",
179+
"hash": "value#fragment",
180+
"semicolon": "value;fragment",
181+
"leading": " value",
182+
"trailing": "value ",
183+
}
174184

175185
withGitConfigParser(config_path, read_only=False) asgit_config:
176186
forkey, valueinvalues.items():
@@ -185,11 +195,72 @@ def test_writer_escapes_special_characters_without_newline(self, rw_dir):
185195
stdout=subprocess.PIPE,
186196
check=True,
187197
).stdout,
188-
value.encode() +b"\n",
198+
value.encode(defenc) +b"\n",
189199
)
190200
withopen(config_path, "rb") asconfig_file:
191201
self.assertNotIn(b"\x08", config_file.read())
192202

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

747818
deftest_config_with_quotes_containing_escapes(self):
748-
"""For now just suppress quote removal. But it would be good to interpret most of these."""
819+
"""Interpret Git's quoted escapes without changing malformed values."""
749820
cr=GitConfigParser(fixture_path("git_config_with_quotes_escapes"), read_only=True)
750821

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"')
822+
self.assertEqual(cr.get("custom", "hasnewline"), "first\nsecond")
823+
self.assertEqual(cr.get("custom", "hasbackslash"), R"foo\bar")
824+
self.assertEqual(cr.get("custom", "hasquote"), 'ab"cd')
825+
self.assertEqual(cr.get("custom", "hastrailingbackslash"), "word\\")
826+
self.assertEqual(cr.get("custom", "hasunrecognized"), R"p\qrs")
757827

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

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit eefa7e4

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 eefa7e4

2 files changed

Lines changed: 102 additions & 15 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-
returnv.encode(defenc).decode("unicode_escape")
465+
escapes= {"b": "\b", "n": "\n", "r": "\r", "t": "\t", '"': '"', "\\": "\\"}
466+
returnre.sub(r"\\(.)", lambdamatch: 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-
elifoptval.find("\\", 1, -1) ==-1andoptval.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+
elifre.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
forvinvalues:
708711
value=self._value_to_string(v)
709-
ifany(charinvalueforcharin'\n\t\b\\"'):
712+
ifany(charinvalueforcharin'\n\t\b\\"#;') orvalue[:1].isspace() orvalue[-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_sectioninself._sections.items():
780+
sections.append(stored_section)
781+
forsectioninsections:
782+
forkey, valuesinsection.items_all():
783+
ifkey!="__name__":
784+
forraw_valueinvalues:
785+
if"\r"inself._value_to_string(raw_value) or"\x00"inself._value_to_string(raw_value):
786+
raiseValueError("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: 79 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
importpytest
1515

1616
fromgitimportGitConfigParser
17+
fromgit.compatimportdefenc
1718
fromgit.configimport_OMD, cp
1819
fromgit.utilimportcwd, rmfile
1920
fromtest.libimportSkipTest, TestCase, fixture_path, with_rw_directory
@@ -170,7 +171,16 @@ def test_rewriting_multiline_value_does_not_create_option(self, rw_dir):
170171
@with_rw_directory
171172
deftest_writer_escapes_special_characters_without_newline(self, rw_dir):
172173
config_path=osp.join(rw_dir, "config")
173-
values= {"tab": "\tvalue\t", "backspace": "a\bb", "quote": 'a"b', "backslash": "a\\qb"}
174+
values= {
175+
"tab": "\tvalue\t",
176+
"backspace": "a\bb",
177+
"quote": 'a"b',
178+
"backslash": "a\\qb",
179+
"hash": "value#fragment",
180+
"semicolon": "value;fragment",
181+
"leading": " value",
182+
"trailing": "value ",
183+
}
174184

175185
withGitConfigParser(config_path, read_only=False) asgit_config:
176186
forkey, valueinvalues.items():
@@ -185,11 +195,72 @@ def test_writer_escapes_special_characters_without_newline(self, rw_dir):
185195
stdout=subprocess.PIPE,
186196
check=True,
187197
).stdout,
188-
value.encode() +b"\n",
198+
value.encode(defenc) +b"\n",
189199
)
190200
withopen(config_path, "rb") asconfig_file:
191201
self.assertNotIn(b"\x08", config_file.read())
192202

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

747818
deftest_config_with_quotes_containing_escapes(self):
748-
"""For now just suppress quote removal. But it would be good to interpret most of these."""
819+
"""Interpret Git's quoted escapes without changing malformed values."""
749820
cr=GitConfigParser(fixture_path("git_config_with_quotes_escapes"), read_only=True)
750821

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"')
822+
self.assertEqual(cr.get("custom", "hasnewline"), "first\nsecond")
823+
self.assertEqual(cr.get("custom", "hasbackslash"), R"foo\bar")
824+
self.assertEqual(cr.get("custom", "hasquote"), 'ab"cd')
825+
self.assertEqual(cr.get("custom", "hastrailingbackslash"), "word\\")
826+
self.assertEqual(cr.get("custom", "hasunrecognized"), R"p\qrs")
757827

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

0 commit comments

Comments
 (0)