dsh-git-desk 0.0.0-stage → 0.18.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 +79 -2
- package/client.js +5162 -0
- package/cordis.patch.yml +4 -0
- package/icon.svg +9 -0
- package/index.js +16 -0
- package/lib/ai.js +187 -0
- package/lib/exec.js +168 -0
- package/lib/git.js +1037 -0
- package/lib/http.js +139 -0
- package/lib/parse.js +319 -0
- package/lib/rpc.js +266 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +61 -4
package/lib/git.js
ADDED
|
@@ -0,0 +1,1037 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import {
|
|
4
|
+
GitError,
|
|
5
|
+
} from './exec.js';
|
|
6
|
+
import {
|
|
7
|
+
buildRows,
|
|
8
|
+
joinLines,
|
|
9
|
+
parseHunks,
|
|
10
|
+
parseLog,
|
|
11
|
+
parseNumstat,
|
|
12
|
+
parseStashes,
|
|
13
|
+
parseStatus,
|
|
14
|
+
splitLines,
|
|
15
|
+
} from './parse.js';
|
|
16
|
+
|
|
17
|
+
const ZERO_CONTEXT = ['-U0', '--no-color', '--no-ext-diff'];
|
|
18
|
+
const MAX_TEXT_BYTES = 5 * 1024 * 1024;
|
|
19
|
+
|
|
20
|
+
function hashText(text) {
|
|
21
|
+
return createHash('sha1').update(text).digest('hex');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function failure(result, fallback) {
|
|
25
|
+
const message = result.stderr.trim() || result.stdout.trim() || fallback;
|
|
26
|
+
return new GitError('git/command-failed', message);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function commitHash(value) {
|
|
30
|
+
const hash = typeof value === 'string' ? value.trim() : '';
|
|
31
|
+
if (!/^[0-9a-f]{4,64}$/i.test(hash)) {
|
|
32
|
+
throw new GitError('git/invalid-commit', 'A commit hash is required.');
|
|
33
|
+
}
|
|
34
|
+
return hash;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function resolveCommit(runtime, root, value) {
|
|
38
|
+
const hash = commitHash(value);
|
|
39
|
+
const resolved = await runtime.run(root, ['rev-parse', '--verify', `${hash}^{commit}`]);
|
|
40
|
+
const full = resolved.stdout.trim();
|
|
41
|
+
if (resolved.code !== 0 || full === '') {
|
|
42
|
+
throw new GitError('git/invalid-commit', 'That commit no longer exists.');
|
|
43
|
+
}
|
|
44
|
+
const listed = await runtime.run(root, ['rev-list', '--parents', '-n', '1', full]);
|
|
45
|
+
if (listed.code !== 0) throw failure(listed, 'Git could not read that commit.');
|
|
46
|
+
const fields = listed.stdout.trim().split(' ').filter(Boolean);
|
|
47
|
+
return { hash: full, parents: fields.slice(1) };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function operationOf(snapshot) {
|
|
51
|
+
if (snapshot.merging) return 'merge';
|
|
52
|
+
if (snapshot.rebasing) return 'rebase';
|
|
53
|
+
if (snapshot.reverting) return 'revert';
|
|
54
|
+
if (snapshot.cherryPicking) return 'cherry-pick';
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function refuseOperation(snapshot) {
|
|
59
|
+
const operation = operationOf(snapshot);
|
|
60
|
+
if (operation !== null) {
|
|
61
|
+
throw new GitError(
|
|
62
|
+
'git/operation-in-progress',
|
|
63
|
+
`Finish or abort the ${operation} before changing history.`,
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function repoPath(root, value) {
|
|
69
|
+
if (typeof value !== 'string' || value === '') {
|
|
70
|
+
throw new GitError('git/invalid-path', 'A file path is required.');
|
|
71
|
+
}
|
|
72
|
+
if (value.includes('\0')) throw new GitError('git/invalid-path', 'A file path contains an invalid character.');
|
|
73
|
+
if (value.startsWith('/') || /^[A-Za-z]:[\\/]/.test(value)) {
|
|
74
|
+
throw new GitError('git/invalid-path', 'Only repository-relative paths are accepted.');
|
|
75
|
+
}
|
|
76
|
+
const normalized = path.posix.normalize(value.replaceAll('\\', '/'));
|
|
77
|
+
if (normalized === '.' || normalized === '..' || normalized.startsWith('../') || normalized.includes('/../')) {
|
|
78
|
+
throw new GitError('git/invalid-path', 'The file path escapes the repository.');
|
|
79
|
+
}
|
|
80
|
+
if (normalized.split('/').includes('.git')) {
|
|
81
|
+
throw new GitError('git/invalid-path', 'Git metadata cannot be addressed as a file.');
|
|
82
|
+
}
|
|
83
|
+
const absolute = path.resolve(root, ...normalized.split('/'));
|
|
84
|
+
if (absolute !== root && !absolute.startsWith(root + path.sep)) {
|
|
85
|
+
throw new GitError('git/invalid-path', 'The file path escapes the repository.');
|
|
86
|
+
}
|
|
87
|
+
return { path: normalized, absolute };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function validateBlock(block) {
|
|
91
|
+
const numeric = (value) => Number.isInteger(value) && value >= 0;
|
|
92
|
+
if (
|
|
93
|
+
block === null ||
|
|
94
|
+
typeof block !== 'object' ||
|
|
95
|
+
!numeric(block.leftStart) ||
|
|
96
|
+
!numeric(block.leftEnd) ||
|
|
97
|
+
!numeric(block.rightStart) ||
|
|
98
|
+
!numeric(block.rightEnd)
|
|
99
|
+
) {
|
|
100
|
+
throw new GitError('git/invalid-block', 'A block range is invalid.');
|
|
101
|
+
}
|
|
102
|
+
return block;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function readBlob(runtime, root, spec) {
|
|
106
|
+
const result = await runtime.run(root, ['show', spec]);
|
|
107
|
+
if (result.code !== 0) {
|
|
108
|
+
return { text: '', missing: true, binary: false, size: 0 };
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
text: result.stdout,
|
|
112
|
+
missing: false,
|
|
113
|
+
binary: result.stdout.includes('\0') || result.stdout.includes('\uFFFD'),
|
|
114
|
+
size: Buffer.byteLength(result.stdout, 'utf8'),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function readWorktree(runtime, root, value) {
|
|
119
|
+
const target = repoPath(root, value);
|
|
120
|
+
const link = await runtime.lstatPath(target.absolute);
|
|
121
|
+
if (link !== null && link.isSymbolicLink()) {
|
|
122
|
+
return { text: '', missing: false, binary: true, symlink: true, size: link.size };
|
|
123
|
+
}
|
|
124
|
+
if (link !== null && link.size > MAX_TEXT_BYTES) {
|
|
125
|
+
return { text: '', missing: false, binary: true, symlink: false, size: link.size };
|
|
126
|
+
}
|
|
127
|
+
const read = await runtime.readText(target.absolute);
|
|
128
|
+
if (read === null) return { text: '', missing: true, binary: false, size: 0 };
|
|
129
|
+
return { text: read.text, missing: false, binary: read.binary, symlink: false, size: read.size };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function readPair(runtime, root, options) {
|
|
133
|
+
const value = repoPath(root, options.path);
|
|
134
|
+
if (options.side === 'staged') {
|
|
135
|
+
const left = await readBlob(runtime, root, `HEAD:${value.path}`);
|
|
136
|
+
const right = await readBlob(runtime, root, `:${value.path}`);
|
|
137
|
+
return { left, right, path: value.path };
|
|
138
|
+
}
|
|
139
|
+
if (options.side === 'unstaged') {
|
|
140
|
+
const left = await readBlob(runtime, root, `:${value.path}`);
|
|
141
|
+
const right = await readWorktree(runtime, root, value.path);
|
|
142
|
+
return { left, right, path: value.path };
|
|
143
|
+
}
|
|
144
|
+
if (options.side === 'conflict') {
|
|
145
|
+
const left = await readBlob(runtime, root, `:2:${value.path}`);
|
|
146
|
+
const right = await readBlob(runtime, root, `:3:${value.path}`);
|
|
147
|
+
const worktree = await readWorktree(runtime, root, value.path);
|
|
148
|
+
return { left, right, worktree, path: value.path };
|
|
149
|
+
}
|
|
150
|
+
if (options.side === 'log') {
|
|
151
|
+
const commit = typeof options.commit === 'string' ? options.commit.trim() : '';
|
|
152
|
+
const parent = typeof options.parent === 'string' ? options.parent.trim() : '';
|
|
153
|
+
if (!/^[0-9a-f]{4,64}$/i.test(commit)) {
|
|
154
|
+
throw new GitError('git/invalid-commit', 'A commit hash is required.');
|
|
155
|
+
}
|
|
156
|
+
const left =
|
|
157
|
+
parent && /^[0-9a-f]{4,64}$/i.test(parent)
|
|
158
|
+
? await readBlob(runtime, root, `${parent}:${value.path}`)
|
|
159
|
+
: { text: '', missing: true, binary: false, size: 0 };
|
|
160
|
+
const right = await readBlob(runtime, root, `${commit}:${value.path}`);
|
|
161
|
+
return { left, right, path: value.path };
|
|
162
|
+
}
|
|
163
|
+
throw new GitError('git/invalid-side', 'Unknown diff side.');
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function patchFor(runtime, root, options, value) {
|
|
167
|
+
if (options.side === 'unstaged') {
|
|
168
|
+
const result = await runtime.run(root, ['diff', ...ZERO_CONTEXT, '--', value]);
|
|
169
|
+
return result.code === 0 ? result.stdout : '';
|
|
170
|
+
}
|
|
171
|
+
if (options.side === 'staged') {
|
|
172
|
+
const result = await runtime.run(root, ['diff', '--cached', ...ZERO_CONTEXT, '--', value]);
|
|
173
|
+
return result.code === 0 ? result.stdout : '';
|
|
174
|
+
}
|
|
175
|
+
if (options.side === 'log') {
|
|
176
|
+
const commit = typeof options.commit === 'string' ? options.commit.trim() : '';
|
|
177
|
+
const parent = typeof options.parent === 'string' ? options.parent.trim() : '';
|
|
178
|
+
const args =
|
|
179
|
+
parent && /^[0-9a-f]{4,64}$/i.test(parent)
|
|
180
|
+
? ['diff', ...ZERO_CONTEXT, parent, commit, '--', value]
|
|
181
|
+
: ['show', '--format=', ...ZERO_CONTEXT, commit, '--', value];
|
|
182
|
+
const result = await runtime.run(root, args);
|
|
183
|
+
return result.code === 0 ? result.stdout : '';
|
|
184
|
+
}
|
|
185
|
+
return '';
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async function readStatus(runtime, root) {
|
|
189
|
+
const porcelain = await runtime.run(root, ['status', '--porcelain=v2', '--branch', '-z', '-uall']);
|
|
190
|
+
if (porcelain.code !== 0) throw failure(porcelain, 'Git status failed.');
|
|
191
|
+
const parsed = parseStatus(porcelain.stdout);
|
|
192
|
+
|
|
193
|
+
const [unstagedResult, stagedResult] = await Promise.all([
|
|
194
|
+
runtime.run(root, ['diff', '--numstat', '-z', '--no-renames']),
|
|
195
|
+
runtime.run(root, ['diff', '--cached', '--numstat', '-z', '--no-renames']),
|
|
196
|
+
]);
|
|
197
|
+
const unstaged = parseNumstat(unstagedResult.code === 0 ? unstagedResult.stdout : '');
|
|
198
|
+
const staged = parseNumstat(stagedResult.code === 0 ? stagedResult.stdout : '');
|
|
199
|
+
|
|
200
|
+
const entries = [];
|
|
201
|
+
for (const entry of parsed.entries) {
|
|
202
|
+
const work = unstaged.get(entry.path);
|
|
203
|
+
const index = staged.get(entry.path);
|
|
204
|
+
let add = work?.add ?? 0;
|
|
205
|
+
let del = work?.del ?? 0;
|
|
206
|
+
let binary = Boolean(work?.binary || index?.binary);
|
|
207
|
+
if (entry.untracked) {
|
|
208
|
+
const read = await readWorktree(runtime, root, entry.path);
|
|
209
|
+
binary = read.binary;
|
|
210
|
+
if (!read.binary) {
|
|
211
|
+
const lines = splitLines(read.text);
|
|
212
|
+
add = lines.lines.length;
|
|
213
|
+
del = 0;
|
|
214
|
+
} else {
|
|
215
|
+
add = null;
|
|
216
|
+
del = null;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
entries.push({
|
|
220
|
+
...entry,
|
|
221
|
+
add,
|
|
222
|
+
del,
|
|
223
|
+
stagedAdd: index?.add ?? 0,
|
|
224
|
+
stagedDel: index?.del ?? 0,
|
|
225
|
+
binary,
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const [mergeHead, rebaseHead, revertHead, cherryHead] = await Promise.all([
|
|
230
|
+
runtime.run(root, ['rev-parse', '-q', '--verify', 'MERGE_HEAD']),
|
|
231
|
+
runtime.run(root, ['rev-parse', '-q', '--verify', 'REBASE_HEAD']),
|
|
232
|
+
runtime.run(root, ['rev-parse', '-q', '--verify', 'REVERT_HEAD']),
|
|
233
|
+
runtime.run(root, ['rev-parse', '-q', '--verify', 'CHERRY_PICK_HEAD']),
|
|
234
|
+
]);
|
|
235
|
+
|
|
236
|
+
return {
|
|
237
|
+
repo: true,
|
|
238
|
+
root,
|
|
239
|
+
branch: parsed.branch,
|
|
240
|
+
entries,
|
|
241
|
+
merging: mergeHead.code === 0,
|
|
242
|
+
rebasing: rebaseHead.code === 0,
|
|
243
|
+
reverting: revertHead.code === 0,
|
|
244
|
+
cherryPicking: cherryHead.code === 0,
|
|
245
|
+
conflicts: entries.filter((entry) => entry.conflicted).map((entry) => entry.path),
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export async function findRepository(runtime, directory) {
|
|
250
|
+
const result = await runtime.run(directory, ['rev-parse', '--show-toplevel']);
|
|
251
|
+
if (result.code !== 0) return null;
|
|
252
|
+
const root = result.stdout.trim();
|
|
253
|
+
return root === '' ? null : root;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export async function initRepository(runtime, directory) {
|
|
257
|
+
const result = await runtime.run(directory, ['init']);
|
|
258
|
+
if (result.code !== 0) throw failure(result, 'Git could not initialize this directory.');
|
|
259
|
+
const root = await findRepository(runtime, directory);
|
|
260
|
+
if (root === null) throw new GitError('git/init-failed', 'Git initialized the directory but did not report a root.');
|
|
261
|
+
return readStatus(runtime, root);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const REPO_SCAN_DEPTH = 2;
|
|
265
|
+
const REPO_SCAN_LIMIT = 40;
|
|
266
|
+
const REPO_SKIP = new Set(['node_modules', '.dsh']);
|
|
267
|
+
|
|
268
|
+
async function isRepoRoot(runtime, directory) {
|
|
269
|
+
return (await runtime.lstatPath(path.join(directory, '.git'))) !== null;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export async function discoverRepositories(runtime, workspacePath) {
|
|
273
|
+
const found = new Map();
|
|
274
|
+
let workspace = workspacePath;
|
|
275
|
+
try {
|
|
276
|
+
workspace = await runtime.realpath(workspacePath);
|
|
277
|
+
} catch {
|
|
278
|
+
workspace = workspacePath;
|
|
279
|
+
}
|
|
280
|
+
const root = await findRepository(runtime, workspace);
|
|
281
|
+
if (root !== null) found.set(root, root);
|
|
282
|
+
async function scan(directory, depth) {
|
|
283
|
+
if (found.size >= REPO_SCAN_LIMIT || depth > REPO_SCAN_DEPTH) return;
|
|
284
|
+
const entries = await runtime.readdir(directory);
|
|
285
|
+
for (const entry of entries) {
|
|
286
|
+
if (found.size >= REPO_SCAN_LIMIT) return;
|
|
287
|
+
if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
|
|
288
|
+
if (entry.name.startsWith('.') || REPO_SKIP.has(entry.name)) continue;
|
|
289
|
+
const child = path.join(directory, entry.name);
|
|
290
|
+
if (await isRepoRoot(runtime, child)) {
|
|
291
|
+
found.set(child, child);
|
|
292
|
+
} else if (depth < REPO_SCAN_DEPTH) {
|
|
293
|
+
await scan(child, depth + 1);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
await scan(workspace, 1);
|
|
298
|
+
return [...found.values()]
|
|
299
|
+
.map((repoRoot) => ({
|
|
300
|
+
root: repoRoot,
|
|
301
|
+
name: path.relative(workspace, repoRoot) || '.',
|
|
302
|
+
label: path.basename(repoRoot),
|
|
303
|
+
}))
|
|
304
|
+
.sort((a, b) => (a.name === '.' ? -1 : b.name === '.' ? 1 : a.name.localeCompare(b.name)));
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export async function resolveRepository(runtime, workspacePath, requested) {
|
|
308
|
+
if (typeof requested !== 'string' || requested.trim() === '') {
|
|
309
|
+
throw new GitError('git/no-repository', 'Choose a repository first.');
|
|
310
|
+
}
|
|
311
|
+
if (!path.isAbsolute(requested.trim())) {
|
|
312
|
+
throw new GitError('git/repo-invalid', 'Choose the repository root.');
|
|
313
|
+
}
|
|
314
|
+
let workspace;
|
|
315
|
+
try {
|
|
316
|
+
workspace = await runtime.realpath(workspacePath);
|
|
317
|
+
} catch {
|
|
318
|
+
workspace = workspacePath;
|
|
319
|
+
}
|
|
320
|
+
let target;
|
|
321
|
+
try {
|
|
322
|
+
target = await runtime.realpath(requested.trim());
|
|
323
|
+
} catch {
|
|
324
|
+
throw new GitError('git/not-repo', 'That repository is no longer available.');
|
|
325
|
+
}
|
|
326
|
+
const root = await findRepository(runtime, target);
|
|
327
|
+
if (root === null) throw new GitError('git/not-repo', 'That folder is not a Git repository.');
|
|
328
|
+
if (root !== target) throw new GitError('git/repo-invalid', 'Choose the repository root.');
|
|
329
|
+
const inside = target === workspace || target.startsWith(`${workspace}${path.sep}`);
|
|
330
|
+
if (!inside) {
|
|
331
|
+
const workspaceRepo = await findRepository(runtime, workspace);
|
|
332
|
+
if (workspaceRepo !== target) {
|
|
333
|
+
throw new GitError('git/repo-invalid', 'That repository is outside this workspace.');
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return root;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export async function status(runtime, root) {
|
|
340
|
+
return readStatus(runtime, root);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export async function diff(runtime, root, options) {
|
|
344
|
+
const pair = await readPair(runtime, root, options);
|
|
345
|
+
const labels =
|
|
346
|
+
options.side === 'staged'
|
|
347
|
+
? { left: 'HEAD', right: 'Staged' }
|
|
348
|
+
: options.side === 'unstaged'
|
|
349
|
+
? { left: 'Staged', right: 'Local' }
|
|
350
|
+
: options.side === 'conflict'
|
|
351
|
+
? { left: 'HEAD', right: 'Incoming' }
|
|
352
|
+
: { left: 'Parent', right: 'Commit' };
|
|
353
|
+
|
|
354
|
+
if (options.side === 'conflict') {
|
|
355
|
+
const worktree = pair.worktree;
|
|
356
|
+
const text = worktree.text;
|
|
357
|
+
const lines = splitLines(text);
|
|
358
|
+
return {
|
|
359
|
+
path: pair.path,
|
|
360
|
+
side: options.side,
|
|
361
|
+
labels,
|
|
362
|
+
binary: worktree.binary,
|
|
363
|
+
conflict: true,
|
|
364
|
+
left: [],
|
|
365
|
+
right: lines.lines,
|
|
366
|
+
leftTrailing: false,
|
|
367
|
+
rightTrailing: lines.trailing,
|
|
368
|
+
rows: lines.lines.map((_, index) => ({ l: null, r: index + 1, k: 'ctx' })),
|
|
369
|
+
blocks: [],
|
|
370
|
+
add: null,
|
|
371
|
+
del: null,
|
|
372
|
+
baseHash: null,
|
|
373
|
+
targetHash: hashText(text),
|
|
374
|
+
leftMissing: true,
|
|
375
|
+
rightMissing: worktree.missing,
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
if (
|
|
380
|
+
pair.left.binary ||
|
|
381
|
+
pair.right.binary ||
|
|
382
|
+
pair.left.text.length > MAX_TEXT_BYTES ||
|
|
383
|
+
pair.right.text.length > MAX_TEXT_BYTES
|
|
384
|
+
) {
|
|
385
|
+
return {
|
|
386
|
+
path: pair.path,
|
|
387
|
+
side: options.side,
|
|
388
|
+
labels,
|
|
389
|
+
binary: true,
|
|
390
|
+
conflict: false,
|
|
391
|
+
left: [],
|
|
392
|
+
right: [],
|
|
393
|
+
leftTrailing: false,
|
|
394
|
+
rightTrailing: false,
|
|
395
|
+
rows: [],
|
|
396
|
+
blocks: [],
|
|
397
|
+
add: null,
|
|
398
|
+
del: null,
|
|
399
|
+
baseHash: hashText(pair.left.text),
|
|
400
|
+
targetHash: hashText(pair.right.text),
|
|
401
|
+
leftMissing: pair.left.missing,
|
|
402
|
+
rightMissing: pair.right.missing,
|
|
403
|
+
leftSize: pair.left.size,
|
|
404
|
+
rightSize: pair.right.size,
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const left = splitLines(pair.left.text);
|
|
409
|
+
const right = splitLines(pair.right.text);
|
|
410
|
+
let hunks = parseHunks(await patchFor(runtime, root, options, pair.path));
|
|
411
|
+
if (hunks.length === 0 && pair.left.missing && !pair.right.missing) {
|
|
412
|
+
hunks = [{ oldStart: 0, oldCount: 0, newStart: 1, newCount: right.lines.length }];
|
|
413
|
+
} else if (hunks.length === 0 && !pair.left.missing && pair.right.missing) {
|
|
414
|
+
hunks = [{ oldStart: 1, oldCount: left.lines.length, newStart: 0, newCount: 0 }];
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
const built = buildRows(left.lines, right.lines, hunks);
|
|
418
|
+
const blocks = built.blocks.map((block) => ({
|
|
419
|
+
...block,
|
|
420
|
+
id: `b${block.leftStart}-${block.leftEnd}-${block.rightStart}-${block.rightEnd}`,
|
|
421
|
+
}));
|
|
422
|
+
|
|
423
|
+
return {
|
|
424
|
+
path: pair.path,
|
|
425
|
+
side: options.side,
|
|
426
|
+
labels,
|
|
427
|
+
binary: false,
|
|
428
|
+
conflict: false,
|
|
429
|
+
left: left.lines,
|
|
430
|
+
right: right.lines,
|
|
431
|
+
leftTrailing: left.trailing,
|
|
432
|
+
rightTrailing: right.trailing,
|
|
433
|
+
rows: built.rows,
|
|
434
|
+
blocks,
|
|
435
|
+
add: built.add,
|
|
436
|
+
del: built.del,
|
|
437
|
+
baseHash: hashText(pair.left.text),
|
|
438
|
+
targetHash: hashText(pair.right.text),
|
|
439
|
+
leftMissing: pair.left.missing,
|
|
440
|
+
rightMissing: pair.right.missing,
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
async function writeIndex(runtime, root, value, content) {
|
|
445
|
+
const target = repoPath(root, value);
|
|
446
|
+
const blob = await runtime.run(root, ['hash-object', '-w', '--stdin'], { input: content });
|
|
447
|
+
if (blob.code !== 0) throw failure(blob, 'Git could not write the new index entry.');
|
|
448
|
+
const hash = blob.stdout.trim();
|
|
449
|
+
const entry = await runtime.run(root, ['ls-files', '-s', '--', target.path]);
|
|
450
|
+
const hasEntry = entry.code === 0 && entry.stdout.trim() !== '';
|
|
451
|
+
let mode = hasEntry ? entry.stdout.trim().split(' ')[0] : '100644';
|
|
452
|
+
if (!hasEntry) {
|
|
453
|
+
const stat = await runtime.statPath(target.absolute);
|
|
454
|
+
if (stat !== null && (stat.mode & 0o111) !== 0) mode = '100755';
|
|
455
|
+
}
|
|
456
|
+
const update = await runtime.run(root, ['update-index', '--add', '--cacheinfo', mode, hash, target.path]);
|
|
457
|
+
if (update.code !== 0) throw failure(update, 'Git could not update the index.');
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function replaceRange(lines, start, end, replacement) {
|
|
461
|
+
const begin = Math.max(0, start - 1);
|
|
462
|
+
const stop = Math.max(begin, end);
|
|
463
|
+
return [...lines.slice(0, begin), ...replacement, ...lines.slice(stop)];
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
export async function applyBlocks(runtime, root, options) {
|
|
467
|
+
const value = repoPath(root, options.path);
|
|
468
|
+
if (!Array.isArray(options.blocks) || options.blocks.length === 0 || options.blocks.length > 200) {
|
|
469
|
+
throw new GitError('git/invalid-block', 'Select at least one block.');
|
|
470
|
+
}
|
|
471
|
+
if (options.side !== 'unstaged' && options.side !== 'staged' && options.side !== 'revert') {
|
|
472
|
+
throw new GitError('git/invalid-side', 'Unknown block action.');
|
|
473
|
+
}
|
|
474
|
+
if (options.side === 'revert' && options.confirm !== true) {
|
|
475
|
+
throw new GitError('git/confirm-required', 'Reverting a block needs confirmation.');
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
const indexEntry = await runtime.run(root, ['ls-files', '-s', '--', value.path]);
|
|
479
|
+
if (indexEntry.code === 0 && indexEntry.stdout.trim() !== '') {
|
|
480
|
+
const mode = indexEntry.stdout.trim().split(' ')[0];
|
|
481
|
+
if (mode === '120000' || mode === '160000') {
|
|
482
|
+
throw new GitError('git/unsupported', 'Block actions are not available for a symlink or a submodule.');
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
const pair = await readPair(runtime, root, {
|
|
487
|
+
path: value.path,
|
|
488
|
+
side: options.side === 'staged' ? 'staged' : 'unstaged',
|
|
489
|
+
});
|
|
490
|
+
if (pair.left.binary || pair.right.binary) {
|
|
491
|
+
throw new GitError('git/binary', 'Blocks cannot be changed in a binary or non-UTF-8 file.');
|
|
492
|
+
}
|
|
493
|
+
if (options.side === 'revert' && pair.left.missing) {
|
|
494
|
+
throw new GitError('git/unsupported', 'A file with no staged version cannot be reverted block by block.');
|
|
495
|
+
}
|
|
496
|
+
if (options.baseHash !== hashText(pair.left.text) || options.targetHash !== hashText(pair.right.text)) {
|
|
497
|
+
throw new GitError('git/stale', 'The file changed after the diff was read. Refresh and try again.');
|
|
498
|
+
}
|
|
499
|
+
const snapshot = await readStatus(runtime, root);
|
|
500
|
+
const current = snapshot.entries.find((entry) => entry.path === value.path);
|
|
501
|
+
if (current?.kind === 'renamed') {
|
|
502
|
+
throw new GitError('git/unsupported', 'Block actions are not available for a rename. Use the file buttons.');
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
const left = splitLines(pair.left.text);
|
|
506
|
+
const right = splitLines(pair.right.text);
|
|
507
|
+
const blocks = options.blocks.map(validateBlock);
|
|
508
|
+
|
|
509
|
+
if (options.side === 'unstaged' || options.side === 'staged') {
|
|
510
|
+
const source = options.side === 'staged' ? right.lines : left.lines;
|
|
511
|
+
const trailing =
|
|
512
|
+
options.side === 'staged'
|
|
513
|
+
? pair.right.missing
|
|
514
|
+
? left.trailing
|
|
515
|
+
: right.trailing
|
|
516
|
+
: options.side === 'unstaged' && pair.left.missing
|
|
517
|
+
? right.trailing
|
|
518
|
+
: left.trailing;
|
|
519
|
+
let next = [...source];
|
|
520
|
+
const ordered = [...blocks].sort((a, b) =>
|
|
521
|
+
options.side === 'staged' ? b.rightStart - a.rightStart : b.leftStart - a.leftStart,
|
|
522
|
+
);
|
|
523
|
+
for (const block of ordered) {
|
|
524
|
+
const start = options.side === 'staged' ? block.rightStart : block.leftStart;
|
|
525
|
+
const end = options.side === 'staged' ? block.rightEnd : block.leftEnd;
|
|
526
|
+
const piece =
|
|
527
|
+
options.side === 'staged'
|
|
528
|
+
? left.lines.slice(block.leftStart - 1, block.leftEnd)
|
|
529
|
+
: right.lines.slice(block.rightStart - 1, block.rightEnd);
|
|
530
|
+
next = replaceRange(next, start, end, piece);
|
|
531
|
+
}
|
|
532
|
+
const content = joinLines(next, trailing);
|
|
533
|
+
if (
|
|
534
|
+
(options.side === 'staged' && pair.left.missing && content === '') ||
|
|
535
|
+
(options.side === 'unstaged' && pair.right.missing)
|
|
536
|
+
) {
|
|
537
|
+
const removed = await runtime.run(root, ['update-index', '--force-remove', '--', value.path]);
|
|
538
|
+
if (removed.code !== 0) throw failure(removed, 'Git could not remove the file from the index.');
|
|
539
|
+
} else {
|
|
540
|
+
await writeIndex(runtime, root, value.path, content);
|
|
541
|
+
}
|
|
542
|
+
return readStatus(runtime, root);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
const source = right.lines;
|
|
546
|
+
let next = [...source];
|
|
547
|
+
const ordered = [...blocks].sort((a, b) => b.rightStart - a.rightStart);
|
|
548
|
+
for (const block of ordered) {
|
|
549
|
+
const piece = left.lines.slice(block.leftStart - 1, block.leftEnd);
|
|
550
|
+
next = replaceRange(next, block.rightStart, block.rightEnd, piece);
|
|
551
|
+
}
|
|
552
|
+
const content = joinLines(next, right.trailing);
|
|
553
|
+
const target = repoPath(root, value.path);
|
|
554
|
+
await runtime.writeText(target.absolute, content);
|
|
555
|
+
return readStatus(runtime, root);
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
export async function stagePaths(runtime, root, paths) {
|
|
559
|
+
const safe = paths.map((value) => repoPath(root, value).path);
|
|
560
|
+
if (safe.length === 0) return readStatus(runtime, root);
|
|
561
|
+
const result = await runtime.run(root, ['add', '--', ...safe]);
|
|
562
|
+
if (result.code !== 0) throw failure(result, 'Git could not stage the selected files.');
|
|
563
|
+
return readStatus(runtime, root);
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
export async function unstagePaths(runtime, root, paths) {
|
|
567
|
+
const safe = paths.map((value) => repoPath(root, value).path);
|
|
568
|
+
if (safe.length === 0) return readStatus(runtime, root);
|
|
569
|
+
const head = await runtime.run(root, ['rev-parse', '--verify', 'HEAD']);
|
|
570
|
+
const result =
|
|
571
|
+
head.code === 0
|
|
572
|
+
? await runtime.run(root, ['restore', '--staged', '--', ...safe])
|
|
573
|
+
: await runtime.run(root, ['rm', '--cached', '--', ...safe]);
|
|
574
|
+
if (result.code !== 0) throw failure(result, 'Git could not unstage the selected files.');
|
|
575
|
+
return readStatus(runtime, root);
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
export async function commit(runtime, root, options) {
|
|
579
|
+
const message = typeof options.message === 'string' ? options.message.trim() : '';
|
|
580
|
+
if (message === '') throw new GitError('git/message-required', 'Write a commit message first.');
|
|
581
|
+
const snapshot = await readStatus(runtime, root);
|
|
582
|
+
if (snapshot.entries.some((entry) => entry.conflicted)) {
|
|
583
|
+
throw new GitError('git/conflict', 'Resolve the conflicts before committing.');
|
|
584
|
+
}
|
|
585
|
+
if (!snapshot.entries.some((entry) => entry.staged)) {
|
|
586
|
+
throw new GitError('git/nothing-staged', 'Stage at least one file before committing.');
|
|
587
|
+
}
|
|
588
|
+
const args = ['commit', '-F', '-'];
|
|
589
|
+
if (options.amend === true) args.push('--amend');
|
|
590
|
+
const result = await runtime.run(root, args, {
|
|
591
|
+
input: message.endsWith('\n') ? message : `${message}\n`,
|
|
592
|
+
});
|
|
593
|
+
if (result.code !== 0) {
|
|
594
|
+
throw new GitError('git/commit-failed', result.stderr.trim() || result.stdout.trim() || 'Git could not commit.', {
|
|
595
|
+
stdout: result.stdout,
|
|
596
|
+
stderr: result.stderr,
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
const head = await runtime.run(root, ['rev-parse', 'HEAD']);
|
|
600
|
+
return {
|
|
601
|
+
hash: head.stdout.trim(),
|
|
602
|
+
output: `${result.stdout}${result.stderr}`.trim(),
|
|
603
|
+
status: await readStatus(runtime, root),
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
export async function createBranch(runtime, root, options) {
|
|
608
|
+
const name = typeof options.name === 'string' ? options.name.trim() : '';
|
|
609
|
+
if (name === '') throw new GitError('git/branch-required', 'Write a branch name first.');
|
|
610
|
+
const valid = await runtime.run(root, ['check-ref-format', '--branch', name]);
|
|
611
|
+
if (valid.code !== 0) throw new GitError('git/branch-invalid', 'Use a valid branch name.');
|
|
612
|
+
const created = await runtime.run(root, ['checkout', '-b', name]);
|
|
613
|
+
if (created.code !== 0) {
|
|
614
|
+
throw new GitError('git/branch-failed', created.stderr.trim() || created.stdout.trim() || 'Git could not create the branch.');
|
|
615
|
+
}
|
|
616
|
+
return {
|
|
617
|
+
output: `${created.stdout}${created.stderr}`.trim(),
|
|
618
|
+
status: await readStatus(runtime, root),
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
export async function createBranchAndCommit(runtime, root, options) {
|
|
623
|
+
const name = typeof options.name === 'string' ? options.name.trim() : '';
|
|
624
|
+
if (name === '') throw new GitError('git/branch-required', 'Write a branch name first.');
|
|
625
|
+
if (!/^[A-Za-z0-9._/-]+$/.test(name)) {
|
|
626
|
+
throw new GitError('git/branch-invalid', 'Use letters, numbers, dots, slashes, or dashes in a branch name.');
|
|
627
|
+
}
|
|
628
|
+
const snapshot = await readStatus(runtime, root);
|
|
629
|
+
if (snapshot.entries.some((entry) => entry.conflicted)) {
|
|
630
|
+
throw new GitError('git/conflict', 'Resolve the conflicts before creating a branch.');
|
|
631
|
+
}
|
|
632
|
+
if (!snapshot.entries.some((entry) => entry.staged)) {
|
|
633
|
+
throw new GitError('git/nothing-staged', 'Stage at least one file before creating a branch.');
|
|
634
|
+
}
|
|
635
|
+
const created = await runtime.run(root, ['checkout', '-b', name]);
|
|
636
|
+
if (created.code !== 0) {
|
|
637
|
+
throw new GitError('git/branch-failed', created.stderr.trim() || 'Git could not create the branch.');
|
|
638
|
+
}
|
|
639
|
+
try {
|
|
640
|
+
return await commit(runtime, root, { message: options.message });
|
|
641
|
+
} catch (error) {
|
|
642
|
+
if (error instanceof GitError) {
|
|
643
|
+
error.message = `Branch ${name} was created, but the commit failed. ${error.message}`;
|
|
644
|
+
}
|
|
645
|
+
throw error;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
export async function remoteStatus(runtime, root) {
|
|
650
|
+
const upstream = await runtime.run(root, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
|
|
651
|
+
const remotes = await runtime.run(root, ['remote']);
|
|
652
|
+
const names =
|
|
653
|
+
remotes.code === 0
|
|
654
|
+
? remotes.stdout
|
|
655
|
+
.split('\n')
|
|
656
|
+
.map((name) => name.trim())
|
|
657
|
+
.filter(Boolean)
|
|
658
|
+
: [];
|
|
659
|
+
return {
|
|
660
|
+
upstream: upstream.code === 0 ? upstream.stdout.trim() : null,
|
|
661
|
+
hasRemote: names.length > 0,
|
|
662
|
+
remote: names.includes('origin') ? 'origin' : names[0] ?? null,
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
export async function push(runtime, root) {
|
|
667
|
+
const remote = await remoteStatus(runtime, root);
|
|
668
|
+
if (!remote.hasRemote || remote.remote === null) {
|
|
669
|
+
throw new GitError('git/no-remote', 'This repository has no remote.');
|
|
670
|
+
}
|
|
671
|
+
const args = remote.upstream === null ? ['push', '-u', remote.remote, 'HEAD'] : ['push'];
|
|
672
|
+
const result = await runtime.run(root, args, { network: true });
|
|
673
|
+
if (result.code !== 0) {
|
|
674
|
+
throw new GitError('git/push-failed', result.stderr.trim() || result.stdout.trim() || 'Push failed.', {
|
|
675
|
+
stdout: result.stdout,
|
|
676
|
+
stderr: result.stderr,
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
return {
|
|
680
|
+
output: `${result.stdout}${result.stderr}`.trim(),
|
|
681
|
+
status: await readStatus(runtime, root),
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
export async function pull(runtime, root) {
|
|
686
|
+
const remote = await remoteStatus(runtime, root);
|
|
687
|
+
if (remote.upstream === null) throw new GitError('git/no-upstream', 'This branch has no upstream branch.');
|
|
688
|
+
const result = await runtime.run(root, ['pull', '--ff-only'], { network: true });
|
|
689
|
+
if (result.code !== 0) {
|
|
690
|
+
throw new GitError('git/pull-failed', result.stderr.trim() || result.stdout.trim() || 'Pull failed.', {
|
|
691
|
+
stdout: result.stdout,
|
|
692
|
+
stderr: result.stderr,
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
return {
|
|
696
|
+
output: `${result.stdout}${result.stderr}`.trim(),
|
|
697
|
+
status: await readStatus(runtime, root),
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
export async function fetch(runtime, root) {
|
|
702
|
+
const remote = await remoteStatus(runtime, root);
|
|
703
|
+
if (!remote.hasRemote) throw new GitError('git/no-remote', 'This repository has no remote.');
|
|
704
|
+
const result = await runtime.run(root, ['fetch'], { network: true });
|
|
705
|
+
if (result.code !== 0) {
|
|
706
|
+
throw new GitError('git/fetch-failed', result.stderr.trim() || result.stdout.trim() || 'Fetch failed.');
|
|
707
|
+
}
|
|
708
|
+
return {
|
|
709
|
+
output: `${result.stdout}${result.stderr}`.trim(),
|
|
710
|
+
status: await readStatus(runtime, root),
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
export async function stagedPatch(runtime, root) {
|
|
715
|
+
const result = await runtime.run(root, [
|
|
716
|
+
'diff',
|
|
717
|
+
'--cached',
|
|
718
|
+
'--patch',
|
|
719
|
+
'--no-color',
|
|
720
|
+
'--no-ext-diff',
|
|
721
|
+
'--unified=2',
|
|
722
|
+
]);
|
|
723
|
+
if (result.code !== 0) throw failure(result, 'Git could not read the staged changes.');
|
|
724
|
+
return result.stdout;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
export async function recentSubjects(runtime, root, count = 5) {
|
|
728
|
+
const result = await runtime.run(root, ['log', `--max-count=${count}`, '--format=%s']);
|
|
729
|
+
if (result.code !== 0) return [];
|
|
730
|
+
return result.stdout
|
|
731
|
+
.split('\n')
|
|
732
|
+
.map((line) => line.trim())
|
|
733
|
+
.filter((line) => line !== '');
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
export async function log(runtime, root) {
|
|
737
|
+
const format = '%H%x00%P%x00%an%x00%ae%x00%ad%x00%D%x00%s%x1e';
|
|
738
|
+
const result = await runtime.run(root, [
|
|
739
|
+
'log',
|
|
740
|
+
'--all',
|
|
741
|
+
'--exclude=refs/stash',
|
|
742
|
+
'--max-count=100',
|
|
743
|
+
'--date=iso-strict',
|
|
744
|
+
`--pretty=format:${format}`,
|
|
745
|
+
]);
|
|
746
|
+
if (result.code !== 0) {
|
|
747
|
+
if (result.stderr.includes('does not have any commits yet')) return { commits: [] };
|
|
748
|
+
throw failure(result, 'Git log failed.');
|
|
749
|
+
}
|
|
750
|
+
return { commits: parseLog(result.stdout) };
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
export async function commitDetail(runtime, root, options) {
|
|
754
|
+
const hash = commitHash(options.hash);
|
|
755
|
+
const meta = await runtime.run(root, [
|
|
756
|
+
'show',
|
|
757
|
+
'-s',
|
|
758
|
+
'--date=iso-strict',
|
|
759
|
+
'--pretty=format:%H%x00%P%x00%an%x00%ae%x00%ad%x00%s%x00%b',
|
|
760
|
+
hash,
|
|
761
|
+
]);
|
|
762
|
+
if (meta.code !== 0) throw failure(meta, 'Git could not read that commit.');
|
|
763
|
+
const fields = meta.stdout.split('\x00');
|
|
764
|
+
const filesResult = await runtime.run(root, ['show', '--numstat', '-z', '--no-renames', '--format=', hash]);
|
|
765
|
+
const files = [];
|
|
766
|
+
if (filesResult.code === 0) {
|
|
767
|
+
for (const record of filesResult.stdout.split('\0')) {
|
|
768
|
+
if (record === '') continue;
|
|
769
|
+
const parts = record.split('\t');
|
|
770
|
+
if (parts.length < 3) continue;
|
|
771
|
+
const add = parts[0] === '-' ? null : Number(parts[0]);
|
|
772
|
+
const del = parts[1] === '-' ? null : Number(parts[1]);
|
|
773
|
+
files.push({
|
|
774
|
+
path: parts.slice(2).join('\t'),
|
|
775
|
+
add: Number.isFinite(add) ? add : null,
|
|
776
|
+
del: Number.isFinite(del) ? del : null,
|
|
777
|
+
binary: add === null || del === null,
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
return {
|
|
782
|
+
hash: fields[0],
|
|
783
|
+
parents: fields[1] ? fields[1].split(' ').filter(Boolean) : [],
|
|
784
|
+
author: fields[2],
|
|
785
|
+
email: fields[3],
|
|
786
|
+
date: fields[4],
|
|
787
|
+
subject: fields[5],
|
|
788
|
+
body: fields[6] ?? '',
|
|
789
|
+
files,
|
|
790
|
+
};
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
export async function undoCommit(runtime, root, options) {
|
|
794
|
+
const snapshot = await readStatus(runtime, root);
|
|
795
|
+
refuseOperation(snapshot);
|
|
796
|
+
if (snapshot.branch.detached) {
|
|
797
|
+
throw new GitError('git/detached', 'Check out a branch before undoing a commit.');
|
|
798
|
+
}
|
|
799
|
+
const target = await resolveCommit(runtime, root, options.hash);
|
|
800
|
+
const head = await runtime.run(root, ['rev-parse', '--verify', 'HEAD']);
|
|
801
|
+
if (head.code !== 0 || head.stdout.trim() === '') {
|
|
802
|
+
throw new GitError('git/no-head', 'This branch has no commit to undo.');
|
|
803
|
+
}
|
|
804
|
+
if (head.stdout.trim() !== target.hash) {
|
|
805
|
+
throw new GitError('git/not-head', 'Only the last commit on the current branch can be undone.');
|
|
806
|
+
}
|
|
807
|
+
if (target.parents.length === 0) {
|
|
808
|
+
throw new GitError('git/root-commit', 'The first commit has no parent to move back to.');
|
|
809
|
+
}
|
|
810
|
+
if (snapshot.branch.upstream !== null && snapshot.branch.ahead === 0) {
|
|
811
|
+
throw new GitError(
|
|
812
|
+
'git/undo-pushed',
|
|
813
|
+
`The last commit is already on ${snapshot.branch.upstream}. Revert it instead.`,
|
|
814
|
+
);
|
|
815
|
+
}
|
|
816
|
+
const logged = await runtime.run(root, ['log', '-1', '--pretty=%B', target.hash]);
|
|
817
|
+
const reset = await runtime.run(root, ['reset', '--soft', target.parents[0]]);
|
|
818
|
+
if (reset.code !== 0) throw failure(reset, 'Git could not undo the commit.');
|
|
819
|
+
return {
|
|
820
|
+
hash: target.hash,
|
|
821
|
+
message: logged.code === 0 ? logged.stdout.replace(/\s+$/, '') : '',
|
|
822
|
+
output: `${reset.stdout}${reset.stderr}`.trim(),
|
|
823
|
+
status: await readStatus(runtime, root),
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
export async function revertCommit(runtime, root, options) {
|
|
828
|
+
const snapshot = await readStatus(runtime, root);
|
|
829
|
+
refuseOperation(snapshot);
|
|
830
|
+
if (snapshot.entries.some((entry) => entry.conflicted)) {
|
|
831
|
+
throw new GitError('git/conflict', 'Resolve the conflicts before reverting a commit.');
|
|
832
|
+
}
|
|
833
|
+
if (snapshot.entries.some((entry) => entry.staged)) {
|
|
834
|
+
throw new GitError('git/index-dirty', 'Commit or unstage the staged files before reverting a commit.');
|
|
835
|
+
}
|
|
836
|
+
const target = await resolveCommit(runtime, root, options.hash);
|
|
837
|
+
if (target.parents.length > 1) {
|
|
838
|
+
throw new GitError('git/merge-commit', 'A merge commit needs a mainline choice and cannot be reverted here.');
|
|
839
|
+
}
|
|
840
|
+
const subject = await runtime.run(root, ['show', '-s', '--format=%s', target.hash]);
|
|
841
|
+
if (subject.code !== 0) throw failure(subject, 'Git could not read that commit.');
|
|
842
|
+
const message = `Revert "${subject.stdout.trim()}"\n\nThis reverts commit ${target.hash}.`;
|
|
843
|
+
const result = await runtime.run(root, ['revert', '--no-commit', target.hash]);
|
|
844
|
+
const status = await readStatus(runtime, root);
|
|
845
|
+
const output = `${result.stdout}${result.stderr}`.trim();
|
|
846
|
+
if (result.code !== 0) {
|
|
847
|
+
const paths = status.entries.filter((entry) => entry.conflicted).map((entry) => entry.path);
|
|
848
|
+
if (paths.length > 0) {
|
|
849
|
+
return { hash: target.hash, conflicted: true, paths, message, output, status };
|
|
850
|
+
}
|
|
851
|
+
throw new GitError('git/revert-failed', output || 'Git could not revert the commit.', {
|
|
852
|
+
stdout: result.stdout,
|
|
853
|
+
stderr: result.stderr,
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
return { hash: target.hash, conflicted: false, paths: [], message, output, status };
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
export async function cherryPickCommit(runtime, root, options) {
|
|
860
|
+
const snapshot = await readStatus(runtime, root);
|
|
861
|
+
refuseOperation(snapshot);
|
|
862
|
+
if (snapshot.entries.some((entry) => entry.conflicted)) {
|
|
863
|
+
throw new GitError('git/conflict', 'Resolve the conflicts before cherry-picking a commit.');
|
|
864
|
+
}
|
|
865
|
+
const target = await resolveCommit(runtime, root, options.hash);
|
|
866
|
+
if (target.parents.length > 1) {
|
|
867
|
+
throw new GitError('git/merge-commit', 'A merge commit cannot be cherry-picked here.');
|
|
868
|
+
}
|
|
869
|
+
const contained = await runtime.run(root, ['cherry', 'HEAD', target.hash]);
|
|
870
|
+
if (contained.code !== 0) throw failure(contained, 'Git could not compare the commits.');
|
|
871
|
+
const pending = contained.stdout
|
|
872
|
+
.split('\n')
|
|
873
|
+
.map((line) => line.trim())
|
|
874
|
+
.find((line) => line.length > 0 && line.split(' ').pop() === target.hash);
|
|
875
|
+
if (pending === undefined || pending.startsWith('-')) {
|
|
876
|
+
throw new GitError('git/already-applied', 'This commit is already applied to the current branch.');
|
|
877
|
+
}
|
|
878
|
+
const result = await runtime.run(root, ['cherry-pick', target.hash]);
|
|
879
|
+
const status = await readStatus(runtime, root);
|
|
880
|
+
if (result.code !== 0) {
|
|
881
|
+
const paths = status.entries.filter((entry) => entry.conflicted).map((entry) => entry.path);
|
|
882
|
+
const aborted = await runtime.run(root, ['cherry-pick', '--abort']);
|
|
883
|
+
if (paths.length > 0) {
|
|
884
|
+
throw new GitError(
|
|
885
|
+
'git/cherry-pick-conflict',
|
|
886
|
+
`Cherry-pick stopped with conflicts in ${paths.join(', ')}. The pick was aborted and the branch is unchanged.`,
|
|
887
|
+
{ paths, aborted: aborted.code === 0, stdout: result.stdout, stderr: result.stderr },
|
|
888
|
+
);
|
|
889
|
+
}
|
|
890
|
+
throw new GitError(
|
|
891
|
+
'git/cherry-pick-failed',
|
|
892
|
+
result.stderr.trim() || result.stdout.trim() || 'Git could not cherry-pick the commit.',
|
|
893
|
+
{ stdout: result.stdout, stderr: result.stderr, aborted: aborted.code === 0 },
|
|
894
|
+
);
|
|
895
|
+
}
|
|
896
|
+
const head = await runtime.run(root, ['rev-parse', '--verify', 'HEAD']);
|
|
897
|
+
return {
|
|
898
|
+
hash: head.code === 0 ? head.stdout.trim() : target.hash,
|
|
899
|
+
output: `${result.stdout}${result.stderr}`.trim(),
|
|
900
|
+
status: await readStatus(runtime, root),
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
const RESET_MODES = new Set(['soft', 'mixed', 'hard']);
|
|
905
|
+
|
|
906
|
+
export async function resetToCommit(runtime, root, options) {
|
|
907
|
+
const mode = typeof options.mode === 'string' ? options.mode : '';
|
|
908
|
+
if (!RESET_MODES.has(mode)) {
|
|
909
|
+
throw new GitError('git/invalid-reset-mode', 'Choose soft, mixed, or hard.');
|
|
910
|
+
}
|
|
911
|
+
if (options.confirm !== true) {
|
|
912
|
+
throw new GitError('git/confirm-required', 'Resetting the branch needs confirmation.');
|
|
913
|
+
}
|
|
914
|
+
const snapshot = await readStatus(runtime, root);
|
|
915
|
+
refuseOperation(snapshot);
|
|
916
|
+
if (snapshot.branch.detached) {
|
|
917
|
+
throw new GitError('git/detached', 'Check out a branch before resetting it.');
|
|
918
|
+
}
|
|
919
|
+
const target = await resolveCommit(runtime, root, options.hash);
|
|
920
|
+
const result = await runtime.run(root, ['reset', `--${mode}`, target.hash]);
|
|
921
|
+
if (result.code !== 0) throw failure(result, 'Git could not reset the branch.');
|
|
922
|
+
return {
|
|
923
|
+
hash: target.hash,
|
|
924
|
+
mode,
|
|
925
|
+
output: `${result.stdout}${result.stderr}`.trim(),
|
|
926
|
+
status: await readStatus(runtime, root),
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
export async function branches(runtime, root) {
|
|
931
|
+
const result = await runtime.run(root, [
|
|
932
|
+
'for-each-ref',
|
|
933
|
+
'--format=%(refname:short)%00%(HEAD)%00%(upstream:short)%00%(refname)',
|
|
934
|
+
'refs/heads',
|
|
935
|
+
'refs/remotes',
|
|
936
|
+
]);
|
|
937
|
+
if (result.code !== 0) throw failure(result, 'Git could not list branches.');
|
|
938
|
+
const list = [];
|
|
939
|
+
for (const record of result.stdout.split('\n')) {
|
|
940
|
+
if (record.trim() === '') continue;
|
|
941
|
+
const [name, head, upstream, full] = record.split('\x00');
|
|
942
|
+
if (name === undefined || name === '') continue;
|
|
943
|
+
if (full?.includes('refs/remotes/') && name.endsWith('/HEAD')) continue;
|
|
944
|
+
const remote = Boolean(full?.startsWith('refs/remotes/'));
|
|
945
|
+
list.push({
|
|
946
|
+
name,
|
|
947
|
+
current: head === '*',
|
|
948
|
+
upstream: upstream || null,
|
|
949
|
+
remote,
|
|
950
|
+
});
|
|
951
|
+
}
|
|
952
|
+
return { branches: list };
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
export async function checkout(runtime, root, options) {
|
|
956
|
+
const name = typeof options.branch === 'string' ? options.branch.trim() : '';
|
|
957
|
+
if (name === '' || name.startsWith('-') || name.includes('\0')) {
|
|
958
|
+
throw new GitError('git/branch-invalid', 'Choose a branch.');
|
|
959
|
+
}
|
|
960
|
+
const result = await runtime.run(root, options.remote === true ? ['checkout', '--track', name] : ['checkout', name]);
|
|
961
|
+
if (result.code !== 0) {
|
|
962
|
+
throw new GitError('git/checkout-failed', result.stderr.trim() || result.stdout.trim() || 'Checkout failed.');
|
|
963
|
+
}
|
|
964
|
+
return {
|
|
965
|
+
output: `${result.stdout}${result.stderr}`.trim(),
|
|
966
|
+
status: await readStatus(runtime, root),
|
|
967
|
+
};
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
export async function stashList(runtime, root) {
|
|
971
|
+
const result = await runtime.run(root, ['stash', 'list', '--pretty=format:%gd%x00%gs%x00%H%x1e']);
|
|
972
|
+
if (result.code !== 0) throw failure(result, 'Git could not list stashes.');
|
|
973
|
+
return { stashes: parseStashes(result.stdout) };
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
export async function stashPush(runtime, root, options) {
|
|
977
|
+
const message = typeof options.message === 'string' && options.message.trim() !== ''
|
|
978
|
+
? options.message.trim()
|
|
979
|
+
: 'WIP';
|
|
980
|
+
const paths = Array.isArray(options.paths) ? options.paths.map((value) => repoPath(root, value).path) : [];
|
|
981
|
+
const args = ['stash', 'push', '-m', message];
|
|
982
|
+
if (options.includeUntracked === true) args.push('-u');
|
|
983
|
+
if (paths.length > 0) args.push('--', ...paths);
|
|
984
|
+
const result = await runtime.run(root, args);
|
|
985
|
+
if (result.code !== 0) throw failure(result, 'Git could not stash the selected files.');
|
|
986
|
+
return {
|
|
987
|
+
output: `${result.stdout}${result.stderr}`.trim(),
|
|
988
|
+
status: await readStatus(runtime, root),
|
|
989
|
+
...(await stashList(runtime, root)),
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
function stashRef(value) {
|
|
994
|
+
if (typeof value !== 'string' || !/^stash@\{\d+\}$/.test(value)) {
|
|
995
|
+
throw new GitError('git/invalid-stash', 'Choose a stash.');
|
|
996
|
+
}
|
|
997
|
+
return value;
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
export async function stashApply(runtime, root, options) {
|
|
1001
|
+
const ref = stashRef(options.ref);
|
|
1002
|
+
const verb = options.pop === true ? 'pop' : 'apply';
|
|
1003
|
+
const result = await runtime.run(root, ['stash', verb, ref]);
|
|
1004
|
+
if (result.code !== 0) {
|
|
1005
|
+
throw new GitError('git/stash-failed', result.stderr.trim() || result.stdout.trim() || 'Git could not apply the stash.');
|
|
1006
|
+
}
|
|
1007
|
+
return {
|
|
1008
|
+
output: `${result.stdout}${result.stderr}`.trim(),
|
|
1009
|
+
status: await readStatus(runtime, root),
|
|
1010
|
+
...(await stashList(runtime, root)),
|
|
1011
|
+
};
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
export async function stashDrop(runtime, root, options) {
|
|
1015
|
+
const ref = stashRef(options.ref);
|
|
1016
|
+
const result = await runtime.run(root, ['stash', 'drop', ref]);
|
|
1017
|
+
if (result.code !== 0) throw failure(result, 'Git could not drop the stash.');
|
|
1018
|
+
return {
|
|
1019
|
+
output: `${result.stdout}${result.stderr}`.trim(),
|
|
1020
|
+
status: await readStatus(runtime, root),
|
|
1021
|
+
...(await stashList(runtime, root)),
|
|
1022
|
+
};
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
export async function resolveConflict(runtime, root, options) {
|
|
1026
|
+
const value = repoPath(root, options.path);
|
|
1027
|
+
if (options.side !== 'ours' && options.side !== 'theirs') {
|
|
1028
|
+
throw new GitError('git/invalid-side', 'Choose a conflict side.');
|
|
1029
|
+
}
|
|
1030
|
+
const checked = await runtime.run(root, ['checkout', `--${options.side}`, '--', value.path]);
|
|
1031
|
+
if (checked.code !== 0) {
|
|
1032
|
+
throw new GitError('git/resolve-failed', checked.stderr.trim() || 'Git could not resolve the file.');
|
|
1033
|
+
}
|
|
1034
|
+
const added = await runtime.run(root, ['add', '--', value.path]);
|
|
1035
|
+
if (added.code !== 0) throw failure(added, 'Git could not stage the resolved file.');
|
|
1036
|
+
return readStatus(runtime, root);
|
|
1037
|
+
}
|