LoginSignup
6
1

More than 3 years have passed since last update.

【git】checkoutせずに特定ブランチをpullするエイリアス

Last updated at Posted at 2019-05-15

本文

これのエイリアス版。.gitconfig[alias]以下にそのままコピペすれば動くはず。

.gitconfig
[alias]
    pull-o = "!f(){ \
        local branch_name=${1};\
        local current_branch=$(git symbolic-ref --short HEAD);\
        local branch_remote=$(git config branch.${branch_name}.remote);\
        local branch_path=$(git config branch.${branch_name}.merge);\
        if [ ${branch_name} = ${current_branch} ];then \
            git pull ${branch_remote} ${branch_name} --ff-only;\
            return ${?};\
        else \
            git fetch ${branch_remote} && \
            git fetch . refs/remotes/${branch_remote}/${branch_name}:${branch_path};\
            return ${?};\
        fi;\
    };f"

引数を扱うため関数としてaliasに登録する。使い方はgit pull-o <ブランチ名>HEADの位置によらずoriginの指定ブランチをpullするので、定期的にスクリプト等で実行したい場合に便利……かもしれない。
なお、ファストフォワード不可能な場合などはちゃんと失敗する。

解説

「checkoutせずに特定ブランチをpullする」で書いたように、git fetch . origin/<ブランチ名>:<ブランチ名>はHEADの位置と指定のブランチが一致していると失敗する。その場合は通常のpullをすれば良いのだが、どうせエイリアスにするならということで一致した場合の対策も入れた。
git symbolic-ref --short HEADはHEADのブランチ名を返すため、指定したブランチと比較して分岐し、等しい場合は通常のgit pullを実行する。git pull --ff-onlyにしたのは念のため。

ブランチ名が等しくない(HEADの位置と異なる)場合は以前の記事と同等のことをしている。ただしgit fetch originに失敗した場合はfetch . (略)を実行させたくないため、ここだけは;ではなく&&で接続しておく。あと折角なのでrefs/remotes/${branch_remote}/${branch_name}:refs/heads/${branch_name}とパスを全て書いた。別に書かなくても動く。

return ${?}で直前の実行コマンドの戻り値をそのまま返しているので、このalias自体をシェルスクリプトや&&, ||で繋ぐことが可能。

更新履歴

しれっとアップデートしている。remoteの名前とパスをgit configから引っ張ってきたり、変数宣言をlocalにしたり。

6
1
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
6
1