How to force a clean git working repository in a makefile?

git, makefile, working-directory

Solution

Use `git diff-index` to check if the repo is dirty:

deploy:
        git diff-index --quiet HEAD 
        git branch -f deployment
        git push origin deployment

If you want to check shell variables in a makefile, you need to ensure that you check the value of the variable in the same shell as the one in which it is set. Make will invoke each command in a separate shell, so you would need to do something like:

deploy:
        @status=$$(git status --porcelain); \
        if test "x$${status}" = x; then \
            git branch -f deployment; \
            git push origin deployment; \
        else \
            echo Working directory is dirty >&2; \
        fi

Note the double '$', the semi-colon, and the line continuations.

Problem

I'm trying to make a `deploy` command in my Makefile, which simply overwrites to the branch `deployment` and then pushes this branch to `origin`. However, the command must stop/fail with an error message when the working tree is not empty. Something like the following: ``` deploy: status=$(git status --porcelain) test "x$(status)" = "x" git branch -f deployment git push origin deployment ``` Unfortunately, this test on and status variable do not seem to function as wanted. How would one achieve this? Am I indeed supposed to use `test`?

Original source