castle-web-cli 0.4.213 → 0.4.214

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/dist/index.js CHANGED
@@ -17,6 +17,7 @@ import { listVersions, restoreVersion, saveVersion, showVersion } from './versio
17
17
  import { getKitsDir } from './localPaths.js';
18
18
  import * as api from './api.js';
19
19
  import * as config from './config.js';
20
+ import { CloudGitError } from './cloudGit.js';
20
21
  const args = process.argv.slice(2);
21
22
  const command = args[0];
22
23
  const FLAGS_WITH_VALUES = new Set([
@@ -33,6 +34,8 @@ const FLAGS_WITH_VALUES = new Set([
33
34
  '--dir',
34
35
  '--message',
35
36
  '-m',
37
+ '--reason',
38
+ '--remote',
36
39
  ]);
37
40
  // `--foo` is always a flag; a single dash only when it is one we know (`-m`).
38
41
  // Anything else starting with `-` is a positional -- a path can begin with one,
@@ -167,6 +170,9 @@ function usage() {
167
170
  castle-web restore-version <version> [--force] [--dir DIR]
168
171
  castle-web git init [dir] [--dir DIR] [--staging] (connects the deck to its Castle git remote: git push castle <branch>)
169
172
  castle-web git credential get|store|erase (git's credential helper for git.castle.xyz; git init sets it up)
173
+ castle-web git attach <dir> --remote <url> (cloud sandbox only: makes the deck a clone of its Castle repo)
174
+ castle-web git sync [--dir DIR] (cloud sandbox only: commit, merge the remote's main, push)
175
+ castle-web commit [-m MESSAGE] [--reason turn|task|leave|manual|sync] [--resolve] [paths...] [--dir DIR] (cloud sandbox only)
170
176
  castle-web login
171
177
  castle-web whoami
172
178
  castle-web --version
@@ -228,8 +234,15 @@ async function gitCommand() {
228
234
  process.stdout.write(answer.stdout);
229
235
  return;
230
236
  }
231
- if (sub !== 'init')
237
+ if (sub === 'attach' || sub === 'sync') {
238
+ await cloudGitCommand(sub);
239
+ return;
240
+ }
241
+ if (sub !== 'init') {
242
+ if (sub)
243
+ console.error(`Unknown command: git ${sub}`);
232
244
  usage();
245
+ }
233
246
  const initArgs = parseGitInitArgs();
234
247
  await gitRemote.gitInit(initArgs.dir, { environment: initArgs.staging ? 'staging' : 'production' }, {
235
248
  token: config.getToken(),
@@ -243,6 +256,131 @@ async function gitCommand() {
243
256
  warn: (message) => console.error(message),
244
257
  });
245
258
  }
259
+ // Strict parsing for the cloud git commands, which other programs call: an unknown flag or
260
+ // a flag missing its value is an error rather than a path.
261
+ function parseCloudArgs(from, valueFlags, booleanFlags = []) {
262
+ const flags = new Map();
263
+ const positionals = [];
264
+ let onlyPositionals = false;
265
+ for (let i = from; i < args.length; i++) {
266
+ const arg = args[i];
267
+ if (onlyPositionals) {
268
+ positionals.push(arg);
269
+ }
270
+ else if (arg === '--') {
271
+ onlyPositionals = true;
272
+ }
273
+ else if (valueFlags.includes(arg)) {
274
+ const value = args[++i];
275
+ if (value === undefined)
276
+ throw new Error(`${arg} needs a value.`);
277
+ flags.set(arg, value);
278
+ }
279
+ else if (booleanFlags.includes(arg)) {
280
+ flags.set(arg, 'true');
281
+ }
282
+ else if (arg.startsWith('-')) {
283
+ throw new Error(`Unknown option: ${arg}`);
284
+ }
285
+ else {
286
+ positionals.push(arg);
287
+ }
288
+ }
289
+ return { flags, positionals };
290
+ }
291
+ async function cloudGitDeps() {
292
+ const cloudGit = await import('./cloudGit.js');
293
+ return { cloudGit, deps: cloudGit.defaultCloudGitDeps(() => api.whoAmI()) };
294
+ }
295
+ function reportSync(sync, syncError) {
296
+ if (syncError)
297
+ console.error(`Not pushed yet (the next sync retries): ${syncError}`);
298
+ if (!sync)
299
+ return;
300
+ if (sync.merge === 'conflict') {
301
+ console.error('Merging the Castle remote left conflicts; the agent has been asked to resolve them.');
302
+ process.exitCode = 3;
303
+ return;
304
+ }
305
+ if (sync.merge === 'deferred') {
306
+ console.log(`${sync.pushed ? 'Pushed main. ' : ''}The remote has changes that are merged once the deck is idle.`);
307
+ return;
308
+ }
309
+ const merged = { none: '', 'fast-forward': 'Took changes from the remote. ', merged: 'Merged changes from the remote. ', seeded: '' }[sync.merge];
310
+ console.log(`${merged}${sync.pushed ? 'Pushed main.' : 'Up to date with the remote.'}`);
311
+ }
312
+ // `castle-web git attach <dir> --remote <url>` and `castle-web git sync [dir] [--dir DIR]`.
313
+ async function cloudGitCommand(sub) {
314
+ const { cloudGit, deps } = await cloudGitDeps();
315
+ const { flags, positionals } = parseCloudArgs(2, ['--remote', '--dir']);
316
+ if (sub === 'attach') {
317
+ const remote = flags.get('--remote');
318
+ const dir = positionals[0] ?? flags.get('--dir');
319
+ if (!remote || !dir || positionals.length > 1) {
320
+ throw new Error('Usage: castle-web git attach <dir> --remote <url>');
321
+ }
322
+ const outcome = await cloudGit.cloudAttach(dir, remote, deps);
323
+ console.log(`Attached ${path.resolve(dir)} to ${remote} (${outcome.repo} repo, ${outcome.outcome}).`);
324
+ if (outcome.backup)
325
+ console.log(`The cloud copy's differing files are saved in ${outcome.backup}.`);
326
+ reportSync(outcome.sync ?? null);
327
+ return;
328
+ }
329
+ if (positionals.length > 1)
330
+ throw new Error('Usage: castle-web git sync [dir] [--dir DIR]');
331
+ reportSync(await cloudGit.cloudSync(positionals[0] ?? flags.get('--dir') ?? '.', deps));
332
+ }
333
+ // `castle-web commit [-m MESSAGE] [--reason REASON] [--resolve] [paths...] [--dir DIR]`.
334
+ // --resolve concludes a conflicted merge (an agent's commit unless --reason says otherwise).
335
+ async function commitCommand() {
336
+ const { cloudGit, deps } = await cloudGitDeps();
337
+ const { flags, positionals } = parseCloudArgs(1, ['-m', '--message', '--reason', '--dir'], ['--resolve']);
338
+ const resolve = flags.has('--resolve');
339
+ const reason = flags.get('--reason') ?? (resolve ? 'task' : 'manual');
340
+ if (!cloudGit.COMMIT_REASONS.includes(reason)) {
341
+ throw new Error(`--reason must be one of ${cloudGit.COMMIT_REASONS.join(', ')}.`);
342
+ }
343
+ const outcome = await cloudGit.cloudCommit(flags.get('--dir') ?? '.', {
344
+ message: flags.get('-m') ?? flags.get('--message'),
345
+ reason: reason,
346
+ paths: positionals,
347
+ resolve,
348
+ }, deps);
349
+ console.log(outcome.sha ? `Committed ${outcome.sha}` : 'Nothing to commit.');
350
+ reportSync(outcome.sync, outcome.syncError);
351
+ }
352
+ // The version commands with git on (the serve's gate env plus an attached deck): a version
353
+ // is a commit, and the old store stops growing. A version id the old store has still goes
354
+ // there, so older versions stay readable. False when the command is the old store's.
355
+ const VERSION_COMMANDS = new Set(['save-version', 'list-versions', 'show-version', 'restore-version']);
356
+ async function gitVersionCommand(name) {
357
+ const dir = path.resolve(getFlagValue('--dir') ?? '.');
358
+ const target = readPositionals()[0];
359
+ const cloudGit = await import('./cloudGit.js');
360
+ if (!cloudGit.cloudGitMode(dir))
361
+ return false;
362
+ const store = await import('./versionStore.js');
363
+ if (target && name !== 'save-version' && store.versionExists(dir, target))
364
+ return false;
365
+ if (name === 'save-version') {
366
+ await commitCommand();
367
+ }
368
+ else if (name === 'list-versions') {
369
+ cloudGit.printGitLog(dir, target);
370
+ }
371
+ else if (name === 'show-version' && target) {
372
+ cloudGit.printGitShow(dir, target);
373
+ }
374
+ else if (name === 'restore-version' && target) {
375
+ const outcome = await cloudGit.cloudRestore(dir, target, cloudGit.defaultCloudGitDeps(() => api.whoAmI()));
376
+ console.log(outcome.sha ? `Restored ${target} as commit ${outcome.sha}` : `Already at ${target}.`);
377
+ reportSync(outcome.sync, outcome.syncError);
378
+ }
379
+ else {
380
+ return false;
381
+ }
382
+ return true;
383
+ }
246
384
  async function main() {
247
385
  // Before the switch: `--version` is a flag, not a command, and it has to work
248
386
  // when there is no command at all. Which version is installed is the first
@@ -251,6 +389,8 @@ async function main() {
251
389
  console.log(getCliVersion());
252
390
  return;
253
391
  }
392
+ if (VERSION_COMMANDS.has(command) && (await gitVersionCommand(command)))
393
+ return;
254
394
  switch (command) {
255
395
  case 'init': {
256
396
  const dir = findPositionalDir();
@@ -355,6 +495,9 @@ async function main() {
355
495
  // The version commands spend their positionals on their own arguments --
356
496
  // paths to save, a version to list from or restore to -- so the deck dir is
357
497
  // `--dir`, defaulting to the cwd.
498
+ case 'commit':
499
+ await commitCommand();
500
+ break;
358
501
  case 'save-version': {
359
502
  saveVersion(getFlagValue('--dir') ?? '.', {
360
503
  message: getFlagValue('-m') ?? getFlagValue('--message'),
@@ -437,10 +580,14 @@ async function main() {
437
580
  break;
438
581
  }
439
582
  default:
583
+ if (command)
584
+ console.error(`Unknown command: ${command}`);
440
585
  usage();
441
586
  }
442
587
  }
443
588
  main().catch((e) => {
444
589
  console.error(e instanceof Error ? e.message : String(e));
445
- process.exit(1);
590
+ // Only the cloud git commands' own errors carry an exit code (2: not enabled here, 3: a
591
+ // merge waiting on the agent); anything else is a plain failure.
592
+ process.exit(e instanceof CloudGitError ? e.exitCode : 1);
446
593
  });