@git-stunts/git-cas 3.1.0 → 5.0.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/bin/git-cas.js CHANGED
@@ -3,19 +3,24 @@
3
3
  import { readFileSync } from 'node:fs';
4
4
  import { program } from 'commander';
5
5
  import GitPlumbing, { ShellRunnerFactory } from '@git-stunts/plumbing';
6
- import ContentAddressableStore from '../index.js';
6
+ import ContentAddressableStore, { EventEmitterObserver } from '../index.js';
7
7
  import Manifest from '../src/domain/value-objects/Manifest.js';
8
8
  import { createStoreProgress, createRestoreProgress } from './ui/progress.js';
9
9
  import { renderEncryptionCard } from './ui/encryption-card.js';
10
10
  import { renderHistoryTimeline } from './ui/history-timeline.js';
11
11
  import { renderManifestView } from './ui/manifest-view.js';
12
12
  import { renderHeatmap } from './ui/heatmap.js';
13
+ import { runAction } from './actions.js';
14
+ import { filterEntries, formatTable, formatTabSeparated } from './ui/vault-list.js';
15
+
16
+ const getJson = () => program.opts().json;
13
17
 
14
18
  program
15
19
  .name('git-cas')
16
20
  .description('Content Addressable Storage backed by Git')
17
- .version('3.1.0')
18
- .option('-q, --quiet', 'Suppress progress output');
21
+ .version('4.0.1')
22
+ .option('-q, --quiet', 'Suppress progress output')
23
+ .option('--json', 'Output results as JSON');
19
24
 
20
25
  /**
21
26
  * Read a 32-byte raw encryption key from a file.
@@ -25,12 +30,12 @@ function readKeyFile(keyFilePath) {
25
30
  }
26
31
 
27
32
  /**
28
- * Create a CAS instance for the given working directory.
33
+ * Create a CAS instance for the given working directory with an optional observability adapter.
29
34
  */
