@aloth/olcli 0.18.1 → 0.19.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/dist/cli.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * Command-line access to Overleaf projects using session cookies
6
6
  * for authentication. Download, upload, sync, and compile LaTeX projects.
7
7
  */
8
- import { Command } from 'commander';
8
+ import { Command, Option } from 'commander';
9
9
  import chalk from 'chalk';
10
10
  import { colorDisabled, createSpinner as ora, icon } from './term.js';
11
11
  import { CaptchaRequiredError, ProjectOwnerOnlyError, formatError } from './errors.js';
@@ -21,6 +21,9 @@ import { scanLocalFiles } from './scan.js';
21
21
  import { compareTrees, DIFF_EXIT_FAILURE, differencesExitCode, filterRemoteTree, renderFileDiff, statusLetter, } from './diff.js';
22
22
  import { DIFF_OUTPUT_DIR, LatexdiffError, RootDocumentError, buildLatexdiffArgs, diffOutputPath, isTexPath, latexdiffInstallHint, materializeTree, remoteScratchPath, resolveRootDocument, runLatexdiff, } from './latexdiff.js';
23
23
  import { loadIgnore } from './ignore.js';
24
+ import { nodeFloorNotice } from './node-floor.js';
25
+ import { describeSuggestionPlan, parseSuggestionEdits, suggestionPlanJson, suggestionResultJson } from './suggest-cli.js';
26
+ import { EXIT, HELP_TOPICS, UsageError, commanderExitCode, exitCodeFor } from './exit-codes.js';
24
27
  // Read version from package.json
25
28
  const __dirname = dirname(fileURLToPath(import.meta.url));
26
29
  const pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'));
