Is there a way to keep two branches from merging i

2019-02-13 16:24发布

问题:

I would like to be able to keep two separate branches in a git repo that cannot accidentally be merged even though the branches may contain similar content.

Is there a trick for forcing a branch to remain separate in git? That is assuming I have branch A and branch B, something like git merge B //assuming A is checked out would fail.

The concern here arose because in creating a repository of a website I'm developing I need the HEAD of the master branch to always be the current state of the stable website.

Any development commits I need to occur on the development branch with topic branches off of the development branch if necessary.

 C1-C2                        master
     \
     C3-C4-C5-C6-C9-C10-C11   development
               \
                C7-C8-C12     topic/HEAD

I need to make sure that there's little chance of an accidental merge between the master branch and other branches.

So I'm looking for a way to step 'in between' a merge with the master branch to ask, "This merge will go live on the site, are you sure you want to do it?" And only after I confirm the merge will it go through.

I guess this scenario is relevant only to web developers with code that does not need to be compiled in order to run, and may pull copies of the stable website on a live installation.

回答1:

I believe the only way you could accomplish this is with a pre-commit hook. From the manpage:

This hook is invoked by git commit, and can be bypassed with --no-verify option. It takes no parameter, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with non-zero status from this script causes the git commit to abort.

So, if you really want to, you can write a pre-commit hook which checks the current branch and the branch you're attempting to merge, and exits with non-zero status if it's the pair you don't want. Off the top of my head, the only way I can think of to check what branch you're attempting to merge is to examine the file .git/MERGE_MSG and parse the first line. (The alternative, .git/MERGE_HEAD will tell you the SHA1 you're merging, but with no record of what branch it was, so if two branches are in the same place, you're out of luck.

The pre-commit hook is obviously not run for fast-forward merges; I doubt there's really any way to protect against that. But presumably if you keep the branches from being merged, there won't ever be a fast-forward attempt.



回答2:

Note that a git merge with auto-commit would not call the pre-commit hook. See "git merge auto-commit doesn't fire pre-commit hook"

Merge calls commit_tree directly, so the standard commit hooks are bypassed.

A Patch is in progress.