@kud/jira-cli 0.10.0 → 0.12.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.
Files changed (3) hide show
  1. package/README.md +31 -3
  2. package/dist/index.js +391 -38
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -79,8 +79,9 @@ jira issue list # yours, most recently updated first
79
79
  jira issue list --status 'In Progress'
80
80
  jira issue list --project ABC --sprint current
81
81
  jira issue view ABC-123
82
+ jira issue view ABC-123 --fields status,assignee,issuelinks
82
83
  jira issue transition ABC-123 # list what's available
83
- jira issue transition ABC-123 'In Review'
84
+ jira issue transition ABC-123 'In Review' # by transition name or target status
84
85
  jira issue open ABC-123
85
86
  ```
86
87
 
@@ -88,14 +89,16 @@ Writing:
88
89
 
89
90
  ```sh
90
91
  jira issue create -p ABC -t Task -s 'Fix the thing' -b 'Longer **markdown** body'
91
- jira issue edit ABC-123 --summary 'Better title'
92
- jira issue assign ABC-123 me # or a name, or 'none'
92
+ jira issue create -p ABC -t Task -s 'A sub-task' --parent ABC-100 --link Relates:ABC-99
93
+ jira issue edit ABC-123 --summary 'Better title' --assignee me --parent ABC-100
94
+ jira issue assign ABC-123 me # or a name, an email, an account id, or 'none'
93
95
  jira issue comment add ABC-123 - # body from stdin
94
96
  jira issue comment list ABC-123
95
97
  jira issue comment edit ABC-123 12345 'Actually fixed in 2.1'
96
98
  jira issue delete ABC-123 # asks first; --yes to confirm in scripts
97
99
  jira issue rank ABC-1 ABC-2 --before ABC-3
98
100
  jira issue link ABC-1 Blocks ABC-2
101
+ jira issue link list ABC-1
99
102
  jira issue watch add ABC-123
100
103
  jira issue worklog add ABC-123 '2h 30m'
101
104
  jira issue worklog edit ABC-123 456 --time '3h'
@@ -106,6 +109,14 @@ jira issue remotelink remove ABC-123 789
106
109
  jira issue history ABC-123
107
110
  ```
108
111
 
112
+ `jira issue view` lists the issue's links and subtasks, in plain text and in `--json`. Pass `--fields status,assignee,parent,issuelinks` (comma-separated) to see only those fields — both in plain text and `--json`; the key and summary stay either way, and without `--fields` the view is exactly what it has always been.
113
+
114
+ People are resolved for you. `issue assign`, and `--assignee` on `create` and `edit`, accept a name or an email: assignable users of the project are searched first, then every user. `me` means you, `none` unassigns, and a raw account id passes straight through. If a name matches several people nothing is assigned — every match is printed on stderr and the command exits non-zero, because a guess is worse than an error.
115
+
116
+ Parents and links belong to the same commands. `--parent ABC-100` sets a parent on `create` or `edit`, and `edit --parent none` clears it. `--link Relates:ABC-99` (repeatable, `<type>:<KEY>`) links the new issue right after creating it, exactly as `jira issue link <new> <type> <KEY>` would. The link type is checked against your instance's link type names before anything is created, so a typo costs nothing; if creation succeeds but a link fails, the new key and the failure are reported and the exit is non-zero.
117
+
118
+ `issue transition` takes either a transition name or the status it leads to (`Start Progress` or `In Progress`), matched case-insensitively and by transition id. With no argument it lists the transitions as `name → target status`.
119
+
109
120
  Bodies accept Markdown — paragraphs, headings, lists, fenced code, links and code spans are converted to ADF.
110
121
 
111
122
  Deletes (`issue delete`, `comment delete`, `worklog delete`, `remotelink remove`) ask before they act; piped or scripted runs refuse unless `--yes` is passed, since there is no undo on Jira's side. `remotelink add` is idempotent: re-adding the same url updates the same link rather than creating duplicates.
@@ -194,6 +205,21 @@ jira fields points
194
205
 
195
206
  Named fields are requested on every search and shown in `issue view`.
196
207
 
208
+ ## Automation rules
209
+
210
+ ```sh
211
+ jira automation list --project SHOP # --state ENABLED|DISABLED, --limit, --json
212
+ jira automation get 0192e5ac-0e25-71de-ba7b-d972e6a2049a > rule.json
213
+ jira automation update 0192e5ac-0e25-71de-ba7b-d972e6a2049a --file rule.json
214
+ jira automation create --file rule.json # prints the new rule's UUID; - reads stdin
215
+ jira automation disable 0192e5ac-0e25-71de-ba7b-d972e6a2049a
216
+ jira automation enable 0192e5ac-0e25-71de-ba7b-d972e6a2049a
217
+ ```
218
+
219
+ These use Atlassian's [Automation REST API](https://developer.atlassian.com/cloud/automation/rest/api-group-rule-management/) with the same classic API token as everything else; nothing new to configure. The account behind it needs the **Jira administrator** global permission (Administer Jira): Jira answers a project admin with a bare 403, even for rules scoped to that project, and the CLI says so and exits 4. Project admins can still manage their project's rules in the Jira web UI.
220
+
221
+ `create` and `update` take the shape `get` prints, `{ "rule": { … } }`, or a bare rule. The cloud ID is read from the site's `/_edge/tenant_info`; set `ATLASSIAN_CLOUD_ID` to skip that call. Requests go through the site's gateway by default; `--host api` (or `ATLASSIAN_AUTOMATION_HOST=api`) sends them to `api.atlassian.com` instead.
222
+
197
223
  ## Escape hatch
198
224
 
199
225
  Anything not covered:
@@ -203,6 +229,8 @@ jira api /rest/api/3/myself
203
229
  jira api /rest/api/3/issue/ABC-123/watchers -X POST -d '{"accountId":"..."}'
204
230
  ```
