Instantly share code, notes, and snippets.

Embed
What would you like to do?
git xargs: execute utility on files under source control

git xargs: execute utility on files in repository

Provides a new git command, git xargs, that runs an arbitrary shell command on all files under source control. Optionally you can specify a pathspec (such as a subpath or a glob expression), restricting the operation to a subset of the repository files.

As git xargs delegates the work to xargs(1), it supports all options provided by the version of xargs installed on your system.

Installation

After running

curl -sL https://gist.githubusercontent.com/pesterhazy/65360ed980ae0c86a4150102ca6484a0/raw/git-xargs | \
sudo tee /usr/local/bin/git-xargs > /dev/null && \
sudo chmod +x /usr/local/bin/git-xargs

in your shell and making sure that /usr/local/bin is on your PATH, git will automatically detect git xargs.

Usage

git xargs [xargs-options] [<command> <args>]
git xargs [<file>...] -- [xargs-options] [<command> <args>]

Examples

  • git xargs du -c

    shows total disk usage of files under source control

  • git xargs -n1 echo

    equivalent to git ls-files

  • git xargs '*.cpp' '*.c' -- sed -i '' 's/foo/bar/g'

    replace string foo with string bar in all c and cpp fles under source control

  • git xargs rpl foo bar

    simpler way to do the same. This requires installation of rpl(1).

#!/usr/bin/env python
#
# Execute utility on files under source control
#
# https://gist.githubusercontent.com/pesterhazy/65360ed980ae0c86a4150102ca6484a0
import sys, subprocess
def usage():
print """Execute utility on files in repository, optionally matching pathspec
## Usage
```shell
git xargs [xargs-options] [<command> <args>]
git xargs [<file>...] -- [xargs-options] [<command> <args>]
```
## Examples
- `git xargs du -c`
shows total disk usage of files under source control
- `git xargs -n1 echo`
equivalent to git ls-files
- `git xargs '*.cpp' '*.c' -- sed -i '' 's/foo/bar/g'`
replace string foo with string bar in all c and cpp fles under source control
- `git xargs rpl foo bar`
simpler way to do the same. This requires installation of
[rpl(1)](https://linux.die.net/man/1/rpl).
"""
def split_argv(argv):
if '--' in argv:
idx = argv.index('--')
return [argv[:idx],argv[idx+1:]]
else:
return [[], argv]
a, b = split_argv(sys.argv[1:])
if len(b)==0:
usage()
sys.exit(1)
p1 = subprocess.Popen(["git", "ls-files"]+a, stdout=subprocess.PIPE)
p2 = subprocess.Popen(["xargs"] + b, stdin=p1.stdout)
p1.stdout.close()
p2.communicate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment