@kud/jira-cli 0.11.0 → 0.13.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 +28 -1
  2. package/dist/index.js +448 -63
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -88,15 +88,18 @@ jira issue open ABC-123
88
88
  Writing:
89
89
 
90
90
  ```sh
91
- jira issue create -p ABC -t Task -s 'Fix the thing' -b 'Longer **markdown** body'
91
+ jira issue create -p ABC -t Task -s 'Fix the thing' -b 'Longer **markdown** body' --status 'In Progress'
92
92
  jira issue create -p ABC -t Task -s 'A sub-task' --parent ABC-100 --link Relates:ABC-99
93
93
  jira issue edit ABC-123 --summary 'Better title' --assignee me --parent ABC-100
94
+ jira issue edit ABC-123 --prepend-description '**Update:** finished QA'
94
95
  jira issue assign ABC-123 me # or a name, an email, an account id, or 'none'
95
96
  jira issue comment add ABC-123 - # body from stdin
96
97
  jira issue comment list ABC-123
98
+ jira issue comment list ABC-123 --last 5 # the 5 most recent, oldest first
97
99
  jira issue comment edit ABC-123 12345 'Actually fixed in 2.1'
98
100
  jira issue delete ABC-123 # asks first; --yes to confirm in scripts
99
101
  jira issue rank ABC-1 ABC-2 --before ABC-3
102
+ jira issue rank ABC-1 ABC-2 --top --jql 'project = ABC AND sprint = 42'
100
103
  jira issue link ABC-1 Blocks ABC-2
101
104
  jira issue link list ABC-1
102
105
  jira issue watch add ABC-123
@@ -115,8 +118,14 @@ People are resolved for you. `issue assign`, and `--assignee` on `create` and `e
115
118
 
116
119
  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
120
 
121
+ `create --status 'In Progress'` moves the new issue to that status right after creation and any links. If the fresh issue already sits in that status nothing is sent, and if the move fails the key and the reason are reported with a non-zero exit, as with links.
122
+
123
+ `edit --prepend-description` and `--append-description` splice markdown onto the start or end of an existing description without touching it: the current ADF nodes are preserved and the converted markdown is added around them. Both may be combined; with `--body` neither is allowed. Like `-b`, a value of `-` reads stdin.
124
+
118
125
  `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
126
 
127
+ `issue rank --top --jql <jql>` ranks the keys above the first issue of the JQL scope. The JQL must order by rank (`ORDER BY Rank ASC` is appended when missing, and a JQL ordered any other way is refused, since its first result would not be the top). When the keys already occupy the top in rank order nothing is sent.
128
+
120
129
  Bodies accept Markdown — paragraphs, headings, lists, fenced code, links and code spans are converted to ADF.
121
130
 
122
131
  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.
@@ -130,6 +139,9 @@ jira project components ABC
130
139
  jira project statuses ABC
131
140
 
132
141
  jira board list
142
+ jira board list --project ABC
143
+ jira board view 42 # columns, their statuses, and the board's filter
144
+ jira board view 42 --json
133
145
  jira board issues 42
134
146
  jira board backlog 42
135
147
  jira board epics 42
@@ -205,6 +217,21 @@ jira fields points
205
217
 
206
218
  Named fields are requested on every search and shown in `issue view`.
207
219
 
220
+ ## Automation rules
221
+
222
+ ```sh
223
+ jira automation list --project SHOP # --state ENABLED|DISABLED, --limit, --json
224
+ jira automation get 0192e5ac-0e25-71de-ba7b-d972e6a2049a > rule.json
225
+ jira automation update 0192e5ac-0e25-71de-ba7b-d972e6a2049a --file rule.json
226
+ jira automation create --file rule.json # prints the new rule's UUID; - reads stdin
227
+ jira automation disable 0192e5ac-0e25-71de-ba7b-d972e6a2049a
228
+ jira automation enable 0192e5ac-0e25-71de-ba7b-d972e6a2049a
229
+ ```
230
+
231
+ 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.
232
+
233
+ `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.
234
+
208
235
  ## Escape hatch
209
236
 
210
237
  Anything not covered:
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 isJiraApiError3 } 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";
@@ -139,6 +344,7 @@ var registerAttachmentCommands = (program2) => {
139
344
  };
