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/client.py ADDED
@@ -0,0 +1,491 @@
1
+ """Jira REST API client (Server / Data Center)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from atli.client import AtlassianAPIError, AtlassianClient
8
+
9
+
10
+ class JiraClient(AtlassianClient):
11
+ API = "/rest/api/2"
12
+
13
+ def get_issue(self, key: str, fields: str | None = None) -> dict:
14
+ if fields:
15
+ return self.get(f"{self.API}/issue/{key}", params={"fields": fields})
16
+ return self.get(f"{self.API}/issue/{key}")
17
+
18
+ def create_issue(
19
+ self,
20
+ project: str,
21
+ title: str,
22
+ issue_type: str,
23
+ description: str | None = None,
24
+ assignee: str | None = None,
25
+ **extra_fields: Any,
26
+ ) -> dict:
27
+ fields: dict[str, Any] = {
28
+ "project": {"key": project},
29
+ "summary": title,
30
+ "issuetype": {"name": issue_type},
31
+ }
32
+ if description:
33
+ fields["description"] = description
34
+ if assignee:
35
+ fields["assignee"] = {"name": assignee}
36
+ fields.update(extra_fields)
37
+ return self.post(f"{self.API}/issue", json={"fields": fields})
38
+
39
+ def update_issue(self, key: str, fields: dict[str, Any]) -> dict:
40
+ return self.put(f"{self.API}/issue/{key}", json={"fields": fields})
41
+
42
+ def assign_issue(self, key: str, assignee: str | None) -> dict:
43
+ """Set assignee by username, or ``None`` to unassign."""
44
+ value: dict[str, str] | None
45
+ value = {"name": assignee} if assignee is not None else None
46
+ return self.put(f"{self.API}/issue/{key}", json={"fields": {"assignee": value}})
47
+
48
+ def search_jql(self, jql: str, max_results: int = 50, fields: str | None = None) -> dict:
49
+ # Validate max_results is within reasonable bounds
50
+ if max_results < 1 or max_results > 1000:
51
+ raise AtlassianAPIError(400, "max_results must be between 1 and 1000")
52
+ params: dict[str, Any] = {"jql": jql, "maxResults": max_results}
53
+ if fields:
54
+ params["fields"] = fields
55
+ return self.get(f"{self.API}/search", params=params)
56
+
57
+ def add_comment(self, key: str, text: str, *, internal: bool = False) -> dict:
58
+ payload: dict[str, Any] = {"body": text}
59
+ if internal:
60
+ # Jira Service Management / SD marker (same as jira-cli).
61
+ payload["properties"] = [
62
+ {"key": "sd.public.comment", "value": {"internal": True}}
63
+ ]
64
+ return self.post(f"{self.API}/issue/{key}/comment", json=payload)
65
+
66
+ def list_comments(self, key: str, max_results: int = 50) -> dict:
67
+ """Return all comments on an issue."""
68
+ return self.get(
69
+ f"{self.API}/issue/{key}/comment",
70
+ params={"maxResults": max_results},
71
+ )
72
+
73
+ def update_comment(
74
+ self, key: str, comment_id: str, text: str, *, internal: bool = False
75
+ ) -> dict:
76
+ """Update the body of an existing comment."""
77
+ payload: dict[str, Any] = {"body": text}
78
+ if internal:
79
+ payload["properties"] = [
80
+ {"key": "sd.public.comment", "value": {"internal": True}}
81
+ ]
82
+ return self.put(
83
+ f"{self.API}/issue/{key}/comment/{comment_id}", json=payload
84
+ )
85
+
86
+ def delete_comment(self, key: str, comment_id: str) -> dict:
87
+ """Delete a comment by ID."""
88
+ return self.delete(f"{self.API}/issue/{key}/comment/{comment_id}")
89
+
90
+ def get_transitions(self, key: str) -> list[dict]:
91
+ data = self.get(f"{self.API}/issue/{key}/transitions")
92
+ return list(data.get("transitions", []))
93
+
94
+ def transition(
95
+ self,
96
+ key: str,
97
+ target_status: str,
98
+ *,
99
+ comment: str | None = None,
100
+ resolution: str | None = None,
101
+ assignee: str | None = None,
102
+ ) -> None:
103
+ """Transition `key` to a state whose name matches `target_status`.
104
+
105
+ Looks up available transitions case-insensitively and posts the
106
+ first match. Raises AtlassianAPIError when no transition matches.
107
+
108
+ Optional ``comment``, ``resolution``, and ``assignee`` are attached to
109
+ the transition payload when provided (workflow must allow them).
110
+ """
111
+ transitions = self.get_transitions(key)
112
+ target = target_status.casefold()
113
+ match = next(
114
+ (
115
+ t
116
+ for t in transitions
117
+ if t.get("name", "").casefold() == target
118
+ or t.get("to", {}).get("name", "").casefold() == target
119
+ ),
120
+ None,
121
+ )
122
+ if match is None:
123
+ available = ", ".join(t.get("name", "?") for t in transitions) or "(none)"
124
+ raise AtlassianAPIError(
125
+ 400,
126
+ f"no transition '{target_status}' available for {key}. "
127
+ f"Available: {available}",
128
+ )
129
+ payload: dict[str, Any] = {"transition": {"id": match["id"]}}
130
+ if comment is not None:
131
+ payload["update"] = {"comment": [{"add": {"body": comment}}]}
132
+ fields: dict[str, Any] = {}
133
+ if resolution is not None:
134
+ fields["resolution"] = {"name": resolution}
135
+ if assignee is not None:
136
+ if assignee.casefold() in {"x", "none"}:
137
+ fields["assignee"] = None
138
+ else:
139
+ fields["assignee"] = {"name": assignee}
140
+ if fields:
141
+ payload["fields"] = fields
142
+ self.post(f"{self.API}/issue/{key}/transitions", json=payload)
143
+
144
+ def myself(self) -> dict:
145
+ return self.get(f"{self.API}/myself")
146
+
147
+ def list_link_types(self) -> list[dict]:
148
+ data = self.get(f"{self.API}/issueLinkType")
149
+ return list(data.get("issueLinkTypes", []))
150
+
151
+ def link_issues(self, inward: str, outward: str, link_type: str) -> dict:
152
+ """Create an issue link. ``inward`` / ``outward`` match Jira link semantics."""
153
+ return self.post(
154
+ f"{self.API}/issueLink",
155
+ json={
156
+ "type": {"name": link_type},
157
+ "inwardIssue": {"key": inward},
158
+ "outwardIssue": {"key": outward},
159
+ },
160
+ )
161
+
162
+ def find_link_id(self, key_a: str, key_b: str) -> str:
163
+ """Return the issueLink id connecting ``key_a`` and ``key_b``."""
164
+ issue = self.get_issue(key_a, fields="issuelinks")
165
+ for link in issue.get("fields", {}).get("issuelinks", []) or []:
166
+ inward = (link.get("inwardIssue") or {}).get("key")
167
+ outward = (link.get("outwardIssue") or {}).get("key")
168
+ if inward == key_b or outward == key_b:
169
+ # Defensive: link.get('id') may be None
170
+ link_id = link.get("id")
171
+ if link_id is not None:
172
+ return str(link_id)
173
+ raise AtlassianAPIError(
174
+ 404, f"no link found between {key_a} and {key_b}"
175
+ )
176
+
177
+ def unlink_issues(self, key_a: str, key_b: str) -> dict:
178
+ link_id = self.find_link_id(key_a, key_b)
179
+ return self.delete(f"{self.API}/issueLink/{link_id}")
180
+
181
+ def add_remote_link(self, key: str, url: str, title: str | None = None) -> dict:
182
+ return self.post(
183
+ f"{self.API}/issue/{key}/remotelink",
184
+ json={"object": {"url": url, "title": title or url}},
185
+ )
186
+
187
+ def list_remote_links(self, key: str) -> list[dict]:
188
+ """Return all remote links on an issue."""
189
+ data = self.get(f"{self.API}/issue/{key}/remotelink")
190
+ return data if isinstance(data, list) else []
191
+
192
+ def update_remote_link(
193
+ self, key: str, link_id: str, url: str, title: str | None = None
194
+ ) -> dict:
195
+ """Update the URL and/or title of a remote link."""
196
+ return self.put(
197
+ f"{self.API}/issue/{key}/remotelink/{link_id}",
198
+ json={"object": {"url": url, "title": title or url}},
199
+ )
200
+
201
+ def delete_remote_link(self, key: str, link_id: str) -> dict:
202
+ """Delete a remote link by ID."""
203
+ return self.delete(f"{self.API}/issue/{key}/remotelink/{link_id}")
204
+
205
+ def search_users(self, query: str, max_results: int = 20) -> list[dict]:
206
+ """Search users by username / display name (fuzzy)."""
207
+ data = self.get(
208
+ f"{self.API}/user/search",
209
+ params={"username": query, "maxResults": max_results},
210
+ )
211
+ return data if isinstance(data, list) else []
212
+
213
+ def search_assignable_users(
214
+ self, query: str, project: str | None = None, issue: str | None = None, max_results: int = 20
215
+ ) -> list[dict]:
216
+ """Search users assignable to a project or specific issue."""
217
+ params: dict[str, Any] = {"username": query, "maxResults": max_results}
218
+ if issue:
219
+ params["issueKey"] = issue
220
+ elif project:
221
+ params["project"] = project
222
+ data = self.get(f"{self.API}/user/assignable/search", params=params)
223
+ return data if isinstance(data, list) else []
224
+
225
+
226
+ def delete_issue(self, key: str, *, cascade: bool = False) -> dict:
227
+ if cascade:
228
+ return self.delete(
229
+ f"{self.API}/issue/{key}", params={"deleteSubtasks": "true"}
230
+ )
231
+ return self.delete(f"{self.API}/issue/{key}")
232
+
233
+ def add_worklog(
234
+ self,
235
+ key: str,
236
+ time_spent: str,
237
+ *,
238
+ comment: str | None = None,
239
+ ) -> dict:
240
+ payload: dict[str, Any] = {"timeSpent": time_spent}
241
+ if comment is not None:
242
+ payload["comment"] = comment
243
+ return self.post(f"{self.API}/issue/{key}/worklog", json=payload)
244
+
245
+ def list_worklogs(self, key: str) -> dict:
246
+ """Return all worklogs on an issue."""
247
+ return self.get(f"{self.API}/issue/{key}/worklog")
248
+
249
+ def update_worklog(
250
+ self,
251
+ key: str,
252
+ worklog_id: str,
253
+ time_spent: str,
254
+ *,
255
+ comment: str | None = None,
256
+ ) -> dict:
257
+ """Update time_spent (and optionally comment) on an existing worklog."""
258
+ payload: dict[str, Any] = {"timeSpent": time_spent}
259
+ if comment is not None:
260
+ payload["comment"] = comment
261
+ return self.put(
262
+ f"{self.API}/issue/{key}/worklog/{worklog_id}", json=payload
263
+ )
264
+
265
+ def delete_worklog(self, key: str, worklog_id: str) -> dict:
266
+ """Delete a worklog entry."""
267
+ return self.delete(f"{self.API}/issue/{key}/worklog/{worklog_id}")
268
+
269
+ def watch_issue(self, key: str, username: str) -> dict:
270
+ """Add ``username`` as a watcher. Body is a JSON string (Jira API quirk)."""
271
+ return self.post(f"{self.API}/issue/{key}/watchers", json=username)
272
+
273
+ def list_watchers(self, key: str) -> dict:
274
+ """Return the full watchers response (includes isWatching + watchers list)."""
275
+ return self.get(f"{self.API}/issue/{key}/watchers")
276
+
277
+ def unwatch_issue(self, key: str, username: str) -> dict:
278
+ """Remove ``username`` from the watchers list."""
279
+ return self.delete(
280
+ f"{self.API}/issue/{key}/watchers",
281
+ params={"username": username},
282
+ )
283
+
284
+ def bulk_create_issues(self, issue_updates: list[dict]) -> dict:
285
+ """Create multiple issues in one request.
286
+
287
+ Each element of ``issue_updates`` must be a dict with a ``fields`` key,
288
+ same shape as the single-issue create payload.
289
+
290
+ Returns the ``issueUpdates`` bulk response (list of ``{id, key}``).
291
+ """
292
+ return self.post(
293
+ f"{self.API}/issue/bulk",
294
+ json={"issueUpdates": issue_updates},
295
+ )
296
+
297
+ def get_priorities(self) -> list[dict]:
298
+ """Return all configured priorities."""
299
+ data = self.get(f"{self.API}/priority")
300
+ return data if isinstance(data, list) else []
301
+
302
+ def get_issue_types(self) -> list[dict]:
303
+ """Return all issue types."""
304
+ data = self.get(f"{self.API}/issuetype")
305
+ return data if isinstance(data, list) else []
306
+
307
+ def get_statuses(self) -> list[dict]:
308
+ """Return all statuses (global list; per-project statuses via project API)."""
309
+ data = self.get(f"{self.API}/status")
310
+ return data if isinstance(data, list) else []
311
+
312
+ def get_resolutions(self) -> list[dict]:
313
+ """Return all resolutions."""
314
+ data = self.get(f"{self.API}/resolution")
315
+ return data if isinstance(data, list) else []
316
+
317
+ def get_editmeta(self, key: str) -> dict:
318
+ """Return the edit metadata (available fields and their schemas) for an issue."""
319
+ return self.get(f"{self.API}/issue/{key}/editmeta")
320
+
321
+ def get_create_meta(
322
+ self, project_key: str | None = None, issue_type: str | None = None
323
+ ) -> dict:
324
+ """Return createmeta (field schemas for creating issues).
325
+
326
+ Optionally filter to a specific project and/or issue type.
327
+ """
328
+ params: dict[str, Any] = {"expand": "projects.issuetypes.fields"}
329
+ if project_key:
330
+ params["projectKeys"] = project_key
331
+ if issue_type:
332
+ params["issuetypeNames"] = issue_type
333
+ return self.get(f"{self.API}/issue/createmeta", params=params)
334
+
335
+ def clone_issue(
336
+ self,
337
+ key: str,
338
+ *,
339
+ summary: str | None = None,
340
+ replace: list[tuple[str, str]] | None = None,
341
+ assignee: str | None = None,
342
+ ) -> dict:
343
+ """Clone an issue by re-creating selected fields.
344
+
345
+ ``replace`` is a list of ``(old, new)`` applied to summary and description
346
+ (case-sensitive substring replace).
347
+ """
348
+ src = self.get_issue(
349
+ key,
350
+ fields="summary,description,issuetype,priority,labels,components,assignee,project",
351
+ )
352
+ fields = src.get("fields") or {}
353
+ new_summary = summary if summary is not None else (fields.get("summary") or "")
354
+ new_desc = fields.get("description")
355
+ if new_desc is None:
356
+ new_desc_str: str | None = None
357
+ else:
358
+ new_desc_str = str(new_desc)
359
+ if replace:
360
+ for old, new in replace:
361
+ new_summary = new_summary.replace(old, new)
362
+ if new_desc_str is not None:
363
+ new_desc_str = new_desc_str.replace(old, new)
364
+
365
+ project_key = (fields.get("project") or {}).get("key")
366
+ issue_type = (fields.get("issuetype") or {}).get("name") or "Task"
367
+ if not project_key:
368
+ raise AtlassianAPIError(400, f"cannot clone {key}: missing project")
369
+
370
+ extra: dict[str, Any] = {}
371
+ # Defensive: priority may be None
372
+ if fields.get("priority"):
373
+ pname = (fields.get("priority") or {}).get("name")
374
+ if pname:
375
+ extra["priority"] = {"name": pname}
376
+ # Defensive: labels may be None
377
+ if fields.get("labels") is not None:
378
+ extra["labels"] = list(fields.get("labels") or [])
379
+ if fields.get("components"):
380
+ extra["components"] = [
381
+ {"name": c["name"]} for c in fields["components"] if c.get("name")
382
+ ]
383
+
384
+ assignee_name = assignee
385
+ if assignee_name is None and fields.get("assignee"):
386
+ assignee_name = fields["assignee"].get("name")
387
+
388
+ return self.create_issue(
389
+ project=project_key,
390
+ title=new_summary,
391
+ issue_type=issue_type,
392
+ description=new_desc_str,
393
+ assignee=assignee_name,
394
+ **extra,
395
+ )
396
+
397
+ # ----------------------------- filters -----------------------------
398
+
399
+ def list_filters(self) -> list[dict]:
400
+ """List all filters visible to the current user."""
401
+ result = self.get(f"{self.API}/filter/favourite")
402
+ return result if isinstance(result, list) else []
403
+
404
+ def get_filter(self, filter_id: str) -> dict:
405
+ """Get filter details by ID."""
406
+ return self.get(f"{self.API}/filter/{filter_id}")
407
+
408
+ def create_filter(
409
+ self, name: str, jql: str, description: str | None = None, favourite: bool = False
410
+ ) -> dict:
411
+ """Create a new filter."""
412
+ payload: dict[str, Any] = {"name": name, "jql": jql, "favourite": favourite}
413
+ if description:
414
+ payload["description"] = description
415
+ return self.post(f"{self.API}/filter", json=payload)
416
+
417
+ def update_filter(
418
+ self,
419
+ filter_id: str,
420
+ name: str | None = None,
421
+ jql: str | None = None,
422
+ description: str | None = None,
423
+ favourite: bool | None = None,
424
+ ) -> dict:
425
+ """Update filter properties."""
426
+ payload: dict[str, Any] = {}
427
+ if name is not None:
428
+ payload["name"] = name
429
+ if jql is not None:
430
+ payload["jql"] = jql
431
+ if description is not None:
432
+ payload["description"] = description
433
+ if favourite is not None:
434
+ payload["favourite"] = favourite
435
+ return self.put(f"{self.API}/filter/{filter_id}", json=payload)
436
+
437
+ def delete_filter(self, filter_id: str) -> dict:
438
+ """Delete a filter."""
439
+ return self.delete(f"{self.API}/filter/{filter_id}")
440
+
441
+ def run_filter(self, filter_id: str, max_results: int = 50) -> dict:
442
+ """Execute a filter and return matching issues."""
443
+ filter_data = self.get_filter(filter_id)
444
+ jql = filter_data.get("jql", "")
445
+ if not jql:
446
+ raise AtlassianAPIError(400, f"filter {filter_id} has no JQL")
447
+ return self.search_jql(jql, max_results=max_results)
448
+
449
+ # ----------------------------- bulk operations -----------------------------
450
+
451
+ def bulk_transition(
452
+ self, keys: list[str], transition_name: str, comment: str | None = None
453
+ ) -> dict:
454
+ """Transition multiple issues. Returns summary of successes and failures."""
455
+ results = {"success": [], "failed": []}
456
+ for key in keys:
457
+ try:
458
+ self.transition(key, transition_name, comment=comment)
459
+ results["success"].append(key)
460
+ except AtlassianAPIError as e:
461
+ results["failed"].append({"key": key, "error": str(e)})
462
+ return results
463
+
464
+ def bulk_assign(self, keys: list[str], assignee: str | None) -> dict:
465
+ """Assign multiple issues. Returns summary of successes and failures."""
466
+ results = {"success": [], "failed": []}
467
+ for key in keys:
468
+ try:
469
+ self.assign_issue(key, assignee)
470
+ results["success"].append(key)
471
+ except AtlassianAPIError as e:
472
+ results["failed"].append({"key": key, "error": str(e)})
473
+ return results
474
+
475
+ def bulk_edit(self, keys: list[str], fields: dict[str, Any]) -> dict:
476
+ """Update fields on multiple issues. Returns summary of successes and failures."""
477
+ results = {"success": [], "failed": []}
478
+ for key in keys:
479
+ try:
480
+ self.update_issue(key, fields)
481
+ results["success"].append(key)
482
+ except AtlassianAPIError as e:
483
+ results["failed"].append({"key": key, "error": str(e)})
484
+ return results
485
+
486
+ # ----------------------------- link types -----------------------------
487
+
488
+ def list_link_types(self) -> list[dict]:
489
+ """List all available issue link types."""
490
+ result = self.get(f"{self.API}/issueLinkType")
491
+ return result.get("issueLinkTypes", [])