@tuanhv/op-cli 0.3.1 → 0.4.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
@@ -39,7 +39,14 @@ points beyond the quickstart:
39
39
 
40
40
  ```sh
41
41
  op-cli wp create "Fix login bug" --type Bug --priority High
42
+ op-cli wp update 123 --start 2026-09-01 --due 2026-09-30 --estimate 4h --done 40 --story-points 5
42
43
  op-cli wp list --search login # server-side subject search
44
+ op-cli wp list --sort updatedAt:desc # repeatable; also --id <id>, --no-include-subprojects
45
+ op-cli wp update 123 --sprint "Sprint 14" # or --bucket <name>, never both
46
+ op-cli wp list --backlog-inbox # in neither a sprint nor a backlog bucket
47
+ op-cli wp watchers <id> # list watchers; also `wp watch` / `wp unwatch`, `wp list --watcher me`
48
+ op-cli wp attach 42 ./trace.log # upload; `wp attachments 42` lists, `wp attachment-download <id>` fetches
49
+ op-cli wp comment 42 "Ask first" --internal # internal comment, where the instance supports them
43
50
  op-cli time log 42 --hours 1h30m --activity Development
44
51
  op-cli time report --from 2026-08-01 --to 2026-08-31 # closed period
45
52
  op-cli project member add web alice Manager # join members so assignment works
@@ -52,16 +59,22 @@ op-cli update # self-update; prints the right command for Volta/Homeb
52
59
  ## Things worth knowing
53
60
 
54
61
  - **Errors are a closed set.** Every failure prints a stable code on stderr,
55
- such as `[CONFLICT]` or `[PROFILE_NOT_FOUND]`, with exit codes 0 through 7.
62
+ such as `[CONFLICT]` or `[PROFILE_NOT_FOUND]`, with exit codes 0 through 8.
56
63
  Run `op-cli doctor` when something does not work.
57
64
  - **A project in context narrows listings.** `--project`, or a profile's
58
65
  default project, scopes `wp list`, `wp count`, `time list`, and
59
66
  `time report` to that project and its subprojects. Without one, those
60
67
  four commands report instance-wide.
68
+ - **Workspace is another word for project.** OpenProject 17 renamed projects
69
+ to workspaces in its API. `--workspace` is accepted wherever `--project` is
70
+ (both may name the same project; different projects are refused), and
71
+ `op-cli workspace <subcommand>` is `op-cli project <subcommand>`. Output
72
+ keeps saying project.
61
73
  - **Finding things needs no id.** `wp list --search <text>` matches
62
74
  subjects server-side, `--created-after` / `--updated-after` bound by
63
- date, and `time list` / `time report` take `--from` and an inclusive
64
- `--to`. Every name flag also accepts the human name or the id.
75
+ date, `--due-before` / `--due-after` / `--overdue` bound by due date
76
+ (`7d` counts back from today; only `YYYY-MM-DD` reaches the future), and
77
+ `time list` / `time report` take `--from` and an inclusive `--to`. Every name flag also accepts the human name or the id.
65
78
  - **Tables respect the terminal.** Read from a terminal, a table is
66
79
  bounded to its width and long cells are cut with an ellipsis; `--json`
67
80
  output is never truncated.
@@ -174,7 +187,12 @@ cleans up known created IDs even on failure. Existing-project mode skips
174
187
  project creation, project description writes, and favourites. A timed-out
175
188
  creation can leave an unknown ID: inspect the test project before retrying;
176
189
  cleanup never guesses records by name. It fails loudly at the first
177
- broken step. There are no automated integration tests by design; this
190
+ broken step. On the disposable work package it also sets, clears (`""`),
191
+ and reads back with `wp get --json` the accountable, dates, estimate and
192
+ remaining work, percent complete, story points, version and observed-in,
193
+ sprint and bucket (including the clear-then-set move), and edits a comment;
194
+ optional steps print a `skip:` line when the project or schema lacks the
195
+ field. There are no automated integration tests by design; this
178
196
  script is the regression net for real write paths before every publish.
179
197
 
180
198
  Releases after the first can ship from CI: once the package exists and its
package/dist/bin.js CHANGED
@@ -21,6 +21,9 @@ exitOnBrokenPipe(process.stdout);
21
21
  exitOnBrokenPipe(process.stderr);
22
22
  const result = await run(process.argv.slice(2), process.env, createNodeIo());
23
23
  process.stdout.write(result.stdout);
24
+ if (result.stdoutBytes !== undefined) {
25
+ process.stdout.write(result.stdoutBytes);
26
+ }
24
27
  process.stderr.write(result.stderr);
25
28
  process.exitCode = result.exitCode;
26
29
  //# sourceMappingURL=bin.js.map
@@ -0,0 +1,196 @@
1
+ import { openAsBlob } from "node:fs";
2
+ import { stat, writeFile } from "node:fs/promises";
3
+ import { basename, join } from "node:path";
4
+ import { defineCollectionCommand } from "../core/define.js";
5
+ import { OpCliError, refuseCombined, unknownIfUnfinished, writeFailure, } from "../core/errors.js";
6
+ import { flattenHalRecord, formattableRaw } from "../core/hal.js";
7
+ import { apiGet, apiGetBytes, apiPostMultipartRaw, } from "../core/http.js";
8
+ import { isIdForm } from "../context/resolve.js";
9
+ export const ATTACHMENT_COLUMNS = [
10
+ { title: "ID", field: "id" },
11
+ { title: "FILE NAME", field: "fileName" },
12
+ { title: "SIZE", field: "fileSize" },
13
+ { title: "CONTENT TYPE", field: "contentType" },
14
+ { title: "AUTHOR", field: "author" },
15
+ { title: "CREATED", field: "createdAt" },
16
+ ];
17
+ /**
18
+ * One attachment as the flat record every attachment command shows: the
19
+ * whole flattened resource (ADR-0003), with the Formattable description
20
+ * reduced to its markdown. `--fields` is the projection.
21
+ */
22
+ export function attachmentRow(element) {
23
+ const record = flattenHalRecord(element);
24
+ if (!("description" in record)) {
25
+ return record;
26
+ }
27
+ const description = formattableRaw(record.description);
28
+ return { ...record, description: description === "" ? null : description };
29
+ }
30
+ /** The attributes of an attachment the API documents; a --fields name is checked against them. */
31
+ const ATTACHMENT_RECORD_SHAPE = Object.fromEntries([
32
+ "id", "title", "fileName", "fileSize", "description", "status",
33
+ "contentType", "digest", "createdAt", "author", "container",
34
+ ].map((field) => [field, null]));
35
+ function requireId(reference, what) {
36
+ if (!isIdForm(reference)) {
37
+ throw new OpCliError("USAGE_ERROR", `${what} "${reference}" is not an id.`, `${what}s are addressed by their numeric id.`);
38
+ }
39
+ }
40
+ /** The size ceiling of the instance, or undefined when it names none. */
41
+ async function maximumFileSize(profile) {
42
+ const configuration = await apiGet(profile.instanceUrl, profile.apiKey, "/api/v3/configuration");
43
+ const limit = configuration?.maximumAttachmentFileSize;
44
+ return typeof limit === "number" && limit > 0 ? limit : undefined;
45
+ }
46
+ /** What an upload says when its outcome cannot be known. */
47
+ const UPLOAD_WRITE = (reference) => ({
48
+ action: "upload",
49
+ unknown: "whether the file was attached is unknown",
50
+ check: `run op-cli wp attachments ${reference} before repeating the command.`,
51
+ });
52
+ async function pathKind(path) {
53
+ try {
54
+ const info = await stat(path);
55
+ return info.isFile() ? "file" : info.isDirectory() ? "directory" : "other";
56
+ }
57
+ catch {
58
+ return "missing";
59
+ }
60
+ }
61
+ async function upload(runtime, helpers, reference, path, options) {
62
+ helpers.requireWpId(reference);
63
+ // --fields is checked against the columns every attachment record has,
64
+ // so a typo is refused before the upload and a repeat cannot attach
65
+ // the file twice.
66
+ helpers.selectedFields(options.fields, ATTACHMENT_RECORD_SHAPE);
67
+ // Every refusal that needs no network comes before the first request,
68
+ // so a repeated command can never upload twice.
69
+ const kind = await pathKind(path);
70
+ if (kind !== "file") {
71
+ throw new OpCliError("USAGE_ERROR", kind === "missing"
72
+ ? `file "${path}" does not exist or is not readable.`
73
+ : `"${path}" is not a regular file.`, "pass the path of a readable file.");
74
+ }
75
+ const fileName = options.name ?? basename(path);
76
+ if (fileName === "") {
77
+ throw new OpCliError("USAGE_ERROR", "--name must not be empty.");
78
+ }
79
+ const size = (await stat(path)).size;
80
+ const profile = await helpers.openProfile(runtime, options);
81
+ const limit = await maximumFileSize(profile);
82
+ if (limit !== undefined && size > limit) {
83
+ throw new OpCliError("USAGE_ERROR", `"${path}" is ${String(size)} bytes; the instance accepts at most ${String(limit)} bytes per attachment.`, "attach a smaller file.");
84
+ }
85
+ let blob;
86
+ try {
87
+ blob = await openAsBlob(path);
88
+ }
89
+ catch {
90
+ throw new OpCliError("USAGE_ERROR", `file "${path}" does not exist or is not readable.`, "pass the path of a readable file.");
91
+ }
92
+ const form = new FormData();
93
+ form.append("metadata", JSON.stringify({
94
+ fileName,
95
+ ...(options.description === undefined ? {} : { description: { raw: options.description } }),
96
+ }));
97
+ form.append("file", blob, fileName);
98
+ const response = await unknownIfUnfinished(() => apiPostMultipartRaw(profile.instanceUrl, profile.apiKey, `/api/v3/work_packages/${reference}/attachments`, form), UPLOAD_WRITE(reference));
99
+ if (response.status < 200 || response.status >= 300) {
100
+ throw writeFailure(response.status, response.body, UPLOAD_WRITE(reference));
101
+ }
102
+ helpers.renderRecord(runtime, options, attachmentRow(response.body), "the file was attached");
103
+ }
104
+ async function download(runtime, helpers, reference, options) {
105
+ requireId(reference, "attachment");
106
+ // Bytes on stdout carry no JSON record, and there is no file to
107
+ // overwrite: refuse the combination instead of ignoring a flag.
108
+ const toStdout = options.output === "-";
109
+ refuseCombined([toStdout ? "--output -" : undefined, options.json === true ? "--json" : undefined], "--output - writes the file's bytes to stdout; drop --json or write to a path.");
110
+ refuseCombined([toStdout ? "--output -" : undefined, options.force === true ? "--force" : undefined], "--output - writes to stdout, where there is no file to overwrite.");
111
+ const profile = await helpers.openProfile(runtime, options);
112
+ const get = (path) => apiGet(profile.instanceUrl, profile.apiKey, path);
113
+ const contentPath = `/api/v3/attachments/${reference}/content`;
114
+ if (toStdout) {
115
+ runtime.writeBytes(await apiGetBytes(profile.instanceUrl, profile.apiKey, contentPath));
116
+ return;
117
+ }
118
+ const meta = attachmentRow(await get(`/api/v3/attachments/${reference}`));
119
+ // The server's name is never trusted as a path: only its last segment.
120
+ const fileName = basename(typeof meta.fileName === "string" ? meta.fileName : "") || `attachment-${reference}`;
121
+ let target = options.output ?? fileName;
122
+ if (options.output !== undefined && await pathKind(options.output) === "directory") {
123
+ target = join(options.output, fileName);
124
+ }
125
+ const existing = await pathKind(target);
126
+ if (existing === "directory" || (existing !== "missing" && options.force !== true)) {
127
+ throw new OpCliError("USAGE_ERROR", existing === "directory"
128
+ ? `"${target}" is a directory.`
129
+ : `"${target}" already exists.`, existing === "directory"
130
+ ? "pass --output with a file path."
131
+ : "pass --force to overwrite it, or --output with another path.");
132
+ }
133
+ const bytes = await apiGetBytes(profile.instanceUrl, profile.apiKey, contentPath);
134
+ try {
135
+ // "wx" keeps the no-overwrite promise even if the file appeared since
136
+ // the check above.
137
+ await writeFile(target, bytes, { flag: options.force === true ? "w" : "wx" });
138
+ }
139
+ catch (error) {
140
+ const code = error.code;
141
+ throw new OpCliError("USAGE_ERROR", code === "EEXIST"
142
+ ? `"${target}" already exists.`
143
+ : `cannot write "${target}": ${code ?? "unknown error"}.`, code === "EEXIST"
144
+ ? "pass --force to overwrite it, or --output with another path."
145
+ : "pass --output with a writable path.");
146
+ }
147
+ if (options.json === true) {
148
+ runtime.write(`${JSON.stringify({
149
+ id: Number(reference),
150
+ fileName,
151
+ path: target,
152
+ size: bytes.length,
153
+ })}\n`);
154
+ return;
155
+ }
156
+ runtime.write(`Saved ${target} (${String(bytes.length)} bytes).\n`);
157
+ }
158
+ /**
159
+ * Work package attachments. `attach` and `attachment-download` are
160
+ * separate commands rather than flags of `wp attachments`: the download
161
+ * target is an attachment id, not a work package id, the same split as
162
+ * `wp comment` and `wp comment-edit`. There is deliberately no delete.
163
+ */
164
+ export function registerAttachmentCommands(wp, runtime, helpers) {
165
+ wp.addCommand(defineCollectionCommand({
166
+ name: "attachments",
167
+ description: "List the attachments of one work package",
168
+ path: (id) => `/api/v3/work_packages/${id}/attachments`,
169
+ row: attachmentRow,
170
+ columns: ATTACHMENT_COLUMNS,
171
+ resolve: (getPage) => helpers.authorResolver(getPage, "author"),
172
+ }, helpers.collectionRuntime));
173
+ wp.command("attach")
174
+ .description("Upload a file as an attachment of one work package")
175
+ .argument("<id>", "work package id")
176
+ .argument("<path>", "file to upload")
177
+ .option("--description <text>", "description stored with the attachment")
178
+ .option("--name <fileName>", "file name to store instead of the file's own")
179
+ .option("--json", "emit a flat JSON record")
180
+ .option("--fields <list>", "comma-separated columns to show")
181
+ .option("--profile <name>", "use this profile for this command only")
182
+ .option("--project <name-or-id>", "override the profile default project")
183
+ .action((reference, path, options) => upload(runtime, helpers, reference, path, options));
184
+ // Named after its target, like `comment-edit`: the argument is an
185
+ // attachment id, never a work package id.
186
+ wp.command("attachment-download")
187
+ .description("Download one attachment by id (see `wp attachments`)")
188
+ .argument("<attachment-id>", "id of the attachment, as listed by `wp attachments`")
189
+ .option("--output <path>", "file or directory to write; - writes to stdout (default: the attachment's file name)")
190
+ .option("--force", "overwrite an existing file")
191
+ .option("--json", "emit the saved file as a JSON record")
192
+ .option("--profile <name>", "use this profile for this command only")
193
+ .option("--project <name-or-id>", "override the profile default project")
194
+ .action((reference, options) => download(runtime, helpers, reference, options));
195
+ }
196
+ //# sourceMappingURL=attachments.js.map
@@ -20,6 +20,24 @@ function majorOf(version) {
20
20
  const major = match?.[1];
21
21
  return major === undefined ? undefined : Number.parseInt(major, 10);
22
22
  }
23
+ /**
24
+ * Feature names from /api/v3/configuration. Some instances hide coreVersion
25
+ * from the root document yet keep the configuration readable; its
26
+ * availableFeatures is the evidence that remains. Never throws: a refused or
27
+ * odd configuration only means there is less to report.
28
+ */
29
+ async function availableFeaturesOf(profile) {
30
+ try {
31
+ const configuration = await apiGet(profile.instanceUrl, profile.apiKey, "/api/v3/configuration");
32
+ const features = configuration.availableFeatures;
33
+ return Array.isArray(features)
34
+ ? features.filter((entry) => typeof entry === "string")
35
+ : [];
36
+ }
37
+ catch {
38
+ return [];
39
+ }
40
+ }
23
41
  function errorCodeOf(error) {
24
42
  return error instanceof OpCliError ? error.code : "INTERNAL_ERROR";
25
43
  }
@@ -113,6 +131,16 @@ export function registerDoctorCommand(parent, runtime) {
113
131
  detail: `core ${info.coreVersion} is below the minimum supported v13`,
114
132
  });
115
133
  }
134
+ else if (info.coreVersion === null) {
135
+ const features = await availableFeaturesOf(profile);
136
+ checks.push({
137
+ check: "versions",
138
+ status: "info",
139
+ detail: `core version hidden; API v3 reachable${features.length === 0
140
+ ? "; no feature list readable"
141
+ : `; features: ${features.join(", ")}`}`,
142
+ });
143
+ }
116
144
  else {
117
145
  checks.push({
118
146
  check: "versions",
@@ -1,4 +1,4 @@
1
- import { clearStoredMetadata, customFieldAllowedNames, loadProjectVocabulary, loadStoredMetadata, readStoredMetadata, refreshStoredMetadata, } from "../context/metadata.js";
1
+ import { clearStoredMetadata, customFieldAllowedNames, loadProjectVocabulary, loadStoredMetadata, readStoredMetadata, refreshStoredMetadata, requireVocabulary, unavailableSources, } from "../context/metadata.js";
2
2
  import { parseProjectOverride } from "../context/profile.js";
3
3
  import { defineLookupCommand, } from "../core/define.js";
4
4
  import { renderTable } from "../output/table.js";
@@ -77,7 +77,7 @@ const memberLookup = {
77
77
  const versionLookup = {
78
78
  name: "versions",
79
79
  description: "List the versions of the active project",
80
- select: (vocabulary) => vocabulary.versions,
80
+ select: (vocabulary) => requireVocabulary(vocabulary, "versions"),
81
81
  options: [profileOption, projectOption],
82
82
  columns: [
83
83
  { title: "ID", cell: (entry) => String(entry.id) },
@@ -88,7 +88,30 @@ const versionLookup = {
88
88
  const categoryLookup = {
89
89
  name: "categories",
90
90
  description: "List the categories of the active project",
91
- select: (vocabulary) => vocabulary.categories,
91
+ select: (vocabulary) => requireVocabulary(vocabulary, "categories"),
92
+ options: [profileOption, projectOption],
93
+ columns: [
94
+ { title: "ID", cell: (entry) => String(entry.id) },
95
+ { title: "NAME", cell: (entry) => entry.name },
96
+ ],
97
+ };
98
+ const sprintLookup = {
99
+ name: "sprints",
100
+ description: "List the sprints of the active project",
101
+ select: (vocabulary) => requireVocabulary(vocabulary, "sprints"),
102
+ options: [profileOption, projectOption],
103
+ columns: [
104
+ { title: "ID", cell: (entry) => String(entry.id) },
105
+ { title: "NAME", cell: (entry) => entry.name },
106
+ { title: "START", cell: (entry) => entry.start_date ?? "" },
107
+ { title: "FINISH", cell: (entry) => entry.finish_date ?? "" },
108
+ { title: "STATUS", cell: (entry) => entry.status },
109
+ ],
110
+ };
111
+ const bucketLookup = {
112
+ name: "buckets",
113
+ description: "List the backlog buckets of the active project",
114
+ select: (vocabulary) => requireVocabulary(vocabulary, "buckets"),
92
115
  options: [profileOption, projectOption],
93
116
  columns: [
94
117
  { title: "ID", cell: (entry) => String(entry.id) },
@@ -144,7 +167,7 @@ const fieldLookup = {
144
167
  const activityLookup = {
145
168
  name: "activities",
146
169
  description: "List the time entry activities of the active project",
147
- select: (vocabulary) => vocabulary.activities,
170
+ select: (vocabulary) => requireVocabulary(vocabulary, "activities"),
148
171
  options: [profileOption, projectOption],
149
172
  columns: [
150
173
  { title: "ID", cell: (entry) => String(entry.id) },
@@ -182,6 +205,10 @@ function registerShow(parent, runtime) {
182
205
  ["types", String(stored.types.length)],
183
206
  ["statuses", String(stored.statuses.length)],
184
207
  ["priorities", String(stored.priorities.length)],
208
+ ...unavailableSources(stored).map((entry) => [
209
+ "unavailable",
210
+ `project ${String(entry.project_id)}: ${entry.source} (${String(entry.status)})`,
211
+ ]),
185
212
  ]));
186
213
  });
187
214
  }
@@ -200,16 +227,25 @@ function registerRefresh(parent, runtime) {
200
227
  runtime.setJsonMode(options.json === true);
201
228
  const profile = await runtime.resolve({ profile: options.profile });
202
229
  const changes = await refreshStoredMetadata(runtime.env, profile);
230
+ // A refused source is not a change, but a caller relying on it needs
231
+ // to hear about it on every refresh, not only when it flips.
232
+ const stored = await readStoredMetadata(runtime.env, profile);
233
+ const unavailable = stored === undefined ? [] : unavailableSources(stored);
203
234
  if (options.json === true) {
204
235
  runtime.write(`${JSON.stringify({
205
236
  profile: profile.name,
206
237
  instance: profile.instanceUrl,
207
238
  changes,
239
+ unavailable,
208
240
  })}\n`);
209
241
  return;
210
242
  }
211
243
  runtime.write(`Refreshing metadata for profile ${profile.name} at ${profile.instanceUrl}.\n`);
212
244
  writeChangeLines(runtime.write, changes);
245
+ for (const entry of unavailable) {
246
+ runtime.write(`unavailable: project ${String(entry.project_id)} ${entry.source}`
247
+ + ` (${String(entry.status)}: ${entry.message})\n`);
248
+ }
213
249
  runtime.write(changes.length > 0 ? "Metadata updated.\n" : "No changes.\n");
214
250
  });
215
251
  }
@@ -264,6 +300,16 @@ async function projectProfile(runtime, options) {
264
300
  function projectLoad(runtime) {
265
301
  return async (options) => loadProjectVocabulary(runtime.env, await projectProfile(runtime, options));
266
302
  }
303
+ /**
304
+ * The project load for the sprint and bucket lookups: a vocabulary stored
305
+ * before those sources were captured is refreshed once instead of
306
+ * listing nothing.
307
+ */
308
+ function backlogLoad(runtime) {
309
+ return async (options) => loadProjectVocabulary(runtime.env, await projectProfile(runtime, options), {
310
+ require: ["sprints", "buckets"],
311
+ });
312
+ }
267
313
  /**
268
314
  * The fields lookup needs the instance types too, to name them. Instance
269
315
  * metadata is loaded first because the vocabulary is stored inside it, so
@@ -280,7 +326,7 @@ function fieldLoad(runtime) {
280
326
  };
281
327
  }
282
328
  export function registerMetaCommands(parent, runtime) {
283
- // Eight read-only lookups, one declaration each.
329
+ // Ten read-only lookups, one declaration each.
284
330
  const instance = instanceLoad(runtime);
285
331
  const project = projectLoad(runtime);
286
332
  addLookup(parent, runtime, typeLookup, instance);
@@ -291,6 +337,8 @@ export function registerMetaCommands(parent, runtime) {
291
337
  addLookup(parent, runtime, categoryLookup, project);
292
338
  addLookup(parent, runtime, fieldLookup, fieldLoad(runtime));
293
339
  addLookup(parent, runtime, activityLookup, project);
340
+ addLookup(parent, runtime, sprintLookup, backlogLoad(runtime));
341
+ addLookup(parent, runtime, bucketLookup, backlogLoad(runtime));
294
342
  registerShow(parent, runtime);
295
343
  registerRefresh(parent, runtime);
296
344
  registerClear(parent, runtime);
@@ -294,7 +294,8 @@ Successful IDs are not rolled back. Inspect per-ID results, not just stderr.
294
294
  }
295
295
  catch (cause) {
296
296
  let error = cause instanceof OpCliError ? cause : new OpCliError("INTERNAL_ERROR");
297
- const unknown = writing && error.code !== "AUTH_FAILED";
297
+ const unknown = writing && error.code !== "AUTH_FAILED"
298
+ && error.code !== "PERMISSION_DENIED";
298
299
  if (unknown) {
299
300
  error = new OpCliError(error.code, `The write result for notification ${id} is unknown.`, "read the notification state before deciding whether to repeat the write; it was not retried.", error.details);
300
301
  }
@@ -7,7 +7,8 @@ import { apiDelete, apiGet, apiPatchRaw, apiPost, apiPostRaw, authenticate, } fr
7
7
  import { DEFAULT_PAGE_SIZE, allPageSize, halElements, parsePageSize, withPageSize, } from "../core/paginate.js";
8
8
  import { isIdForm, rankByCloseness, resolveName, } from "../context/resolve.js";
9
9
  import { parseProjectOverride, } from "../context/profile.js";
10
- import { PROJECTS_COLLECTION, resolveProjectRef } from "../context/projectref.js";
10
+ import { sprintStatusKey } from "../context/metadata.js";
11
+ import { PROJECTS_COLLECTION, resolveProjectRef, withMovedRetry, WORKSPACES_COLLECTION, } from "../context/projectref.js";
11
12
  export const LIST_COLUMNS = [
12
13
  { title: "ID", field: "id" },
13
14
  { title: "IDENTIFIER", field: "identifier" },
@@ -24,6 +25,17 @@ export const CATEGORY_COLUMNS = [
24
25
  { title: "ID", field: "id" },
25
26
  { title: "NAME", field: "name" },
26
27
  ];
28
+ export const SPRINT_COLUMNS = [
29
+ { title: "ID", field: "id" },
30
+ { title: "NAME", field: "name" },
31
+ { title: "START", field: "startDate" },
32
+ { title: "FINISH", field: "finishDate" },
33
+ { title: "STATUS", field: "status" },
34
+ ];
35
+ export const BUCKET_COLUMNS = [
36
+ { title: "ID", field: "id" },
37
+ { title: "NAME", field: "name" },
38
+ ];
27
39
  export const TYPE_COLUMNS = [
28
40
  { title: "ID", field: "id" },
29
41
  { title: "NAME", field: "name" },
@@ -441,13 +453,13 @@ export function registerProjectCommands(project, runtime) {
441
453
  runtime.write(`Unstarred project ${hit.name} (${String(hit.id)}).\n`);
442
454
  });
443
455
  // ---------------------------------------------------------------------------
444
- // project versions / categories / types
456
+ // project versions / categories / sprints / buckets / types
445
457
  const vocabularyRuntime = {
446
458
  write: runtime.write,
447
459
  writeErr: runtime.writeErr,
448
460
  setJsonMode: runtime.setJsonMode,
449
461
  };
450
- const registerVocabulary = (name, description, endpoint, columns) => project
462
+ const registerVocabulary = (name, description, endpoint, columns, extras = {}) => project
451
463
  .command(name)
452
464
  .description(description)
453
465
  .argument("<reference>", "project, by id, identifier, or name")
@@ -456,18 +468,37 @@ export function registerProjectCommands(project, runtime) {
456
468
  .option("--profile <name>", "use this profile for this command only")
457
469
  .option("--project <name-or-id>", "override the profile default project")
458
470
  .action(async (reference, options) => {
471
+ const { tableCells, moved } = extras;
459
472
  const { getPage } = await connect(runtime, options);
460
473
  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));
465
- }
466
- emitRows(vocabularyRuntime, columns, rows, options);
474
+ const collect = async (path) => {
475
+ const rows = [];
476
+ const shown = [];
477
+ for await (const element of halElements(getPage, withPageSize(path, DEFAULT_PAGE_SIZE))) {
478
+ const row = flattenHalRecord(element);
479
+ rows.push(row);
480
+ shown.push({ ...row, ...tableCells?.(element) });
481
+ }
482
+ return { rows, shown };
483
+ };
484
+ const collected = moved === undefined
485
+ ? await collect(endpoint(hit))
486
+ : await withMovedRetry(() => collect(endpoint(hit)), () => collect(moved(hit.id)));
487
+ emitRows(vocabularyRuntime, columns, options.json === true ? collected.rows : collected.shown, options);
488
+ });
489
+ 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);
490
+ 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);
491
+ registerVocabulary("sprints", "List the sprints a work package in this project may use", (hit) => `${PROJECTS_COLLECTION}/${String(hit.id)}/sprints`, SPRINT_COLUMNS, {
492
+ // The link's title is localized; the table shows the urn tail, like
493
+ // `meta sprints`.
494
+ tableCells: (element) => {
495
+ const status = sprintStatusKey(element);
496
+ return status === "" ? {} : { status };
497
+ },
498
+ moved: (projectId) => `${WORKSPACES_COLLECTION}/${String(projectId)}/sprints`,
467
499
  });
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);
500
+ 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` });
501
+ registerVocabulary("types", "List the work package types usable in this project", (hit) => hit.links?.types ?? `${PROJECTS_COLLECTION}/${String(hit.id)}/types`, TYPE_COLUMNS);
471
502
  // ---------------------------------------------------------------------------