@@ -35,6 +38,28 @@ import { BrowserSignInAborted, browserSignIn, chromiumLauncher, findBrowser, req
35
38
  if (colorDisabled())
36
39
  chalk.level = 0;
37
40
  const program = new Command();
41
+ // Before any subcommand exists: Commander copies the exit callback into each
42
+ // subcommand when it is created. Every parse error (unknown option or
43
+ // command, missing argument or value) exits 2 instead of Commander's 1, so a
44
+ // script can tell a typo from a failed run. `diff` sets its own, see there.
45
+ program.exitOverride((error) => {
46
+ process.exit(commanderExitCode(error));
47
+ });
48
+ // Moves the value of a deprecated option to its replacement before the
49
+ // action reads its options, so actions only know the new names.
50
+ program.hook('preAction', (_program, actionCommand) => {
51
+ for (const entry of deprecatedOptions) {
52
+ if (entry.command !== actionCommand)
53
+ continue;
54
+ const value = actionCommand.getOptionValue(entry.attr);
55
+ if (value === undefined)
56
+ continue;
57
+ if (actionCommand.getOptionValue(entry.target) === undefined)
58
+ actionCommand.setOptionValue(entry.target, value);
59
+ actionCommand.setOptionValue(entry.attr, undefined);
60
+ deprecationNotice(entry.oldFlag, entry.newFlag);
61
+ }
62
+ });
38
63
  program
39
64
  .name('olcli')
40
65
  .description('Overleaf CLI - interact with Overleaf projects from the command line')
@@ -63,16 +88,42 @@ Environment:
63
88
  /**
64
89
  * The one way a command reports a failure: the cause (and the command that
65
90
  * fixes it) on the spinner line, details such as the HTTP status on stderr
66
- * after it. Exits with `code`, 1 unless the command reserves 1 for something
67
- * else (`diff --exit-code`).
91
+ * after it. Exits with the status from the exit-code table for the error
92
+ * (`olcli help exit-codes`), or with `code` when the command reserves its
93
+ * statuses for something else (`diff --exit-code`).
68
94
  */
69
- function failWith(spinner, error, code = 1) {
95
+ function failWith(spinner, error, code) {
70
96
  const verbose = Boolean(program.opts().verbose);
71
97
  const [first, ...rest] = formatError(error, { verbose });
72
98
  spinner.fail(first);
73
99
  for (const line of rest)
74
100
  console.error(chalk.dim(` ${line}`));
75
- process.exit(code);
101
+ process.exit(code ?? exitCodeFor(error));
102
+ }
103
+ const deprecatedOptions = [];
104
+ const noticesShown = new Set();
105
+ /** Print a deprecation notice once per run, only when stderr is a terminal. */
106
+ export function deprecationNotice(oldSpelling, newSpelling, stream = process.stderr) {
107
+ const key = `${oldSpelling}->${newSpelling}`;
108
+ if (noticesShown.has(key) || !stream.isTTY)
109
+ return false;
110
+ noticesShown.add(key);
111
+ stream.write(chalk.dim(`'${oldSpelling}' is deprecated; use '${newSpelling}'. It keeps working until the next major release.\n`));
112
+ return true;
113
+ }
114
+ function deprecatedOption(command, flags, newFlag, target) {
115
+ const option = new Option(flags, `Deprecated alias of ${newFlag}`).hideHelp();
116
+ command.addOption(option);
117
+ deprecatedOptions.push({ command, attr: option.attributeName(), oldFlag: option.long, target, newFlag });
118
+ return command;
119
+ }
120
+ /** A usage error found after parsing: the message on stderr, exit 2. */
121
+ function usageError(...lines) {
122
+ const [first, ...rest] = lines;
123
+ console.error(chalk.red(first));
124
+ for (const line of rest)
125
+ console.error(line);
126
+ process.exit(EXIT.USAGE);
76
127
  }
77
128
  /** Everything on stdin, as text. Used by `auth --cookie -`. */
78
129
  async function readStdin() {
@@ -117,11 +168,11 @@ function defaultProjectDir(projectId, name, cwd = '.') {
117
168
  /**
118
169
  * Helper to get authenticated client
119
170
  *
120
- * `failureCode` is the status when no credential is found at all. It is 1 for
121
- * every command except `diff --exit-code`, which reserves 1 for "something
122
- * differs" and reports a run that could not start as 2.
171
+ * `failureCode` is the status when no credential is found at all. It is 4
172
+ * (not signed in) for every command except `diff --exit-code`, which keeps
173
+ * diff(1)'s statuses and reports a run that could not start as 2.
123
174
  */
124
- async function getClient(cookieOpt, baseUrlOpt, failureCode = 1) {
175
+ async function getClient(cookieOpt, baseUrlOpt, failureCode = EXIT.AUTH) {
125
176
  const baseUrl = baseUrlOpt || program.opts().baseUrl || getBaseUrl();
126
177
  const cookieName = program.opts().cookieName || getSessionCookieName();
127
178
  const cookie = cookieOpt || getSessionCookie();
@@ -186,7 +237,7 @@ async function resolveProject(client, projectArg, dir = '.') {
186
237
  }
187
238
  }
188
239
  // No project found
189
- throw new Error('No project specified. Provide a project name/ID or run from a synced directory.');
240
+ throw new UsageError('No project specified. Provide a project name/ID or run from a synced directory.');
190
241
  }
191
242
  // ─────────────────────────────────────────────────────────────────────────────
192
243
  // AUTH COMMANDS
@@ -233,8 +284,7 @@ reCAPTCHA only).`)
233
284
  .action(async (options) => {
234
285
  if (options.browser) {
235
286
  if (options.cookie || options.email || options.password) {
236
- console.error(chalk.red('Use either --browser or --cookie or --email/--password, not several.'));
237
- process.exit(1);
287
+ usageError('Use either --browser or --cookie or --email/--password, not several.');
238
288
  }
239
289
  await authWithBrowser(options);
240
290
  return;
@@ -262,12 +312,10 @@ reCAPTCHA only).`)
262
312
  return;
263
313
  }
264
314
  if (options.cookie && (options.email || options.password)) {
265
- console.error(chalk.red('Use either --cookie or --email/--password, not both.'));
266
- process.exit(1);
315
+ usageError('Use either --cookie or --email/--password, not both.');
267
316
  }
268
317
  if (!options.cookie && !options.email) {
269
- console.error(chalk.red('--email is required for password login.'));
270
- process.exit(1);
318
+ usageError('--email is required for password login.');
271
319
  }
272
320
  // The cookie is a secret, so it does not have to travel through argv:
273
321
  // no value prompts with hidden input, "-" reads stdin. Resolved before
@@ -287,7 +335,7 @@ reCAPTCHA only).`)
287
335
  }
288
336
  if (error instanceof PromptCancelled) {
289
337
  console.error(chalk.red('Cancelled.'));
290
- process.exit(1);
338
+ process.exit(EXIT.INTERRUPTED);
291
339
  }
292
340
  throw error;
293
341
  }
@@ -328,7 +376,7 @@ reCAPTCHA only).`)
328
376
  }
329
377
  if (error instanceof PromptCancelled) {
330
378
  console.error(chalk.red('Cancelled.'));
331
- process.exit(1);
379
+ process.exit(EXIT.INTERRUPTED);
332
380
  }
333
381
  throw error;
334
382
  }
