[英]Disallowing branching from a branch in git
在我的工作流程中,我几乎从不想从 master 以外的分支分支。 有几次我在开始一个新功能时不小心这样做了。 当我这样做时,它在合并时搞砸了我的历史。
如果我已经在一个分支上,有什么好方法可以保护自己免受创建新分支的影响? 我知道 git branch 的第二个参数
git checkout -b newbranch master
但我不确定我是否可以重新训练自己以始终提供它。 理想情况下,当我键入git checkout -b newbranch
,我会将其作为默认行为,或者在我尝试从分支分支时发出警告。
您可以为git
创建一个bash 别名来检查此条件并重写您的 checkout 命令以遵循您的约定。 在下面的这个例子中,我保留了一个传入的父分支,但在没有给出时默认为master
。
#!/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.
合并失败是我们的预期结果(如果别名未激活,我们会从test1
分支到test2
,合并会快进。测试一下!
我有一个自定义的批处理/别名,可以切换到 master,可能是 pull master 等,然后创建了一个新分支。
另一种选择是首先在远程仓库中创建分支。 我不知道你的远程仓库使用什么解决方案,但这样这个过程会更有意识。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.