@tuanhv/op-cli 0.3.1 → 0.5.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.
@@ -3,11 +3,13 @@ import { OpCliError, writeRefusal } from "../core/errors.js";
3
3
  import { filtersQuery } from "../core/filters.js";
4
4
  import { emitRows, PAGED_JSON_HELP, } from "../core/define.js";
5
5
  import { flattenHalRecord, toFormattable } from "../core/hal.js";
6
+ import { readDate } from "../core/scalars.js";
6
7
  import { apiDelete, apiGet, apiPatchRaw, apiPost, apiPostRaw, authenticate, } from "../core/http.js";
7
8
  import { DEFAULT_PAGE_SIZE, allPageSize, halElements, parsePageSize, withPageSize, } from "../core/paginate.js";
8
9
  import { isIdForm, rankByCloseness, resolveName, } from "../context/resolve.js";
9
10
  import { parseProjectOverride, } from "../context/profile.js";
10
- import { PROJECTS_COLLECTION, resolveProjectRef } from "../context/projectref.js";
11
+ import { sprintStatusKey } from "../context/metadata.js";
12
+ import { PROJECTS_COLLECTION, resolveProjectRef, withMovedRetry, WORKSPACES_COLLECTION, } from "../context/projectref.js";
11
13
  export const LIST_COLUMNS = [
12
14
  { title: "ID", field: "id" },
13
15
  { title: "IDENTIFIER", field: "identifier" },
@@ -24,6 +26,17 @@ export const CATEGORY_COLUMNS = [
24
26
  { title: "ID", field: "id" },
25
27
  { title: "NAME", field: "name" },
26
28
  ];
29
+ export const SPRINT_COLUMNS = [
30
+ { title: "ID", field: "id" },
31
+ { title: "NAME", field: "name" },
32
+ { title: "START", field: "startDate" },
33
+ { title: "FINISH", field: "finishDate" },
34
+ { title: "STATUS", field: "status" },
35
+ ];
36
+ export const BUCKET_COLUMNS = [
37
+ { title: "ID", field: "id" },
38
+ { title: "NAME", field: "name" },
39
+ ];
27
40
  export const TYPE_COLUMNS = [
28
41
  { title: "ID", field: "id" },
29
42
  { title: "NAME", field: "name" },
@@ -43,6 +56,19 @@ async function connect(runtime, options) {
43
56
  function collectValue(value, previous) {
44
57
  return [...previous, value];
45
58
  }
59
+ const VERSIONS_COLLECTION = "/api/v3/versions";
60
+ const VERSION_STATUSES = ["open", "locked", "closed"];
61
+ const VERSION_SHARINGS = ["none", "descendants", "hierarchy", "tree", "system"];
62
+ /** One closed-vocabulary flag: absent stays undefined; empty or unknown is misuse. */
63
+ function readChoice(raw, flag, choices) {
64
+ if (raw === undefined) {
65
+ return undefined;
66
+ }
67
+ if (!choices.includes(raw)) {
68
+ throw new OpCliError("USAGE_ERROR", `${flag} "${raw}" is not one of ${choices.join(", ")}.`, `pass ${flag} with one of: ${choices.join(", ")}.`);
69
+ }
70
+ return raw;
71
+ }
46
72
  const PRINCIPALS_COLLECTION = "/api/v3/principals";
47
73
  const ROLES_COLLECTION = "/api/v3/roles";
48
74
  const MEMBERSHIPS_COLLECTION = "/api/v3/memberships";
@@ -116,13 +142,16 @@ async function resolveRoleIds(profile, raws) {
116
142
  * The shared tail of every single-record command: --fields validated
117
143
  * against the actual record, then the FIELD/VALUE table or picked JSON.
118
144
  */
119
- function selectedRecordFields(raw, record) {
145
+ function selectedRecordFields(raw, record,
146
+ /** What a completed write already did; a bad name must not invite a repeat. */
147
+ done) {
120
148
  const requested = [
121
149
  ...new Set(raw.split(",").map((name) => name.trim()).filter((name) => name !== "")),
122
150
  ];
123
151
  const first = requested.find((name) => !(name in record));
124
152
  if (first !== undefined) {
125
- throw new OpCliError("USAGE_ERROR", `field "${first}" is not a column. Valid fields, closest first: `
153
+ throw new OpCliError("USAGE_ERROR", `${done === undefined ? "" : `${done}; `}`
154
+ + `field "${first}" is not a column. Valid fields, closest first: `
126
155
  + `${rankByCloseness(first, Object.keys(record)).join(", ")}.`, "run the command without --fields to list every available field.");
127
156
  }
128
157
  return requested;
@@ -130,9 +159,9 @@ function selectedRecordFields(raw, record) {
130
159
  function renderFieldTable(fields, record) {
131
160
  return renderTable(["FIELD", "VALUE"], fields.map((field) => [field, formatCell(record[field])]));
132
161
  }
133
- function renderRecord(runtime, options, record) {
162
+ function renderRecord(runtime, options, record, done) {
134
163
  const fields = typeof options.fields === "string"
135
- ? selectedRecordFields(options.fields, record)
164
+ ? selectedRecordFields(options.fields, record, done)
136
165
  : Object.keys(record);
137
166
  if (options.json === true) {
138
167
  const picked = {};
@@ -151,16 +180,19 @@ function renderRecord(runtime, options, record) {
151
180
  * catalogue: 404 stays NOT_FOUND, 5xx becomes the unknown-state
152
181
  * NETWORK_ERROR, everything else carries the server's message.
153
182
  */
154
- async function projectWrite(attempt, verb) {
183
+ async function projectWrite(attempt, verb,
184
+ /** What to check before repeating, when "the project exists" is the wrong advice. */
185
+ check) {
186
+ const hint = check ?? (verb === "update"
187
+ ? "run op-cli project get to see the stored values before repeating the command."
188
+ : "check whether the project exists before repeating the command.");
155
189
  let response;
156
190
  try {
157
191
  response = await attempt();
158
192
  }
159
193
  catch (error) {
160
194
  if (error instanceof OpCliError && error.code === "NETWORK_ERROR") {
161
- throw new OpCliError("NETWORK_ERROR", `the ${verb} request did not complete; whether it was applied is unknown.`, verb === "update"
162
- ? "run op-cli project get to see the stored values before repeating the command."
163
- : "check whether the project exists before repeating the command.");
195
+ throw new OpCliError("NETWORK_ERROR", `the ${verb} request did not complete; whether it was applied is unknown.`, hint);
164
196
  }
165
197
  throw error;
166
198
  }
@@ -172,9 +204,7 @@ async function projectWrite(attempt, verb) {
172
204
  }
173
205
  if (response.status >= 500) {
174
206
  throw new OpCliError("NETWORK_ERROR", `the ${verb} failed with HTTP ${String(response.status)}; `
175
- + "whether it was applied is unknown.", verb === "update"
176
- ? "run op-cli project get to see the stored values before repeating the command."
177
- : "check whether the project exists before repeating the command.");
207
+ + "whether it was applied is unknown.", hint);
178
208
  }
179
209
  throw writeRefusal(verb, response.status, response.body);
180
210
  }
@@ -441,13 +471,13 @@ export function registerProjectCommands(project, runtime) {
441
471
  runtime.write(`Unstarred project ${hit.name} (${String(hit.id)}).\n`);
442
472
  });
443
473
  // ---------------------------------------------------------------------------
444
- // project versions / categories / types
474
+ // project versions / categories / sprints / buckets / types
445
475
  const vocabularyRuntime = {
446
476
  write: runtime.write,
447
477
  writeErr: runtime.writeErr,
448
478
  setJsonMode: runtime.setJsonMode,
449
479
  };
450
- const registerVocabulary = (name, description, endpoint, columns) => project
480
+ const registerVocabulary = (name, description, endpoint, columns, extras = {}) => project
451
481
  .command(name)
452
482
  .description(description)
453
483
  .argument("<reference>", "project, by id, identifier, or name")
@@ -456,18 +486,100 @@ export function registerProjectCommands(project, runtime) {
456
486
  .option("--profile <name>", "use this profile for this command only")
457
487
  .option("--project <name-or-id>", "override the profile default project")
458
488
  .action(async (reference, options) => {
489
+ const { tableCells, moved } = extras;
490
+ const { getPage } = await connect(runtime, options);
491
+ const hit = await resolveProjectRef(getPage, reference);
492
+ const collect = async (path) => {
493
+ const rows = [];
494
+ const shown = [];
495
+ for await (const element of halElements(getPage, withPageSize(path, DEFAULT_PAGE_SIZE))) {
496
+ const row = flattenHalRecord(element);
497
+ rows.push(row);
498
+ shown.push({ ...row, ...tableCells?.(element) });
499
+ }
500
+ return { rows, shown };
501
+ };
502
+ const collected = moved === undefined
503
+ ? await collect(endpoint(hit))
504
+ : await withMovedRetry(() => collect(endpoint(hit)), () => collect(moved(hit.id)));
505
+ emitRows(vocabularyRuntime, columns, options.json === true ? collected.rows : collected.shown, options);
506
+ });
507
+ registerVocabulary("versions", "List the versions a work package in this project may use", (hit) => hit.links?.versions ?? `${PROJECTS_COLLECTION}/${String(hit.id)}/versions`, VERSION_COLUMNS);
508
+ registerVocabulary("categories", "List the categories a work package in this project may use", (hit) => hit.links?.categories ?? `${PROJECTS_COLLECTION}/${String(hit.id)}/categories`, CATEGORY_COLUMNS);
509
+ registerVocabulary("sprints", "List the sprints a work package in this project may use", (hit) => `${PROJECTS_COLLECTION}/${String(hit.id)}/sprints`, SPRINT_COLUMNS, {
510
+ // The link's title is localized; the table shows the urn tail, like
511
+ // `meta sprints`.
512
+ tableCells: (element) => {
513
+ const status = sprintStatusKey(element);
514
+ return status === "" ? {} : { status };
515
+ },
516
+ moved: (projectId) => `${WORKSPACES_COLLECTION}/${String(projectId)}/sprints`,
517
+ });
518
+ registerVocabulary("buckets", "List the backlog buckets a work package in this project may use", (hit) => `${PROJECTS_COLLECTION}/${String(hit.id)}/backlog_buckets`, BUCKET_COLUMNS, { moved: (projectId) => `${WORKSPACES_COLLECTION}/${String(projectId)}/backlog_buckets` });
519
+ registerVocabulary("types", "List the work package types usable in this project", (hit) => hit.links?.types ?? `${PROJECTS_COLLECTION}/${String(hit.id)}/types`, TYPE_COLUMNS);
520
+ // ---------------------------------------------------------------------------
521
+ // project version create
522
+ project
523
+ .command("version")
524
+ .description("Manage the versions of one project")
525
+ .command("create")
526
+ .description("Create one version in a project")
527
+ .argument("<reference>", "project, by id, identifier, or name")
528
+ .argument("<name>", "name of the new version")
529
+ .option("--description <text>", 'markdown description; "" stores an empty one')
530
+ .option("--status <status>", "open, locked, or closed (default open)")
531
+ .option("--sharing <mode>", "none, descendants, hierarchy, tree, or system (instance default if omitted)")
532
+ .option("--start <date>", 'start date YYYY-MM-DD; "" leaves it empty')
533
+ .option("--end <date>", 'end date YYYY-MM-DD; "" leaves it empty')
534
+ .option("--json", "emit a flat JSON record")
535
+ .option("--fields <list>", "comma-separated fields to show")
536
+ .option("--profile <name>", "use this profile for this command only")
537
+ .option("--project <name-or-id>", "override the profile default project")
538
+ .action(async (reference, name, options) => {
539
+ // Misuse is refused before any traffic, JSON mode included.
540
+ runtime.setJsonMode(options.json === true);
541
+ if (name.trim() === "") {
542
+ throw new OpCliError("USAGE_ERROR", "the version name is empty.", "give the new version a non-empty <name>.");
543
+ }
544
+ const status = readChoice(options.status ?? "open", "--status", VERSION_STATUSES);
545
+ const sharing = readChoice(options.sharing, "--sharing", VERSION_SHARINGS);
546
+ const start = options.start === undefined || options.start === ""
547
+ ? options.start
548
+ : readDate(options.start, "--start");
549
+ const end = options.end === undefined || options.end === ""
550
+ ? options.end
551
+ : readDate(options.end, "--end");
552
+ if (start !== undefined && end !== undefined && start !== "" && end !== "" && start > end) {
553
+ throw new OpCliError("USAGE_ERROR", `--start ${start} is after --end ${end}.`, "give a start date on or before the end date.");
554
+ }
459
555
  const { getPage } = await connect(runtime, options);
556
+ const profile = await runtime.resolve({
557
+ profile: options.profile,
558
+ project: parseProjectOverride(options.project),
559
+ });
460
560
  const hit = await resolveProjectRef(getPage, reference);
461
- const startPath = withPageSize(endpoint(hit.id), DEFAULT_PAGE_SIZE);
462
- const rows = [];
463
- for await (const element of halElements(getPage, startPath)) {
464
- rows.push(flattenHalRecord(element));
561
+ const payload = {
562
+ name: name.trim(),
563
+ status,
564
+ _links: { definingProject: { href: `${PROJECTS_COLLECTION}/${String(hit.id)}` } },
565
+ };
566
+ if (options.description !== undefined) {
567
+ payload.description = toFormattable(options.description);
568
+ }
569
+ if (sharing !== undefined) {
570
+ payload.sharing = sharing;
571
+ }
572
+ if (start !== undefined) {
573
+ payload.startDate = start === "" ? null : start;
574
+ }
575
+ if (end !== undefined) {
576
+ payload.endDate = end === "" ? null : end;
465
577
  }
466
- emitRows(vocabularyRuntime, columns, rows, options);
578
+ const body = await projectWrite(() => apiPostRaw(profile.instanceUrl, profile.apiKey, VERSIONS_COLLECTION, payload), "create", `run op-cli project versions ${reference} before repeating the command, `
579
+ + "so the version is not created twice.");
580
+ const created = flattenHalRecord(body);
581
+ renderRecord(runtime, options, created, `version ${String(created.id)} was created`);
467
582
  });
468
- registerVocabulary("versions", "List the versions a work package in this project may use", (projectId) => `${PROJECTS_COLLECTION}/${String(projectId)}/versions`, VERSION_COLUMNS);
469
- registerVocabulary("categories", "List the categories a work package in this project may use", (projectId) => `${PROJECTS_COLLECTION}/${String(projectId)}/categories`, CATEGORY_COLUMNS);
470
- registerVocabulary("types", "List the work package types usable in this project", (projectId) => `${PROJECTS_COLLECTION}/${String(projectId)}/types`, TYPE_COLUMNS);
471
583
  // ---------------------------------------------------------------------------
472
584
  // project member add / remove
473
585
  const member = project
@@ -0,0 +1,67 @@
1
+ import { OpCliError, unknownIfUnfinished, writeFailure } from "../core/errors.js";
2
+ import { apiDeleteRaw, apiPatchRaw } from "../core/http.js";
3
+ import { addQueryScopeOptions, connectQuery, flattenQueryRecord, QUERIES_COLLECTION, refuseDefault, renderQueryRecord, resolveSavedQuery, } from "./query.js";
4
+ function registerStar(query, runtime, verb) {
5
+ const past = verb === "star" ? "starred" : "unstarred";
6
+ addQueryScopeOptions(query
7
+ .command(verb)
8
+ .description(verb === "star"
9
+ ? "Mark one saved query as a favourite of the current user"
10
+ : "Remove one saved query from the current user's favourites")
11
+ .argument("<id-or-name>", "query id or exact name")
12
+ .option("--json", "emit a flat JSON record")
13
+ .option("--fields <list>", "comma-separated fields to show")).action(async (reference, options) => {
14
+ // JSON mode is set first so the refusal below is shaped for the caller.
15
+ runtime.setJsonMode(options.json === true);
16
+ refuseDefault(reference);
17
+ const connection = await connectQuery(runtime, options);
18
+ const { id } = await resolveSavedQuery(connection, reference);
19
+ const { instanceUrl, apiKey } = connection.profile;
20
+ const wording = {
21
+ action: verb,
22
+ unknown: `whether the query was ${past} is unknown`,
23
+ check: `run op-cli query get ${String(id)} to check its starred state before repeating the command.`,
24
+ };
25
+ const response = await unknownIfUnfinished(() => apiPatchRaw(instanceUrl, apiKey, `${QUERIES_COLLECTION}/${String(id)}/${verb}`, {}), wording);
26
+ if (response.status >= 400) {
27
+ throw writeFailure(response.status, response.body, wording);
28
+ }
29
+ renderQueryRecord(runtime, options, flattenQueryRecord(response.body), `query ${String(id)} was ${past}`);
30
+ });
31
+ }
32
+ function registerDelete(query, runtime) {
33
+ addQueryScopeOptions(query
34
+ .command("delete")
35
+ .description("Delete one saved query after explicit confirmation")
36
+ .argument("<id-or-name>", "query id or exact name")
37
+ .option("--yes", "confirm the deletion")).action(async (reference, options) => {
38
+ // The guard fires before any resolution or traffic.
39
+ if (options.yes !== true) {
40
+ throw new OpCliError("USAGE_ERROR", `query delete refuses to remove "${reference}" without confirmation; `
41
+ + "deleting a query is irreversible.", "repeat the command with --yes to confirm the deletion.");
42
+ }
43
+ refuseDefault(reference);
44
+ const connection = await connectQuery(runtime, options);
45
+ const ref = await resolveSavedQuery(connection, reference);
46
+ const { id } = ref;
47
+ const wording = {
48
+ action: "delete",
49
+ unknown: "whether the query was deleted is unknown",
50
+ check: "run op-cli query list before repeating the command.",
51
+ };
52
+ const { instanceUrl, apiKey } = connection.profile;
53
+ const response = await unknownIfUnfinished(() => apiDeleteRaw(instanceUrl, apiKey, `${QUERIES_COLLECTION}/${String(id)}`), wording);
54
+ if (response.status >= 400) {
55
+ throw writeFailure(response.status, response.body, wording);
56
+ }
57
+ runtime.write(ref.name === undefined
58
+ ? `Deleted query ${String(id)}.\n`
59
+ : `Deleted query ${ref.name} (${String(id)}).\n`);
60
+ });
61
+ }
62
+ export function registerQueryManage(query, runtime) {
63
+ registerStar(query, runtime, "star");
64
+ registerStar(query, runtime, "unstar");
65
+ registerDelete(query, runtime);
66
+ }
67
+ //# sourceMappingURL=query-manage.js.map
@@ -0,0 +1,115 @@
1
+ import { OpCliError } from "../core/errors.js";
2
+ import { PAGED_JSON_HELP } from "../core/define.js";
3
+ import { flattenHalRecord } from "../core/hal.js";
4
+ import { allPageSize, halElements, parsePageSize, withPageSize } from "../core/paginate.js";
5
+ import { rankByCloseness } from "../context/resolve.js";
6
+ import { instancePathOf } from "../context/projectref.js";
7
+ import { formatCell, renderTable } from "../output/table.js";
8
+ import { addQueryScopeOptions, connectQuery, fetchQuery, lastSegment, resolveQueryRef, } from "./query.js";
9
+ import { LIST_COLUMNS } from "./wp.js";
10
+ /** The href without its pageSize, so the page size is set exactly once. */
11
+ function withoutPageSize(path) {
12
+ const [base = "", query] = path.split("?", 2);
13
+ const kept = (query ?? "").split("&").filter((part) => part !== "" && !part.startsWith("pageSize="));
14
+ return kept.length === 0 ? base : `${base}?${kept.join("&")}`;
15
+ }
16
+ /**
17
+ * The results path of a Query resource: the link the server gave, cut to
18
+ * start at /api/v3 so an instance subpath is not added twice. Without that
19
+ * link the filters of the query would be lost, so it fails loudly.
20
+ */
21
+ function resultsEndpointOf(query) {
22
+ const links = (query._links ?? {});
23
+ const href = links.results?.href;
24
+ const path = typeof href === "string" && href !== "" ? instancePathOf(href) : undefined;
25
+ if (path === undefined) {
26
+ throw new OpCliError("API_ERROR", "the query response carried no results link.", "check the instance version with op-cli doctor.");
27
+ }
28
+ return withoutPageSize(path);
29
+ }
30
+ /** The columns the query shows; the fixed work package columns when it defines none. */
31
+ function queryColumns(query) {
32
+ const links = (query._links ?? {});
33
+ const defined = Array.isArray(links.columns) ? links.columns : [];
34
+ const columns = defined.flatMap((link) => {
35
+ if (typeof link.href !== "string" || link.href === "") {
36
+ return [];
37
+ }
38
+ const field = lastSegment(link.href);
39
+ if (field === undefined) {
40
+ return [];
41
+ }
42
+ const title = typeof link.title === "string" && link.title !== "" ? link.title : field;
43
+ return [{ title: title.toUpperCase(), field }];
44
+ });
45
+ return columns.length === 0 ? LIST_COLUMNS : columns;
46
+ }
47
+ function fieldList(raw) {
48
+ return [...new Set(raw.split(",").map((name) => name.trim()).filter((name) => name !== ""))];
49
+ }
50
+ function requireFields(record, fields) {
51
+ const missing = fields.find((name) => !(name in record));
52
+ if (missing !== undefined) {
53
+ throw new OpCliError("USAGE_ERROR", `field "${missing}" is not a column. Valid fields, closest first: `
54
+ + `${rankByCloseness(missing, Object.keys(record)).join(", ")}.`, "run the command without --fields to list every available column.");
55
+ }
56
+ }
57
+ function pick(record, fields) {
58
+ return Object.fromEntries(fields.map((field) => [field, record[field]]));
59
+ }
60
+ export function registerQueryRun(query, runtime) {
61
+ addQueryScopeOptions(query
62
+ .command("run")
63
+ .description('Run a query and show its work packages, by id, name, or "default"')
64
+ .argument("<id-or-name>", 'query id, exact name, or "default"')
65
+ .option("--json", PAGED_JSON_HELP)
66
+ .option("--fields <list>", "comma-separated columns to show")
67
+ .option("--limit <n>", "maximum number of results to show")
68
+ .option("--all", "fetch every page instead of one limited page")).action(async (reference, options) => {
69
+ runtime.setJsonMode(options.json === true);
70
+ // Flag misuse is refused before any traffic.
71
+ const limit = parsePageSize(options.limit);
72
+ const connection = await connectQuery(runtime, options);
73
+ const resource = await fetchQuery(connection, await resolveQueryRef(connection, reference));
74
+ const endpoint = resultsEndpointOf(resource);
75
+ const { getPage: readPage } = connection;
76
+ const size = options.all === true ? await allPageSize(readPage) : limit;
77
+ const first = withPageSize(endpoint, size);
78
+ const requested = options.fields === undefined ? undefined : fieldList(options.fields);
79
+ const view = requested === undefined
80
+ ? queryColumns(resource)
81
+ : requested.map((field) => ({ title: field.toUpperCase(), field }));
82
+ const flatten = (element) => {
83
+ const record = flattenHalRecord(element);
84
+ if (requested !== undefined) {
85
+ requireFields(record, requested);
86
+ }
87
+ return record;
88
+ };
89
+ const table = (records) => renderTable(view.map((column) => column.title), records.map((record) => view.map((column) => formatCell(record[column.field]))));
90
+ const shaped = (record) => requested === undefined ? record : pick(record, requested);
91
+ if (options.all === true) {
92
+ if (options.json === true) {
93
+ for await (const element of halElements(readPage, first)) {
94
+ runtime.write(`${JSON.stringify(shaped(flatten(element)))}\n`);
95
+ }
96
+ return;
97
+ }
98
+ const records = [];
99
+ for await (const element of halElements(readPage, first)) {
100
+ records.push(flatten(element));
101
+ }
102
+ runtime.write(table(records));
103
+ return;
104
+ }
105
+ const page = (await readPage(first));
106
+ const records = (page._embedded?.elements ?? []).map(flatten);
107
+ runtime.write(options.json === true ? `${JSON.stringify(records.map(shaped))}\n` : table(records));
108
+ const total = typeof page.total === "number" ? page.total : records.length;
109
+ if (total > records.length) {
110
+ runtime.writeErr(`Showing ${String(records.length)} of ${String(total)} work packages. `
111
+ + "Pass --all to fetch every result.\n");
112
+ }
113
+ });
114
+ }
115
+ //# sourceMappingURL=query-run.js.map