Reputation: 77157
I'm trying to write a script that does a git commit
; however, if there is nothing to commit, git exits with a status of 1
. The deploy script takes that as unsuccessful, and quits. How can I allow empty-commit failures to be ignored so that the script can continue, but still catch errors caused when a real commit fails?
git add -p && git commit
Upvotes: 157
Views: 60047
Reputation: 602465
From the git commit
man page:
--allow-empty
Usually recording a commit that has the exact same tree as its
sole parent commit is a mistake, and the command prevents you
from making such a commit. This option bypasses the safety, and
is primarily for use by foreign SCM interface scripts.
Upvotes: 83
Reputation: 81803
Catch this condition beforehand by checking the exit code of git diff-index
?
For example (in shell):
git add -A
git diff-index --quiet HEAD || git commit -m 'bla'
EDIT: Fixed git diff
command according to Holger's comment.
Upvotes: 265
Reputation: 8603
Just extending Tobi & Holger's answer with an explicit if
statement.
git add -A
if ! git diff-index --quiet HEAD; then
git commit -m "Message here"
git push origin main
fi
Let's give it a bit explanation.
git add -A
: staged your changes (required for the next step)
git diff-index --quiet HEAD
will compare your staged changes with the HEAD.
--quiet
is impotant as it will imply --exit-code
which "makes the program exit with codes 1 if there were differences and 0 means no differences".
See --quiet.
Upvotes: 22
Reputation: 35796
When going through a shell, you can use the ... || true
technique to declare a failure to be expected and ignored:
git commit -a -m "beautiful commit" || true
This would also prevent a shell script from exiting when using the errexit
option.
Instead of ... || true
you can also use any other command that exits with a return code of 0, such as
git commit -a -m "beautiful commit" || echo "ignore commit failure, proceed"
Upvotes: 4
Reputation: 3
try/catch baby!
from fabric.api import local
from fabric.colors import green
def commit(message='updates'):
try:
local('git add .')
local('git commit -m "' + message + '"')
local('git push')
print(green('Committed and pushed to git.', bold=False))
except:
print(green('Done committing, likely nothing new to commit.', bold=False))
Upvotes: -8
Reputation: 13133
with settings(warn_only=True):
run('git commit ...')
This causes fabric to ignore the failure. Has the advantage of not creating empty commits.
You can wrap it in a additional layer of with hide('warnings'):
to totally suppress output, otherwise you'll get a note in the fabric output that the commit failed (but the fabfile continues to execute).
Upvotes: 2