0

I have a hair-splitting edge case where I need a commit to BranchA to be immediately merged into BranchB, and I'd like this to be automated.

I tried looking up steps to commit to 2 branches at the same time and found this, but I don't know how to automate it.

I'm aware of .git/hooks/post-commit but I'm not sure if the commit exists before the hook runs or after the script exits 0. Also I don't know if the git merge command can merge to a branch we're not checked out too.

Is this something I can do with just git? Or do I need to invent a complicated rube-goldberg system of file-watchers?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dan
  • 179
  • 1
  • 1
  • 13
  • 3
    "but I'm not sure if the commit exists before the hook runs or after the script exits 0" what happens when you _just try it_? – anthony sottile Jan 11 '22 at 23:52

1 Answers1

0

I'm aware of .git/hooks/post-commit but I'm not sure if the commit exists before the hook runs ...

The commit must exist by this point. What's not guaranteed is how you can find it. The HEAD is updated, and any autostash has not yet been applied, so HEAD will generally work, but things aren't locked here so you could be competing with additional commits.

The more important part is this, though:

Also I don't know if the git merge command can merge to a branch we're not checked out too.

This has a typo (or grammar-o) so I'm not 100% positive what you mean here, but I think you mean to ask whether git merge can merge into some branch other than the current branch, and the answer to that is simple: no, it cannot.

You could use an added working tree (see the git worktree command) to do what you want. Use the existing working tree and $GIT_DIR to run git rev-parse to find the hash ID of the current commit (noting that you're racing against other potential git commit actions), then move to the other working tree, unset GIT_WORK_TREE if necessary, and do the merge there. Remember that merges can fail, and won't start if the directory is not "clean".

torek
  • 448,244
  • 59
  • 642
  • 775