@@ -399,7 +447,7 @@ reCAPTCHA only).`)
399
447
  return;
400
448
  if (offer.outcome === 'unavailable')
401
449
  console.error(chalk.dim(` Browser sign-in is not available here: ${offer.reason}`));
402
- process.exit(1);
450
+ process.exit(EXIT.AUTH);
403
451
  }
404
452
  failWith(spinner, error);
405
453
  }
@@ -467,7 +515,7 @@ async function authWithBrowser(options) {
467
515
  catch (error) {
468
516
  if (error instanceof BrowserSignInAborted) {
469
517
  spinner.fail('Cancelled. The browser was closed and its temporary profile deleted.');
470
- process.exit(130);
518
+ process.exit(EXIT.INTERRUPTED);
471
519
  }
472
520
  failWith(spinner, error);
473
521
  }
@@ -481,9 +529,10 @@ async function authWithBrowser(options) {
481
529
  * session valid) and `check` (where do credentials come from), which both
482
530
  * stay as hidden aliases.
483
531
  *
484
- * Exit status 1 when no credential is found or the session is rejected, so
485
- * `olcli auth status || olcli auth` works. exitCode rather than exit(): the
486
- * report still has to reach a pipe.
532
+ * Exit status 4 when no credential is found or the session is rejected, so
533
+ * `olcli auth status || olcli auth` works; 1 when Overleaf could not be
534
+ * asked (network, server error). exitCode rather than exit(): the report
535
+ * still has to reach a pipe.
487
536
  */
488
537
  async function authStatus(options) {
489
538
  const baseUrl = program.opts().baseUrl || getBaseUrl();
@@ -554,7 +603,7 @@ async function authStatus(options) {
554
603
  }
555
604
  print();
556
605
  if (!report.signedIn) {
557
- process.exitCode = 1;
606
+ process.exitCode = failure === undefined ? EXIT.AUTH : exitCodeFor(failure);
558
607
  if (options.json)
559
608
  return;
560
609
  console.log();
@@ -577,7 +626,7 @@ function deprecatedAlias(name, description) {
577
626
  .description(description)
578
627
  .option('--json', 'Output as JSON')
579
628
  .action(async (options) => {
580
- console.error(chalk.dim(`'olcli ${name}' is now 'olcli auth status'.`));
629
+ deprecationNotice(`olcli ${name}`, 'olcli auth status');
581
630
  await authStatus(options);
582
631
  });
583
632
  }
@@ -586,8 +635,9 @@ authCmd
586
635
  .description('Show instance, account, credential source and a masked cookie')
587
636
  .option('--json', 'Output as JSON')
588
637
  .addHelpText('after', `
589
- Exits 1 when no credential is found or Overleaf rejects the session, so
590
- 'olcli auth status || olcli auth' signs in only when needed. The cookie is
638
+ Exits 4 when no credential is found or Overleaf rejects the session, and 1
639
+ when Overleaf cannot be reached, so 'olcli auth status || olcli auth' signs
640
+ in only when needed (see: olcli help exit-codes). The cookie is
591
641
  shown masked: its last four characters and its length.
592
642
 
593
643
  Credential sources, first match wins:
@@ -946,14 +996,14 @@ commentsCmd
946
996
  // ─────────────────────────────────────────────────────────────────────────────
947
997
  const changesCmd = program
948
998
  .command('changes')
949
- .description('Accept or reject tracked changes (needs a premium project owner)')
999
+ .description('Accept, reject or suggest tracked changes (premium projects)')
950
1000
  .addHelpText('after', `
951
1001
  Tracked changes need a project whose owner has an Overleaf premium plan;
952
1002
  collaborators on any plan can then accept and reject them.`);
953
1003
  changesCmd
954
1004
  .command('accept <ids...>')
955
1005
  .description('Accept tracked changes by id (ids from: olcli comments list --changes)')
956
- .option('--project <project>', 'Project name or ID (default: the project in .olcli.json in the current directory)')
1006
+ .option('-p, --project <project>', 'Project name or ID (default: the project in .olcli.json in the current directory)')
957
1007
  .option('--json', 'Output as JSON')
958
1008
  .option('--cookie <session>', 'Session cookie override')
