@nasebanal/cli 1.1.0 → 1.2.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/README.md CHANGED
@@ -127,19 +127,28 @@ nb assurance report upload --dir locust/logs/20261001_090000
127
127
  job land in the same run, and re-running a job replaces its own result.
128
128
  Commit, branch and CI URL are detected the same way; override with `--run-key`,
129
129
  `--commit`, `--branch`, `--ci-url`.
130
- - **Keep the tool's own report (`--attach <file|folder>`):** a CI runner is thrown away
131
- when the job ends, and the summary above is not the tool's report (Playwright's HTML
132
- report, Specmatic's report, a JUnit file with everything in it). `--attach` sends the
133
- original with the result: a file as it is, a folder as a zip made by the CLI (regular
134
- files only, symbolic links are never followed). Up to 20 MiB per result and 200 MiB per
135
- repository; the CLI checks the size before anything is sent. It is **opt-in twice** - nothing is
136
- attached unless you pass it, and the server refuses it (403 `ATTACHMENTS_DISABLED`) until
137
- the spec has turned on "Attaching original reports" in its settings (off by
138
- default). Make sure the report holds no secrets or personal data.
139
- The server only stores it (next to the result's cases, deleted with the result and by
140
- the repository's retention) and offers it as a **download** to the repository's members in
141
- Assurance; it is never opened, unzipped or shown in the browser. A failed attachment
142
- leaves the result reported and the command exits non-zero with the reason.
130
+ - **Keep the tool's own report (`--attach`, `--attach-if-enabled <file|folder>`):** a CI runner
131
+ is thrown away when the job ends, and the summary above is not the tool's report (Playwright's
132
+ HTML report, Specmatic's report, a JUnit file with everything in it). Both options send the
133
+ original with the result: a file as it is, a folder as a zip made by the CLI (regular files
134
+ only, symbolic links are never followed). Up to 20 MiB per result and 200 MiB per spec; the
135
+ CLI checks the size before it sends anything. It is **opt-in twice**: nothing is attached unless
136
+ you ask, and the repository must have attachments on (Repository Management, or
137
+ `nb specs repositories update <id> --attachments on`; off by default). The CLI reads that
138
+ setting first, so a file the repository does not take never leaves the machine; the server
139
+ checks again. Make sure the report holds no secrets or personal data. The server only stores
140
+ it (deleted with the result and by retention) and offers it as a **download**; it is never
141
+ opened, unzipped or shown in the browser. A result is always reported first.
142
+
143
+ | Repository's attachments | `--attach` (the report is required) | `--attach-if-enabled` |
144
+ |---|---|---|
145
+ | on | attaches it | attaches it |
146
+ | off | does not send it, **fails** | does not send it, says so, succeeds |
147
+ | cannot be told | does not send it, **fails** | does not send it, warns, succeeds |
148
+ | on, but attaching fails (size, limit, network) | **fails** | **fails** |
149
+
150
+ To be sure the report is kept, use `--attach`. Reporting the same result again replaces it,
151
+ **including its attached report**: send it again with the same option, or the old one is gone.
143
152
  - **Pass / fail:** JUnit - any failed or errored test fails the suite. Locust - an
144
153
  unhandled task exception, or a failure ratio above `--max-fail-ratio` (default
145
154
  `$LOCUST_MAX_FAIL_RATIO`, else 0), fails it - the same rule as nb-quickstarts'
@@ -148,7 +157,7 @@ nb assurance report upload --dir locust/logs/20261001_090000
148
157
  failure, its message plus the stack trace, so the Assurance screens can list them. Up to
149
158
  5000 cases per suite - over that, failed and skipped tests are kept first and passed ones
150
159
  fill the rest; a failure text is clipped to 2000 characters, and about 1 MB of failure text
151
- is sent in total (names and outcomes always stay). Locust reports have no cases.
160
+ is sent in total (names and outcomes always stay). A Locust report sends one case per endpoint row of the stats CSV: failed when any of its requests failed (the run's pass / fail is the rule above, so a passed run can list a failed endpoint), timed by its 95th percentile, with the counts, median, max and requests per second as the message.
152
161
  - `--dry-run` prints what would be sent and calls nothing.
153
162
 
154
163
  ## Repositories and the API catalog from a pipeline (`nb specs`)
@@ -698,6 +707,8 @@ To make your own: an executable `nb-<name>` on `PATH` whose second line is `# nb
698
707
  source <(nb completion zsh) source <(nb completion bash)
699
708
  ```
700
709
 
710
+ The `source` line has to come **after** the shell's completion system is started (`compinit`). With oh-my-zsh that means below `source "$ZSH/oh-my-zsh.sh"` (oh-my-zsh runs `compinit` there), so add it at the very end of `~/.zshrc`. Then open a new terminal tab, or run `exec zsh`. `print -r -- ${_comps[nb]}` prints `_nb` once it is registered. Without the line, `nb quick<TAB>` falls back to file names (and may offer a directory such as `nb-quickstarts/`). Needs nb 1.1.0 or later.
711
+
701
712
  `nb quick<TAB>` completes to `nb quickstarts`, `nb assu<TAB>` to `nb assurance`, and below a command its sub-commands and (after a `-`) its options. The script only asks `nb __complete <words...>`, so it follows the command tree, the generated API groups included, with no list to keep in step.
702
713
 
703
714
  A tool answers for the words after its name: `nb quickstarts kong re<TAB>` runs `nb-quickstarts --complete kong re`, which prints one candidate per line (the last word is the one being typed). `nb` asks a tool only when its script contains the literal `--complete`, so it never runs an `nb-*` program that did not say it can answer (the same rule as `nb -h`); a tool that fails or takes more than 2 seconds just gives no candidates.
@@ -28,10 +28,38 @@ function num(value) {
28
28
  return Number.isFinite(n) ? n : null;
29
29
  }
30
30
  const round = (n, digits = 2) => Math.round(n * 10 ** digits) / 10 ** digits;
31
+ const isAggregate = (r) => r.Name === "Aggregated" || r.Name === "Total";
32
+ /**
33
+ * An endpoint's row as a case: failed when any of its requests failed (the run's own verdict is separate: it
34
+ * allows a failure ratio), its time the 95th percentile in whole ms, the other numbers in the message.
35
+ */
36
+ function endpointCase(r) {
37
+ const requests = read(r, COLUMNS.requests) ?? 0;
38
+ const failed = read(r, COLUMNS.failures) ?? 0;
39
+ const median = num(r["50%"]) ?? read(r, COLUMNS.median);
40
+ const p95 = num(r["95%"]);
41
+ const max = read(r, COLUMNS.max);
42
+ const rps = num(r["Requests/s"]);
43
+ const parts = [`${requests} requests`, `${failed} failures`];
44
+ if (median !== null)
45
+ parts.push(`median ${round(median)} ms`);
46
+ if (p95 !== null)
47
+ parts.push(`p95 ${round(p95)} ms`);
48
+ if (max !== null)
49
+ parts.push(`max ${round(max)} ms`);
50
+ if (rps !== null)
51
+ parts.push(`${round(rps)} req/s`);
52
+ return {
53
+ name: `${r.Type ?? r.Method ?? ""} ${r.Name ?? ""}`.trim() || "(unnamed request)",
54
+ status: failed > 0 ? "failed" : "passed",
55
+ duration_ms: p95 === null ? null : Math.round(p95),
56
+ message: parts.join(", "),
57
+ };
58
+ }
31
59
  export function summariseLocust(files, maxFailRatio) {
32
60
  const stats = toRecords(files.stats);
33
61
  // The row of all requests together: "Aggregated" (2.x) or "Total" (1.x).
34
- const total = stats.find((r) => r.Name === "Aggregated" || r.Name === "Total");
62
+ const total = stats.find(isAggregate);
35
63
  if (!total)
36
64
  throw new Error('No "Aggregated" (or "Total") row in the stats CSV - is this a Locust *_stats.csv file?');
37
65
  // Without the counts the numbers below would silently be 0, a green result for a report nobody understood: refuse it.
@@ -81,6 +109,7 @@ export function summariseLocust(files, maxFailRatio) {
81
109
  duration_ms,
82
110
  metrics,
83
111
  failures,
112
+ cases: stats.filter((r) => !isAggregate(r)).map(endpointCase),
84
113
  status: reasons.length === 0 ? "passed" : "failed",
85
114
  reasons,
86
115
  };
@@ -202,6 +202,7 @@ export function parseReport(opts) {
202
202
  ...(l.duration_ms !== null ? { duration_ms: l.duration_ms } : {}),
203
203
  metrics: l.metrics,
204
204
  ...(toFailures(l.failures) ? { failures: toFailures(l.failures) } : {}),
205
+ ...(toCases(l.cases) ? { cases: toCases(l.cases) } : {}),
205
206
  },
206
207
  };
207
208
  }
@@ -294,6 +295,17 @@ function resolveFormat(opts, file) {
294
295
  return "junit";
295
296
  return fail("Cannot tell the report format from the file name; pass --format junit|locust");
296
297
  }
298
+ export function attachmentSetting(repository) {
299
+ if (repository.attachments_enabled === true)
300
+ return "enabled";
301
+ return repository.attachments_enabled === false ? "disabled" : "unknown";
302
+ }
303
+ /** Why a report was not sent, and what to do about it. */
304
+ function notSentReason(setting, repositoryId) {
305
+ return setting === "disabled"
306
+ ? `attachments are off for the repository (turn them on in Repository Management, or: nb specs repositories update ${repositoryId} --attachments on)`
307
+ : "the catalog did not say whether attachments are on for the repository";
308
+ }
297
309
  /** `--attach`: a file as it is, or a folder as a zip. Refuses before anything is sent: missing, empty, or too big for the server. */
298
310
  export function prepareAttachment(path, limit = MAX_ATTACHMENT_BYTES) {
299
311
  if (!existsSync(path))
@@ -366,7 +378,8 @@ export function buildReportUploadCommand() {
366
378
  .option("--contract-file <path>", "the contract document the result was produced against (e.g. node_modules/@nasebanal/api-specs-<api>/spec.yaml): its SHA-256 is sent as --spec-hash would, the same hash the catalog keeps for that document. Exclusive with --spec-hash")
367
379
  .option("--metric <key=value>", "an extra number for the suite, repeatable (e.g. --metric high=0 --metric medium=3; for security: critical, high, medium, low, info)", (v, all = []) => [...all, v])
368
380
  .option("--api-version <v>", "by names: the API version (v1, v2) of the spec, part of the spec's key (a new major API version is a new spec). It selects the spec; a result has no API version of its own. Left out, it is the API version of the one spec the rest of the key matches (several: the error lists them). With --all-specs: only the specs at this API version get the result (a release branch feeds its own API version)")
369
- .option("--attach <path>", "keep the tool's own report with the result: a file as it is, or a folder as a zip (up to 20 MiB). The server only stores it and offers it for download; nothing opens it. Nothing is attached unless you pass this, so check the report holds no secrets")
381
+ .option("--attach <path>", "keep the tool's own report with the result: a file as it is, or a folder as a zip (up to 20 MiB). The server only stores it and offers it for download; nothing opens it. Nothing is attached unless you ask, so check the report holds no secrets. The report is required: if the repository's attachments are off (or that cannot be told), the result is still reported, the file is not sent and the command fails")
382
+ .option("--attach-if-enabled <path>", "as --attach, but only when the repository's attachments are on: otherwise the file is not sent, a line says so and the command succeeds. When they are on, a report that cannot be attached still fails the command. Exclusive with --attach")
370
383
  .option("--spec-id <id>", "the spec to report to, by its id in the catalog (default: $NB_SPEC_ID). Keep the id in the pipeline's variable: a rename of the spec or its repository never moves the results. Exclusive with --repository / --component / --spec")
371
384
  .option("--repository <owner/name>", "by names: the repository the spec is tied to (owner/name for a git host). Needs --spec; --component is optional (none = the repository as a whole). The three are checked against each other: the spec must be tied to exactly that repository row. Nothing is created")
372
385
  .option("--component <name>", "by names: the component part of the repository's key (the owner's own name for a part of it, e.g. account-api, web); optional, none = the repository as a whole")
@@ -441,7 +454,12 @@ export function buildReportUploadCommand() {
441
454
  }
442
455
  const ci = detectCi(process.env);
443
456
  const runKey = opts.runKey ?? ci.runKey ?? fail("Cannot determine the run key; pass --run-key");
444
- const attachment = opts.attach !== undefined ? prepareAttachment(opts.attach) : undefined;
457
+ if (opts.attach !== undefined && opts.attachIfEnabled !== undefined)
458
+ fail("--attach and --attach-if-enabled are exclusive: one requires the report to be kept, the other keeps it only when attachments are on");
459
+ const attachPath = opts.attach ?? opts.attachIfEnabled;
460
+ const required = opts.attach !== undefined;
461
+ // A required report is read before anything is sent; an optional one only once the repository says it takes it.
462
+ let attachment = required ? prepareAttachment(opts.attach) : undefined;
445
463
  // Which spec the result is for is settled before anything is sent: an id, or names the catalog turns into one (or, with
446
464
  // --all-specs, every spec of one repository row: only for results that belong to the source).
447
465
  if (opts.allSpecs) {
@@ -476,8 +494,11 @@ export function buildReportUploadCommand() {
476
494
  });
477
495
  const env = opts.env || resolveEnv();
478
496
  const specsConn = { baseUrl: specsBaseUrl(env), token: opts.token || (await resolveAccessToken()), org };
479
- const attachmentNote = attachment ? { attachment: { name: attachment.name, size_bytes: attachment.bytes.length } } : {};
497
+ const noteOf = (a) => (a ? { attachment: { name: a.name, size_bytes: a.bytes.length } } : {});
480
498
  if (opts.dryRun) {
499
+ if (!required && attachPath !== undefined)
500
+ attachment = prepareAttachment(attachPath);
501
+ const attachmentNote = { ...noteOf(attachment), ...(attachment && !required ? { attachment_only_if_enabled: true } : {}) };
481
502
  // Nothing is written. By names the catalog is only read (to say which spec and repository they mean); by id nothing is called.
482
503
  if (opts.allSpecs) {
483
504
  const hits = await resolveRepositorySpecs(specsConn, ref);
@@ -498,16 +519,34 @@ export function buildReportUploadCommand() {
498
519
  const orgHeaders = org === "personal" ? undefined : { "X-Active-Organization-Id": org };
499
520
  const hits = opts.allSpecs ? await resolveRepositorySpecs(specsConn, ref) : [await resolveSpec(specsConn, ref)];
500
521
  const conn = { baseUrl, token: specsConn.token, ...(orgHeaders ? { headers: orgHeaders } : {}) };
522
+ // Whether to send the file is settled per repository before any result goes out: a file the repository does not
523
+ // take never leaves this machine.
524
+ if (!required && attachPath !== undefined && hits.some((h) => attachmentSetting(h.repository) === "enabled"))
525
+ attachment = prepareAttachment(attachPath);
501
526
  const results = [];
527
+ let notKept;
528
+ let attached = false;
502
529
  for (const hit of hits) {
503
530
  const label = `${hit.spec_name} (${hit.repository.provider} ${hit.repository.name}${hit.repository.component ? ` / ${hit.repository.component}` : ""}), id ${hit.spec_id}`;
504
531
  const result = await uploadReport({ conn, specId: hit.spec_id, payload: buildPayload(hit.repository_id) });
505
- if (attachment)
506
- await uploadAttachment(conn, result, attachment);
532
+ const setting = attachPath === undefined ? undefined : attachmentSetting(hit.repository);
533
+ const sent = setting === "enabled" ? attachment : undefined;
534
+ if (sent) {
535
+ await uploadAttachment(conn, result, sent);
536
+ attached = true;
537
+ }
538
+ else if (setting !== undefined && setting !== "enabled") {
539
+ const why = notSentReason(setting, hit.repository_id);
540
+ if (required)
541
+ notKept = why;
542
+ else
543
+ process.stderr.write(`${setting === "unknown" ? "!" : "-"} report not attached: ${why}\n`);
544
+ }
507
545
  results.push(result);
508
546
  process.stderr.write(`✓ ${kind}/${checkedTool} ${parsed.suite.status}: ${parsed.note} -> spec ${label}, run '${runKey}'${result.replaced ? " (replaced)" : ""}` +
509
- `${attachment ? `, attached ${attachment.name} (${(attachment.bytes.length / 1024).toFixed(0)} KiB)` : ""}\n`);
547
+ `${sent ? `, attached ${sent.name} (${(sent.bytes.length / 1024).toFixed(0)} KiB)` : ""}\n`);
510
548
  }
549
+ const attachmentNote = attached ? noteOf(attachment) : {};
511
550
  if (opts.allSpecs) {
512
551
  printJson({ results, ...attachmentNote });
513
552
  exportGithubOutput("spec_ids", results.map((x) => x.spec_id).join(","));
@@ -517,5 +556,8 @@ export function buildReportUploadCommand() {
517
556
  exportGithubOutput("spec_id", results[0].spec_id);
518
557
  }
519
558
  exportGithubOutput("repository_id", results[0].repository_id);
559
+ // After every result is in: a missing report must not cost the pipeline its test results.
560
+ if (notKept)
561
+ throw new Error(`The result was reported, but the attached report was not kept: ${notKept}. The file was not sent`);
520
562
  });
521
563
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nasebanal/cli",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "gcloud-style command-line interface for NASEBANAL APIs, generated from nb-api-specs OpenAPI contracts.",
5
5
  "license": "MIT",
6
6
  "type": "module",