Repository navigation
Description
Describe the bug
A reversed bracket range such as [z-a] makes PathSpec.from_lines('gitignore', ...) raise a raw re.error. Git accepts the pattern without error. Pull #123 made GitIgnoreSpec handle this, but the gitignore pattern factory (GitIgnoreBasicPattern) still crashes.
To reproduce
import pathspec
files = ['a', 'm', 'z', '-', '[z-a]']
print("EXPECTED: PathSpec.from_lines('gitignore', ['[z-a]']) builds without error (git accepts it)")
try:
spec = pathspec.PathSpec.from_lines('gitignore', ['[z-a]'])
except Exception as e:
print(f"ACTUAL: {type(e).__module__}.{type(e).__name__}: {e}")
raise SystemExit(1)
matched = [f for f in files if spec.match_file(f)]
print(f"ACTUAL: built OK, matched {matched}")Output on master (3dfbd91):
EXPECTED: PathSpec.from_lines('gitignore', ['[z-a]']) builds without error (git accepts it)
ACTUAL: re.error: bad character range z-a at position 11
Real Git (2.53.0), with a .gitignore containing [z-a]: git check-ignore -v -n a m z - "[z-a]" gives no error and ignores only z.
Expected behavior
The pattern loads without an exception. With the default 'literal' mode I'd expect the bracket expression to be treated as literal text, the same as [!] and [^] already are. With 'raise' I'd expect a GitIgnorePatternError. The docstring for errors says invalid notation is handled according to errors (default 'literal'), and that GitIgnorePatternError is raised if a pattern fails to process, not a raw re.error.
Versions
- pathspec 1.1.1 and
master@ 3dfbd91 (both affected; the error position is 10 on 1.1.1) - Python 3.12, Linux
Additional context
In pathspec/patterns/gitignore/base.py (lines 513-520) the re.compile check on the bracket expression only runs when errors == 'raise'. With the default 'literal', the bad range goes into the regex and fails later, when the regex is compiled. #123 covered GitIgnoreSpecPattern only, whose default mode runs the check. 'gitignore' isn't deprecated, so PathSpec.from_lines('gitignore', lines) hits this with a real-world .gitignore containing such a typo.
Running the check in every mode would fix the crash. Git itself matches only z here, so the literal fallback still differs from Git. Matching only z would need a separate change.
I have a fix with a regression test ready and will open a pull request for it right after filing this issue; it will link back here.
Activity