😸

Git checkoutの移動先をGUIで選ぶためのシェルスクリプト

2023/03/25に公開

(Mac Catalina, Ubutnu22.04のzshで確認)
(同様のツールがあるかも)

動機

ターミナル上のGUIで、git checkoutで移動するブランチを選択して移動したい

現状やっていること

  • git branchして一覧を出してから、git checkoutのあとにコピペ
  • 似たような名前のブランチを使っている
  • auto completionでローカル以外のリポジトリが見えるので面倒
  • ターミナル上でコマンドを打って移動したい(ログ的に見返すため)

やったこと

ChatGPT4にシェルスクリプトを作ってもらいました。

fzfをインストール

選択用のGUIを作るためのものです。
https://github.com/junegunn/fzf#installation を見てインストール。
(インストール時の質問は全部yesにしました)
(ターミナルを再起動するか、.zshrcを再読込する必要があります)

シェルスクリプトを用意

git_branch_checkout.sh
#!/bin/bash

# 1. Read the results of `git branch` and store them in the variable $files
files=$(git branch)

# 2. Use fzf for GUI-like selection of a branch in the terminal
selected_branch=$(echo "$files" | fzf)

# 3. Check if a branch was selected and perform git checkout
if [ -n "$selected_branch" ]; then
  # Remove the leading '*' and any whitespace from the selected branch name
  branch_name=$(echo "$selected_branch" | sed 's/^\*//; s/^[[:space:]]*//')

  # Perform git checkout on the selected branch
  git checkout "$branch_name"
else
  echo "No branch selected"
fi

別バージョン

INSTRUCTIONSを追加、順番を逆に

クリックして表示
#!/bin/bash

# 1. Read the results of `git branch` and store them in the variable $files
files=$(git branch)

# 2. Add instructions to the list of branches
instructions="
=== INSTRUCTIONS ===
Please select a branch from the list below.
You can type to filter the list and press Enter to confirm your selection.
====================
"
branch_list=$(echo -e "$instructions\n$files")

# 3. Reverse the order of branches and instructions using `tac`
reversed_branch_list=$(echo "$branch_list" | tac)

# 4. Use fzf for GUI-like selection of a branch in the terminal
selected_branch=$(echo "$reversed_branch_list" | fzf)

# 5. Check if a branch was selected and perform git checkout
if [ -n "$selected_branch" ]; then
  # Check if the selected item is part of the instructions (by looking for the `===` delimiter)
  if [[ $selected_branch != *"==="* ]]; then
    # Remove the leading '*' and any whitespace from the selected branch name
    branch_name=$(echo "$selected_branch" | sed 's/^\*//; s/^[[:space:]]*//')

    # Perform git checkout on the selected branch
    git checkout "$branch_name"
  else
    echo "Invalid selection. Please try again."
  fi
else
  echo "No branch selected"
fi

GUI操作

実行する

bash /full/path/git_branch_checkout.sh

  • feature...というブランチが5つある
  • 今いるブランチが *
  • 移動するブランチが >
    • Enterで選択、Escでキャンセル

エイリアスは例えば

.zshrc
alias gg=`bash /full/path/git_branch_checkout.sh`

Appendix GPT4へのコマンド

GPT4へのコマンドは、こんな感じでした。別のGUIツールを使った方法を提案されることもありました。

I want a shell script for following requirements.

1. read the results of `git branch`. Set them as $files.
2. call `git checkout` and add the selection of the file, use GUI in the terminal
3. Select the file from $files to `git checkout`

Discussion