Using git to open your editor

Joshua Nussbaum - Feb 4 '20 - - Dev Community

As busy developers, interruption is inevitable.

Someone asks a question and we need to research some code, so we open files, switch branches or change projects, The position of the editor gets lost.

Eventually the disruption ends and we we want to return to where we left off.

Sure, we can search or click around to re-open those files and close tabs.

But wait... there is another way 😅

We can use git history to control what files are opened by our editor.

Modified Files

When returning to a repo that has uncommitted changes, it would be nice to re-open all changes in one shot.

The git ls-files command can give us a list of changed file names. The command requires some flags to return both modified --modified and new files --others. It's also a good idea to use --exclude-standard, just to skip files excluded by .gitignore.

> #...modify file1.js
> #...modify file2.js
> #...add file3.js
> git ls-files . --modified --others --exclude-standard
file1.js
file2.js
file3.js
Enter fullscreen mode Exit fullscreen mode

Armed with the list of modified files, we can setup a bash alias to open these file with our editor:

# ~/.bash_aliases

# for vim
# vim -O opens a split window
alias mods='vim -O $(git ls-files . --modified --exclude-standard --others)'

# for vscode
alias mods='code $(git ls-files . --modified --exclude-standard --others)'
Enter fullscreen mode Exit fullscreen mode

Now simply type mods - and presto - your editor opens with all the modified files. ✨

Amending Commits

When working on a branch, it's common to continue work based on the last commit. Maybe a reviewer suggested an edit on GitHub, or there's a typo. It would be awesome to just re-open the last commit right where we were.

This is very similar to what we did before, except this time the file list comes from the previous commit.

We can use the git diff-tree <sha> command to get the file list from a commit. We only want names --name-only and don't need the commit id --no-commit-id, and we only want files from the last commit (aka HEAD).

> git diff-tree --no-commit-id --name-only HEAD
file1.js
file2.js
Enter fullscreen mode Exit fullscreen mode

Just like before, we can setup a bash alias to pass the files list to our editor:

# ~/.bash_aliases

# for vim
alias amend='vim -O $(git diff-tree --no-commit-id --name-only -r HEAD)'

# for vscode
alias amend='code $(git diff-tree --no-commit-id --name-only -r HEAD)'
Enter fullscreen mode Exit fullscreen mode

Now you can type amend - and voila - you are editing the files from the last commit ✨

Happy Coding!

. . . . . . . . . . . . . . . . . . .