git-colabor 0.1.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 +179 -0
- package/bin/git-colabor.cjs +5 -0
- package/dist/askpass.cjs +71 -0
- package/dist/cli.cjs +1475 -0
- package/dist/index.cjs +1110 -0
- package/package.json +43 -0
package/dist/cli.cjs
ADDED
|
@@ -0,0 +1,1475 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var fs = require('fs');
|
|
4
|
+
var path = require('path');
|
|
5
|
+
var promises = require('readline/promises');
|
|
6
|
+
var promises$1 = require('fs/promises');
|
|
7
|
+
var os = require('os');
|
|
8
|
+
var child_process = require('child_process');
|
|
9
|
+
var crypto = require('crypto');
|
|
10
|
+
|
|
11
|
+
// src/cli/index.ts
|
|
12
|
+
|
|
13
|
+
// src/core/errors.ts
|
|
14
|
+
var EXIT_CODES = {
|
|
15
|
+
RUNTIME: 1,
|
|
16
|
+
USAGE: 2,
|
|
17
|
+
NOT_A_REPO: 3,
|
|
18
|
+
SECRET_UNAVAILABLE: 4,
|
|
19
|
+
NOT_FOUND: 5};
|
|
20
|
+
var AppError = class extends Error {
|
|
21
|
+
code;
|
|
22
|
+
exitCode;
|
|
23
|
+
hints;
|
|
24
|
+
constructor(init) {
|
|
25
|
+
super(init.message);
|
|
26
|
+
this.name = "AppError";
|
|
27
|
+
this.code = init.code;
|
|
28
|
+
this.exitCode = init.exitCode ?? EXIT_CODES.RUNTIME;
|
|
29
|
+
this.hints = init.hints;
|
|
30
|
+
}
|
|
31
|
+
toPayload() {
|
|
32
|
+
return { code: this.code, message: this.message, hints: this.hints, exitCode: this.exitCode };
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
var Errors = {
|
|
36
|
+
notARepo: (cwd) => new AppError({
|
|
37
|
+
code: "NOT_A_REPO",
|
|
38
|
+
message: cwd ? `not a git repository: ${cwd}` : "not a git repository",
|
|
39
|
+
exitCode: EXIT_CODES.NOT_A_REPO
|
|
40
|
+
}),
|
|
41
|
+
authorNotFound: (key) => new AppError({
|
|
42
|
+
code: "AUTHOR_NOT_FOUND",
|
|
43
|
+
message: `Author with initials "${key}" not found in .git-coauthors`,
|
|
44
|
+
exitCode: EXIT_CODES.NOT_FOUND,
|
|
45
|
+
hints: [`Add it with: git colabor coauthor add ${key} "Full Name" email@example.com`]
|
|
46
|
+
}),
|
|
47
|
+
duplicateKey: (key) => new AppError({
|
|
48
|
+
code: "DUPLICATE_KEY",
|
|
49
|
+
message: `Key "${key}" already exists in .git-coauthors`,
|
|
50
|
+
exitCode: EXIT_CODES.NOT_FOUND,
|
|
51
|
+
hints: ["Edit .git-coauthors directly to change an existing entry."]
|
|
52
|
+
}),
|
|
53
|
+
invalidEmail: (email) => new AppError({ code: "INVALID_EMAIL", message: `Invalid email: ${email}`, exitCode: EXIT_CODES.USAGE }),
|
|
54
|
+
usage: (message, hints) => new AppError({ code: "USAGE", message, exitCode: EXIT_CODES.USAGE, hints }),
|
|
55
|
+
secretUnavailable: (message, hints) => new AppError({ code: "SECRET_UNAVAILABLE", message, exitCode: EXIT_CODES.SECRET_UNAVAILABLE, hints })
|
|
56
|
+
};
|
|
57
|
+
function toErrorPayload(e) {
|
|
58
|
+
if (e instanceof AppError) return e.toPayload();
|
|
59
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
60
|
+
return { code: "INTERNAL", message, exitCode: EXIT_CODES.RUNTIME };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// src/cli/json.ts
|
|
64
|
+
function ok(data, warnings) {
|
|
65
|
+
return warnings && warnings.length > 0 ? { ok: true, data, warnings } : { ok: true, data };
|
|
66
|
+
}
|
|
67
|
+
function failFromError(e) {
|
|
68
|
+
return { ok: false, error: toErrorPayload(e), data: null };
|
|
69
|
+
}
|
|
70
|
+
function emit(result, opts) {
|
|
71
|
+
if (opts.json) {
|
|
72
|
+
process.stdout.write(JSON.stringify(result) + "\n");
|
|
73
|
+
} else if (opts.human) {
|
|
74
|
+
const txt = opts.human(result);
|
|
75
|
+
if (txt) {
|
|
76
|
+
const stream = result.ok ? process.stdout : process.stderr;
|
|
77
|
+
stream.write(txt.endsWith("\n") ? txt : `${txt}
|
|
78
|
+
`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
process.exit(result.ok ? 0 : result.error.exitCode);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// src/cli/parse-args.ts
|
|
85
|
+
function parseGlobals(argv) {
|
|
86
|
+
const flags = { json: false, noColor: false, help: false, version: false };
|
|
87
|
+
const rest = [];
|
|
88
|
+
for (let i = 0; i < argv.length; i++) {
|
|
89
|
+
const tok = argv[i];
|
|
90
|
+
if (!tok) continue;
|
|
91
|
+
if (tok === "--") {
|
|
92
|
+
rest.push(...argv.slice(i + 1));
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
if (tok === "-C") {
|
|
96
|
+
flags.cwd = argv[++i];
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (tok.startsWith("-C") && tok.length > 2) {
|
|
100
|
+
flags.cwd = tok.slice(2);
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (tok === "--log-level") {
|
|
104
|
+
flags.logLevel = argv[++i];
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if (tok.startsWith("--log-level=")) {
|
|
108
|
+
flags.logLevel = tok.slice("--log-level=".length);
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (tok === "--json") {
|
|
112
|
+
flags.json = true;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (tok === "--no-color") {
|
|
116
|
+
flags.noColor = true;
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (tok === "-h" || tok === "--help") {
|
|
120
|
+
flags.help = true;
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if (tok === "-v" || tok === "--version") {
|
|
124
|
+
flags.version = true;
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
rest.push(tok);
|
|
128
|
+
}
|
|
129
|
+
return { flags, rest };
|
|
130
|
+
}
|
|
131
|
+
function parseCommandArgs(tokens, spec = {}) {
|
|
132
|
+
const positionals = [];
|
|
133
|
+
const values = {};
|
|
134
|
+
const bools = /* @__PURE__ */ new Set();
|
|
135
|
+
const valueFlags = new Set(spec.valueFlags ?? []);
|
|
136
|
+
const boolFlags = new Set(spec.boolFlags ?? []);
|
|
137
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
138
|
+
const tok = tokens[i];
|
|
139
|
+
if (!tok) continue;
|
|
140
|
+
if (tok === "--") {
|
|
141
|
+
positionals.push(...tokens.slice(i + 1));
|
|
142
|
+
break;
|
|
143
|
+
}
|
|
144
|
+
if (tok.startsWith("--") && tok.includes("=")) {
|
|
145
|
+
const eq = tok.indexOf("=");
|
|
146
|
+
const k = tok.slice(0, eq);
|
|
147
|
+
const v = tok.slice(eq + 1);
|
|
148
|
+
if (valueFlags.has(k)) values[k] = v;
|
|
149
|
+
else bools.add(k);
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (valueFlags.has(tok)) {
|
|
153
|
+
const v = tokens[++i];
|
|
154
|
+
if (v !== void 0) values[tok] = v;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
if (boolFlags.has(tok)) {
|
|
158
|
+
bools.add(tok);
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (tok.startsWith("-")) {
|
|
162
|
+
bools.add(tok);
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
positionals.push(tok);
|
|
166
|
+
}
|
|
167
|
+
return { positionals, values, bools };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// src/cli/render.ts
|
|
171
|
+
function authorToJson(a) {
|
|
172
|
+
return { key: a.key, name: a.name, email: a.email };
|
|
173
|
+
}
|
|
174
|
+
function renderAuthors(authors) {
|
|
175
|
+
if (authors.length === 0) return "(none)";
|
|
176
|
+
const keyW = Math.max(2, ...authors.map((a) => a.key.length));
|
|
177
|
+
const nameW = Math.max(4, ...authors.map((a) => a.name.length));
|
|
178
|
+
return authors.map((a) => `${a.key.padEnd(keyW)} ${a.name.padEnd(nameW)} ${a.email}`).join("\n");
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// src/core/authors/types.ts
|
|
182
|
+
var CO_AUTHOR_TRAILER = "Co-authored-by:";
|
|
183
|
+
var Author = class {
|
|
184
|
+
constructor(key, name, email) {
|
|
185
|
+
this.key = key;
|
|
186
|
+
this.name = name;
|
|
187
|
+
this.email = email;
|
|
188
|
+
}
|
|
189
|
+
key;
|
|
190
|
+
name;
|
|
191
|
+
email;
|
|
192
|
+
/** `NAME <EMAIL>` */
|
|
193
|
+
toString() {
|
|
194
|
+
return `${this.name} <${this.email}>`;
|
|
195
|
+
}
|
|
196
|
+
/** `Co-authored-by: NAME <EMAIL>` */
|
|
197
|
+
format() {
|
|
198
|
+
return `${CO_AUTHOR_TRAILER} ${this.toString()}`;
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
function genKey(name, email) {
|
|
202
|
+
const initials = name.toLowerCase().split(/\s+/).filter(Boolean).map((w) => w[0] ?? "").join("");
|
|
203
|
+
return `${initials}${email.slice(0, 2)}`;
|
|
204
|
+
}
|
|
205
|
+
var GitError = class extends Error {
|
|
206
|
+
cmd;
|
|
207
|
+
exitCode;
|
|
208
|
+
stderr;
|
|
209
|
+
constructor(cmd, exitCode, stderr) {
|
|
210
|
+
super(`git ${cmd} failed (exit ${exitCode})${stderr ? ": " + stderr.trim() : ""}`);
|
|
211
|
+
this.name = "GitError";
|
|
212
|
+
this.cmd = cmd;
|
|
213
|
+
this.exitCode = exitCode;
|
|
214
|
+
this.stderr = stderr;
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
function run(args, opts) {
|
|
218
|
+
return new Promise((resolve4, reject) => {
|
|
219
|
+
const child = child_process.spawn("git", args, {
|
|
220
|
+
cwd: opts.cwd,
|
|
221
|
+
env: opts.env ? { ...process.env, ...opts.env } : process.env,
|
|
222
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
223
|
+
});
|
|
224
|
+
let stdout = "";
|
|
225
|
+
let stderr = "";
|
|
226
|
+
child.stdout.on("data", (d) => {
|
|
227
|
+
stdout += d.toString("utf8");
|
|
228
|
+
});
|
|
229
|
+
child.stderr.on("data", (d) => {
|
|
230
|
+
stderr += d.toString("utf8");
|
|
231
|
+
});
|
|
232
|
+
child.on("error", reject);
|
|
233
|
+
child.on("close", (code) => {
|
|
234
|
+
resolve4({ stdout, stderr, exitCode: code ?? 0 });
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
async function gitRaw(args, opts = {}) {
|
|
239
|
+
return run(args, opts);
|
|
240
|
+
}
|
|
241
|
+
async function git(args, opts = {}) {
|
|
242
|
+
const result = await run(args, opts);
|
|
243
|
+
if (result.exitCode !== 0) throw new GitError(args.join(" "), result.exitCode, result.stderr);
|
|
244
|
+
return result;
|
|
245
|
+
}
|
|
246
|
+
async function runBin(cmd, args, opts = {}) {
|
|
247
|
+
return new Promise((resolve4, reject) => {
|
|
248
|
+
const child = child_process.spawn(cmd, args, {
|
|
249
|
+
cwd: opts.cwd,
|
|
250
|
+
env: opts.env ? { ...process.env, ...opts.env } : process.env,
|
|
251
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
252
|
+
});
|
|
253
|
+
let stdout = "";
|
|
254
|
+
let stderr = "";
|
|
255
|
+
child.stdout.on("data", (d) => {
|
|
256
|
+
stdout += d.toString("utf8");
|
|
257
|
+
});
|
|
258
|
+
child.stderr.on("data", (d) => {
|
|
259
|
+
stderr += d.toString("utf8");
|
|
260
|
+
});
|
|
261
|
+
child.on("error", reject);
|
|
262
|
+
child.on("close", (code) => {
|
|
263
|
+
resolve4({ stdout, stderr, exitCode: code ?? 0 });
|
|
264
|
+
});
|
|
265
|
+
if (opts.input !== void 0) child.stdin.end(opts.input, "utf8");
|
|
266
|
+
else child.stdin.end();
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// src/core/git/rev.ts
|
|
271
|
+
async function insideWorkTree(cwd) {
|
|
272
|
+
const r = await gitRaw(["rev-parse", "--is-inside-work-tree"], { cwd });
|
|
273
|
+
return r.exitCode === 0 && r.stdout.trim() === "true";
|
|
274
|
+
}
|
|
275
|
+
async function topLevel(cwd) {
|
|
276
|
+
const r = await git(["rev-parse", "--show-toplevel"], { cwd });
|
|
277
|
+
return r.stdout.trim();
|
|
278
|
+
}
|
|
279
|
+
async function gitDir(cwd) {
|
|
280
|
+
const r = await git(["rev-parse", "--git-dir"], { cwd });
|
|
281
|
+
return path.resolve(cwd ?? process.cwd(), r.stdout.trim());
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// src/core/authors/store.ts
|
|
285
|
+
var COAUTHORS_FILENAME = ".git-coauthors";
|
|
286
|
+
var EMAIL_RE = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|((\w+\.)+[a-zA-Z]{2,}))$/;
|
|
287
|
+
function validateEmail(email) {
|
|
288
|
+
return EMAIL_RE.test(email);
|
|
289
|
+
}
|
|
290
|
+
function homeCoAuthorsPath() {
|
|
291
|
+
return path.join(os.homedir(), COAUTHORS_FILENAME);
|
|
292
|
+
}
|
|
293
|
+
async function coAuthorsPath(cwd) {
|
|
294
|
+
const envPath = process.env.GIT_COLABOR_COAUTHORS_PATH;
|
|
295
|
+
if (envPath) return path.resolve(envPath);
|
|
296
|
+
try {
|
|
297
|
+
const root = await topLevel(cwd);
|
|
298
|
+
const local = path.join(root, COAUTHORS_FILENAME);
|
|
299
|
+
if (fs.existsSync(local)) return local;
|
|
300
|
+
} catch {
|
|
301
|
+
}
|
|
302
|
+
return homeCoAuthorsPath();
|
|
303
|
+
}
|
|
304
|
+
async function readAuthors(cwd) {
|
|
305
|
+
const p = await coAuthorsPath(cwd);
|
|
306
|
+
const txt = await promises$1.readFile(p, "utf8");
|
|
307
|
+
const parsed = JSON.parse(txt);
|
|
308
|
+
if (!parsed || typeof parsed !== "object" || !parsed.coauthors) {
|
|
309
|
+
throw Errors.usage(`Invalid .git-coauthors at ${p}: missing "coauthors" object`);
|
|
310
|
+
}
|
|
311
|
+
return { coauthors: parsed.coauthors };
|
|
312
|
+
}
|
|
313
|
+
async function writeAuthors(schema, cwd) {
|
|
314
|
+
const p = await coAuthorsPath(cwd);
|
|
315
|
+
await promises$1.mkdir(path.dirname(p), { recursive: true });
|
|
316
|
+
await promises$1.writeFile(p, JSON.stringify(schema, null, 2) + "\n", "utf8");
|
|
317
|
+
}
|
|
318
|
+
function schemaToAuthors(schema) {
|
|
319
|
+
return Object.entries(schema.coauthors).map(([key, v]) => new Author(key, v.name, v.email));
|
|
320
|
+
}
|
|
321
|
+
async function listAuthors(filter, cwd) {
|
|
322
|
+
let schema;
|
|
323
|
+
try {
|
|
324
|
+
schema = await readAuthors(cwd);
|
|
325
|
+
} catch {
|
|
326
|
+
return [];
|
|
327
|
+
}
|
|
328
|
+
const all = schemaToAuthors(schema);
|
|
329
|
+
if (!filter) return all;
|
|
330
|
+
const f = filter.toLowerCase();
|
|
331
|
+
return all.filter(
|
|
332
|
+
(a) => a.key.toLowerCase().includes(f) || a.name.toLowerCase().includes(f) || a.email.toLowerCase().includes(f)
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
async function addCoAuthor(author, cwd) {
|
|
336
|
+
if (!validateEmail(author.email)) throw Errors.invalidEmail(author.email);
|
|
337
|
+
let schema;
|
|
338
|
+
try {
|
|
339
|
+
schema = await readAuthors(cwd);
|
|
340
|
+
} catch {
|
|
341
|
+
schema = { coauthors: {} };
|
|
342
|
+
}
|
|
343
|
+
if (Object.prototype.hasOwnProperty.call(schema.coauthors, author.key)) {
|
|
344
|
+
throw Errors.duplicateKey(author.key);
|
|
345
|
+
}
|
|
346
|
+
schema.coauthors[author.key] = { name: author.name, email: author.email };
|
|
347
|
+
await writeAuthors(schema, cwd);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// src/core/git/config.ts
|
|
351
|
+
function scopeArgs(scope) {
|
|
352
|
+
return scope ? [`--${scope}`] : [];
|
|
353
|
+
}
|
|
354
|
+
async function getConfig(key, scope, cwd) {
|
|
355
|
+
const r = await gitRaw(["config", ...scopeArgs(scope), "--get", key], { cwd });
|
|
356
|
+
if (r.exitCode !== 0) return void 0;
|
|
357
|
+
const v = r.stdout.trim();
|
|
358
|
+
return v.length > 0 ? v : void 0;
|
|
359
|
+
}
|
|
360
|
+
async function getAllConfig(key, scope, cwd) {
|
|
361
|
+
const r = await gitRaw(["config", ...scopeArgs(scope), "--get-all", key], { cwd });
|
|
362
|
+
return r.exitCode === 0 ? r.stdout.replace(/\s+$/, "") : "";
|
|
363
|
+
}
|
|
364
|
+
async function setConfig(key, value, scope, cwd) {
|
|
365
|
+
await git(["config", ...scopeArgs(scope), key, value], { cwd });
|
|
366
|
+
}
|
|
367
|
+
async function addConfigValue(key, value, scope, cwd) {
|
|
368
|
+
await git(["config", ...scopeArgs(scope), "--add", key, value], { cwd });
|
|
369
|
+
}
|
|
370
|
+
async function unsetConfig(key, scope, cwd) {
|
|
371
|
+
await gitRaw(["config", ...scopeArgs(scope), "--unset", key], { cwd });
|
|
372
|
+
}
|
|
373
|
+
async function unsetAllConfig(key, scope, cwd) {
|
|
374
|
+
await gitRaw(["config", ...scopeArgs(scope), "--unset-all", key], { cwd });
|
|
375
|
+
}
|
|
376
|
+
function formatMessage(txt, authors) {
|
|
377
|
+
const stripRe = new RegExp(`(\r
|
|
378
|
+
|\r|
|
|
379
|
+
){0,2}${CO_AUTHOR_TRAILER}.*`, "g");
|
|
380
|
+
const message = txt.replace(stripRe, "");
|
|
381
|
+
if (authors && authors.length > 0) {
|
|
382
|
+
const trailerText = authors.map((a) => a.format()).join(os.EOL);
|
|
383
|
+
return [message, os.EOL, os.EOL, trailerText].join("");
|
|
384
|
+
}
|
|
385
|
+
return message;
|
|
386
|
+
}
|
|
387
|
+
function printTrailers(authors) {
|
|
388
|
+
if (authors.length === 0) return "";
|
|
389
|
+
return os.EOL + os.EOL + authors.map((a) => a.format()).join(os.EOL);
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// src/core/message/template.ts
|
|
393
|
+
function gitMessagePath() {
|
|
394
|
+
return path.join(os.homedir(), ".gitmessage");
|
|
395
|
+
}
|
|
396
|
+
async function resolveTemplatePath(templatePath, cwd) {
|
|
397
|
+
if (process.env.GIT_COLABOR_MESSAGE_PATH) return path.resolve(process.env.GIT_COLABOR_MESSAGE_PATH);
|
|
398
|
+
if (templatePath) return path.resolve(await topLevel(cwd), templatePath);
|
|
399
|
+
return gitMessagePath();
|
|
400
|
+
}
|
|
401
|
+
async function ensureCommitTemplate(cwd) {
|
|
402
|
+
const has = await getConfig("commit.template", void 0, cwd);
|
|
403
|
+
if (!has) await setConfig("commit.template", gitMessagePath(), "global", cwd);
|
|
404
|
+
}
|
|
405
|
+
async function readMsg(p) {
|
|
406
|
+
try {
|
|
407
|
+
return await promises$1.readFile(p, "utf8");
|
|
408
|
+
} catch {
|
|
409
|
+
return "";
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
async function writeMsg(p, txt) {
|
|
413
|
+
await promises$1.mkdir(path.dirname(p), { recursive: true });
|
|
414
|
+
await promises$1.writeFile(p, txt, "utf8");
|
|
415
|
+
}
|
|
416
|
+
async function applyToTemplate(authors, cwd) {
|
|
417
|
+
const [localTpl, firstTpl] = await Promise.all([
|
|
418
|
+
getConfig("commit.template", "local", cwd),
|
|
419
|
+
getConfig("commit.template", void 0, cwd)
|
|
420
|
+
]);
|
|
421
|
+
const primaryPath = await resolveTemplatePath(firstTpl ?? void 0, cwd);
|
|
422
|
+
await writeMsg(primaryPath, formatMessage(await readMsg(primaryPath), authors));
|
|
423
|
+
if (localTpl) {
|
|
424
|
+
const globalTpl = await getConfig("commit.template", "global", cwd) ?? gitMessagePath();
|
|
425
|
+
const globalPath = await resolveTemplatePath(globalTpl, cwd);
|
|
426
|
+
await writeMsg(globalPath, formatMessage(await readMsg(globalPath), authors));
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
async function writeCoAuthorsToTemplate(authors, cwd) {
|
|
430
|
+
await applyToTemplate(authors, cwd);
|
|
431
|
+
}
|
|
432
|
+
async function clearTemplate(cwd) {
|
|
433
|
+
await applyToTemplate([], cwd);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// src/core/coauthors/state.ts
|
|
437
|
+
var KEY = "colabor.selected";
|
|
438
|
+
var LINE_RE = /^(.*)\s<([^>]+)>$/;
|
|
439
|
+
async function getSelected(cwd) {
|
|
440
|
+
const raw = (await getAllConfig(KEY, "local", cwd)).split(/\r?\n/).filter(Boolean);
|
|
441
|
+
if (raw.length === 0) return [];
|
|
442
|
+
const all = await listAuthors(void 0, cwd);
|
|
443
|
+
const out = [];
|
|
444
|
+
for (const line of raw) {
|
|
445
|
+
const m = line.match(LINE_RE);
|
|
446
|
+
if (!m) continue;
|
|
447
|
+
const name = m[1].trim();
|
|
448
|
+
const email = m[2].trim();
|
|
449
|
+
const found = all.find((a) => a.email === email);
|
|
450
|
+
out.push(found ?? new Author(email.split("@")[0] || "co", name, email));
|
|
451
|
+
}
|
|
452
|
+
return out;
|
|
453
|
+
}
|
|
454
|
+
async function setSelected(authors, cwd) {
|
|
455
|
+
await unsetAllConfig(KEY, "local", cwd);
|
|
456
|
+
for (const a of authors) await addConfigValue(KEY, a.toString(), "local", cwd);
|
|
457
|
+
await ensureCommitTemplate(cwd);
|
|
458
|
+
await writeCoAuthorsToTemplate(authors, cwd);
|
|
459
|
+
}
|
|
460
|
+
async function clearSelected(cwd) {
|
|
461
|
+
await unsetAllConfig(KEY, "local", cwd);
|
|
462
|
+
await ensureCommitTemplate(cwd);
|
|
463
|
+
await clearTemplate(cwd);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// src/core/git/shortlog.ts
|
|
467
|
+
var SHORTLOG_LINE = /^\d+\t(.+)\s<(.+)>$/;
|
|
468
|
+
async function repoAuthors(filter, cwd) {
|
|
469
|
+
const args = ["shortlog", "-seni", "HEAD"];
|
|
470
|
+
if (filter) args.splice(1, 0, `--author=${filter}`);
|
|
471
|
+
const r = await gitRaw(args, { cwd });
|
|
472
|
+
if (r.exitCode !== 0) return [];
|
|
473
|
+
const out = [];
|
|
474
|
+
for (const line of r.stdout.split(/\r?\n/)) {
|
|
475
|
+
const m = line.match(SHORTLOG_LINE);
|
|
476
|
+
if (!m) continue;
|
|
477
|
+
const name = m[1].trim();
|
|
478
|
+
const email = m[2].trim();
|
|
479
|
+
out.push(new Author(genKey(name, email), name, email));
|
|
480
|
+
}
|
|
481
|
+
return out;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// src/cli/coauthor.ts
|
|
485
|
+
async function requireRepo(cwd) {
|
|
486
|
+
if (!await insideWorkTree(cwd)) throw Errors.notARepo(cwd);
|
|
487
|
+
}
|
|
488
|
+
async function prompt(question) {
|
|
489
|
+
const rl = promises.createInterface({ input: process.stdin, output: process.stderr });
|
|
490
|
+
try {
|
|
491
|
+
return (await rl.question(question)).trim();
|
|
492
|
+
} finally {
|
|
493
|
+
rl.close();
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
async function ls(args, cwd) {
|
|
497
|
+
const authors = await listAuthors(args[0], cwd);
|
|
498
|
+
return ok(authors.map(authorToJson));
|
|
499
|
+
}
|
|
500
|
+
async function use(args, cwd) {
|
|
501
|
+
await requireRepo(cwd);
|
|
502
|
+
if (args.length === 0) {
|
|
503
|
+
const selected2 = await getSelected(cwd);
|
|
504
|
+
const data = { selected: selected2.map(authorToJson) };
|
|
505
|
+
return selected2.length === 0 ? ok(data, [{ code: "empty", message: "no co-authors selected" }]) : ok(data);
|
|
506
|
+
}
|
|
507
|
+
const all = await listAuthors(void 0, cwd);
|
|
508
|
+
const selected = [];
|
|
509
|
+
for (const k of args) {
|
|
510
|
+
const found = all.find((a) => a.key === k);
|
|
511
|
+
if (!found) throw Errors.authorNotFound(k);
|
|
512
|
+
selected.push(found);
|
|
513
|
+
}
|
|
514
|
+
await setSelected(selected, cwd);
|
|
515
|
+
return ok({ selected: selected.map(authorToJson) });
|
|
516
|
+
}
|
|
517
|
+
async function solo(cwd) {
|
|
518
|
+
await requireRepo(cwd);
|
|
519
|
+
await clearSelected(cwd);
|
|
520
|
+
return ok({ selected: [] });
|
|
521
|
+
}
|
|
522
|
+
async function print(opts, cwd) {
|
|
523
|
+
const selected = await getSelected(cwd);
|
|
524
|
+
const text = opts.initials ? selected.map((a) => a.key).join(",") : printTrailers(selected);
|
|
525
|
+
return ok({ text });
|
|
526
|
+
}
|
|
527
|
+
async function add(args, cwd) {
|
|
528
|
+
const [key, name, email] = args;
|
|
529
|
+
if (!key || !name || !email) {
|
|
530
|
+
throw Errors.usage('git colabor coauthor add <initials> "Name" <email>');
|
|
531
|
+
}
|
|
532
|
+
if (!validateEmail(email)) throw Errors.invalidEmail(email);
|
|
533
|
+
const author = new Author(key, name, email);
|
|
534
|
+
await addCoAuthor(author, cwd);
|
|
535
|
+
return ok({ author: authorToJson(author) });
|
|
536
|
+
}
|
|
537
|
+
async function suggest(args, cwd) {
|
|
538
|
+
await requireRepo(cwd);
|
|
539
|
+
const candidates = await repoAuthors(args[0], cwd);
|
|
540
|
+
if (candidates.length === 0) {
|
|
541
|
+
return ok({ candidates: [], added: [] }, [
|
|
542
|
+
{ code: "none", message: "no contributors found" }
|
|
543
|
+
]);
|
|
544
|
+
}
|
|
545
|
+
return ok({ candidates: candidates.map(authorToJson), added: [] });
|
|
546
|
+
}
|
|
547
|
+
async function suggestInteractive(args, cwd) {
|
|
548
|
+
await requireRepo(cwd);
|
|
549
|
+
const candidates = await repoAuthors(args[0], cwd);
|
|
550
|
+
if (candidates.length === 0) {
|
|
551
|
+
process.stderr.write("No contributors found.\n");
|
|
552
|
+
return ok({ added: [] });
|
|
553
|
+
}
|
|
554
|
+
process.stderr.write(
|
|
555
|
+
candidates.map((a, i) => `[${i}] ${a.name} <${a.email}>`).join("\n") + "\n"
|
|
556
|
+
);
|
|
557
|
+
const answer = await prompt("Add which? (comma-separated numbers, blank to skip) ");
|
|
558
|
+
const added = [];
|
|
559
|
+
for (const part of answer.split(",")) {
|
|
560
|
+
const idx = Number(part.trim());
|
|
561
|
+
if (Number.isInteger(idx) && idx >= 0 && idx < candidates.length) {
|
|
562
|
+
added.push(candidates[idx]);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
for (const a of added) {
|
|
566
|
+
try {
|
|
567
|
+
await addCoAuthor(a, cwd);
|
|
568
|
+
} catch (e) {
|
|
569
|
+
if (!(e instanceof AppError && e.code === "DUPLICATE_KEY")) throw e;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
return ok({ added: added.map(authorToJson) });
|
|
573
|
+
}
|
|
574
|
+
function dataDir() {
|
|
575
|
+
if (process.platform === "win32") {
|
|
576
|
+
return path.join(process.env.APPDATA ?? path.join(os.homedir(), "AppData", "Roaming"), "git-colabor");
|
|
577
|
+
}
|
|
578
|
+
return path.join(process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config"), "git-colabor");
|
|
579
|
+
}
|
|
580
|
+
function mapPath() {
|
|
581
|
+
return process.env.GIT_COLABOR_MAP ?? path.join(dataDir(), "identities.json");
|
|
582
|
+
}
|
|
583
|
+
function keysDir() {
|
|
584
|
+
return path.join(dataDir(), "keys");
|
|
585
|
+
}
|
|
586
|
+
function auditLogPath() {
|
|
587
|
+
return process.env.GIT_COLABOR_AUDIT_FILE ?? path.join(dataDir(), "audit.log");
|
|
588
|
+
}
|
|
589
|
+
function keyFileName(fingerprint) {
|
|
590
|
+
return fingerprint.replace(/[^A-Za-z0-9]+/g, "_") + ".key";
|
|
591
|
+
}
|
|
592
|
+
function keyFilePath(fingerprint) {
|
|
593
|
+
return path.join(keysDir(), keyFileName(fingerprint));
|
|
594
|
+
}
|
|
595
|
+
async function atomicWriteJson(path$1, data, mode) {
|
|
596
|
+
await promises$1.mkdir(path.dirname(path$1), { recursive: true });
|
|
597
|
+
const tmp = `${path$1}.${crypto.randomBytes(4).toString("hex")}.tmp`;
|
|
598
|
+
await promises$1.writeFile(tmp, JSON.stringify(data, null, 2) + "\n", "utf8");
|
|
599
|
+
{
|
|
600
|
+
await promises$1.chmod(tmp, mode).catch(() => {
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
await promises$1.rename(tmp, path$1);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// src/core/identity/map.ts
|
|
607
|
+
function genId() {
|
|
608
|
+
return "id_" + crypto.randomBytes(4).toString("hex");
|
|
609
|
+
}
|
|
610
|
+
async function readMap() {
|
|
611
|
+
try {
|
|
612
|
+
const txt = await promises$1.readFile(mapPath(), "utf8");
|
|
613
|
+
const parsed = JSON.parse(txt);
|
|
614
|
+
return {
|
|
615
|
+
schemaVersion: 1,
|
|
616
|
+
identities: parsed.identities ?? {},
|
|
617
|
+
defaultIdentity: parsed.defaultIdentity
|
|
618
|
+
};
|
|
619
|
+
} catch {
|
|
620
|
+
return { schemaVersion: 1, identities: {} };
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
async function writeMap(map) {
|
|
624
|
+
await atomicWriteJson(mapPath(), map, 384);
|
|
625
|
+
}
|
|
626
|
+
async function getIdentity(id) {
|
|
627
|
+
const map = await readMap();
|
|
628
|
+
const found = map.identities[id];
|
|
629
|
+
if (!found) throw Errors.usage(`identity "${id}" not found`);
|
|
630
|
+
return found;
|
|
631
|
+
}
|
|
632
|
+
async function addIdentity(input) {
|
|
633
|
+
const map = await readMap();
|
|
634
|
+
const id = input.id ?? genId();
|
|
635
|
+
if (map.identities[id]) throw Errors.usage(`identity "${id}" already exists`);
|
|
636
|
+
const identity = { ...input, id, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
637
|
+
map.identities[id] = identity;
|
|
638
|
+
await writeMap(map);
|
|
639
|
+
return identity;
|
|
640
|
+
}
|
|
641
|
+
async function removeIdentity(id) {
|
|
642
|
+
const map = await readMap();
|
|
643
|
+
if (!map.identities[id]) throw Errors.usage(`identity "${id}" not found`);
|
|
644
|
+
delete map.identities[id];
|
|
645
|
+
if (map.defaultIdentity === id) delete map.defaultIdentity;
|
|
646
|
+
await writeMap(map);
|
|
647
|
+
}
|
|
648
|
+
async function setDefault(id) {
|
|
649
|
+
const map = await readMap();
|
|
650
|
+
if (!map.identities[id]) throw Errors.usage(`identity "${id}" not found`);
|
|
651
|
+
map.defaultIdentity = id;
|
|
652
|
+
await writeMap(map);
|
|
653
|
+
}
|
|
654
|
+
async function listIdentities() {
|
|
655
|
+
const map = await readMap();
|
|
656
|
+
return { identities: Object.values(map.identities), defaultIdentity: map.defaultIdentity };
|
|
657
|
+
}
|
|
658
|
+
var FP_RE = /SHA256:[A-Za-z0-9+/=]+/;
|
|
659
|
+
async function fingerprintOfFile(path) {
|
|
660
|
+
const r = await runBin("ssh-keygen", ["-lf", path]);
|
|
661
|
+
if (r.exitCode !== 0) {
|
|
662
|
+
throw new AppError({
|
|
663
|
+
code: "KEY_READ_FAILED",
|
|
664
|
+
message: `cannot read key fingerprint: ${r.stderr.trim() || "ssh-keygen failed"}`
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
const m = r.stdout.match(FP_RE);
|
|
668
|
+
if (!m) throw new AppError({ code: "KEY_READ_FAILED", message: `unparseable ssh-keygen output: ${r.stdout}` });
|
|
669
|
+
return m[0];
|
|
670
|
+
}
|
|
671
|
+
async function isEncrypted(path) {
|
|
672
|
+
const r = await runBin("ssh-keygen", ["-y", "-P", "", "-f", path]);
|
|
673
|
+
return r.exitCode !== 0;
|
|
674
|
+
}
|
|
675
|
+
async function restrictKeyPerms(path) {
|
|
676
|
+
if (process.platform === "win32") {
|
|
677
|
+
const user = process.env.USERNAME ?? process.env.USER ?? "";
|
|
678
|
+
if (user) {
|
|
679
|
+
await runBin("icacls", [path, "/inheritance:r", "/grant:r", `${user}:(R,W)`]).catch(() => {
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
await promises$1.chmod(path, 384).catch(() => {
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
async function materializeKey(privateKeyPem) {
|
|
688
|
+
await promises$1.mkdir(keysDir(), { recursive: true });
|
|
689
|
+
const tmp = path.join(keysDir(), `.import.${crypto.randomBytes(4).toString("hex")}`);
|
|
690
|
+
await promises$1.writeFile(tmp, privateKeyPem.endsWith("\n") ? privateKeyPem : privateKeyPem + "\n", "utf8");
|
|
691
|
+
await restrictKeyPerms(tmp);
|
|
692
|
+
const fingerprint = await fingerprintOfFile(tmp);
|
|
693
|
+
const dest = keyFilePath(fingerprint);
|
|
694
|
+
await promises$1.rename(tmp, dest);
|
|
695
|
+
await restrictKeyPerms(dest);
|
|
696
|
+
return { path: dest, fingerprint };
|
|
697
|
+
}
|
|
698
|
+
async function importKey(sourcePath) {
|
|
699
|
+
const pem = await promises$1.readFile(sourcePath, "utf8");
|
|
700
|
+
const { path, fingerprint } = await materializeKey(pem);
|
|
701
|
+
const encrypted = await isEncrypted(path);
|
|
702
|
+
return { path, fingerprint, encrypted };
|
|
703
|
+
}
|
|
704
|
+
async function statePath(cwd) {
|
|
705
|
+
return path.join(await gitDir(cwd), "colabor", "state.json");
|
|
706
|
+
}
|
|
707
|
+
async function readState(cwd) {
|
|
708
|
+
try {
|
|
709
|
+
const p = await statePath(cwd);
|
|
710
|
+
const txt = await promises$1.readFile(p, "utf8");
|
|
711
|
+
return JSON.parse(txt);
|
|
712
|
+
} catch {
|
|
713
|
+
return { schemaVersion: 1 };
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
async function writeState(state, cwd) {
|
|
717
|
+
const p = await statePath(cwd);
|
|
718
|
+
await atomicWriteJson(p, state, 384);
|
|
719
|
+
}
|
|
720
|
+
async function readCurrentIdentityConfig(cwd) {
|
|
721
|
+
const [userName, userEmail, sshCommand, commitTemplate] = await Promise.all([
|
|
722
|
+
getConfig("user.name", "local", cwd),
|
|
723
|
+
getConfig("user.email", "local", cwd),
|
|
724
|
+
getConfig("core.sshCommand", "local", cwd),
|
|
725
|
+
getConfig("commit.template", "local", cwd)
|
|
726
|
+
]);
|
|
727
|
+
return { userName, userEmail, sshCommand, commitTemplate };
|
|
728
|
+
}
|
|
729
|
+
async function captureBackupIfFirstTouch(cwd) {
|
|
730
|
+
const managed = await getConfig("colabor.managed", "local", cwd);
|
|
731
|
+
const state = await readState(cwd);
|
|
732
|
+
if (managed === "true" || state.backups) return state;
|
|
733
|
+
state.backups = await readCurrentIdentityConfig(cwd);
|
|
734
|
+
await writeState(state, cwd);
|
|
735
|
+
return state;
|
|
736
|
+
}
|
|
737
|
+
function isStale(heldBy, staleMinutes) {
|
|
738
|
+
const ageMs = Date.now() - new Date(heldBy.since).getTime();
|
|
739
|
+
return ageMs > staleMinutes * 6e4;
|
|
740
|
+
}
|
|
741
|
+
async function detectConflict(session, cwd, staleMinutes = 5) {
|
|
742
|
+
const st = await readState(cwd);
|
|
743
|
+
const hb = st.heldBy;
|
|
744
|
+
if (!hb || hb.session === session) return null;
|
|
745
|
+
if (isStale(hb, staleMinutes)) return null;
|
|
746
|
+
return { heldBy: hb };
|
|
747
|
+
}
|
|
748
|
+
function cliSessionId() {
|
|
749
|
+
return `cli:${process.pid}@${os.hostname()}`;
|
|
750
|
+
}
|
|
751
|
+
function nowHeldBy(session, source) {
|
|
752
|
+
return {
|
|
753
|
+
session,
|
|
754
|
+
since: (/* @__PURE__ */ new Date()).toISOString(),
|
|
755
|
+
host: os.hostname(),
|
|
756
|
+
osUser: os.userInfo().username,
|
|
757
|
+
source
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
async function appendAudit(input) {
|
|
761
|
+
const entry = {
|
|
762
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
763
|
+
action: input.action,
|
|
764
|
+
identity: input.identity,
|
|
765
|
+
identityName: input.identityName,
|
|
766
|
+
fingerprint: input.fingerprint,
|
|
767
|
+
repo: input.repo,
|
|
768
|
+
sha: input.sha,
|
|
769
|
+
host: os.hostname(),
|
|
770
|
+
osUser: os.userInfo().username,
|
|
771
|
+
source: input.source,
|
|
772
|
+
result: input.result ?? "ok",
|
|
773
|
+
message: input.message
|
|
774
|
+
};
|
|
775
|
+
const file = auditLogPath();
|
|
776
|
+
try {
|
|
777
|
+
await promises$1.mkdir(path.dirname(file), { recursive: true });
|
|
778
|
+
await promises$1.appendFile(file, JSON.stringify(entry) + "\n", "utf8");
|
|
779
|
+
await promises$1.chmod(file, 384).catch(() => {
|
|
780
|
+
});
|
|
781
|
+
} catch {
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
async function readAudit(opts = {}) {
|
|
785
|
+
try {
|
|
786
|
+
const txt = await promises$1.readFile(auditLogPath(), "utf8");
|
|
787
|
+
let entries = txt.split(/\r?\n/).filter(Boolean).map((l) => JSON.parse(l));
|
|
788
|
+
if (opts.repo) entries = entries.filter((e) => e.repo === opts.repo);
|
|
789
|
+
if (opts.since) {
|
|
790
|
+
const t = new Date(opts.since).getTime();
|
|
791
|
+
entries = entries.filter((e) => new Date(e.ts).getTime() >= t);
|
|
792
|
+
}
|
|
793
|
+
if (opts.tail && opts.tail > 0) entries = entries.slice(-opts.tail);
|
|
794
|
+
return entries;
|
|
795
|
+
} catch {
|
|
796
|
+
return [];
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
function runInherit(cmdArgs, env, stdinNull = false) {
|
|
800
|
+
return new Promise((resolve4) => {
|
|
801
|
+
const [cmd, ...args] = cmdArgs;
|
|
802
|
+
const child = child_process.spawn(cmd, args, {
|
|
803
|
+
env: env ?? process.env,
|
|
804
|
+
stdio: [stdinNull ? "ignore" : "inherit", "inherit", "pipe"]
|
|
805
|
+
});
|
|
806
|
+
child.on("error", () => resolve4(127));
|
|
807
|
+
child.on("close", (c) => resolve4(c ?? 127));
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
function hasBin(bin) {
|
|
811
|
+
if (process.platform === "win32") {
|
|
812
|
+
return child_process.spawnSync("where", [bin]).status === 0;
|
|
813
|
+
}
|
|
814
|
+
return child_process.spawnSync(`command -v ${bin}`, { shell: true }).status === 0;
|
|
815
|
+
}
|
|
816
|
+
async function supportsAppleKeychain() {
|
|
817
|
+
if (process.platform !== "darwin") return false;
|
|
818
|
+
const r = await runBinQuiet("ssh-add", ["-h"]);
|
|
819
|
+
return r.includes("--apple-use-keychain");
|
|
820
|
+
}
|
|
821
|
+
async function runBinQuiet(cmd, args) {
|
|
822
|
+
return new Promise((resolve4) => {
|
|
823
|
+
const child = child_process.spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
824
|
+
let out = "";
|
|
825
|
+
child.stdout.on("data", (d) => {
|
|
826
|
+
out += d.toString("utf8");
|
|
827
|
+
});
|
|
828
|
+
child.on("error", () => resolve4(""));
|
|
829
|
+
child.on("close", () => resolve4(out));
|
|
830
|
+
});
|
|
831
|
+
}
|
|
832
|
+
async function loadKey(opts) {
|
|
833
|
+
if (!fs.existsSync(opts.keyPath)) return { loaded: false, via: "none", message: "key file missing" };
|
|
834
|
+
let code = await runInherit(["ssh-add", opts.keyPath], void 0, !process.stdin.isTTY);
|
|
835
|
+
if (code === 0) return { loaded: true, via: "plain" };
|
|
836
|
+
if (await supportsAppleKeychain()) {
|
|
837
|
+
code = await runInherit(["ssh-add", "--apple-use-keychain", opts.keyPath]);
|
|
838
|
+
if (code === 0) return { loaded: true, via: "apple-keychain" };
|
|
839
|
+
}
|
|
840
|
+
const haveSource = opts.socketPath && opts.token || opts.passphraseCommand;
|
|
841
|
+
if (opts.askpassScriptPath && haveSource) {
|
|
842
|
+
const env = { ...process.env };
|
|
843
|
+
env.SSH_ASKPASS = opts.askpassScriptPath;
|
|
844
|
+
env.SSH_ASKPASS_REQUIRE = "force";
|
|
845
|
+
env.DISPLAY = env.DISPLAY ?? ":0";
|
|
846
|
+
if (opts.socketPath) env.GIT_COLABOR_ASKPASS_SOCK = opts.socketPath;
|
|
847
|
+
if (opts.token) env.GIT_COLABOR_ASKPASS_TOKEN = opts.token;
|
|
848
|
+
if (opts.passphraseCommand) env.GIT_COLABOR_PASSPHRASE_COMMAND = opts.passphraseCommand;
|
|
849
|
+
env.GIT_COLABOR_FINGERPRINT = opts.fingerprint;
|
|
850
|
+
const useSetsid = process.platform !== "win32" && hasBin("setsid");
|
|
851
|
+
code = await runInherit(useSetsid ? ["setsid", "ssh-add", opts.keyPath] : ["ssh-add", opts.keyPath], env, true);
|
|
852
|
+
if (code === 0) return { loaded: true, via: "askpass" };
|
|
853
|
+
return { loaded: false, via: "askpass", message: `ssh-add exited ${code}` };
|
|
854
|
+
}
|
|
855
|
+
if (process.stdin.isTTY) {
|
|
856
|
+
code = await runInherit(["ssh-add", opts.keyPath]);
|
|
857
|
+
if (code === 0) return { loaded: true, via: "tty" };
|
|
858
|
+
return { loaded: false, via: "tty", message: `ssh-add exited ${code}` };
|
|
859
|
+
}
|
|
860
|
+
return { loaded: false, via: "none", message: "no passphrase source and no tty" };
|
|
861
|
+
}
|
|
862
|
+
async function listAgent() {
|
|
863
|
+
return runBinQuiet("ssh-add", ["-l"]);
|
|
864
|
+
}
|
|
865
|
+
async function removeKey(keyPath) {
|
|
866
|
+
const code = await runInherit(["ssh-add", "-d", keyPath], void 0, true);
|
|
867
|
+
return code === 0;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// src/core/identity/apply.ts
|
|
871
|
+
async function safeTopLevel(cwd) {
|
|
872
|
+
try {
|
|
873
|
+
return await topLevel(cwd);
|
|
874
|
+
} catch {
|
|
875
|
+
return void 0;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
async function applyResolvedIdentity(args) {
|
|
879
|
+
const { name, email, sshCommand, identity, opts } = args;
|
|
880
|
+
const session = opts.session ?? (opts.source === "cli" ? cliSessionId() : "ext:unknown");
|
|
881
|
+
const conflict = await detectConflict(session, opts.cwd, opts.staleMinutes);
|
|
882
|
+
if (conflict && opts.noOverride) {
|
|
883
|
+
throw new AppError({
|
|
884
|
+
code: "CONFLICT_BLOCKED",
|
|
885
|
+
message: `repo is held by ${conflict.heldBy.session} (since ${conflict.heldBy.since})`,
|
|
886
|
+
exitCode: 6,
|
|
887
|
+
hints: ["re-run without --no-override to take over"]
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
await captureBackupIfFirstTouch(opts.cwd);
|
|
891
|
+
await setConfig("user.name", name, "local", opts.cwd);
|
|
892
|
+
await setConfig("user.email", email, "local", opts.cwd);
|
|
893
|
+
if (sshCommand) await setConfig("core.sshCommand", sshCommand, "local", opts.cwd);
|
|
894
|
+
await setConfig("colabor.managed", "true", "local", opts.cwd);
|
|
895
|
+
await setConfig("colabor.managed-by", opts.source, "local", opts.cwd);
|
|
896
|
+
const state = await readState(opts.cwd);
|
|
897
|
+
state.activeIdentity = identity?.id;
|
|
898
|
+
state.heldBy = nowHeldBy(session, opts.source);
|
|
899
|
+
await writeState(state, opts.cwd);
|
|
900
|
+
let keyLoaded;
|
|
901
|
+
if (identity?.sshKeyPath && identity.sshKeyFingerprint) {
|
|
902
|
+
keyLoaded = await loadKey({
|
|
903
|
+
keyPath: identity.sshKeyPath,
|
|
904
|
+
fingerprint: identity.sshKeyFingerprint,
|
|
905
|
+
askpassScriptPath: opts.askpassScriptPath,
|
|
906
|
+
socketPath: opts.socketPath,
|
|
907
|
+
token: opts.token,
|
|
908
|
+
passphraseCommand: identity.passphraseCommand});
|
|
909
|
+
}
|
|
910
|
+
await appendAudit({
|
|
911
|
+
action: "identity.use",
|
|
912
|
+
source: opts.source,
|
|
913
|
+
identity: identity?.id,
|
|
914
|
+
identityName: identity?.name ?? name,
|
|
915
|
+
fingerprint: identity?.sshKeyFingerprint,
|
|
916
|
+
repo: await safeTopLevel(opts.cwd),
|
|
917
|
+
result: conflict ? "warn" : "ok",
|
|
918
|
+
message: conflict ? `overrode ${conflict.heldBy.session}` : void 0
|
|
919
|
+
});
|
|
920
|
+
return { name, email, sshCommand, conflict, keyLoaded };
|
|
921
|
+
}
|
|
922
|
+
async function applyIdentity(id, opts) {
|
|
923
|
+
const identity = await getIdentity(id);
|
|
924
|
+
const sshCommand = identity.sshKeyPath ? `ssh -i ${identity.sshKeyPath} -o IdentitiesOnly=yes` : void 0;
|
|
925
|
+
const result = await applyResolvedIdentity({
|
|
926
|
+
name: opts.asName ?? identity.name,
|
|
927
|
+
email: opts.asEmail ?? identity.email,
|
|
928
|
+
sshCommand,
|
|
929
|
+
identity,
|
|
930
|
+
opts
|
|
931
|
+
});
|
|
932
|
+
return { identity, result };
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
// src/core/identity/revert.ts
|
|
936
|
+
async function safeTopLevel2(cwd) {
|
|
937
|
+
try {
|
|
938
|
+
return await topLevel(cwd);
|
|
939
|
+
} catch {
|
|
940
|
+
return void 0;
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
async function restoreKey(key, value, cwd) {
|
|
944
|
+
if (value === void 0) await unsetConfig(key, "local", cwd);
|
|
945
|
+
else await setConfig(key, value, "local", cwd);
|
|
946
|
+
}
|
|
947
|
+
async function revertRepo(opts) {
|
|
948
|
+
const state = await readState(opts.cwd);
|
|
949
|
+
const backups = state.backups;
|
|
950
|
+
const managed = await getConfig("colabor.managed", "local", opts.cwd);
|
|
951
|
+
if (backups) {
|
|
952
|
+
await restoreKey("user.name", backups.userName, opts.cwd);
|
|
953
|
+
await restoreKey("user.email", backups.userEmail, opts.cwd);
|
|
954
|
+
await restoreKey("core.sshCommand", backups.sshCommand, opts.cwd);
|
|
955
|
+
await restoreKey("commit.template", backups.commitTemplate, opts.cwd);
|
|
956
|
+
}
|
|
957
|
+
if (state.activeIdentity) {
|
|
958
|
+
try {
|
|
959
|
+
const id = await getIdentity(state.activeIdentity);
|
|
960
|
+
if (id.sshKeyPath) await removeKey(id.sshKeyPath);
|
|
961
|
+
} catch {
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
await unsetConfig("colabor.managed", "local", opts.cwd);
|
|
965
|
+
await unsetConfig("colabor.managed-by", "local", opts.cwd);
|
|
966
|
+
await unsetAllConfig("colabor.selected", "local", opts.cwd);
|
|
967
|
+
await clearTemplate(opts.cwd).catch(() => {
|
|
968
|
+
});
|
|
969
|
+
state.activeIdentity = void 0;
|
|
970
|
+
state.backups = void 0;
|
|
971
|
+
state.heldBy = void 0;
|
|
972
|
+
await writeState(state, opts.cwd);
|
|
973
|
+
await appendAudit({
|
|
974
|
+
action: "identity.revert",
|
|
975
|
+
source: opts.source,
|
|
976
|
+
repo: await safeTopLevel2(opts.cwd),
|
|
977
|
+
result: managed === "true" ? "ok" : "warn",
|
|
978
|
+
message: managed === "true" ? void 0 : "repo was not managed"
|
|
979
|
+
});
|
|
980
|
+
return { restored: backups, hadBackup: !!backups };
|
|
981
|
+
}
|
|
982
|
+
async function safeTopLevel3(cwd) {
|
|
983
|
+
try {
|
|
984
|
+
return await topLevel(cwd);
|
|
985
|
+
} catch {
|
|
986
|
+
return void 0;
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
async function shred(path) {
|
|
990
|
+
if (process.platform !== "win32") {
|
|
991
|
+
const r = child_process.spawnSync("shred", ["-u", path]);
|
|
992
|
+
if (r.status === 0) return true;
|
|
993
|
+
}
|
|
994
|
+
try {
|
|
995
|
+
await promises$1.unlink(path);
|
|
996
|
+
return true;
|
|
997
|
+
} catch {
|
|
998
|
+
return false;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
async function logoutIdentity(opts) {
|
|
1002
|
+
const state = await readState(opts.cwd);
|
|
1003
|
+
let id = opts.id ?? state.activeIdentity;
|
|
1004
|
+
if (!id) {
|
|
1005
|
+
const { identities } = await listIdentities();
|
|
1006
|
+
if (identities.length === 1) id = identities[0].id;
|
|
1007
|
+
else throw Errors.usage("no active identity \u2014 specify one: git colabor identity logout <id>");
|
|
1008
|
+
}
|
|
1009
|
+
const identity = await getIdentity(id);
|
|
1010
|
+
let agentRemoved = false;
|
|
1011
|
+
let keyfileShredded = false;
|
|
1012
|
+
if (identity.sshKeyPath) {
|
|
1013
|
+
agentRemoved = await removeKey(identity.sshKeyPath);
|
|
1014
|
+
keyfileShredded = await shred(identity.sshKeyPath);
|
|
1015
|
+
}
|
|
1016
|
+
if (state.activeIdentity === identity.id) {
|
|
1017
|
+
state.activeIdentity = void 0;
|
|
1018
|
+
state.heldBy = void 0;
|
|
1019
|
+
await writeState(state, opts.cwd);
|
|
1020
|
+
}
|
|
1021
|
+
await appendAudit({
|
|
1022
|
+
action: "identity.logout",
|
|
1023
|
+
source: opts.source,
|
|
1024
|
+
identity: identity.id,
|
|
1025
|
+
identityName: identity.name,
|
|
1026
|
+
fingerprint: identity.sshKeyFingerprint,
|
|
1027
|
+
repo: await safeTopLevel3(opts.cwd)
|
|
1028
|
+
});
|
|
1029
|
+
return {
|
|
1030
|
+
identity: { id: identity.id, name: identity.name, fingerprint: identity.sshKeyFingerprint },
|
|
1031
|
+
agentRemoved,
|
|
1032
|
+
keyfileShredded
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
// src/core/repo/status.ts
|
|
1037
|
+
async function repoStatus(cwd) {
|
|
1038
|
+
const inRepo = cwd ? await insideWorkTree(cwd) : false;
|
|
1039
|
+
if (!inRepo) {
|
|
1040
|
+
return {
|
|
1041
|
+
inRepo: false,
|
|
1042
|
+
repo: cwd ?? null,
|
|
1043
|
+
managed: false,
|
|
1044
|
+
managedBy: null,
|
|
1045
|
+
activeIdentityId: null,
|
|
1046
|
+
heldBy: null,
|
|
1047
|
+
selected: [],
|
|
1048
|
+
available: []
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
1051
|
+
const [managed, managedBy, state, selected] = await Promise.all([
|
|
1052
|
+
getConfig("colabor.managed", "local", cwd),
|
|
1053
|
+
getConfig("colabor.managed-by", "local", cwd),
|
|
1054
|
+
readState(cwd),
|
|
1055
|
+
getSelected(cwd)
|
|
1056
|
+
]);
|
|
1057
|
+
const allAuthors = await listAuthors(void 0, cwd);
|
|
1058
|
+
const selectedEmails = new Set(selected.map((a) => a.email));
|
|
1059
|
+
const available = allAuthors.filter((a) => !selectedEmails.has(a.email)).map(toBrief);
|
|
1060
|
+
return {
|
|
1061
|
+
inRepo: true,
|
|
1062
|
+
repo: cwd,
|
|
1063
|
+
managed: managed === "true",
|
|
1064
|
+
managedBy: managedBy ?? null,
|
|
1065
|
+
activeIdentityId: state.activeIdentity ?? null,
|
|
1066
|
+
heldBy: state.heldBy ?? null,
|
|
1067
|
+
selected: selected.map(toBrief),
|
|
1068
|
+
available
|
|
1069
|
+
};
|
|
1070
|
+
}
|
|
1071
|
+
function toBrief(a) {
|
|
1072
|
+
return { key: a.key, name: a.name, email: a.email };
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
// src/cli/identity.ts
|
|
1076
|
+
var USE_SPEC = { valueFlags: ["--source", "--as-name", "--as-email"], boolFlags: ["--no-override"] };
|
|
1077
|
+
var ADD_SPEC = {
|
|
1078
|
+
valueFlags: ["--name", "--email", "--key", "--passphrase-command", "--host", "--source"],
|
|
1079
|
+
boolFlags: ["--default", "--no-encrypt"]
|
|
1080
|
+
};
|
|
1081
|
+
var AUDIT_SPEC = { valueFlags: ["--repo", "--since", "--tail"] };
|
|
1082
|
+
var APPLY_SPEC = { valueFlags: ["--name", "--email", "--ssh-command", "--source"] };
|
|
1083
|
+
function identityToJson(i, defaultId) {
|
|
1084
|
+
return {
|
|
1085
|
+
id: i.id,
|
|
1086
|
+
name: i.name,
|
|
1087
|
+
email: i.email,
|
|
1088
|
+
sshKeyFingerprint: i.sshKeyFingerprint,
|
|
1089
|
+
host: i.host,
|
|
1090
|
+
hasKey: !!i.sshKeyPath,
|
|
1091
|
+
isDefault: i.id === defaultId
|
|
1092
|
+
};
|
|
1093
|
+
}
|
|
1094
|
+
function asSource(v) {
|
|
1095
|
+
return v === "ext" ? "ext" : "cli";
|
|
1096
|
+
}
|
|
1097
|
+
async function dispatch(command, tokens, ctx) {
|
|
1098
|
+
switch (command) {
|
|
1099
|
+
case void 0:
|
|
1100
|
+
case "ls":
|
|
1101
|
+
return ls2();
|
|
1102
|
+
case "use":
|
|
1103
|
+
return use2(parseCommandArgs(tokens, USE_SPEC), ctx);
|
|
1104
|
+
case "add":
|
|
1105
|
+
return add2(parseCommandArgs(tokens, ADD_SPEC));
|
|
1106
|
+
case "rm":
|
|
1107
|
+
return rm(parseCommandArgs(tokens), ctx);
|
|
1108
|
+
case "logout":
|
|
1109
|
+
return logout(parseCommandArgs(tokens), ctx);
|
|
1110
|
+
case "audit":
|
|
1111
|
+
return audit(parseCommandArgs(tokens, AUDIT_SPEC));
|
|
1112
|
+
case "doctor":
|
|
1113
|
+
return doctor(ctx);
|
|
1114
|
+
case "revert":
|
|
1115
|
+
return revert(ctx);
|
|
1116
|
+
case "status":
|
|
1117
|
+
return status(ctx);
|
|
1118
|
+
case "_apply":
|
|
1119
|
+
return hiddenApply(parseCommandArgs(tokens, APPLY_SPEC), ctx);
|
|
1120
|
+
default:
|
|
1121
|
+
throw Errors.usage(`unknown identity command "${command}"`);
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
async function ls2() {
|
|
1125
|
+
const { identities, defaultIdentity } = await listIdentities();
|
|
1126
|
+
return ok({ identities: identities.map((i) => identityToJson(i, defaultIdentity)), defaultIdentity });
|
|
1127
|
+
}
|
|
1128
|
+
async function use2(p, ctx) {
|
|
1129
|
+
const id = p.positionals[0];
|
|
1130
|
+
if (!id) throw Errors.usage("git colabor identity use <id>");
|
|
1131
|
+
const { identity, result } = await applyIdentity(id, {
|
|
1132
|
+
source: asSource(p.values["--source"]),
|
|
1133
|
+
cwd: ctx.cwd,
|
|
1134
|
+
asName: p.values["--as-name"],
|
|
1135
|
+
asEmail: p.values["--as-email"],
|
|
1136
|
+
noOverride: p.bools.has("--no-override"),
|
|
1137
|
+
askpassScriptPath: ctx.askpassScriptPath,
|
|
1138
|
+
socketPath: ctx.socketPath,
|
|
1139
|
+
token: ctx.token
|
|
1140
|
+
});
|
|
1141
|
+
const warnings = [];
|
|
1142
|
+
if (result.conflict) warnings.push({ code: "conflict", message: `overrode ${result.conflict.heldBy.session}` });
|
|
1143
|
+
if (result.keyLoaded && !result.keyLoaded.loaded) {
|
|
1144
|
+
warnings.push({ code: "key-not-loaded", message: `key not loaded into agent: ${result.keyLoaded.message ?? result.keyLoaded.via}` });
|
|
1145
|
+
}
|
|
1146
|
+
return ok(
|
|
1147
|
+
{
|
|
1148
|
+
identity: identityToJson(identity),
|
|
1149
|
+
applied: { userName: result.name, userEmail: result.email, sshCommand: result.sshCommand ?? null },
|
|
1150
|
+
keyLoaded: result.keyLoaded ?? null,
|
|
1151
|
+
conflict: result.conflict
|
|
1152
|
+
},
|
|
1153
|
+
warnings
|
|
1154
|
+
);
|
|
1155
|
+
}
|
|
1156
|
+
async function add2(p) {
|
|
1157
|
+
const name = p.values["--name"];
|
|
1158
|
+
const email = p.values["--email"];
|
|
1159
|
+
if (!name || !email) {
|
|
1160
|
+
throw Errors.usage("git colabor identity add --name <n> --email <e> [--key <path>] [--passphrase-command <cmd>] [--host <h>] [--default]");
|
|
1161
|
+
}
|
|
1162
|
+
const warnings = [];
|
|
1163
|
+
let sshKeyFingerprint;
|
|
1164
|
+
let sshKeyPath;
|
|
1165
|
+
let encrypted = null;
|
|
1166
|
+
const keySource = p.values["--key"];
|
|
1167
|
+
if (keySource) {
|
|
1168
|
+
if (!fs.existsSync(keySource)) throw Errors.usage(`key file not found: ${keySource}`);
|
|
1169
|
+
const imp = await importKey(keySource);
|
|
1170
|
+
sshKeyFingerprint = imp.fingerprint;
|
|
1171
|
+
sshKeyPath = imp.path;
|
|
1172
|
+
encrypted = imp.encrypted;
|
|
1173
|
+
if (imp.encrypted && !p.values["--passphrase-command"]) {
|
|
1174
|
+
warnings.push({
|
|
1175
|
+
code: "encrypted-key",
|
|
1176
|
+
message: "key is encrypted; provide --passphrase-command or run via the extension to load it at use time"
|
|
1177
|
+
});
|
|
1178
|
+
} else if (!imp.encrypted) {
|
|
1179
|
+
warnings.push({
|
|
1180
|
+
code: "unencrypted-key",
|
|
1181
|
+
message: "key is UNENCRYPTED \u2014 anyone who reads the key file can use it. Consider encrypting it."
|
|
1182
|
+
});
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
const identity = await addIdentity({
|
|
1186
|
+
name,
|
|
1187
|
+
email,
|
|
1188
|
+
sshKeyFingerprint,
|
|
1189
|
+
sshKeyPath,
|
|
1190
|
+
passphraseCommand: p.values["--passphrase-command"],
|
|
1191
|
+
host: p.values["--host"]
|
|
1192
|
+
});
|
|
1193
|
+
if (p.bools.has("--default")) await setDefault(identity.id);
|
|
1194
|
+
await appendAudit({ action: "key.load", source: "cli", identity: identity.id, identityName: name, fingerprint: sshKeyFingerprint });
|
|
1195
|
+
return ok({ identity: identityToJson(identity), encrypted }, warnings);
|
|
1196
|
+
}
|
|
1197
|
+
async function rm(p, ctx) {
|
|
1198
|
+
const id = p.positionals[0];
|
|
1199
|
+
if (!id) throw Errors.usage("git colabor identity rm <id>");
|
|
1200
|
+
try {
|
|
1201
|
+
await logoutIdentity({ source: "cli", cwd: ctx.cwd, id });
|
|
1202
|
+
} catch {
|
|
1203
|
+
}
|
|
1204
|
+
await removeIdentity(id);
|
|
1205
|
+
return ok({ removed: id });
|
|
1206
|
+
}
|
|
1207
|
+
async function logout(p, ctx) {
|
|
1208
|
+
const r = await logoutIdentity({ source: "cli", cwd: ctx.cwd, id: p.positionals[0] });
|
|
1209
|
+
return ok({
|
|
1210
|
+
identity: r.identity,
|
|
1211
|
+
cleared: { agent: r.agentRemoved, keyfile: r.keyfileShredded }
|
|
1212
|
+
});
|
|
1213
|
+
}
|
|
1214
|
+
async function audit(p) {
|
|
1215
|
+
const entries = await readAudit({
|
|
1216
|
+
repo: p.values["--repo"],
|
|
1217
|
+
since: p.values["--since"],
|
|
1218
|
+
tail: p.values["--tail"] ? Number(p.values["--tail"]) : void 0
|
|
1219
|
+
});
|
|
1220
|
+
return ok({ entries });
|
|
1221
|
+
}
|
|
1222
|
+
async function revert(ctx) {
|
|
1223
|
+
const r = await revertRepo({ source: "cli", cwd: ctx.cwd });
|
|
1224
|
+
return ok({ restored: r.restored ?? null, hadBackup: r.hadBackup });
|
|
1225
|
+
}
|
|
1226
|
+
async function hiddenApply(p, ctx) {
|
|
1227
|
+
const name = p.values["--name"];
|
|
1228
|
+
const email = p.values["--email"];
|
|
1229
|
+
if (!name || !email) throw Errors.usage("internal _apply requires --name and --email");
|
|
1230
|
+
const result = await applyResolvedIdentity({
|
|
1231
|
+
name,
|
|
1232
|
+
email,
|
|
1233
|
+
sshCommand: p.values["--ssh-command"],
|
|
1234
|
+
opts: { source: asSource(p.values["--source"]), cwd: ctx.cwd }
|
|
1235
|
+
});
|
|
1236
|
+
return ok({
|
|
1237
|
+
applied: { userName: result.name, userEmail: result.email, sshCommand: result.sshCommand ?? null },
|
|
1238
|
+
conflict: result.conflict
|
|
1239
|
+
});
|
|
1240
|
+
}
|
|
1241
|
+
async function status(ctx) {
|
|
1242
|
+
const { identities, defaultIdentity } = await listIdentities();
|
|
1243
|
+
const rs = await repoStatus(ctx.cwd);
|
|
1244
|
+
const active = rs.activeIdentityId ? identities.find((i) => i.id === rs.activeIdentityId) : void 0;
|
|
1245
|
+
return ok({
|
|
1246
|
+
repo: rs.repo,
|
|
1247
|
+
inRepo: rs.inRepo,
|
|
1248
|
+
managed: rs.managed,
|
|
1249
|
+
managedBy: rs.managedBy,
|
|
1250
|
+
heldBy: rs.heldBy,
|
|
1251
|
+
activeIdentity: active ? identityToJson(active, defaultIdentity) : null,
|
|
1252
|
+
identities: identities.map((i) => ({ ...identityToJson(i, defaultIdentity), active: i.id === rs.activeIdentityId })),
|
|
1253
|
+
selected: rs.selected,
|
|
1254
|
+
available: rs.available
|
|
1255
|
+
});
|
|
1256
|
+
}
|
|
1257
|
+
async function doctor(ctx) {
|
|
1258
|
+
const diags = [];
|
|
1259
|
+
const check = (check2, fn, detail) => {
|
|
1260
|
+
try {
|
|
1261
|
+
const r = fn();
|
|
1262
|
+
diags.push({ check: check2, status: r === true ? "ok" : r === false ? "warn" : "ok", detail: typeof r === "string" ? r : detail });
|
|
1263
|
+
} catch (e) {
|
|
1264
|
+
diags.push({ check: check2, status: "fail", detail: e instanceof Error ? e.message : String(e) });
|
|
1265
|
+
}
|
|
1266
|
+
};
|
|
1267
|
+
const hasBin2 = (b) => process.platform === "win32" ? child_process.spawnSync("where", [b]).status === 0 : child_process.spawnSync(`command -v ${b}`, { shell: true }).status === 0;
|
|
1268
|
+
check("git", () => hasBin2("git"));
|
|
1269
|
+
check("ssh-keygen", () => hasBin2("ssh-keygen"));
|
|
1270
|
+
check("ssh-add", () => hasBin2("ssh-add"));
|
|
1271
|
+
try {
|
|
1272
|
+
fs.accessSync(mapPath(), fs.constants.R_OK | fs.constants.W_OK);
|
|
1273
|
+
check("identity map", () => true, mapPath());
|
|
1274
|
+
} catch {
|
|
1275
|
+
check("identity map", () => true, `${mapPath()} (will be created on first add)`);
|
|
1276
|
+
}
|
|
1277
|
+
try {
|
|
1278
|
+
fs.accessSync(keysDir(), fs.constants.W_OK);
|
|
1279
|
+
check("keys dir", () => true, keysDir());
|
|
1280
|
+
} catch {
|
|
1281
|
+
check("keys dir", () => true, `${keysDir()} (will be created on first import)`);
|
|
1282
|
+
}
|
|
1283
|
+
check("audit log", () => true, auditLogPath());
|
|
1284
|
+
check("askpass bundle", () => !!ctx.askpassScriptPath && fs.existsSync(ctx.askpassScriptPath), ctx.askpassScriptPath);
|
|
1285
|
+
const agentOut = await listAgent();
|
|
1286
|
+
check("ssh-agent", () => !agentOut.includes("Could not open a connection"), agentOut.split("\n")[0]);
|
|
1287
|
+
const inRepo = ctx.cwd ? await insideWorkTree(ctx.cwd) : false;
|
|
1288
|
+
check("inside git repo", () => inRepo, ctx.cwd);
|
|
1289
|
+
if (inRepo && ctx.cwd) {
|
|
1290
|
+
const managed = await getConfig("colabor.managed", "local", ctx.cwd);
|
|
1291
|
+
check("repo managed", () => managed === "true", `colabor.managed=${managed ?? "unset"}`);
|
|
1292
|
+
const st = await readState(ctx.cwd);
|
|
1293
|
+
check("active identity", () => !!st.activeIdentity, st.activeIdentity ?? "(none)");
|
|
1294
|
+
}
|
|
1295
|
+
return ok({ diagnostics: diags });
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
// src/cli/index.ts
|
|
1299
|
+
var VERSION = "0.1.0";
|
|
1300
|
+
function resolveAskpass() {
|
|
1301
|
+
let dir;
|
|
1302
|
+
if (typeof __dirname === "string" && __dirname.length > 0) dir = __dirname;
|
|
1303
|
+
else if (process.argv[1]) dir = path.dirname(process.argv[1]);
|
|
1304
|
+
if (!dir) return void 0;
|
|
1305
|
+
const p = path.join(dir, "askpass.cjs");
|
|
1306
|
+
return fs.existsSync(p) ? p : void 0;
|
|
1307
|
+
}
|
|
1308
|
+
function topHelp() {
|
|
1309
|
+
return [
|
|
1310
|
+
"git colabor \u2014 co-author + identity + SSH key management",
|
|
1311
|
+
"",
|
|
1312
|
+
"Usage:",
|
|
1313
|
+
" git colabor coauthor ls [filter]",
|
|
1314
|
+
" git colabor coauthor use <initials...>",
|
|
1315
|
+
" git colabor coauthor solo",
|
|
1316
|
+
" git colabor coauthor print [-i]",
|
|
1317
|
+
' git colabor coauthor add <initials> "Name" <email>',
|
|
1318
|
+
" git colabor coauthor suggest [filter]",
|
|
1319
|
+
" git colabor identity ls",
|
|
1320
|
+
" git colabor identity use <id> [--as-name <n> --as-email <e>]",
|
|
1321
|
+
" git colabor identity add --name <n> --email <e> [--key <path>] [--passphrase-command <cmd>]",
|
|
1322
|
+
" git colabor identity rm <id>",
|
|
1323
|
+
" git colabor identity logout [id]",
|
|
1324
|
+
" git colabor identity revert",
|
|
1325
|
+
" git colabor identity status",
|
|
1326
|
+
" git colabor identity audit [--repo <p>] [--tail N]",
|
|
1327
|
+
" git colabor identity doctor",
|
|
1328
|
+
"",
|
|
1329
|
+
"Global flags: --json --log-level <level> -C <path> --no-color -h -v"
|
|
1330
|
+
].join("\n");
|
|
1331
|
+
}
|
|
1332
|
+
async function main(argv = process.argv.slice(2)) {
|
|
1333
|
+
const { flags, rest } = parseGlobals(argv);
|
|
1334
|
+
if (flags.version) {
|
|
1335
|
+
process.stdout.write(`${VERSION}
|
|
1336
|
+
`);
|
|
1337
|
+
process.exit(0);
|
|
1338
|
+
}
|
|
1339
|
+
const subgroup = rest[0];
|
|
1340
|
+
const command = rest[1];
|
|
1341
|
+
const cmdTokens = rest.slice(2);
|
|
1342
|
+
if (!subgroup || flags.help) {
|
|
1343
|
+
process.stdout.write(`${topHelp()}
|
|
1344
|
+
`);
|
|
1345
|
+
process.exit(0);
|
|
1346
|
+
}
|
|
1347
|
+
const cwd = flags.cwd ?? process.cwd();
|
|
1348
|
+
let result;
|
|
1349
|
+
try {
|
|
1350
|
+
if (subgroup === "coauthor") {
|
|
1351
|
+
result = await dispatchCoauthor(command, cmdTokens, flags, cwd);
|
|
1352
|
+
} else if (subgroup === "identity") {
|
|
1353
|
+
result = await dispatch(command, cmdTokens, {
|
|
1354
|
+
cwd,
|
|
1355
|
+
flags,
|
|
1356
|
+
askpassScriptPath: resolveAskpass(),
|
|
1357
|
+
socketPath: process.env.GIT_COLABOR_ASKPASS_SOCK,
|
|
1358
|
+
token: process.env.GIT_COLABOR_ASKPASS_TOKEN
|
|
1359
|
+
});
|
|
1360
|
+
} else {
|
|
1361
|
+
throw Errors.usage(`unknown subgroup "${subgroup}"`);
|
|
1362
|
+
}
|
|
1363
|
+
} catch (e) {
|
|
1364
|
+
result = failFromError(e);
|
|
1365
|
+
}
|
|
1366
|
+
emit(result, { json: flags.json, human: (r) => humanFor(r, subgroup, command) });
|
|
1367
|
+
}
|
|
1368
|
+
async function dispatchCoauthor(command, tokens, flags, cwd) {
|
|
1369
|
+
switch (command) {
|
|
1370
|
+
case void 0:
|
|
1371
|
+
case "ls": {
|
|
1372
|
+
const p = parseCommandArgs(tokens);
|
|
1373
|
+
return ls(p.positionals, cwd);
|
|
1374
|
+
}
|
|
1375
|
+
case "use": {
|
|
1376
|
+
const p = parseCommandArgs(tokens);
|
|
1377
|
+
return use(p.positionals, cwd);
|
|
1378
|
+
}
|
|
1379
|
+
case "solo":
|
|
1380
|
+
return solo(cwd);
|
|
1381
|
+
case "print": {
|
|
1382
|
+
const p = parseCommandArgs(tokens, { boolFlags: ["-i", "--initials"] });
|
|
1383
|
+
return print({ initials: p.bools.has("-i") || p.bools.has("--initials") }, cwd);
|
|
1384
|
+
}
|
|
1385
|
+
case "add": {
|
|
1386
|
+
const p = parseCommandArgs(tokens);
|
|
1387
|
+
return add(p.positionals, cwd);
|
|
1388
|
+
}
|
|
1389
|
+
case "suggest": {
|
|
1390
|
+
const p = parseCommandArgs(tokens);
|
|
1391
|
+
return flags.json ? suggest(p.positionals, cwd) : suggestInteractive(p.positionals, cwd);
|
|
1392
|
+
}
|
|
1393
|
+
default:
|
|
1394
|
+
throw Errors.usage(`unknown coauthor command "${command}"`);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
function humanFor(r, subgroup, command) {
|
|
1398
|
+
if (!r.ok) {
|
|
1399
|
+
const lines = [`Error: ${r.error.message}`];
|
|
1400
|
+
for (const h of r.error.hints ?? []) lines.push(` hint: ${h}`);
|
|
1401
|
+
return lines.join("\n");
|
|
1402
|
+
}
|
|
1403
|
+
const d = r.data;
|
|
1404
|
+
if (subgroup === "coauthor") return coauthorHuman(command, d);
|
|
1405
|
+
if (subgroup === "identity") return identityHuman(command, d);
|
|
1406
|
+
return JSON.stringify(d, null, 2);
|
|
1407
|
+
}
|
|
1408
|
+
function coauthorHuman(command, d) {
|
|
1409
|
+
if (command === "print") return String(d.text ?? "");
|
|
1410
|
+
if (command === void 0 || command === "ls") {
|
|
1411
|
+
return renderAuthors(d ?? []);
|
|
1412
|
+
}
|
|
1413
|
+
if (command === "use") {
|
|
1414
|
+
const sel = d.selected ?? [];
|
|
1415
|
+
return sel.length ? `Co-authoring with:
|
|
1416
|
+
${renderAuthors(sel)}` : "No co-authors selected.";
|
|
1417
|
+
}
|
|
1418
|
+
if (command === "solo") return "Cleared co-authors.";
|
|
1419
|
+
if (command === "add") return `${d.author.name} added to .git-coauthors`;
|
|
1420
|
+
if (command === "suggest") {
|
|
1421
|
+
const added = d.added ?? [];
|
|
1422
|
+
return added.length ? `Added ${added.length} co-author(s):
|
|
1423
|
+
${renderAuthors(added)}` : "No co-authors added.";
|
|
1424
|
+
}
|
|
1425
|
+
return JSON.stringify(d, null, 2);
|
|
1426
|
+
}
|
|
1427
|
+
function identityHuman(command, d) {
|
|
1428
|
+
if (command === void 0 || command === "ls") {
|
|
1429
|
+
const identities = d.identities ?? [];
|
|
1430
|
+
if (identities.length === 0) return "No identities. Add one: git colabor identity add --name <n> --email <e>";
|
|
1431
|
+
return identities.map(
|
|
1432
|
+
(i) => `${i.isDefault ? "* " : " "}${i.id} ${i.name} <${i.email}>${i.hasKey ? ` [key ${i.sshKeyFingerprint ?? ""}]` : ""}`
|
|
1433
|
+
).join("\n");
|
|
1434
|
+
}
|
|
1435
|
+
if (command === "use") {
|
|
1436
|
+
const data = d;
|
|
1437
|
+
const lines = [
|
|
1438
|
+
`Applied identity "${data.identity.name}" <${data.identity.email}>`,
|
|
1439
|
+
` user.name = ${data.applied.userName}`,
|
|
1440
|
+
` user.email = ${data.applied.userEmail}`
|
|
1441
|
+
];
|
|
1442
|
+
if (data.applied.sshCommand) lines.push(` core.sshCommand = ${data.applied.sshCommand}`);
|
|
1443
|
+
return lines.join("\n");
|
|
1444
|
+
}
|
|
1445
|
+
if (command === "add") {
|
|
1446
|
+
const data = d;
|
|
1447
|
+
return `Added identity "${data.identity.name}" <${data.identity.email}> (${data.identity.id})${data.identity.hasKey ? ` key=${data.identity.sshKeyFingerprint ?? ""}` : ""}`;
|
|
1448
|
+
}
|
|
1449
|
+
if (command === "rm") return `Removed identity ${d.removed}`;
|
|
1450
|
+
if (command === "logout") {
|
|
1451
|
+
const data = d;
|
|
1452
|
+
return `Logged out "${data.identity.name}" (agent:${data.cleared.agent ? "removed" : "n/a"}, keyfile:${data.cleared.keyfile ? "shredded" : "n/a"})`;
|
|
1453
|
+
}
|
|
1454
|
+
if (command === "revert") {
|
|
1455
|
+
const data = d;
|
|
1456
|
+
return data.hadBackup ? "Reverted repo identity to pre-tool state." : "Repo was not managed; nothing to revert.";
|
|
1457
|
+
}
|
|
1458
|
+
if (command === "audit") {
|
|
1459
|
+
const entries = d.entries ?? [];
|
|
1460
|
+
if (entries.length === 0) return "(no audit entries)";
|
|
1461
|
+
return entries.map((e) => `${e.ts} ${e.result.padEnd(4)} ${e.action} ${e.identityName ?? ""}`).join("\n");
|
|
1462
|
+
}
|
|
1463
|
+
if (command === "doctor") {
|
|
1464
|
+
const diags = d.diagnostics ?? [];
|
|
1465
|
+
return diags.map((x) => `[${x.status.padEnd(4)}] ${x.check}${x.detail ? ` \u2014 ${x.detail}` : ""}`).join("\n");
|
|
1466
|
+
}
|
|
1467
|
+
return JSON.stringify(d, null, 2);
|
|
1468
|
+
}
|
|
1469
|
+
main().catch((e) => {
|
|
1470
|
+
process.stderr.write(`internal error: ${e instanceof Error ? e.message : String(e)}
|
|
1471
|
+
`);
|
|
1472
|
+
process.exit(1);
|
|
1473
|
+
});
|
|
1474
|
+
|
|
1475
|
+
exports.main = main;
|