@yaakaito/agflo-gh
v0.4.0
Published
gh CLI を直接 exec する代わりに使う薄いラッパー。認証は gh に移譲する
Readme
@yaakaito/agflo-gh
Node.js から GitHub CLI (gh) を呼び出す helper。
認証は gh に委譲し、JSON / GraphQL の応答取得と認証付き clone を提供する。
インストール
Node.js 22.6.0 以上、ESM、PATH 上の gh が必要。
clone には git も必要。
利用先の GitHub に対する gh の認証を済ませる。
pnpm add @yaakaito/agflo-gh
gh auth login使用例
import { createGh } from '@yaakaito/agflo-gh'
const gh = createGh({ cwd: process.cwd() })
await gh.ensureAvailable()
const pr = await gh.json<{ number: number; title: string }>([
'pr', 'view', '--json', 'number,title',
])
console.log(pr.number, pr.title)
const data = await gh.graphql<{ viewer: { login: string } }>(
'query { viewer { login } }',
)
console.log(data.viewer.login)型引数 T は JSON の実行時検証を行わない。
検証が必要な場合は取得後に schema などで確認する。
createGh(options?): Gh
| GhOptions | 内容 |
|---|---|
| cwd?: string | gh / git の既定の作業ディレクトリ。省略時はプロセスの cwd |
| exec?: ExecFn | コマンド実行関数の差し替え。既定はこのパッケージの exec |
各メソッドの opts?: GhRunOptions は { cwd?: string; env?: NodeJS.ProcessEnv }。
メソッドの cwd が createGh の cwd より優先される。
env を指定すると子プロセスの環境を置き換えるため、継承する場合は { ...process.env, KEY: 'value' } を渡す。
| Gh のメソッド | 戻り値 | 内容 |
|---|---|---|
| raw(args: string[], opts?) | Promise<ExecResult> | gh を引数配列で実行 |
| json<T>(args: string[], opts?) | Promise<T> | raw の stdout を JSON.parse |
| graphql<T>(query: string, vars?: GraphqlVars, opts?) | Promise<T> | gh api graphql の応答の data を返す |
| ensureAvailable() | Promise<void> | gh --version を実行。認証の有効性は検証しない |
| gitCredentialArgs() | string[] | Git に gh credential helper を指定する引数 |
| cloneWithAuth(url: string, dir: string, opts?) | Promise<void> | gh 認証で clone し、clone 先の Git 設定に helper を保存 |
GraphqlVars = Record<string, string | number | boolean>。
文字列は -f、数値と真偽値は -F で渡す。
graphql() は応答に errors がある場合、または data がない場合に例外を投げる。
import { createGh } from '@yaakaito/agflo-gh'
const gh = createGh()
await gh.cloneWithAuth('https://github.com/OWNER/REPO.git', './checkout')cloneWithAuth は HTTPS URL 向け。
既存の credential helper をコマンド単位で解除して !gh auth git-credential を使い、clone 後も fetch / push に使えるよう .git/config に保存する。
exec と gitCredentialArgs
ルートから単独でも import できる。
import { exec, gitCredentialArgs } from '@yaakaito/agflo-gh'
const { stdout } = await exec('git', [
...gitCredentialArgs(), 'ls-remote', 'https://github.com/OWNER/REPO.git',
])
console.log(stdout)type ExecOptions = { cwd?: string; env?: NodeJS.ProcessEnv }
type ExecResult = { stdout: string; stderr: string; code: number }
type ExecFn = (cmd: string, args: string[], opts?: ExecOptions) => Promise<ExecResult>exec はシェルを介さず spawn し、stdin を無視して stdout / stderr を文字列に集める。
通常の終了コードが非 0 なら reject し、Error の result に ExecResult を付ける。
プロセス起動自体の失敗も reject する。
raw() も既定の exec では同じ挙動になる。
再試行、timeout、応答のページネーションは自動では行わない。
