偶尔对版本库中的文件或与某个模式相匹配的所有文件运行命令是很有用的。 这可以通过组合 git ls-files和 xargs.
对于所有文件。
$ git ls-files | xargs <command>
或者对于具有给定后缀的文件。
$ git ls-files -- '*.<suffix>' | xargs <command>
一个解构的例子
例如,要获得所有Python文件的行数。
$ git ls-files -- '*.py' | xargs wc -l
...
255 example/urls.py
138 example/utils.py
3160 example/views.py
78123 total
让我们把它拆开。
你可以把一个文件的行数用 wc和它的 -l标志。
$ wc -l example/models.py
7142 example/models.py
git ls-files -- '*.py'列出Git已知的所有以.py 结尾的文件,在当前文件夹中。
$ git ls-files -- '*.py'
...
example/urls.py
example/utils.py
example/views.py
xargs 从它的输入中获取文件列表,并对它们分组运行你给它的命令。 所以在组合命令中,它接收来自 git ls-files的文件列表,并对它们分批运行 wc -l对它们分批运行。
运行修复器工具
你也可以使用这个技术来运行 "修复器 "工具。 例如,要运行我的工具 django-upgrade在你版本库中的所有 Python 文件上运行。
$ git ls-files -- '*.py' | xargs django-upgrade --target-version 4.0
...
Rewriting example/models.py
Rewriting example/urls.py