@@ -239,6 +239,51 @@ def test_multi_line_config(self):
239239 )
240240 self .assertEqual (len (config .sections ()), 23 )
241241
242+ def test_inline_comments_are_stripped_like_git (self ):
243+ """A `#` or `;` outside quotes starts a comment, with or without a space
244+ before it, and whether or not the value is quoted. Expectations are what
245+ `git config -f <file> --get a.k` prints on git 2.50.1."""
246+ cases = [
247+ (b"[a]\n \t k = value # comment\n " , "value" ),
248+ (b"[a]\n \t k = value ; comment\n " , "value" ),
249+ (b"[a]\n \t k = value#nospace\n " , "value" ),
250+ (b"[a]\n \t k = value;nospace\n " , "value" ),
251+ (b"[a]\n \t k = a # b ; c\n " , "a" ),
252+ (b'[a]\n \t k = "quoted" # after\n ' , "quoted" ),
253+ # A comment character inside quotes is literal.
254+ (b'[a]\n \t k = "has # inside"\n ' , "has # inside" ),
255+ (b'[a]\n \t k = "has ; inside"\n ' , "has ; inside" ),
256+ ]
257+ for content , expected in cases :
258+ config_file = io .BytesIO (content )
259+ config_file .name = "inline_comment.config"
260+ config = GitConfigParser (config_file )
261+ config .read ()
262+ with self .subTest (content = content ):
263+ self .assertEqual (config .get_value ("a" , "k" ), expected )
264+
265+ @with_rw_directory
266+ def test_inline_comments_preserve_balanced_quotes_and_following_settings (self , rw_dir ):
267+ config_path = osp .join (rw_dir , "config" )
268+ values = (b'"foo"bar' , b'"foo\\ "bar"baz' , b'"foo#;bar"baz' )
269+ for value in values :
270+ for comment in (b' # "note"' , b' ; "note"' ):
271+ with self .subTest (value = value , comment = comment ):
272+ with open (config_path , "wb" ) as config_file :
273+ config_file .write (b"[a]\n \t k = " + value + comment + b"\n \t x = keep\n [b]\n \t y = stay\n " )
274+
275+ with GitConfigParser (config_path , read_only = False ) as config :
276+ self .assertEqual (config .get_value ("a" , "k" ), value .decode (defenc ))
277+ self .assertEqual (config .get_value ("a" , "x" ), "keep" )
278+ self .assertEqual (config .get_value ("b" , "y" ), "stay" )
279+ config .set_value ("other" , "value" , "updated" )
280+
281+ with GitConfigParser (config_path ) as config :
282+ self .assertEqual (config .get_value ("a" , "k" ), value .decode (defenc ))
283+ self .assertEqual (config .get_value ("a" , "x" ), "keep" )
284+ self .assertEqual (config .get_value ("b" , "y" ), "stay" )
285+ self .assertEqual (config .get_value ("other" , "value" ), "updated" )
286+
242287 def test_backslash_line_continuation (self ):
243288 """An unquoted value ending in a backslash continues on the next line,
244289 exactly as git config parses it: the final backslash and the newline
0 commit comments