git-colabor 0.1.8 → 0.1.9

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.
Files changed (4) hide show
  1. package/README.md +2 -3
  2. package/dist/cli.cjs +1094 -870
  3. package/dist/index.cjs +408 -179
  4. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -1,42 +1,57 @@
1
1
  'use strict';
2
2
 
3
3
  var os = require('os');
4
- var promises = require('fs/promises');
5
- var path = require('path');
6
4
  var child_process = require('child_process');
5
+ var path = require('path');
6
+ var promises = require('fs/promises');
7
7
  var crypto = require('crypto');
8
8
  var fs = require('fs');
9
9
  var net = require('net');
10
10
  var promises$1 = require('readline/promises');
11
11
 
12
- // src/core/authors/types.ts
13
- var CO_AUTHOR_TRAILER = "Co-authored-by:";
14
- var Author = class {
15
- constructor(key, name, email) {
16
- this.key = key;
17
- this.name = name;
18
- this.email = email;
19
- }
20
- key;
21
- name;
22
- email;
23
- /** `NAME <EMAIL>` */
24
- toString() {
25
- return `${this.name} <${this.email}>`;
26
- }
27
- /** `Co-authored-by: NAME <EMAIL>` */
28
- format() {
29
- return `${CO_AUTHOR_TRAILER} ${this.toString()}`;
30
- }
12
+ var __defProp = Object.defineProperty;
13
+ var __getOwnPropNames = Object.getOwnPropertyNames;
14
+ var __esm = (fn, res) => function __init() {
15
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
31
16
  };
17
+ var __export = (target, all) => {
18
+ for (var name in all)
19
+ __defProp(target, name, { get: all[name], enumerable: true });
20
+ };
21
+
22
+ // src/core/authors/types.ts
32
23
  function genKey(name, email) {
33
24
  const initials = name.toLowerCase().split(/\s+/).filter(Boolean).map((w) => w[0] ?? "").join("");
34
25
  return `${initials}${email.slice(0, 2)}`;
35
26
  }
27
+ exports.CO_AUTHOR_TRAILER = void 0; exports.Author = void 0;
28
+ var init_types = __esm({
29
+ "src/core/authors/types.ts"() {
30
+ exports.CO_AUTHOR_TRAILER = "Co-authored-by:";
31
+ exports.Author = class {
32
+ constructor(key, name, email) {
33
+ this.key = key;
34
+ this.name = name;
35
+ this.email = email;
36
+ }
37
+ key;
38
+ name;
39
+ email;
40
+ /** `NAME <EMAIL>` */
41
+ toString() {
42
+ return `${this.name} <${this.email}>`;
43
+ }
44
+ /** `Co-authored-by: NAME <EMAIL>` */
45
+ format() {
46
+ return `${exports.CO_AUTHOR_TRAILER} ${this.toString()}`;
47
+ }
48
+ };
49
+ }
50
+ });
36
51
  function formatMessage(txt, authors) {
37
52
  const stripRe = new RegExp(`(\r
38
53
  |\r|
39
- ){0,2}${CO_AUTHOR_TRAILER}.*`, "g");
54
+ ){0,2}${exports.CO_AUTHOR_TRAILER}.*`, "g");
40
55
  const message = txt.replace(stripRe, "");
41
56
  if (authors && authors.length > 0) {
42
57
  const trailerText = authors.map((a) => a.format()).join(os.EOL);
@@ -48,18 +63,11 @@ function printTrailers(authors) {
48
63
  if (authors.length === 0) return "";
49
64
  return os.EOL + os.EOL + authors.map((a) => a.format()).join(os.EOL);
50
65
  }
51
- var GitError = class extends Error {
52
- cmd;
53
- exitCode;
54
- stderr;
55
- constructor(cmd, exitCode, stderr) {
56
- super(`git ${cmd} failed (exit ${exitCode})${stderr ? ": " + stderr.trim() : ""}`);
57
- this.name = "GitError";
58
- this.cmd = cmd;
59
- this.exitCode = exitCode;
60
- this.stderr = stderr;
66
+ var init_formatter = __esm({
67
+ "src/core/message/formatter.ts"() {
68
+ init_types();
61
69
  }
62
- };
70
+ });
63
71
  function run(args, opts) {
64
72
  return new Promise((resolve4, reject) => {
65
73
  const child = child_process.spawn("git", args, {
@@ -86,7 +94,7 @@ async function gitRaw(args, opts = {}) {
86
94
  }
87
95
  async function git(args, opts = {}) {
88
96
  const result = await run(args, opts);
89
- if (result.exitCode !== 0) throw new GitError(args.join(" "), result.exitCode, result.stderr);
97
+ if (result.exitCode !== 0) throw new exports.GitError(args.join(" "), result.exitCode, result.stderr);
90
98
  return result;
91
99
  }
92
100
  async function runBin(cmd, args, opts = {}) {
@@ -112,8 +120,36 @@ async function runBin(cmd, args, opts = {}) {
112
120
  else child.stdin.end();
113
121
  });
114
122
  }
123
+ exports.GitError = void 0;
124
+ var init_exec = __esm({
125
+ "src/core/git/exec.ts"() {
126
+ exports.GitError = class extends Error {
127
+ cmd;
128
+ exitCode;
129
+ stderr;
130
+ constructor(cmd, exitCode, stderr) {
131
+ super(`git ${cmd} failed (exit ${exitCode})${stderr ? ": " + stderr.trim() : ""}`);
132
+ this.name = "GitError";
133
+ this.cmd = cmd;
134
+ this.exitCode = exitCode;
135
+ this.stderr = stderr;
136
+ }
137
+ };
138
+ }
139
+ });
115
140
 
116
141
  // src/core/git/config.ts
142
+ var config_exports = {};
143
+ __export(config_exports, {
144
+ addConfigValue: () => addConfigValue,
145
+ getAllConfig: () => getAllConfig,
146
+ getConfig: () => getConfig,
147
+ getEffectiveConfig: () => getEffectiveConfig,
148
+ removeSection: () => removeSection,
149
+ setConfig: () => setConfig,
150
+ unsetAllConfig: () => unsetAllConfig,
151
+ unsetConfig: () => unsetConfig
152
+ });
117
153
  function scopeArgs(scope) {
118
154
  return scope ? [`--${scope}`] : [];
119
155
  }
@@ -151,6 +187,11 @@ async function unsetAllConfig(key, scope, cwd) {
151
187
  async function removeSection(section, scope, cwd) {
152
188
  await gitRaw(["config", ...scopeArgs(scope), "--remove-section", section], { cwd });
153
189
  }
190
+ var init_config = __esm({
191
+ "src/core/git/config.ts"() {
192
+ init_exec();
193
+ }
194
+ });
154
195
  async function insideWorkTree(cwd) {
155
196
  const r = await gitRaw(["rev-parse", "--is-inside-work-tree"], { cwd });
156
197
  return r.exitCode === 0 && r.stdout.trim() === "true";
@@ -172,8 +213,21 @@ async function headSha(cwd) {
172
213
  const sha = r.stdout.trim();
173
214
  return sha.length > 0 ? sha : void 0;
174
215
  }
216
+ var init_rev = __esm({
217
+ "src/core/git/rev.ts"() {
218
+ init_exec();
219
+ }
220
+ });
175
221
 
176
222
  // src/core/message/template.ts
223
+ var template_exports = {};
224
+ __export(template_exports, {
225
+ clearTemplate: () => clearTemplate,
226
+ ensureCommitTemplate: () => ensureCommitTemplate,
227
+ gitMessagePath: () => gitMessagePath,
228
+ resolveTemplatePath: () => resolveTemplatePath,
229
+ writeCoAuthorsToTemplate: () => writeCoAuthorsToTemplate
230
+ });
177
231
  function gitMessagePath() {
178
232
  return path.join(os.homedir(), ".gitmessage");
179
233
  }
@@ -216,8 +270,89 @@ async function writeCoAuthorsToTemplate(authors, cwd) {
216
270
  async function clearTemplate(cwd) {
217
271
  await applyToTemplate([], cwd);
218
272
  }
273
+ var init_template = __esm({
274
+ "src/core/message/template.ts"() {
275
+ init_config();
276
+ init_rev();
277
+ init_formatter();
278
+ }
279
+ });
280
+
281
+ // src/core/identity/configClear.ts
282
+ var configClear_exports = {};
283
+ __export(configClear_exports, {
284
+ clearIdentityConfigLayer: () => clearIdentityConfigLayer
285
+ });
286
+ function signingKeyOwned(configured, keys) {
287
+ const value = configured.trim();
288
+ if (!value) return false;
289
+ if (keys.sshPaths.some((p) => bare(p) === bare(value))) return true;
290
+ if (keys.gpgFingerprint) {
291
+ const hex = (k) => /^(0x)?[0-9a-f]{8,}!?$/i.test(k) ? k.replace(/^0x/i, "").replace(/!$/, "").toUpperCase() : void 0;
292
+ const a = hex(value);
293
+ const b = hex(keys.gpgFingerprint);
294
+ if (a && b && (a.endsWith(b) || b.endsWith(a))) return true;
295
+ }
296
+ return false;
297
+ }
298
+ async function clearIdentityConfigLayer(identity, opts = {}) {
299
+ const forceKeys = opts.forceKeys === true;
300
+ const sshPaths = [
301
+ ...identity.pushKeyPath ? [identity.pushKeyPath] : [],
302
+ ...identity.signKey?.format === "ssh" ? [identity.signKey.path] : []
303
+ ];
304
+ const gpgFingerprint = identity.signKey?.format === "openpgp" ? identity.signKey.key : void 0;
305
+ const [n, e, ssh, signKey, sshProgram] = await Promise.all([
306
+ getConfig("user.name", "local", opts.cwd),
307
+ getConfig("user.email", "local", opts.cwd),
308
+ getConfig("core.sshCommand", "local", opts.cwd),
309
+ getConfig("user.signingKey", "local", opts.cwd),
310
+ getConfig("gpg.ssh.program", "local", opts.cwd)
311
+ ]);
312
+ const eq = (a, b) => !!a && a.trim() === b.trim();
313
+ const result = { identityLayer: false, sshCommand: false, signing: false };
314
+ if (eq(n, identity.name)) {
315
+ await unsetConfig("user.name", "local", opts.cwd);
316
+ result.identityLayer = true;
317
+ }
318
+ if (eq(e, identity.email)) {
319
+ await unsetConfig("user.email", "local", opts.cwd);
320
+ result.identityLayer = true;
321
+ }
322
+ if (ssh && (forceKeys || sshPaths.some((p) => sshCommandUses(ssh, p)))) {
323
+ await unsetConfig("core.sshCommand", "local", opts.cwd);
324
+ result.sshCommand = true;
325
+ }
326
+ const wrapperIsOurs = !!sshProgram && sshProgram.includes("git-colabor");
327
+ if (signKey && (forceKeys || signingKeyOwned(signKey, { sshPaths, gpgFingerprint }))) {
328
+ await unsetConfig("user.signingKey", "local", opts.cwd);
329
+ result.signing = true;
330
+ }
331
+ if (result.signing || wrapperIsOurs || forceKeys) {
332
+ await unsetConfig("gpg.format", "local", opts.cwd);
333
+ await unsetConfig("gpg.ssh.program", "local", opts.cwd);
334
+ await unsetConfig("commit.gpgsign", "local", opts.cwd);
335
+ }
336
+ return result;
337
+ }
338
+ var bare, sshCommandUses;
339
+ var init_configClear = __esm({
340
+ "src/core/identity/configClear.ts"() {
341
+ init_config();
342
+ bare = (p) => p.trim().replace(/\.pub$/, "");
343
+ sshCommandUses = (command, keyPath) => command.includes(bare(keyPath));
344
+ }
345
+ });
346
+
347
+ // src/index.ts
348
+ init_types();
349
+ init_formatter();
350
+ init_template();
219
351
 
220
352
  // src/core/coauthors/state.ts
353
+ init_config();
354
+ init_types();
355
+ init_template();
221
356
  var KEY = "colabor.selected";
222
357
  var LINE_RE = /^(.*)\s<([^>]+)>$/;
223
358
  async function getSelected(cwd) {
@@ -227,7 +362,7 @@ async function getSelected(cwd) {
227
362
  for (const line of raw) {
228
363
  const m = line.match(LINE_RE);
229
364
  if (!m) continue;
230
- out.push(new Author(m[2].split("@")[0] || "co", m[1].trim(), m[2].trim()));
365
+ out.push(new exports.Author(m[2].split("@")[0] || "co", m[1].trim(), m[2].trim()));
231
366
  }
232
367
  return out;
233
368
  }
@@ -243,7 +378,14 @@ async function clearSelected(cwd) {
243
378
  await clearTemplate(cwd);
244
379
  }
245
380
 
381
+ // src/index.ts
382
+ init_exec();
383
+ init_config();
384
+ init_rev();
385
+
246
386
  // src/core/git/shortlog.ts
387
+ init_exec();
388
+ init_types();
247
389
  var SHORTLOG_LINE = /^\s*\d+\t(.+)\s<(.+)>$/;
248
390
  async function repoAuthors(filter, cwd) {
249
391
  const args = ["shortlog", "-seni", "HEAD"];
@@ -256,12 +398,13 @@ async function repoAuthors(filter, cwd) {
256
398
  if (!m) continue;
257
399
  const name = m[1].trim();
258
400
  const email = m[2].trim();
259
- out.push(new Author(genKey(name, email), name, email));
401
+ out.push(new exports.Author(genKey(name, email), name, email));
260
402
  }
261
403
  return out;
262
404
  }
263
405
 
264
406
  // src/core/git/committers.ts
407
+ init_exec();
265
408
  async function historyCommitters(cwd) {
266
409
  const r = await gitRaw(["log", "--format=%cn%x1f%ce"], { cwd });
267
410
  if (r.exitCode !== 0) return [];
@@ -416,6 +559,10 @@ async function atomicWriteJson(path$1, data, mode) {
416
559
  }
417
560
  await promises.rename(tmp, path$1);
418
561
  }
562
+
563
+ // src/core/repo/state.ts
564
+ init_rev();
565
+ init_config();
419
566
  async function statePath(cwd) {
420
567
  return path.join(await gitDir(cwd), "colabor", "state.json");
421
568
  }
@@ -476,6 +623,10 @@ function nowHeldBy(session, source) {
476
623
  };
477
624
  }
478
625
 
626
+ // src/core/repo/status.ts
627
+ init_config();
628
+ init_rev();
629
+
479
630
  // src/core/errors.ts
480
631
  var EXIT_CODES = {
481
632
  OK: 0,
@@ -530,25 +681,49 @@ function toErrorPayload(e) {
530
681
  }
531
682
 
532
683
  // src/core/identity/map.ts
533
- function genId() {
534
- return "id_" + crypto.randomBytes(4).toString("hex");
684
+ function identityId(name, email) {
685
+ return "id_" + crypto.createHash("sha256").update(`${name}
686
+ ${email}`).digest("hex").slice(0, 12);
535
687
  }
536
688
  async function readMap() {
537
689
  try {
538
690
  const txt = await promises.readFile(mapPath(), "utf8");
539
691
  const parsed = JSON.parse(txt);
540
692
  const identities = { ...parsed.identities };
693
+ const keyBindings = { ...parsed.keyBindings ?? {} };
541
694
  for (const id of Object.keys(identities)) {
542
695
  const row = identities[id];
696
+ if (row.sshKeyPath && row.sshKeyFingerprint && !keyBindings[id]?.pushKey) {
697
+ const ref = { path: row.sshKeyPath, fingerprint: row.sshKeyFingerprint };
698
+ if (row.sshKeyEncrypted) ref.encrypted = true;
699
+ const existing = keyBindings[id] ?? {};
700
+ keyBindings[id] = { ...existing, pushKey: ref };
701
+ }
702
+ if (row.gpgKey && !keyBindings[id]?.signKey) {
703
+ const existing = keyBindings[id] ?? {};
704
+ keyBindings[id] = { ...existing, signKey: { format: "openpgp", key: row.gpgKey } };
705
+ }
706
+ delete row.sshKeyPath;
707
+ delete row.sshKeyFingerprint;
708
+ delete row.sshKeyEncrypted;
709
+ delete row.gpgKey;
543
710
  delete row.passphraseCommand;
544
- if (row.scope === "user" || row.scope === "vscode") row.scope = "machine";
711
+ delete row.disabled;
712
+ delete row.remoteKeys;
713
+ const legacyScope = row.scope;
714
+ if (legacyScope === "user" || legacyScope === "vscode") row.scope = "machine";
545
715
  }
546
- return {
716
+ const migrated = {
547
717
  schemaVersion: 1,
548
718
  identities,
719
+ keyBindings,
549
720
  defaultIdentity: parsed.defaultIdentity,
550
721
  hidden: parsed.hidden
551
722
  };
723
+ if (JSON.stringify(parsed) !== JSON.stringify(migrated)) {
724
+ await writeMap(migrated);
725
+ }
726
+ return migrated;
552
727
  } catch {
553
728
  return { schemaVersion: 1, identities: {} };
554
729
  }
@@ -562,11 +737,17 @@ async function getIdentity(id) {
562
737
  if (!found) throw Errors.usage(`identity "${id}" not found`);
563
738
  return found;
564
739
  }
740
+ async function findIdentity(name, email) {
741
+ const map = await readMap();
742
+ return Object.values(map.identities).find(
743
+ (i) => i.email.toLowerCase() === email.toLowerCase() && i.name.trim() === name.trim()
744
+ );
745
+ }
565
746
  async function addIdentity(input) {
566
747
  const map = await readMap();
567
- const id = input.id ?? genId();
568
- if (map.identities[id]) throw Errors.usage(`identity "${id}" already exists`);
748
+ const id = input.id ?? identityId(input.name, input.email);
569
749
  const identity = { ...input, id, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
750
+ if (map.identities[id]) return map.identities[id];
570
751
  map.identities[id] = identity;
571
752
  if (map.hidden?.[identity.email.toLowerCase()]) delete map.hidden[identity.email.toLowerCase()];
572
753
  await writeMap(map);
@@ -576,15 +757,27 @@ async function updateIdentity(id, patch) {
576
757
  const map = await readMap();
577
758
  const identity = map.identities[id];
578
759
  if (!identity) throw Errors.usage(`identity "${id}" not found`);
579
- const next = { ...identity, ...patch };
580
- if (patch.sshKeyPath === void 0 && Object.keys(patch).includes("sshKeyPath")) {
581
- delete next.sshKeyPath;
582
- delete next.sshKeyFingerprint;
583
- delete next.sshKeyEncrypted;
584
- }
585
- map.identities[id] = next;
760
+ map.identities[id] = { ...identity, ...patch };
586
761
  await writeMap(map);
587
- return next;
762
+ return map.identities[id];
763
+ }
764
+ async function getKeyBinding(id) {
765
+ const map = await readMap();
766
+ return map.keyBindings?.[id] ?? {};
767
+ }
768
+ async function setKeyBinding(id, binding) {
769
+ const map = await readMap();
770
+ if (!map.identities[id]) throw Errors.usage(`identity "${id}" not found`);
771
+ map.keyBindings = { ...map.keyBindings, [id]: binding };
772
+ await writeMap(map);
773
+ }
774
+ async function setPushKey(id, ref) {
775
+ const b = await getKeyBinding(id);
776
+ await setKeyBinding(id, { ...b, pushKey: ref });
777
+ }
778
+ async function setSignKey(id, ref) {
779
+ const b = await getKeyBinding(id);
780
+ await setKeyBinding(id, { ...b, signKey: ref });
588
781
  }
589
782
  async function hideIdentityEmail(email) {
590
783
  const map = await readMap();
@@ -607,6 +800,7 @@ async function removeIdentity(id) {
607
800
  const map = await readMap();
608
801
  if (!map.identities[id]) throw Errors.usage(`identity "${id}" not found`);
609
802
  delete map.identities[id];
803
+ if (map.keyBindings?.[id]) delete map.keyBindings[id];
610
804
  if (map.defaultIdentity === id) delete map.defaultIdentity;
611
805
  await writeMap(map);
612
806
  }
@@ -622,6 +816,7 @@ async function listIdentities() {
622
816
  }
623
817
 
624
818
  // src/core/repo/status.ts
819
+ init_types();
625
820
  async function repoStatus(cwd) {
626
821
  const inRepo = cwd ? await insideWorkTree(cwd) : false;
627
822
  if (!inRepo) {
@@ -659,6 +854,9 @@ async function repoStatus(cwd) {
659
854
  function toBrief(a) {
660
855
  return { key: a.key, name: a.name, email: a.email };
661
856
  }
857
+
858
+ // src/core/identity/keys.ts
859
+ init_exec();
662
860
  var FP_RE = /SHA256:[A-Za-z0-9+/=]+/;
663
861
  async function fingerprintOfFile(path) {
664
862
  const r = await runBin("ssh-keygen", ["-lf", path]);
@@ -821,7 +1019,17 @@ async function verifyKey(opts) {
821
1019
  return verify === 0;
822
1020
  }
823
1021
 
1022
+ // src/core/identity/apply.ts
1023
+ init_config();
1024
+ init_rev();
1025
+
1026
+ // src/core/identity/sign.ts
1027
+ init_config();
1028
+ init_rev();
1029
+
824
1030
  // src/core/identity/gpg.ts
1031
+ init_config();
1032
+ init_exec();
825
1033
  var UNUSABLE = /* @__PURE__ */ new Set(["i", "d", "r", "e", "n"]);
826
1034
  function unescape(s) {
827
1035
  return s.replace(/\\x([0-9a-fA-F]{2})/g, (_, h) => String.fromCharCode(parseInt(h, 16)));
@@ -925,9 +1133,12 @@ async function signingKeyPath(sshKeyPath, fingerprint) {
925
1133
  return sshKeyPath;
926
1134
  }
927
1135
  async function signingConfigFor(identity) {
928
- if (identity.gpgKey) return { format: "openpgp", key: identity.gpgKey };
929
- if (identity.sshKeyPath && await keyUsable(identity.sshKeyPath)) {
930
- return { format: "ssh", key: await signingKeyPath(identity.sshKeyPath, identity.sshKeyFingerprint) };
1136
+ const binding = await getKeyBinding(identity.id);
1137
+ if (binding.signKey) {
1138
+ return binding.signKey.format === "openpgp" ? { format: "openpgp", key: binding.signKey.key } : { format: "ssh", key: await signingKeyPath(binding.signKey.path, binding.signKey.fingerprint) };
1139
+ }
1140
+ if (binding.pushKey && await keyUsable(binding.pushKey.path)) {
1141
+ return { format: "ssh", key: await signingKeyPath(binding.pushKey.path, binding.pushKey.fingerprint) };
931
1142
  }
932
1143
  return void 0;
933
1144
  }
@@ -944,12 +1155,10 @@ async function writeIdentitySigning(identity, cwd, askpassScriptPath) {
944
1155
  }
945
1156
  return cfg;
946
1157
  }
947
- async function disableSigning(cwd, managed = true) {
948
- if (managed) {
949
- await unsetConfig("gpg.format", "local", cwd);
950
- await unsetConfig("user.signingKey", "local", cwd);
951
- await unsetConfig("gpg.ssh.program", "local", cwd);
952
- }
1158
+ async function disableSigning(cwd, _managed = true) {
1159
+ await unsetConfig("gpg.format", "local", cwd);
1160
+ await unsetConfig("user.signingKey", "local", cwd);
1161
+ await unsetConfig("gpg.ssh.program", "local", cwd);
953
1162
  await unsetConfig("commit.gpgsign", "local", cwd);
954
1163
  if ((await getEffectiveConfig("commit.gpgsign", cwd, "bool"))?.value === "true") {
955
1164
  await setConfig("commit.gpgsign", "false", "local", cwd);
@@ -957,11 +1166,8 @@ async function disableSigning(cwd, managed = true) {
957
1166
  }
958
1167
  async function setCommitSigning(opts) {
959
1168
  if (!await insideWorkTree(opts.cwd)) throw Errors.notARepo(opts.cwd);
960
- const state = await readState(opts.cwd);
961
1169
  if (!opts.on) {
962
- await disableSigning(opts.cwd, state.signing === true);
963
- state.signing = false;
964
- await writeState(state, opts.cwd);
1170
+ await disableSigning(opts.cwd, false);
965
1171
  await appendAudit({ action: "identity.sign", source: opts.source, identity: opts.id, repo: await safeTopLevel(opts.cwd), result: "ok", message: "signing off" });
966
1172
  return { signing: false };
967
1173
  }
@@ -969,21 +1175,19 @@ async function setCommitSigning(opts) {
969
1175
  const identity = await getIdentity(opts.id);
970
1176
  const cfg = await writeIdentitySigning(identity, opts.cwd, opts.askpassScriptPath);
971
1177
  if (!cfg) throw Errors.usage(`identity "${identity.name}" has no usable SSH or GPG key to sign with`);
972
- state.signing = true;
973
- await writeState(state, opts.cwd);
974
1178
  await appendAudit({
975
1179
  action: "identity.sign",
976
1180
  source: opts.source,
977
1181
  identity: opts.id,
978
1182
  identityName: identity.name,
979
- fingerprint: cfg.format === "ssh" ? identity.sshKeyFingerprint : cfg.key,
1183
+ fingerprint: cfg.key,
980
1184
  repo: await safeTopLevel(opts.cwd),
981
1185
  result: "ok",
982
1186
  message: `signing on (${cfg.format})`
983
1187
  });
984
1188
  return { signing: true, format: cfg.format, key: cfg.key };
985
1189
  }
986
- async function signingStatus(cwd, managed) {
1190
+ async function signingStatus(cwd) {
987
1191
  const [sign, format, key] = await Promise.all([
988
1192
  getEffectiveConfig("commit.gpgsign", cwd, "bool"),
989
1193
  getEffectiveConfig("gpg.format", cwd),
@@ -995,7 +1199,7 @@ async function signingStatus(cwd, managed) {
995
1199
  format: format?.value || "openpgp",
996
1200
  scope: sign?.scope ?? null,
997
1201
  origin: sign?.origin ?? null,
998
- managed
1202
+ managed: sign?.scope === "local"
999
1203
  };
1000
1204
  if (status.enabled && status.format === "openpgp" && status.key) {
1001
1205
  const emails = (await listSigningKeys(cwd, status.key).catch(() => [])).flatMap((k) => k.emails);
@@ -1025,6 +1229,7 @@ function discoverSessionBridge() {
1025
1229
  }
1026
1230
 
1027
1231
  // src/core/identity/apply.ts
1232
+ init_config();
1028
1233
  async function safeTopLevel2(cwd) {
1029
1234
  try {
1030
1235
  return await topLevel(cwd);
@@ -1034,49 +1239,29 @@ async function safeTopLevel2(cwd) {
1034
1239
  }
1035
1240
  async function applyResolvedIdentity(args) {
1036
1241
  const { name, email, sshCommand, identity, opts } = args;
1037
- const session = opts.session ?? (opts.source === "cli" ? cliSessionId() : "ext:unknown");
1038
- const conflict = await detectConflict(session, opts.cwd, opts.staleMinutes);
1039
- if (conflict && opts.noOverride) {
1040
- throw new AppError({
1041
- code: "CONFLICT_BLOCKED",
1042
- message: `repo is held by ${conflict.heldBy.session} (since ${conflict.heldBy.since})`,
1043
- exitCode: 6,
1044
- hints: ["re-run without --no-override to take over"]
1045
- });
1046
- }
1047
- await captureBackupIfFirstTouch(opts.cwd);
1048
1242
  await setConfig("user.name", name, "local", opts.cwd);
1049
1243
  await setConfig("user.email", email, "local", opts.cwd);
1050
1244
  if (sshCommand) {
1051
1245
  await setConfig("core.sshCommand", sshCommand, "local", opts.cwd);
1052
- } else if (identity && !identity.sshKeyPath) {
1246
+ } else if (identity) {
1053
1247
  await unsetConfig("core.sshCommand", "local", opts.cwd);
1248
+ const gpgsign = await getConfig("commit.gpgsign", "local", opts.cwd);
1249
+ if (gpgsign === "true") await disableSigning(opts.cwd);
1054
1250
  }
1055
- await setConfig("colabor.managed", "true", "local", opts.cwd);
1056
- await setConfig("colabor.managed-by", opts.source, "local", opts.cwd);
1057
- const state = await readState(opts.cwd);
1058
- state.activeIdentity = identity?.id;
1059
- state.heldBy = nowHeldBy(session, opts.source);
1060
- if (state.signing === true && identity && !await writeIdentitySigning(identity, opts.cwd, opts.askpassScriptPath)) {
1061
- state.signing = false;
1062
- await disableSigning(opts.cwd);
1063
- }
1064
- await writeState(state, opts.cwd);
1251
+ const binding = identity ? await getKeyBinding(identity.id) : void 0;
1065
1252
  let agent;
1066
- if (identity?.sshKeyFingerprint) {
1067
- agent = { inAgent: await keyInAgent(identity.sshKeyFingerprint) };
1253
+ if (binding?.pushKey) {
1254
+ agent = { inAgent: await keyInAgent(binding.pushKey.fingerprint) };
1068
1255
  }
1069
1256
  await appendAudit({
1070
1257
  action: "identity.use",
1071
1258
  source: opts.source,
1072
1259
  identity: identity?.id,
1073
1260
  identityName: identity?.name ?? name,
1074
- fingerprint: identity?.sshKeyFingerprint,
1075
- repo: await safeTopLevel2(opts.cwd),
1076
- result: conflict ? "warn" : "ok",
1077
- message: conflict ? `overrode ${conflict.heldBy.session}` : void 0
1261
+ fingerprint: binding?.pushKey?.fingerprint,
1262
+ repo: await safeTopLevel2(opts.cwd)
1078
1263
  });
1079
- return { name, email, sshCommand, conflict, agent };
1264
+ return { name, email, sshCommand, keyApplied: !!sshCommand, agent };
1080
1265
  }
1081
1266
  async function ensureAskpassWrapper(askpassScriptPath) {
1082
1267
  const wrapperPath = path.join(dataDir(), "askpass-wrapper.sh");
@@ -1093,30 +1278,26 @@ exec "${process.execPath}" "${askpassScriptPath}" "$@"
1093
1278
  return wrapperPath;
1094
1279
  }
1095
1280
  async function applyIdentity(id, opts) {
1096
- let identity = await getIdentity(id);
1281
+ const identity = await getIdentity(id);
1282
+ const binding = await getKeyBinding(id);
1283
+ const push = binding.pushKey;
1097
1284
  let sshCommand;
1098
- let bridgeUsed = false;
1099
1285
  let keyMissing = false;
1100
- if (identity.sshKeyPath) {
1101
- let imp;
1102
- try {
1103
- imp = await importKey(identity.sshKeyPath);
1104
- } catch {
1105
- imp = void 0;
1106
- }
1107
- if (imp) {
1108
- if (imp.fingerprint !== identity.sshKeyFingerprint || imp.encrypted !== !!identity.sshKeyEncrypted) {
1109
- await updateIdentity(id, { sshKeyFingerprint: imp.fingerprint, sshKeyEncrypted: imp.encrypted });
1110
- identity = { ...identity, sshKeyFingerprint: imp.fingerprint, sshKeyEncrypted: imp.encrypted };
1286
+ const keyDegraded = false;
1287
+ if (push) {
1288
+ if (await keyUsable(push.path)) {
1289
+ const fp = await fingerprintOfFile(push.path).catch(() => void 0);
1290
+ if (fp && fp !== push.fingerprint) {
1291
+ await setPushKey(id, { ...push, fingerprint: fp });
1292
+ push.fingerprint = fp;
1111
1293
  }
1112
- const bare = `ssh -i ${identity.sshKeyPath} -o IdentitiesOnly=yes`;
1294
+ const bare2 = `ssh -i ${push.path} -o IdentitiesOnly=yes`;
1113
1295
  const bridge = opts.socketPath && opts.token || discoverSessionBridge();
1114
1296
  if (opts.askpassScriptPath && bridge) {
1115
1297
  const wrapper = await ensureAskpassWrapper(opts.askpassScriptPath);
1116
- sshCommand = `SSH_ASKPASS="${wrapper}" SSH_ASKPASS_REQUIRE=force DISPLAY=:0 ${bare}`;
1117
- bridgeUsed = true;
1298
+ sshCommand = `SSH_ASKPASS="${wrapper}" SSH_ASKPASS_REQUIRE=force DISPLAY=:0 ${bare2}`;
1118
1299
  } else {
1119
- sshCommand = bare;
1300
+ sshCommand = bare2;
1120
1301
  }
1121
1302
  } else {
1122
1303
  keyMissing = true;
@@ -1126,67 +1307,96 @@ async function applyIdentity(id, opts) {
1126
1307
  name: opts.asName ?? identity.name,
1127
1308
  email: opts.asEmail ?? identity.email,
1128
1309
  sshCommand,
1129
- identity: keyMissing ? { ...identity, sshKeyPath: void 0 } : identity,
1310
+ identity,
1130
1311
  opts
1131
1312
  });
1132
1313
  result.keyMissing = keyMissing;
1133
- result.bridgeUsed = bridgeUsed;
1314
+ result.keyDegraded = keyDegraded;
1315
+ if (identity) {
1316
+ const gpgsign = await getConfig("commit.gpgsign", "local", opts.cwd);
1317
+ if (gpgsign === "true") {
1318
+ const okSign = await writeIdentitySigning(identity, opts.cwd, opts.askpassScriptPath);
1319
+ if (!okSign) await disableSigning(opts.cwd);
1320
+ }
1321
+ }
1134
1322
  return { identity, result };
1135
1323
  }
1136
1324
 
1137
- // src/core/identity/revert.ts
1138
- async function safeTopLevel3(cwd) {
1325
+ // src/index.ts
1326
+ init_configClear();
1327
+
1328
+ // src/core/identity/logout.ts
1329
+ init_rev();
1330
+
1331
+ // src/core/identity/resolve.ts
1332
+ init_config();
1333
+ var norm = (s) => s.trim().toLowerCase();
1334
+ function keyPathFromSshCommand(cmd) {
1335
+ if (!cmd) return void 0;
1336
+ const m = cmd.match(/(?:^|\s)-i\s+(\S+)/);
1337
+ return m?.[1];
1338
+ }
1339
+ async function fpOf(path) {
1139
1340
  try {
1140
- return await topLevel(cwd);
1341
+ return await fingerprintOfFile(path);
1141
1342
  } catch {
1142
1343
  return void 0;
1143
1344
  }
1144
1345
  }
1145
- async function restoreKey(key, value, cwd) {
1146
- if (value === void 0) await unsetConfig(key, "local", cwd);
1147
- else await setConfig(key, value, "local", cwd);
1148
- }
1149
- async function revertRepo(opts) {
1150
- const state = await readState(opts.cwd);
1151
- const backups = state.backups;
1152
- const managed = await getConfig("colabor.managed", "local", opts.cwd);
1153
- if (backups) {
1154
- await restoreKey("user.name", backups.userName, opts.cwd);
1155
- await restoreKey("user.email", backups.userEmail, opts.cwd);
1156
- await restoreKey("core.sshCommand", backups.sshCommand, opts.cwd);
1157
- await restoreKey("commit.template", backups.commitTemplate, opts.cwd);
1158
- await restoreKey("commit.gpgsign", backups.commitGpgsign, opts.cwd);
1159
- await restoreKey("gpg.format", backups.gpgFormat, opts.cwd);
1160
- await restoreKey("user.signingKey", backups.signingKey, opts.cwd);
1161
- }
1162
- if (state.activeIdentity) {
1163
- try {
1164
- const id = await getIdentity(state.activeIdentity);
1165
- if (id.sshKeyPath) await removeKey(id.sshKeyPath);
1166
- } catch {
1346
+ async function resolveActive(cwd, opts = {}) {
1347
+ const [n, e] = await Promise.all([
1348
+ getEffectiveConfig("user.name", cwd),
1349
+ getEffectiveConfig("user.email", cwd)
1350
+ ]);
1351
+ if (!n?.value || !e?.value) return void 0;
1352
+ const name = n.value;
1353
+ const email = e.value;
1354
+ const { identities } = await listIdentities();
1355
+ const byEmail = identities.filter((i) => norm(i.email) === norm(email));
1356
+ let match = byEmail.find((i) => norm(i.name) === norm(name));
1357
+ let enrolled = false;
1358
+ if (!match) {
1359
+ if (!opts.enroll) return void 0;
1360
+ match = await addIdentity({ name, email, scope: "machine", fromConfig: true });
1361
+ enrolled = true;
1362
+ }
1363
+ const sshCmd = await getEffectiveConfig("core.sshCommand", cwd);
1364
+ const cfgPushPath = keyPathFromSshCommand(sshCmd?.value);
1365
+ if (cfgPushPath) {
1366
+ const fp = await fpOf(cfgPushPath);
1367
+ const binding = await getKeyBinding(match.id);
1368
+ if (!binding.pushKey || binding.pushKey.path !== cfgPushPath || fp && binding.pushKey.fingerprint !== fp) {
1369
+ const ref = { path: cfgPushPath, fingerprint: fp ?? binding.pushKey?.fingerprint ?? "" };
1370
+ await setPushKey(match.id, ref);
1167
1371
  }
1168
1372
  }
1169
- await unsetConfig("colabor.managed", "local", opts.cwd);
1170
- await unsetConfig("colabor.managed-by", "local", opts.cwd);
1171
- await unsetAllConfig("colabor.selected", "local", opts.cwd);
1172
- await clearTemplate(opts.cwd).catch(() => {
1173
- });
1174
- state.activeIdentity = void 0;
1175
- state.backups = void 0;
1176
- state.heldBy = void 0;
1177
- await writeState(state, opts.cwd);
1178
- await appendAudit({
1179
- action: "identity.revert",
1180
- source: opts.source,
1181
- repo: await safeTopLevel3(opts.cwd),
1182
- result: managed === "true" ? "ok" : "warn",
1183
- message: managed === "true" ? void 0 : "repo was not managed"
1184
- });
1185
- return { restored: backups, hadBackup: !!backups };
1373
+ const signKeyCfg = await getEffectiveConfig("user.signingKey", cwd);
1374
+ const gpgFormat = await getEffectiveConfig("gpg.format", cwd);
1375
+ if (signKeyCfg?.value) {
1376
+ const binding = await getKeyBinding(match.id);
1377
+ const cur = binding.signKey;
1378
+ if (gpgFormat?.value === "openpgp") {
1379
+ if (!cur || cur.format !== "openpgp" || cur.key !== signKeyCfg.value) {
1380
+ await setSignKey(match.id, { format: "openpgp", key: signKeyCfg.value });
1381
+ }
1382
+ } else {
1383
+ const path = signKeyCfg.value.replace(/\.pub$/, "");
1384
+ if (!cur || cur.format !== "ssh" || cur.path !== path) {
1385
+ const fp = await fpOf(path);
1386
+ if (fp) await setSignKey(match.id, { format: "ssh", path, fingerprint: fp });
1387
+ }
1388
+ }
1389
+ }
1390
+ const finalBinding = await getKeyBinding(match.id);
1391
+ return {
1392
+ identity: match,
1393
+ enrolled,
1394
+ keyPref: { push: !!finalBinding.pushKey, sign: !!finalBinding.signKey }
1395
+ };
1186
1396
  }
1187
1397
 
1188
1398
  // src/core/identity/logout.ts
1189
- async function safeTopLevel4(cwd) {
1399
+ async function safeTopLevel3(cwd) {
1190
1400
  try {
1191
1401
  return await topLevel(cwd);
1192
1402
  } catch {
@@ -1194,35 +1404,52 @@ async function safeTopLevel4(cwd) {
1194
1404
  }
1195
1405
  }
1196
1406
  async function logoutIdentity(opts) {
1197
- const state = await readState(opts.cwd);
1198
- let id = opts.id ?? state.activeIdentity;
1407
+ const resolved = await resolveActive(opts.cwd);
1408
+ let id = opts.id ?? resolved?.identity.id;
1199
1409
  if (!id) {
1200
1410
  const { identities } = await listIdentities();
1201
1411
  if (identities.length === 1) id = identities[0].id;
1202
1412
  else throw Errors.usage("no active identity \u2014 specify one: git colabor identity logout <id>");
1203
1413
  }
1204
1414
  const identity = await getIdentity(id);
1205
- const agentRemoved = identity.sshKeyPath ? await removeKey(identity.sshKeyPath) : false;
1206
- if (state.activeIdentity === identity.id) {
1207
- state.activeIdentity = void 0;
1208
- state.heldBy = void 0;
1209
- if (state.signing === true) {
1210
- state.signing = false;
1211
- await disableSigning(opts.cwd);
1212
- }
1213
- await writeState(state, opts.cwd);
1415
+ const binding = await getKeyBinding(id);
1416
+ const agentRemoved = binding.pushKey ? await removeKey(binding.pushKey.path) : false;
1417
+ const { clearIdentityConfigLayer: clearIdentityConfigLayer2 } = await Promise.resolve().then(() => (init_configClear(), configClear_exports));
1418
+ const cleared = await clearIdentityConfigLayer2(
1419
+ {
1420
+ name: identity.name,
1421
+ email: identity.email,
1422
+ pushKeyPath: binding.pushKey?.path,
1423
+ signKey: binding.signKey
1424
+ },
1425
+ { cwd: opts.cwd, forceKeys: resolved?.identity.id === id }
1426
+ );
1427
+ const clearedAnything = cleared.identityLayer || cleared.sshCommand || cleared.signing;
1428
+ if (cleared.identityLayer) {
1429
+ const { unsetAllConfig: unsetAllConfig2 } = await Promise.resolve().then(() => (init_config(), config_exports));
1430
+ const { clearTemplate: clearTemplate2 } = await Promise.resolve().then(() => (init_template(), template_exports));
1431
+ await unsetAllConfig2("colabor.selected", "local", opts.cwd);
1432
+ await clearTemplate2(opts.cwd).catch(() => {
1433
+ });
1214
1434
  }
1215
1435
  await appendAudit({
1216
1436
  action: "identity.logout",
1217
1437
  source: opts.source,
1218
1438
  identity: identity.id,
1219
1439
  identityName: identity.name,
1220
- fingerprint: identity.sshKeyFingerprint,
1221
- repo: await safeTopLevel4(opts.cwd)
1440
+ fingerprint: binding.pushKey?.fingerprint,
1441
+ repo: await safeTopLevel3(opts.cwd),
1442
+ message: clearedAnything ? `cleared ${[cleared.identityLayer ? "config" : null, cleared.sshCommand ? "ssh key" : null, cleared.signing ? "sign key" : null].filter(Boolean).join(" + ")} + agent` : "agent only"
1222
1443
  });
1223
1444
  return {
1224
- identity: { id: identity.id, name: identity.name, fingerprint: identity.sshKeyFingerprint },
1225
- agentRemoved
1445
+ identity: { id: identity.id, name: identity.name, fingerprint: binding.pushKey?.fingerprint },
1446
+ agentRemoved,
1447
+ cleared: {
1448
+ agent: agentRemoved,
1449
+ config: cleared.identityLayer,
1450
+ sshCommand: cleared.sshCommand,
1451
+ signing: cleared.signing
1452
+ }
1226
1453
  };
1227
1454
  }
1228
1455
  var SOCKET_TIMEOUT_MS = 3e3;
@@ -1281,11 +1508,8 @@ async function promptPassphraseTty(prompt) {
1281
1508
  }
1282
1509
 
1283
1510
  exports.AppError = AppError;
1284
- exports.Author = Author;
1285
- exports.CO_AUTHOR_TRAILER = CO_AUTHOR_TRAILER;
1286
1511
  exports.EXIT_CODES = EXIT_CODES;
1287
1512
  exports.Errors = Errors;
1288
- exports.GitError = GitError;
1289
1513
  exports.addConfigValue = addConfigValue;
1290
1514
  exports.addIdentity = addIdentity;
1291
1515
  exports.addRedactable = addRedactable;
@@ -1297,6 +1521,7 @@ exports.askSocket = askSocket;
1297
1521
  exports.atomicWriteJson = atomicWriteJson;
1298
1522
  exports.auditLogPath = auditLogPath;
1299
1523
  exports.captureBackupIfFirstTouch = captureBackupIfFirstTouch;
1524
+ exports.clearIdentityConfigLayer = clearIdentityConfigLayer;
1300
1525
  exports.clearSelected = clearSelected;
1301
1526
  exports.clearTemplate = clearTemplate;
1302
1527
  exports.cliSessionId = cliSessionId;
@@ -1308,14 +1533,15 @@ exports.disableSigning = disableSigning;
1308
1533
  exports.ensureAskpassWrapper = ensureAskpassWrapper;
1309
1534
  exports.ensureCommitTemplate = ensureCommitTemplate;
1310
1535
  exports.ensureSignWrapper = ensureSignWrapper;
1536
+ exports.findIdentity = findIdentity;
1311
1537
  exports.fingerprintOfFile = fingerprintOfFile;
1312
1538
  exports.formatMessage = formatMessage;
1313
- exports.genId = genId;
1314
1539
  exports.genKey = genKey;
1315
1540
  exports.getAllConfig = getAllConfig;
1316
1541
  exports.getConfig = getConfig;
1317
1542
  exports.getEffectiveConfig = getEffectiveConfig;
1318
1543
  exports.getIdentity = getIdentity;
1544
+ exports.getKeyBinding = getKeyBinding;
1319
1545
  exports.getSelected = getSelected;
1320
1546
  exports.git = git;
1321
1547
  exports.gitDir = gitDir;
@@ -1324,6 +1550,7 @@ exports.gitRaw = gitRaw;
1324
1550
  exports.headSha = headSha;
1325
1551
  exports.hideIdentityEmail = hideIdentityEmail;
1326
1552
  exports.historyCommitters = historyCommitters;
1553
+ exports.identityId = identityId;
1327
1554
  exports.importKey = importKey;
1328
1555
  exports.insideWorkTree = insideWorkTree;
1329
1556
  exports.isEncrypted = isEncrypted;
@@ -1354,12 +1581,14 @@ exports.repoAuthors = repoAuthors;
1354
1581
  exports.repoStatus = repoStatus;
1355
1582
  exports.resolvePassphrase = resolvePassphrase;
1356
1583
  exports.resolveTemplatePath = resolveTemplatePath;
1357
- exports.revertRepo = revertRepo;
1358
1584
  exports.runBin = runBin;
1359
1585
  exports.setCommitSigning = setCommitSigning;
1360
1586
  exports.setConfig = setConfig;
1361
1587
  exports.setDefault = setDefault;
1588
+ exports.setKeyBinding = setKeyBinding;
1589
+ exports.setPushKey = setPushKey;
1362
1590
  exports.setSelected = setSelected;
1591
+ exports.setSignKey = setSignKey;
1363
1592
  exports.signingStatus = signingStatus;
1364
1593
  exports.statePath = statePath;
1365
1594
  exports.toErrorPayload = toErrorPayload;