88 lines
3.6 KiB
Markdown
88 lines
3.6 KiB
Markdown
---
|
|
title: git-jsを使ってみた備忘録
|
|
tags:
|
|
- NodeJS
|
|
- Typescript
|
|
- Git
|
|
image: /uploads/
|
|
publish: public
|
|
---
|
|
<script>
|
|
</script>
|
|
|
|
# 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<SimpleGitOptions> = {
|
|
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 |