user1529891
user1529891

Reputation:

Auto-create branch if on another branch prior to committing with git

I have a branch, lets say master. I do not have master pushes restricted. Is there a way to have it say that if a commit is accidentally done on the master branch (or another branch) that a new branch is automatically created and the commits are in there?

Example workflow:

  1. Clone the repo master branch.
  2. Makes lots of changes
  3. Does git commit -am ...

I want to hook into #3 and create a new branch if the person is committing on master (or some other "marked" branch).

If it's not possible, does one just block commits at master?

Upvotes: 1

Views: 900

Answers (1)

user1529891
user1529891

Reputation:

I was able to do this by creating a pre-commit hook:

#!/bin/bash
PROTECTEDBRANCH="master"

CURRENTBRANCH=$(git rev-parse --abbrev-ref HEAD)

if [ "$PROTECTEDBRANCH" == "$CURRENTBRANCH" ]; then
    RANDOMBRANCH=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1)

    git checkout -b $RANDOMBRANCH
fi

I saved it in .git/hooks/pre-commit; it works as expected.

Upvotes: 1

Related Questions