959
1009
  .action(async (ids, options) => {
@@ -981,8 +1031,8 @@ changesCmd
981
1031
  changesCmd
982
1032
  .command('reject <ids...>')
983
1033
  .description('Reject tracked changes by id: removes suggested insertions, restores suggested deletions. Shows a preview and writes nothing unless --yes is given')
984
- .option('--project <project>', 'Project name or ID (default: the project in .olcli.json in the current directory)')
985
- .option('--yes', 'Apply the rejection after showing the preview')
1034
+ .option('-p, --project <project>', 'Project name or ID (default: the project in .olcli.json in the current directory)')
1035
+ .option('-y, --yes', 'Apply the rejection after showing the preview')
986
1036
  .option('--json', 'Output as JSON')
987
1037
  .option('--cookie <session>', 'Session cookie override')
988
1038
  .action(async (ids, options) => {
@@ -1017,6 +1067,109 @@ changesCmd
1017
1067
  failWith(spinner, error);
1018
1068
  }
1019
1069
  });
1070
+ changesCmd
1071
+ .command('suggest <file> [project]')
1072
+ .description('Experimental: turn edits already on Overleaf into tracked changes. Shows a preview and writes nothing unless --yes is given')
1073
+ .requiredOption('--edits <path>', 'JSON file with the edits, or "-" for stdin')
1074
+ .option('-p, --project <project>', 'Project name or ID (instead of the positional argument)')
1075
+ .option('-y, --yes', 'Write the suggestions after showing the preview')
1076
+ .option('--json', 'Output as JSON')
1077
+ .option('--cookie <session>', 'Session cookie override')
1078
+ .addHelpText('after', `
1079
+ Experimental, and outside the stability promise of docs/STABILITY.md: the
1080
+ command, its options and its output may change in a minor release.
1081
+
1082
+ Edits that reached Overleaf as plain text (through git, olcli push or a sync)
1083
+ become suggestions that collaborators can accept or reject, as if they had
1084
+ been typed in Reviewing mode. The text ends up the same. Each edit is the old
1085
+ and the new text with some unchanged text around it; hint is the approximate
1086
+ character offset and picks the nearest match:
1087
+
1088
+ [{ "before": "The ", "deleted": "quick", "inserted": "slow", "after": " fox", "hint": 120 }]
1089
+
1090
+ The same shape as SuggestionEdit[] in the library and the edits of the MCP
1091
+ tool suggest_changes. Without --yes, olcli prints each edit's location and the
1092
+ suggested deletion and insertion, or why it is left alone, and writes nothing.
1093
+ With --yes it writes, and refuses (exit 5) when the document changed since the
1094
+ preview.
1095
+
1096
+ Limits:
1097
+ - sharejs-text-ot documents only; history-ot documents are refused
1098
+ - each edit is undone without tracking and redone with tracking, so
1099
+ collaborators with the document open see the old text for about 0.2 s
1100
+ - needs edit access to the project; review-only access is refused before
1101
+ anything is written
1102
+ - track changes needs a project whose owner has an Overleaf premium plan
1103
+
1104
+ Examples:
1105
+ olcli changes suggest main.tex --edits edits.json
1106
+ olcli changes suggest main.tex "My Paper" --edits edits.json --yes
1107
+ cat edits.json | olcli changes suggest main.tex --edits - --yes --json`)
1108
+ .action(async (file, project, options) => {
1109
+ if (project && options.project && project !== options.project) {
1110
+ usageError('Give the project either as an argument or with --project, not both.');
1111
+ }
1112
+ let edits;
1113
+ try {
1114
+ const text = options.edits === '-' ? await readStdin() : readFileSync(options.edits, 'utf-8');
1115
+ edits = parseSuggestionEdits(text, options.edits === '-' ? 'stdin' : options.edits);
1116
+ }
1117
+ catch (error) {
1118
+ if (error instanceof UsageError)
1119
+ usageError(error.message);
1120
+ usageError(`Cannot read the edits from ${options.edits}: ${error instanceof Error ? error.message : String(error)}`);
1121
+ }
1122
+ const spinner = ora('Planning suggestions...').start();
1123
+ try {
1124
+ const client = await getClient(options.cookie);
1125
+ const proj = await resolveProject(client, project ?? options.project);
1126
+ const plan = await client.planSuggestions(proj.id, file, edits);
1127
+ spinner.stop();
1128
+ const toSuggest = plan.edits.filter((item) => item.outcome === 'suggest').length;
1129
+ if (!options.yes || toSuggest === 0) {
1130
+ if (options.json) {
1131
+ console.log(JSON.stringify(suggestionPlanJson(plan), null, 2));
1132
+ }
1133
+ else {
1134
+ for (const line of describeSuggestionPlan(plan))
1135
+ console.log(line);
1136
+ console.log();
1137
+ if (toSuggest === 0)
1138
+ console.log(chalk.yellow('None of the edits can become a suggestion. Nothing was written.'));
1139
+ else
1140
+ console.log(chalk.yellow(`Preview only: ${toSuggest} edit(s) would become suggestions. Run again with --yes to write.`));
1141
+ }
1142
+ return;
1143
+ }
1144
+ if (!options.json) {
1145
+ for (const line of describeSuggestionPlan(plan))
1146
+ console.log(line);
1147
+ console.log();
1148
+ }
1149
+ const applying = ora(`Turning ${toSuggest} edit(s) into suggestions...`).start();
1150
+ // expectedVersion: refuses (RejectConflictError, exit 5) when the
1151
+ // document moved since the preview printed above.
1152
+ const results = await client.suggestChanges(proj.id, file, edits, { expectedVersion: plan.version });
1153
+ applying.stop();
1154
+ const done = results.filter((r) => r === 'done').length;
1155
+ const untracked = results.filter((r) => r === 'not-tracked').length;
1156
+ if (options.json) {
1157
+ console.log(JSON.stringify(suggestionResultJson(plan.path, edits, results), null, 2));
1158
+ }
1159
+ else {
1160
+ results.forEach((result, index) => console.log(`${index + 1}. ${result}`));
1161
+ console.log(chalk.green(`${done} edit(s) are now suggestions in ${plan.path}.`));
1162
+ if (untracked > 0) {
1163
+ console.log(chalk.yellow(`${untracked} edit(s) were sent, but no tracked change showed up when the document was read again. The text is as before.`));
1164
+ }
1165
+ }
1166
+ if (untracked > 0)
1167
+ process.exitCode = EXIT.FAILURE;
1168
+ }
1169
+ catch (error) {
1170
+ failWith(spinner, error);
1171
+ }
1172
+ });
1020
1173
  program
1021
1174
  .command('download <file> [project]')
1022
1175
  .description('Download a single file from project')
@@ -1085,7 +1238,7 @@ program
1085
1238
  .option('-o, --output <path>', 'Output path')
1086
1239
  .option('-r, --resource <path>', 'Compile this .tex file as root document (e.g. paper.tex, folder/test.tex)')
1087
1240
  .option('--list', 'List available output files')
1088
- .option('--project <name>', 'Project name or ID')
1241
+ .option('-p, --project <project>', 'Project name or ID')
1089
1242
  .option('--cookie <session>', 'Session cookie override')
1090
1243
  .action(async (type, options) => {
1091
1244
  const spinner = ora('Compiling project...').start();
@@ -1256,9 +1409,7 @@ projectCmd
1256
1409
  .action(async (name, options) => {
1257
1410
  const template = options.template;
1258
1411
  if (template !== 'blank' && template !== 'example') {
1259
- console.error(chalk.red(`Unsupported project template: ${template}`));
1260
- console.error('Supported templates: blank, example');
1261
- process.exit(1);
1412
+ usageError(`Unsupported project template: ${template}`, 'Supported templates: blank, example');
1262
1413
  }
1263
1414
  const spinner = ora('Creating project...').start();
1264
1415
  try {
@@ -1314,22 +1465,22 @@ projectCmd
1314
1465
  failWith(spinner, error);
1315
1466
  }
1316
1467
  });
1317
- projectCmd
1468
+ const renameBulkCmd = projectCmd
1318
1469
  .command('rename-bulk')
1319
- .description('Rename many projects at once by pattern (dry-run unless --apply)')
1470
+ .description('Rename many projects at once by pattern (dry run unless --yes)')
1320
1471
  .option('--match <regex>', 'Only consider projects whose name matches this regex')
1321
1472
  .option('--search <text>', 'Literal substring to replace in the name')
1322
1473
  .option('--replace <text>', 'Replacement for --search or --match (supports $1, $2 backrefs)')
1323
1474
  .option('--prefix <text>', 'Prepend this to the name')
1324
1475
  .option('--suffix <text>', 'Append this to the name')
1325
- .option('--apply', 'Actually rename. Without this flag nothing is changed.')
1476
+ .option('-y, --yes', 'Actually rename. Without this flag nothing is changed.')
1326
1477
  .option('--max <n>', 'Refuse to apply if more than n projects would change', parseInt)
1327
1478
  .option('--cookie <session>', 'Session cookie override')
1328
1479
  .action(async (options) => {
1329
1480
  // Inverted default on purpose: for a single project a dry-run flag is a
1330
1481
  // convenience, but a bulk rename that fires on a typo is unrecoverable
1331
1482
  // (Overleaf keeps no project-name history). So doing nothing is the
1332
- // default and --apply is the deliberate act.
1483
+ // default and --yes is the deliberate act.
1333
1484
  const spinner = ora('Fetching projects...').start();
1334
1485
  try {
1335
1486
  const client = await getClient(options.cookie);
@@ -1347,7 +1498,7 @@ projectCmd
1347
1498
  }
1348
1499
  catch (err) {
1349
1500
  spinner.fail(err.message);
1350
- process.exit(1);
1501
+ process.exit(EXIT.USAGE);
1351
1502
  }
1352
1503
  const { planned, skipped, collisions } = plan;
1353
1504
  spinner.stop();
@@ -1372,16 +1523,16 @@ projectCmd
1372
1523
  console.log(chalk.red(` ${c}`));
1373
1524
  console.log(chalk.red('Refusing to apply. Overleaf allows duplicate names, so this would'));
1374
1525
  console.log(chalk.red('succeed silently and leave projects you cannot tell apart.'));
1375
- process.exit(1);
1526
+ process.exit(EXIT.CONFLICT);
1376
1527
  }
1377
1528
  if (options.max !== undefined && planned.length > options.max) {
1378
1529
  console.log();
1379
1530
  console.log(chalk.red(`Refusing to apply: ${planned.length} changes exceed --max ${options.max}.`));
1380
1531
  process.exit(1);
1381
1532
  }
1382
- if (!options.apply) {
1533
+ if (!options.yes) {
1383
1534
  console.log();
1384
- console.log(chalk.yellow('Dry run. Nothing was changed. Re-run with --apply to rename.'));
1535
+ console.log(chalk.yellow('Dry run. Nothing was changed. Re-run with --yes to rename.'));
1385
1536
  return;
1386
1537
  }
1387
1538
  const applySpinner = ora(`Renaming ${planned.length} project(s)...`).start();
@@ -1455,10 +1606,7 @@ program
1455
1606
  projectName = meta.projectName;
1456
1607
  }
1457
1608
  else if (!project) {
1458
- console.error(chalk.red('No project specified.'));
1459
- console.error('Usage: olcli pull <project> [dir]');
1460
- console.error('Or run from a directory with .olcli.json');
1461
- process.exit(1);
1609
+ usageError('No project specified.', 'Usage: olcli pull <project> [dir]', 'Or run from a directory with .olcli.json');
1462
1610
  }
1463
1611
  const spinner = ora('Fetching project...').start();
1464
1612
  try {
@@ -1574,7 +1722,7 @@ program
1574
1722
  program
1575
1723
  .command('push [dir]')
1576
1724
  .description('Upload local changes to Overleaf project')
1577
- .option('--project <name>', 'Project name or ID (overrides .olcli.json)')
1725
+ .option('-p, --project <project>', 'Project name or ID (overrides .olcli.json)')
1578
1726
  .option('--all', 'Upload all files (not just changed)')
1579
1727
  .option('--delete', 'Propagate local deletions to the remote (opt-in; see docs)')
1580
1728
  .option('--dry-run', 'Show what would be uploaded without uploading')
@@ -1613,9 +1761,7 @@ program
1613
1761
  projectName = options.project;
1614
1762
  }
1615
1763
  if (!projectId && !projectName) {
1616
- console.error(chalk.red('No project specified.'));
1617
- console.error('Either run from a directory with .olcli.json or use --project');
1618
- process.exit(1);
1764
+ usageError('No project specified.', 'Either run from a directory with .olcli.json or use --project');
1619
1765
  }
1620
1766
  const spinner = ora('Connecting...').start();
1621
1767
  try {
@@ -1805,7 +1951,7 @@ program
1805
1951
  program
1806
1952
  .command('sync [dir]')
1807
1953
  .description('Pull then push (bidirectional sync, propagates local deletions)')
1808
- .option('--project <name>', 'Project name or ID')
1954
+ .option('-p, --project <project>', 'Project name or ID (overrides .olcli.json)')
1809
1955
  .option('--no-delete', 'Do not propagate local deletions to the remote (safer)')
1810
1956
  .option('--dry-run', 'Show what would change without applying')
1811
1957
  .option('--no-default-ignore', 'Disable built-in LaTeX artifact ignore list (only .olignore applies)')
@@ -1832,9 +1978,7 @@ skipped, or pushed. Combine it with --dry-run to preview deletions:
1832
1978
  projectId = undefined;
1833
1979
  }
1834
1980
  if (!projectId && !projectName) {
1835
- console.error(chalk.red('No project specified.'));
1836
- console.error('Either run from a directory with .olcli.json or use --project');
1837
- process.exit(1);
1981
+ usageError('No project specified.', 'Either run from a directory with .olcli.json or use --project');
1838
1982
  }
1839
1983
  const spinner = ora('Connecting...').start();
1840
1984
  try {
@@ -2058,7 +2202,7 @@ skipped, or pushed. Combine it with --dry-run to preview deletions:
2058
2202
  failWith(spinner, error);
2059
2203
  }
2060
2204
  });
2061
- program
2205
+ const diffCmd = program
2062
2206
  .command('diff [project] [dir]')
2063
2207
  .description('Show content differences between local files and the remote project')
2064
2208
  .option('--name-only', 'List changed paths instead of printing patches')
@@ -2067,21 +2211,21 @@ program
2067
2211
  .option('--exit-code', 'Exit 1 if anything differs, 0 if nothing does, 2 on failure (for CI)')
2068
2212
  .option('--latexdiff', 'Mark the revision up inside the document with latexdiff (requires latexdiff on PATH)')
2069
2213
  .option('--pdf', 'Compile the marked-up document on Overleaf and download the PDF (implies --latexdiff)')
2070
- .option('--main <path>', 'Root .tex document to mark up (default: the only file declaring \\documentclass)')
2214
+ .option('-r, --resource <path>', 'Root .tex document to mark up (default: the only file declaring \\documentclass)')
2071
2215
  .option('-o, --output <path>', `Where to write the marked-up .tex (default: ${DIFF_OUTPUT_DIR}/<root>-diff.tex)`)
2072
2216
  .option('--no-flatten', 'Leave \\input/\\include in place instead of inlining them')
2073
2217
  .option('--latexdiff-opt <opt>', 'Pass an option straight through to latexdiff (repeatable)', (value, previous = []) => [...previous, value])
2074
2218
  .option('--no-default-ignore', 'Disable built-in LaTeX artifact ignore list (only .olignore applies)')
2075
2219
  .option('--no-ignore', 'Disable all ignore filtering')
2076
2220
  .option('--cookie <session>', 'Session cookie override')
2077
- // Commander reports an unknown option or a missing option value with status
2078
- // 1, which under --exit-code means "something differs". Only this command's
2079
- // own usage errors are remapped; help and version still exit 0.
2221
+ // A usage error exits 2 on every command (olcli help exit-codes), which is
2222
+ // also what --exit-code reserves for a failed run, so the two agree. Kept
2223
+ // explicit here because under --exit-code a 1 would read as "differs".
2080
2224
  .exitOverride((error) => {
2081
2225
  const args = process.argv.slice(2);
2082
2226
  const end = args.indexOf('--');
2083
2227
  const exitCodeRequested = (end === -1 ? args : args.slice(0, end)).includes('--exit-code');
2084
- process.exit(error.exitCode !== 0 && exitCodeRequested ? DIFF_EXIT_FAILURE : error.exitCode);
2228
+ process.exit(error.exitCode !== 0 && exitCodeRequested ? DIFF_EXIT_FAILURE : commanderExitCode(error));
2085
2229
  })
2086
2230
  .addHelpText('after', `
2087
2231
  The remote side is fetched fresh on every run, so the diff describes the
@@ -2122,26 +2266,23 @@ where the markup only covers the root document.`)
2122
2266
  options.unified !== undefined ? '-U/--unified' : null,
2123
2267
  ].filter(Boolean);
2124
2268
  if (latexdiffMode && conflicting.length > 0) {
2125
- console.error(chalk.red(`--latexdiff cannot be combined with ${conflicting.join(', ')}`));
2126
- console.error('It marks up one root document; those options select and shape unified patch output.');
2127
- process.exit(failureCode);
2269
+ usageError(`--latexdiff cannot be combined with ${conflicting.join(', ')}`, 'It marks up one root document; those options select and shape unified patch output.');
2128
2270
  }
2129
2271
  if (!latexdiffMode) {
2130
2272
  // Accepting these silently would produce a normal patch and no markup,
2131
2273
  // with nothing in the output saying the flag was dropped.
2132
2274
  const latexdiffOnly = [
2133
- options.main ? '--main' : null,
2275
+ options.resource ? '--resource' : null,
2134
2276
  options.output ? '--output' : null,
2135
2277
  options.latexdiffOpt?.length ? '--latexdiff-opt' : null,
2136
2278
  ].filter(Boolean);
2137
2279
  if (latexdiffOnly.length > 0) {
2138
- console.error(chalk.red(`${latexdiffOnly.join(', ')} only applies with --latexdiff`));
2139
- process.exit(failureCode);
2280
+ usageError(`${latexdiffOnly.join(', ')} only applies with --latexdiff`);
2140
2281
  }
2141
2282
  }
2142
2283
  const spinner = ora('Connecting...').start();
2143
2284
  try {
2144
- const client = await getClient(options.cookie, undefined, failureCode);
2285
+ const client = await getClient(options.cookie, undefined, options.exitCode ? DIFF_EXIT_FAILURE : EXIT.AUTH);
2145
2286
  let resolved;
2146
2287
  try {
2147
2288
  resolved = await resolveProject(client, project, targetDir);
@@ -2149,7 +2290,7 @@ where the markup only covers the root document.`)
2149
2290
  catch (error) {
2150
2291
  spinner.fail(error.message);
2151
2292
  console.error('Either run from a directory with .olcli.json or pass a project name/ID');
2152
- process.exit(failureCode);
2293
+ process.exit(options.exitCode ? DIFF_EXIT_FAILURE : exitCodeFor(error));
2153
2294
  }
2154
2295
  const { id: projectId, name: projectName } = resolved;
2155
2296
  // The whole project arrives as one zip in a single request - the same
@@ -2255,7 +2396,7 @@ where the markup only covers the root document.`)
2255
2396
  process.exitCode = differencesExitCode(entries);
2256
2397
  }
2257
2398
  catch (error) {
2258
- failWith(spinner, error, failureCode);
2399
+ failWith(spinner, error, options.exitCode ? DIFF_EXIT_FAILURE : undefined);
2259
2400
  }
2260
2401
  });
