atli 0.5.1__py3-none-any.whl

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.
atli/jira/commands.py ADDED
@@ -0,0 +1,1525 @@
1
+ """`atli jira ...` click commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import click
8
+
9
+ from atli.client import AtlassianAPIError
10
+ from atli.config import Config, ConfigError
11
+ from atli.jira.body import resolve_text
12
+ from atli.jira.client import JiraClient
13
+ from atli.jira.fields import build_issue_fields, parse_field_options
14
+ from atli.jira.jql import build_list_jql
15
+ from atli.output import emit_json, emit_kv, emit_table, fail
16
+
17
+
18
+ def _client(ctx: click.Context) -> JiraClient:
19
+ # Import here to avoid circular dependency
20
+ from atli.cli import _ensure_config
21
+ cfg = _ensure_config(ctx)
22
+ try:
23
+ cfg.require_jira()
24
+ except ConfigError as e:
25
+ fail(str(e))
26
+ return JiraClient(cfg.jira_url, cfg.jira_token)
27
+
28
+
29
+ def _issue_url(base_url: str, key: str) -> str:
30
+ return f"{base_url.rstrip('/')}/browse/{key}"
31
+
32
+
33
+ def _parse_fields(field: tuple[str, ...]) -> dict[str, Any]:
34
+ try:
35
+ return parse_field_options(field)
36
+ except ValueError as e:
37
+ fail(str(e))
38
+ raise # pragma: no cover — fail() exits
39
+
40
+
41
+ def _resolve_body(
42
+ *,
43
+ text: str | None,
44
+ file: str | None,
45
+ required: bool = False,
46
+ required_msg: str = "body required via --text or --file",
47
+ ) -> str | None:
48
+ try:
49
+ body = resolve_text(text=text, file=file)
50
+ except ValueError as e:
51
+ fail(str(e))
52
+ raise # pragma: no cover
53
+ if required and not body:
54
+ fail(required_msg)
55
+ return body
56
+
57
+
58
+ @click.group()
59
+ def jira() -> None:
60
+ """Manage Jira issues."""
61
+
62
+
63
+ @jira.command("create")
64
+ @click.option("--project", required=True, help="Project key, e.g. PROJ")
65
+ @click.option("--title", required=True, help="Issue summary")
66
+ @click.option("--type", "issue_type", default="Task", show_default=True, help="Issue type name")
67
+ @click.option("--description", default=None, help="Issue description (plain text)")
68
+ @click.option("--file", "body_file", default=None, help="Read description from file")
69
+ @click.option("--assignee", default=None, help="Assignee username")
70
+ @click.option("--priority", default=None, help="Priority name, e.g. High")
71
+ @click.option("--label", "labels", multiple=True, help="Label (repeatable; sets full list)")
72
+ @click.option(
73
+ "--component", "components", multiple=True, help="Component name (repeatable; sets full list)"
74
+ )
75
+ @click.option("--parent", default=None, help="Parent/epic issue key (fields.parent)")
76
+ @click.option(
77
+ "--field",
78
+ "extra_fields",
79
+ multiple=True,
80
+ help="Custom/extra field as KEY=VALUE (repeatable; JSON array/object values auto-parsed)",
81
+ )
82
+ @click.pass_context
83
+ def create(
84
+ ctx: click.Context,
85
+ project: str,
86
+ title: str,
87
+ issue_type: str,
88
+ description: str | None,
89
+ body_file: str | None,
90
+ assignee: str | None,
91
+ priority: str | None,
92
+ labels: tuple[str, ...],
93
+ components: tuple[str, ...],
94
+ parent: str | None,
95
+ extra_fields: tuple[str, ...],
96
+ ) -> None:
97
+ """Create a new issue."""
98
+ desc = _resolve_body(text=description, file=body_file)
99
+
100
+ # Build fields dict to avoid kwarg conflicts
101
+ fields = build_issue_fields(
102
+ priority=priority,
103
+ labels=labels or None,
104
+ components=components or None,
105
+ parent=parent,
106
+ extra=_parse_fields(extra_fields),
107
+ )
108
+
109
+ # Add required fields (allow --field to override if explicitly provided)
110
+ fields.setdefault("project", {"key": project})
111
+ fields.setdefault("summary", title)
112
+ fields.setdefault("issuetype", {"name": issue_type})
113
+
114
+ # Add optional fields, allowing --field to override
115
+ if desc:
116
+ fields.setdefault("description", desc)
117
+ if assignee:
118
+ fields.setdefault("assignee", {"name": assignee})
119
+
120
+ client = _client(ctx)
121
+ try:
122
+ result = client.post(f"{client.API}/issue", json={"fields": fields})
123
+ except AtlassianAPIError as e:
124
+ fail(str(e))
125
+
126
+ from atli.cli import _ensure_config
127
+ cfg = _ensure_config(ctx)
128
+ key = result.get("key", "")
129
+ if ctx.obj["json"]:
130
+ emit_json(result)
131
+ return
132
+ emit_kv(
133
+ [
134
+ ("Issue", key),
135
+ ("Title", title),
136
+ ("Type", issue_type),
137
+ ("URL", _issue_url(cfg.jira_url, key)),
138
+ ],
139
+ json_mode=False,
140
+ )
141
+
142
+
143
+ @jira.command("edit")
144
+ @click.argument("key")
145
+ @click.option("--title", default=None, help="New summary")
146
+ @click.option("--description", default=None, help="New description (plain text)")
147
+ @click.option("--file", "body_file", default=None, help="Read description from file")
148
+ @click.option("--type", "issue_type", default=None, help="Issue type name")
149
+ @click.option("--priority", default=None, help="Priority name")
150
+ @click.option("--assignee", default=None, help="Assignee username (x/none to unassign)")
151
+ @click.option("--label", "labels", multiple=True, help="Replace labels (repeatable)")
152
+ @click.option("--component", "components", multiple=True, help="Replace components (repeatable)")
153
+ @click.option("--parent", default=None, help="Parent/epic issue key")
154
+ @click.option(
155
+ "--field",
156
+ "extra_fields",
157
+ multiple=True,
158
+ help="Custom/extra field as KEY=VALUE (repeatable; JSON array/object values auto-parsed)",
159
+ )
160
+ @click.pass_context
161
+ def edit(
162
+ ctx: click.Context,
163
+ key: str,
164
+ title: str | None,
165
+ description: str | None,
166
+ body_file: str | None,
167
+ issue_type: str | None,
168
+ priority: str | None,
169
+ assignee: str | None,
170
+ labels: tuple[str, ...],
171
+ components: tuple[str, ...],
172
+ parent: str | None,
173
+ extra_fields: tuple[str, ...],
174
+ ) -> None:
175
+ """Edit fields on an existing issue."""
176
+ # Distinguish "description omitted" from "clear via empty file": only resolve
177
+ # body when --description or --file was passed.
178
+ desc: str | None = None
179
+ body_requested = description is not None or body_file is not None
180
+ if body_requested:
181
+ desc = _resolve_body(text=description, file=body_file) or ""
182
+
183
+ fields = build_issue_fields(
184
+ summary=title,
185
+ description=desc if body_requested else None,
186
+ issue_type=issue_type,
187
+ priority=priority,
188
+ assignee=assignee,
189
+ labels=labels or None,
190
+ components=components or None,
191
+ parent=parent,
192
+ extra=_parse_fields(extra_fields),
193
+ )
194
+ if not fields:
195
+ fail("nothing to edit: pass at least one of --title/--description/--file/"
196
+ "--type/--priority/--assignee/--label/--component/--parent/--field")
197
+
198
+ client = _client(ctx)
199
+ try:
200
+ client.update_issue(key, fields)
201
+ issue = client.get_issue(key)
202
+ except AtlassianAPIError as e:
203
+ fail(str(e))
204
+
205
+ cfg: Config = ctx.obj["config"]
206
+ f = issue.get("fields", {})
207
+ rows = [
208
+ ("Issue", issue.get("key", key)),
209
+ ("Title", f.get("summary", "")),
210
+ ("Status", _name(f.get("status"))),
211
+ ("Type", _name(f.get("issuetype"))),
212
+ ("Assignee", _person(f.get("assignee"))),
213
+ ("URL", _issue_url(cfg.jira_url, issue.get("key", key))),
214
+ ]
215
+ emit_kv(rows, json_mode=ctx.obj["json"], payload=issue)
216
+
217
+
218
+ @jira.command("assign")
219
+ @click.argument("key")
220
+ @click.argument("assignee")
221
+ @click.pass_context
222
+ def assign(ctx: click.Context, key: str, assignee: str) -> None:
223
+ """Assign an issue to a user (use x or none to unassign)."""
224
+ name: str | None
225
+ if assignee.casefold() in {"x", "none"}:
226
+ name = None
227
+ display = "(unassigned)"
228
+ else:
229
+ name = assignee
230
+ display = assignee
231
+ client = _client(ctx)
232
+ try:
233
+ client.assign_issue(key, name)
234
+ except AtlassianAPIError as e:
235
+ fail(str(e))
236
+ if ctx.obj["json"]:
237
+ emit_json({"key": key, "assignee": name})
238
+ return
239
+ emit_kv([("Issue", key), ("Assignee", display)], json_mode=False)
240
+
241
+
242
+ @jira.command("view")
243
+ @click.argument("key")
244
+ @click.pass_context
245
+ def view(ctx: click.Context, key: str) -> None:
246
+ """Show one issue."""
247
+ client = _client(ctx)
248
+ try:
249
+ issue = client.get_issue(key)
250
+ except AtlassianAPIError as e:
251
+ fail(str(e))
252
+
253
+ cfg: Config = ctx.obj["config"]
254
+ fields = issue.get("fields", {})
255
+ rows = [
256
+ ("Issue", issue.get("key", key)),
257
+ ("Title", fields.get("summary", "")),
258
+ ("Status", _name(fields.get("status"))),
259
+ ("Type", _name(fields.get("issuetype"))),
260
+ ("Assignee", _person(fields.get("assignee"))),
261
+ ("Reporter", _person(fields.get("reporter"))),
262
+ ("URL", _issue_url(cfg.jira_url, issue.get("key", key))),
263
+ ]
264
+ emit_kv(rows, json_mode=ctx.obj["json"], payload=issue)
265
+
266
+
267
+ @jira.command("list")
268
+ @click.option("--project", required=True, help="Project key, e.g. PROJ")
269
+ @click.option("--status", default=None, help="Filter by status name")
270
+ @click.option("--assignee", default=None, help="Filter by assignee username (use 'currentUser()' for self)")
271
+ @click.option("--reporter", default=None, help="Filter by reporter username")
272
+ @click.option("--priority", default=None, help="Filter by priority name")
273
+ @click.option("--label", "labels", multiple=True, help="Filter by label (repeatable, AND)")
274
+ @click.option("--watching", is_flag=True, help="Only issues watched by current user")
275
+ @click.option("--created", default=None, help="Created since: -7d / week / month")
276
+ @click.option("--created-before", default=None, help="Created before: -7d / week / month")
277
+ @click.option("--updated", default=None, help="Updated since: -7d / week / month")
278
+ @click.option("--updated-before", default=None, help="Updated before: -7d / week / month")
279
+ @click.option("--order-by", default="updated", show_default=True, help="Order by field")
280
+ @click.option("--reverse", is_flag=True, help="Ascending order (default is DESC)")
281
+ @click.option("--limit", default=20, show_default=True, help="Max results")
282
+ @click.pass_context
283
+ def list_cmd(
284
+ ctx: click.Context,
285
+ project: str,
286
+ status: str | None,
287
+ assignee: str | None,
288
+ reporter: str | None,
289
+ priority: str | None,
290
+ labels: tuple[str, ...],
291
+ watching: bool,
292
+ created: str | None,
293
+ created_before: str | None,
294
+ updated: str | None,
295
+ updated_before: str | None,
296
+ order_by: str,
297
+ reverse: bool,
298
+ limit: int,
299
+ ) -> None:
300
+ """List issues in a project."""
301
+ jql = build_list_jql(
302
+ project=project,
303
+ status=status,
304
+ assignee=assignee,
305
+ reporter=reporter,
306
+ priority=priority,
307
+ labels=labels or None,
308
+ watching=watching,
309
+ created=created,
310
+ created_before=created_before,
311
+ updated=updated,
312
+ updated_before=updated_before,
313
+ order_by=order_by,
314
+ reverse=reverse,
315
+ )
316
+ _search_and_emit(ctx, jql, limit)
317
+
318
+
319
+ @jira.command("search")
320
+ @click.argument("jql")
321
+ @click.option("--limit", default=20, show_default=True, help="Max results")
322
+ @click.pass_context
323
+ def search(ctx: click.Context, jql: str, limit: int) -> None:
324
+ """Run a raw JQL query."""
325
+ _search_and_emit(ctx, jql, limit)
326
+
327
+
328
+ def _search_and_emit(ctx: click.Context, jql: str, limit: int) -> None:
329
+ client = _client(ctx)
330
+ try:
331
+ result = client.search_jql(jql, max_results=limit, fields="summary,status,assignee,issuetype")
332
+ except AtlassianAPIError as e:
333
+ fail(str(e))
334
+
335
+ issues = result.get("issues", [])
336
+ if ctx.obj["json"]:
337
+ emit_json(result)
338
+ return
339
+
340
+ rows = []
341
+ for issue in issues:
342
+ f = issue.get("fields", {})
343
+ rows.append(
344
+ [
345
+ issue.get("key", ""),
346
+ _name(f.get("issuetype")),
347
+ _name(f.get("status")),
348
+ _person(f.get("assignee")),
349
+ f.get("summary", ""),
350
+ ]
351
+ )
352
+ emit_table(["Key", "Type", "Status", "Assignee", "Title"], rows, json_mode=False)
353
+
354
+
355
+ @jira.group("comment")
356
+ def comment() -> None:
357
+ """Manage issue comments."""
358
+
359
+
360
+ @comment.command("add")
361
+ @click.argument("key")
362
+ @click.option("--text", default=None, help="Comment body")
363
+ @click.option("--file", "body_file", default=None, help="Read comment body from file")
364
+ @click.option(
365
+ "--internal",
366
+ is_flag=True,
367
+ help="Mark comment internal (Jira Service Management sd.public.comment)",
368
+ )
369
+ @click.pass_context
370
+ def comment_add(
371
+ ctx: click.Context,
372
+ key: str,
373
+ text: str | None,
374
+ body_file: str | None,
375
+ internal: bool,
376
+ ) -> None:
377
+ """Add a comment to an issue."""
378
+ body = _resolve_body(
379
+ text=text,
380
+ file=body_file,
381
+ required=True,
382
+ required_msg="comment body required via --text or --file (or stdin)",
383
+ )
384
+ assert body is not None
385
+ client = _client(ctx)
386
+ try:
387
+ result = client.add_comment(key, body, internal=internal)
388
+ except AtlassianAPIError as e:
389
+ fail(str(e))
390
+ if ctx.obj["json"]:
391
+ emit_json(result)
392
+ return
393
+ rows: list[tuple[str, str]] = [("Issue", key), ("Comment", "added")]
394
+ if internal:
395
+ rows.append(("Internal", "yes"))
396
+ emit_kv(rows, json_mode=False)
397
+
398
+
399
+ @comment.command("list")
400
+ @click.argument("key")
401
+ @click.option("--limit", default=50, show_default=True, help="Max comments to return")
402
+ @click.pass_context
403
+ def comment_list(ctx: click.Context, key: str, limit: int) -> None:
404
+ """List comments on an issue."""
405
+ client = _client(ctx)
406
+ try:
407
+ result = client.list_comments(key, max_results=limit)
408
+ except AtlassianAPIError as e:
409
+ fail(str(e))
410
+ if ctx.obj["json"]:
411
+ emit_json(result)
412
+ return
413
+ comments = result.get("comments", [])
414
+ rows = [
415
+ [
416
+ c.get("id", ""),
417
+ (c.get("author") or {}).get("displayName") or (c.get("author") or {}).get("name") or "?",
418
+ (c.get("body") or "")[:60].replace("\n", " "),
419
+ ]
420
+ for c in comments
421
+ ]
422
+ emit_table(["ID", "Author", "Body (truncated)"], rows, json_mode=False)
423
+
424
+
425
+ @comment.command("update")
426
+ @click.argument("key")
427
+ @click.argument("comment_id")
428
+ @click.option("--text", default=None, help="New comment body")
429
+ @click.option("--file", "body_file", default=None, help="Read new comment body from file")
430
+ @click.option("--internal", is_flag=True, help="Mark internal (JSM)")
431
+ @click.pass_context
432
+ def comment_update(
433
+ ctx: click.Context,
434
+ key: str,
435
+ comment_id: str,
436
+ text: str | None,
437
+ body_file: str | None,
438
+ internal: bool,
439
+ ) -> None:
440
+ """Update a comment body."""
441
+ body = _resolve_body(
442
+ text=text,
443
+ file=body_file,
444
+ required=True,
445
+ required_msg="new body required via --text or --file",
446
+ )
447
+ assert body is not None
448
+ client = _client(ctx)
449
+ try:
450
+ result = client.update_comment(key, comment_id, body, internal=internal)
451
+ except AtlassianAPIError as e:
452
+ fail(str(e))
453
+ if ctx.obj["json"]:
454
+ emit_json(result)
455
+ return
456
+ emit_kv([("Issue", key), ("Comment", comment_id), ("Action", "updated")], json_mode=False)
457
+
458
+
459
+ @comment.command("delete")
460
+ @click.argument("key")
461
+ @click.argument("comment_id")
462
+ @click.option("--yes", is_flag=True, help="Skip confirmation")
463
+ @click.pass_context
464
+ def comment_delete(
465
+ ctx: click.Context, key: str, comment_id: str, yes: bool
466
+ ) -> None:
467
+ """Delete a comment."""
468
+ if not yes:
469
+ if ctx.obj["json"]:
470
+ fail("--yes is required when --json is set")
471
+ if not click.confirm(f"Delete comment {comment_id} on {key}?", default=False):
472
+ fail("aborted")
473
+ client = _client(ctx)
474
+ try:
475
+ client.delete_comment(key, comment_id)
476
+ except AtlassianAPIError as e:
477
+ fail(str(e))
478
+ if ctx.obj["json"]:
479
+ emit_json({"key": key, "comment_id": comment_id, "deleted": True})
480
+ return
481
+ emit_kv([("Issue", key), ("Comment", comment_id), ("Deleted", "yes")], json_mode=False)
482
+
483
+
484
+ @jira.command("transition")
485
+ @click.argument("key")
486
+ @click.option("--to", "target", required=True, help="Target status name (e.g. 'Done')")
487
+ @click.option("--comment", default=None, help="Comment to add during transition")
488
+ @click.option("--resolution", default=None, help="Resolution name (if workflow allows)")
489
+ @click.option("--assignee", default=None, help="Assignee username (x/none to unassign)")
490
+ @click.pass_context
491
+ def transition(
492
+ ctx: click.Context,
493
+ key: str,
494
+ target: str,
495
+ comment: str | None,
496
+ resolution: str | None,
497
+ assignee: str | None,
498
+ ) -> None:
499
+ """Move an issue to a new status."""
500
+ client = _client(ctx)
501
+ try:
502
+ client.transition(
503
+ key,
504
+ target,
505
+ comment=comment,
506
+ resolution=resolution,
507
+ assignee=assignee,
508
+ )
509
+ except AtlassianAPIError as e:
510
+ fail(str(e))
511
+ if ctx.obj["json"]:
512
+ emit_json({"key": key, "transitioned_to": target})
513
+ return
514
+ emit_kv([("Issue", key), ("Transitioned to", target)], json_mode=False)
515
+
516
+
517
+ @jira.command("me")
518
+ @click.pass_context
519
+ def me(ctx: click.Context) -> None:
520
+ """Show the authenticated Jira user (`/myself`)."""
521
+ client = _client(ctx)
522
+ try:
523
+ user = client.myself()
524
+ except AtlassianAPIError as e:
525
+ fail(str(e))
526
+ rows = [
527
+ ("Username", user.get("name", "")),
528
+ ("Display name", user.get("displayName", "")),
529
+ ("Email", user.get("emailAddress", "")),
530
+ ("Active", str(user.get("active", ""))),
531
+ ]
532
+ emit_kv(rows, json_mode=ctx.obj["json"], payload=user)
533
+
534
+
535
+ @jira.command("link")
536
+ @click.argument("inward")
537
+ @click.argument("outward")
538
+ @click.argument("link_type")
539
+ @click.pass_context
540
+ def link(ctx: click.Context, inward: str, outward: str, link_type: str) -> None:
541
+ """Link two issues (INWARD OUTWARD TYPE), e.g. PROJ-1 PROJ-2 Blocks."""
542
+ client = _client(ctx)
543
+ try:
544
+ result = client.link_issues(inward, outward, link_type)
545
+ except AtlassianAPIError as e:
546
+ fail(str(e))
547
+ payload = {"inward": inward, "outward": outward, "type": link_type, **(result or {})}
548
+ if ctx.obj["json"]:
549
+ emit_json(payload)
550
+ return
551
+ emit_kv(
552
+ [
553
+ ("Inward", inward),
554
+ ("Outward", outward),
555
+ ("Type", link_type),
556
+ ("Linked", "yes"),
557
+ ],
558
+ json_mode=False,
559
+ )
560
+
561
+
562
+ @jira.command("unlink")
563
+ @click.argument("key_a")
564
+ @click.argument("key_b")
565
+ @click.pass_context
566
+ def unlink(ctx: click.Context, key_a: str, key_b: str) -> None:
567
+ """Remove the link between two issues."""
568
+ client = _client(ctx)
569
+ try:
570
+ client.unlink_issues(key_a, key_b)
571
+ except AtlassianAPIError as e:
572
+ fail(str(e))
573
+ if ctx.obj["json"]:
574
+ emit_json({"unlinked": [key_a, key_b]})
575
+ return
576
+ emit_kv([("Unlinked", f"{key_a} <-> {key_b}")], json_mode=False)
577
+
578
+
579
+ @jira.group("remote-link")
580
+ def remote_link_group() -> None:
581
+ """Manage remote (web) links on an issue."""
582
+
583
+
584
+ @remote_link_group.command("add")
585
+ @click.argument("key")
586
+ @click.argument("url")
587
+ @click.argument("title", required=False, default=None)
588
+ @click.pass_context
589
+ def remote_link_add(ctx: click.Context, key: str, url: str, title: str | None) -> None:
590
+ """Add a remote web link to an issue."""
591
+ client = _client(ctx)
592
+ try:
593
+ result = client.add_remote_link(key, url, title)
594
+ except AtlassianAPIError as e:
595
+ fail(str(e))
596
+ display_title = title or url
597
+ if ctx.obj["json"]:
598
+ emit_json(result or {"key": key, "url": url, "title": display_title})
599
+ return
600
+ emit_kv(
601
+ [("Issue", key), ("URL", url), ("Title", display_title)],
602
+ json_mode=False,
603
+ )
604
+
605
+
606
+ @remote_link_group.command("list")
607
+ @click.argument("key")
608
+ @click.pass_context
609
+ def remote_link_list(ctx: click.Context, key: str) -> None:
610
+ """List all remote links on an issue."""
611
+ client = _client(ctx)
612
+ try:
613
+ links = client.list_remote_links(key)
614
+ except AtlassianAPIError as e:
615
+ fail(str(e))
616
+ if ctx.obj["json"]:
617
+ emit_json(links)
618
+ return
619
+ rows = [
620
+ [
621
+ str(lk.get("id", "")),
622
+ (lk.get("object") or {}).get("title", ""),
623
+ (lk.get("object") or {}).get("url", ""),
624
+ ]
625
+ for lk in links
626
+ ]
627
+ emit_table(["ID", "Title", "URL"], rows, json_mode=False)
628
+
629
+
630
+ @remote_link_group.command("update")
631
+ @click.argument("key")
632
+ @click.argument("link_id")
633
+ @click.argument("url")
634
+ @click.option("--title", default=None, help="Link title (defaults to URL)")
635
+ @click.pass_context
636
+ def remote_link_update(
637
+ ctx: click.Context, key: str, link_id: str, url: str, title: str | None
638
+ ) -> None:
639
+ """Update the URL and/or title of a remote link."""
640
+ client = _client(ctx)
641
+ try:
642
+ result = client.update_remote_link(key, link_id, url, title)
643
+ except AtlassianAPIError as e:
644
+ fail(str(e))
645
+ if ctx.obj["json"]:
646
+ emit_json(result)
647
+ return
648
+ emit_kv(
649
+ [("Issue", key), ("Link", link_id), ("URL", url), ("Action", "updated")],
650
+ json_mode=False,
651
+ )
652
+
653
+
654
+ @remote_link_group.command("delete")
655
+ @click.argument("key")
656
+ @click.argument("link_id")
657
+ @click.option("--yes", is_flag=True, help="Skip confirmation")
658
+ @click.pass_context
659
+ def remote_link_delete(ctx: click.Context, key: str, link_id: str, yes: bool) -> None:
660
+ """Delete a remote link."""
661
+ if not yes:
662
+ if ctx.obj["json"]:
663
+ fail("--yes is required when --json is set")
664
+ if not click.confirm(f"Delete remote link {link_id} on {key}?", default=False):
665
+ fail("aborted")
666
+ client = _client(ctx)
667
+ try:
668
+ client.delete_remote_link(key, link_id)
669
+ except AtlassianAPIError as e:
670
+ fail(str(e))
671
+ if ctx.obj["json"]:
672
+ emit_json({"key": key, "link_id": link_id, "deleted": True})
673
+ return
674
+ emit_kv([("Issue", key), ("Link", link_id), ("Deleted", "yes")], json_mode=False)
675
+
676
+
677
+ @jira.group("user")
678
+ def user_group() -> None:
679
+ """Search Jira users."""
680
+
681
+
682
+ @user_group.command("search")
683
+ @click.argument("query")
684
+ @click.option("--limit", default=20, show_default=True, help="Max results")
685
+ @click.option("--project", default=None, help="Filter to users assignable in this project")
686
+ @click.option("--issue", default=None, help="Filter to users assignable to this issue")
687
+ @click.pass_context
688
+ def user_search(
689
+ ctx: click.Context, query: str, limit: int, project: str | None, issue: str | None
690
+ ) -> None:
691
+ """Search users by name or username.
692
+
693
+ Pass --project or --issue to restrict to users who can be assigned there.
694
+ """
695
+ client = _client(ctx)
696
+ try:
697
+ if project or issue:
698
+ users = client.search_assignable_users(
699
+ query, project=project, issue=issue, max_results=limit
700
+ )
701
+ else:
702
+ users = client.search_users(query, max_results=limit)
703
+ except AtlassianAPIError as e:
704
+ fail(str(e))
705
+ if ctx.obj["json"]:
706
+ emit_json(users)
707
+ return
708
+ rows = [
709
+ [
710
+ u.get("name", ""),
711
+ u.get("displayName", ""),
712
+ u.get("emailAddress", ""),
713
+ ]
714
+ for u in users
715
+ ]
716
+ emit_table(["Username", "Display Name", "Email"], rows, json_mode=False)
717
+
718
+
719
+
720
+ def _name(node: dict | None) -> str:
721
+ return (node or {}).get("name", "")
722
+
723
+
724
+ def _person(node: dict | None) -> str:
725
+ if not node:
726
+ return ""
727
+ return node.get("displayName") or node.get("name") or node.get("emailAddress") or ""
728
+
729
+
730
+
731
+ @jira.command("clone")
732
+ @click.argument("key")
733
+ @click.option("--title", default=None, help="Override summary on the clone")
734
+ @click.option(
735
+ "--replace",
736
+ "replacements",
737
+ multiple=True,
738
+ help="Replace OLD:NEW in summary/description (repeatable, case-sensitive)",
739
+ )
740
+ @click.option("--assignee", default=None, help="Assignee for the clone (default: copy source)")
741
+ @click.pass_context
742
+ def clone(
743
+ ctx: click.Context,
744
+ key: str,
745
+ title: str | None,
746
+ replacements: tuple[str, ...],
747
+ assignee: str | None,
748
+ ) -> None:
749
+ """Clone an issue (copies summary/description/type/priority/labels/components)."""
750
+ pairs: list[tuple[str, str]] = []
751
+ for raw in replacements:
752
+ if ":" not in raw:
753
+ fail(f"--replace expects OLD:NEW, got {raw!r}")
754
+ old, new = raw.split(":", 1)
755
+ pairs.append((old, new))
756
+ client = _client(ctx)
757
+ try:
758
+ result = client.clone_issue(
759
+ key, summary=title, replace=pairs or None, assignee=assignee
760
+ )
761
+ except AtlassianAPIError as e:
762
+ fail(str(e))
763
+ cfg: Config = ctx.obj["config"]
764
+ new_key = result.get("key", "")
765
+ if ctx.obj["json"]:
766
+ emit_json(result)
767
+ return
768
+ emit_kv(
769
+ [
770
+ ("Cloned from", key),
771
+ ("Issue", new_key),
772
+ ("URL", _issue_url(cfg.jira_url, new_key)),
773
+ ],
774
+ json_mode=False,
775
+ )
776
+
777
+
778
+ @jira.command("delete")
779
+ @click.argument("key")
780
+ @click.option("--cascade", is_flag=True, help="Also delete sub-tasks")
781
+ @click.option("--yes", is_flag=True, help="Skip confirmation (required with --json)")
782
+ @click.pass_context
783
+ def delete(ctx: click.Context, key: str, cascade: bool, yes: bool) -> None:
784
+ """Delete an issue."""
785
+ if ctx.obj["json"] and not yes:
786
+ fail("--yes is required with --json for delete")
787
+ if not yes and not ctx.obj["json"]:
788
+ click.confirm(f"Delete {key}{' and sub-tasks' if cascade else ''}?", abort=True)
789
+ client = _client(ctx)
790
+ try:
791
+ client.delete_issue(key, cascade=cascade)
792
+ except AtlassianAPIError as e:
793
+ fail(str(e))
794
+ if ctx.obj["json"]:
795
+ emit_json({"key": key, "deleted": True, "cascade": cascade})
796
+ return
797
+ emit_kv([("Issue", key), ("Deleted", "yes")], json_mode=False)
798
+
799
+
800
+ @jira.group("worklog")
801
+ def worklog() -> None:
802
+ """Manage issue worklogs."""
803
+
804
+
805
+ @worklog.command("add")
806
+ @click.argument("key")
807
+ @click.argument("time_spent")
808
+ @click.option("--comment", default=None, help="Worklog comment")
809
+ @click.pass_context
810
+ def worklog_add(
811
+ ctx: click.Context, key: str, time_spent: str, comment: str | None
812
+ ) -> None:
813
+ """Add a worklog (e.g. ``2h``, ``30m``, ``1d 2h``)."""
814
+ client = _client(ctx)
815
+ try:
816
+ result = client.add_worklog(key, time_spent, comment=comment)
817
+ except AtlassianAPIError as e:
818
+ fail(str(e))
819
+ if ctx.obj["json"]:
820
+ emit_json(result)
821
+ return
822
+ emit_kv(
823
+ [("Issue", key), ("Time spent", time_spent), ("Worklog", "added")],
824
+ json_mode=False,
825
+ )
826
+
827
+
828
+ @worklog.command("list")
829
+ @click.argument("key")
830
+ @click.pass_context
831
+ def worklog_list(ctx: click.Context, key: str) -> None:
832
+ """List worklogs on an issue."""
833
+ client = _client(ctx)
834
+ try:
835
+ result = client.list_worklogs(key)
836
+ except AtlassianAPIError as e:
837
+ fail(str(e))
838
+ if ctx.obj["json"]:
839
+ emit_json(result)
840
+ return
841
+ logs = result.get("worklogs", [])
842
+ rows = [
843
+ [
844
+ w.get("id", ""),
845
+ (w.get("author") or {}).get("displayName") or (w.get("author") or {}).get("name") or "?",
846
+ w.get("timeSpent", ""),
847
+ (w.get("comment") or "")[:40].replace("\n", " "),
848
+ ]
849
+ for w in logs
850
+ ]
851
+ emit_table(["ID", "Author", "Time Spent", "Comment"], rows, json_mode=False)
852
+
853
+
854
+ @worklog.command("update")
855
+ @click.argument("key")
856
+ @click.argument("worklog_id")
857
+ @click.argument("time_spent")
858
+ @click.option("--comment", default=None, help="New comment")
859
+ @click.pass_context
860
+ def worklog_update(
861
+ ctx: click.Context, key: str, worklog_id: str, time_spent: str, comment: str | None
862
+ ) -> None:
863
+ """Update a worklog's time and optional comment."""
864
+ client = _client(ctx)
865
+ try:
866
+ result = client.update_worklog(key, worklog_id, time_spent, comment=comment)
867
+ except AtlassianAPIError as e:
868
+ fail(str(e))
869
+ if ctx.obj["json"]:
870
+ emit_json(result)
871
+ return
872
+ emit_kv(
873
+ [("Issue", key), ("Worklog", worklog_id), ("Time spent", time_spent), ("Action", "updated")],
874
+ json_mode=False,
875
+ )
876
+
877
+
878
+ @worklog.command("delete")
879
+ @click.argument("key")
880
+ @click.argument("worklog_id")
881
+ @click.option("--yes", is_flag=True, help="Skip confirmation")
882
+ @click.pass_context
883
+ def worklog_delete(ctx: click.Context, key: str, worklog_id: str, yes: bool) -> None:
884
+ """Delete a worklog entry."""
885
+ if not yes:
886
+ if ctx.obj["json"]:
887
+ fail("--yes is required when --json is set")
888
+ if not click.confirm(f"Delete worklog {worklog_id} on {key}?", default=False):
889
+ fail("aborted")
890
+ client = _client(ctx)
891
+ try:
892
+ client.delete_worklog(key, worklog_id)
893
+ except AtlassianAPIError as e:
894
+ fail(str(e))
895
+ if ctx.obj["json"]:
896
+ emit_json({"key": key, "worklog_id": worklog_id, "deleted": True})
897
+ return
898
+ emit_kv([("Issue", key), ("Worklog", worklog_id), ("Deleted", "yes")], json_mode=False)
899
+
900
+
901
+ @jira.group("watch")
902
+ def watch_group() -> None:
903
+ """Manage issue watchers."""
904
+
905
+
906
+ @watch_group.command("add")
907
+ @click.argument("key")
908
+ @click.argument("username", required=False, default=None)
909
+ @click.pass_context
910
+ def watch_add(ctx: click.Context, key: str, username: str | None) -> None:
911
+ """Watch an issue (default: current user from /myself)."""
912
+ client = _client(ctx)
913
+ try:
914
+ user = username
915
+ if user is None:
916
+ user = client.myself().get("name")
917
+ if not user:
918
+ fail("could not resolve current username from /myself")
919
+ client.watch_issue(key, user)
920
+ except AtlassianAPIError as e:
921
+ fail(str(e))
922
+ if ctx.obj["json"]:
923
+ emit_json({"key": key, "watcher": user})
924
+ return
925
+ emit_kv([("Issue", key), ("Watcher", user), ("Action", "watching")], json_mode=False)
926
+
927
+
928
+ @watch_group.command("list")
929
+ @click.argument("key")
930
+ @click.pass_context
931
+ def watch_list(ctx: click.Context, key: str) -> None:
932
+ """List watchers on an issue."""
933
+ client = _client(ctx)
934
+ try:
935
+ result = client.list_watchers(key)
936
+ except AtlassianAPIError as e:
937
+ fail(str(e))
938
+ if ctx.obj["json"]:
939
+ emit_json(result)
940
+ return
941
+ watchers = result.get("watchers", [])
942
+ rows = [
943
+ [
944
+ w.get("name", ""),
945
+ w.get("displayName", ""),
946
+ ]
947
+ for w in watchers
948
+ ]
949
+ watching = result.get("watchCount", len(watchers))
950
+ click.echo(f"Watching: {watching}")
951
+ emit_table(["Username", "Display Name"], rows, json_mode=False)
952
+
953
+
954
+ @watch_group.command("remove")
955
+ @click.argument("key")
956
+ @click.argument("username", required=False, default=None)
957
+ @click.pass_context
958
+ def watch_remove(ctx: click.Context, key: str, username: str | None) -> None:
959
+ """Remove a watcher (default: current user)."""
960
+ client = _client(ctx)
961
+ try:
962
+ user = username
963
+ if user is None:
964
+ user = client.myself().get("name")
965
+ if not user:
966
+ fail("could not resolve current username from /myself")
967
+ client.unwatch_issue(key, user)
968
+ except AtlassianAPIError as e:
969
+ fail(str(e))
970
+ if ctx.obj["json"]:
971
+ emit_json({"key": key, "watcher": user, "removed": True})
972
+ return
973
+ emit_kv([("Issue", key), ("Watcher", user), ("Action", "removed")], json_mode=False)
974
+
975
+
976
+ @jira.command("bulk-create")
977
+ @click.option(
978
+ "--file", "input_file",
979
+ type=click.Path(exists=True, dir_okay=False),
980
+ required=True,
981
+ help="JSON file with issue definitions (array or {issueUpdates:[...]})",
982
+ )
983
+ @click.pass_context
984
+ def bulk_create(ctx: click.Context, input_file: str) -> None:
985
+ """Create multiple issues from a JSON file.
986
+
987
+ The file must be a JSON array of issue-field objects, e.g.:
988
+
989
+ \b
990
+ [
991
+ {"project": "PROJ", "title": "Task 1", "type": "Task"},
992
+ {"project": "PROJ", "title": "Task 2", "type": "Bug"}
993
+ ]
994
+
995
+ Each object accepts the same keys as `atli jira create`: project, title,
996
+ type, description, assignee, priority, labels, components, parent.
997
+ """
998
+ import json as _json
999
+
1000
+ with open(input_file) as fh:
1001
+ raw = _json.load(fh)
1002
+
1003
+ # Accept either a plain list or {"issueUpdates": [...]}
1004
+ if isinstance(raw, dict) and "issueUpdates" in raw:
1005
+ issue_updates = raw["issueUpdates"]
1006
+ elif isinstance(raw, list):
1007
+ # Convert shorthand keys to Jira field payloads
1008
+ issue_updates = []
1009
+ for item in raw:
1010
+ fields: dict[str, Any] = {
1011
+ "project": {"key": item["project"]},
1012
+ "summary": item["title"],
1013
+ "issuetype": {"name": item.get("type", "Task")},
1014
+ }
1015
+ if item.get("description"):
1016
+ fields["description"] = item["description"]
1017
+ if item.get("assignee"):
1018
+ fields["assignee"] = {"name": item["assignee"]}
1019
+ if item.get("priority"):
1020
+ fields["priority"] = {"name": item["priority"]}
1021
+ if item.get("labels"):
1022
+ fields["labels"] = item["labels"]
1023
+ if item.get("components"):
1024
+ fields["components"] = [{"name": c} for c in item["components"]]
1025
+ if item.get("parent"):
1026
+ fields["parent"] = {"key": item["parent"]}
1027
+ for k, v in item.get("fields", {}).items():
1028
+ fields[k] = v
1029
+ issue_updates.append({"fields": fields})
1030
+ else:
1031
+ fail("file must be a JSON array or {\"issueUpdates\": [...]}")
1032
+
1033
+ client = _client(ctx)
1034
+ try:
1035
+ result = client.bulk_create_issues(issue_updates)
1036
+ except AtlassianAPIError as e:
1037
+ fail(str(e))
1038
+
1039
+ issues = result.get("issues", [])
1040
+ errors = result.get("errors", [])
1041
+
1042
+ if ctx.obj["json"]:
1043
+ emit_json(result)
1044
+ if errors:
1045
+ raise SystemExit(1)
1046
+ return
1047
+
1048
+ # Display successful issues
1049
+ if issues:
1050
+ rows = [[iss.get("key", ""), iss.get("id", "")] for iss in issues]
1051
+ emit_table(["Key", "ID"], rows, json_mode=False)
1052
+ click.echo(f"\nCreated {len(issues)} issue(s).")
1053
+
1054
+ # Display errors if any
1055
+ if errors:
1056
+ click.echo("\nErrors:", err=True)
1057
+ for err in errors:
1058
+ element_num = err.get("failedElementNumber", "?")
1059
+ element_errors = err.get("elementErrors", {})
1060
+ error_msgs = element_errors.get("errors", {})
1061
+ click.echo(f" Issue #{element_num}: {error_msgs}", err=True)
1062
+ fail(f"Partial failure: {len(issues)} created, {len(errors)} failed")
1063
+
1064
+
1065
+ @jira.group("meta")
1066
+ def meta_group() -> None:
1067
+ """Query Jira instance metadata (priorities, issue types, statuses, resolutions)."""
1068
+
1069
+
1070
+ @meta_group.command("priorities")
1071
+ @click.pass_context
1072
+ def meta_priorities(ctx: click.Context) -> None:
1073
+ """List all configured priorities."""
1074
+ client = _client(ctx)
1075
+ try:
1076
+ items = client.get_priorities()
1077
+ except AtlassianAPIError as e:
1078
+ fail(str(e))
1079
+ if ctx.obj["json"]:
1080
+ emit_json(items)
1081
+ return
1082
+ rows = [[p.get("name", ""), p.get("description", "")] for p in items]
1083
+ emit_table(["Name", "Description"], rows, json_mode=False)
1084
+
1085
+
1086
+ @meta_group.command("issue-types")
1087
+ @click.pass_context
1088
+ def meta_issue_types(ctx: click.Context) -> None:
1089
+ """List all issue types."""
1090
+ client = _client(ctx)
1091
+ try:
1092
+ items = client.get_issue_types()
1093
+ except AtlassianAPIError as e:
1094
+ fail(str(e))
1095
+ if ctx.obj["json"]:
1096
+ emit_json(items)
1097
+ return
1098
+ rows = [
1099
+ [it.get("name", ""), "subtask" if it.get("subtask") else "standard", it.get("description", "")]
1100
+ for it in items
1101
+ ]
1102
+ emit_table(["Name", "Kind", "Description"], rows, json_mode=False)
1103
+
1104
+
1105
+ @meta_group.command("statuses")
1106
+ @click.pass_context
1107
+ def meta_statuses(ctx: click.Context) -> None:
1108
+ """List all statuses."""
1109
+ client = _client(ctx)
1110
+ try:
1111
+ items = client.get_statuses()
1112
+ except AtlassianAPIError as e:
1113
+ fail(str(e))
1114
+ if ctx.obj["json"]:
1115
+ emit_json(items)
1116
+ return
1117
+ rows = [
1118
+ [s.get("name", ""), (s.get("statusCategory") or {}).get("name", "")]
1119
+ for s in items
1120
+ ]
1121
+ emit_table(["Status", "Category"], rows, json_mode=False)
1122
+
1123
+
1124
+ @meta_group.command("resolutions")
1125
+ @click.pass_context
1126
+ def meta_resolutions(ctx: click.Context) -> None:
1127
+ """List all resolutions."""
1128
+ client = _client(ctx)
1129
+ try:
1130
+ items = client.get_resolutions()
1131
+ except AtlassianAPIError as e:
1132
+ fail(str(e))
1133
+ if ctx.obj["json"]:
1134
+ emit_json(items)
1135
+ return
1136
+ rows = [[r.get("name", ""), r.get("description", "")] for r in items]
1137
+ emit_table(["Name", "Description"], rows, json_mode=False)
1138
+
1139
+
1140
+ @jira.command("fields")
1141
+ @click.argument("key")
1142
+ @click.pass_context
1143
+ def fields_cmd(ctx: click.Context, key: str) -> None:
1144
+ """Show all fields (including custom fields) on an issue.
1145
+
1146
+ Useful for discovering custom field IDs and current values.
1147
+ """
1148
+ client = _client(ctx)
1149
+ try:
1150
+ issue = client.get_issue(key)
1151
+ except AtlassianAPIError as e:
1152
+ fail(str(e))
1153
+ fields = issue.get("fields", {})
1154
+ if ctx.obj["json"]:
1155
+ emit_json(fields)
1156
+ return
1157
+ rows = []
1158
+ for field_key, value in fields.items():
1159
+ # simplify display: show short repr for dicts/lists
1160
+ if isinstance(value, dict):
1161
+ display = value.get("name") or value.get("value") or str(value)[:60]
1162
+ elif isinstance(value, list):
1163
+ display = f"[{len(value)} items]" if value else "[]"
1164
+ else:
1165
+ display = str(value) if value is not None else ""
1166
+ rows.append([field_key, display[:80]])
1167
+ emit_table(["Field ID", "Value"], rows, json_mode=False)
1168
+
1169
+
1170
+ @jira.command("editmeta")
1171
+ @click.argument("key")
1172
+ @click.pass_context
1173
+ def editmeta_cmd(ctx: click.Context, key: str) -> None:
1174
+ """Show editable fields and their schemas for an issue.
1175
+
1176
+ Returns the field definitions (type, allowed values, required, etc.).
1177
+ """
1178
+ client = _client(ctx)
1179
+ try:
1180
+ meta = client.get_editmeta(key)
1181
+ except AtlassianAPIError as e:
1182
+ fail(str(e))
1183
+ if ctx.obj["json"]:
1184
+ emit_json(meta)
1185
+ return
1186
+ fields = meta.get("fields", {})
1187
+ rows = []
1188
+ for field_id, field_def in fields.items():
1189
+ name = field_def.get("name", field_id)
1190
+ required = "yes" if field_def.get("required") else "no"
1191
+ ftype = field_def.get("schema", {}).get("type", "")
1192
+ rows.append([field_id, name, ftype, required])
1193
+ emit_table(["Field ID", "Name", "Type", "Required"], rows, json_mode=False)
1194
+ click.echo(f"\nTotal: {len(fields)} editable field(s)")
1195
+
1196
+
1197
+ @jira.command("open")
1198
+ @click.argument("key", required=False, default=None)
1199
+ @click.pass_context
1200
+ def open_cmd(ctx: click.Context, key: str | None) -> None:
1201
+ """Open the Jira base URL or an issue in the default browser."""
1202
+ import webbrowser
1203
+ from atli.cli import _ensure_config
1204
+
1205
+ cfg = _ensure_config(ctx)
1206
+ url = _issue_url(cfg.jira_url, key) if key else cfg.jira_url.rstrip("/")
1207
+ if ctx.obj["json"]:
1208
+ emit_json({"url": url, "opened": False})
1209
+ return
1210
+ webbrowser.open(url)
1211
+ emit_kv([("Opened", url)], json_mode=False)
1212
+
1213
+
1214
+ # ----------------------------- filter commands -----------------------------
1215
+
1216
+
1217
+ @jira.group("filter")
1218
+ def filter_group() -> None:
1219
+ """Manage Jira filters (saved JQL queries)."""
1220
+
1221
+
1222
+ @filter_group.command("list")
1223
+ @click.pass_context
1224
+ def filter_list(ctx: click.Context) -> None:
1225
+ """List all favourite filters."""
1226
+ client = _client(ctx)
1227
+ try:
1228
+ filters = client.list_filters()
1229
+ except AtlassianAPIError as e:
1230
+ fail(str(e))
1231
+
1232
+ if ctx.obj["json"]:
1233
+ emit_json({"filters": filters})
1234
+ return
1235
+
1236
+ rows = [
1237
+ [f.get("id", ""), f.get("name", ""), f.get("jql", "")[:60]]
1238
+ for f in filters
1239
+ ]
1240
+ emit_table(["ID", "Name", "JQL (truncated)"], rows, json_mode=False)
1241
+ click.echo(f"\nTotal: {len(filters)} filter(s)")
1242
+
1243
+
1244
+ @filter_group.command("view")
1245
+ @click.argument("filter_id")
1246
+ @click.pass_context
1247
+ def filter_view(ctx: click.Context, filter_id: str) -> None:
1248
+ """Show filter details."""
1249
+ client = _client(ctx)
1250
+ try:
1251
+ filter_data = client.get_filter(filter_id)
1252
+ except AtlassianAPIError as e:
1253
+ fail(str(e))
1254
+
1255
+ if ctx.obj["json"]:
1256
+ emit_json(filter_data)
1257
+ return
1258
+
1259
+ emit_kv([
1260
+ ("ID", filter_data.get("id", "")),
1261
+ ("Name", filter_data.get("name", "")),
1262
+ ("JQL", filter_data.get("jql", "")),
1263
+ ("Description", filter_data.get("description", "")),
1264
+ ("Favourite", str(filter_data.get("favourite", False))),
1265
+ ("Owner", filter_data.get("owner", {}).get("displayName", "")),
1266
+ ], json_mode=False)
1267
+
1268
+
1269
+ @filter_group.command("create")
1270
+ @click.option("--name", required=True, help="Filter name")
1271
+ @click.option("--jql", required=True, help="JQL query")
1272
+ @click.option("--description", help="Filter description")
1273
+ @click.option("--favourite", is_flag=True, help="Mark as favourite")
1274
+ @click.pass_context
1275
+ def filter_create(
1276
+ ctx: click.Context, name: str, jql: str, description: str | None, favourite: bool
1277
+ ) -> None:
1278
+ """Create a new filter."""
1279
+ client = _client(ctx)
1280
+ try:
1281
+ result = client.create_filter(name, jql, description=description, favourite=favourite)
1282
+ except AtlassianAPIError as e:
1283
+ fail(str(e))
1284
+
1285
+ if ctx.obj["json"]:
1286
+ emit_json(result)
1287
+ return
1288
+
1289
+ emit_kv([
1290
+ ("ID", result.get("id", "")),
1291
+ ("Name", result.get("name", "")),
1292
+ ("JQL", result.get("jql", "")),
1293
+ ], json_mode=False)
1294
+
1295
+
1296
+ @filter_group.command("update")
1297
+ @click.argument("filter_id")
1298
+ @click.option("--name", help="New filter name")
1299
+ @click.option("--jql", help="New JQL query")
1300
+ @click.option("--description", help="New description")
1301
+ @click.option("--favourite/--no-favourite", default=None, help="Set favourite status")
1302
+ @click.pass_context
1303
+ def filter_update(
1304
+ ctx: click.Context,
1305
+ filter_id: str,
1306
+ name: str | None,
1307
+ jql: str | None,
1308
+ description: str | None,
1309
+ favourite: bool | None,
1310
+ ) -> None:
1311
+ """Update filter properties."""
1312
+ client = _client(ctx)
1313
+ try:
1314
+ result = client.update_filter(
1315
+ filter_id, name=name, jql=jql, description=description, favourite=favourite
1316
+ )
1317
+ except AtlassianAPIError as e:
1318
+ fail(str(e))
1319
+
1320
+ if ctx.obj["json"]:
1321
+ emit_json(result)
1322
+ return
1323
+
1324
+ click.echo(f"Filter {filter_id} updated")
1325
+
1326
+
1327
+ @filter_group.command("delete")
1328
+ @click.argument("filter_id")
1329
+ @click.option("--yes", is_flag=True, help="Skip confirmation")
1330
+ @click.pass_context
1331
+ def filter_delete(ctx: click.Context, filter_id: str, yes: bool) -> None:
1332
+ """Delete a filter."""
1333
+ if not yes:
1334
+ if ctx.obj["json"]:
1335
+ fail("--yes is required when --json is set")
1336
+ click.confirm(f"Delete filter {filter_id}?", abort=True)
1337
+
1338
+ client = _client(ctx)
1339
+ try:
1340
+ client.delete_filter(filter_id)
1341
+ except AtlassianAPIError as e:
1342
+ fail(str(e))
1343
+
1344
+ if ctx.obj["json"]:
1345
+ emit_json({"filter_id": filter_id, "deleted": True})
1346
+ return
1347
+
1348
+ click.echo(f"Filter {filter_id} deleted")
1349
+
1350
+
1351
+ @filter_group.command("run")
1352
+ @click.argument("filter_id")
1353
+ @click.option("--limit", default=50, help="Max results")
1354
+ @click.pass_context
1355
+ def filter_run(ctx: click.Context, filter_id: str, limit: int) -> None:
1356
+ """Execute a filter and show matching issues."""
1357
+ client = _client(ctx)
1358
+ try:
1359
+ result = client.run_filter(filter_id, max_results=limit)
1360
+ except AtlassianAPIError as e:
1361
+ fail(str(e))
1362
+
1363
+ if ctx.obj["json"]:
1364
+ emit_json(result)
1365
+ return
1366
+
1367
+ issues = result.get("issues", [])
1368
+ rows = [
1369
+ [
1370
+ iss.get("key", ""),
1371
+ iss.get("fields", {}).get("summary", "")[:50],
1372
+ (iss.get("fields", {}).get("status") or {}).get("name", ""),
1373
+ ]
1374
+ for iss in issues
1375
+ ]
1376
+ emit_table(["Key", "Summary", "Status"], rows, json_mode=False)
1377
+ total = result.get("total", len(issues))
1378
+ click.echo(f"\nShowing {len(issues)} of {total} issue(s)")
1379
+
1380
+
1381
+ # ----------------------------- bulk operations -----------------------------
1382
+
1383
+
1384
+ @jira.group("bulk")
1385
+ def bulk_group() -> None:
1386
+ """Bulk operations on multiple issues."""
1387
+
1388
+
1389
+ @bulk_group.command("transition")
1390
+ @click.argument("keys", nargs=-1, required=True)
1391
+ @click.option("--to", "transition_name", required=True, help="Target transition name")
1392
+ @click.option("--comment", help="Comment to add during transition")
1393
+ @click.pass_context
1394
+ def bulk_transition(
1395
+ ctx: click.Context, keys: tuple[str, ...], transition_name: str, comment: str | None
1396
+ ) -> None:
1397
+ """Transition multiple issues."""
1398
+ client = _client(ctx)
1399
+ try:
1400
+ result = client.bulk_transition(list(keys), transition_name, comment=comment)
1401
+ except AtlassianAPIError as e:
1402
+ fail(str(e))
1403
+
1404
+ if ctx.obj["json"]:
1405
+ emit_json(result)
1406
+ if result["failed"]:
1407
+ raise SystemExit(1)
1408
+ return
1409
+
1410
+ success = result["success"]
1411
+ failed = result["failed"]
1412
+
1413
+ if success:
1414
+ click.echo(f"Transitioned {len(success)} issue(s):")
1415
+ for key in success:
1416
+ click.echo(f" {key}")
1417
+
1418
+ if failed:
1419
+ click.echo(f"\nFailed {len(failed)} issue(s):", err=True)
1420
+ for item in failed:
1421
+ click.echo(f" {item['key']}: {item['error']}", err=True)
1422
+ raise SystemExit(1)
1423
+
1424
+
1425
+ @bulk_group.command("assign")
1426
+ @click.argument("keys", nargs=-1, required=True)
1427
+ @click.option("--to", "assignee", help="Username to assign (omit to unassign)")
1428
+ @click.pass_context
1429
+ def bulk_assign(ctx: click.Context, keys: tuple[str, ...], assignee: str | None) -> None:
1430
+ """Assign multiple issues."""
1431
+ client = _client(ctx)
1432
+ try:
1433
+ result = client.bulk_assign(list(keys), assignee)
1434
+ except AtlassianAPIError as e:
1435
+ fail(str(e))
1436
+
1437
+ if ctx.obj["json"]:
1438
+ emit_json(result)
1439
+ if result["failed"]:
1440
+ raise SystemExit(1)
1441
+ return
1442
+
1443
+ success = result["success"]
1444
+ failed = result["failed"]
1445
+
1446
+ action = f"assigned to {assignee}" if assignee else "unassigned"
1447
+ if success:
1448
+ click.echo(f"{len(success)} issue(s) {action}:")
1449
+ for key in success:
1450
+ click.echo(f" {key}")
1451
+
1452
+ if failed:
1453
+ click.echo(f"\nFailed {len(failed)} issue(s):", err=True)
1454
+ for item in failed:
1455
+ click.echo(f" {item['key']}: {item['error']}", err=True)
1456
+ raise SystemExit(1)
1457
+
1458
+
1459
+ @bulk_group.command("edit")
1460
+ @click.argument("keys", nargs=-1, required=True)
1461
+ @click.option("--field", "fields", multiple=True, help="field=value pairs")
1462
+ @click.pass_context
1463
+ def bulk_edit(ctx: click.Context, keys: tuple[str, ...], fields: tuple[str, ...]) -> None:
1464
+ """Update fields on multiple issues."""
1465
+ parsed_fields = _parse_fields(fields)
1466
+ if not parsed_fields:
1467
+ fail("at least one --field is required")
1468
+
1469
+ client = _client(ctx)
1470
+ try:
1471
+ result = client.bulk_edit(list(keys), parsed_fields)
1472
+ except AtlassianAPIError as e:
1473
+ fail(str(e))
1474
+
1475
+ if ctx.obj["json"]:
1476
+ emit_json(result)
1477
+ if result["failed"]:
1478
+ raise SystemExit(1)
1479
+ return
1480
+
1481
+ success = result["success"]
1482
+ failed = result["failed"]
1483
+
1484
+ if success:
1485
+ click.echo(f"Updated {len(success)} issue(s):")
1486
+ for key in success:
1487
+ click.echo(f" {key}")
1488
+
1489
+ if failed:
1490
+ click.echo(f"\nFailed {len(failed)} issue(s):", err=True)
1491
+ for item in failed:
1492
+ click.echo(f" {item['key']}: {item['error']}", err=True)
1493
+ raise SystemExit(1)
1494
+
1495
+
1496
+ # ----------------------------- link types -----------------------------
1497
+
1498
+
1499
+ @jira.command("link-types")
1500
+ @click.pass_context
1501
+ def link_types(ctx: click.Context) -> None:
1502
+ """List all available issue link types."""
1503
+ client = _client(ctx)
1504
+ try:
1505
+ types = client.list_link_types()
1506
+ except AtlassianAPIError as e:
1507
+ fail(str(e))
1508
+
1509
+ if ctx.obj["json"]:
1510
+ emit_json({"linkTypes": types})
1511
+ return
1512
+
1513
+ rows = [
1514
+ [t.get("name", ""), t.get("inward", ""), t.get("outward", "")]
1515
+ for t in types
1516
+ ]
1517
+ emit_table(["Name", "Inward", "Outward"], rows, json_mode=False)
1518
+ click.echo(f"\nTotal: {len(types)} link type(s)")
1519
+
1520
+
1521
+
1522
+
1523
+ from atli.jira.agile_commands import register as _register_agile
1524
+
1525
+ _register_agile(jira)