472
503
  // project member add / remove
473
504
  const member = project
@@ -7,7 +7,7 @@ import { apiDelete, apiGet, apiPatchRaw, apiPostRaw, authenticate, } from "../co
7
7
  import { allPageSize, halElements, parsePageSize, withPageSize } from "../core/paginate.js";
8
8
  import { isIdForm, rankByCloseness, resolveName, } from "../context/resolve.js";
9
9
  import { parseProjectOverride, } from "../context/profile.js";
10
- import { loadProjectVocabulary, loadProjectVocabularyById, refreshStoredMetadata, } from "../context/metadata.js";
10
+ import { loadProjectVocabulary, loadProjectVocabularyById, refreshStoredMetadata, requireVocabulary, } from "../context/metadata.js";
11
11
  import { formatCell, renderTable } from "../output/table.js";
12
12
  // One flat row per time entry; the work package sits on every row so a
13
13
  // multi-wp listing stays a single table instead of a nested grouping.
@@ -166,7 +166,7 @@ function membersSource(env, profile) {
166
166
  label: "user",
167
167
  load: async () => {
168
168
  if (profile.project === undefined) {
169
- throw new OpCliError("USAGE_ERROR", "--user needs a project to look member names up in.", "pass --project <name-or-id> or set a default project on the profile.");
169
+ throw new OpCliError("USAGE_ERROR", "--user needs a project to look member names up in.", "pass --project <name-or-id> (or --workspace) or set a default project on the profile.");
170
170
  }
171
171
  const select = (vocabulary) => vocabulary.members.map((member) => ({
172
172
  name: member.name,
@@ -210,7 +210,7 @@ async function resolveUserValues(env, profile, raws) {
210
210
  function activitiesSource(env, profile, projectId) {
211
211
  return {
212
212
  label: "activity",
213
- load: async () => (await loadProjectVocabularyById(env, profile, projectId)).activities.map((activity) => ({ name: activity.name, owner: "activity", value: activity.id })),
213
+ load: async () => requireVocabulary(await loadProjectVocabularyById(env, profile, projectId), "activities").map((activity) => ({ name: activity.name, owner: "activity", value: activity.id })),
214
214
  refresh: async () => {
215
215
  await refreshStoredMetadata(env, profile);
216
216
  },