Skip to content

Commit

Permalink
Add edge case: patterns that end with an escaped space
Browse files Browse the repository at this point in the history
  • Loading branch information
karagenc committed Apr 21, 2023
1 parent 6fd6bee commit 8534317
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
9 changes: 8 additions & 1 deletion pathspec/patterns/gitwildmatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,14 @@ def pattern_to_regex(
raise TypeError(f"pattern:{pattern!r} is not a unicode or byte string.")

original_pattern = pattern
pattern = pattern.strip()

if pattern.endswith('\\ '):
# EDGE CASE: Spaces can be escaped with backslash.
# If a pattern that ends with backslash followed by a space,
# only strip from left.
pattern = pattern.lstrip()
else:
pattern = pattern.strip()

if pattern.startswith('#'):
# A pattern starting with a hash ('#') serves as a comment
Expand Down
27 changes: 27 additions & 0 deletions tests/test_pathspec.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
PathSpec)
from pathspec.util import (
iter_tree_entries)
from pathspec.patterns.gitwildmatch import GitWildMatchPatternError
from tests.util import (
make_dirs,
make_files,
Expand Down Expand Up @@ -119,6 +120,32 @@ def test_01_current_dir_paths(self):
'./src/test2/c/c.txt',
})

def test_01_empty_path(self):
"""
Tests that patterns that end with an escaped space will be treated properly.
"""
spec = PathSpec.from_lines('gitwildmatch', [
'\\ ',
'abc\\ '
])
test_files = [
' ',
' ',
'abc ',
'somefile',
]
results = list(filter(spec.match_file, test_files))
self.assertEqual(results, [
' ',
'abc '
])

# An escape with double spaces is invalid.
# Disallow it. Better to be safe than sorry.
self.assertRaises(GitWildMatchPatternError, lambda: PathSpec.from_lines('gitwildmatch', [
'\\ '
]))

def test_01_match_files(self):
"""
Tests that matching files one at a time yields the same results as
Expand Down

0 comments on commit 8534317

Please sign in to comment.