🐕

【--helpの代わり】`$ which foo-function`をしたときに見られるヘルプを雑に書く【Bash,Zsh】

に公開

読者の方々はdotfilesを書いているだろうか?
.bashrcや.zshrcに、aliasで表現できないものを関数で書いているだろうか?

aliasや関数は、alias gs='git staus'のような、手には馴染むが名前からは使い方がイマイチわからないものも作ることがあるだろう。
だが全ての関数がこのgsのように、定義部から使い方が自明な場合であるとは限らない。

(このgsはaliasだが、aliasと関数は.bashrcや.zshrc内では用途がほぼ同じであるだろうことを考えて、ここでは仮に同一視している。)

その時にgs --helpのように、使い方がわかるように--helpをしっかり実装したいと思うだろうか?
筆者的にはNoだ。

そこで今回は、記述コストが最低ランクで、かつwhich fooと打つだけでfoo --helpと同じように「使い方がわかる」ようになる、コスパの高い実装方法を記す。

:コマンドを使う。
:コマンドは「引数に対して何もしない」コマンド。

function gwab () {
  : Creates a worktree for a new branch basing on a base branch
  base_branch=$1
  new_branch=$2
  git worktree add -b "$new_branch" "${new_branch//\#/}" "$base_branch"
}

以下を実行することで、雑にこのgwab関数がなんのためのコマンドなのかわかる。

$ which gwab
gwab () {
        : Creates a worktree for a new branch basing on a base branch
        base_branch=$1
        new_branch=$2
        git worktree add -b "$new_branch" "${new_branch//\#/}" "$base_branch"
}

コメントでいいのでは?

コメント#は消える。

function gwab () {
  # Creates a worktree for a new branch basing on a base branch
  base_branch=$1
  new_branch=$2
  git worktree add -b "$new_branch" "${new_branch//\#/}" "$base_branch"
}
$ which gwab
gwab () {
        base_branch=$1
        new_branch=$2
        git worktree add -b "$new_branch" "${new_branch//\#/}" "$base_branch"
}

(設定によっては消えないかもしれない。そのような設定をしている人は、ぜひコメントで教えて欲しい。)

構文ハイライトが壊れる

前述の:コマンドはforという字句を含んでいるので、エディタによっては構文ハイライトが壊れる。
そのような場合は''でくくるといい。

function gwab () {
  : 'Creates a worktree for a new branch basing on a base branch'
  base_branch=$1
  new_branch=$2
  git worktree add -b "$new_branch" "${new_branch//\#/}" "$base_branch"
}

# ... 構文ハイライトが壊れない
$ which gwab
gwab () {
        : 'Creates a worktree for a new branch basing on a base branch'
        base_branch=$1
        new_branch=$2
        git worktree add -b "$new_branch" "${new_branch//\#/}" "$base_branch"
}

複数行にわたる場合

複数行にわたる場合は''でくくるといい。

function gh-workflow-run-all () {
  : '
  Runs GitHub Actions Workflows that are set to
  ```yaml
  on:
    workflow_dispatch:
  ```
  '

  gh workflow list --json name -q '.[].name' | while read -r workflow ; do
    echo "Running: $workflow"
    gh workflow run "$workflow" --ref main
  done
}
$ which gh-workflow-run-all
gh-workflow-run-all () {
        : '
  Runs GitHub Actions Workflows that are set to
  ```yaml
  on:
    workflow_dispatch:
  ```
  '
        gh workflow list --json name -q '.[].name' | while read -r workflow
        do
                echo "Running: $workflow"
                gh workflow run "$workflow" --ref main
        done
}

少々フォーマットが崩れるが、そこはあまり気にしていない。

逆に、ここを気にするようになるくらいが、もっとよい方法を考えるべきタイミングだと思っている。

Discussion