Skip to content

Fix escape() not escaping backslash characters#106

Merged
cpburnz merged 1 commit into
cpburnz:masterfrom
bysiber:fix/escape-backslash
Feb 21, 2026
Merged

Fix escape() not escaping backslash characters#106
cpburnz merged 1 commit into
cpburnz:masterfrom
bysiber:fix/escape-backslash

Conversation

@bysiber
Copy link
Copy Markdown
Contributor

@bysiber bysiber commented Feb 20, 2026

The escape() method is meant to escape special characters in a filename so it can be safely used as a gitignore pattern. Currently it escapes []!*#? but misses backslash (\), which is the escape character in gitignore patterns.

This means escape() doesn't produce a round-trippable result for filenames containing backslashes:

from pathspec import PathSpec
from pathspec.patterns.gitignore.base import _GitIgnoreBasePattern

filename = "foo\\bar"

escaped = _GitIgnoreBasePattern.escape(filename)
# Returns 'foo\\bar' — unchanged, backslash NOT escaped

spec = PathSpec.from_lines('gitwildmatch', [escaped])
spec.match_file(filename)
# Returns False — the pattern doesn't match the original filename!
# The parser consumed the backslash as an escape for 'b',
# so the pattern actually matches 'foobar' instead of 'foo\bar'

The fix adds \\ to the set of escaped characters, so escape('foo\\bar') correctly produces 'foo\\\\bar', which the parser then interprets as a literal backslash.

The escape() method escapes special gitignore characters so that a
literal filename can be used as a pattern. However, it only escapes
[]-f pr_body_1.md && git checkout master && git checkout -b fix/escape-backslash master#? and misses backslash, which is the escape character in
gitignore patterns.

Without this fix, escape('foo\\bar') returns 'foo\\bar' unchanged.
When this is then parsed as a gitignore pattern, the backslash is
consumed as an escape sequence (escaping 'b'), so the resulting
pattern matches 'foobar' instead of the intended 'foo\\bar'.

Add backslash to the set of characters that get escaped.
@cpburnz cpburnz merged commit 3199cd4 into cpburnz:master Feb 21, 2026
@cpburnz
Copy link
Copy Markdown
Owner

cpburnz commented Feb 21, 2026

Thanks for finding and fixing this bug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants