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