@myrialabs/clopen 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -36,6 +36,7 @@ export const ADMIN_ONLY_ROUTES = new Set([
36
36
  'projects:create',
37
37
  'projects:delete',
38
38
  'settings:update',
39
+ 'settings:update-system',
39
40
  'settings:update-batch',
40
41
  'system:run-update',
41
42
  'system:clear-data',
@@ -101,7 +101,16 @@ export function parseStatus(output: string): GitStatus {
101
101
  }
102
102
 
103
103
  /**
104
- * Parse `git branch -a -v --format` output
104
+ * Parse `git for-each-ref` output for branches into structured info.
105
+ *
106
+ * Expects lines in the custom format produced by `gitService.getBranches`:
107
+ * - local: `*|main|abc1234|commit subject|2024-01-15T10:30:00+07:00`
108
+ * ` |dev |abc1234|another subject|2024-01-14T09:00:00+07:00`
109
+ * - remote: `origin/main|abc1234|commit subject|2024-01-15T10:30:00+07:00`
110
+ *
111
+ * The date is strict ISO 8601 and never contains `|`, so `lastIndexOf('|')`
112
+ * safely extracts it. The subject (which may itself contain `|`) is kept
113
+ * whole by limiting the head split to 4 / 3 parts.
105
114
  */
106
115
  export function parseBranches(localOutput: string, remoteOutput: string): GitBranchInfo {
107
116
  const local: GitBranch[] = [];
@@ -111,23 +120,18 @@ export function parseBranches(localOutput: string, remoteOutput: string): GitBra
111
120
  // Parse local branches
112
121
  const localLines = localOutput.split('\n').filter(Boolean);
113
122
  for (const line of localLines) {
114
- // Format: "* main abc1234 commit message" or " dev abc1234 commit message"
115
- const isCurrent = line.startsWith('*');
116
- const trimmed = line.replace(/^\*?\s+/, '');
117
-
118
- // When HEAD is detached, git emits a parenthesized pseudo-ref instead of a
119
- // branch name, e.g. "* (no branch, rebasing main)" or "* (HEAD detached at
120
- // abc1234)". These are not real branches — skip them so they never leak into
121
- // the branch list or get treated as the current branch (which produced the
122
- // bogus "(no" branch name). Match git's exact pseudo-ref prefixes so legit
123
- // branch names containing parentheses (e.g. "feature(x)") are preserved. The
124
- // real current branch / detached state is resolved authoritatively in
125
- // git-service. Output is forced to en_US locale, so these strings are stable.
126
- if (isCurrent && /^\((?:HEAD detached|no branch)\b/.test(trimmed)) continue;
127
-
128
- const parts = trimmed.split(/\s+/);
129
- const name = parts[0];
130
- const lastCommit = parts[1] || '';
123
+ const dateSep = line.lastIndexOf('|');
124
+ if (dateSep === -1) continue;
125
+ const lastCommitDate = line.substring(dateSep + 1);
126
+ const head = line.substring(0, dateSep);
127
+
128
+ // head = "<*>|<name>|<hash>|<subject>"
129
+ const parts = head.split('|', 4);
130
+ if (parts.length < 4) continue;
131
+ const isCurrent = parts[0] === '*';
132
+ const name = parts[1];
133
+ const lastCommit = parts[2];
134
+ const lastCommitMessage = parts[3];
131
135
 
132
136
  if (isCurrent) current = name;
133
137
 
@@ -137,18 +141,30 @@ export function parseBranches(localOutput: string, remoteOutput: string): GitBra
137
141
  isRemote: false,
138
142
  ahead: 0,
139
143
  behind: 0,
140
- lastCommit
141
- });
144
+ lastCommit,
145
+ lastCommitMessage,
146
+ lastCommitDate
147
+ } as GitBranch);
142
148
  }
143
149
 
144
150
  // Parse remote branches
