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:

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: