0

I'm working on a script that monitors a repository by running a git status and searching for the text "Your branch is behind". If it finds it, it pulls the changes and does a build.

It seems to work well, but it's not super easy to test. I have tested with a test repo where I just edit a text file from another machine and push it, but now I want to test end-to-end with the real code.

Is there any way to put my local repo folder in a state that would simulate a status result of "Your branch is behind"? I tried checkout of a previous commit hash but then I just get a detached head.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Seems like a fragile approach. What if Git's message changes? I'd look into [hooks](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) instead. – isherwood Jan 24 '22 at 21:54
  • 1
    To do this without parsing Git's human-intended text, you can use `git rev-list --left-right` as in [git ahead/behind info between master and branch?](https://stackoverflow.com/q/20433867/1426891). – Jeff Bowman Jan 24 '22 at 22:13

1 Answers1

3

Instead of just checking out a previous commit (i.e. move HEAD to that commit), but leaving the branch pointer where it is, thus entering detached HEAD state, actually move the branch pointer to the previous commit as well:

Before:

$ git checkout mybranch
origin/mybranch → C ← mybranch ← HEAD
                  ↓
                  B
                  ↓
                  A
$ git reset --hard A

After:

origin/mybranch → C
                  ↓
                  B
                  ↓
                  A ← mybranch ← HEAD

Which is the same situation as if your local branch was on commit A to begin with and you fetched new commits B and C from remote origin.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65