用部分名称在git中切换分支

问题描述 投票:10回答:3

如果我在git中有以下分支

1194-qa-server
master
remotes/origin/1178-authentication
remotes/origin/1194-qa-server
remotes/origin/HEAD -> origin/master
remotes/origin/master

我想使用--just--切换到分支,即使需要调用脚本,例如:

switch_branch 1178

并且脚本/解决方案应该执行以下操作

  1. git branch -a(在我的存储库中查找本地和远程的所有分支)
  2. 按给定参数过滤('1178'以上)
  3. 提取git可以使用的分支的名称
  4. 切换到那个分支

在不必手动执行所有这些步骤的情况下,建议的方法是什么?

我正在使用Mac OSX,如果这在这里很重要。

更新 - bash-it(github.com/revans/bash-it)符合我的目的

Welcome to Bash It!

Here is a list of commands you can use to get help screens for specific pieces of Bash it:

  rails-help                  list out all aliases you can use with rails.
  git-help                    list out all aliases you can use with git.
  todo-help                   list out all aliases you can use with todo.txt-cli
  brew-help                   list out all aliases you can use with Homebrew
  aliases-help                generic list of aliases.
  plugins-help                list out all functions you have installed with bash-it
  bash-it-plugins             summarize bash-it plugins, and their installation status
  reference <function name>   detailed help for a specific function
git shell console bash-it
3个回答
11
投票

很少有你想要结帐remotes/origin/*的场合。它们存在,但为了这个捷径的目的,让我们不要担心它们。这将为您提供OSX上的所需功能:

git config --global alias.sco '!sh -c "git branch -a | grep -v remotes | grep $1 | xargs git checkout"'

然后你可以发出git sco <number>来签出一个包含<number>但不包括“遥控器”的分支。您可以将sco更改为您想要的任何内容。我刚刚选择了“超级结帐”。

当然,如果你有一个以上的分支与<number>匹配,这将不会很好。然而,它应该是一个不错的起点。


3
投票

这是我为自己想出的解决方案。

[ ${#} -ne 1 ] && { echo -e "Please provide one search string" ; exit 1 ; }
MATCHES=( $(git branch -a --color=never | sed -r 's|^[* ] (remotes/origin/)?||' | sort -u | grep -E "^((feature|bugfix|release|hotfix)/)?([A-Z]+-[1-9][0-9]*-)?${1}") )
case ${#MATCHES[@]} in
  ( 0 ) echo "No branches matched '${1}'" ; exit 1  ;;
  ( 1 ) git checkout "${MATCHES[0]}"      ; exit $? ;;
esac
echo "Ambiguous search '${1}'; returned ${#MATCHES[@]} matches:"

for ITEM in "${MATCHES[@]}" ; do
  echo -e "  ${ITEM}"
done
exit 1

我把它称为git-rcheckout(“r”代表正则表达式,因为缺少一个更好的名字)并把它放在我的路径上(它有点太长了,无法穿上我的.gitconfig。)

它将尝试匹配本地和远程分支(虽然只检查本地),并且可以容忍(IE无视搜索目的)一些JIRA样式,例如以公共前缀开头的分支和样式为JIRA票证ID的东西。

例如打字这个:

git rcheckout this

应该匹配的东西

this-branch
feature/this-branch
bugfix/JIRA-123-this-branch
JIRA-123-this-branch
remotes/origin/this-branch
remotes/origin/feature/this-branch
remotes/origin/bugfix/JIRA-123-this-branch
remotes/origin/JIRA-123-this-branch

但是我使用的正则表达式足够宽容你也可以这样做:

git rcheckout JIRA-123

要访问:

bugfix/JIRA-123-this-branch
JIRA-123-this-branch
remotes/origin/bugfix/JIRA-123-this-branch
remotes/origin/JIRA-123-this-branch

它默认搜索分支前缀,但实际上你可以使用正则表达式来做更好的事情,如下所示:

git rcheckout '.*bran'
git rcheckout '.*is-br.*h'

0
投票

我切换到git-flow工作流程并从此开心。

© www.soinside.com 2019 - 2024. All rights reserved.