doxtr-cli 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,166 @@
1
+ """Confluence Sphinx export command construction and REST attachment upload helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import mimetypes
6
+ import os
7
+ from collections.abc import Mapping, Sequence
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import requests
12
+
13
+ from .config import ConfluenceTargetConfig
14
+ from .errors import ConfigError, ConfluenceError
15
+
16
+
17
+ def resolve_confluence_token(target: ConfluenceTargetConfig) -> str:
18
+ """Resolve bearer/personal access token from config or standard environment variables."""
19
+ return (
20
+ target.token
21
+ or os.environ.get("DOXTR_CONFLUENCE_TOKEN", "")
22
+ or os.environ.get("CONFLUENCE_PUBLISH_TOKEN", "")
23
+ )
24
+
25
+
26
+ def build_confluence_sphinx_cmd(
27
+ source_dir: Path,
28
+ out_dir: Path,
29
+ doctree_dir: Path,
30
+ target: ConfluenceTargetConfig,
31
+ *,
32
+ extra_defines: Mapping[str, str] | None = None,
33
+ sphinx_build: str = "sphinx-build",
34
+ ) -> list[str]:
35
+ """Construct the ``sphinx-build -b confluence`` command for *target*."""
36
+ if not target.space_key:
37
+ raise ConfigError("Confluence target is enabled but 'space_key' is empty.")
38
+ if not target.server_url:
39
+ raise ConfigError("Confluence target is enabled but 'server_url' is empty.")
40
+
41
+ cmd = [
42
+ sphinx_build,
43
+ "-b",
44
+ "confluence",
45
+ "-d",
46
+ str(doctree_dir),
47
+ "-D",
48
+ "confluence_publish=1",
49
+ "-D",
50
+ f"confluence_space_key={target.space_key}",
51
+ "-D",
52
+ f"confluence_server_url={target.server_url}",
53
+ ]
54
+ if target.parent_page:
55
+ cmd.extend(["-D", f"confluence_parent_page={target.parent_page}"])
56
+ if target.page_title_prefix:
57
+ cmd.extend(["-D", f"confluence_publish_prefix={target.page_title_prefix}"])
58
+
59
+ token = resolve_confluence_token(target)
60
+ if token:
61
+ cmd.extend(["-D", f"confluence_publish_token={token}"])
62
+ elif target.username:
63
+ cmd.extend(["-D", f"confluence_server_user={target.username}"])
64
+ if target.password:
65
+ cmd.extend(["-D", f"confluence_server_pass={target.password}"])
66
+
67
+ if extra_defines:
68
+ for key, value in sorted(extra_defines.items()):
69
+ cmd.extend(["-D", f"{key}={value}"])
70
+
71
+ cmd.extend([str(source_dir), str(out_dir)])
72
+ return cmd
73
+
74
+
75
+ def _build_auth_headers_and_auth(
76
+ target: ConfluenceTargetConfig,
77
+ ) -> tuple[dict[str, str], tuple[str, str] | None]:
78
+ headers = {"X-Atlassian-Token": "nocheck", "Accept": "application/json"}
79
+ token = resolve_confluence_token(target)
80
+ if token:
81
+ headers["Authorization"] = f"Bearer {token}"
82
+ return headers, None
83
+ if target.username and target.password:
84
+ return headers, (target.username, target.password)
85
+ return headers, None
86
+
87
+
88
+ def upload_confluence_attachments(
89
+ target: ConfluenceTargetConfig,
90
+ files: Sequence[Path],
91
+ *,
92
+ session: Any | None = None,
93
+ default_page_title: str = "",
94
+ timeout: float = 30.0,
95
+ ) -> list[dict[str, Any]]:
96
+ """Attach PDF files to the target root documentation page via Confluence REST API."""
97
+ if not files:
98
+ return []
99
+ if not target.server_url or not target.space_key:
100
+ raise ConfigError("Confluence upload requires both 'server_url' and 'space_key'.")
101
+
102
+ page_title = target.root_page_title or target.parent_page or default_page_title
103
+ if (
104
+ target.page_title_prefix
105
+ and page_title
106
+ and not page_title.startswith(target.page_title_prefix)
107
+ ):
108
+ page_title = f"{target.page_title_prefix}{page_title}"
109
+ if not page_title:
110
+ raise ConfigError("Confluence upload requires 'parent_page' or 'root_page_title'.")
111
+
112
+ base_url = target.server_url.rstrip("/")
113
+ api_base = base_url if base_url.endswith("/rest/api") else f"{base_url}/rest/api"
114
+ headers, auth = _build_auth_headers_and_auth(target)
115
+ client: Any = session if session is not None else requests.Session()
116
+
117
+ try:
118
+ lookup_resp = client.get(
119
+ f"{api_base}/content",
120
+ params={"spaceKey": target.space_key, "title": page_title},
121
+ headers=headers,
122
+ auth=auth,
123
+ timeout=timeout,
124
+ )
125
+ except requests.RequestException as exc:
126
+ raise ConfluenceError(f"Failed querying Confluence page '{page_title}': {exc}") from exc
127
+
128
+ if lookup_resp.status_code >= 400:
129
+ raise ConfluenceError(
130
+ f"Confluence page lookup returned HTTP {lookup_resp.status_code}: {lookup_resp.text}"
131
+ )
132
+
133
+ results = lookup_resp.json().get("results") or []
134
+ if not results:
135
+ raise ConfluenceError(
136
+ f"Confluence page '{page_title}' not found in space '{target.space_key}'."
137
+ )
138
+ page_id = str(results[0]["id"])
139
+
140
+ uploaded: list[dict[str, Any]] = []
141
+ for file_path in files:
142
+ if not file_path.is_file():
143
+ raise ConfluenceError(f"Attachment file does not exist: {file_path}")
144
+ mime_type = mimetypes.guess_type(file_path.name)[0] or "application/pdf"
145
+ try:
146
+ with file_path.open("rb") as fh:
147
+ post_resp = client.post(
148
+ f"{api_base}/content/{page_id}/child/attachment",
149
+ files={"file": (file_path.name, fh, mime_type)},
150
+ headers=headers,
151
+ auth=auth,
152
+ timeout=timeout,
153
+ )
154
+ except requests.RequestException as exc:
155
+ raise ConfluenceError(f"Failed uploading attachment '{file_path.name}': {exc}") from exc
156
+
157
+ if post_resp.status_code >= 400:
158
+ raise ConfluenceError(
159
+ f"Confluence attachment upload failed ({post_resp.status_code}) for "
160
+ f"'{file_path.name}': {post_resp.text}"
161
+ )
162
+ uploaded.append(
163
+ {"file": file_path.name, "page_id": page_id, "status": post_resp.status_code}
164
+ )
165
+
166
+ return uploaded
doxtr_cli/errors.py ADDED
@@ -0,0 +1,49 @@
1
+ """Custom exceptions and standardized exit codes for doxtr-cli."""
2
+
3
+ from __future__ import annotations
4
+
5
+ EXIT_OK = 0
6
+ EXIT_FAILURE = 1
7
+ EXIT_CONFIG_ERROR = 2
8
+ EXIT_INTERRUPTED = 130
9
+
10
+
11
+ class DoxtrError(Exception):
12
+ """Base exception carrying a standardized CLI process exit code."""
13
+
14
+ exit_code: int = EXIT_FAILURE
15
+
16
+ def __init__(self, message: str, *, exit_code: int | None = None) -> None:
17
+ super().__init__(message)
18
+ if exit_code is not None:
19
+ self.exit_code = exit_code
20
+
21
+
22
+ class ConfigError(DoxtrError):
23
+ """Raised when configuration cannot be located, parsed, or validated."""
24
+
25
+ exit_code: int = EXIT_CONFIG_ERROR
26
+
27
+
28
+ class MissingBinaryError(DoxtrError):
29
+ """Raised when a required external binary (e.g. sphinx-build, make, nginx) is missing."""
30
+
31
+ exit_code: int = EXIT_CONFIG_ERROR
32
+
33
+
34
+ class BuildError(DoxtrError):
35
+ """Raised when a Sphinx, LaTeX, or packaging build step fails."""
36
+
37
+ exit_code: int = EXIT_FAILURE
38
+
39
+
40
+ class ConfluenceError(DoxtrError):
41
+ """Raised when Confluence export or attachment upload fails."""
42
+
43
+ exit_code: int = EXIT_FAILURE
44
+
45
+
46
+ class ConfirmationDeclinedError(DoxtrError):
47
+ """Raised when the interactive release confirmation gate is declined."""
48
+
49
+ exit_code: int = EXIT_FAILURE
doxtr_cli/git_meta.py ADDED
@@ -0,0 +1,118 @@
1
+ """Git metadata resolution and version stamp formatting for Doxtr builds."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import subprocess
7
+ from dataclasses import dataclass
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class GitMetadata:
14
+ """Resolved Git state for a documentation repository."""
15
+
16
+ tag: str | None
17
+ latest_tag: str | None
18
+ commit_sha: str
19
+ short_sha: str
20
+ branch: str
21
+ dirty: bool
22
+ utc_timestamp: str
23
+
24
+
25
+ def _run_git(cwd: Path, args: list[str]) -> tuple[int, str]:
26
+ git_bin = shutil.which("git")
27
+ if not git_bin:
28
+ return 127, ""
29
+ try:
30
+ proc = subprocess.run(
31
+ [git_bin, *args],
32
+ cwd=str(cwd),
33
+ capture_output=True,
34
+ text=True,
35
+ check=False,
36
+ )
37
+ except OSError:
38
+ return 1, ""
39
+ return proc.returncode, proc.stdout.strip()
40
+
41
+
42
+ def _strip_v_prefix(tag: str) -> str:
43
+ if len(tag) >= 2 and tag[0] in {"v", "V"} and tag[1].isdigit():
44
+ return tag[1:]
45
+ return tag
46
+
47
+
48
+ def collect_git_metadata(cwd: Path, *, now: datetime | None = None) -> GitMetadata:
49
+ """Inspect *cwd* for current Git commit, tag, branch, dirty flag, and UTC timestamp."""
50
+ current_time = now.astimezone(timezone.utc) if now is not None else datetime.now(timezone.utc)
51
+ utc_stamp = current_time.strftime("%Y-%m-%dT%H:%MZ")
52
+
53
+ rc_top, _ = _run_git(cwd, ["rev-parse", "--is-inside-work-tree"])
54
+ if rc_top != 0:
55
+ return GitMetadata(
56
+ tag=None,
57
+ latest_tag=None,
58
+ commit_sha="unknown",
59
+ short_sha="nogit",
60
+ branch="unknown",
61
+ dirty=False,
62
+ utc_timestamp=utc_stamp,
63
+ )
64
+
65
+ rc_sha, commit_sha = _run_git(cwd, ["rev-parse", "HEAD"])
66
+ if rc_sha != 0 or not commit_sha:
67
+ commit_sha = "unknown"
68
+
69
+ rc_short, short_sha = _run_git(cwd, ["rev-parse", "--short=7", "HEAD"])
70
+ if rc_short != 0 or not short_sha:
71
+ short_sha = commit_sha[:7] if commit_sha != "unknown" else "unborn"
72
+
73
+ rc_branch, branch = _run_git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"])
74
+ if rc_branch != 0 or not branch:
75
+ branch = "detached"
76
+
77
+ rc_tag, exact_tag = _run_git(cwd, ["describe", "--tags", "--exact-match", "HEAD"])
78
+ tag = exact_tag if rc_tag == 0 and exact_tag else None
79
+
80
+ rc_latest, nearest_tag = _run_git(cwd, ["describe", "--tags", "--abbrev=0"])
81
+ latest_tag = nearest_tag if rc_latest == 0 and nearest_tag else None
82
+
83
+ rc_status, status_out = _run_git(cwd, ["status", "--porcelain"])
84
+ dirty = bool(rc_status == 0 and status_out)
85
+
86
+ return GitMetadata(
87
+ tag=tag,
88
+ latest_tag=latest_tag,
89
+ commit_sha=commit_sha,
90
+ short_sha=short_sha,
91
+ branch=branch,
92
+ dirty=dirty,
93
+ utc_timestamp=utc_stamp,
94
+ )
95
+
96
+
97
+ def resolve_release_version(meta: GitMetadata, fallback: str = "0.1.0") -> str:
98
+ """Resolve the clean release version string from exact/nearest Git tag or fallback."""
99
+ if meta.tag:
100
+ return _strip_v_prefix(meta.tag)
101
+ if meta.latest_tag:
102
+ return _strip_v_prefix(meta.latest_tag)
103
+ return fallback
104
+
105
+
106
+ def resolve_test_short_version(meta: GitMetadata) -> str:
107
+ """Resolve short version identifier (tag if exact-matched, else short commit SHA)."""
108
+ if meta.tag:
109
+ return _strip_v_prefix(meta.tag)
110
+ return meta.short_sha
111
+
112
+
113
+ def format_test_stamp(meta: GitMetadata, base_version: str | None = None) -> str:
114
+ """Build a detailed staging stamp like ``0.1.0+g4a91f2c.main (2026-11-28T18:30Z)``."""
115
+ base = base_version or resolve_release_version(meta)
116
+ dirty_suffix = "-dirty" if meta.dirty else ""
117
+ safe_branch = meta.branch.replace("/", "-")
118
+ return f"{base}+g{meta.short_sha}.{safe_branch}{dirty_suffix} ({meta.utc_timestamp})"
doxtr_cli/prompts.py ADDED
@@ -0,0 +1,89 @@
1
+ """Strict interactive confirmation gate for production releases."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+ from .errors import ConfirmationDeclinedError
10
+
11
+ CONFIRMATION_PROMPT = "Type 'yes' and press Enter to start publishing this release: "
12
+ CANCELLED_MESSAGE = "Cancelled; nothing published."
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class ReleaseSummary:
17
+ """Human-readable summary printed before prompting for production release confirmation."""
18
+
19
+ project_name: str
20
+ version: str
21
+ commit_sha: str
22
+ branch: str
23
+ dirty: bool
24
+ light_pdf: Path | None = None
25
+ dark_pdf: Path | None = None
26
+ html_dir: Path | None = None
27
+ downloads_dir: Path | None = None
28
+ confluence_enabled: bool = False
29
+ confluence_server_url: str = ""
30
+ confluence_space_key: str = ""
31
+ confluence_parent_page: str = ""
32
+ confluence_attachments: list[str] = field(default_factory=list)
33
+
34
+
35
+ def format_release_summary(summary: ReleaseSummary) -> str:
36
+ """Format a multi-line production release summary including dirty-tree warnings."""
37
+ lines = [
38
+ "=== Doxtr Production Release Summary ===",
39
+ f"Project: {summary.project_name}",
40
+ f"Version: {summary.version}",
41
+ f"Git Commit: {summary.commit_sha} (branch: {summary.branch})",
42
+ ]
43
+ if summary.dirty:
44
+ lines.append("WARNING: Workspace has uncommitted local changes (dirty tree)!")
45
+
46
+ lines.append(f"Light PDF: {summary.light_pdf if summary.light_pdf else '(skipped)'}")
47
+ lines.append(f"Dark PDF: {summary.dark_pdf if summary.dark_pdf else '(skipped)'}")
48
+ lines.append(f"HTML Root: {summary.html_dir if summary.html_dir else '(skipped)'}")
49
+ lines.append(f"Downloads: {summary.downloads_dir if summary.downloads_dir else '(disabled)'}")
50
+
51
+ if summary.confluence_enabled:
52
+ attachments = ", ".join(summary.confluence_attachments) or "(none)"
53
+ lines.extend(
54
+ [
55
+ f"Confluence: {summary.confluence_server_url or '(unset URL)'}",
56
+ f"Space Key: {summary.confluence_space_key or '(unset space)'}",
57
+ f"Parent: {summary.confluence_parent_page or '(root)'}",
58
+ f"Attach PDF: {attachments}",
59
+ ]
60
+ )
61
+ else:
62
+ lines.append("Confluence: (disabled)")
63
+ lines.append("========================================")
64
+ return "\n".join(lines)
65
+
66
+
67
+ def confirm_release(
68
+ summary: ReleaseSummary,
69
+ *,
70
+ input_fn: Callable[[str], str] = input,
71
+ output_fn: Callable[[str], None] = print,
72
+ ) -> bool:
73
+ """Print *summary* and require exact literal ``'yes'`` + Enter to continue.
74
+
75
+ Rejects empty input, ``'y'``, ``'Y'``, ``'YES'``, whitespace, ``'true'``,
76
+ ``'no'``, and EOF with :class:`ConfirmationDeclinedError` (exit code 1).
77
+ ``KeyboardInterrupt`` propagates directly (exit code 130).
78
+ """
79
+ output_fn(format_release_summary(summary))
80
+ try:
81
+ response = input_fn(CONFIRMATION_PROMPT)
82
+ except EOFError as exc:
83
+ output_fn(CANCELLED_MESSAGE)
84
+ raise ConfirmationDeclinedError(CANCELLED_MESSAGE) from exc
85
+
86
+ if response != "yes":
87
+ output_fn(CANCELLED_MESSAGE)
88
+ raise ConfirmationDeclinedError(CANCELLED_MESSAGE)
89
+ return True