140
345
 
141
346
  // src/commands/agile.ts
347
+ import { isJiraApiError as isJiraApiError2 } from "@kud/jira";
142
348
  var issueRows = [
143
349
  { header: "KEY", value: (i) => i.key },
144
350
  { header: "STATUS", value: (i) => i.fields.status?.name ?? "\u2014" },
@@ -157,18 +363,73 @@ var writeIssues = (issues, json) => {
157
363
  process.stdout.write(`${table(issues, issueRows)}
158
364
  `);
159
365
  };
366
+ var listProjectBoards = async (request, project) => {
367
+ const base = `/rest/agile/1.0/board?projectKeyOrId=${encodeURIComponent(project)}`;
368
+ const boards = [];
369
+ let path = base;
370
+ while (path) {
371
+ const page = await request(path);
372
+ const pageBoards = page.values ?? [];
373
+ boards.push(...pageBoards);
374
+ const startAt = (page.startAt ?? 0) + pageBoards.length;
375
+ path = page.isLast !== false || pageBoards.length === 0 ? "" : `${base}&startAt=${startAt}`;
376
+ }
377
+ return boards;
378
+ };
160
379
  var registerBoardCommands = (program2) => {
161
380
  const board = program2.command("board").description("boards, backlogs and epics");
162
- board.command("list").alias("ls").description("list boards").option("--json", "emit JSON").action(async (options) => {
381
+ board.command("list").alias("ls").description("list boards").option("--json", "emit JSON").option("--project <key>", "filter boards by project key").action(async (options) => {
163
382
  const ctx = context();
164
- const { values } = await ctx.client.getBoards();
165
- if (options.json) return printJson(values);
383
+ const boards = options.project ? await listProjectBoards(ctx.client.request, options.project) : (await ctx.client.getBoards()).values;
384
+ if (options.json) return printJson(boards);
166
385
  process.stdout.write(
167
- `${table(values, [
386
+ `${table(boards, [
168
387
  { header: "ID", value: (b) => String(b.id) },
169
388
  { header: "NAME", value: (b) => b.name },
170
389
  { header: "TYPE", value: (b) => b.type ?? "\u2014" }
171
390
  ])}
391
+ `
392
+ );
393
+ });
394
+ board.command("view <id>").description("show a board's configuration and filter").option("--json", "emit JSON").action(async (id, options) => {
395
+ const ctx = context();
396
+ const config = await ctx.client.getBoardConfiguration(
397
+ Number(id)
398
+ );
399
+ let filter = null;
400
+ let unavailable = !config.filter?.id;
401
+ if (config.filter?.id) {
402
+ try {
403
+ filter = await ctx.client.request(
404
+ `/rest/api/3/filter/${config.filter.id}`
405
+ );
406
+ } catch (e) {
407
+ if (isJiraApiError2(e) && (e.status === 403 || e.status === 404))
408
+ unavailable = true;
409
+ else throw e;
410
+ }
411
+ }
412
+ const statuses = await ctx.client.getStatuses();
413
+ const statusMap = new Map(statuses.map((s) => [s.id, s.name]));
414
+ if (options.json) {
415
+ return printJson({
416
+ ...config,
417
+ filter: filter ? { ...config.filter, ...filter } : { ...config.filter, unavailable: true }
418
+ });
419
+ }
420
+ const { dim } = ctx.out;
421
+ const columns = config.columnConfig?.columns ?? [];
422
+ const columnLines = columns.map((col) => {
423
+ const statusNames = col.statuses.map((s) => statusMap.get(s.id) ?? s.id).join(", ");
424
+ return `${dim("column")} ${col.name} ${dim(statusNames)}`;
425
+ });
426
+ process.stdout.write(
427
+ `${[
428
+ config.name,
429
+ `${dim("type")} ${config.type ?? "\u2014"}`,
430
+ `${dim("filter")} ${filter ? `${filter.name} ${dim(filter.jql ?? "")}` : unavailable ? "unavailable" : "\u2014"}`,
431
+ ...columnLines
432
+ ].join("\n")}
172
433
  `
173
434
  );
174
435
  });
@@ -270,8 +531,12 @@ import { execFile } from "child_process";
270
531
  import { adfToMarkdown as adfToMarkdown2, flattenIssueLinks as flattenIssueLinks2, locateAttachments as locateAttachments2 } from "@kud/jira";
271
532
 
272
533
  // src/commands/issue-write.ts
273
- import { readFileSync } from "fs";
274
- import { adfToMarkdown, flattenIssueLinks, markdownToAdf } from "@kud/jira";
534
+ import { readFileSync as readFileSync2 } from "fs";
535
+ import {
536
+ adfToMarkdown,
537
+ flattenIssueLinks,
538
+ markdownToAdf
539
+ } from "@kud/jira";
275
540
 
276
541
  // src/commands/confirm.ts
277
542
  import { createInterface } from "readline/promises";
@@ -293,15 +558,59 @@ var confirmDestructive = async (what, options) => {
293
558
 
294
559
  // src/commands/issue-write.ts
295
560
  var rankPosition = (options) => {
296
- const { before, after } = options;
561
+ const { before, after, top, jql } = options;
562
+ if (top) {
563
+ if (!jql) throw exitError(1, "--top requires --jql");
564
+ if (before || after)
565
+ throw exitError(1, "--top is mutually exclusive with --before and --after");
566
+ return { top: true, jql };
567
+ }
568
+ if (jql)
569
+ throw exitError(
570
+ 1,
571
+ "--jql needs --top; use --before or --after to rank against an issue"
572
+ );
297
573
  if (before && after) throw exitError(1, "pass --before or --after, not both");
298
574
  if (!before && !after)
299
575
  throw exitError(1, "pass one of --before <key> or --after <key>");
300
576
  if (before) return { before };
301
577
  return { after };
302
578
  };
303
- var readBody = (value) => value === "-" ? readFileSync(0, "utf8") : value;
579
+ var readBody = (value) => value === "-" ? readFileSync2(0, "utf8") : value;
304
580
  var projectOf = (issueKey) => issueKey.split("-")[0];
581
+ var TRANSITION_HINT = "the argument may be either the transition name or its target status";
582
+ var resolveTransition = (transitions, key, status) => {
583
+ const wanted = status.toLowerCase();
584
+ const byName = transitions.filter(
585
+ (t) => t.name.toLowerCase() === wanted || t.id === status
586
+ );
587
+ const byTarget = transitions.filter(
588
+ (t) => t.to?.name.toLowerCase() === wanted
589
+ );
590
+ const match = byName.length > 0 ? byName.length === 1 ? byName[0] : void 0 : byTarget.length === 1 ? byTarget[0] : void 0;
591
+ if (byName.length > 1) {
592
+ throw exitError(
593
+ 1,
594
+ `'${status}' matches ${byName.length} transitions on ${key}: ${byName.map((t) => `${t.name} \u2192 ${t.to?.name ?? "\u2014"}`).join("; ")}`
595
+ );
596
+ }
597
+ if (byName.length === 0 && byTarget.length > 1) {
598
+ throw exitError(
599
+ 1,
600
+ `${byTarget.length} transitions reach '${status}' on ${key}: ${byTarget.map((t) => `${t.name} \u2192 ${t.to?.name ?? "\u2014"}`).join("; ")}
601
+ Use a transition name instead`
602
+ );
603
+ }
604
+ if (!match) {
605
+ throw exitError(
606
+ 1,
607
+ `no transition or status '${status}' on ${key}. Available:
608
+ ${transitions.map((t) => ` ${t.name} \u2192 ${t.to?.name ?? "\u2014"}`).join("\n")}
609
+ ${TRANSITION_HINT}`
610
+ );
611
+ }
612
+ return match;
613
+ };
305
614
  var collectLink = (value, prior) => [
306
615
  ...prior,
307
616
  value
@@ -355,7 +664,7 @@ var registerIssueWriteCommands = (issue) => {
355
664
  "link the new issue to another, repeatable, e.g. Relates:ABC-2",
356
665
  collectLink,
357
666
  []
358
- ).option("--json", "emit JSON").action(
667
+ ).option("--status <name>", "transition the new issue to this status after creation").option("--json", "emit JSON").action(
359
668
  async (options) => {
360
669
  const ctx = context();
361
670
  const fields = {
@@ -392,10 +701,51 @@ var registerIssueWriteCommands = (issue) => {
392
701
  process.stderr.write(`linked ${created.key} ${link2.type} ${link2.key}
393
702
  `);
394
703
  }
704
+ if (options.status) {
705
+ try {
706
+ const found = await ctx.client.getIssue(created.key);
707
+ const currentStatus = found.fields.status?.name;
708
+ if (currentStatus && currentStatus.toLowerCase() === options.status.toLowerCase()) {
709
+ process.stderr.write(
710
+ `${created.key} is already in '${currentStatus}', not moving
711
+ `
712
+ );
713
+ } else {
714
+ const { transitions } = await ctx.client.getTransitions(
715
+ created.key
716
+ );
717
+ const match = resolveTransition(
718
+ transitions,
719
+ created.key,
720
+ options.status
721
+ );
722
+ await ctx.client.transitionIssue(created.key, match.id);
723
+ process.stderr.write(
724
+ `moved ${created.key} to ${match.to?.name ?? match.name}
725
+ `
726
+ );
727
+ }
728
+ } catch (e) {
729
+ throw exitError(
730
+ 1,
731
+ `created ${created.key}, but moving it to ${options.status} failed: ${messageOf(e)}`
732
+ );
733
+ }
734
+ }
395
735
  }
396
736
  );
397
- 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(
737
+ 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("--prepend-description <md>", "prepend markdown to the description; '-' reads stdin").option("--append-description <md>", "append markdown to the 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(
398
738
  async (key, options) => {
739
+ if (options.body && (options.prependDescription || options.appendDescription))
740
+ throw exitError(
741
+ 2,
742
+ "--prepend-description and --append-description are mutually exclusive with --body"
743
+ );
744
+ if (options.prependDescription === "-" && options.appendDescription === "-")
745
+ throw exitError(
746
+ 2,
747
+ "--prepend-description and --append-description both read stdin; run two edits instead"
748
+ );
399
749
  const fields = {};
400
750
  if (options.summary) fields["summary"] = options.summary;
401
751
  if (options.body)
@@ -411,6 +761,22 @@ var registerIssueWriteCommands = (issue) => {
411
761
  );
412
762
  fields["assignee"] = accountId ? { accountId } : null;
413
763
  }
764
+ if (options.prependDescription || options.appendDescription) {
765
+ const ctx = context();
766
+ const issue2 = await ctx.client.getIssue(key);
767
+ const existingDescription = issue2.fields.description;
768
+ let existingContent = [];
769
+ if (existingDescription && typeof existingDescription === "object" && "content" in existingDescription) {
770
+ existingContent = existingDescription.content;
771
+ }
772
+ const prependContent = options.prependDescription ? markdownToAdf(readBody(options.prependDescription)).content : [];
773
+ const appendContent = options.appendDescription ? markdownToAdf(readBody(options.appendDescription)).content : [];
774
+ fields["description"] = {
775
+ type: "doc",
776
+ version: 1,
777
+ content: [...prependContent, ...existingContent, ...appendContent]
778
+ };
779
+ }
414
780
  if (Object.keys(fields).length === 0)
415
781
  throw exitError(2, "nothing to change \u2014 pass at least one option");
416
782
  await context().client.updateIssue(key, fields);
@@ -431,22 +797,39 @@ var registerIssueWriteCommands = (issue) => {
431
797
  `);
432
798
  });
433
799
  const comment = issue.command("comment").description("read and write comments");
434
- comment.command("list <key>").alias("ls").description("comments on an issue").option("--json", "emit JSON").action(async (key, options) => {
435
- const ctx = context();
436
- const { comments } = await ctx.client.getComments(key);
437
- if (options.json) return printJson(comments);
438
- process.stdout.write(
439
- `${comments.map(
440
- (c) => [
441
- `${ctx.out.bold(c.author?.displayName ?? "unknown")} ${ctx.out.dim(
442
- `${c.created?.slice(0, 10) ?? ""} ${c.id}`
443
- )}`,
444
- adfToMarkdown(c.body)
445
- ].join("\n")
446
- ).join("\n\n")}
800
+ comment.command("list <key>").alias("ls").description("comments on an issue").option("--json", "emit JSON").option("--last [n]", "show only the n most recent comments (default 1)").action(
801
+ async (key, options) => {
802
+ const ctx = context();
803
+ let lastN;
804
+ if (options.last !== void 0) {
805
+ const raw = options.last === true ? "1" : String(options.last);
806
+ if (!/^\d+$/.test(raw) || Number(raw) < 1)
807
+ throw exitError(2, "--last requires a positive integer");
808
+ lastN = Number(raw);
809
+ }
810
+ let comments;
811
+ if (lastN !== void 0) {
812
+ const response = await ctx.client.request(
813
+ `/rest/api/3/issue/${encodeURIComponent(key)}/comment?orderBy=-created&maxResults=${lastN}`
814
+ );
815
+ comments = response.comments.reverse();
816
+ } else {
817
+ comments = (await ctx.client.getComments(key)).comments;
818
+ }
819
+ if (options.json) return printJson(comments);
820
+ process.stdout.write(
821
+ `${comments.map(
822
+ (c) => [
823
+ `${ctx.out.bold(c.author?.displayName ?? "unknown")} ${ctx.out.dim(
824
+ `${c.created?.slice(0, 10) ?? ""} ${c.id}`
825
+ )}`,
826
+ adfToMarkdown(c.body)
827
+ ].join("\n")
828
+ ).join("\n\n")}
447
829
  `
448
- );
449
- });
830
+ );
831
+ }
832
+ );
450
833
  comment.command("add <key> <body>").description("comment on an issue; '-' reads stdin").action(async (key, body) => {
451
834
  await context().client.addComment(key, markdownToAdf(readBody(body)));
452
835
  process.stderr.write(`commented on ${key}
@@ -583,15 +966,44 @@ var registerIssueWriteCommands = (issue) => {
583
966
  process.stderr.write(`removed remote link ${linkId} from ${key}
584
967
  `);
585
968
  });
586
- issue.command("rank <keys...>").description("order issues before or after another issue").option("--before <key>", "place the issues before this one").option("--after <key>", "place the issues after this one").action(
969
+ issue.command("rank <keys...>").description("order issues before or after another issue, or at the top of a JQL scope").option("--before <key>", "place the issues before this one").option("--after <key>", "place the issues after this one").option("--top", "rank at the top of the JQL scope (requires --jql)").option("--jql <jql>", "JQL scope for --top").action(
587
970
  async (keys, options) => {
588
971
  const position = rankPosition(options);
589
- await context().client.rankIssues(keys, position);
590
- const anchor = "before" in position ? position.before : position.after;
591
- process.stderr.write(
592
- `ranked ${keys.join(", ")} ${"before" in position ? "before" : "after"} ${anchor}
972
+ if (!("top" in position)) {
973
+ await context().client.rankIssues(keys, position);
974
+ const anchor2 = "before" in position ? position.before : position.after;
975
+ process.stderr.write(
976
+ `ranked ${keys.join(", ")} ${"before" in position ? "before" : "after"} ${anchor2}
593
977
  `
594
- );
978
+ );
979
+ return;
980
+ }
981
+ const jql = position.jql.trim();
982
+ const orderByMatch = jql.match(/\bORDER\s+BY\s+(.+)$/i);
983
+ if (orderByMatch && !/^Rank(\s+ASC)?$/i.test(orderByMatch[1].trim()))
984
+ throw exitError(
985
+ 1,
986
+ `foreign ORDER BY is not supported with --top: '${orderByMatch[1].trim()}'. Remove it, or use ORDER BY Rank ASC`
987
+ );
988
+ position.jql = orderByMatch ? jql : `${jql} ORDER BY Rank ASC`;
989
+ const ctx = context();
990
+ const issues = await ctx.client.searchIssues(position.jql, {
991
+ limit: keys.length + 1
992
+ });
993
+ if (issues.length === 0)
994
+ throw exitError(1, `no issues match: ${position.jql}`);
995
+ const wanted = keys.map((k) => k.toLowerCase());
996
+ const alreadyTop = issues.length >= keys.length && issues.slice(0, keys.length).every((issue2, index) => issue2.key.toLowerCase() === wanted[index]);
997
+ const anchor = alreadyTop ? void 0 : issues.find((i) => !wanted.includes(i.key.toLowerCase()));
998
+ if (!anchor) {
999
+ process.stderr.write(
1000
+ alreadyTop ? "issues already at the top in order\n" : "no issue outside the given keys in the scope to rank against\n"
1001
+ );
1002
+ return;
1003
+ }
1004
+ await ctx.client.rankIssues(keys, { before: anchor.key });
1005
+ process.stderr.write(`ranked ${keys.join(", ")} before ${anchor.key}
1006
+ `);
595
1007
  }
596
1008
  );
597
1009
  const link = issue.command("link").description("link two issues, e.g. jira issue link ABC-1 Blocks ABC-2");
@@ -784,35 +1196,7 @@ var registerIssueCommands = (program2) => {
784
1196
  process.stderr.write(TRANSITION_HINT + "\n");
785
1197
  return;
786
1198
  }
787
- const wanted = status.toLowerCase();
788
- const byName = transitions.filter(
789
- (t) => t.name.toLowerCase() === wanted || t.id === status
790
- );
791
- const byTarget = transitions.filter(
792
- (t) => t.to?.name.toLowerCase() === wanted
793
- );
794
- const match = byName.length > 0 ? byName.length === 1 ? byName[0] : void 0 : byTarget.length === 1 ? byTarget[0] : void 0;
795
- if (byName.length > 1) {
796
- throw exitError(
797
- 1,
798
- `'${status}' matches ${byName.length} transitions on ${key}: ${byName.map((t) => `${t.name} \u2192 ${t.to?.name ?? "\u2014"}`).join("; ")}`
799
- );
800
- }
801
- if (byName.length === 0 && byTarget.length > 1) {
802
- throw exitError(
803
- 1,
804
- `${byTarget.length} transitions reach '${status}' on ${key}: ${byTarget.map((t) => `${t.name} \u2192 ${t.to?.name ?? "\u2014"}`).join("; ")}
805
- Use a transition name instead`
806
- );
807
- }
808
- if (!match) {
809
- throw exitError(
810
- 1,
811
- `no transition or status '${status}' on ${key}. Available:
812
- ${transitions.map((t) => ` ${t.name} \u2192 ${t.to?.name ?? "\u2014"}`).join("\n")}
813
- ${TRANSITION_HINT}`
814
- );
815
- }
1199
+ const match = resolveTransition(transitions, key, status);
816
1200
  await ctx.client.transitionIssue(
817
1201
  key,
818
1202
  match.id,
@@ -836,7 +1220,6 @@ ${TRANSITION_HINT}`
836
1220
  });
837
1221
  };
838
1222
  var issueUrl = (ctx, key) => `${ctx.config.baseUrl.replace(/\/$/, "")}/browse/${key}`;
839
- var TRANSITION_HINT = "the argument may be either the transition name or its target status";
840
1223
  var formatField = (value) => {
841
1224
  if (value == null) return "\u2014";
842
1225
  if (typeof value === "object") {
@@ -1161,6 +1544,7 @@ Examples:
1161
1544
  jira attachment list ABC-123
1162
1545
  jira attachment read ABC-123 error.log | grep -i timeout
1163
1546
  jira search 'project = ABC AND created >= -7d' --json | jq '.[].key'
1547
+ jira automation list --project ABC
1164
1548
  `
1165
1549
  );
1166
1550
  registerIssueCommands(program);
@@ -1176,10 +1560,11 @@ registerEpicCommands(program);
1176
1560
  registerUserCommands(program);
1177
1561
  registerMetaCommands(program);
1178
1562
  registerCountCommand(program);
1563
+ registerAutomationCommands(program);
1179
1564
  registerApiCommand(program);
1180
1565
  var exitCodeFor = (error) => {
1181
1566
  if (isExitError(error)) return error.code;
1182
- if (isJiraApiError(error))
1567
+ if (isJiraApiError3(error))
1183
1568
  return error.status === 401 || error.status === 403 ? 4 : 1;
1184
1569
  return 1;
1185
1570
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kud/jira-cli",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
5
  "description": "Jira on the command line — read issues, comments and attachments as plain text",
6
6
  "keywords": [