11 Oct 2020
This is a small shell script that I use to open all files related to a commit in git; I find it quite useful when I want to resume working on a local branch.
This is useful if you're not using an IDE or you are working on multiple changes and switch between them.
Anyway, let's get to the script.
#!/bin/bash gitPrefix=$(git rev-parse --show-toplevel) __num=$(git diff --name-only | wc -l) filter_open() { $1 | perl -p -e 's!.+!'$gitPrefix'/$&!; s!.+(png|jpeg)$!!' | xargs kate -n > /dev/null 2>&1 & } if [ -z "$1" -a "$__num" -ge 1 ]; then filter_open "git diff --name-only" else filter_open "git diff HEAD^1 --name-only" fi
git rev-parse --show-toplevel
: returns the absolute path to the top-level git repo directory
git diff --name-only
: returns the list of the files that are changed but not committed yet
git diff HEAD^1 --name-only
: returns the list of files that were changed (committed or not) since the commit before last in the repo
perl -p -e 's!.+!'$gitPrefix'/$&!; s!.+(png|jpeg)$!!'
: since the git diff commands above return relative paths, I need to prepend $gitPrefix (the output of the git rev-parse --show-toplevel
command) to all those relative paths, that's what this perl command does; also it filters out all png/jpeg files (I don't want to edit images with a text editor... it doesn't work)
As you can see, I write hacky bash scripts, I am sure there are ways to make it more elegant, but it works, so.
I have two use cases here:
all
.
Bonus point, if you save the script as e.g. git-open-files
somewhere in your PATH, you can call the script directly (after making it executable) from terminal or you can use it as a git command, i.e. git open-files
should work.
Happy hacking!
Credits: I had done some online research to get most of those commands (I find it easier to search for a "concept", the after actually finding it, then read the relevant sections of the man pages; sometimes (well, usually) someone, somewhere, had already asked the same question :)), so thanks to all those online resources; e.g. I definitely recall finding the git rev-parse --show-toplevel
command in a stack{overflow,exchange} thread.