2261
2402
  /**
@@ -2273,7 +2414,7 @@ async function runLatexdiffMode(params) {
2273
2414
  const { client, projectId, projectName, targetDir, localFiles, remoteFiles, entries, fetchedAt, failureCode, options, spinner, } = params;
2274
2415
  let root = '';
2275
2416
  try {
2276
- root = resolveRootDocument(localFiles, options.main ? normalizeRemotePath(options.main) : undefined);
2417
+ root = resolveRootDocument(localFiles, options.resource ? normalizeRemotePath(options.resource) : undefined);
2277
2418
  }
2278
2419
  catch (error) {
2279
2420
  if (!(error instanceof RootDocumentError))
@@ -2291,7 +2432,7 @@ async function runLatexdiffMode(params) {
2291
2432
  if (!remoteFiles.has(root)) {
2292
2433
  spinner.stop();
2293
2434
  console.error(chalk.red(`${root} is not in "${projectName}" yet, so there is no earlier version to mark up.`));
2294
- console.error(chalk.dim(' Push it first, or use --main to name a document that exists on both sides.'));
2435
+ console.error(chalk.dim(' Push it first, or use --resource to name a document that exists on both sides.'));
2295
2436
  process.exit(failureCode);
2296
2437
  }
2297
2438
  if (!entries.some((e) => isTexPath(e.path))) {
@@ -2512,8 +2653,7 @@ configCmd
2512
2653
  .action((ms) => {
2513
2654
  const timeout = parseInt(ms, 10);
2514
2655
  if (isNaN(timeout)) {
2515
- console.error(chalk.red('Invalid timeout value. Must be a number.'));
2516
- process.exit(1);
2656
+ usageError('Invalid timeout value. Must be a number.');
2517
2657
  }
2518
2658
  setTimeout(timeout);
2519
2659
  console.log(chalk.green(`Default timeout set to: ${timeout}ms`));
@@ -2561,6 +2701,9 @@ program
2561
2701
  }
2562
2702
  });
2563
2703
  deprecatedAlias('check', 'Alias of: auth status');
2704
+ // Old spellings, hidden from the help (see docs/CLI-CONVENTIONS.md).
2705
+ deprecatedOption(diffCmd, '--main <path>', '--resource', 'resource');
2706
+ deprecatedOption(renameBulkCmd, '--apply', '--yes', 'yes');
2564
2707
  // ─────────────────────────────────────────────────────────────────────────────
2565
2708
  // ROOT HELP GROUPS
2566
2709
  // ─────────────────────────────────────────────────────────────────────────────
@@ -2585,7 +2728,33 @@ const HELP_GROUPS = [
2585
2728
  });
2586
2729
  // Commander lists groups in the order their first command appears.
2587
2730
  program.commands.sort((a, b) => (order.get(a.name()) ?? 9999) - (order.get(b.name()) ?? 9999));
2588
- program.commandsGroup('Help:').helpCommand(true);
2731
+ program.commandsGroup('Help:').helpCommand('help [command]', 'Help for a command, or a topic: exit-codes, environment');
2732
+ }
2733
+ /**
2734
+ * `olcli help exit-codes` and `olcli help environment`: topics served by the
2735
+ * built-in help command rather than new commands, so the root help does not
2736
+ * grow. Returns the topic name when argv asks for one.
2737
+ */
2738
+ export function requestedHelpTopic(args) {
2739
+ const valueOptions = new Set(['--base-url', '--cookie-name', '--timeout']);
2740
+ let i = 0;
2741
+ while (i < args.length && args[i].startsWith('-')) {
2742
+ i += valueOptions.has(args[i]) ? 2 : 1;
2743
+ }
2744
+ if (args[i] !== 'help')
2745
+ return undefined;
2746
+ const topic = args[i + 1];
2747
+ return topic !== undefined && Object.hasOwn(HELP_TOPICS, topic) ? topic : undefined;
2748
+ }
2749
+ // Once per run, terminal only; see src/node-floor.ts.
2750
+ const floorNotice = nodeFloorNotice();
2751
+ if (floorNotice)
2752
+ process.stderr.write(chalk.yellow(`${floorNotice}\n`));
2753
+ const helpTopic = requestedHelpTopic(process.argv.slice(2));
2754
+ if (helpTopic) {
2755
+ process.stdout.write(HELP_TOPICS[helpTopic]);
2756
+ }
2757
+ else {
2758
+ program.parse(process.argv);
2589
2759
  }
2590
- program.parse(process.argv);
2591
2760
  //# sourceMappingURL=cli.js.map