205
231
 
232
+ A call returning 2xx with an empty body — a 204, or a 201 with no content — prints nothing and exits 0, rather than printing the string `null`; that way `null` only ever means Jira really answered null. A non-2xx is still an error, showing the body.
233
+
206
234
  ## Licence
207
235
 
208
236
  MIT
package/dist/index.js CHANGED
@@ -14,7 +14,212 @@ import { realpathSync } from "fs";
14
14
  import { createRequire } from "module";
15
15
  import { fileURLToPath } from "url";
16
16
  import { Command } from "commander";
17
- import { configPath as configPath2, isJiraApiError } from "@kud/jira";
17
+ import { configPath as configPath2, isJiraApiError as isJiraApiError2 } from "@kud/jira";
18
+
19
+ // src/commands/automation.ts
20
+ import { readFileSync } from "fs";
21
+ import { isJiraApiError } from "@kud/jira";
22
+ var HOSTS = /* @__PURE__ */ new Set(["site", "api"]);
23
+ var automationHost = (flag, env = process.env) => {
24
+ const raw = (flag ?? env["ATLASSIAN_AUTOMATION_HOST"] ?? "site").toLowerCase();
25
+ if (!HOSTS.has(raw))
26
+ throw exitError(2, `unknown automation host '${raw}' \u2014 use 'site' or 'api'`);
27
+ return raw;
28
+ };
29
+ var automationBase = (host, baseUrl, cloudId) => host === "api" ? `https://api.atlassian.com/automation/public/jira/${cloudId}/rest/v1` : `${baseUrl}/gateway/api/automation/public/jira/${cloudId}/rest/v1`;
30
+ var resolveCloudId = async (client, env = process.env) => {
31
+ const fromEnv = env["ATLASSIAN_CLOUD_ID"];
32
+ if (fromEnv) return fromEnv;
33
+ const tenant = await client.request(
34
+ "/_edge/tenant_info"
35
+ );
36
+ if (!tenant?.cloudId)
37
+ throw exitError(
38
+ 1,
39
+ "could not read this site's cloud ID from /_edge/tenant_info \u2014 set ATLASSIAN_CLOUD_ID"
40
+ );
41
+ return tenant.cloudId;
42
+ };
43
+ var explainAuthFailure = (error) => {
44
+ if (!isJiraApiError(error)) return error;
45
+ if (error.status === 401)
46
+ return exitError(
47
+ 4,
48
+ "Jira rejected the credentials for the Automation API.\nATLASSIAN_API_TOKEN must be a classic API token (basic auth with ATLASSIAN_USER_EMAIL) \u2014\nthe rule management API is closed to OAuth 2.0 and Forge apps.\n id.atlassian.com/manage-profile/security/api-tokens"
49
+ );
50
+ if (error.status === 403)
51
+ return exitError(
52
+ 4,
53
+ `Automation API refused ${error.method} (403).
54
+ Managing automation rules needs the Jira administrator global permission
55
+ (Administer Jira) on the account behind ATLASSIAN_API_TOKEN; project admin is not enough,
56
+ even for rules scoped to that project. Ask a Jira admin to grant it, or to run the command.
57
+ A project admin can still create and edit that project's rules in the Jira web UI.`
58
+ );
59
+ return error;
60
+ };
61
+ var automation = async (hostFlag) => {
62
+ const host = automationHost(hostFlag);
63
+ const ctx = context();
64
+ const cloudId = await resolveCloudId(ctx.client);
65
+ const base = automationBase(host, ctx.config.baseUrl, cloudId);
66
+ const call = async (path, init = {}) => {
67
+ try {
68
+ return await ctx.client.request(`${base}${path}`, init);
69
+ } catch (error) {
70
+ throw explainAuthFailure(error);
71
+ }
72
+ };
73
+ return { ctx, cloudId, call };
74
+ };
75
+ var nextCursor = (next) => {
76
+ if (!next) return void 0;
77
+ const query = next.includes("?") ? next.slice(next.indexOf("?")) : next;
78
+ return new URLSearchParams(query).get("cursor") ?? void 0;
79
+ };
80
+ var projectAri = (cloudId, projectId) => `ari:cloud:jira:${cloudId}:project/${projectId}`;
81
+ var rulePayload = (raw, file) => {
82
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
83
+ throw exitError(1, `${file}: expected a JSON object holding a rule`);
84
+ return "rule" in raw ? raw : { rule: raw };
85
+ };
86
+ var readRuleFile = (file) => {
87
+ const text = file === "-" ? readFileSync(0, "utf8") : readFileSync(file, "utf8");
88
+ let parsed;
89
+ try {
90
+ parsed = JSON.parse(text);
91
+ } catch (error) {
92
+ throw exitError(
93
+ 1,
94
+ `${file}: not valid JSON \u2014 ${error instanceof Error ? error.message : String(error)}`
95
+ );
96
+ }
97
+ return rulePayload(parsed, file);
98
+ };
99
+ var STATES = /* @__PURE__ */ new Set(["ENABLED", "DISABLED"]);
100
+ var hostOption = (command) => command.option(
101
+ "--host <site|api>",
102
+ "where to reach the Automation API: the site gateway, or api.atlassian.com (env: ATLASSIAN_AUTOMATION_HOST)"
103
+ );
104
+ var setState = (automationCommand, name, state) => {
105
+ hostOption(
106
+ automationCommand.command(`${name} <uuid>`).description(`${name} a rule`)
107
+ ).action(async (uuid, options) => {
108
+ const { call } = await automation(options.host);
109
+ await call(`/rule/${encodeURIComponent(uuid)}/state`, {
110
+ method: "PUT",
111
+ body: JSON.stringify({ value: state })
112
+ });
113
+ process.stderr.write(`${name}d ${uuid}
114
+ `);
115
+ });
116
+ };
117
+ var registerAutomationCommands = (program2) => {
118
+ const automationCommand = program2.command("automation").description("list, read, create and switch Jira Automation rules").addHelpText(
119
+ "after",
120
+ `
121
+ Needs the Jira administrator global permission on the account behind
122
+ ATLASSIAN_API_TOKEN (a classic API token). Project admin is not enough.
123
+
124
+ Examples:
125
+ jira automation list --project SHOP
126
+ jira automation get 0192e5ac-0e25-71de-ba7b-d972e6a2049a > rule.json
127
+ jira automation update 0192e5ac-0e25-71de-ba7b-d972e6a2049a --file rule.json
128
+ jira automation disable 0192e5ac-0e25-71de-ba7b-d972e6a2049a
129
+ `
130
+ );
131
+ hostOption(
132
+ automationCommand.command("list").description("list rules, optionally only those scoped to a project").option("-p, --project <key>", "only rules scoped to this project").option("--state <state>", "ENABLED or DISABLED").option("-n, --limit <n>", "maximum rules to return", "100").option("--json", "emit JSON")
133
+ ).action(
134
+ async (options) => {
135
+ const limit = Number(options.limit);
136
+ if (!Number.isInteger(limit) || limit < 1)
137
+ throw exitError(1, `--limit must be a positive whole number`);
138
+ const state = options.state?.toUpperCase();
139
+ if (state && !STATES.has(state))
140
+ throw exitError(1, `--state must be ENABLED or DISABLED`);
141
+ const { ctx, cloudId, call } = await automation(options.host);
142
+ let scope;
143
+ if (options.project) {
144
+ const project = await ctx.client.request(
145
+ `/rest/api/3/project/${encodeURIComponent(options.project)}`
146
+ );
147
+ scope = projectAri(cloudId, project.id);
148
+ }
149
+ const rules = [];
150
+ let cursor;
151
+ do {
152
+ const page = await call("/rule/summary", {
153
+ method: "POST",
154
+ body: JSON.stringify({
155
+ limit: Math.min(100, limit - rules.length),
156
+ ...scope ? { scope } : {},
157
+ ...state ? { state } : {},
158
+ ...cursor ? { cursor } : {}
159
+ })
160
+ });
161
+ rules.push(...page?.data ?? []);
162
+ cursor = nextCursor(page?.links?.next);
163
+ } while (cursor && rules.length < limit);
164
+ if (options.json) {
165
+ printJson(rules);
166
+ warnIfTruncated(rules.length, limit, { exitCode: true });
167
+ return;
168
+ }
169
+ if (rules.length === 0) {
170
+ process.stderr.write("no rules match\n");
171
+ return;
172
+ }
173
+ process.stdout.write(
174
+ `${table(rules, [
175
+ { header: "UUID", value: (r) => r.uuid },
176
+ { header: "STATE", value: (r) => r.state },
177
+ { header: "NAME", value: (r) => r.name }
178
+ ])}
179
+ `
180
+ );
181
+ warnIfTruncated(rules.length, limit, { exitCode: false });
182
+ }
183
+ );
184
+ hostOption(
185
+ automationCommand.command("get <uuid>").description("print a rule's full configuration as JSON").option(
186
+ "--redact",
187
+ "redact sensitive fields such as secrets in web requests"
188
+ )
189
+ ).action(async (uuid, options) => {
190
+ const { call } = await automation(options.host);
191
+ const query = options.redact ? "?redactSensitiveFields=true" : "";
192
+ printJson(await call(`/rule/${encodeURIComponent(uuid)}${query}`));
193
+ });
194
+ hostOption(
195
+ automationCommand.command("create").description("create a rule from a JSON file (the shape `get` prints)").requiredOption("-f, --file <path>", "rule JSON, or - for stdin")
196
+ ).action(async (options) => {
197
+ const body = readRuleFile(options.file);
198
+ const { call } = await automation(options.host);
199
+ const created = await call("/rule", {
200
+ method: "POST",
201
+ body: JSON.stringify(body)
202
+ });
203
+ process.stdout.write(`${created?.ruleUuid ?? ""}
204
+ `);
205
+ });
206
+ hostOption(
207
+ automationCommand.command("update <uuid>").description(
208
+ "replace a rule with the JSON in a file (the shape `get` prints)"
209
+ ).requiredOption("-f, --file <path>", "rule JSON, or - for stdin")
210
+ ).action(async (uuid, options) => {
211
+ const body = readRuleFile(options.file);
212
+ const { call } = await automation(options.host);
213
+ await call(`/rule/${encodeURIComponent(uuid)}`, {
214
+ method: "PUT",
215
+ body: JSON.stringify(body)
216
+ });
217
+ process.stderr.write(`updated ${uuid}
218
+ `);
219
+ });
220
+ setState(automationCommand, "enable", "ENABLED");
221
+ setState(automationCommand, "disable", "DISABLED");
222
+ };
18
223
 
