Skip to content

Instantly share code, notes, and snippets.

@ssbarnea
Last active July 18, 2022 16:28
Show Gist options
  • Save ssbarnea/6089714 to your computer and use it in GitHub Desktop.
Save ssbarnea/6089714 to your computer and use it in GitHub Desktop.
require-clean-work-tree is a bash script that will prevent you from doing things if your working tree is dirty. It will detect your scm and return false if detection fails or the tree is dirty. Currently it supports only git and mercurial but we can add other scm later like svn or perforce.
#!/bin/bash
# version: 1.0
# author: Sorin Sbarnea
require_clean_work_tree_git () {
git rev-parse --verify HEAD >/dev/null || exit 1
git update-index -q --ignore-submodules --refresh
err=0
if ! git diff-files --quiet --ignore-submodules
then
echo >&2 "Cannot $1: You have unstaged changes."
err=1
fi
if ! git diff-index --cached --quiet --ignore-submodules HEAD --
then
if [ $err = 0 ]
then
echo >&2 "Cannot $1: Your index contains uncommitted changes."
else
echo >&2 "Additionally, your index contains uncommitted changes."
fi
err=1
fi
if [ $err = 1 ]
then
test -n "$2" && echo >&2 "$2"
exit 1
fi
}
require_clean_work_tree_hg () {
set -e
hg pull
hg update
hg diff
# Disallow unstaged changes in the working tree
if [ -n "$(hg status -mar)" ]
then
echo >&2 "error: your index contains uncommitted changes."
exit 1
fi
}
LOC=`pwd`
while [ $LOC != '/' ]; do
if [ -d "$LOC/.git" ]; then
require_clean_work_tree_git
break
elif [ -d "$LOC/.hg" ]; then
require_clean_work_tree_hg
break
else
LOC=`dirname $LOC`
fi
done
if [ $LOC == '/' ]; then
echo >&2 "Unable to detect any .git or .hg repositories."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment