Skip to content

Instantly share code, notes, and snippets.

@jorgsk
Forked from pesterhazy/git xargs.md
Last active November 25, 2022 09:26
Show Gist options
  • Save jorgsk/23ccc12e783f8624fec0af2d2db19e49 to your computer and use it in GitHub Desktop.
Save jorgsk/23ccc12e783f8624fec0af2d2db19e49 to your computer and use it in GitHub Desktop.
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.github.com/jorgsk/23ccc12e783f8624fec0af2d2db19e49/raw/0430391b22558edb08a3af9786ca4f33aca45caf/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 '*.cpp' '*.c' -- 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.github.com/jorgsk/23ccc12e783f8624fec0af2d2db19e49
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 '*.cpp' '*.c' -- 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