Skip to content

Instantly share code, notes, and snippets.

@jondo2010
Created September 6, 2017 22:46
Show Gist options
  • Save jondo2010/7b2f1cdbb998e1ba67a552d07a31bbcf to your computer and use it in GitHub Desktop.
Save jondo2010/7b2f1cdbb998e1ba67a552d07a31bbcf to your computer and use it in GitHub Desktop.
Git hash of a tree object, including uncommitted changes
#!/bin/bash
function usage {
cat << EOL
Return the GIT hash for the tree object under a specified directory. This is
effectively a unique hash of only the contents of the files in the directory
and does not depend on commit data.
Usage: $0 [path/to/directory]
EOL
exit 1
}
# Check for correct arguments
if [[ "$#" -ne 1 ]] || [[ ! -d "$1" ]]; then
usage
else
# Check for any untracked files in directory
UNTRACKED=$(git ls-files --others "$1")
if [[ -n "$UNTRACKED" ]]; then
NFILES=$(wc -l <<< "$UNTRACKED")
echo "$NFILES untracked files were found under '$1', either add or clean them."
exit 1
fi
# The revision to create the tree-hash for, either a detached stash commit,
# or 'HEAD' if the working tree is clean.
STASH=$(git stash create)
REVISION=${STASH:-HEAD} # Defaults to 'HEAD' if the stash was empty (clean working tree)
# Return the tree-hash for $REVISION under the directory argument passed
git rev-parse --short "$REVISION":"$1"
fi
@rogerlin0330
Copy link

I think there is an issue with the script that is, git ls-files --others "$1" will also include files matched the patterns defined in .gitignore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment