@kmmz1127/wash-git 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +20 -2
- package/lib/api.d.ts +68 -0
- package/lib/git/diff.d.ts +2 -0
- package/lib/git/diff.js +108 -0
- package/lib/git/fs-client.d.ts +3 -0
- package/lib/git/fs-client.js +89 -0
- package/lib/git/git.d.ts +2 -0
- package/lib/git/git.js +518 -0
- package/package.json +39 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mizuto, Kaminakano
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,21 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Wash Git for npm
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
```sh
|
|
4
|
+
npm install @kmmz1127/wash @kmmz1127/wash-git
|
|
5
|
+
```
|
|
6
|
+
|
|
7
|
+
```js
|
|
8
|
+
import { createJustBashShell } from "@kmmz1127/wash";
|
|
9
|
+
import { createGitCommand } from "@kmmz1127/wash-git";
|
|
10
|
+
|
|
11
|
+
const shell = await createJustBashShell({ commands: [createGitCommand()] });
|
|
12
|
+
await shell.exec("git init");
|
|
13
|
+
const { stdout } = await shell.exec("git status");
|
|
14
|
+
console.log(stdout);
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Git operations use the Wash shell's filesystem. See the [command list and limitations](https://github.com/kmmz532/wash-git#supported-commands).
|
|
18
|
+
|
|
19
|
+
## Packaging
|
|
20
|
+
|
|
21
|
+
Run `npm run pack:npm` from the repository root to build the npm tarball. Publish that tarball with `npm publish ./kmmz1127-wash-git-<version>.tgz --access public`.
|
package/lib/api.d.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
export interface WashCommand {
|
|
2
|
+
name: string;
|
|
3
|
+
run(args: string[], ctx: WashCommandContext): Promise<ExecResult>;
|
|
4
|
+
/** 1行の説明。補完候補の一覧に表示する。 */
|
|
5
|
+
description?: string;
|
|
6
|
+
/**
|
|
7
|
+
* 引数の補完候補を返す。args の最後の要素は入力中の単語で、空文字列の場合もある。
|
|
8
|
+
* 候補の引用符付けと区切りの空白はWashが付ける。/ で終わる候補には空白を付けない。
|
|
9
|
+
* エラーまたは1秒以内に応答しない場合、Washはパスの補完に切り替える。
|
|
10
|
+
*/
|
|
11
|
+
complete?(args: string[], ctx: WashCommandContext): Promise<string[]>;
|
|
12
|
+
}
|
|
13
|
+
export interface WashCommandContext {
|
|
14
|
+
/** Washのパス空間のファイルシステム。相対パスは cwd を基準とし、読み取り専用のマウントへの変更を拒否する。 */
|
|
15
|
+
fs: WashFileSystem;
|
|
16
|
+
/** 同じシェルで1行を実行する。cd や export の結果は呼び出し元へ引き継がない。 */
|
|
17
|
+
exec(line: string, options?: {
|
|
18
|
+
stdin?: string;
|
|
19
|
+
signal?: AbortSignal;
|
|
20
|
+
}): Promise<ExecResult>;
|
|
21
|
+
cwd: string;
|
|
22
|
+
env: Record<string, string>;
|
|
23
|
+
/** パイプ・リダイレクトの入力。端末に直接接続されている場合は空。 */
|
|
24
|
+
stdin: string;
|
|
25
|
+
/** 端末に直接接続されている場合の入出力。 */
|
|
26
|
+
terminal?: WashTerminal;
|
|
27
|
+
signal?: AbortSignal;
|
|
28
|
+
}
|
|
29
|
+
export interface ExecResult {
|
|
30
|
+
stdout: string;
|
|
31
|
+
stderr: string;
|
|
32
|
+
exitCode: number;
|
|
33
|
+
}
|
|
34
|
+
export interface WashTerminal {
|
|
35
|
+
/** 1行を読む。改行を含む。EOFでは null を返す。 */
|
|
36
|
+
readLine(): Promise<string | null>;
|
|
37
|
+
write(text: string): void;
|
|
38
|
+
/** 端末の列数。不明な場合は undefined。 */
|
|
39
|
+
readonly columns?: number;
|
|
40
|
+
/** 端末の行数。不明な場合は undefined。 */
|
|
41
|
+
readonly rows?: number;
|
|
42
|
+
}
|
|
43
|
+
export type WashFileType = "file" | "directory";
|
|
44
|
+
export interface WashFileStat {
|
|
45
|
+
type: WashFileType;
|
|
46
|
+
size: number;
|
|
47
|
+
mtime: Date;
|
|
48
|
+
mode?: number;
|
|
49
|
+
identity?: string;
|
|
50
|
+
}
|
|
51
|
+
export type WashFsErrorCode = "ENOENT" | "EEXIST" | "ENOTDIR" | "EISDIR" | "EACCES" | "EROFS" | "ENOTEMPTY" | "EIO";
|
|
52
|
+
/** ファイル操作が投げるエラー。code で原因を判別する。 */
|
|
53
|
+
export interface WashFsError extends Error {
|
|
54
|
+
readonly code: WashFsErrorCode;
|
|
55
|
+
}
|
|
56
|
+
export interface WashFileSystem {
|
|
57
|
+
readonly readOnly?: boolean;
|
|
58
|
+
stat(path: string): Promise<WashFileStat>;
|
|
59
|
+
chmod?(path: string, mode: number): Promise<void>;
|
|
60
|
+
readFile(path: string): Promise<Uint8Array>;
|
|
61
|
+
writeFile(path: string, data: Uint8Array): Promise<void>;
|
|
62
|
+
readDirectory(path: string): Promise<[name: string, type: WashFileType][]>;
|
|
63
|
+
createDirectory(path: string): Promise<void>;
|
|
64
|
+
delete(path: string, options: {
|
|
65
|
+
recursive: boolean;
|
|
66
|
+
}): Promise<void>;
|
|
67
|
+
rename(from: string, to: string): Promise<void>;
|
|
68
|
+
}
|
package/lib/git/diff.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// 行単位の差分を unified 形式で作る。
|
|
2
|
+
const CONTEXT = 3;
|
|
3
|
+
/** これを超える組み合わせの比較は行わず、差分があることだけを示す。 */
|
|
4
|
+
const LIMIT = 4_000_000;
|
|
5
|
+
function splitLines(text) {
|
|
6
|
+
if (text === "")
|
|
7
|
+
return [];
|
|
8
|
+
const lines = text.split("\n");
|
|
9
|
+
if (lines.at(-1) === "")
|
|
10
|
+
lines.pop();
|
|
11
|
+
return lines;
|
|
12
|
+
}
|
|
13
|
+
function edits(a, b) {
|
|
14
|
+
// 先頭と末尾の共通部分を除いてから、最長共通部分列で比較する。
|
|
15
|
+
let start = 0;
|
|
16
|
+
while (start < a.length && start < b.length && a[start] === b[start])
|
|
17
|
+
start++;
|
|
18
|
+
let endA = a.length;
|
|
19
|
+
let endB = b.length;
|
|
20
|
+
while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
|
|
21
|
+
endA--;
|
|
22
|
+
endB--;
|
|
23
|
+
}
|
|
24
|
+
const n = endA - start;
|
|
25
|
+
const m = endB - start;
|
|
26
|
+
if (n * m > LIMIT)
|
|
27
|
+
return undefined;
|
|
28
|
+
const table = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
|
|
29
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
30
|
+
for (let j = m - 1; j >= 0; j--) {
|
|
31
|
+
table[i][j] = a[start + i] === b[start + j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const result = a.slice(0, start).map((text) => ({ kind: " ", text }));
|
|
35
|
+
let i = 0;
|
|
36
|
+
let j = 0;
|
|
37
|
+
while (i < n || j < m) {
|
|
38
|
+
if (i < n && j < m && a[start + i] === b[start + j]) {
|
|
39
|
+
result.push({ kind: " ", text: a[start + i] });
|
|
40
|
+
i++;
|
|
41
|
+
j++;
|
|
42
|
+
}
|
|
43
|
+
else if (i < n && (j >= m || table[i + 1][j] >= table[i][j + 1])) {
|
|
44
|
+
// gitと同じく、置き換えでは削除行を追加行より先に示す。
|
|
45
|
+
result.push({ kind: "-", text: a[start + i++] });
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
result.push({ kind: "+", text: b[start + j++] });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
result.push(...a.slice(endA).map((text) => ({ kind: " ", text })));
|
|
52
|
+
return result;
|
|
53
|
+
}
|
|
54
|
+
function isBinary(bytes) {
|
|
55
|
+
return bytes.subarray(0, 8000).includes(0);
|
|
56
|
+
}
|
|
57
|
+
/** 2つの内容の差分を返す。old・next が undefined の場合は、ファイルの追加・削除として扱う。 */
|
|
58
|
+
export function unifiedDiff(path, old, next) {
|
|
59
|
+
const header = [`diff --git a/${path} b/${path}`];
|
|
60
|
+
if (!old)
|
|
61
|
+
header.push("new file mode 100644");
|
|
62
|
+
if (!next)
|
|
63
|
+
header.push("deleted file mode 100644");
|
|
64
|
+
if ((old && isBinary(old)) || (next && isBinary(next)))
|
|
65
|
+
return [...header, `Binary files ${old ? "a/" + path : "/dev/null"} and ${next ? "b/" + path : "/dev/null"} differ`, ""].join("\n");
|
|
66
|
+
const decoder = new TextDecoder();
|
|
67
|
+
const a = splitLines(old ? decoder.decode(old) : "");
|
|
68
|
+
const b = splitLines(next ? decoder.decode(next) : "");
|
|
69
|
+
const list = edits(a, b);
|
|
70
|
+
header.push(`--- ${old ? "a/" + path : "/dev/null"}`, `+++ ${next ? "b/" + path : "/dev/null"}`);
|
|
71
|
+
if (!list)
|
|
72
|
+
return [...header, "@@ the files are too large to compare @@", ""].join("\n");
|
|
73
|
+
const lines = [...header];
|
|
74
|
+
let index = 0;
|
|
75
|
+
while (index < list.length) {
|
|
76
|
+
while (index < list.length && list[index].kind === " ")
|
|
77
|
+
index++;
|
|
78
|
+
if (index >= list.length)
|
|
79
|
+
break;
|
|
80
|
+
// 変更の前後 CONTEXT 行を含め、近い変更は1つの塊にまとめる。
|
|
81
|
+
const first = Math.max(0, index - CONTEXT);
|
|
82
|
+
let last = index;
|
|
83
|
+
let scan = index;
|
|
84
|
+
while (scan < list.length) {
|
|
85
|
+
if (list[scan].kind !== " ")
|
|
86
|
+
last = scan;
|
|
87
|
+
else if (scan - last > CONTEXT * 2)
|
|
88
|
+
break;
|
|
89
|
+
scan++;
|
|
90
|
+
}
|
|
91
|
+
const end = Math.min(list.length, last + CONTEXT + 1);
|
|
92
|
+
let oldStart = 1;
|
|
93
|
+
let newStart = 1;
|
|
94
|
+
for (let k = 0; k < first; k++) {
|
|
95
|
+
if (list[k].kind !== "+")
|
|
96
|
+
oldStart++;
|
|
97
|
+
if (list[k].kind !== "-")
|
|
98
|
+
newStart++;
|
|
99
|
+
}
|
|
100
|
+
const hunk = list.slice(first, end);
|
|
101
|
+
const oldCount = hunk.filter((edit) => edit.kind !== "+").length;
|
|
102
|
+
const newCount = hunk.filter((edit) => edit.kind !== "-").length;
|
|
103
|
+
lines.push(`@@ -${oldCount === 0 ? oldStart - 1 : oldStart},${oldCount} +${newCount === 0 ? newStart - 1 : newStart},${newCount} @@`);
|
|
104
|
+
lines.push(...hunk.map((edit) => edit.kind + edit.text));
|
|
105
|
+
index = end;
|
|
106
|
+
}
|
|
107
|
+
return lines.join("\n") + "\n";
|
|
108
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
const encoder = new TextEncoder();
|
|
2
|
+
const decoder = new TextDecoder();
|
|
3
|
+
function withCode(code, path) {
|
|
4
|
+
return Object.assign(new Error(`${code}: ${path}`), { code });
|
|
5
|
+
}
|
|
6
|
+
/** isomorphic-gitが渡す "/repo/." などのパスを正規化する。 */
|
|
7
|
+
function normalize(path) {
|
|
8
|
+
const parts = [];
|
|
9
|
+
for (const part of path.split("/")) {
|
|
10
|
+
if (part === "" || part === ".")
|
|
11
|
+
continue;
|
|
12
|
+
if (part === "..")
|
|
13
|
+
parts.pop();
|
|
14
|
+
else
|
|
15
|
+
parts.push(part);
|
|
16
|
+
}
|
|
17
|
+
return "/" + parts.join("/");
|
|
18
|
+
}
|
|
19
|
+
export function createFsClient(raw) {
|
|
20
|
+
const fs = {
|
|
21
|
+
readOnly: raw.readOnly,
|
|
22
|
+
stat: (path) => raw.stat(normalize(path)),
|
|
23
|
+
chmod: raw.chmod && ((path, mode) => raw.chmod(normalize(path), mode)),
|
|
24
|
+
readFile: (path) => raw.readFile(normalize(path)),
|
|
25
|
+
writeFile: (path, data) => raw.writeFile(normalize(path), data),
|
|
26
|
+
readDirectory: (path) => raw.readDirectory(normalize(path)),
|
|
27
|
+
createDirectory: (path) => raw.createDirectory(normalize(path)),
|
|
28
|
+
delete: (path, options) => raw.delete(normalize(path), options),
|
|
29
|
+
rename: (from, to) => raw.rename(normalize(from), normalize(to)),
|
|
30
|
+
};
|
|
31
|
+
const stat = async (path) => {
|
|
32
|
+
const entry = await fs.stat(path);
|
|
33
|
+
const directory = entry.type === "directory";
|
|
34
|
+
const mtimeMs = entry.mtime.getTime();
|
|
35
|
+
return {
|
|
36
|
+
type: directory ? "dir" : "file",
|
|
37
|
+
mode: directory ? 0o40755 : (entry.mode ?? 0o100644) | 0o100000,
|
|
38
|
+
size: entry.size,
|
|
39
|
+
ino: 0,
|
|
40
|
+
mtimeMs,
|
|
41
|
+
ctimeMs: mtimeMs,
|
|
42
|
+
uid: 1,
|
|
43
|
+
gid: 1,
|
|
44
|
+
dev: 1,
|
|
45
|
+
isFile: () => !directory,
|
|
46
|
+
isDirectory: () => directory,
|
|
47
|
+
isSymbolicLink: () => false,
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
return {
|
|
51
|
+
promises: {
|
|
52
|
+
async readFile(path, options) {
|
|
53
|
+
const bytes = await fs.readFile(path);
|
|
54
|
+
const encoding = typeof options === "string" ? options : options?.encoding;
|
|
55
|
+
return encoding ? decoder.decode(bytes) : bytes;
|
|
56
|
+
},
|
|
57
|
+
async writeFile(path, data) {
|
|
58
|
+
await fs.writeFile(path, typeof data === "string" ? encoder.encode(data) : data);
|
|
59
|
+
},
|
|
60
|
+
async unlink(path) {
|
|
61
|
+
await fs.delete(path, { recursive: false });
|
|
62
|
+
},
|
|
63
|
+
async readdir(path) {
|
|
64
|
+
return (await fs.readDirectory(path)).map(([name]) => name);
|
|
65
|
+
},
|
|
66
|
+
async mkdir(path) {
|
|
67
|
+
// isomorphic-gitは、既に存在する場合の EEXIST を前提に処理する。
|
|
68
|
+
const exists = await fs.stat(path).then(() => true, () => false);
|
|
69
|
+
if (exists)
|
|
70
|
+
throw withCode("EEXIST", path);
|
|
71
|
+
await fs.createDirectory(path);
|
|
72
|
+
},
|
|
73
|
+
async rmdir(path) {
|
|
74
|
+
await fs.delete(path, { recursive: false });
|
|
75
|
+
},
|
|
76
|
+
stat,
|
|
77
|
+
lstat: stat,
|
|
78
|
+
async readlink(path) {
|
|
79
|
+
throw withCode("ENOENT", path);
|
|
80
|
+
},
|
|
81
|
+
async symlink(_target, path) {
|
|
82
|
+
throw withCode("EACCES", path);
|
|
83
|
+
},
|
|
84
|
+
async chmod(path, mode) {
|
|
85
|
+
await fs.chmod?.(path, mode & 0o777);
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
package/lib/git/git.d.ts
ADDED
package/lib/git/git.js
ADDED
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
// git コマンド。WashApiのコマンドの型だけを利用し、VS Codeの実行時APIには依存しない。
|
|
2
|
+
import git, { STAGE, TREE } from "isomorphic-git";
|
|
3
|
+
import { unifiedDiff } from "./diff.js";
|
|
4
|
+
import { createFsClient } from "./fs-client.js";
|
|
5
|
+
const USAGE = `usage: git <command> [<args>]
|
|
6
|
+
|
|
7
|
+
Supported commands:
|
|
8
|
+
init Create an empty Git repository
|
|
9
|
+
status Show the working tree status
|
|
10
|
+
add Add file contents to the index
|
|
11
|
+
rm Remove files from the working tree and from the index
|
|
12
|
+
restore Restore working tree files, or unstage with --staged
|
|
13
|
+
reset Unstage files
|
|
14
|
+
commit Record changes to the repository
|
|
15
|
+
log Show commit logs
|
|
16
|
+
diff Show changes between the index and the working tree, or with --cached
|
|
17
|
+
branch List, create, or delete branches
|
|
18
|
+
switch Switch branches
|
|
19
|
+
checkout Switch branches
|
|
20
|
+
config Get and set repository options
|
|
21
|
+
|
|
22
|
+
Remote operations (clone, fetch, pull, push) are not supported.
|
|
23
|
+
`;
|
|
24
|
+
const COMMANDS = ["init", "status", "add", "rm", "restore", "reset", "commit", "log", "diff", "branch", "switch", "checkout", "config", "help", "version"];
|
|
25
|
+
class GitError extends Error {
|
|
26
|
+
exitCode;
|
|
27
|
+
constructor(message, exitCode = 128) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.exitCode = exitCode;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function createGitCommand() {
|
|
33
|
+
return {
|
|
34
|
+
name: "git",
|
|
35
|
+
description: "Version control for local repositories",
|
|
36
|
+
run: (args, ctx) => runGit(args, ctx),
|
|
37
|
+
async complete(args, ctx) {
|
|
38
|
+
const current = args.at(-1) ?? "";
|
|
39
|
+
if (args.length === 1)
|
|
40
|
+
return COMMANDS.filter((name) => name.startsWith(current));
|
|
41
|
+
if (["switch", "checkout", "branch"].includes(args[0]) && !current.startsWith("-")) {
|
|
42
|
+
try {
|
|
43
|
+
const repo = await openRepo(ctx);
|
|
44
|
+
return (await git.listBranches({ fs: repo.fs, dir: repo.dir })).filter((name) => name.startsWith(current));
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
throw new Error("use path completion");
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function normalize(path) {
|
|
55
|
+
const parts = [];
|
|
56
|
+
for (const part of path.split("/")) {
|
|
57
|
+
if (part === "" || part === ".")
|
|
58
|
+
continue;
|
|
59
|
+
if (part === "..")
|
|
60
|
+
parts.pop();
|
|
61
|
+
else
|
|
62
|
+
parts.push(part);
|
|
63
|
+
}
|
|
64
|
+
return "/" + parts.join("/");
|
|
65
|
+
}
|
|
66
|
+
function absolute(ctx, path) {
|
|
67
|
+
return normalize(path.startsWith("/") ? path : `${ctx.cwd}/${path}`);
|
|
68
|
+
}
|
|
69
|
+
async function openRepo(ctx) {
|
|
70
|
+
const fs = createFsClient(ctx.fs);
|
|
71
|
+
let dir;
|
|
72
|
+
try {
|
|
73
|
+
dir = await git.findRoot({ fs, filepath: absolute(ctx, ".") });
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
throw new GitError("fatal: not a git repository (or any of the parent directories): .git");
|
|
77
|
+
}
|
|
78
|
+
const cwd = absolute(ctx, ".");
|
|
79
|
+
const relative = (path) => {
|
|
80
|
+
const full = absolute(ctx, path);
|
|
81
|
+
if (full === dir)
|
|
82
|
+
return ".";
|
|
83
|
+
if (!full.startsWith(dir === "/" ? "/" : dir + "/"))
|
|
84
|
+
throw new GitError(`fatal: ${path}: '${path}' is outside repository at '${dir}'`);
|
|
85
|
+
return full.slice(dir === "/" ? 1 : dir.length + 1);
|
|
86
|
+
};
|
|
87
|
+
const display = (path) => {
|
|
88
|
+
const full = normalize(`${dir}/${path}`);
|
|
89
|
+
const base = cwd === "/" ? "" : cwd;
|
|
90
|
+
if (full.startsWith(base + "/"))
|
|
91
|
+
return full.slice(base.length + 1);
|
|
92
|
+
// cwd より上のファイルは ../ を付けて示す。
|
|
93
|
+
const from = base.split("/").filter(Boolean);
|
|
94
|
+
const to = full.split("/").filter(Boolean);
|
|
95
|
+
let common = 0;
|
|
96
|
+
while (common < from.length && common < to.length && from[common] === to[common])
|
|
97
|
+
common++;
|
|
98
|
+
return [...Array(from.length - common).fill(".."), ...to.slice(common)].join("/");
|
|
99
|
+
};
|
|
100
|
+
return { fs, dir, relative, display };
|
|
101
|
+
}
|
|
102
|
+
async function runGit(args, ctx) {
|
|
103
|
+
const [command, ...rest] = args;
|
|
104
|
+
try {
|
|
105
|
+
switch (command) {
|
|
106
|
+
case undefined:
|
|
107
|
+
case "help":
|
|
108
|
+
case "--help":
|
|
109
|
+
case "-h":
|
|
110
|
+
return { stdout: USAGE, stderr: "", exitCode: command === undefined ? 1 : 0 };
|
|
111
|
+
case "version":
|
|
112
|
+
case "--version":
|
|
113
|
+
return { stdout: `git version isomorphic-git ${git.version()} (wash-git)\n`, stderr: "", exitCode: 0 };
|
|
114
|
+
case "init":
|
|
115
|
+
return await init(rest, ctx);
|
|
116
|
+
case "clone":
|
|
117
|
+
case "fetch":
|
|
118
|
+
case "pull":
|
|
119
|
+
case "push":
|
|
120
|
+
case "remote":
|
|
121
|
+
throw new GitError(`git: '${command}' is not supported in Wash. Use the Source Control view or GitHub for remote operations.`, 1);
|
|
122
|
+
}
|
|
123
|
+
const repo = await openRepo(ctx);
|
|
124
|
+
switch (command) {
|
|
125
|
+
case "status": return await status(rest, repo);
|
|
126
|
+
case "add": return await add(rest, repo);
|
|
127
|
+
case "rm": return await rm(rest, repo);
|
|
128
|
+
case "restore": return await restore(rest, repo);
|
|
129
|
+
case "reset": return await reset(rest, repo);
|
|
130
|
+
case "commit": return await commit(rest, repo, ctx);
|
|
131
|
+
case "log": return await log(rest, repo);
|
|
132
|
+
case "diff": return await diff(rest, repo);
|
|
133
|
+
case "branch": return await branch(rest, repo);
|
|
134
|
+
case "switch":
|
|
135
|
+
case "checkout": return await checkout(command, rest, repo);
|
|
136
|
+
case "config": return await config(rest, repo);
|
|
137
|
+
default:
|
|
138
|
+
throw new GitError(`git: '${command}' is not a git command. See 'git help'.`, 1);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
if (error instanceof GitError)
|
|
143
|
+
return { stdout: "", stderr: error.message + "\n", exitCode: error.exitCode };
|
|
144
|
+
return { stdout: "", stderr: `fatal: ${error instanceof Error ? error.message : String(error)}\n`, exitCode: 128 };
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function ok(stdout = "") {
|
|
148
|
+
return { stdout, stderr: "", exitCode: 0 };
|
|
149
|
+
}
|
|
150
|
+
/** -m などの値を取るオプションと、それ以外の引数を分ける。 */
|
|
151
|
+
function parse(args, withValue = []) {
|
|
152
|
+
const flags = new Set();
|
|
153
|
+
const values = new Map();
|
|
154
|
+
const rest = [];
|
|
155
|
+
for (let index = 0; index < args.length; index++) {
|
|
156
|
+
const arg = args[index];
|
|
157
|
+
if (arg === "--") {
|
|
158
|
+
rest.push(...args.slice(index + 1));
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
const equals = arg.startsWith("--") ? arg.indexOf("=") : -1;
|
|
162
|
+
const name = equals > 0 ? arg.slice(0, equals) : arg;
|
|
163
|
+
if (withValue.includes(name)) {
|
|
164
|
+
const value = equals > 0 ? arg.slice(equals + 1) : args[++index];
|
|
165
|
+
if (value === undefined)
|
|
166
|
+
throw new GitError(`error: switch '${name.replace(/^-+/, "")}' requires a value`, 129);
|
|
167
|
+
values.set(name, [...(values.get(name) ?? []), value]);
|
|
168
|
+
}
|
|
169
|
+
else if (/^-[a-zA-Z]{2,}$/.test(arg)) {
|
|
170
|
+
for (const char of arg.slice(1))
|
|
171
|
+
flags.add("-" + char);
|
|
172
|
+
}
|
|
173
|
+
else if (arg.startsWith("-") && arg !== "-") {
|
|
174
|
+
flags.add(arg);
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
rest.push(arg);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return { flags, values, rest };
|
|
181
|
+
}
|
|
182
|
+
async function init(args, ctx) {
|
|
183
|
+
const { values, rest } = parse(args, ["-b", "--initial-branch"]);
|
|
184
|
+
const dir = absolute(ctx, rest[0] ?? ".");
|
|
185
|
+
const fs = createFsClient(ctx.fs);
|
|
186
|
+
const existed = await ctx.fs.stat(`${dir}/.git`).then(() => true, () => false);
|
|
187
|
+
await ctx.fs.createDirectory(dir);
|
|
188
|
+
const defaultBranch = values.get("-b")?.[0] ?? values.get("--initial-branch")?.[0] ?? "main";
|
|
189
|
+
await git.init({ fs, dir, defaultBranch });
|
|
190
|
+
return ok(`${existed ? "Reinitialized existing" : "Initialized empty"} Git repository in ${dir === "/" ? "" : dir}/.git/\n`);
|
|
191
|
+
}
|
|
192
|
+
async function matrix(repo, filepaths) {
|
|
193
|
+
return await git.statusMatrix({ fs: repo.fs, dir: repo.dir, filepaths });
|
|
194
|
+
}
|
|
195
|
+
/** statusMatrix の1行を、git status --short の2文字に変換する。 */
|
|
196
|
+
function shortCode([, head, workdir, stage]) {
|
|
197
|
+
if (head === 0 && workdir === 2 && stage === 0)
|
|
198
|
+
return "??";
|
|
199
|
+
const index = head === 0 ? (stage === 0 ? " " : "A") : stage === 0 ? "D" : stage === 1 ? " " : "M";
|
|
200
|
+
let tree = " ";
|
|
201
|
+
if (workdir === 0)
|
|
202
|
+
tree = stage === 0 ? " " : "D";
|
|
203
|
+
else if (stage === 0)
|
|
204
|
+
tree = " ";
|
|
205
|
+
else if (stage === 1 ? workdir === 2 : stage === 2 ? workdir === 1 : workdir !== 2 || stage === 3)
|
|
206
|
+
tree = "M";
|
|
207
|
+
return index + tree;
|
|
208
|
+
}
|
|
209
|
+
async function currentBranch(repo) {
|
|
210
|
+
return (await git.currentBranch({ fs: repo.fs, dir: repo.dir })) ?? undefined;
|
|
211
|
+
}
|
|
212
|
+
async function hasCommits(repo) {
|
|
213
|
+
return git.resolveRef({ fs: repo.fs, dir: repo.dir, ref: "HEAD" }).then(() => true, () => false);
|
|
214
|
+
}
|
|
215
|
+
async function status(args, repo) {
|
|
216
|
+
const { flags } = parse(args);
|
|
217
|
+
const rows = (await matrix(repo)).map((row) => [row, shortCode(row)]).filter(([, code]) => code !== " ");
|
|
218
|
+
if (flags.has("-s") || flags.has("--short") || flags.has("--porcelain")) {
|
|
219
|
+
return ok(rows.map(([row, code]) => `${code} ${repo.display(row[0])}\n`).join(""));
|
|
220
|
+
}
|
|
221
|
+
const branch = await currentBranch(repo);
|
|
222
|
+
const lines = [branch ? `On branch ${branch}` : "HEAD detached"];
|
|
223
|
+
if (!(await hasCommits(repo)))
|
|
224
|
+
lines.push("", "No commits yet");
|
|
225
|
+
const staged = rows.filter(([, code]) => code !== "??" && code[0] !== " ");
|
|
226
|
+
const unstaged = rows.filter(([, code]) => code !== "??" && code[1] !== " ");
|
|
227
|
+
const untracked = rows.filter(([, code]) => code === "??");
|
|
228
|
+
const label = (char) => char === "A" ? "new file: " : char === "D" ? "deleted: " : "modified: ";
|
|
229
|
+
if (staged.length > 0) {
|
|
230
|
+
lines.push("", "Changes to be committed:", ' (use "git restore --staged <file>..." to unstage)');
|
|
231
|
+
lines.push(...staged.map(([row, code]) => `\t${label(code[0])}${repo.display(row[0])}`));
|
|
232
|
+
}
|
|
233
|
+
if (unstaged.length > 0) {
|
|
234
|
+
lines.push("", "Changes not staged for commit:", ' (use "git add <file>..." to update what will be committed)', ' (use "git restore <file>..." to discard changes in working directory)');
|
|
235
|
+
lines.push(...unstaged.map(([row, code]) => `\t${label(code[1])}${repo.display(row[0])}`));
|
|
236
|
+
}
|
|
237
|
+
if (untracked.length > 0) {
|
|
238
|
+
lines.push("", "Untracked files:", ' (use "git add <file>..." to include in what will be committed)');
|
|
239
|
+
lines.push(...untracked.map(([row]) => `\t${repo.display(row[0])}`));
|
|
240
|
+
}
|
|
241
|
+
if (rows.length === 0)
|
|
242
|
+
lines.push((await hasCommits(repo)) ? "nothing to commit, working tree clean" : "\nnothing to commit (create/copy files and use \"git add\" to track)");
|
|
243
|
+
else if (staged.length === 0)
|
|
244
|
+
lines.push("", 'no changes added to commit (use "git add" and/or "git commit -a")');
|
|
245
|
+
return ok(lines.join("\n") + "\n");
|
|
246
|
+
}
|
|
247
|
+
/** 引数のパスに一致する statusMatrix の行。"." やディレクトリはその配下すべてに一致する。 */
|
|
248
|
+
async function matching(repo, paths) {
|
|
249
|
+
const prefixes = paths.map(repo.relative);
|
|
250
|
+
const rows = await matrix(repo);
|
|
251
|
+
const matched = rows.filter(([file]) => prefixes.some((prefix) => prefix === "." || file === prefix || file.startsWith(prefix + "/")));
|
|
252
|
+
for (const [index, prefix] of prefixes.entries()) {
|
|
253
|
+
if (!matched.some(([file]) => prefix === "." || file === prefix || file.startsWith(prefix + "/"))) {
|
|
254
|
+
throw new GitError(`fatal: pathspec '${paths[index]}' did not match any files`);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return matched;
|
|
258
|
+
}
|
|
259
|
+
async function add(args, repo) {
|
|
260
|
+
const { flags, rest } = parse(args);
|
|
261
|
+
const paths = flags.has("-A") || flags.has("--all") ? ["/" + repo.dir.replace(/^\//, "")] : rest;
|
|
262
|
+
if (paths.length === 0)
|
|
263
|
+
return { stdout: "", stderr: "Nothing specified, nothing added.\nhint: Maybe you wanted to say 'git add .'?\n", exitCode: 0 };
|
|
264
|
+
for (const [file, , workdir] of await matching(repo, paths)) {
|
|
265
|
+
if (workdir === 0)
|
|
266
|
+
await git.remove({ fs: repo.fs, dir: repo.dir, filepath: file });
|
|
267
|
+
else
|
|
268
|
+
await git.add({ fs: repo.fs, dir: repo.dir, filepath: file });
|
|
269
|
+
}
|
|
270
|
+
return ok();
|
|
271
|
+
}
|
|
272
|
+
async function rm(args, repo) {
|
|
273
|
+
const { flags, rest } = parse(args);
|
|
274
|
+
if (rest.length === 0)
|
|
275
|
+
throw new GitError("usage: git rm [--cached] [-r] <file>...", 129);
|
|
276
|
+
const cached = flags.has("--cached");
|
|
277
|
+
const recursive = flags.has("-r");
|
|
278
|
+
const lines = [];
|
|
279
|
+
for (const path of rest) {
|
|
280
|
+
const prefix = repo.relative(path);
|
|
281
|
+
const files = (await git.listFiles({ fs: repo.fs, dir: repo.dir })).filter((file) => file === prefix || (recursive && file.startsWith(prefix + "/")));
|
|
282
|
+
if (files.length === 0) {
|
|
283
|
+
const directory = (await git.listFiles({ fs: repo.fs, dir: repo.dir })).some((file) => file.startsWith(prefix + "/"));
|
|
284
|
+
throw new GitError(directory ? `fatal: not removing '${path}' recursively without -r` : `fatal: pathspec '${path}' did not match any files`);
|
|
285
|
+
}
|
|
286
|
+
for (const file of files) {
|
|
287
|
+
await git.remove({ fs: repo.fs, dir: repo.dir, filepath: file });
|
|
288
|
+
if (!cached)
|
|
289
|
+
await repo.fs.promises.unlink(`${repo.dir}/${file}`).catch(() => { });
|
|
290
|
+
lines.push(`rm '${file}'\n`);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
return ok(lines.join(""));
|
|
294
|
+
}
|
|
295
|
+
async function unstage(repo, paths) {
|
|
296
|
+
const files = paths.length === 0 ? (await matrix(repo)).map(([file]) => file) : (await matching(repo, paths)).map(([file]) => file);
|
|
297
|
+
for (const file of files)
|
|
298
|
+
await git.resetIndex({ fs: repo.fs, dir: repo.dir, filepath: file });
|
|
299
|
+
}
|
|
300
|
+
async function restore(args, repo) {
|
|
301
|
+
const { flags, rest } = parse(args);
|
|
302
|
+
if (rest.length === 0)
|
|
303
|
+
throw new GitError("fatal: you must specify path(s) to restore");
|
|
304
|
+
if (flags.has("--staged") || flags.has("-S")) {
|
|
305
|
+
await unstage(repo, rest);
|
|
306
|
+
if (!flags.has("--worktree") && !flags.has("-W"))
|
|
307
|
+
return ok();
|
|
308
|
+
}
|
|
309
|
+
const files = (await matching(repo, rest)).filter(([, head, , stage]) => head === 1 || stage !== 0).map(([file]) => file);
|
|
310
|
+
if (files.length > 0)
|
|
311
|
+
await git.checkout({ fs: repo.fs, dir: repo.dir, filepaths: files, force: true });
|
|
312
|
+
return ok();
|
|
313
|
+
}
|
|
314
|
+
async function reset(args, repo) {
|
|
315
|
+
const { flags, rest } = parse(args);
|
|
316
|
+
if (flags.has("--hard") || flags.has("--soft"))
|
|
317
|
+
throw new GitError("fatal: only 'git reset [<path>...]' is supported", 1);
|
|
318
|
+
await unstage(repo, rest.filter((arg) => arg !== "HEAD"));
|
|
319
|
+
return ok();
|
|
320
|
+
}
|
|
321
|
+
async function author(repo, ctx) {
|
|
322
|
+
const name = ctx.env.GIT_AUTHOR_NAME || await git.getConfig({ fs: repo.fs, dir: repo.dir, path: "user.name" });
|
|
323
|
+
const email = ctx.env.GIT_AUTHOR_EMAIL || await git.getConfig({ fs: repo.fs, dir: repo.dir, path: "user.email" });
|
|
324
|
+
if (!name || !email) {
|
|
325
|
+
throw new GitError(`Author identity unknown
|
|
326
|
+
|
|
327
|
+
*** Please tell me who you are.
|
|
328
|
+
|
|
329
|
+
Run
|
|
330
|
+
|
|
331
|
+
git config user.email "you@example.com"
|
|
332
|
+
git config user.name "Your Name"
|
|
333
|
+
|
|
334
|
+
to set your identity for this repository.
|
|
335
|
+
|
|
336
|
+
fatal: unable to auto-detect email address`);
|
|
337
|
+
}
|
|
338
|
+
return { name, email };
|
|
339
|
+
}
|
|
340
|
+
async function commit(args, repo, ctx) {
|
|
341
|
+
const { flags, values } = parse(args, ["-m", "--message"]);
|
|
342
|
+
const messages = [...(values.get("-m") ?? []), ...(values.get("--message") ?? [])];
|
|
343
|
+
if (messages.length === 0)
|
|
344
|
+
throw new GitError("error: a commit message is required. Use git commit -m <message>.", 1);
|
|
345
|
+
if (flags.has("-a") || flags.has("--all")) {
|
|
346
|
+
for (const [file, head, workdir] of await matrix(repo)) {
|
|
347
|
+
if (head === 0)
|
|
348
|
+
continue;
|
|
349
|
+
if (workdir === 0)
|
|
350
|
+
await git.remove({ fs: repo.fs, dir: repo.dir, filepath: file });
|
|
351
|
+
else
|
|
352
|
+
await git.add({ fs: repo.fs, dir: repo.dir, filepath: file });
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
const rows = await matrix(repo);
|
|
356
|
+
const changed = rows.filter((row) => shortCode(row)[0] !== " " && shortCode(row) !== "??");
|
|
357
|
+
if (changed.length === 0 && !flags.has("--allow-empty")) {
|
|
358
|
+
const result = await status([], repo);
|
|
359
|
+
return { stdout: result.stdout, stderr: "", exitCode: 1 };
|
|
360
|
+
}
|
|
361
|
+
const message = messages.join("\n\n");
|
|
362
|
+
const identity = await author(repo, ctx);
|
|
363
|
+
const root = !(await hasCommits(repo));
|
|
364
|
+
const oid = await git.commit({ fs: repo.fs, dir: repo.dir, message, author: identity });
|
|
365
|
+
const branch = (await currentBranch(repo)) ?? "HEAD";
|
|
366
|
+
const summary = `${changed.length} file${changed.length === 1 ? "" : "s"} changed`;
|
|
367
|
+
return ok(`[${branch}${root ? " (root-commit)" : ""} ${oid.slice(0, 7)}] ${message.split("\n")[0]}\n ${summary}\n`);
|
|
368
|
+
}
|
|
369
|
+
function formatDate(timestamp, offset) {
|
|
370
|
+
// isomorphic-gitの timezoneOffset は分単位で、UTCより東が負になる。
|
|
371
|
+
const date = new Date((timestamp - offset * 60) * 1000);
|
|
372
|
+
const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
|
373
|
+
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
374
|
+
const pad = (value) => String(value).padStart(2, "0");
|
|
375
|
+
const sign = offset <= 0 ? "+" : "-";
|
|
376
|
+
const zone = `${sign}${pad(Math.floor(Math.abs(offset) / 60))}${pad(Math.abs(offset) % 60)}`;
|
|
377
|
+
return `${days[date.getUTCDay()]} ${months[date.getUTCMonth()]} ${date.getUTCDate()} ${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())} ${date.getUTCFullYear()} ${zone}`;
|
|
378
|
+
}
|
|
379
|
+
async function log(args, repo) {
|
|
380
|
+
const { flags, values, rest } = parse(args, ["-n", "--max-count"]);
|
|
381
|
+
let depth = Number(values.get("-n")?.[0] ?? values.get("--max-count")?.[0] ?? NaN);
|
|
382
|
+
for (const flag of flags)
|
|
383
|
+
if (/^-\d+$/.test(flag))
|
|
384
|
+
depth = Number(flag.slice(1));
|
|
385
|
+
if (!(await hasCommits(repo))) {
|
|
386
|
+
throw new GitError(`fatal: your current branch '${(await currentBranch(repo)) ?? "HEAD"}' does not have any commits yet`);
|
|
387
|
+
}
|
|
388
|
+
const commits = await git.log({ fs: repo.fs, dir: repo.dir, ref: rest[0] ?? "HEAD", depth: Number.isFinite(depth) ? depth : undefined });
|
|
389
|
+
if (flags.has("--oneline")) {
|
|
390
|
+
return ok(commits.map(({ oid, commit: entry }) => `${oid.slice(0, 7)} ${entry.message.split("\n")[0]}\n`).join(""));
|
|
391
|
+
}
|
|
392
|
+
return ok(commits.map(({ oid, commit: entry }) => [
|
|
393
|
+
`commit ${oid}`,
|
|
394
|
+
`Author: ${entry.author.name} <${entry.author.email}>`,
|
|
395
|
+
`Date: ${formatDate(entry.author.timestamp, entry.author.timezoneOffset)}`,
|
|
396
|
+
"",
|
|
397
|
+
...entry.message.replace(/\n$/, "").split("\n").map((line) => " " + line),
|
|
398
|
+
"",
|
|
399
|
+
].join("\n")).join("\n"));
|
|
400
|
+
}
|
|
401
|
+
/** HEADまたはインデックスにある各ファイルの blob の oid。 */
|
|
402
|
+
async function blobs(repo, walker) {
|
|
403
|
+
const result = new Map();
|
|
404
|
+
await git.walk({
|
|
405
|
+
fs: repo.fs,
|
|
406
|
+
dir: repo.dir,
|
|
407
|
+
trees: [walker],
|
|
408
|
+
map: async (filepath, [entry]) => {
|
|
409
|
+
if (!entry || filepath === ".")
|
|
410
|
+
return true;
|
|
411
|
+
if ((await entry.type()) === "blob")
|
|
412
|
+
result.set(filepath, await entry.oid());
|
|
413
|
+
return true;
|
|
414
|
+
},
|
|
415
|
+
});
|
|
416
|
+
return result;
|
|
417
|
+
}
|
|
418
|
+
async function diff(args, repo) {
|
|
419
|
+
const { flags, rest } = parse(args);
|
|
420
|
+
const cached = flags.has("--cached") || flags.has("--staged");
|
|
421
|
+
const rows = rest.length > 0 ? await matching(repo, rest) : await matrix(repo);
|
|
422
|
+
const read = async (oid) => oid ? (await git.readBlob({ fs: repo.fs, dir: repo.dir, oid })).blob : undefined;
|
|
423
|
+
const index = await blobs(repo, STAGE());
|
|
424
|
+
const head = cached && await hasCommits(repo) ? await blobs(repo, TREE({ ref: "HEAD" })) : new Map();
|
|
425
|
+
const output = [];
|
|
426
|
+
for (const row of rows) {
|
|
427
|
+
const code = shortCode(row);
|
|
428
|
+
const [file] = row;
|
|
429
|
+
if (cached) {
|
|
430
|
+
if (code[0] === " " || code === "??")
|
|
431
|
+
continue;
|
|
432
|
+
output.push(unifiedDiff(file, await read(head.get(file)), await read(index.get(file))));
|
|
433
|
+
}
|
|
434
|
+
else {
|
|
435
|
+
if (code[1] === " " || code === "??")
|
|
436
|
+
continue;
|
|
437
|
+
const next = row[2] === 0 ? undefined : new Uint8Array(await repo.fs.promises.readFile(`${repo.dir}/${file}`));
|
|
438
|
+
output.push(unifiedDiff(file, await read(index.get(file)), next));
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return ok(output.join(""));
|
|
442
|
+
}
|
|
443
|
+
async function branch(args, repo) {
|
|
444
|
+
const { flags, rest } = parse(args);
|
|
445
|
+
if (flags.has("-d") || flags.has("-D") || flags.has("--delete")) {
|
|
446
|
+
if (rest.length === 0)
|
|
447
|
+
throw new GitError("fatal: branch name required");
|
|
448
|
+
const current = await currentBranch(repo);
|
|
449
|
+
const lines = [];
|
|
450
|
+
for (const name of rest) {
|
|
451
|
+
if (name === current)
|
|
452
|
+
throw new GitError(`error: cannot delete branch '${name}' used by worktree`, 1);
|
|
453
|
+
const oid = await git.resolveRef({ fs: repo.fs, dir: repo.dir, ref: name }).catch(() => undefined);
|
|
454
|
+
if (!oid)
|
|
455
|
+
throw new GitError(`error: branch '${name}' not found`, 1);
|
|
456
|
+
await git.deleteBranch({ fs: repo.fs, dir: repo.dir, ref: name });
|
|
457
|
+
lines.push(`Deleted branch ${name} (was ${oid.slice(0, 7)}).\n`);
|
|
458
|
+
}
|
|
459
|
+
return ok(lines.join(""));
|
|
460
|
+
}
|
|
461
|
+
if (rest.length > 0) {
|
|
462
|
+
if (!(await hasCommits(repo)))
|
|
463
|
+
throw new GitError(`fatal: not a valid object name: '${(await currentBranch(repo)) ?? "HEAD"}'`);
|
|
464
|
+
await git.branch({ fs: repo.fs, dir: repo.dir, ref: rest[0], object: rest[1] });
|
|
465
|
+
return ok();
|
|
466
|
+
}
|
|
467
|
+
const current = await currentBranch(repo);
|
|
468
|
+
const names = await git.listBranches({ fs: repo.fs, dir: repo.dir });
|
|
469
|
+
return ok(names.map((name) => `${name === current ? "*" : " "} ${name}\n`).join(""));
|
|
470
|
+
}
|
|
471
|
+
async function checkout(command, args, repo) {
|
|
472
|
+
const create = command === "switch" ? ["-c", "--create"] : ["-b"];
|
|
473
|
+
const { values, rest } = parse(args, create);
|
|
474
|
+
const created = create.map((flag) => values.get(flag)?.[0]).find(Boolean);
|
|
475
|
+
if (created) {
|
|
476
|
+
await git.branch({ fs: repo.fs, dir: repo.dir, ref: created, object: rest[0], checkout: true });
|
|
477
|
+
return { stdout: "", stderr: `Switched to a new branch '${created}'\n`, exitCode: 0 };
|
|
478
|
+
}
|
|
479
|
+
const [target, ...paths] = rest;
|
|
480
|
+
if (!target)
|
|
481
|
+
throw new GitError(command === "switch" ? "fatal: missing branch or commit argument" : "fatal: you must specify a branch to checkout", 128);
|
|
482
|
+
const branches = await git.listBranches({ fs: repo.fs, dir: repo.dir });
|
|
483
|
+
if (command === "checkout" && (!branches.includes(target) || paths.length > 0)) {
|
|
484
|
+
// git checkout <path> は作業ツリーの変更を取り消す。
|
|
485
|
+
return restore(target === "--" ? paths : [target, ...paths], repo);
|
|
486
|
+
}
|
|
487
|
+
if (!branches.includes(target))
|
|
488
|
+
throw new GitError(`fatal: invalid reference: ${target}`);
|
|
489
|
+
if ((await currentBranch(repo)) === target)
|
|
490
|
+
return { stdout: "", stderr: `Already on '${target}'\n`, exitCode: 0 };
|
|
491
|
+
// 変更が失われる場合は isomorphic-git が CheckoutConflictError を投げる。
|
|
492
|
+
try {
|
|
493
|
+
await git.checkout({ fs: repo.fs, dir: repo.dir, ref: target });
|
|
494
|
+
}
|
|
495
|
+
catch (error) {
|
|
496
|
+
if (error instanceof Error && error.name === "CheckoutConflictError") {
|
|
497
|
+
const files = error.data?.filepaths ?? [];
|
|
498
|
+
throw new GitError(`error: Your local changes to the following files would be overwritten by checkout:\n${files.map((file) => "\t" + file).join("\n")}\nPlease commit your changes or stash them before you switch branches.\nAborting`, 1);
|
|
499
|
+
}
|
|
500
|
+
throw error;
|
|
501
|
+
}
|
|
502
|
+
return { stdout: "", stderr: `Switched to branch '${target}'\n`, exitCode: 0 };
|
|
503
|
+
}
|
|
504
|
+
async function config(args, repo) {
|
|
505
|
+
const { flags, rest } = parse(args);
|
|
506
|
+
if (flags.has("--global") || flags.has("--system")) {
|
|
507
|
+
throw new GitError("error: only repository configuration is supported in Wash. Run git config without --global.", 1);
|
|
508
|
+
}
|
|
509
|
+
const [path, value] = rest;
|
|
510
|
+
if (!path)
|
|
511
|
+
throw new GitError("usage: git config <name> [<value>]", 129);
|
|
512
|
+
if (value === undefined) {
|
|
513
|
+
const current = await git.getConfig({ fs: repo.fs, dir: repo.dir, path });
|
|
514
|
+
return current === undefined ? { stdout: "", stderr: "", exitCode: 1 } : ok(`${current}\n`);
|
|
515
|
+
}
|
|
516
|
+
await git.setConfig({ fs: repo.fs, dir: repo.dir, path, value });
|
|
517
|
+
return ok();
|
|
518
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kmmz1127/wash-git",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "git command for Wash, the Web Unix-like Shell",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/kmmz532/wash-git.git"
|
|
9
|
+
},
|
|
10
|
+
"bugs": {
|
|
11
|
+
"url": "https://github.com/kmmz532/wash-git/issues"
|
|
12
|
+
},
|
|
13
|
+
"homepage": "https://github.com/kmmz532/wash-git#readme",
|
|
14
|
+
"keywords": [
|
|
15
|
+
"git",
|
|
16
|
+
"wash",
|
|
17
|
+
"terminal",
|
|
18
|
+
"shell",
|
|
19
|
+
"isomorphic-git"
|
|
20
|
+
],
|
|
21
|
+
"type": "module",
|
|
22
|
+
"main": "./lib/git/git.js",
|
|
23
|
+
"types": "./lib/git/git.d.ts",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./lib/git/git.d.ts",
|
|
27
|
+
"default": "./lib/git/git.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"lib/api.d.ts",
|
|
32
|
+
"lib/git/*.js",
|
|
33
|
+
"lib/git/*.d.ts"
|
|
34
|
+
],
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"isomorphic-git": "1.45.0"
|
|
40
|
+
}
|
|
41
|
+
}
|