require-clean-working-tree.sh 930 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/env bash
  2. # Exits with an error code of there are any uncomitted changes. Derived from:
  3. # http://stackoverflow.com/questions/3878624/how-do-i-programmatically-determine-if-there-are-uncommited-changes
  4. # optional argument
  5. working_subdir="$1"
  6. # git complains if empty string path in statements below
  7. if [[ -z "$working_subdir" ]]
  8. then
  9. working_subdir="."
  10. fi
  11. # Update the index
  12. git update-index -q --refresh
  13. err=0
  14. # Disallow unstaged changes in the working tree
  15. if ! git diff-files --quiet -- "$working_subdir"
  16. then
  17. echo >&2 "You have unstaged changes."
  18. git diff-files --name-status -r -- "$working_subdir" >&2
  19. err=1
  20. fi
  21. # Disallow uncommitted changes in the index
  22. if ! git diff-index --cached --quiet HEAD --
  23. then
  24. echo >&2 "Your index contains uncommitted changes."
  25. git diff-index --cached --name-status -r HEAD -- >&2
  26. err=1
  27. fi
  28. if [ $err = 1 ]
  29. then
  30. echo >&2 "Please commit or stash them."
  31. exit 1
  32. fi