9

使用 Python 使用 .gitignore 样式的 fnmatch() 最简单的方法是什么。看起来 stdlib 没有提供 match() 函数,该函数将路径规范与 UNIX 样式路径正则表达式匹配。

.gitignore 有通配符的路径和文件都被列入(黑)名单

4

2 回答 2

21

有一个名为pathspec的库,它实现了完整的.gitignore规范,包括**/*.py:该文档描述了如何处理 Git 模式匹配(您也可以查看代码)。

>>> 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'])
于 2014-02-28T09:05:46.100 回答
9

如果您想使用 .gitignore 示例中列出的混合 UNIX 通配符模式,为什么不采用每个模式并使用fnmatch.translatewithre.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将通配符模式转换为 re 模式

隐藏的 UNIX 文件:

s = '/path/to/hidden/.file'
isHiddenFile = re.search(fnmatch.translate('.*'), s)
if not isHiddenFile:
    # do something with it
于 2012-04-06T20:22:56.907 回答