Reputation: 70250
In my workflow I almost never want to branch from a branch other than master. A couple of times I have done this by accident when starting a new feature. When I do, it screws up my history when merging.
What's a good way to protect myself from creating a new branch if I am already on a branch? I know about the second parameter to git branch
git checkout -b newbranch master
but I'm not sure I can retrain myself to always provide it. Ideally I would have this be the default behaviour when I type git checkout -b newbranch
, or have a warning when I attempt to branch from a branch.
Upvotes: 1
Views: 86
Reputation: 5386
You can create a bash alias for git
that checks for this condition and rewrites your checkout command to follow your convention. In this example below, I preserve a passed in parent branch, but default to master
when one is not given.
#!/bin/bash
cmd=$1
opt=$2
branch=$3
parent=$4
if [[ $cmd = "checkout" ]] && [[ $opt = "-b" ]]; then
if [ -z "$parent" ]; then
parent="master"
fi
/usr/bin/git checkout -b $branch $parent
else
/usr/bin/git "$@"
fi
chmod +x /path/to/git-wrapper.sh
alias git=/path/to/git-wrapper.sh
mkdir test
cd ./test
git init
echo "First line" >readme.md
git add readme.md
git commit -m "Initial commit"
git checkout -b test1
echo "Second line" >> readme.md
git commit -am "Second line"
git checkout -b test2
echo "Third line" >> readme.md
git commit -am "Third line"
git checkout master
git branch -a
git log
git merge test1
git merge test2
Initialized empty Git repository in ...
[master (root-commit) 11bd292] Initial commit
1 file changed, 1 insertion(+)
create mode 100644 readme.md
Switched to a new branch 'test1'
[test1 4ace272] Second line
1 file changed, 1 insertion(+)
Switched to a new branch 'test2'
[test2 54b7fff] Third line
1 file changed, 1 insertion(+)
Switched to branch 'master'
* master
test1
test2
Updating 11bd292..4ace272
Fast-forward
readme.md | 1 +
1 file changed, 1 insertion(+)
Auto-merging readme.md
CONFLICT (content): Merge conflict in readme.md
Automatic merge failed; fix conflicts and then commit the result.
A merge failure is our expected result (if the alias were not active, we would have branched from test1
to test2
and the merge would have been fast-forwarded. Test it out!
Upvotes: 1
Reputation: 35155
I'd have a custom batch/alias that switched to master, maybe pulled master, etc, and then created a new branch.
Another option would be to create branches in your remote repo first. I don't know what solution you're using for your remote repo but this way the process would be more conscious.
Upvotes: 0