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.
@@ -0,0 +1,181 @@
1
+ """Markdown → Confluence storage format conversion.
2
+
3
+ Public entry: ``to_storage(md, *, engine="auto") -> str``.
4
+
5
+ Engines:
6
+ * ``"pandoc"`` — shells out to the system ``pandoc`` binary (best fidelity).
7
+ * ``"python"`` — uses ``markdown-it-py`` (pure Python, zero ext deps).
8
+ * ``"auto"`` — pandoc if on PATH, else python.
9
+
10
+ Code blocks (fenced) become Confluence ``<ac:structured-macro ac:name="code">``
11
+ macros so they render with syntax highlighting.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import html
17
+ import re
18
+ import shutil
19
+ import subprocess
20
+ from functools import lru_cache
21
+
22
+ from markdown_it import MarkdownIt
23
+
24
+
25
+ class MarkdownError(Exception):
26
+ """Raised when markdown-to-storage conversion fails."""
27
+
28
+
29
+ def _code_macro(lang: str, code: str) -> str:
30
+ """Wrap ``code`` in a Confluence code macro with optional language.
31
+
32
+ The body is placed inside CDATA, so HTML-special characters do not need
33
+ escaping. A ``]]>`` sequence in the source is split with the standard
34
+ ``]]]]><![CDATA[>`` pattern to preserve XML well-formedness.
35
+ """
36
+ body = code.replace("]]>", "]]]]><![CDATA[>")
37
+ param = (
38
+ f'<ac:parameter ac:name="language">{lang}</ac:parameter>' if lang else ""
39
+ )
40
+ return (
41
+ f'<ac:structured-macro ac:name="code">{param}'
42
+ f"<ac:plain-text-body><![CDATA[{body}]]></ac:plain-text-body>"
43
+ f"</ac:structured-macro>"
44
+ )
45
+
46
+
47
+ def _render_with_markdown_it(md_text: str) -> str:
48
+ """Convert markdown to Confluence storage XHTML using markdown-it-py."""
49
+ if not md_text:
50
+ return ""
51
+
52
+ # gfm-like enables tables, strikethrough, task lists, autolinks. linkify
53
+ # would need the optional linkify-it-py dep, so we disable it.
54
+ md = MarkdownIt("gfm-like").disable("linkify")
55
+
56
+ def render_fence(self, tokens, idx, options, env): # noqa: ARG001
57
+ token = tokens[idx]
58
+ info = (token.info or "").strip().split(maxsplit=1)
59
+ lang = info[0] if info else ""
60
+ return _code_macro(lang, token.content)
61
+
62
+ md.add_render_rule("fence", render_fence)
63
+ return md.render(md_text).rstrip("\n")
64
+
65
+
66
+ @lru_cache(maxsize=1)
67
+ def _pandoc_available() -> bool:
68
+ """Cached check for pandoc on PATH."""
69
+ return shutil.which("pandoc") is not None
70
+
71
+
72
+ # pandoc html5 with --no-highlight emits one of:
73
+ # <pre><code>...</code></pre> (no language)
74
+ # <pre class="X"><code>...</code></pre> (pandoc 3.x with language)
75
+ # <pre><code class="language-X">...</code></pre> (pandoc 2.x legacy form)
76
+ # We capture both the pre-class and the code-class to support all three shapes.
77
+ _PANDOC_CODE_BLOCK_RE = re.compile(
78
+ r'<pre(?:\s+class="([^"]*)")?\s*>'
79
+ r'<code(?:\s+class="([^"]*)")?\s*>'
80
+ r'(.*?)</code></pre>',
81
+ re.DOTALL,
82
+ )
83
+
84
+
85
+ def _pandoc_code_block_to_macro(match: re.Match[str]) -> str:
86
+ pre_classes = (match.group(1) or "").split()
87
+ code_classes = (match.group(2) or "").split()
88
+ lang = ""
89
+ # Prefer the legacy `language-X` form on <code> (pandoc 2.x, also our
90
+ # markdown-it-py output if it ever flows through here).
91
+ for cls in code_classes + pre_classes:
92
+ if cls.startswith("language-"):
93
+ lang = cls[len("language-") :]
94
+ break
95
+ # Fallback: bare class on <pre> (pandoc 3.x with --no-highlight). Skip the
96
+ # "sourceCode" marker class which pandoc may emit alongside even without
97
+ # highlighting in some configs.
98
+ if not lang:
99
+ for cls in pre_classes:
100
+ if cls and cls != "sourceCode":
101
+ lang = cls
102
+ break
103
+ body = html.unescape(match.group(3))
104
+ # pandoc 3.x strips the trailing newline inside <code>; pandoc 2.x and
105
+ # markdown-it-py preserve it. Normalise to "ends with newline" so the
106
+ # CDATA body matches the markdown source contract regardless of engine.
107
+ if body and not body.endswith("\n"):
108
+ body += "\n"
109
+ return _code_macro(lang, body)
110
+
111
+
112
+ def _render_with_pandoc(md_text: str) -> str:
113
+ """Convert markdown via the system pandoc binary. Caller must have
114
+ verified pandoc is on PATH (or accept a CalledProcessError → MarkdownError).
115
+ """
116
+ if not md_text:
117
+ return ""
118
+ try:
119
+ result = subprocess.run(
120
+ ["pandoc", "-f", "gfm", "-t", "html5", "--wrap=none", "--no-highlight"],
121
+ input=md_text,
122
+ capture_output=True,
123
+ text=True,
124
+ check=True,
125
+ timeout=30,
126
+ )
127
+ except FileNotFoundError as e:
128
+ raise MarkdownError("pandoc not on PATH") from e
129
+ except subprocess.TimeoutExpired as e:
130
+ raise MarkdownError(f"pandoc timeout (>30s)") from e
131
+ except subprocess.CalledProcessError as e:
132
+ raise MarkdownError(f"pandoc failed: {e.stderr.strip()}") from e
133
+
134
+ html_out = result.stdout
135
+ return _PANDOC_CODE_BLOCK_RE.sub(_pandoc_code_block_to_macro, html_out).rstrip("\n")
136
+
137
+
138
+ def _picked_engine(engine: str = "auto") -> str:
139
+ """Resolve the engine string. Raises MarkdownError on bad input or when
140
+ pandoc is explicitly requested but not available.
141
+ """
142
+ if engine == "auto":
143
+ return "pandoc" if _pandoc_available() else "python"
144
+ if engine == "python":
145
+ return "python"
146
+ if engine == "pandoc":
147
+ if not _pandoc_available():
148
+ raise MarkdownError(
149
+ "engine='pandoc' was requested but pandoc is not on PATH"
150
+ )
151
+ return "pandoc"
152
+ raise MarkdownError(f"unknown engine: {engine!r}")
153
+
154
+
155
+ def to_storage(md_text: str, *, engine: str = "auto") -> str:
156
+ """Convert markdown to Confluence storage XHTML.
157
+
158
+ ``engine`` is one of ``"auto"``, ``"pandoc"``, or ``"python"``. The
159
+ default ``"auto"`` prefers pandoc when on PATH, else falls back to
160
+ markdown-it-py. Raises :class:`MarkdownError` on conversion failure or
161
+ when ``engine`` is unknown / unavailable.
162
+ """
163
+ picked = _picked_engine(engine)
164
+ if picked == "pandoc":
165
+ return _render_with_pandoc(md_text)
166
+ return _render_with_markdown_it(md_text)
167
+
168
+
169
+ def to_markdown_macro(md_text: str) -> str:
170
+ """Wrap a markdown document in a Confluence 'markdown' macro.
171
+
172
+ The plugin renders client-side, supports Mermaid, hljs, GFM tables,
173
+ and whatever else the plugin enables. atli does not transform the
174
+ body beyond CDATA-safe escaping of `]]>`.
175
+ """
176
+ body = md_text.replace("]]>", "]]]]><![CDATA[>")
177
+ return (
178
+ '<ac:structured-macro ac:name="markdown">'
179
+ f'<ac:plain-text-body><![CDATA[{body}]]></ac:plain-text-body>'
180
+ '</ac:structured-macro>'
181
+ )
atli/jira/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Jira REST API client and CLI commands."""
atli/jira/agile.py ADDED
@@ -0,0 +1,282 @@
1
+ """Jira Software Agile REST helpers (Server / Data Center)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from atli.client import AtlassianAPIError
8
+ from atli.jira.client import JiraClient
9
+
10
+
11
+ class AgileClient(JiraClient):
12
+ """Extends ``JiraClient`` with ``/rest/agile/1.0`` and project meta APIs."""
13
+
14
+ AGILE = "/rest/agile/1.0"
15
+
16
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
17
+ super().__init__(*args, **kwargs)
18
+ self._epic_fields: dict[str, str] | None = None
19
+
20
+ # ----- discovery -----
21
+
22
+ def epic_fields(self) -> dict[str, str]:
23
+ """Return ``{"name": customfield_…, "link": customfield_…}`` for Classic epics."""
24
+ if self._epic_fields is not None:
25
+ return self._epic_fields
26
+ name_id = link_id = None
27
+ for field in self.get(f"{self.API}/field"):
28
+ custom = (field.get("schema") or {}).get("custom") or ""
29
+ if custom == "com.pyxis.greenhopper.jira:gh-epic-label":
30
+ name_id = field["id"]
31
+ elif custom == "com.pyxis.greenhopper.jira:gh-epic-link":
32
+ link_id = field["id"]
33
+ if not name_id or not link_id:
34
+ raise AtlassianAPIError(
35
+ 400,
36
+ "could not discover Epic Name / Epic Link custom fields on this instance",
37
+ )
38
+ self._epic_fields = {"name": name_id, "link": link_id}
39
+ return self._epic_fields
40
+
41
+ # ----- project / board / release -----
42
+
43
+ def list_projects(self) -> list[dict]:
44
+ data = self.get(f"{self.API}/project")
45
+ return list(data) if isinstance(data, list) else []
46
+
47
+ def list_boards(
48
+ self,
49
+ *,
50
+ project: str | None = None,
51
+ max_results: int = 50,
52
+ ) -> dict:
53
+ params: dict[str, Any] = {"maxResults": max_results}
54
+ if project:
55
+ params["projectKeyOrId"] = project
56
+ return self.get(f"{self.AGILE}/board", params=params)
57
+
58
+ def list_versions(self, project: str) -> list[dict]:
59
+ data = self.get(f"{self.API}/project/{project}/versions")
60
+ return list(data) if isinstance(data, list) else []
61
+
62
+ # ----- epic -----
63
+
64
+ def list_epics(self, project: str, max_results: int = 50) -> dict:
65
+ jql = f"project = {project} AND issuetype = Epic ORDER BY updated DESC"
66
+ return self.search_jql(jql, max_results=max_results, fields="summary,status,issuetype")
67
+
68
+ def epic_issues(self, epic_key: str, max_results: int = 50) -> dict:
69
+ return self.get(
70
+ f"{self.AGILE}/epic/{epic_key}/issue",
71
+ params={"maxResults": max_results},
72
+ )
73
+
74
+ def create_epic(
75
+ self,
76
+ *,
77
+ project: str,
78
+ title: str,
79
+ name: str,
80
+ description: str | None = None,
81
+ ) -> dict:
82
+ fields = self.epic_fields()
83
+ extra: dict[str, Any] = {fields["name"]: name}
84
+ return self.create_issue(
85
+ project=project,
86
+ title=title,
87
+ issue_type="Epic",
88
+ description=description,
89
+ **extra,
90
+ )
91
+
92
+ def epic_add_issues(self, epic_key: str, issues: list[str]) -> dict:
93
+ return self.post(
94
+ f"{self.AGILE}/epic/{epic_key}/issue",
95
+ json={"issues": issues},
96
+ )
97
+
98
+ def epic_remove_issues(self, issues: list[str]) -> dict:
99
+ return self.post(
100
+ f"{self.AGILE}/epic/none/issue",
101
+ json={"issues": issues},
102
+ )
103
+
104
+ # ----- sprint -----
105
+
106
+ def list_sprints(
107
+ self,
108
+ board_id: int,
109
+ *,
110
+ state: str | None = None,
111
+ max_results: int = 50,
112
+ ) -> dict:
113
+ params: dict[str, Any] = {"maxResults": max_results}
114
+ if state:
115
+ params["state"] = state
116
+ return self.get(f"{self.AGILE}/board/{board_id}/sprint", params=params)
117
+
118
+ def get_sprint(self, sprint_id: int) -> dict:
119
+ return self.get(f"{self.AGILE}/sprint/{sprint_id}")
120
+
121
+ def sprint_issues(self, sprint_id: int, max_results: int = 50) -> dict:
122
+ return self.get(
123
+ f"{self.AGILE}/sprint/{sprint_id}/issue",
124
+ params={"maxResults": max_results},
125
+ )
126
+
127
+ def sprint_add_issues(self, sprint_id: int, issues: list[str]) -> dict:
128
+ return self.post(
129
+ f"{self.AGILE}/sprint/{sprint_id}/issue",
130
+ json={"issues": issues},
131
+ )
132
+
133
+ def close_sprint(self, sprint_id: int) -> dict:
134
+ sprint = self.get_sprint(sprint_id)
135
+ if sprint.get("state") == "closed":
136
+ raise AtlassianAPIError(400, f"sprint {sprint_id} is already closed")
137
+ payload = {
138
+ "id": sprint_id,
139
+ "state": "closed",
140
+ "name": sprint.get("name"),
141
+ }
142
+ # preserve dates when present — required by some DC versions
143
+ for key in ("startDate", "endDate", "originBoardId", "goal"):
144
+ if key in sprint and sprint[key] is not None:
145
+ payload[key] = sprint[key]
146
+ return self.put(f"{self.AGILE}/sprint/{sprint_id}", json=payload)
147
+
148
+ def create_sprint(
149
+ self,
150
+ board_id: int,
151
+ name: str,
152
+ *,
153
+ start_date: str | None = None,
154
+ end_date: str | None = None,
155
+ goal: str | None = None,
156
+ ) -> dict:
157
+ """Create a new sprint on a board.
158
+
159
+ Dates must be ISO8601 strings if provided.
160
+ """
161
+ payload: dict[str, Any] = {"name": name, "originBoardId": board_id}
162
+ if start_date:
163
+ payload["startDate"] = start_date
164
+ if end_date:
165
+ payload["endDate"] = end_date
166
+ if goal:
167
+ payload["goal"] = goal
168
+ return self.post(f"{self.AGILE}/sprint", json=payload)
169
+
170
+ def update_sprint(
171
+ self,
172
+ sprint_id: int,
173
+ *,
174
+ name: str | None = None,
175
+ start_date: str | None = None,
176
+ end_date: str | None = None,
177
+ goal: str | None = None,
178
+ ) -> dict:
179
+ """Update sprint name, dates, or goal."""
180
+ sprint = self.get_sprint(sprint_id)
181
+ payload: dict[str, Any] = {
182
+ "id": sprint_id,
183
+ "state": sprint.get("state", "future"),
184
+ }
185
+ if name is not None:
186
+ payload["name"] = name
187
+ if start_date is not None:
188
+ payload["startDate"] = start_date
189
+ if end_date is not None:
190
+ payload["endDate"] = end_date
191
+ if goal is not None:
192
+ payload["goal"] = goal
193
+ return self.put(f"{self.AGILE}/sprint/{sprint_id}", json=payload)
194
+
195
+ def start_sprint(
196
+ self,
197
+ sprint_id: int,
198
+ *,
199
+ start_date: str | None = None,
200
+ end_date: str | None = None,
201
+ ) -> dict:
202
+ """Start a sprint (move from future → active)."""
203
+ sprint = self.get_sprint(sprint_id)
204
+ if sprint.get("state") == "active":
205
+ raise AtlassianAPIError(400, f"sprint {sprint_id} is already active")
206
+ if sprint.get("state") == "closed":
207
+ raise AtlassianAPIError(400, f"sprint {sprint_id} is closed")
208
+ payload: dict[str, Any] = {
209
+ "id": sprint_id,
210
+ "state": "active",
211
+ "name": sprint.get("name"),
212
+ }
213
+ if start_date:
214
+ payload["startDate"] = start_date
215
+ if end_date:
216
+ payload["endDate"] = end_date
217
+ # preserve existing dates if not overridden
218
+ for key in ("startDate", "endDate"):
219
+ if key not in payload and key in sprint and sprint[key]:
220
+ payload[key] = sprint[key]
221
+ if "originBoardId" in sprint:
222
+ payload["originBoardId"] = sprint["originBoardId"]
223
+ if "goal" in sprint and sprint["goal"]:
224
+ payload["goal"] = sprint["goal"]
225
+ return self.put(f"{self.AGILE}/sprint/{sprint_id}", json=payload)
226
+
227
+ def sprint_remove_issues(self, sprint_id: int, issues: list[str]) -> dict:
228
+ """Remove issues from a sprint (move back to backlog)."""
229
+ return self.post(
230
+ f"{self.AGILE}/sprint/{sprint_id}/issue/remove",
231
+ json={"issues": issues},
232
+ )
233
+
234
+ def pick_sprint(
235
+ self,
236
+ board_id: int,
237
+ *,
238
+ current: bool = False,
239
+ prev: bool = False,
240
+ next_: bool = False,
241
+ ) -> dict:
242
+ """Pick current/prev/next sprint for a board.
243
+
244
+ current = first active; prev = most recently closed; next = first future.
245
+ """
246
+ flags = sum(bool(x) for x in (current, prev, next_))
247
+ if flags != 1:
248
+ raise AtlassianAPIError(
249
+ 400, "specify exactly one of --current / --prev / --next"
250
+ )
251
+ if current:
252
+ data = self.list_sprints(board_id, state="active", max_results=50)
253
+ values = data.get("values") or []
254
+ if not values:
255
+ raise AtlassianAPIError(404, f"no active sprint on board {board_id}")
256
+ return values[0]
257
+ if next_:
258
+ data = self.list_sprints(board_id, state="future", max_results=50)
259
+ values = data.get("values") or []
260
+ if not values:
261
+ raise AtlassianAPIError(404, f"no future sprint on board {board_id}")
262
+ return values[0]
263
+ # prev: closed, prefer last completed
264
+ # Fetch all closed sprints to find the most recent
265
+ all_closed = []
266
+ start_at = 0
267
+ max_results = 50
268
+ while True:
269
+ data = self.get(
270
+ f"{self.AGILE}/board/{board_id}/sprint",
271
+ params={"state": "closed", "maxResults": max_results, "startAt": start_at},
272
+ )
273
+ values = data.get("values") or []
274
+ all_closed.extend(values)
275
+ if data.get("isLast", True):
276
+ break
277
+ start_at += len(values)
278
+
279
+ if not all_closed:
280
+ raise AtlassianAPIError(404, f"no closed sprint on board {board_id}")
281
+ # Return the last one (assuming API returns them in chronological order)
282
+ return all_closed[-1]