Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compute git hash of all *uncommitted* code

Tags:

git

Is there a good way to get a git hash that works as follows:

  1. if there are no uncommitted changes, return the git hash of the current branch tip (ignoring untracked files), or
  2. if there is at least one uncommited change (whether in the staging area or not, but ignoring untracked files), compute the git hash that would result if one ran git commit -a -m ''?

Background:

I'm writing some development tools that package up builds. I'd like the build package to include some sort of reasonably-robust and completely automatic version id. A git SHA1 hash is more than sufficient for my purposes. Unfortunately, just using git rev-parse HEAD isn't sufficient because users will commonly run the build before committing, and thus before HEAD is updated.

like image 436
Mr Fooz Avatar asked May 22 '14 20:05

Mr Fooz


2 Answers

Create a temporary index, write the uncommitted changes to it, then get the sha of that tree.

cp .git/index /tmp/git_index
export GIT_INDEX_FILE=/tmp/git_index
git add -u
git write-tree

This will print out a sha unique to the current state of the git repo including uncommitted changes, but not including new files.

like image 152
Cory Klein Avatar answered Sep 21 '22 05:09

Cory Klein


I think you want the hash of a Git tree object, not that of a commit. A commit hash depends on the commit time and will be different every time you compute it.

To create a new tree object from your working copy you can run the write-tree command:

git add -u && git write-tree && git reset

Note that this will mess up your index (as it will temporarily stage all changes)

like image 25
knittl Avatar answered Sep 22 '22 05:09

knittl