Skip to content

Instantly share code, notes, and snippets.

@anzdaddy
Last active June 19, 2024 00:59
Show Gist options
  • Save anzdaddy/2a0157e10bcba5304150872cd50f9b90 to your computer and use it in GitHub Desktop.
Save anzdaddy/2a0157e10bcba5304150872cd50f9b90 to your computer and use it in GitHub Desktop.
Run a command against a clean working tree

Add this snippet to your .*shrc.

gx() {(
  set -e
  # If working tree dirty bar staged content...
  if git status --porcelain | grep -v '^. ' >/dev/null; then
    echo "⮑  Temporarily stashing unstaged and untracked content."
    git stash push --keep-index --include-untracked
    unstash() {
      if [ -z "$unstashed" ]; then
        echo "⮐  Restoring stashed content."
        git restore . # in case the command made local changes
        git stash pop --index
        unstashed=1
      fi
    }
    trap unstash EXIT SIGINT
  fi
  ("$@") && echo 👍 || echo 💥
)}

Now you can run commands against a clean working tree.

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