themadoc 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.
themadoc/__about__.py ADDED
@@ -0,0 +1,4 @@
1
+ # src/themadoc/__about__.py
2
+ """ThemAdoc - Themed AsciiDoc document converter powered by Asciidoctor and Pandoc"""
3
+
4
+ __version__ = "0.1.0"
themadoc/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ # src/themadoc/__init__.py
2
+ """ThemAdoc - Themed AsciiDoc document converter powered by Asciidoctor and Pandoc"""
themadoc/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ # src/themadoc/__main__.py
2
+ """Entry point for ThemAdoc CLI."""
3
+
4
+ from .cli import main
5
+
6
+ if __name__ == "__main__":
7
+ raise SystemExit(main())
@@ -0,0 +1,110 @@
1
+ # src/themadoc/adoc_normalize.py
2
+ """Normalize AsciiDoc files while protecting comments and literal blocks."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import re
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ LITERAL_DELIMITERS = {
12
+ "----",
13
+ "....",
14
+ "++++",
15
+ "****",
16
+ "____",
17
+ "====",
18
+ "--",
19
+ "```",
20
+ "~~~",
21
+ }
22
+
23
+
24
+ def normalize_adoc(text: str) -> str:
25
+ """Normalize AsciiDoc text while protecting blocks and normalizing comments."""
26
+ result: list[str] = []
27
+ in_block_comment = False
28
+ in_literal_block: str | None = None
29
+
30
+ for line in text.splitlines(keepends=True):
31
+ stripped = line.strip()
32
+
33
+ if in_block_comment:
34
+ result.append(line)
35
+ if stripped == "////":
36
+ in_block_comment = False
37
+ continue
38
+
39
+ if in_literal_block is not None:
40
+ result.append(line)
41
+ if stripped == in_literal_block:
42
+ in_literal_block = None
43
+ continue
44
+
45
+ if stripped == "////":
46
+ in_block_comment = True
47
+ result.append(line)
48
+ continue
49
+
50
+ if stripped in LITERAL_DELIMITERS:
51
+ in_literal_block = stripped
52
+ result.append(line)
53
+ continue
54
+
55
+ match = re.match(r"^([ \t]*)//(?!/)(.*?)(\r?\n)?$", line)
56
+ if match:
57
+ indent, body, newline = match.groups()
58
+ if not body or not body[0].isspace():
59
+ body = " " + body
60
+ line = indent + "//" + body + (newline or "")
61
+
62
+ result.append(line)
63
+
64
+ return "".join(result)
65
+
66
+
67
+ def main() -> int:
68
+ parser = argparse.ArgumentParser(
69
+ description="Normalize AsciiDoc files while protecting blocks and comments."
70
+ )
71
+ parser.add_argument(
72
+ "-i",
73
+ "--input",
74
+ type=Path,
75
+ default=None,
76
+ help="Input AsciiDoc file (default: stdin)",
77
+ )
78
+ parser.add_argument(
79
+ "-o",
80
+ "--output",
81
+ type=Path,
82
+ default=None,
83
+ help="Output AsciiDoc file (default: stdout)",
84
+ )
85
+ args = parser.parse_args()
86
+
87
+ try:
88
+ if args.input:
89
+ if not args.input.is_file():
90
+ parser.error(f"Input file not found: {args.input}")
91
+ text = args.input.read_text(encoding="utf-8")
92
+ else:
93
+ text = sys.stdin.read()
94
+
95
+ normalized = normalize_adoc(text)
96
+
97
+ if args.output:
98
+ args.output.write_text(normalized, encoding="utf-8")
99
+ else:
100
+ sys.stdout.write(normalized)
101
+
102
+ except (OSError, ValueError) as error:
103
+ print(f"ERROR: {error}", file=sys.stderr)
104
+ return 1
105
+
106
+ return 0
107
+
108
+
109
+ if __name__ == "__main__":
110
+ raise SystemExit(main())
themadoc/cli.py ADDED
@@ -0,0 +1,278 @@
1
+ # src/themadoc/cli.py
2
+ """Build an AsciiDoc project to HTML, PDF, and/or ODT."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import tempfile
8
+ from pathlib import Path
9
+
10
+ from .config import VALID_FORMATS, BuildConfig, load_config
11
+ from .converters import get_converter
12
+ from .utils import log
13
+
14
+
15
+ def find_project_root(source_file: Path) -> Path:
16
+ """Find project root by searching upward for build.toml or system.toml.
17
+
18
+ If neither is found, return the directory containing the source file.
19
+ """
20
+ current = source_file.resolve().parent
21
+
22
+ while True:
23
+ if (current / "build.toml").exists() or (current / "system.toml").exists():
24
+ return current
25
+
26
+ parent = current.parent
27
+ if parent == current:
28
+ # Reached filesystem root, return source directory
29
+ return source_file.resolve().parent
30
+
31
+ current = parent
32
+
33
+
34
+ def determine_relative_path(
35
+ source: Path,
36
+ project_root: Path,
37
+ output_dir: Path,
38
+ output_format: str | None = None,
39
+ subdir: str | None = None,
40
+ ) -> Path:
41
+ """Determine output path based on source location, mirroring src/ structure to dist/.
42
+
43
+ Args:
44
+ source: Source file path
45
+ project_root: Project root directory
46
+ output_dir: Output base directory
47
+ output_format: File extension (e.g., "odt"). If None, returns directory.
48
+ subdir: Optional subdirectory (e.g., "assets"). Applied before output_format.
49
+
50
+ Returns:
51
+ Path to output file or directory, mirroring src/ structure under dist/.
52
+ """
53
+ source_resolved = source.resolve()
54
+ project_resolved = project_root.resolve()
55
+ src_path = project_resolved / "src"
56
+
57
+ try:
58
+ # Source is under src/: use dist structure
59
+ rel = source_resolved.relative_to(src_path)
60
+ base = output_dir / rel.parent
61
+ except ValueError:
62
+ # Source is not under src/: output next to source
63
+ base = source_resolved.parent
64
+
65
+ if subdir:
66
+ base = base / subdir
67
+
68
+ if output_format:
69
+ return base / source_resolved.with_suffix(f".{output_format}").name
70
+
71
+ return base
72
+
73
+
74
+ def stage_source(
75
+ source: Path, fmt: str, build_config: BuildConfig, temporary: Path, verbose: bool = False
76
+ ) -> Path:
77
+ """Copy source file and replace with format-filtered version."""
78
+ import re
79
+
80
+ stage = temporary / fmt
81
+ stage.mkdir(parents=True, exist_ok=True)
82
+
83
+ adoc_text = source.read_text(encoding="utf-8")
84
+
85
+ # Determine base directory: source_dir if set, otherwise project_root
86
+ if build_config.source_dir:
87
+ base_dir = (build_config.project_root / build_config.source_dir).resolve()
88
+ else:
89
+ base_dir = build_config.project_root.resolve()
90
+
91
+ # Compute relative path from base directory to source
92
+ try:
93
+ source_rel = source.relative_to(base_dir)
94
+ except ValueError:
95
+ source_rel = source.name
96
+
97
+ staged_file = stage / source_rel
98
+ staged_file.parent.mkdir(parents=True, exist_ok=True)
99
+ staged_file.write_text(adoc_text, encoding="utf-8")
100
+
101
+ # Find and copy all include:: files
102
+ include_pattern = re.compile(r"include::([^\[\]]+)\[\]")
103
+ for match in include_pattern.finditer(adoc_text):
104
+ include_path = match.group(1)
105
+ # Resolve relative to original source
106
+ original_include = (source.parent / include_path).resolve()
107
+
108
+ if original_include.exists():
109
+ # Compute relative path from base directory to include
110
+ try:
111
+ include_rel = original_include.relative_to(base_dir)
112
+ except ValueError:
113
+ log("WARNING", f"Include outside source_dir: {original_include}", verbose=verbose)
114
+ continue
115
+
116
+ # Copy to staged directory, preserving source_dir structure
117
+ staged_include = stage / include_rel
118
+ staged_include.parent.mkdir(parents=True, exist_ok=True)
119
+ staged_include.write_bytes(original_include.read_bytes())
120
+ else:
121
+ log("WARNING", f"Include file not found: {original_include}", verbose=verbose)
122
+
123
+ return staged_file
124
+
125
+
126
+ def build_one(
127
+ source: Path,
128
+ fmt: str,
129
+ build_config: BuildConfig,
130
+ staged_source: Path,
131
+ variant: str | None,
132
+ verbose: bool,
133
+ dry_run: bool,
134
+ ) -> Path:
135
+ """Render one staged document using the appropriate converter."""
136
+ project_root = build_config.project_root
137
+ output_dir = build_config.output_path
138
+
139
+ target = determine_relative_path(source, project_root, output_dir, output_format=fmt)
140
+ assets_dir = determine_relative_path(
141
+ source, project_root, output_dir, subdir=build_config.assets_dir
142
+ )
143
+
144
+ config_path = build_config.theme_path(fmt) / f"{fmt}-config.toml"
145
+ converter = get_converter(fmt, config_path, build_config.theme_path(fmt), build_config)
146
+ converter.convert(
147
+ staged_source,
148
+ target,
149
+ variant=variant,
150
+ verbose=verbose,
151
+ dry_run=dry_run,
152
+ original_source=source,
153
+ assets_dir=assets_dir,
154
+ )
155
+
156
+ return target
157
+
158
+
159
+ def with_extracted_attributes(build_config: BuildConfig, extracted: dict[str, str]) -> BuildConfig:
160
+ """Return a new BuildConfig with extracted_attributes set."""
161
+ return BuildConfig(
162
+ project_root=build_config.project_root,
163
+ source_dir=build_config.source_dir,
164
+ output_dir=build_config.output_dir,
165
+ assets_dir=build_config.assets_dir,
166
+ extensions=build_config.extensions,
167
+ attributes=build_config.attributes,
168
+ export_variants=build_config.export_variants,
169
+ theme_dir=build_config.theme_dir,
170
+ system_config=build_config.system_config,
171
+ extracted_attributes=extracted,
172
+ )
173
+
174
+
175
+ def main() -> int:
176
+ parser = argparse.ArgumentParser(description=__doc__)
177
+ parser.add_argument(
178
+ "source",
179
+ type=Path,
180
+ help="AsciiDoc source file to convert",
181
+ )
182
+ parser.add_argument(
183
+ "--format",
184
+ dest="formats",
185
+ choices=sorted(VALID_FORMATS),
186
+ action="append",
187
+ help="repeat for selected formats (default: all)",
188
+ )
189
+ parser.add_argument(
190
+ "--theme",
191
+ type=Path,
192
+ help="override theme path from build.toml",
193
+ )
194
+ parser.add_argument("--variant", help="document variant (e.g. solution)")
195
+ parser.add_argument("--config", type=Path, help="optional build.toml")
196
+ parser.add_argument("--verbose", action="store_true", help="enable debug output")
197
+ parser.add_argument("--dry-run", action="store_true", help="show commands without executing")
198
+
199
+ args = parser.parse_args()
200
+ formats = args.formats or sorted(VALID_FORMATS)
201
+
202
+ try:
203
+ source = args.source.resolve()
204
+ if not source.is_file():
205
+ raise FileNotFoundError(f"Source file not found: {source}")
206
+
207
+ # Find project root
208
+ project_root = find_project_root(source)
209
+ log("DEBUG", f"Project root: {project_root}", verbose=args.verbose)
210
+
211
+ # Load configuration
212
+ build_config = load_config(project_root, args.config)
213
+
214
+ # Override theme if provided
215
+ if args.theme:
216
+ build_config = BuildConfig(
217
+ project_root=build_config.project_root,
218
+ source_dir=build_config.source_dir,
219
+ output_dir=build_config.output_dir,
220
+ assets_dir=build_config.assets_dir,
221
+ extensions=build_config.extensions,
222
+ attributes=build_config.attributes,
223
+ export_variants=build_config.export_variants,
224
+ theme_dir=args.theme.resolve(),
225
+ system_config=build_config.system_config,
226
+ extracted_attributes={},
227
+ )
228
+
229
+ if build_config.theme_dir is None:
230
+ raise ValueError("Theme not configured in build.toml and not provided via --theme")
231
+
232
+ # Load theme config and extract document attributes
233
+ from .config import load_theme
234
+ from .utils import extract_document_attributes
235
+
236
+ theme_config = load_theme(build_config.theme_path("html") / "html-config.toml")
237
+ doc_attrs_to_extract = theme_config.get("theme", {}).get("document_attributes", [])
238
+
239
+ # Extract document attributes from source
240
+ extracted_attrs = extract_document_attributes(source, doc_attrs_to_extract)
241
+ build_config = with_extracted_attributes(build_config, extracted_attrs)
242
+
243
+ log("DEBUG", f"Extracted attributes: {extracted_attrs}", verbose=args.verbose)
244
+
245
+ # Verify theme exists
246
+ for fmt in formats:
247
+ theme_config_path = build_config.theme_path(fmt) / f"{fmt}-config.toml"
248
+ if not theme_config_path.exists():
249
+ raise FileNotFoundError(f"Theme config not found: {theme_config_path}")
250
+
251
+ # Build each format
252
+ with tempfile.TemporaryDirectory(prefix="asciidoc-build-") as temp:
253
+ for fmt in formats:
254
+ staged = stage_source(source, fmt, build_config, Path(temp), args.verbose)
255
+ target = build_one(
256
+ source,
257
+ fmt,
258
+ build_config,
259
+ staged,
260
+ args.variant,
261
+ args.verbose,
262
+ args.dry_run,
263
+ )
264
+ log(
265
+ "INFO",
266
+ f"Built {target.relative_to(build_config.project_root) if target.is_relative_to(build_config.project_root) else target}",
267
+ )
268
+
269
+ log("INFO", f"Build complete: {len(formats)} format(s)")
270
+ return 0
271
+
272
+ except (OSError, ValueError, RuntimeError) as exc:
273
+ log("ERROR", str(exc))
274
+ return 1
275
+
276
+
277
+ if __name__ == "__main__":
278
+ raise SystemExit(main())
themadoc/config.py ADDED
@@ -0,0 +1,197 @@
1
+ # src/themadoc/config.py
2
+ """TOML configuration loading and validated project settings."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import tomllib
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ VALID_FORMATS = frozenset({"html", "pdf", "odt"})
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class SystemConfig:
16
+ """System-specific settings (where are the programs located?)."""
17
+
18
+ asciidoctor: str = "asciidoctor"
19
+ asciidoctor_pdf: str = "asciidoctor-pdf"
20
+ pandoc: str = "pandoc"
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class BuildConfig:
25
+ """Project-wide settings."""
26
+
27
+ project_root: Path
28
+ source_dir: Path = Path("src")
29
+ output_dir: Path = Path("dist")
30
+ assets_dir: str = "images"
31
+ extensions: tuple[str, ...] = (".adoc", ".asciidoc")
32
+ attributes: dict[str, str] = field(default_factory=dict)
33
+ export_variants: dict[str, list[str]] = field(default_factory=dict)
34
+ theme_dir: Path | None = None
35
+ system_config: SystemConfig = field(default_factory=SystemConfig)
36
+ extracted_attributes: dict[str, str] = field(default_factory=dict)
37
+
38
+ @property
39
+ def source_path(self) -> Path:
40
+ """Return source directory (may not exist for flat projects)."""
41
+ return self.project_root / self.source_dir
42
+
43
+ @property
44
+ def output_path(self) -> Path:
45
+ """Return output directory."""
46
+ return self.project_root / self.output_dir
47
+
48
+ def theme_path(self, output_format: str) -> Path:
49
+ """Return the theme directory for a format (html/, pdf/, odt/)."""
50
+ if self.theme_dir is None:
51
+ raise ValueError("Theme not configured")
52
+ theme_dir = (
53
+ self.theme_dir
54
+ if self.theme_dir.is_absolute()
55
+ else self.project_root / self.theme_dir
56
+ )
57
+ return theme_dir / output_format
58
+
59
+
60
+ def _string(value: Any, key: str, default: str) -> str:
61
+ if value is None:
62
+ return default
63
+ if not isinstance(value, str) or not value:
64
+ raise ValueError(f"{key} must be a non-empty string")
65
+ return value
66
+
67
+
68
+ def _load_toml(path: Path) -> dict[str, Any]:
69
+ """Load a TOML file, return empty dict if not found."""
70
+ if not path.is_file():
71
+ return {}
72
+ with path.open("rb") as fh:
73
+ return tomllib.load(fh)
74
+
75
+
76
+ def load_system_config(project_root: Path) -> SystemConfig:
77
+ """Load optional system.toml from project root."""
78
+ raw = _load_toml(project_root / "system.toml")
79
+ system_raw = raw.get("system", {})
80
+
81
+ if not isinstance(system_raw, dict):
82
+ raise TypeError("system.toml [system] section must be a table")
83
+
84
+ return SystemConfig(
85
+ asciidoctor=_string(
86
+ system_raw.get("asciidoctor"), "asciidoctor", "asciidoctor"
87
+ ),
88
+ asciidoctor_pdf=_string(
89
+ system_raw.get("asciidoctor_pdf"), "asciidoctor_pdf", "asciidoctor-pdf"
90
+ ),
91
+ pandoc=_string(system_raw.get("pandoc"), "pandoc", "pandoc"),
92
+ )
93
+
94
+
95
+ def load_config(project_root: Path, config_file: Path | None = None) -> BuildConfig:
96
+ """Load optional build.toml from project root.
97
+
98
+ Unknown keys are deliberately ignored for forwards compatibility.
99
+ """
100
+ root = project_root.resolve()
101
+ raw: dict[str, Any] = {}
102
+ source = config_file or root / "build.toml"
103
+
104
+ if source.exists():
105
+ with source.open("rb") as fh:
106
+ parsed = tomllib.load(fh)
107
+ raw = parsed.get("build", parsed)
108
+ if not isinstance(raw, dict):
109
+ raise ValueError("build.toml must contain a table")
110
+
111
+ extensions_raw = raw.get("extensions", [".adoc", ".asciidoc"])
112
+ if not isinstance(extensions_raw, list) or not all(
113
+ isinstance(x, str) and x.startswith(".") for x in extensions_raw
114
+ ):
115
+ raise ValueError("extensions must be an array of filename suffixes")
116
+
117
+ attrs = raw.get("attributes", {})
118
+ if not isinstance(attrs, dict) or not all(
119
+ isinstance(k, str) and isinstance(v, (str, int, float, bool))
120
+ for k, v in attrs.items()
121
+ ):
122
+ raise ValueError("attributes must be a table of scalar values")
123
+
124
+ export_variants = raw.get("export_variants", {})
125
+ if not isinstance(export_variants, dict):
126
+ raise TypeError("export_variants must be a table")
127
+ for variant_name, variant_attrs in export_variants.items():
128
+ if not isinstance(variant_name, str):
129
+ raise TypeError("export_variants keys must be strings")
130
+ if not isinstance(variant_attrs, list) or not all(
131
+ isinstance(x, str) for x in variant_attrs
132
+ ):
133
+ raise ValueError(
134
+ f"export_variants[{variant_name}] must be a list of strings"
135
+ )
136
+
137
+ theme_raw = raw.get("theme_dir")
138
+ theme_dir = Path(theme_raw) if theme_raw else None
139
+
140
+ system_config = load_system_config(root)
141
+
142
+ cfg = BuildConfig(
143
+ project_root=root,
144
+ source_dir=Path(_string(raw.get("source_dir"), "source_dir", "src")),
145
+ output_dir=Path(_string(raw.get("output_dir"), "output_dir", "dist")),
146
+ assets_dir=_string(raw.get("assets_dir"), "assets_dir", "images"),
147
+ extensions=tuple(extensions_raw),
148
+ attributes={
149
+ str(k): str(v).lower() if isinstance(v, bool) else str(v)
150
+ for k, v in attrs.items()
151
+ },
152
+ export_variants={str(k): list(v) for k, v in export_variants.items()},
153
+ theme_dir=theme_dir,
154
+ system_config=system_config,
155
+ extracted_attributes={},
156
+ )
157
+
158
+ if (
159
+ cfg.source_dir.is_absolute()
160
+ or cfg.output_dir.is_absolute()
161
+ or ".." in cfg.source_dir.parts
162
+ or ".." in cfg.output_dir.parts
163
+ ):
164
+ raise ValueError("source_dir and output_dir must be safe relative paths")
165
+
166
+ return cfg
167
+
168
+
169
+ def load_theme(path: Path) -> dict[str, Any]:
170
+ """Read a per-format TOML theme document and resolve relative paths."""
171
+ if not path.is_file():
172
+ raise FileNotFoundError(f"Theme configuration not found: {path}")
173
+ with path.open("rb") as fh:
174
+ data = tomllib.load(fh)
175
+ if not isinstance(data, dict):
176
+ raise TypeError(f"Theme configuration {path} must be a TOML table")
177
+
178
+ # Resolve relative paths in format-specific sections
179
+ config_dir = path.parent
180
+ format_key = None
181
+
182
+ # Find the format-specific section (html, pdf, odt)
183
+ for key in ("html", "pdf", "odt"):
184
+ if key in data and isinstance(data[key], dict):
185
+ format_key = key
186
+ break
187
+
188
+ if format_key and "paths" in data[format_key]:
189
+ paths = data[format_key]["paths"]
190
+ if isinstance(paths, dict):
191
+ for path_key in list(paths.keys()):
192
+ if isinstance(paths[path_key], str) and not paths[path_key].startswith(
193
+ "/"
194
+ ):
195
+ paths[path_key] = str((config_dir / paths[path_key]).resolve())
196
+
197
+ return data
@@ -0,0 +1,44 @@
1
+ # src/themadoc/converters/__init__.py
2
+ """Converter factory and registry."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from pathlib import Path
7
+
8
+ from ..config import BuildConfig
9
+ from .asciidoctor import (
10
+ AsciidoctorHtmlConverter,
11
+ AsciidoctorPdfConverter,
12
+ )
13
+ from .base import BaseConverter
14
+ from .odt import PandocOdtConverter
15
+
16
+ # Converter registry: maps formats to converter classes
17
+ CONVERTERS = {
18
+ "html": AsciidoctorHtmlConverter,
19
+ "pdf": AsciidoctorPdfConverter,
20
+ "odt": PandocOdtConverter,
21
+ }
22
+
23
+
24
+ def get_converter(
25
+ output_format: str, config_path: Path, theme_dir: Path, build_config: BuildConfig
26
+ ) -> BaseConverter:
27
+ """Factory function to get the appropriate converter.
28
+
29
+ Args:
30
+ output_format: Output format ("html", "pdf", "odt")
31
+ config_path: Path to *-config.toml
32
+ theme_dir: Path to theme directory
33
+ build_config: Project and system configuration
34
+
35
+ Returns:
36
+ Initialized converter instance
37
+
38
+ Raises:
39
+ ValueError: If output_format is unknown
40
+ """
41
+ if output_format not in CONVERTERS:
42
+ raise ValueError(f"Unknown format: {output_format}")
43
+ converter_class = CONVERTERS[output_format]
44
+ return converter_class(output_format, config_path, theme_dir, build_config)