Reputation: 4185
I have a Jenkins job that builds from a github.com repository's master branch with Maven (mvn clean install
), then checks for license headers in Java files and missing NOTICE files, and adds them if necessary (mvn license:format notice:generate
). Sometimes this will result in changed or added files, sometimes not.
Whenever there have any changes been made (by the license plugin) I want to push the changes to the github repo.
Now I'm having trouble figuring out how best to achieve that. I've added a shell build step after the Maven license plugin where I execute git commands:
git add . # Just in case any NOTICE files have been added
git commit -m "Added license headers"
git add .
alone works, i.e., doesn't break the build, even if no files have been added. However, git commit
breaks the build, if there aren't any changes at all.
I'm not concerned about pushing back to github, as I believe the Git Publisher post-build action can do this for me. Can someone please point me in the right direction for the git commit?
Upvotes: 42
Views: 25555
Reputation: 126
Following worked for me:
if [[ -n $(git status --porcelain) ]]; then
echo "Changes detected. Preparing to commit and push."
else
echo "No changes to commit."
fi
This is mentioned in detail here: What does the term "porcelain" mean in Git?
Upvotes: 0
Reputation: 12601
git diff --quiet && git diff --staged --quiet || git commit -am 'Added license headers'
This command do exactly what is required, 'git commit only if there are changes', while the commands in the other answers do not: they only ignore any error of git commit
.
Upvotes: 116
Reputation: 1995
You can also just catch the error code with an OR operator:
git commit -m "Added license headers" || echo "No changes to commit"
Upvotes: 40
Reputation: 4185
To stop the build from breaking on the shell build step returning exit code 1
at any one point, e.g., when trying to make a git commit although there is nothing to commit, you can simply wrap the respective commands into an echo.
echo `git add -A && git commit -m "Added license headers"`
Now, whether there are untracked files to add to the index or not, and whether the working tree is dirty or clean, echo will return exit code 0
, as there will be some string to be echo
ed.
Upvotes: 5