19
224
  // src/commands/attachment.ts
20
225
  import { writeFileSync } from "fs";
@@ -267,11 +472,11 @@ var registerBacklogCommand = (program2) => {
267
472
 
268
473
  // src/commands/issue.ts
269
474
  import { execFile } from "child_process";
270
- import { adfToMarkdown as adfToMarkdown2, locateAttachments as locateAttachments2 } from "@kud/jira";
475
+ import { adfToMarkdown as adfToMarkdown2, flattenIssueLinks as flattenIssueLinks2, locateAttachments as locateAttachments2 } from "@kud/jira";
271
476
 
272
477
  // src/commands/issue-write.ts
273
- import { readFileSync } from "fs";
274
- import { adfToMarkdown, markdownToAdf } from "@kud/jira";
478
+ import { readFileSync as readFileSync2 } from "fs";
479
+ import { adfToMarkdown, flattenIssueLinks, markdownToAdf } from "@kud/jira";
275
480
 
276
481
  // src/commands/confirm.ts
277
482
  import { createInterface } from "readline/promises";
@@ -300,23 +505,62 @@ var rankPosition = (options) => {
300
505
  if (before) return { before };
301
506
  return { after };
302
507
  };
303
- var readBody = (value) => value === "-" ? readFileSync(0, "utf8") : value;
508
+ var readBody = (value) => value === "-" ? readFileSync2(0, "utf8") : value;
509
+ var projectOf = (issueKey) => issueKey.split("-")[0];
510
+ var collectLink = (value, prior) => [
511
+ ...prior,
512
+ value
513
+ ];
514
+ var messageOf = (e) => e instanceof Error ? e.message : String(e);
515
+ var linkTypes = (ctx) => ctx.client.getIssueLinkTypes().then(({ issueLinkTypes }) => issueLinkTypes);
516
+ var parseLinkSpecs = (link, types) => {
517
+ if (!link?.length) return [];
518
+ const titles = types.map((t) => t.name);
519
+ return link.map((spec) => {
520
+ const colon = spec.indexOf(":");
521
+ const type = colon === -1 ? void 0 : spec.slice(0, colon);
522
+ const key = colon === -1 ? void 0 : spec.slice(colon + 1);
523
+ if (!type || !key)
524
+ throw exitError(
525
+ 1,
526
+ `malformed --link '${spec}' \u2014 expected <type>:<KEY>, e.g. Relates:ABC-2`
527
+ );
528
+ const resolved = types.find(
529
+ (t) => t.name.toLowerCase() === type.toLowerCase()
530
+ );
531
+ if (!resolved)
532
+ throw exitError(
533
+ 1,
534
+ `no link type '${type}'. Valid: ${titles.join(", ")}`
535
+ );
536
+ return { type: resolved.name, key };
537
+ });
538
+ };
304
539
  var resolveAccountId = async (who, projectKey) => {
305
540
  if (who === "none" || who === "unassigned") return null;
306
541
  if (who === "me") return (await context().client.getMe()).accountId;
307
542
  if (/^[0-9a-f]{24}$|:/.test(who)) return who;
308
543
  const ctx = context();
309
- const candidates = projectKey ? await ctx.client.searchAssignableUsers(who, projectKey) : await ctx.client.searchUsers(who);
544
+ const assignable = projectKey ? await ctx.client.searchAssignableUsers(who, projectKey) : [];
545
+ const candidates = assignable.length > 0 ? assignable : await ctx.client.searchUsers(who);
310
546
  if (candidates.length === 0) throw exitError(1, `no user matching '${who}'`);
311
- if (candidates.length > 1)
312
- throw exitError(
313
- 1,
314
- `'${who}' matches ${candidates.length} people: ${candidates.map((u) => `${u.displayName} (${u.accountId})`).join(", ")}`
315
- );
547
+ if (candidates.length > 1) {
548
+ for (const u of candidates)
549
+ process.stderr.write(
550
+ `${u.displayName}${u.emailAddress ? ` ${u.emailAddress}` : ""} ${u.accountId}
551
+ `
552
+ );
553
+ throw exitError(1, `'${who}' matches ${candidates.length} people`);
554
+ }
316
555
  return candidates[0].accountId;
317
556
  };
318
557
  var registerIssueWriteCommands = (issue) => {
319
- issue.command("create").description("create an issue").requiredOption("-p, --project <key>", "project key").requiredOption("-t, --type <type>", "issue type, e.g. Task").requiredOption("-s, --summary <text>", "summary").option("-b, --body <text>", "description; '-' reads stdin").option("-a, --assignee <who>", "assignee, or 'me'").option("-l, --label <label...>", "labels").option("--priority <name>", "priority name").option("--json", "emit JSON").action(
558
+ issue.command("create").description("create an issue").requiredOption("-p, --project <key>", "project key").requiredOption("-t, --type <type>", "issue type, e.g. Task").requiredOption("-s, --summary <text>", "summary").option("-b, --body <text>", "description; '-' reads stdin").option("-a, --assignee <who>", "assignee, or 'me'").option("-l, --label <label...>", "labels").option("--priority <name>", "priority name").option("--parent <key>", "parent issue key").option(
559
+ "--link <type:key>",
560
+ "link the new issue to another, repeatable, e.g. Relates:ABC-2",
561
+ collectLink,
562
+ []
563
+ ).option("--json", "emit JSON").action(
320
564
  async (options) => {
321
565
  const ctx = context();
322
566
  const fields = {
@@ -328,6 +572,7 @@ var registerIssueWriteCommands = (issue) => {
328
572
  fields["description"] = markdownToAdf(readBody(options.body));
329
573
  if (options.label) fields["labels"] = options.label;
330
574
  if (options.priority) fields["priority"] = { name: options.priority };
575
+ if (options.parent) fields["parent"] = { key: options.parent };
331
576
  if (options.assignee)
332
577
  fields["assignee"] = {
333
578
  accountId: await resolveAccountId(
@@ -335,13 +580,26 @@ var registerIssueWriteCommands = (issue) => {
335
580
  options.project
336
581
  )
337
582
  };
583
+ const links = options.link?.length ? parseLinkSpecs(options.link, await linkTypes(ctx)) : [];
338
584
  const created = await ctx.client.createIssue(fields);
339
- if (options.json) return printJson(created);
340
- process.stdout.write(`${created.key}
585
+ if (options.json) printJson(created);
586
+ else process.stdout.write(`${created.key}
341
587
  `);
588
+ for (const link2 of links) {
589
+ try {
590
+ await ctx.client.linkIssues(link2.type, created.key, link2.key);
591
+ } catch (e) {
592
+ throw exitError(
593
+ 1,
594
+ `created ${created.key}, but the ${link2.type} link to ${link2.key} failed: ${messageOf(e)}`
595
+ );
596
+ }
597
+ process.stderr.write(`linked ${created.key} ${link2.type} ${link2.key}
598
+ `);
599
+ }
342
600
  }
343
601
  );
344
- issue.command("edit <key>").description("change an issue's fields").option("-s, --summary <text>", "new summary").option("-b, --body <text>", "new description; '-' reads stdin").option("-l, --label <label...>", "replace labels").option("--priority <name>", "priority name").action(
602
+ issue.command("edit <key>").description("change an issue's fields").option("-s, --summary <text>", "new summary").option("-b, --body <text>", "new description; '-' reads stdin").option("-l, --label <label...>", "replace labels").option("--priority <name>", "priority name").option("--parent <key>", "parent issue key; 'none' clears it").option("-a, --assignee <who>", "assignee; 'me' or 'none' both work").action(
345
603
  async (key, options) => {
346
604
  const fields = {};
347
605
  if (options.summary) fields["summary"] = options.summary;
@@ -349,6 +607,15 @@ var registerIssueWriteCommands = (issue) => {
349
607
  fields["description"] = markdownToAdf(readBody(options.body));
350
608
  if (options.label) fields["labels"] = options.label;
351
609
  if (options.priority) fields["priority"] = { name: options.priority };
610
+ if (options.parent !== void 0)
611
+ fields["parent"] = options.parent === "none" ? null : { key: options.parent };
612
+ if (options.assignee) {
613
+ const accountId = await resolveAccountId(
614
+ options.assignee,
615
+ projectOf(key)
616
+ );
617
+ fields["assignee"] = accountId ? { accountId } : null;
618
+ }
352
619
  if (Object.keys(fields).length === 0)
353
620
  throw exitError(2, "nothing to change \u2014 pass at least one option");
354
621
  await context().client.updateIssue(key, fields);
@@ -362,8 +629,8 @@ var registerIssueWriteCommands = (issue) => {
362
629
  process.stderr.write(`deleted ${key}
363
630
  `);
364
631
  });
365
- issue.command("assign <key> <who>").description("assign an issue; 'me' or 'none' both work").action(async (key, who) => {
366
- const accountId = await resolveAccountId(who);
632
+ issue.command("assign <key> <who>").description("assign an issue; 'me', a name, or 'none' all work").action(async (key, who) => {
633
+ const accountId = await resolveAccountId(who, projectOf(key));
367
634
  await context().client.assignIssue(key, accountId);
368
635
  process.stderr.write(`${key} assigned to ${accountId ? who : "nobody"}
369
636
  `);
@@ -532,9 +799,31 @@ var registerIssueWriteCommands = (issue) => {
532
799
  );
533
800
  }
534
801
  );
535
- issue.command("link <inward> <type> <outward>").description("link two issues, e.g. ABC-1 Blocks ABC-2").action(async (inward, type, outward) => {
802
+ const link = issue.command("link").description("link two issues, e.g. jira issue link ABC-1 Blocks ABC-2");
803
+ link.command("list <key>").alias("ls").description("links on an issue").option("--json", "emit JSON").action(async (key, options) => {
804
+ const ctx = context();
805
+ const found = await ctx.client.getIssue(key);
806
+ const links = flattenIssueLinks(found);
807
+ if (options.json) return printJson(links);
808
+ if (links.length === 0) {
809
+ process.stderr.write(`${key} has no links
810
+ `);
811
+ return;
812
+ }
813
+ process.stdout.write(
814
+ `${table(links, [
815
+ { header: "DIR", value: (l) => l.direction },
816
+ { header: "TYPE", value: (l) => l.type },
817
+ { header: "KEY", value: (l) => l.key },
818
+ { header: "STATUS", value: (l) => l.status },
819
+ { header: "SUMMARY", value: (l) => truncate(l.summary, 40) }
820
+ ])}
821
+ `
822
+ );
823
+ });
824
+ link.argument("<inward>").argument("<type>").argument("<outward>").action(async (inward, type, outward) => {
536
825
  await context().client.linkIssues(type, inward, outward);
537
- process.stderr.write(`${inward} ${type} ${outward}
826
+ process.stderr.write(`linked ${inward} ${type} ${outward}
538
827
  `);
539
828
  });
540
829
  issue.command("history <key>").description("what changed on an issue and when").option("--json", "emit JSON").action(async (key, options) => {
@@ -591,30 +880,71 @@ var registerIssueCommands = (program2) => {
591
880
  `);
592
881
  warnIfTruncated(issues.length, limit, { exitCode: false });
593
882
  });
594
- issue.command("view <key>").description("show one issue").option("--json", "emit JSON").option("--comments", "include comments").action(
883
+ issue.command("view <key>").description("show one issue").option("--json", "emit JSON").option("--comments", "include comments").option(
884
+ "--fields <list>",
885
+ "restrict the output to these fields, comma-separated"
886
+ ).action(
595
887
  async (key, options) => {
596
888
  const ctx = context();
597
889
  const found = await ctx.client.getIssue(key);
598
- if (options.json) return printJson(found);
890
+ const fields = options.fields?.split(",").map((f2) => f2.trim().toLowerCase()).filter(Boolean);
891
+ const show = (field) => !fields || fields.includes(field.toLowerCase());
892
+ if (options.json) {
893
+ const chosen = fields ? Object.fromEntries(
894
+ Object.entries(found.fields).filter(
895
+ ([k]) => fields.includes(k.toLowerCase())
896
+ )
897
+ ) : { ...found.fields };
898
+ if (show("issuelinks")) chosen["issuelinks"] = flattenIssueLinks2(found);
899
+ if (show("subtasks"))
900
+ chosen["subtasks"] = found.fields.subtasks?.map((s) => ({
901
+ key: s.key,
902
+ summary: s.fields.summary,
903
+ status: s.fields.status.name
904
+ }));
905
+ return printJson({ ...found, fields: chosen });
906
+ }
599
907
  const { bold, dim } = ctx.out;
600
908
  const f = found.fields;
601
909
  const lines = [
602
910
  `${bold(found.key)} ${f.summary ?? ""}`,
603
911
  "",
604
- ...f.parent ? [
912
+ ...show("parent") && f.parent ? [
605
913
  `${dim("parent")} ${f.parent.key} ${truncate(f.parent.fields?.summary ?? "", 60)}`
606
914
  ] : [],
607
- `${dim("status")} ${f.status?.name ?? "\u2014"}`,
608
- `${dim("type")} ${f.issuetype?.name ?? "\u2014"}`,
609
- `${dim("assignee")} ${f.assignee?.displayName ?? "unassigned"}`,
610
- `${dim("reporter")} ${f.reporter?.displayName ?? "\u2014"}`,
611
- ...f.labels?.length ? [`${dim("labels")} ${f.labels.join(", ")}`] : [],
612
- ...ctx.client.customFields.filter((cf) => f[cf.id] != null).map((cf) => `${dim(cf.label.padEnd(9))} ${formatField(f[cf.id])}`),
613
- `${dim("url")} ${issueUrl(ctx, found.key)}`
915
+ ...show("status") ? [`${dim("status")} ${f.status?.name ?? "\u2014"}`] : [],
916
+ ...show("issuetype") ? [`${dim("type")} ${f.issuetype?.name ?? "\u2014"}`] : [],
917
+ ...show("assignee") ? [`${dim("assignee")} ${f.assignee?.displayName ?? "unassigned"}`] : [],
918
+ ...show("reporter") ? [`${dim("reporter")} ${f.reporter?.displayName ?? "\u2014"}`] : [],
919
+ ...show("labels") && f.labels?.length ? [`${dim("labels")} ${f.labels.join(", ")}`] : [],
920
+ ...ctx.client.customFields.filter((cf) => f[cf.id] != null && show(cf.id)).map((cf) => `${dim(cf.label.padEnd(9))} ${formatField(f[cf.id])}`),
921
+ ...fields ? [] : [`${dim("url")} ${issueUrl(ctx, found.key)}`]
614
922
  ];
923
+ const links = flattenIssueLinks2(found);
924
+ if (show("issuelinks") && links.length > 0) {
925
+ lines.push(
926
+ "",
927
+ dim("\u2500\u2500\u2500 links \u2500\u2500\u2500"),
928
+ "",
929
+ ...links.map(
930
+ (l) => `${l.direction.padEnd(7)} ${l.type.padEnd(12)} ${l.key} ${dim(l.status.padEnd(12))} ${truncate(l.summary, 60)}`
931
+ )
932
+ );
933
+ }
934
+ const subtasks = f.subtasks;
935
+ if (show("subtasks") && subtasks?.length) {
936
+ lines.push(
937
+ "",
938
+ dim("\u2500\u2500\u2500 subtasks \u2500\u2500\u2500"),
939
+ "",
940
+ ...subtasks.map(
941
+ (s) => `${s.key} ${dim(s.fields.status.name.padEnd(12))} ${truncate(s.fields.summary, 60)}`
942
+ )
943
+ );
944
+ }
615
945
  const attachments = locateAttachments2(found);
616
946
  const filenameOf = (id) => attachments.find((a) => a.id === id)?.filename;
617
- if (attachments.length > 0) {
947
+ if (!fields && attachments.length > 0) {
618
948
  lines.push(
619
949
  "",
620
950
  dim("\u2500\u2500\u2500 attachments \u2500\u2500\u2500"),
@@ -627,9 +957,9 @@ var registerIssueCommands = (program2) => {
627
957
  );
628
958
  }
629
959
  const description = adfToMarkdown2(f.description, filenameOf);
630
- if (description)
960
+ if (show("description") && description)
631
961
  lines.push("", dim("\u2500\u2500\u2500 description \u2500\u2500\u2500"), "", description);
632
- if (options.comments && f.comment?.comments?.length) {
962
+ if (options.comments && show("comment") && f.comment?.comments?.length) {
633
963
  lines.push("", dim("\u2500\u2500\u2500 comments \u2500\u2500\u2500"));
634
964
  for (const c of f.comment.comments) {
635
965
  lines.push(
@@ -652,21 +982,40 @@ var registerIssueCommands = (program2) => {
652
982
  process.stdout.write(
653
983
  `${table(transitions, [
654
984
  { header: "ID", value: (t) => t.id },
655
- { header: "NAME", value: (t) => t.name },
656
- { header: "TO", value: (t) => t.to?.name ?? "\u2014" }
985
+ { header: "NAME \u2192 TO", value: (t) => `${t.name} \u2192 ${t.to?.name ?? "\u2014"}` }
657
986
  ])}
658
987
  `
659
988
  );
989
+ process.stderr.write(TRANSITION_HINT + "\n");
660
990
  return;
661
991
  }
662
992
  const wanted = status.toLowerCase();
663
- const match = transitions.find(
993
+ const byName = transitions.filter(
664
994
  (t) => t.name.toLowerCase() === wanted || t.id === status
665
995
  );
996
+ const byTarget = transitions.filter(
997
+ (t) => t.to?.name.toLowerCase() === wanted
998
+ );
999
+ const match = byName.length > 0 ? byName.length === 1 ? byName[0] : void 0 : byTarget.length === 1 ? byTarget[0] : void 0;
1000
+ if (byName.length > 1) {
1001
+ throw exitError(
1002
+ 1,
1003
+ `'${status}' matches ${byName.length} transitions on ${key}: ${byName.map((t) => `${t.name} \u2192 ${t.to?.name ?? "\u2014"}`).join("; ")}`
1004
+ );
1005
+ }
1006
+ if (byName.length === 0 && byTarget.length > 1) {
1007
+ throw exitError(
1008
+ 1,
1009
+ `${byTarget.length} transitions reach '${status}' on ${key}: ${byTarget.map((t) => `${t.name} \u2192 ${t.to?.name ?? "\u2014"}`).join("; ")}
1010
+ Use a transition name instead`
1011
+ );
1012
+ }
666
1013
  if (!match) {
667
1014
  throw exitError(
668
1015
  1,
669
- `no transition '${status}' on ${key}. Available: ${transitions.map((t) => t.name).join(", ")}`
1016
+ `no transition or status '${status}' on ${key}. Available:
1017
+ ${transitions.map((t) => ` ${t.name} \u2192 ${t.to?.name ?? "\u2014"}`).join("\n")}
1018
+ ${TRANSITION_HINT}`
670
1019
  );
671
1020
  }
672
1021
  await ctx.client.transitionIssue(
@@ -692,6 +1041,7 @@ var registerIssueCommands = (program2) => {
692
1041
  });
693
1042
  };
694
1043
  var issueUrl = (ctx, key) => `${ctx.config.baseUrl.replace(/\/$/, "")}/browse/${key}`;
1044
+ var TRANSITION_HINT = "the argument may be either the transition name or its target status";
695
1045
  var formatField = (value) => {
696
1046
  if (value == null) return "\u2014";
697
1047
  if (typeof value === "object") {
@@ -958,7 +1308,8 @@ var registerApiCommand = (program2) => {
958
1308
  method,
959
1309
  ...options.data ? { body: options.data } : {}
960
1310
  });
961
- printJson(result ?? null);
1311
+ if (result == null) return;
1312
+ printJson(result);
962
1313
  }
963
1314
  );
964
1315
  };
@@ -1015,6 +1366,7 @@ Examples:
1015
1366
  jira attachment list ABC-123
1016
1367
  jira attachment read ABC-123 error.log | grep -i timeout
1017
1368
  jira search 'project = ABC AND created >= -7d' --json | jq '.[].key'
1369
+ jira automation list --project ABC
1018
1370
  `
1019
1371
  );
1020
1372
  registerIssueCommands(program);
@@ -1030,10 +1382,11 @@ registerEpicCommands(program);
1030
1382
  registerUserCommands(program);
1031
1383
  registerMetaCommands(program);
1032
1384
  registerCountCommand(program);
1385
+ registerAutomationCommands(program);
1033
1386
  registerApiCommand(program);
1034
1387
  var exitCodeFor = (error) => {
1035
1388
  if (isExitError(error)) return error.code;
1036
- if (isJiraApiError(error))
1389
+ if (isJiraApiError2(error))
1037
1390
  return error.status === 401 || error.status === 403 ? 4 : 1;
1038
1391
  return 1;
1039
1392
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kud/jira-cli",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "type": "module",
5
5
  "description": "Jira on the command line — read issues, comments and attachments as plain text",
6
6
  "keywords": [
@@ -38,7 +38,7 @@
38
38
  },
39
39
  "dependencies": {
40
40
  "@kud/ink-ui": "0.32.0",
41
- "@kud/jira": "0.5.0",
41
+ "@kud/jira": "0.6.0",
42
42
  "@kud/jira-ink": "0.11.0",
43
43
  "commander": "14.0.1",
44
44
  "ink": "7.1.1",