Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking a branch, so that it cannot be staged/committed into? (Only merged/etc)

Tags:

git

I have a master/develop branching system that i have come to love, but it comes with a basic rule. No commits are done on develop or master, only merges. This is great, but recently i accidentally made some changes/commits on my develop branch and it annoys the tar out of me.

I looked into moving the ownership of those commits from develop into another already existing branch (We'll call it work), the one i should have been working on in the first place, but i decided to just let this one go. Instead, i'd like to fix the issue to begin with.. How does one go about locking a branch, so that commit simply doesn't work on it for traditional, normal changes?

Eg, if you made changes on a "locked" branch, you couldn't git add nor could you git commit -a. I suppose technically i'm asking to lock staging, but you get the idea. Any thoughts on this? Or would i simply be better off learning git well enough that i know how to fix commit parent issues?

like image 693
Lee Olayvar Avatar asked Feb 22 '11 01:02

Lee Olayvar


People also ask

What does locking a branch do?

Locking a branch prevents other users from changing the existing commit history. Locking also blocks any new commits from being added to the branch by others.

Can you commit to a merged branch?

Merges a branch into the current branch, creating a merge commit. Use git checkout <target-branch> to switch to the branch into which you want to merge.

What happens when a branch is merged?

When you perform a merge, you effectively merge one branch into another—typically a feature branch or bug fix branch into a main branch such as master or develop. Not only will the code changes get merged in, but also all the commits that went into the feature branch.

What does it mean if a branch is not fully merged?

It means the branch you are about to delete contains commits that are not reachable from any of: its upstream branch, or HEAD (currently checked out revision). In other words, when you might lose commits¹. In practice it means that you probably amended, rebased or filtered commits and they don't seem identical.


1 Answers

Copy this:

#!/bin/bash

if [[ `git symbolic-ref HEAD` == "refs/heads/master" ]]
then
    echo "You cannot commit in master!"
    exit 1
fi

into a file named pre-commit in .git/hooks/

It will prevent you from commiting into the branch master. You can easily customize it to add more branches or to personalize the error message and so on.


BTW, a useful trick to know when you made modifications in master but you want to commit them in somebranch is to do:

git stash
git checkout somebranch
git stash apply

and then you are in somebranch with your modifications ready to commit!

like image 136
Simon Avatar answered Sep 30 '22 08:09

Simon