fishからCircleCIの最新のビルドページを開く


概要

CircleCIのビルドのページを見るのにいちいちブラウザを開いて探しに行くのが面倒だったので、CircleCIがセットアップ済みのgitプロジェクト配下をfishで開いている時、コマンド一発で現在のブランチの最新のビルドのページを開けるようにした。

必要なもの

検証環境

  • macOS High Sierra
  • fish, version 3.0.2
  • ghq version 0.8.0
  • jq-1.6

前提

  • CircleCIのAPIトークンを取得している( xxxx を自分のトークンに差し替える)
  • ghqでリポジトリを管理している( ghq root を起点にパスから情報を取得するため)

やること

  1. 現在のパスからプロジェクトの情報を取得
    • パスから vcs-type, username, project 、現在のブランチ名から branch を取得
  2. CircleCIのAPIから最新のビルドのURLを取得
  3. 取得したURLをブラウザで開く
set -x CIRCLECI_API_TOKEN xxxx # トークンを設定
function circleci_latest_build -d "open circleci latest build page"
  set base_url "https://circleci.com/api/v1.1/project"
  set src_root (ghq root)
  set current_path (pwd)
  switch $current_path
  case "$src_root/*"
    set repository_path (string replace "$src_root/" "" $current_path)
    for el in (string split "/" $repository_path)
      set -a info $el
    end
    switch $info[1]
    case "github.com"
      set vcs_type "github"
    case "bitbucket.org"
      set vcs_type "bitbucket"
    case "*"
      echo "invalid vcs type: $info[1]"
      return 1
    end
    set branch_name (git symbolic-ref --short HEAD)
    if test -z $branch_name
      echo "failed to resolve branch name"
      return 1
    end
    set url "$base_url/$vcs_type/$info[2]/$info[3]/tree/$branch_name?circle-token=$CIRCLECI_API_TOKEN"
    set res (curl -sS -w "\n%{http_code}" $url)
    set code $res[-1]
    set body $res[1..-2]
    switch $code
    case "200"
      if test "$body" != "[ ]"
        echo $res[1..-2] | jq ".[0].build_url" | xargs open
      else
        echo "no build found"
      end
    case "*"
      echo "got status $code"
      echo $body | jq
    end
  case "*"
    echo "current path does not contain $src_root: $current_path"
    return 1
  end
end

補足

  • ghqを使っていなくてもリポジトリ管理のルールがあればそれに対応させても良い
    • ただしAPIの仕様上 vsc-type が必要
    • github.comしか使わないのであれば決め打ちでも可能
  • 細かい動作確認やエラーハンドリングは特にしていない
    • 追記:少しエラーハンドリングなどを修正
  • fishで書いてあるのでbash/zshの場合は適宜読み替えてください