145
151
  const remoteLines = remoteOutput.split('\n').filter(Boolean);
146
152
  for (const line of remoteLines) {
147
- const trimmed = line.trim();
148
- if (trimmed.includes('->')) continue; // Skip HEAD pointers
149
- const parts = trimmed.split(/\s+/);
153
+ const dateSep = line.lastIndexOf('|');
154
+ if (dateSep === -1) continue;
155
+ const lastCommitDate = line.substring(dateSep + 1);
156
+ const head = line.substring(0, dateSep);
157
+
158
+ // head = "<name>|<hash>|<subject>"
159
+ const parts = head.split('|', 3);
160
+ if (parts.length < 3) continue;
150
161
  const name = parts[0];
151
- const lastCommit = parts[1] || '';
162
+ // Skip symbolic HEAD pointers like `origin/HEAD -> origin/main`
163
+ // (these only show up in the old `git branch -r` output, not in
164
+ // `for-each-ref refs/remotes/`, but guard anyway).
165
+ if (name.endsWith('/HEAD')) continue;
166
+ const lastCommit = parts[1];
167
+ const lastCommitMessage = parts[2];
152
168
 
153
169
  remote.push({
154
170
  name,
@@ -156,8 +172,10 @@ export function parseBranches(localOutput: string, remoteOutput: string): GitBra
156
172
  isRemote: true,
157
173
  ahead: 0,
158
174
  behind: 0,
159
- lastCommit
160
- });
175
+ lastCommit,
176
+ lastCommitMessage,
177
+ lastCommitDate
178
+ } as GitBranch);
161
179
  }
162
180
 
163
181
  return { current, local, remote, ahead: 0, behind: 0 };
@@ -342,19 +360,30 @@ export function parseRemotes(output: string): GitRemote[] {
342
360
  }
343
361
 
344
362
  /**
345
- * Parse `git stash list` output
363
+ * Parse `git stash list` output.
364
+ *
365
+ * Expects lines in the custom format produced by `git stash list --format="%gd: %gs | %cI"`:
366
+ * `stash@{0}: WIP on main: abc1234 message | 2024-01-15T10:30:00+07:00`
367
+ *
368
+ * The ` | ` separator is safe because `%cI` (strict ISO 8601) never contains it.
369
+ * Falls back to the plain format (`stash@{N}: message`) when the separator is
370
+ * missing — e.g. older snapshots or a git version that ignores `--format`.
346
371
  */
