.gitignore fnmatch () style

What would be the easiest way to have a .gitignore fnmatch () style with Python. It appears that stdlib does not provide a match () function that conforms to the path specification for regexing a UNIX style path.

.gitignore have both paths and wildcard files (black) listed

+9
source share
2 answers

If you want to use mixed UNIX patterns, as indicated in the .gitignore example, why not just take each pattern and use fnmatch.translate with re.search ?

 import fnmatch import re s = '/path/eggs/foo/bar' pattern = "eggs/*" re.search(fnmatch.translate(pattern), s) # <_sre.SRE_Match object at 0x10049e988> 

translate turns a lookup pattern into a re pattern

Hidden UNIX files:

 s = '/path/to/hidden/.file' isHiddenFile = re.search(fnmatch.translate('.*'), s) if not isHiddenFile: # do something with it 
+6
source

Now there is a library called pathspec that implements the full .gitignore specification, including things like **/*.py ; the documentation does not describe the parameters in detail, but says that it is compatible with git, and the code processes them.

 >>> import pathspec >>> spec_src = '**/*.pyc' >>> spec = pathspec.PathSpec.from_lines(pathspec.patterns.GitWildMatchPattern,, spec_src.splitlines()) >>> set(spec.match_files({"test.py", "test.pyc", "deeper/file.pyc", "even/deeper/file.pyc"})) set(['test.pyc', 'even/deeper/file.pyc', 'deeper/file.pyc']) >>> set(spec.match_tree("pathspec/")) set(['__init__.pyc', 'gitignore.pyc', 'util.pyc', 'pattern.pyc', 'tests/__init__.pyc', 'tests/test_gitignore.pyc', 'compat.pyc', 'pathspec.pyc']) 
+15
source

All Articles