LoginSignup
0
0

More than 3 years have passed since last update.

peco を使って git のリモートブランチをチェックアウトする

Posted at

peco を使って リモートブランチをチェックアウトする

peco は標準入力をインクリメンタル検索ができるツールです。

これをつかって git のリモートブランチをチェックアウトする方法を記載します。

最終形

以下の内容で例えば remote.sh というファイル名で保存して .bashrc から source コマンドで読み込みます。

#!/bin/sh
coremote () {
    remotename=`echo $1 | sed -r "s#([^/]+)/.*#\1#"`
    branchname=`echo $1 | sed -r "s#[^/]+/##"`

    echo git checkout -b $branchname $remotename/$branchname
         git checkout -b $branchname $remotename/$branchname
}
alias cor='export -f coremote; git branch -r | peco | xargs -I{} bash -c "coremote {}"'

alias の cor を呼び出せば、インクリメンタル検索を行ってリモートブランチをチェックアウトできます。

$ cor

解説

git branch -r コマンド

git のリモートブランチを取得するには git branch -r コマンドを実行します。
git branch -r コマンドを実行すると、リモートブランチの情報を標準出力に出力します。

peco コマンド

peco は標準入力から受けたデータをユーザーの入力に基づいてフィルタリングして、ユーザーの選択した一行を表示します。

こんな感じ

git branch -r | peco

git checkout コマンド

peco コマンドの結果リモートブランチの情報を例えば以下のような形で出力します。

origin/feauture/hogehoge

git コマンドでは以下のようなコマンドでリモートブランチをチェックアウトします。

git checkout -b feauture/hogehoge origin/feauture/hogehoge

sed コマンド

origin/feauture/hogehogeorigin の部分と feauture/hogehoge の部分に分離するために sed コマンドを使います。

リモート名 (origin の部分)

echo origin/feauture/hogehoge |  sed -r "s#([^/]+)/.*#\1#""

ブランチ名 (feauture/hogehoge の部分)

echo origin/feauture/hogehoge |  sed -r "s#([^/]+)/.*#\1#""

関数で git checkout コマンドを組み立てる。

coremote () {
    remotename=`echo $1 | sed -r "s#([^/]+)/.*#\1#"`
    branchname=`echo $1 | sed -r "s#[^/]+/##"`

    git checkout -b $branchname $remotename/$branchname
}

これで以下を実行すると

coremote origin/feauture/hogehoge

以下コマンドが実行されます。

git checkout -b feauture/hogehoge origin/feauture/hogehoge

xargs で標準出力の結果を引数に関数 coremote を呼び出す

coremote に標準出力からのデータを引数として渡すために xargs を使います。

単純に以下のようにすると

git branch -r | peco | xargs coremote

以下のようなエラーになります。

xargs: coremote: そのようなファイルやディレクトリはありません

coremote は bash の関数なので bash 経由で以下のように呼び出します。

git branch -r | peco | xargs -I{} bash -c "coremote {}"'

そうすると以下のエラーになります。

bash: coremote: コマンドが見つかりません

あらかじめ export -f function をしておくといいらしい。
https://qiita.com/D-3/items/8bdb834ff53256cef481

以下のようになる。

export -f coremote; git branch -r | peco | xargs -I{} bash -c "coremote {}"

参考

https://qiita.com/D-3/items/8bdb834ff53256cef481
https://qiita.com/sukebeeeeei/items/9b815e56a173a281f42f
https://qiita.com/m-tmatma/items/44bfce739023a5b00ac3

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0