🛐

nix設定編集時に新規ファイルのstagingを忘れて時間を溶かす そんな苦しみが減ってほしいという祈り

に公開1

nixコマンドが失敗したとき、まず「git add忘れてない?」の一言があるだけで救われるひとがいます。
シェルの関数でnixをラップして終了ステータスを監視する設定を書きました。これを読み込むと、nixコマンドが失敗したときにif ... fiブロック内のメッセージが表示されるようになります。bashやzshでは動くと思います。

.zshrcなど
nix() {
  command nix "$@"
  local exit_code=$?
  if [[ $exit_code -ne 0 ]]; then
    echo ""
    echo "nix command failed!"
    echo "Did you forget to 'git add' new files?"
  fi
  return $exit_code
}

Discussion

ryota2357ryota2357

何回も git add 忘れをやらかしているので、早速自分の dotfiles にも導入させてもらいました。ありがとうございます。その際に少し改良をしたのでこちらにも投げておこうと思います。

  • untraced なファイルなある時のみ警告メッセージを出すように
  • untraced ファイルを表示 (.nix ファイルは強調表示)
  • メッセージに色をつけた
nix() {
  command nix "$@"
  local exit_code=$?
  if [[ $exit_code -ne 0 ]]; then
    local untracked_files=()
    while IFS= read -r line; do
      [[ -n "$line" ]] && untracked_files+=("$line")
    done < <(git ls-files --others --exclude-standard)
    if [[ ${#untracked_files[@]} -gt 0 ]]; then
      local red yellow bold reset
      red="$(printf '\033[31m')"
      yellow="$(printf '\033[33m')"
      bold="$(printf '\033[1m')"
      reset="$(printf '\033[0m')"
      echo ""
      echo "${red}${bold}nix command failed!${reset}"
      echo "${yellow}Did you forget to ${bold}git add${reset} ${yellow}these new files?${reset}"
      for file in "${untracked_files[@]}"; do
        if [[ "$file" == *.nix ]]; then
          echo "  ${bold}$file${reset}"
        else
          echo "  $file"
        fi
      done
    fi
  fi
  return $exit_code
}
fish版
function nix --description 'Wrapper for nix command that shows untracked files on failure'
  command nix $argv
  set -l exit_code $status
  if test $exit_code -ne 0
    set -l untracked_files (git ls-files --others --exclude-standard)
    if test (count $untracked_files) -gt 0
      set -l red (printf '\033[31m')
      set -l yellow (printf '\033[33m')
      set -l bold (printf '\033[1m')
      set -l reset (printf '\033[0m')
      echo ""
      echo "$red$bold"nix command failed!"$reset"
      echo "$yellow"Did you forget to "$bold"git add"$reset" "$yellow"these new files?"$reset"
      for file in $untracked_files
        if string match -q "*.nix" $file
          echo "  $bold$file$reset"
        else
          echo "  $file"
        end
      end
    end
  end
  return $exit_code
end