codapact-confluence 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 The Confluence Cloud REST API v2."""
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,161 @@
1
+ """Markdown in, Markdown out: Confluence page, blog post and comment bodies as Markdown.
2
+
3
+ Confluence stores bodies as Atlassian Document Format (ADF), and also offers ``storage``
4
+ (XHTML) and ``wiki``. With ``--doc-format markdown`` (the default;
5
+ ``CONFLUENCE_DOC_FORMAT`` sets it too):
6
+
7
+ * a ``body`` given as a Markdown string, or as ``{"representation": "markdown", "value":
8
+ ...}``, is sent as ADF (``atlas_doc_format``);
9
+ * commands that take ``--body-format`` ask for ``atlas_doc_format`` unless you choose
10
+ another format, and every ADF body in a response comes back as
11
+ ``{"representation": "markdown", "value": ...}`` (under the key ``markdown``).
12
+
13
+ ``--doc-format adf`` sends and returns bodies unchanged. Conversion uses adflux with its
14
+ Confluence profile: macros (``::toc``, ``:::info``, ``:jira[KEY-1]``...), emoticons,
15
+ layouts. ``uvx adflux syntax`` documents the dialect; ``uvx adflux macros NAME`` shows a
16
+ macro's parameters.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ import os
24
+ from typing import Any
25
+
26
+ from adflux import to_adf, to_markdown
27
+
28
+ PROFILE = "confluence"
29
+ ADF = "atlas_doc_format"
30
+ CHOICES = ("markdown", "adf")
31
+
32
+
33
+ def _adf_body(markdown: str) -> dict[str, str]:
34
+ return {"representation": ADF, "value": json.dumps(to_adf(markdown, PROFILE), ensure_ascii=False)}
35
+
36
+
37
+ def to_wire(value: Any, key: str | None = None) -> Any:
38
+ """Convert Markdown bodies to ADF bodies, recursively."""
39
+ if key == "body" and isinstance(value, str):
40
+ return _adf_body(value)
41
+ if isinstance(value, dict):
42
+ if value.get("representation") == "markdown" and isinstance(value.get("value"), str):
43
+ return _adf_body(value["value"])
44
+ return {k: to_wire(v, k) for k, v in value.items()}
45
+ if isinstance(value, list):
46
+ return [to_wire(v, key) for v in value]
47
+ return value
48
+
49
+
50
+ def is_adf(value: Any) -> bool:
51
+ """Whether ``value`` is an ADF document."""
52
+ return isinstance(value, dict) and value.get("type") == "doc" and isinstance(value.get("content"), list)
53
+
54
+
55
+ def from_wire(value: Any) -> Any:
56
+ """Convert ADF bodies (and bare ADF documents) in ``value`` to Markdown, recursively."""
57
+ if is_adf(value):
58
+ return to_markdown(value, PROFILE)
59
+ if isinstance(value, dict):
60
+ if value.get("representation") == ADF and isinstance(value.get("value"), str) and value["value"]:
61
+ return {**value, "representation": "markdown", "value": to_markdown(value["value"], PROFILE)}
62
+ out: dict[str, Any] = {}
63
+ for k, v in value.items():
64
+ converted = from_wire(v)
65
+ if k == ADF and isinstance(converted, dict) and converted.get("representation") == "markdown":
66
+ out["markdown"] = converted
67
+ else:
68
+ out[k] = converted
69
+ return out
70
+ if isinstance(value, list):
71
+ return [from_wire(v) for v in value]
72
+ return value
73
+
74
+
75
+ class MarkdownHook:
76
+ """Call hook that converts bodies between Markdown and ADF."""
77
+
78
+ def __init__(self, markdown: str | None = None) -> None:
79
+ self.markdown = markdown
80
+
81
+ def before(self, operation: Any, arguments: dict[str, Any]) -> dict[str, Any]:
82
+ if self.markdown is not None:
83
+ request = arguments.get("body")
84
+ if not isinstance(request, dict):
85
+ raise ValueError("--markdown is for commands that send a page, post or comment body")
86
+ arguments = {**arguments, "body": {**request, "body": self.markdown}}
87
+ out = {k: to_wire(v) if isinstance(v, dict | list) else v for k, v in arguments.items()}
88
+ names = {p.name for p in getattr(operation, "params", ())}
89
+ if "body_format" in names and out.get("body_format") is None:
90
+ out["body_format"] = ADF
91
+ return out
92
+
93
+ def after(self, operation: Any, result: Any) -> Any:
94
+ del operation
95
+ return from_wire(result)
96
+
97
+
98
+ class Extension:
99
+ """``cli.extensions`` entry: the ``--doc-format`` option."""
100
+
101
+ def __init__(self, runtime: Any) -> None:
102
+ self.prefix = getattr(runtime, "env_prefix", "CONFLUENCE")
103
+
104
+ def add_options(self, group: argparse._ArgumentGroup, hidden: bool) -> None:
105
+ group.add_argument(
106
+ "--doc-format",
107
+ choices=CHOICES,
108
+ default=argparse.SUPPRESS,
109
+ help=argparse.SUPPRESS
110
+ if hidden
111
+ else f"bodies as markdown (default) or raw adf JSON (env {self.prefix}_DOC_FORMAT)",
112
+ )
113
+ group.add_argument(
114
+ "--markdown",
115
+ metavar="TEXT|@FILE|@-",
116
+ default=argparse.SUPPRESS,
117
+ help=argparse.SUPPRESS
118
+ if hidden
119
+ else "the body to send, as Markdown text, @file, or @- for stdin (instead of --body JSON)",
120
+ )
121
+
122
+ def format(self, args: argparse.Namespace) -> str:
123
+ chosen = getattr(args, "doc_format", None) or os.environ.get(f"{self.prefix}_DOC_FORMAT") or "markdown"
124
+ if chosen not in CHOICES:
125
+ raise ValueError(f"{self.prefix}_DOC_FORMAT must be markdown or adf")
126
+ return chosen
127
+
128
+ def hooks(self, args: argparse.Namespace) -> list[Any]:
129
+ markdown = _read(getattr(args, "markdown", None))
130
+ if self.format(args) != "markdown":
131
+ if markdown is not None:
132
+ raise ValueError("--markdown needs --doc-format markdown")
133
+ return []
134
+ return [MarkdownHook(markdown)]
135
+
136
+ def notes(self) -> list[str]:
137
+ return [
138
+ "Bodies are Markdown in and out: --markdown TEXT|@file|@- sets the body to send; "
139
+ "responses return "
140
+ "body.markdown.value. --doc-format adf keeps ADF JSON. Dialect: uvx adflux syntax; "
141
+ "macros: uvx adflux macros NAME.",
142
+ ]
143
+
144
+
145
+ def _read(value: str | None) -> str | None:
146
+ if value is None:
147
+ return None
148
+ if value == "@-":
149
+ import sys
150
+
151
+ return sys.stdin.read()
152
+ if value.startswith("@"):
153
+ from pathlib import Path
154
+
155
+ return Path(value[1:]).read_text(encoding="utf-8")
156
+ return value
157
+
158
+
159
+ def extension(runtime: Any) -> Extension:
160
+ """Factory named in ``cli.extensions``."""
161
+ return Extension(runtime)