From d1d724d1170e8cd2460cf1beb5098161ac33ef9a Mon Sep 17 00:00:00 2001 From: Hare Date: Tue, 24 Sep 2024 00:49:23 +0900 Subject: [PATCH] 2024-09-24 00:49:23 --- article/tech/node-simple-git.md | 90 +++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 article/tech/node-simple-git.md diff --git a/article/tech/node-simple-git.md b/article/tech/node-simple-git.md new file mode 100644 index 0000000..ac9c90c --- /dev/null +++ b/article/tech/node-simple-git.md @@ -0,0 +1,90 @@ +--- +title: git-jsを使ってみた備忘録 +released_at: 2024-09-24T00:49:00 +updated_at: "" +tags: + - NodeJS + - Typescript + - Git +image: /uploads/ +publish: public +--- + + +# git-jsについて +--- +[git-js](https://github.com/steveukx/git-js)、パッケージ名は`simple-git`です。ここでは、simple-gitと呼びます。 +正直公式のREADMEが充実してるので記事書くか迷った。 +npmを使用して導入します。 +```sh +npm i simple-git +``` + +このパッケージは、内部でgitコマンドを実行してそれをラッパーするライブラリです。 +なので、実行環境に入っているgitを利用する必要があり、グローバルのconfigも影響します。 + +# 使ってみる +--- +## インスタンスの作成  +simple-gitインスタンスを作成します。 +インスタンスの引数に取る`SimpleGitOptions` には、gitリポジトリであるディレクトリや`-c`でしてされる引数を設定できます。 +```ts +import { simpleGit, } from 'simple-git'; +import type { SimpleGit, SimpleGitOptions } from 'simple-git'; + +const options: Partial = { + baseDir: process.cwd(), + binary: 'git', + maxConcurrentProcesses: 6, + config: [ + 'http.proxy=someproxy' + ], +}; + +const git: SimpleGit = simpleGit(gitOptions); +``` +- `binary`はgitとして実行するバイナリのパス/コマンド +- `maxConcurrentProcesses`は子プロセスの上限数 +- configは`git config http.proxy someproxy`等と書いたときの`config`以降のオプション(キーと値を`=`で繋げて渡す) +### 認証情報の渡し方 +そのアプリケーションでしか使わないデプロイキーをsshのコンフィグファイルから設定するなんて今日日流行りません。 +gitインスタンス作成時に渡される`config`は、コマンドでは +```sh +git -c "http.proxy=someproxy" clone ... +``` +のように、`-c`によって渡されるやつです。 +これを使って、git内部で実行されるsshを設定することができます。 +``` +core.sshCommand=ssh -i ./path/to/key -F /dev/null +``` +詳しくは[[git-ssh-config]]にまとめています。 +## コマンドを実行する +インタフェースに関数として多くのラップされたコマンドが存在します。 +一覧は[README](https://github.com/steveukx/git-js?tab=readme-ov-file#api)を参照してください。 +```ts +git.pull(); +git.clone(`https://github.com/....`); +git.init(); +``` +また、これらの関数をchainさせることができます。 +```ts +await git.init().addRemote('origin', '...remote.git'); +``` +### Wrapされていないコマンド +gitの新機能やニッチすぎるコマンドは関数として実装しきれていないようです。 +その場合は、サブコマンドをテキストで受け取る関数に投げてやりましょう。 +引用:[Complex-Request](https://github.com/steveukx/git-js?tab=readme-ov-file#complex-requests) +```ts +const commands = ['config', '--global', 'advice.pushNonFastForward', 'false']; + +const result = await git.raw(...commands); +``` +# まとめ +--- +もともと`child_process`の`execSync`をつかってGitコマンドを実行していましたが、帰ってきたデータを解析する手間がかかるのでありがたくライブラリに頼りました。 +似たようなライブラリに、[js-git](https://github.com/creationix/js-git)というものがありますが、これはGitのラッパーではなく、gitをjsで実装することで、様々な環境でgitを弄れるというものらしいです。機会があったら触ってみたい。 +# 参考文献 +--- +https://github.com/steveukx/git-js +https://neos21.net/blog/2020/07/24-01.html \ No newline at end of file