Search code examples
linuxgitbashshellgithub

Check if local git repo is ahead/behind remote


I'm developing a git plug-in, and I need to know when a local repo is changed (can commit changes), ahead (can push to remote) or behind (can pull from remote) using the command line.

This is what I am doing so far:

  • Can commit?

    If git diff-index --name-only --ignore-submodules HEAD -- returns something, then yes, there are changes to commit.

  • Can push?

    If git status -sb contains the word ahead in it's output, then yes, there are commits to push.

  • Can pull?

    Nothing implemented yet.

The can commit? part seems to work properly. Can push? only works for the master branch, and this is a huge problem.

How can I safely check if, on every branch, a git repo has changes to commit, commits to push, or needs a git pull?


Solution

  • In the end, I implemented this in my C++11 git-ws plugin.

    string currentBranch = run("git rev-parse --abbrev-ref HEAD"); 
    bool canCommit = run("git diff-index --name-only --ignore-submodules HEAD --").empty();
    bool canPush = stoi(run("git rev-list HEAD...origin/" + currentBranch + " --ignore-submodules --count")[0]) > 0;
    

    Seems to work so far. canPull still needs to be tested and implemented.

    Explanation:

    • currentBranch gets the console output, which is a string of the current branch name
    • canCommit gets whether the console outputs something (difference between current changes and HEAD, ignoring submodules)
    • canPush gets the count of changes between origin/currentBranch and the local repo - if > 0, the local repo can be pushed