GitLab 差分URL生成スクリプト作ってみた

会社ではよく、pushしたあとに、差分をURLでチャットに流したりするんですが、
毎回、ブラウザからCompare用の画面に行くのが面倒なので、
指定リビジョンから、HEADまでの差分URLを生成するスクリプトを作りました。

Macなら、そのままブラウザが開くようにしました。

git-compare-gitlab.sh

git log --graph の出力をそのまま、fzfコマンドに流し込んでいます。
見やすいように、formatは調整していて

fzfコマンドで選択したリビジョンと、現在のHEADのリビジョンを比較するURLを生成しています。
Macの場合は、openコマンドでブラウザが開けるので便利です。

ソースがこちら

#!/usr/bin/env bash
set -u

head=$(git rev-parse HEAD | cut -c1-7)

msg="Where from compare to HEAD ? >>> "
format="%C(yellow)%h%C(reset) %C(magenta)[%ad]%C(reset)%C(auto)%d%C(reset) %s %C(cyan)@%an%C(reset)"
line=$(git log --graph --all --date=short --format="$format" | fzf --ansi --prompt="$msg" --reverse)
if [ -z "$line" ]; then
    exit 1
fi

rev=$(echo "$line" | perl -ne 'print if /^.* (\w+) \[.*$/' | perl -pe "s/^.* (\w+) \[.*$/\1/")
if [ -z "$rev" ]; then
    exit 1
fi

domainAndPath=$(git remote get-url --push origin | perl -pe 's/git@(.+):(.+)\.git/\1\/\2/')
url="https://$domainAndPath/compare/${rev}...${head}"
echo "$url"

# macなら、openコマンドで開く
if [ "$(uname)" == 'Darwin' ]; then
    open $url
fi

必要なコマンド (fzf)

  • fzf

リビジョン選択には、fzfコマンドを使っています。

fzfは、デフォルトで入力欄が下で、表示出力が下から上になるので、
git log --graphで出力されたコミットグラフが逆向きになってしまいます。

そこを合わせる為に、---reverse オプションを付けて、上から下になるように表示を合わせています。

fzf install

brew install fzf

fzf usage

$ fzf --help

usage: fzf [options]

  Search
    -x, --extended        Extended-search mode
                          (enabled by default; +x or --no-extended to disable)
    -e, --exact           Enable Exact-match
    --algo=TYPE           Fuzzy matching algorithm: [v1|v2] (default: v2)
    -i                    Case-insensitive match (default: smart-case match)
    +i                    Case-sensitive match
    --literal             Do not normalize latin script letters before matching
    -n, --nth=N[,..]      Comma-separated list of field index expressions
                          for limiting search scope. Each can be a non-zero
                          integer or a range expression ([BEGIN]..[END]).
    --with-nth=N[,..]     Transform the presentation of each line using
                          field index expressions
    -d, --delimiter=STR   Field delimiter regex (default: AWK-style)
    +s, --no-sort         Do not sort the result
    --tac                 Reverse the order of the input
    --tiebreak=CRI[,..]   Comma-separated list of sort criteria to apply
                          when the scores are tied [length|begin|end|index]
                          (default: length)

  Interface
    -m, --multi           Enable multi-select with tab/shift-tab
    --no-mouse            Disable mouse
    --bind=KEYBINDS       Custom key bindings. Refer to the man page.
    --cycle               Enable cyclic scroll
    --no-hscroll          Disable horizontal scroll
    --hscroll-off=COL     Number of screen columns to keep to the right of the
                          highlighted substring (default: 10)
    --filepath-word       Make word-wise movements respect path separators
    --jump-labels=CHARS   Label characters for jump and jump-accept

  Layout
    --height=HEIGHT[%]    Display fzf window below the cursor with the given
                          height instead of using fullscreen
    --min-height=HEIGHT   Minimum height when --height is given in percent
                          (default: 10)
    --reverse             Reverse orientation
    --border              Draw border above and below the finder
    --margin=MARGIN       Screen margin (TRBL / TB,RL / T,RL,B / T,R,B,L)
    --inline-info         Display finder info inline with the query
    --prompt=STR          Input prompt (default: '> ')
    --header=STR          String to print as header
    --header-lines=N      The first N lines of the input are treated as header

  Display
    --ansi                Enable processing of ANSI color codes
    --tabstop=SPACES      Number of spaces for a tab character (default: 8)
    --color=COLSPEC       Base scheme (dark|light|16|bw) and/or custom colors
    --no-bold             Do not use bold text

  History
    --history=FILE        History file
    --history-size=N      Maximum number of history entries (default: 1000)

  Preview
    --preview=COMMAND     Command to preview highlighted line ({})
    --preview-window=OPT  Preview window layout (default: right:50%)
                          [up|down|left|right][:SIZE[%]][:wrap][:hidden]

  Scripting
    -q, --query=STR       Start the finder with the given query
    -1, --select-1        Automatically select the only match
    -0, --exit-0          Exit immediately when there's no match
    -f, --filter=STR      Filter mode. Do not start interactive finder.
    --print-query         Print query as the first line
    --expect=KEYS         Comma-separated list of keys to complete fzf
    --read0               Read input delimited by ASCII NUL characters
    --print0              Print output delimited by ASCII NUL characters
    --sync                Synchronous search for multi-staged filtering
    --version             Display version information and exit

  Environment variables
    FZF_DEFAULT_COMMAND   Default command to use when input is tty
    FZF_DEFAULT_OPTS      Default options (e.g. '--reverse --inline-info')

おしまい

これで簡単にURLを共有できるね!!

コメントを残す