Skip to content

Commit

Permalink
Fix patterns with leading exclamation marks (#54)
Browse files Browse the repository at this point in the history
Quoting the relevant paragraph in
https://git-scm.com/docs/gitignore#_pattern_format:

  Put a backslash ("\") in front of the first "!" for patterns that
  begin with a literal "!", for example, "\!important!.txt".
  • Loading branch information
jherland authored Oct 3, 2023
1 parent d45a085 commit 1040aa5
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
5 changes: 3 additions & 2 deletions gitignore_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,9 @@ def rule_from_pattern(pattern, base_path=None, source=None):
pattern = pattern[1:]
if pattern[-1] == '/':
pattern = pattern[:-1]
# patterns with leading hashes are escaped with a backslash in front, unescape it
if pattern[0] == '\\' and pattern[1] == '#':
# patterns with leading hashes or exclamation marks are escaped with a
# backslash in front, unescape it
if pattern[0] == '\\' and pattern[1] in ('#', '!'):
pattern = pattern[1:]
# trailing spaces are ignored unless they are escaped with a backslash
i = len(pattern)-1
Expand Down
5 changes: 5 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,11 @@ def test_negation(self):
self.assertFalse(matches('/home/michael/keep.ignore'))
self.assertTrue(matches('/home/michael/waste.ignore'))

def test_literal_exclamation_mark(self):
matches = _parse_gitignore_string('\\!ignore_me!', fake_base_dir='/home/michael')
self.assertTrue(matches('/home/michael/!ignore_me!'))
self.assertFalse(matches('/home/michael/ignore_me!'))
self.assertFalse(matches('/home/michael/ignore_me'))

def test_double_asterisks(self):
matches = _parse_gitignore_string('foo/**/Bar', fake_base_dir='/home/michael')
Expand Down

0 comments on commit 1040aa5

Please sign in to comment.