30
- function createCas(cwd) {
35
+ function createCas(cwd, { observability } = {}) {
31
36
  const runner = ShellRunnerFactory.create();
32
37
  const plumbing = new GitPlumbing({ runner, cwd });
33
- return new ContentAddressableStore({ plumbing });
38
+ return new ContentAddressableStore({ plumbing, observability });
34
39
  }
35
40
 
36
41
  /**
@@ -81,12 +86,10 @@ async function resolveEncryptionKey(cas, opts) {
81
86
  */
82
87
  function validateRestoreFlags(opts) {
83
88
  if (opts.slug && opts.oid) {
84
- process.stderr.write('error: Provide --slug or --oid, not both\n');
85
- process.exit(1);
89
+ throw new Error('Provide --slug or --oid, not both');
86
90
  }
87
91
  if (!opts.slug && !opts.oid) {
88
- process.stderr.write('error: Provide --slug <slug> or --oid <tree-oid>\n');
89
- process.exit(1);
92
+ throw new Error('Provide --slug <slug> or --oid <tree-oid>');
90
93
  }
91
94
  }
92
95
 
@@ -102,39 +105,45 @@ program
102
105
  .option('--force', 'Overwrite existing vault entry')
103
106
  .option('--vault-passphrase <pass>', 'Vault-level passphrase for encryption (prefer GIT_CAS_PASSPHRASE env var)')
104
107
  .option('--cwd <dir>', 'Git working directory', '.')
105
- .action(async (file, opts) => {
106
- try {
107
- const cas = createCas(opts.cwd);
108
- const encryptionKey = await resolveEncryptionKey(cas, opts);
109
- const storeOpts = { filePath: file, slug: opts.slug };
110
- if (encryptionKey) {
111
- storeOpts.encryptionKey = encryptionKey;
112
- }
108
+ .action(runAction(async (file, opts) => {
109
+ const json = program.opts().json;
110
+ const quiet = program.opts().quiet || json;
111
+ const observer = new EventEmitterObserver();
112
+ const cas = createCas(opts.cwd, { observability: observer });
113
+ const encryptionKey = await resolveEncryptionKey(cas, opts);
114
+ if (opts.force && !opts.tree) {
115
+ throw new Error('--force requires --tree');
116
+ }
117
+ const storeOpts = { filePath: file, slug: opts.slug };
118
+ if (encryptionKey) {
119
+ storeOpts.encryptionKey = encryptionKey;
120
+ }
113
121
 
114
- const service = await cas.getService();
115
- const progress = createStoreProgress({
116
- filePath: file, chunkSize: cas.chunkSize, quiet: program.opts().quiet,
117
- });
118
- progress.attach(service);
119
- let manifest;
120
- try {
121
- manifest = await cas.storeFile(storeOpts);
122
- } finally {
123
- progress.detach();
124
- }
122
+ const progress = createStoreProgress({
123
+ filePath: file, chunkSize: cas.chunkSize, quiet,
124
+ });
125
+ progress.attach(observer);
126
+ let manifest;
127
+ try {
128
+ manifest = await cas.storeFile(storeOpts);
129
+ } finally {
130
+ progress.detach();
131
+ }
125
132
 
126
- if (opts.tree) {
127
- const treeOid = await cas.createTree({ manifest });
128
- await cas.addToVault({ slug: opts.slug, treeOid, force: !!opts.force });
129
- process.stdout.write(`${treeOid}\n`);
133
+ if (opts.tree) {
134
+ const treeOid = await cas.createTree({ manifest });
135
+ await cas.addToVault({ slug: opts.slug, treeOid, force: !!opts.force });
136
+ if (json) {
137
+ process.stdout.write(`${JSON.stringify({ treeOid })}\n`);
130
138
  } else {
131
- process.stdout.write(`${JSON.stringify(manifest.toJSON(), null, 2)}\n`);
139
+ process.stdout.write(`${treeOid}\n`);
132
140
  }
133
- } catch (err) {
134
- process.stderr.write(`error: ${err.message}\n`);
135
- process.exit(1);
141
+ } else if (json) {
142
+ process.stdout.write(`${JSON.stringify({ manifest: manifest.toJSON() })}\n`);
143
+ } else {
144
+ process.stdout.write(`${JSON.stringify(manifest.toJSON(), null, 2)}\n`);
136
145
  }
137
- });
146
+ }, getJson));
138
147
 
139
148
  // ---------------------------------------------------------------------------
140
149
  // tree
@@ -144,18 +153,18 @@ program
144
153
  .description('Create a Git tree from a manifest')
145
154
  .requiredOption('--manifest <path>', 'Path to manifest JSON file')
146
155
  .option('--cwd <dir>', 'Git working directory', '.')
147
- .action(async (opts) => {
148
- try {
149
- const cas = createCas(opts.cwd);
150
- const raw = readFileSync(opts.manifest, 'utf8');
151
- const manifest = new Manifest(JSON.parse(raw));
152
- const treeOid = await cas.createTree({ manifest });
156
+ .action(runAction(async (opts) => {
157
+ const cas = createCas(opts.cwd);
158
+ const raw = readFileSync(opts.manifest, 'utf8');
159
+ const manifest = new Manifest(JSON.parse(raw));
160
+ const treeOid = await cas.createTree({ manifest });
161
+ const json = program.opts().json;
162
+ if (json) {
163
+ process.stdout.write(`${JSON.stringify({ treeOid })}\n`);
164
+ } else {
153
165
  process.stdout.write(`${treeOid}\n`);
154
- } catch (err) {
155
- process.stderr.write(`error: ${err.message}\n`);
156
- process.exit(1);
157
166
  }
158
- });
167
+ }, getJson));
159
168
 
160
169
  // ---------------------------------------------------------------------------
161
170
  // inspect
@@ -167,25 +176,23 @@ program
167
176
  .option('--oid <tree-oid>', 'Direct tree OID')
168
177
  .option('--heatmap', 'Show chunk heatmap visualization')
169
178
  .option('--cwd <dir>', 'Git working directory', '.')
170
- .action(async (opts) => {
171
- try {
172
- validateRestoreFlags(opts);
173
- const cas = createCas(opts.cwd);
174
- const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
175
- const manifest = await cas.readManifest({ treeOid });
179
+ .action(runAction(async (opts) => {
180
+ validateRestoreFlags(opts);
181
+ const cas = createCas(opts.cwd);
182
+ const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
183
+ const manifest = await cas.readManifest({ treeOid });
184
+ const json = program.opts().json;
176
185
 
177
- if (opts.heatmap) {
178
- process.stdout.write(renderHeatmap({ manifest }));
179
- } else if (process.stdout.isTTY) {
180
- process.stdout.write(renderManifestView({ manifest }));
181
- } else {
182
- process.stdout.write(`${JSON.stringify(manifest.toJSON(), null, 2)}\n`);
183
- }
184
- } catch (err) {
185
- process.stderr.write(`error: ${err.message}\n`);
186
- process.exit(1);
186
+ if (json) {
187
+ process.stdout.write(`${JSON.stringify(manifest.toJSON())}\n`);
188
+ } else if (opts.heatmap) {
189
+ process.stdout.write(renderHeatmap({ manifest }));
190
+ } else if (process.stdout.isTTY) {
191
+ process.stdout.write(renderManifestView({ manifest }));
192
+ } else {
193
+ process.stdout.write(`${JSON.stringify(manifest.toJSON(), null, 2)}\n`);
187
194
  }
188
- });
195
+ }, getJson));
189
196
 
190
197
  // ---------------------------------------------------------------------------
191
198
  // restore
@@ -199,39 +206,66 @@ program
199
206
  .option('--key-file <path>', 'Path to 32-byte raw encryption key file')
200
207
  .option('--vault-passphrase <pass>', 'Vault-level passphrase for decryption (prefer GIT_CAS_PASSPHRASE env var)')
201
208
  .option('--cwd <dir>', 'Git working directory', '.')
202
- .action(async (opts) => {
203
- try {
204
- validateRestoreFlags(opts);
205
- const cas = createCas(opts.cwd);
206
- const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
207
- const manifest = await cas.readManifest({ treeOid });
209
+ .action(runAction(async (opts) => {
210
+ validateRestoreFlags(opts);
211
+ const quiet = program.opts().quiet || program.opts().json;
212
+ const observer = new EventEmitterObserver();
213
+ const cas = createCas(opts.cwd, { observability: observer });
214
+ const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
215
+ const manifest = await cas.readManifest({ treeOid });
208
216
 
209
- const restoreOpts = { manifest };
210
- const encryptionKey = await resolveEncryptionKey(cas, opts);
211
- if (encryptionKey) {
212
- restoreOpts.encryptionKey = encryptionKey;
213
- }
217
+ const restoreOpts = { manifest };
218
+ const encryptionKey = await resolveEncryptionKey(cas, opts);
219
+ if (encryptionKey) {
220
+ restoreOpts.encryptionKey = encryptionKey;
221
+ }
214
222
 
215
- const service = await cas.getService();
216
- const progress = createRestoreProgress({
217
- totalChunks: manifest.chunks.length, quiet: program.opts().quiet,
218
- });
219
- progress.attach(service);
220
- let bytesWritten;
221
- try {
222
- ({ bytesWritten } = await cas.restoreFile({
223
- ...restoreOpts,
224
- outputPath: opts.out,
225
- }));
226
- } finally {
227
- progress.detach();
228
- }
223
+ const progress = createRestoreProgress({
224
+ totalChunks: manifest.chunks.length, quiet,
225
+ });
226
+ progress.attach(observer);
227
+ let bytesWritten;
228
+ try {
229
+ ({ bytesWritten } = await cas.restoreFile({
230
+ ...restoreOpts,
231
+ outputPath: opts.out,
232
+ }));
233
+ } finally {
234
+ progress.detach();
235
+ }
236
+ const json = program.opts().json;
237
+ if (json) {
238
+ process.stdout.write(`${JSON.stringify({ bytesWritten })}\n`);
239
+ } else {
229
240
  process.stdout.write(`${bytesWritten}\n`);
230
- } catch (err) {
231
- process.stderr.write(`error: ${err.message}\n`);
232
- process.exit(1);
233
241
  }
234
- });
242
+ }, getJson));
243
+
244
+ // ---------------------------------------------------------------------------
245
+ // verify
246
+ // ---------------------------------------------------------------------------
247
+ program
248
+ .command('verify')
249
+ .description('Verify integrity of a stored asset (checks blob hashes; no key needed)')
250
+ .option('--slug <slug>', 'Resolve tree OID from vault slug')
251
+ .option('--oid <tree-oid>', 'Direct tree OID')
252
+ .option('--cwd <dir>', 'Git working directory', '.')
253
+ .action(runAction(async (opts) => {
254
+ validateRestoreFlags(opts);
255
+ const cas = createCas(opts.cwd);
256
+ const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
257
+ const manifest = await cas.readManifest({ treeOid });
258
+ const ok = await cas.verifyIntegrity(manifest);
259
+ const json = program.opts().json;
260
+ if (json) {
261
+ process.stdout.write(`${JSON.stringify({ ok, slug: manifest.slug, chunks: manifest.chunks.length })}\n`);
262
+ } else {
263
+ process.stdout.write(ok ? 'ok\n' : `fail: ${manifest.slug}\n`);
264
+ }
265
+ if (!ok) {
266
+ process.exitCode = 1;
267
+ }
268
+ }, getJson));
235
269
 
236
270
  // ---------------------------------------------------------------------------
237
271
  // vault init
@@ -246,22 +280,22 @@ vault
246
280
  .option('--vault-passphrase <pass>', 'Passphrase for vault-level encryption (prefer GIT_CAS_PASSPHRASE env var)')
247
281
  .option('--algorithm <alg>', 'KDF algorithm (pbkdf2 or scrypt)', 'pbkdf2')
248
282
  .option('--cwd <dir>', 'Git working directory', '.')
249
- .action(async (opts) => {
250
- try {
251
- const cas = createCas(opts.cwd);
252
- const initOpts = {};
253
- const passphrase = resolvePassphrase(opts);
254
- if (passphrase) {
255
- initOpts.passphrase = passphrase;
256
- initOpts.kdfOptions = { algorithm: opts.algorithm };
257
- }
258
- const { commitOid } = await cas.initVault(initOpts);
283
+ .action(runAction(async (opts) => {
284
+ const cas = createCas(opts.cwd);
285
+ const initOpts = {};
286
+ const passphrase = resolvePassphrase(opts);
287
+ if (passphrase) {
288
+ initOpts.passphrase = passphrase;
289
+ initOpts.kdfOptions = { algorithm: opts.algorithm };
290
+ }
291
+ const { commitOid } = await cas.initVault(initOpts);
292
+ const json = program.opts().json;
293
+ if (json) {
294
+ process.stdout.write(`${JSON.stringify({ commitOid })}\n`);
295
+ } else {
259
296
  process.stdout.write(`${commitOid}\n`);
260
- } catch (err) {
261
- process.stderr.write(`error: ${err.message}\n`);
262
- process.exit(1);
263
297
  }
264
- });
298
+ }, getJson));
265
299
 
266
300
  // ---------------------------------------------------------------------------
267
301
  // vault list
@@ -269,19 +303,21 @@ vault
269
303
  vault
270
304
  .command('list')
271
305
  .description('List vault entries')
306
+ .option('--filter <pattern>', 'Filter entries by glob pattern')
272
307
  .option('--cwd <dir>', 'Git working directory', '.')
273
- .action(async (opts) => {
274
- try {
275
- const cas = createCas(opts.cwd);
276
- const entries = await cas.listVault();
277
- for (const { slug, treeOid } of entries) {
278
- process.stdout.write(`${slug}\t${treeOid}\n`);
279
- }
280
- } catch (err) {
281
- process.stderr.write(`error: ${err.message}\n`);
282
- process.exit(1);
308
+ .action(runAction(async (opts) => {
309
+ const cas = createCas(opts.cwd);
310
+ const all = await cas.listVault();
311
+ const entries = filterEntries(all, opts.filter);
312
+ const json = program.opts().json;
313
+ if (json) {
314
+ process.stdout.write(`${JSON.stringify(entries)}\n`);
315
+ } else if (process.stdout.isTTY) {
316
+ process.stdout.write(formatTable(entries));
317
+ } else {
318
+ process.stdout.write(formatTabSeparated(entries));
283
319
  }
284
- });
320
+ }, getJson));
285
321
 
286
322
  // ---------------------------------------------------------------------------
287
323
  // vault remove
@@ -290,16 +326,16 @@ vault
290
326
  .command('remove <slug>')
291
327
  .description('Remove an entry from the vault')
292
328
  .option('--cwd <dir>', 'Git working directory', '.')
293
- .action(async (slug, opts) => {
294
- try {
295
- const cas = createCas(opts.cwd);
296
- const { removedTreeOid } = await cas.removeFromVault({ slug });
329
+ .action(runAction(async (slug, opts) => {
330
+ const cas = createCas(opts.cwd);
331
+ const { commitOid, removedTreeOid } = await cas.removeFromVault({ slug });
332
+ const json = program.opts().json;
333
+ if (json) {
334
+ process.stdout.write(`${JSON.stringify({ commitOid, removedTreeOid })}\n`);
335
+ } else {
297
336
  process.stdout.write(`${removedTreeOid}\n`);
298
- } catch (err) {
299
- process.stderr.write(`error: ${err.message}\n`);
300
- process.exit(1);
301
337
  }
302
- });
338
+ }, getJson));
303
339
 
304
340
  // ---------------------------------------------------------------------------
305
341
  // vault info
@@ -309,21 +345,28 @@ vault
309
345
  .description('Show info for a vault entry')
310
346
  .option('--encryption', 'Show vault encryption details')
311
347
  .option('--cwd <dir>', 'Git working directory', '.')
312
- .action(async (slug, opts) => {
313
- try {
314
- const cas = createCas(opts.cwd);
315
- const treeOid = await cas.resolveVaultEntry({ slug });
348
+ .action(runAction(async (slug, opts) => {
349
+ const cas = createCas(opts.cwd);
350
+ const treeOid = await cas.resolveVaultEntry({ slug });
351
+ const json = program.opts().json;
352
+ if (json) {
353
+ const result = { slug, treeOid };
354
+ if (opts.encryption) {
355
+ const metadata = await cas.getVaultMetadata();
356
+ if (metadata?.encryption) {
357
+ result.encryption = metadata.encryption;
358
+ }
359
+ }
360
+ process.stdout.write(`${JSON.stringify(result)}\n`);
361
+ } else {
316
362
  process.stdout.write(`slug\t${slug}\n`);
317
363
  process.stdout.write(`tree\t${treeOid}\n`);
318
364
  if (opts.encryption) {
319
365
  const metadata = await cas.getVaultMetadata();
320
366
  process.stdout.write(`\n${renderEncryptionCard({ metadata })}\n`);
321
367
  }
322
- } catch (err) {
323
- process.stderr.write(`error: ${err.message}\n`);
324
- process.exit(1);
325
368
  }
326
- });
369
+ }, getJson));
327
370
 
328
371
  // ---------------------------------------------------------------------------
329
372
  // vault history
@@ -334,30 +377,34 @@ vault
334
377
  .option('--cwd <dir>', 'Git working directory', '.')
335
378
  .option('-n, --max-count <n>', 'Limit number of commits')
336
379
  .option('--pretty', 'Render as color-coded timeline')
337
- .action(async (opts) => {
338
- try {
339
- const runner = ShellRunnerFactory.create();
340
- const plumbing = new GitPlumbing({ runner, cwd: opts.cwd || '.' });
341
- const args = ['log', '--oneline', ContentAddressableStore.VAULT_REF];
342
- if (opts.maxCount) {
343
- const n = parseInt(opts.maxCount, 10);
344
- if (Number.isNaN(n) || n <= 0) {
345
- process.stderr.write('error: --max-count must be a positive integer\n');
346
- process.exit(1);
347
- }
348
- args.push(`-${n}`);
380
+ .action(runAction(async (opts) => {
381
+ const runner = ShellRunnerFactory.create();
382
+ const plumbing = new GitPlumbing({ runner, cwd: opts.cwd || '.' });
383
+ const args = ['log', '--oneline', ContentAddressableStore.VAULT_REF];
384
+ if (opts.maxCount) {
385
+ const n = parseInt(opts.maxCount, 10);
386
+ if (Number.isNaN(n) || n <= 0) {
387
+ throw new Error('--max-count must be a positive integer');
349
388
  }
350
- const output = await plumbing.execute({ args });
351
- if (opts.pretty && process.stdout.isTTY) {
352
- process.stdout.write(`${renderHistoryTimeline(output)}\n`);
353
- } else {
354
- process.stdout.write(`${output}\n`);
355
- }
356
- } catch (err) {
357
- process.stderr.write(`error: ${err.message}\n`);
358
- process.exit(1);
389
+ args.push(`-${n}`);
359
390
  }
360
- });
391
+ const output = await plumbing.execute({ args });
392
+ const json = program.opts().json;
393
+ if (json) {
394
+ const history = output
395
+ .split('\n')
396
+ .filter(Boolean)
397
+ .map((line) => {
398
+ const [commitOid, ...messageParts] = line.trim().split(/\s+/);
399
+ return { commitOid, message: messageParts.join(' ') };
400
+ });
401
+ process.stdout.write(`${JSON.stringify(history)}\n`);
402
+ } else if (opts.pretty && process.stdout.isTTY) {
403
+ process.stdout.write(`${renderHistoryTimeline(output)}\n`);
404
+ } else {
405
+ process.stdout.write(`${output}\n`);
406
+ }
407
+ }, getJson));
361
408
 
362
409
  // ---------------------------------------------------------------------------
363
410
  // vault dashboard
@@ -366,15 +413,10 @@ vault
366
413
  .command('dashboard')
367
414
  .description('Interactive vault explorer')
368
415
  .option('--cwd <dir>', 'Git working directory', '.')
369
- .action(async (opts) => {
370
- try {
371
- const cas = createCas(opts.cwd);
372
- const { launchDashboard } = await import('./ui/dashboard.js');
373
- await launchDashboard(cas);
374
- } catch (err) {
375
- process.stderr.write(`error: ${err.message}\n`);
376
- process.exit(1);
377
- }
378
- });
416
+ .action(runAction(async (opts) => {
417
+ const cas = createCas(opts.cwd);
418
+ const { launchDashboard } = await import('./ui/dashboard.js');
419
+ await launchDashboard(cas);
420
+ }, getJson));
379
421
 
380
- await program.parseAsync();
422
+ await program.parseAsync();
@@ -30,14 +30,14 @@ function formatBytes(bytes) {
30
30
  * @param {string} options.filePath - Path to the file being stored.
31
31
  * @param {number} options.chunkSize - Chunk size in bytes.
32
32
  * @param {boolean} [options.quiet] - Suppress all progress output.
33
- * @returns {{ attach(service: EventEmitter): void, detach(): void }}
33
+ * @returns {{ attach(observer: { on(event: string, fn: Function): void, removeListener(event: string, fn: Function): void }): void, detach(): void }}
34
34
  */
35
- export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: providedSize }) {
35
+ export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: providedSize, ctx: providedCtx }) {
36
36
  if (quiet) {
37
37
  return { attach() {}, detach() {} };
38
38
  }
39
39
 
40
- const ctx = getCliContext();
40
+ const ctx = providedCtx || getCliContext();
41
41
  if (ctx.mode === 'pipe') {
42
42
  return { attach() {}, detach() {} };
43
43
  }
@@ -58,14 +58,14 @@ export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: prov
58
58
  * @param {Object} options
59
59
  * @param {number} options.totalChunks - Number of chunks to restore.
60
60
  * @param {boolean} [options.quiet] - Suppress all progress output.
61
- * @returns {{ attach(service: EventEmitter): void, detach(): void }}
61
+ * @returns {{ attach(observer: { on(event: string, fn: Function): void, removeListener(event: string, fn: Function): void }): void, detach(): void }}
62
62
  */
63
- export function createRestoreProgress({ totalChunks, quiet }) {
63
+ export function createRestoreProgress({ totalChunks, quiet, ctx: providedCtx }) {
64
64
  if (quiet || totalChunks === 0) {
65
65
  return { attach() {}, detach() {} };
66
66
  }
67
67
 
68
- const ctx = getCliContext();
68
+ const ctx = providedCtx || getCliContext();
69
69
  if (ctx.mode === 'pipe') {
70
70
  return { attach() {}, detach() {} };
71
71
  }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Vault list filtering and table formatting utilities.
3
+ */
4
+
5
+ /**
6
+ * Convert a simple glob pattern to a RegExp.
7
+ *
8
+ * @param {string} pattern - Glob pattern (supports *, **, ?).
9
+ * @param {string} str - String to test.
10
+ * @returns {boolean}
11
+ */
12
+ export function matchGlob(pattern, str) {
13
+ if (pattern.length > 200) {
14
+ throw new Error(`Glob pattern too long (${pattern.length} chars, max 200)`);
15
+ }
16
+ const escaped = pattern
17
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
18
+ .replace(/\*\*/g, '\0')
19
+ .replace(/\*/g, '[^/]*')
20
+ .replace(/\0/g, '.*')
21
+ .replace(/\?/g, '[^/]');
22
+ return new RegExp(`^${escaped}$`).test(str);
23
+ }
24
+
25
+ /**
26
+ * Filter vault entries by an optional glob pattern.
27
+ *
28
+ * @param {Array<{slug: string, treeOid: string}>} entries
29
+ * @param {string} [pattern]
30
+ * @returns {Array<{slug: string, treeOid: string}>}
31
+ */
32
+ export function filterEntries(entries, pattern) {
33
+ if (!pattern) {
34
+ return entries;
35
+ }
36
+ return entries.filter(e => matchGlob(pattern, e.slug));
37
+ }
38
+
39
+ /**
40
+ * Format entries as an aligned table with header (for TTY output).
41
+ *
42
+ * @param {Array<{slug: string, treeOid: string}>} entries
43
+ * @returns {string}
44
+ */
45
+ export function formatTable(entries) {
46
+ if (entries.length === 0) {
47
+ return '';
48
+ }
49
+ const maxSlug = Math.max('SLUG'.length, ...entries.map(e => e.slug.length));
50
+ const header = `${'SLUG'.padEnd(maxSlug)} TREE OID`;
51
+ const rows = entries.map(e => `${e.slug.padEnd(maxSlug)} ${e.treeOid}`);
52
+ return `${header}\n${rows.join('\n')}\n`;
53
+ }
54
+
55
+ /**
56
+ * Format entries as tab-separated rows (for piped output).
57
+ *
58
+ * @param {Array<{slug: string, treeOid: string}>} entries
59
+ * @returns {string}
60
+ */
61
+ export function formatTabSeparated(entries) {
62
+ return entries.map(e => `${e.slug}\t${e.treeOid}\n`).join('');
63
+ }