347
372
  export function parseStashList(output: string): GitStashEntry[] {
348
373
  const entries: GitStashEntry[] = [];
349
374
  const lines = output.split('\n').filter(Boolean);
350
375
 
351
376
  for (const line of lines) {
352
- const match = line.match(/^stash@\{(\d+)\}:\s*(.+)$/);
377
+ const sepIdx = line.lastIndexOf(' | ');
378
+ const head = sepIdx === -1 ? line : line.substring(0, sepIdx);
379
+ const date = sepIdx === -1 ? '' : line.substring(sepIdx + 3);
380
+
381
+ const match = head.match(/^stash@\{(\d+)\}:\s*(.+)$/);
353
382
  if (match) {
354
383
  entries.push({
355
384
  index: parseInt(match[1]),
356
385
  message: match[2],
357
- date: ''
386
+ date
358
387
  });
359
388
  }
360
389
  }
@@ -233,14 +233,23 @@ export class GitService {
233
233
  // Branches
234
234
  // ============================================
235
235
 
236
- async getBranches(cwd: string): Promise<GitBranchInfo> {
236
+ async getBranches(cwd: string, selectedRemote?: string): Promise<GitBranchInfo> {
237
+ // `git for-each-ref` lets us pull the committer date alongside the
238
+ // short hash and subject in a single call per ref namespace, which
239
+ // the old `git branch -v` output doesn't expose. Format:
240
+ // `HEAD|short-name|short-hash|subject|iso-date`
241
+ // where `HEAD` is `*` for the current branch and ` ` for others.
242
+ // `iso-date` is strict ISO 8601 so it can't collide with the `|`
243
+ // separators — the parser uses `lastIndexOf('|')` to extract it.
244
+ const localFmt = '%(HEAD)|%(refname:short)|%(objectname:short)|%(subject)|%(committerdate:iso8601)';
245
+ const remoteFmt = '%(refname:short)|%(objectname:short)|%(subject)|%(committerdate:iso8601)';
237
246
  const [localResult, remoteResult, headRef] = await Promise.all([
238
- execGit(['branch', '-v', '--no-color'], cwd),
239
- execGit(['branch', '-r', '-v', '--no-color'], cwd),
247
+ execGit(['for-each-ref', `--format=${localFmt}`, 'refs/heads/'], cwd),
248
+ execGit(['for-each-ref', `--format=${remoteFmt}`, 'refs/remotes/'], cwd),
240
249
  execGit(['rev-parse', '--abbrev-ref', 'HEAD'], cwd)
241
250
  ]);
242
251
 
243
- // Handle empty repo (no commits yet) — branch command returns empty
252
+ // Handle empty repo (no commits yet) — for-each-ref returns empty
244
253
  if (!localResult.stdout.trim()) {
245
254
  // Try to get the initial branch name from HEAD
246
255
  const headResult = await execGit(['symbolic-ref', '--short', 'HEAD'], cwd);
@@ -269,11 +278,12 @@ export class GitService {
269
278
  branchInfo.current = headName;
270
279
  for (const b of branchInfo.local) b.isCurrent = b.name === headName;
271
280
 
272
- // Get ahead/behind for current branch
273
- if (branchInfo.current) {
281
+ // Get ahead/behind for current branch relative to the SELECTED remote
282
+ if (branchInfo.current && selectedRemote) {
274
283
  try {
284
+ const remoteRef = `${selectedRemote}/${branchInfo.current}`;
275
285
  const abResult = await execGit(
276
- ['rev-list', '--left-right', '--count', `${branchInfo.current}...@{upstream}`],
286
+ ['rev-list', '--left-right', '--count', `${branchInfo.current}...${remoteRef}`],
277
287
  cwd
278
288
  );
279
289
  if (abResult.exitCode === 0) {
@@ -281,7 +291,6 @@ export class GitService {
281
291
  branchInfo.ahead = ahead;
282
292
  branchInfo.behind = behind;
283
293
 
284
- // Update the current branch entry too
285
294
  const currentBranch = branchInfo.local.find(b => b.isCurrent);
286
295
  if (currentBranch) {
287
296
  currentBranch.ahead = ahead;
@@ -289,7 +298,7 @@ export class GitService {
289
298
  }
290
299
  }
291
300
  } catch {
292
- // No upstream configured
301
+ // Remote tracking branch doesn't exist — show 0
293
302
  }
294
303
  }
295
304
 
@@ -343,6 +352,15 @@ export class GitService {
343
352
  }
344
353
  }
345
354
 
355
+ async deleteRemoteBranch(cwd: string, remote: string, branch: string): Promise<void> {
356
+ assertSafeGitRevish(remote, 'remote name');
357
+ assertSafeGitRevish(branch, 'branch name');
358
+ const result = await execGit(['push', remote, '--delete', branch], cwd);
359
+ if (result.exitCode !== 0) {
360
+ throw new Error(`git push --delete failed: ${result.stderr}`);
361
+ }
362
+ }
363
+
346
364
  async mergeBranch(cwd: string, branchName: string, noFastForward = false): Promise<{ success: boolean; message: string }> {
347
365
  assertSafeGitRevish(branchName, 'merge branch');
348
366
  const args = ['merge'];
@@ -497,6 +515,25 @@ export class GitService {
497
515
  }
498
516
  }
499
517
 
518
+ async setRemoteUrl(cwd: string, name: string, url: string): Promise<void> {
519
+ assertSafeGitRemoteName(name);
520
+ assertSafeGitRemoteUrl(url);
521
+ const result = await execGit(['remote', 'set-url', name, url], cwd);
522
+ if (result.exitCode !== 0) {
523
+ throw new Error(`git remote set-url failed: ${result.stderr}`);
524
+ }
525
+ }
526
+
527
+ async renameRemote(cwd: string, oldName: string, newName: string): Promise<void> {
528
+ assertSafeGitRemoteName(oldName);
529
+ assertSafeGitRemoteName(newName);
530
+ if (oldName === newName) return;
531
+ const result = await execGit(['remote', 'rename', oldName, newName], cwd);
532
+ if (result.exitCode !== 0) {
533
+ throw new Error(`git remote rename failed: ${result.stderr}`);
534
+ }
535
+ }
536
+
500
537
  async removeRemote(cwd: string, name: string): Promise<void> {
501
538
  assertSafeGitRemoteName(name);
502
539
  const result = await execGit(['remote', 'remove', name], cwd);
@@ -510,7 +547,11 @@ export class GitService {
510
547
  // ============================================
511
548
 
512
549
  async stashList(cwd: string): Promise<GitStashEntry[]> {
513
- const result = await execGit(['stash', 'list'], cwd);
550
+ // Custom format appends the committer date (ISO 8601) after a ` | `
551
+ // separator so the parser can extract it. The default `git stash list`
552
+ // output has no date. `%cI` is the strict ISO format — it contains
553
+ // colons and dashes but never ` | `, so the lastIndexOf split is safe.
554
+ const result = await execGit(['stash', 'list', '--format=%gd: %gs | %cI'], cwd);
514
555
  return parseStashList(result.stdout);
515
556
  }
516
557
 
@@ -558,6 +599,19 @@ export class GitService {
558
599
  }
559
600
  }
560
601
 
602
+ async stashDiff(cwd: string, index = 0): Promise<GitFileDiff[]> {
603
+ if (!Number.isInteger(index) || index < 0) {
604
+ throw new Error('Invalid stash index');
605
+ }
606
+ // `git stash show -p stash@{N}` produces a unified diff in the
607
+ // same format as `git diff`, so `parseDiff` handles it unchanged.
608
+ const result = await execGit(['stash', 'show', '-p', `stash@{${index}}`], cwd);
609
+ if (result.exitCode !== 0) {
610
+ throw new Error(`git stash show failed: ${result.stderr}`);
611
+ }
612
+ return parseDiff(result.stdout);
613
+ }
614
+
561
615
  // ============================================
562
616
  // Tags
563
617
  // ============================================
@@ -759,6 +813,21 @@ export class GitService {
759
813
  };
760
814
  }
761
815
 
816
+ /** Cherry-pick one or more commits onto the current branch (`git cherry-pick <hash>...`). */
817
+ async cherryPick(cwd: string, refs: string[]): Promise<{ success: boolean; message: string }> {
818
+ if (refs.length === 0) {
819
+ return { success: false, message: 'No commits provided' };
820
+ }
821
+ for (const ref of refs) {
822
+ assertSafeGitRevish(ref, 'cherry-pick ref');
823
+ }
824
+ const result = await execGit(['cherry-pick', ...refs], cwd);
825
+ return {
826
+ success: result.exitCode === 0,
827
+ message: result.exitCode === 0 ? (result.stdout || result.stderr || 'Cherry-pick succeeded') : result.stderr
828
+ };
829
+ }
830
+
762
831
  // ============================================
763
832
  // Maintenance
764
833
  // ============================================
@@ -25,11 +25,11 @@ export function assertSafeGitRevish(value: string, label: string): void {
25
25
  }
26
26
  }
27
27
 
28
- /** `git remote` names are a small charset in practice; keep strict. */
28
+ /** `git remote` names — allow common refname chars (slashes for hierarchies, plus signs). */
29
29
  export function assertSafeGitRemoteName(name: string): void {
30
30
  assertSafeGitRevish(name, 'remote name');
31
- if (!/^[A-Za-z0-9._-]+$/.test(name)) {
32
- throw new Error('Invalid git remote name');
31
+ if (!/^[A-Za-z0-9._\-+/]+$/.test(name)) {
32
+ throw new Error(`Invalid git remote name "${name}": only letters, digits, '.', '_', '-', '+', '/' allowed`);
33
33
  }
34
34
  }
35
35
 
@@ -20,7 +20,8 @@ const BranchSchema = t.Object({
20
20
  export const branchHandler = createRouter()
21
21
  .http('git:branches', {
22
22
  data: t.Object({
23
- projectId: t.String()
23
+ projectId: t.String(),
24
+ selectedRemote: t.Optional(t.String())
24
25
  }),
25
26
  response: t.Object({
26
27
  current: t.String(),
@@ -31,7 +32,7 @@ export const branchHandler = createRouter()
31
32
  })
32
33
  }, async ({ data, conn }) => {
33
34
  const project = requireProjectAccess(conn, data.projectId);
34
- return await gitService.getBranches(project.path);
35
+ return await gitService.getBranches(project.path, data.selectedRemote);
35
36
  })
36
37
 
37
38
  .http('git:create-branch', {
@@ -62,6 +62,20 @@ export const commitHandler = createRouter()
62
62
  return await gitService.revertCommit(project.path, data.ref);
63
63
  })
64
64
 
65
+ .http('git:cherry-pick', {
66
+ data: t.Object({
67
+ projectId: t.String(),
68
+ hashes: t.Array(t.String(), { minItems: 1 })
69
+ }),
70
+ response: t.Object({
71
+ success: t.Boolean(),
72
+ message: t.String()
73
+ })
74
+ }, async ({ data, conn }) => {
75
+ const project = requireProjectAccess(conn, data.projectId);
76
+ return await gitService.cherryPick(project.path, data.hashes);
77
+ })
78
+
65
79
  .http('git:clean', {
66
80
  data: t.Object({
67
81
  projectId: t.String()
@@ -115,6 +115,49 @@ export const remoteHandler = createRouter()
115
115
  return { ok: true };
116
116
  })
117
117
 
118
+ .http('git:set-remote-url', {
119
+ data: t.Object({
120
+ projectId: t.String(),
121
+ name: t.String(),
122
+ url: t.String()
123
+ }),
124
+ response: t.Object({ ok: t.Boolean() })
125
+ }, async ({ data, conn }) => {
126
+ const project = requireProjectAccess(conn, data.projectId);
127
+ await gitService.setRemoteUrl(project.path, data.name, data.url);
128
+ return { ok: true };
129
+ })
130
+
131
+ .http('git:rename-remote', {
132
+ data: t.Object({
133
+ projectId: t.String(),
134
+ oldName: t.String(),
135
+ newName: t.String()
136
+ }),
137
+ response: t.Object({ ok: t.Boolean() })
138
+ }, async ({ data, conn }) => {
139
+ const project = requireProjectAccess(conn, data.projectId);
140
+ await gitService.renameRemote(project.path, data.oldName, data.newName);
141
+ return { ok: true };
142
+ })
143
+
144
+ .http('git:edit-remote', {
145
+ data: t.Object({
146
+ projectId: t.String(),
147
+ oldName: t.String(),
148
+ newName: t.String(),
149
+ newUrl: t.String()
150
+ }),
151
+ response: t.Object({ ok: t.Boolean() })
152
+ }, async ({ data, conn }) => {
153
+ const project = requireProjectAccess(conn, data.projectId);
154
+ if (data.oldName !== data.newName) {
155
+ await gitService.renameRemote(project.path, data.oldName, data.newName);
156
+ }
157
+ await gitService.setRemoteUrl(project.path, data.newName, data.newUrl);
158
+ return { ok: true };
159
+ })
160
+
118
161
  .http('git:remove-remote', {
119
162
  data: t.Object({
120
163
  projectId: t.String(),
@@ -127,6 +170,19 @@ export const remoteHandler = createRouter()
127
170
  return { ok: true };
128
171
  })
129
172
 
173
+ .http('git:delete-remote-branch', {
174
+ data: t.Object({
175
+ projectId: t.String(),
176
+ remote: t.String(),
177
+ branch: t.String()
178
+ }),
179
+ response: t.Object({ ok: t.Boolean() })
180
+ }, async ({ data, conn }) => {
181
+ const project = requireProjectAccess(conn, data.projectId);
182
+ await gitService.deleteRemoteBranch(project.path, data.remote, data.branch);
183
+ return { ok: true };
184
+ })
185
+
130
186
  .http('git:stash-list', {
131
187
  data: t.Object({
132
188
  projectId: t.String()
@@ -180,6 +236,35 @@ export const remoteHandler = createRouter()
180
236
  return { ok: true };
181
237
  })
182
238
 
239
+ .http('git:stash-diff', {
240
+ data: t.Object({
241
+ projectId: t.String(),
242
+ index: t.Optional(t.Number())
243
+ }),
244
+ response: t.Array(t.Object({
245
+ oldPath: t.String(),
246
+ newPath: t.String(),
247
+ status: t.String(),
248
+ hunks: t.Array(t.Object({
249
+ oldStart: t.Number(),
250
+ oldLines: t.Number(),
251
+ newStart: t.Number(),
252
+ newLines: t.Number(),
253
+ header: t.String(),
254
+ lines: t.Array(t.Object({
255
+ type: t.Union([t.Literal('add'), t.Literal('delete'), t.Literal('context'), t.Literal('header')]),
256
+ content: t.String(),
257
+ oldLineNumber: t.Optional(t.Number()),
258
+ newLineNumber: t.Optional(t.Number())
259
+ }))
260
+ })),
261
+ isBinary: t.Boolean()
262
+ }))
263
+ }, async ({ data, conn }) => {
264
+ const project = requireProjectAccess(conn, data.projectId);
265
+ return await gitService.stashDiff(project.path, data.index);
266
+ })
267
+
183
268
  .http('git:tags', {
184
269
  data: t.Object({
185
270
  projectId: t.String()
@@ -54,6 +54,37 @@ export const crudHandler = createRouter()
54
54
  return setting;
55
55
  })
56
56
 
57
+ // Merge-update system settings (admin only).
58
+ // Reads the current `system:settings` blob, merges the provided patch, and
59
+ // writes it back atomically. Sending only the changed keys prevents a partial
60
+ // update from clobbering sibling fields (e.g. onboardingComplete) when a
61
+ // client's in-memory copy of the settings is stale.
62
+ .http('settings:update-system', {
63
+ data: t.Object({
64
+ patch: t.Record(t.String(), t.Any())
65
+ }),
66
+ response: t.Any()
67
+ }, async ({ data }) => {
68
+ const KEY = 'system:settings';
69
+ const existing = settingsQueries.get(KEY);
70
+
71
+ let current: Record<string, unknown> = {};
72
+ if (existing?.value) {
73
+ try {
74
+ current = typeof existing.value === 'string'
75
+ ? JSON.parse(existing.value)
76
+ : (existing.value as Record<string, unknown>);
77
+ } catch {
78
+ current = {};
79
+ }
80
+ }
81
+
82
+ const merged = { ...current, ...data.patch };
83
+ settingsQueries.set(KEY, JSON.stringify(merged));
84
+
85
+ return settingsQueries.get(KEY);
86
+ })
87
+
57
88
  // Batch update multiple settings
58
89
  .http('settings:update-batch', {
59
90
  data: t.Object({