codapact-atlassian 0.1.0__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,6 @@
1
+ """Generated client for Atlassian Cloud."""
2
+
3
+ from .types import * # noqa: F403
4
+ from .client import Client
5
+
6
+ __all__ = ["Client"]
@@ -0,0 +1,6 @@
1
+ """Run the generated CLI with ``python -m``."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
@@ -0,0 +1,323 @@
1
+ """Markdown in, Markdown out for every Atlassian product the coda covers.
2
+
3
+ Jira and Confluence store rich text as Atlassian Document Format (ADF). With
4
+ ``--doc-format markdown`` (the default; ``ATLASSIAN_DOC_FORMAT`` sets it too):
5
+
6
+ * Jira (``jira``, ``agile`` and ``service-desk`` commands): a Markdown string in an issue's
7
+ rich-text fields, a comment ``body`` or a worklog ``comment`` is sent as ADF; every ADF
8
+ document in a response comes back as Markdown (adflux's Jira profile).
9
+ * Confluence (``confluence`` commands): a ``body`` given as a Markdown string, or as
10
+ ``{"representation": "markdown", "value": ...}``, is sent as ``atlas_doc_format``;
11
+ commands that take ``--body-format`` ask for ADF unless told otherwise; ADF bodies in a
12
+ response come back as ``{"representation": "markdown", "value": ...}`` under
13
+ ``markdown`` (adflux's Confluence profile: macros, emoticons, layouts).
14
+
15
+ ``--markdown TEXT|@FILE|@-`` sets the rich text of the command: a Jira issue description,
16
+ comment or worklog, or a Confluence page, blog post or comment body. ``--doc-format adf``
17
+ sends and returns ADF unchanged. ``uvx adflux syntax`` documents the dialect.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import json
24
+ import os
25
+ from typing import Any
26
+
27
+ from adflux import AdfluxError, to_markdown
28
+ from adflux import to_adf as _to_adf
29
+ from codapact.runtime.errors import ValidationError
30
+
31
+ JIRA = "jira"
32
+ CONFLUENCE = "confluence"
33
+ ADF = "atlas_doc_format"
34
+ CHOICES = ("markdown", "adf")
35
+
36
+
37
+ def to_adf(markdown: str, profile: str) -> dict[str, Any]:
38
+ """Markdown to ADF; Markdown adflux cannot read is a usage error, not a crash."""
39
+ try:
40
+ return _to_adf(markdown, profile)
41
+ except AdfluxError as error:
42
+ raise usage(f"cannot convert the Markdown: {error}") from None
43
+
44
+
45
+ def _markdown(value: Any, profile: str) -> Any:
46
+ """ADF (a document or its JSON text) to Markdown; ``value`` back if it is not ADF."""
47
+ try:
48
+ return to_markdown(value, profile)
49
+ except AdfluxError:
50
+ return value # doc-shaped JSON that is not ADF (an entity property, say)
51
+
52
+
53
+ def _bare_adf(value: Any) -> bool:
54
+ return isinstance(value, dict) and value.get("type") == "doc" and isinstance(value.get("content"), list)
55
+
56
+
57
+ def usage(message: str) -> ValidationError:
58
+ """An input error the CLI reports as a usage error (exit 2, structured with JSON)."""
59
+ return ValidationError("--markdown", message)
60
+
61
+
62
+ # ---------------------------------------------------------------- Jira
63
+
64
+
65
+ def is_adf(value: Any) -> bool:
66
+ """Whether ``value`` is an ADF document."""
67
+ return (
68
+ isinstance(value, dict)
69
+ and value.get("type") == "doc"
70
+ and isinstance(value.get("content"), list)
71
+ and "version" in value
72
+ )
73
+
74
+
75
+ def to_wire(value: Any, path: tuple[str, ...]) -> Any:
76
+ """Convert the Markdown string at ``path`` (``*``: each list item) to ADF.
77
+
78
+ Only that exact place changes; a value already ADF, or not a string, is left alone.
79
+ """
80
+ if not path:
81
+ return to_adf(value, JIRA) if isinstance(value, str) else value
82
+ key, rest = path[0], path[1:]
83
+ if key == "*":
84
+ return [to_wire(v, rest) for v in value] if isinstance(value, list) else value
85
+ if isinstance(value, dict) and key in value:
86
+ return {**value, key: to_wire(value[key], rest)}
87
+ return value
88
+
89
+
90
+ def from_wire(value: Any) -> Any:
91
+ """Convert every ADF document in ``value`` to Markdown, recursively."""
92
+ if is_adf(value):
93
+ return _markdown(value, JIRA)
94
+ if isinstance(value, dict):
95
+ return {k: from_wire(v) for k, v in value.items()}
96
+ if isinstance(value, list):
97
+ return [from_wire(v) for v in value]
98
+ return value
99
+
100
+
101
+ # Operations whose request bodies carry ADF. Elsewhere ``description`` and friends are
102
+ # plain strings (project, field and scheme descriptions), so they are left alone.
103
+ SLOTS: dict[str, tuple[str, ...]] = {
104
+ "create_issue": ("fields", "description"),
105
+ "edit_issue": ("fields", "description"),
106
+ "add_comment": ("body",),
107
+ "update_comment": ("body",),
108
+ "add_worklog": ("comment",),
109
+ "update_worklog": ("comment",),
110
+ }
111
+ # Where each operation's request body carries ADF (paths below ``body``; ``*`` is each
112
+ # item of a list). ``fields`` and ``update`` are free-form maps keyed by Jira field id.
113
+ ISSUE_PATHS: tuple[tuple[str, ...], ...] = (
114
+ ("fields", "description"),
115
+ ("fields", "environment"),
116
+ ("update", "description", "*", "set"),
117
+ ("update", "environment", "*", "set"),
118
+ ("update", "comment", "*", "add", "body"),
119
+ ("update", "worklog", "*", "add", "comment"),
120
+ )
121
+ RICH_TEXT: dict[str, tuple[tuple[str, ...], ...]] = {
122
+ "create_issue": ISSUE_PATHS,
123
+ "edit_issue": ISSUE_PATHS,
124
+ "do_transition": ISSUE_PATHS,
125
+ # the Python field name or Jira's own: the hook runs before the body is encoded
126
+ "create_issues": tuple(
127
+ (name, "*", *path) for name in ("issue_updates", "issueUpdates") for path in ISSUE_PATHS
128
+ ),
129
+ "add_comment": (("body",),),
130
+ "update_comment": (("body",),),
131
+ "add_worklog": (("comment",),),
132
+ "update_worklog": (("comment",),),
133
+ "link_issues": (("comment", "body"),),
134
+ }
135
+
136
+
137
+
138
+
139
+ # ---------------------------------------------------------------- Confluence
140
+
141
+
142
+ def _confluence_body(markdown: str) -> dict[str, str]:
143
+ return {"representation": ADF, "value": json.dumps(to_adf(markdown, CONFLUENCE), ensure_ascii=False)}
144
+
145
+
146
+ def confluence_to_wire(value: Any, key: str | None = None) -> Any:
147
+ """Convert Markdown bodies to ADF bodies, recursively."""
148
+ if key == "body" and isinstance(value, str):
149
+ return _confluence_body(value)
150
+ if isinstance(value, dict):
151
+ if value.get("representation") == "markdown" and isinstance(value.get("value"), str):
152
+ return _confluence_body(value["value"])
153
+ return {k: confluence_to_wire(v, k) for k, v in value.items()}
154
+ if isinstance(value, list):
155
+ return [confluence_to_wire(v, key) for v in value]
156
+ return value
157
+
158
+
159
+ def confluence_from_wire(value: Any) -> Any:
160
+ """Convert ADF bodies (and bare ADF documents) in ``value`` to Markdown, recursively."""
161
+ if _bare_adf(value):
162
+ return _markdown(value, CONFLUENCE)
163
+ if isinstance(value, dict):
164
+ if value.get("representation") == ADF and isinstance(value.get("value"), str) and value["value"]:
165
+ return {**value, "representation": "markdown", "value": _markdown(value["value"], CONFLUENCE)}
166
+ out: dict[str, Any] = {}
167
+ for k, v in value.items():
168
+ converted = confluence_from_wire(v)
169
+ if k == ADF and isinstance(converted, dict) and converted.get("representation") == "markdown":
170
+ out["markdown"] = converted
171
+ else:
172
+ out[k] = converted
173
+ return out
174
+ if isinstance(value, list):
175
+ return [confluence_from_wire(v) for v in value]
176
+ return value
177
+
178
+
179
+ # ---------------------------------------------------------------- dispatch
180
+
181
+
182
+ def product(operation: Any) -> str:
183
+ """``confluence`` for Confluence commands, ``jira`` for the rest (Jira, Agile, JSM)."""
184
+ namespace = tuple(getattr(operation, "namespace", ()) or ())
185
+ return CONFLUENCE if namespace[:1] == (CONFLUENCE,) else JIRA
186
+
187
+
188
+ def jira_name(operation: Any) -> str:
189
+ """The operation's Jira name (a name Confluence also has is ``jira_``-prefixed)."""
190
+ return str(getattr(operation, "name", "")).removeprefix("jira_")
191
+
192
+
193
+ class MarkdownHook:
194
+ """Call hook that converts rich text between Markdown and ADF."""
195
+
196
+ def __init__(self, markdown: str | None = None) -> None:
197
+ self.markdown = markdown
198
+
199
+ def before(self, operation: Any, arguments: dict[str, Any]) -> dict[str, Any]:
200
+ if product(operation) == CONFLUENCE:
201
+ return self._confluence(operation, arguments)
202
+ return self._jira(operation, arguments)
203
+
204
+ def _jira(self, operation: Any, arguments: dict[str, Any]) -> dict[str, Any]:
205
+ name = jira_name(operation)
206
+ if self.markdown is not None:
207
+ path = SLOTS.get(name) if tuple(getattr(operation, "namespace", ()))[:1] == ("jira",) else None
208
+ if path is None:
209
+ raise usage(
210
+ "is for Jira issues, comments and worklogs, and Confluence pages, blog posts and comments"
211
+ )
212
+ body = arguments.get("body")
213
+ if body is not None and not isinstance(body, dict):
214
+ raise usage("needs a JSON object body")
215
+ request = dict(body or {})
216
+ target = request
217
+ for key in path[:-1]:
218
+ inner = target.get(key)
219
+ if inner is not None and not isinstance(inner, dict):
220
+ raise usage(f"needs --{key.replace('_', '-')} to be a JSON object")
221
+ target[key] = dict(inner or {})
222
+ target = target[key]
223
+ target[path[-1]] = self.markdown
224
+ arguments = {**arguments, "body": request}
225
+ paths = RICH_TEXT.get(name, ()) if tuple(getattr(operation, "namespace", ()))[:1] == ("jira",) else ()
226
+ body = arguments.get("body")
227
+ if not paths or not isinstance(body, dict):
228
+ return arguments
229
+ for path in paths:
230
+ body = to_wire(body, path)
231
+ return {**arguments, "body": body}
232
+
233
+ def _confluence(self, operation: Any, arguments: dict[str, Any]) -> dict[str, Any]:
234
+ if self.markdown is not None:
235
+ request = arguments.get("body")
236
+ if not isinstance(request, dict):
237
+ raise usage("is for commands that send a page, blog post or comment body")
238
+ arguments = {**arguments, "body": {**request, "body": self.markdown}}
239
+ out = {k: confluence_to_wire(v) if isinstance(v, dict | list) else v for k, v in arguments.items()}
240
+ names = {p.name for p in getattr(operation, "params", ())}
241
+ if "body_format" in names and out.get("body_format") is None:
242
+ out["body_format"] = ADF
243
+ return out
244
+
245
+ def after(self, operation: Any, result: Any) -> Any:
246
+ if product(operation) == CONFLUENCE:
247
+ return confluence_from_wire(result)
248
+ return from_wire(result)
249
+
250
+
251
+ class Extension:
252
+ """``cli.extensions`` entry: the ``--doc-format`` option."""
253
+
254
+ def __init__(self, runtime: Any) -> None:
255
+ self.prefix = getattr(runtime, "env_prefix", "ATLASSIAN")
256
+
257
+ def add_options(self, group: argparse._ArgumentGroup, hidden: bool) -> None:
258
+ group.add_argument(
259
+ "--doc-format",
260
+ choices=CHOICES,
261
+ default=argparse.SUPPRESS,
262
+ help=argparse.SUPPRESS
263
+ if hidden
264
+ else f"rich text as markdown (default) or raw adf JSON (env {self.prefix}_DOC_FORMAT)",
265
+ )
266
+ group.add_argument(
267
+ "--markdown",
268
+ metavar="TEXT|@FILE|@-",
269
+ default=argparse.SUPPRESS,
270
+ help=argparse.SUPPRESS
271
+ if hidden
272
+ else "rich text to send as Markdown (text, @file, @- for stdin): a Jira issue description, "
273
+ "comment or worklog, or a Confluence page, blog post or comment body",
274
+ )
275
+
276
+ def format(self, args: argparse.Namespace) -> str:
277
+ chosen = getattr(args, "doc_format", None) or os.environ.get(f"{self.prefix}_DOC_FORMAT") or "markdown"
278
+ if chosen not in CHOICES:
279
+ raise ValidationError("--doc-format", f"{self.prefix}_DOC_FORMAT must be markdown or adf")
280
+ return chosen
281
+
282
+ def hooks(self, args: argparse.Namespace) -> list[Any]:
283
+ markdown = _read(getattr(args, "markdown", None))
284
+ if self.format(args) != "markdown":
285
+ if markdown is not None:
286
+ raise usage("needs --doc-format markdown")
287
+ return []
288
+ return [MarkdownHook(markdown)]
289
+
290
+ def notes(self) -> list[str]:
291
+ return [
292
+ (
293
+ "Rich text is Markdown in and out: Jira issue descriptions, comments and "
294
+ "worklogs, and Confluence bodies (returned as body.markdown.value). "
295
+ "--markdown TEXT|@file|@- sets it; --doc-format adf sends and returns ADF JSON. "
296
+ "Dialect: uvx adflux syntax; Confluence macros: uvx adflux macros NAME."
297
+ ),
298
+ ]
299
+
300
+
301
+ def _read(value: str | None) -> str | None:
302
+ if value is None:
303
+ return None
304
+ if value == "@-":
305
+ import sys
306
+
307
+ try: # UTF-8 like @file, whatever the console's code page
308
+ return sys.stdin.buffer.read().decode("utf-8")
309
+ except UnicodeError as error:
310
+ raise usage(f"stdin is not UTF-8: {error}") from None
311
+ if value.startswith("@"):
312
+ from pathlib import Path
313
+
314
+ try:
315
+ return Path(value[1:]).read_text(encoding="utf-8")
316
+ except (OSError, UnicodeError) as error:
317
+ raise usage(f"cannot read {value[1:]}: {getattr(error, 'strerror', None) or error}") from None
318
+ return value
319
+
320
+
321
+ def extension(runtime: Any) -> Extension:
322
+ """Factory named in ``cli.extensions``."""
323
+ return Extension(runtime)