Friday, April 10, 2015

git shortcuts

Over the past few months, I've developed a few shortcuts that make using git a little easier & quicker. Here are a few... I'm curious as to what others are doing. These are defined in my .bashrc

List or use the currently active branch
function gbc() {
if [ -e ./.git ]; then
  git branch | sed -n -e "/^\*/ p " | cut -c 3-99
fi
}
export -f gbc
Now if I want to see what the latest branch is, I simply type `gbc` and the current branch is displayed. What's even more useful, IMO, is that I can now use that function to display the current branch in my bash prompt using something like this:
PS1='${debian_chroot:+($debian_chroot)}\u@\h:[\W-$(gbc)]\w\$ '
and now my prompt looks like this:
jseidel@EDP28:[s_analyzer-master]~/dev/coding/s_analyzer$
I've got mine color-coded (MUCH longer PS1 string) so that the branch name really stands out and I can see immediately where I am.

Quickly add modified (but not new) files
I frequently have a few untracked files in my repo which I do not want to add to the repo, so git adding everything doesn't work for me. So I created a `gadauto` command to do that for me.
function gadauto() {
  git status | ack 'modified:|deleted:' gst.txt | sed -Ee 's/modified:|deleted://' | xargs git add
}
export -f gadauto
Now a quick `gadauto` command adds modified or deleted files to the staging area

Quickly add to and amend a commit
We use git-review and the preferred workflow is to first create a new commit and then amend that commit until you're ready to push it for review. The command to do that is "git commit --amend". To shorten this, I created a simple alias:
alias gcamd='git commit --amend'
Now when I'm ready to add my updated files and amend the commit, all I have to do is type:
gadauto && gcamd
I could shorten that even more but I like to type just a bit more when I could make a messy mistake.

Quickly add merge conflicts that have been resolved
The gadauto command works great but doesn't handle the use case for files that have been conflicted and then resolved during a git rebase, for example. Handling this is just a simple modifaction of the gadauto commend described above.
function gadboth() {
  git status | ack 'both modified:|both added:' gst.txt | sed -Ee 's/both modified:|both added://' | xargs git add
}
export -f gadboth
Now Now following a `git rebase master` and conflict resolution, I just type:
gadboth
and all of the files that were just resolved are added to the staging area, ready for the `git rebase --continue`.

Hopefully this will help someone; I'd be interested to know what your favorite git shortcuts are.

Update If you want to see some really cool git shortcuts, visit Thoughtbot's dotfiles.

No comments:

Post a Comment