Monday, October 10, 2022

[SOLVED] git push to return different staus code if repo is upto date

Issue

I have a merge job in my gitlab ci, which merges two branches at every midnight. Now, this runs fine if there are changes in one branch so deployment job gets triggered. But it doesn't when there no changes. So whenever it runs git push in ci job, I get status code 0. What I require is, to return status code 0 if changes are pushed and staus code 1 if "Everything is upto date".

How can I achive this? Is there any way using shell script or python?

Basically, I want the merge/push job to fail is there are no changes, so on_failure job can trigger.

Thanks.


Solution

If you are merging sourceBranch into targetBranch, before you do the merge, you could check the number of commits that sourceBranch is ahead of targetBranch and "exit 1" if that number is 0. (I assume you wouldn't even need to attempt the push at that point.)

For example, in Bash it might look like:

# Check if there is anything to merge
NumCommitsAhead=$(git log targetBranch..sourceBranch --oneline | wc -l)
if [ $NumCommitsAhead -eq 0 ]; then
    echo "sourceBranch has no new commits to merge. Exiting."
    exit 1
fi


Answered By - TTT
Answer Checked By - Timothy Miller (WPSolving Admin)