text-compositor 0.2.0__tar.gz → 0.3.5__tar.gz

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.
Files changed (63) hide show
  1. {text_compositor-0.2.0/text_compositor.egg-info → text_compositor-0.3.5}/PKG-INFO +22 -2
  2. {text_compositor-0.2.0 → text_compositor-0.3.5}/README.md +21 -1
  3. {text_compositor-0.2.0 → text_compositor-0.3.5}/pyproject.toml +1 -1
  4. text_compositor-0.3.5/tests/test_api.py +330 -0
  5. {text_compositor-0.2.0 → text_compositor-0.3.5}/tests/test_asset_resolution.py +8 -7
  6. text_compositor-0.3.5/tests/test_common_template.py +111 -0
  7. {text_compositor-0.2.0 → text_compositor-0.3.5}/tests/test_config.py +16 -15
  8. text_compositor-0.3.5/tests/test_csv_table.py +149 -0
  9. text_compositor-0.3.5/tests/test_diagnostics.py +134 -0
  10. text_compositor-0.3.5/tests/test_diagram_cache_key.py +45 -0
  11. text_compositor-0.3.5/tests/test_distribution.py +68 -0
  12. text_compositor-0.3.5/tests/test_doc_badges.py +38 -0
  13. text_compositor-0.3.5/tests/test_download.py +213 -0
  14. {text_compositor-0.2.0 → text_compositor-0.3.5}/tests/test_front_matter.py +9 -8
  15. text_compositor-0.3.5/tests/test_html_output.py +689 -0
  16. text_compositor-0.3.5/tests/test_incremental.py +197 -0
  17. {text_compositor-0.2.0 → text_compositor-0.3.5}/tests/test_layout_blocks.py +3 -3
  18. {text_compositor-0.2.0 → text_compositor-0.3.5}/tests/test_line_mapping.py +23 -21
  19. {text_compositor-0.2.0 → text_compositor-0.3.5}/tests/test_markdown_basics.py +9 -9
  20. text_compositor-0.3.5/tests/test_mermaid_resident.py +151 -0
  21. text_compositor-0.3.5/tests/test_paper_template.py +86 -0
  22. text_compositor-0.3.5/tests/test_revision_history.py +83 -0
  23. text_compositor-0.3.5/tests/test_sections.py +188 -0
  24. text_compositor-0.3.5/tests/test_table_cell_style.py +94 -0
  25. text_compositor-0.3.5/tests/test_variables.py +115 -0
  26. text_compositor-0.3.5/tests/test_viewer_version.py +21 -0
  27. text_compositor-0.3.5/tests/test_watch.py +203 -0
  28. text_compositor-0.3.5/tests/test_worker.py +491 -0
  29. text_compositor-0.3.5/text_compositor/__init__.py +28 -0
  30. text_compositor-0.3.5/text_compositor/api.py +349 -0
  31. text_compositor-0.3.5/text_compositor/build.py +215 -0
  32. text_compositor-0.3.5/text_compositor/changes.py +93 -0
  33. text_compositor-0.3.5/text_compositor/chapters.py +270 -0
  34. text_compositor-0.3.5/text_compositor/compiler.py +187 -0
  35. text_compositor-0.3.5/text_compositor/config.py +205 -0
  36. text_compositor-0.3.5/text_compositor/deps.py +457 -0
  37. text_compositor-0.3.5/text_compositor/diagnostics.py +105 -0
  38. text_compositor-0.3.5/text_compositor/document.py +229 -0
  39. text_compositor-0.3.5/text_compositor/env_check.py +204 -0
  40. text_compositor-0.3.5/text_compositor/host_renderers.py +26 -0
  41. text_compositor-0.3.5/text_compositor/html_output.py +690 -0
  42. text_compositor-0.3.5/text_compositor/log.py +37 -0
  43. text_compositor-0.3.5/text_compositor/mermaid.py +150 -0
  44. text_compositor-0.3.5/text_compositor/project.py +155 -0
  45. text_compositor-0.3.5/text_compositor/renderer.py +1515 -0
  46. text_compositor-0.2.0/text_compositor/templates/template.typ → text_compositor-0.3.5/text_compositor/templates/_common.typ +17 -98
  47. text_compositor-0.3.5/text_compositor/templates/paper.typ +99 -0
  48. {text_compositor-0.2.0 → text_compositor-0.3.5}/text_compositor/templates/slide.typ +7 -52
  49. text_compositor-0.3.5/text_compositor/templates/template.typ +151 -0
  50. text_compositor-0.3.5/text_compositor/typst_literal.py +15 -0
  51. text_compositor-0.3.5/text_compositor/worker.py +197 -0
  52. {text_compositor-0.2.0 → text_compositor-0.3.5/text_compositor.egg-info}/PKG-INFO +22 -2
  53. text_compositor-0.3.5/text_compositor.egg-info/SOURCES.txt +57 -0
  54. text_compositor-0.2.0/tests/test_csv_table.py +0 -78
  55. text_compositor-0.2.0/text_compositor/__init__.py +0 -0
  56. text_compositor-0.2.0/text_compositor/build.py +0 -2680
  57. text_compositor-0.2.0/text_compositor.egg-info/SOURCES.txt +0 -20
  58. {text_compositor-0.2.0 → text_compositor-0.3.5}/LICENSE +0 -0
  59. {text_compositor-0.2.0 → text_compositor-0.3.5}/setup.cfg +0 -0
  60. {text_compositor-0.2.0 → text_compositor-0.3.5}/text_compositor.egg-info/dependency_links.txt +0 -0
  61. {text_compositor-0.2.0 → text_compositor-0.3.5}/text_compositor.egg-info/entry_points.txt +0 -0
  62. {text_compositor-0.2.0 → text_compositor-0.3.5}/text_compositor.egg-info/requires.txt +0 -0
  63. {text_compositor-0.2.0 → text_compositor-0.3.5}/text_compositor.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: text-compositor
3
- Version: 0.2.0
3
+ Version: 0.3.5
4
4
  Summary: A tool for composing multiple text files into a PDF document.
5
5
  License-Expression: MIT
6
6
  Project-URL: Repository, https://github.com/tokudiro/text-compositor
@@ -141,6 +141,26 @@ Run `text-compositor --check-env` (or `python build.py --check-env`) to check yo
141
141
 
142
142
  Other flags control runtime behavior only (not document content, which stays entirely in `config.yaml`): `-q`/`--quiet` suppresses `[Info]`-level logging, `-v`/`--verbose` adds extra detail (which chapter is being processed, cache reuse), and `--keep-temp` keeps the intermediate `temp_build.typ` around after a successful build instead of deleting it (useful for debugging; it's always kept after a failed build).
143
143
 
144
+ `--watch` keeps running after the first build and rebuilds whenever it detects a save in the config, the input files, or a custom `.typ` template. A failed build does not stop it; fix the file and save again. Press Ctrl+C to stop. Changes to files outside the project directory (e.g. images referenced via `../`) are not detected.
145
+
146
+ `--if-changed` skips the build, like `make`, when the output PDF is newer than the config, the input files, the template, and text-compositor itself (judged by modification time only). Without it, the PDF is always regenerated. Changes to Typst's version, to files outside the project directory, or to environment variables used by `variables` are not detected. On CI, `actions/checkout` resets every file's modification time, so restore the output directory from a cache if you want the skip to take effect.
147
+
148
+ `--clean` deletes the output PDF and the intermediate files under `.text-compositor/` (`temp_build.typ`, `_template.typ`, `_common.typ`) without building. `--clean-cache` additionally deletes the diagram cache (`.text-compositor/cache/`). Input files and the config are never deleted.
149
+
150
+ ### Python API
151
+
152
+ `text_compositor.Session` and `build_markdown()` turn a single Markdown file into a PDF without a `config.yaml`, and return warnings and errors as structured diagnostics (Markdown file and line included) instead of printing them. A resident worker (`python -m text_compositor.worker`) exposes the same over JSON lines on stdin/stdout, for GUI viewers. See the usage guide chapter "Using from Python" and section 14 of [doc/spec.md](doc/spec.md).
153
+
154
+ ```python
155
+ from text_compositor import Session
156
+
157
+ with Session() as session: # reuses the Mermaid browser and the Typst compiler across builds
158
+ result = session.build("doc.md", "out/doc.pdf")
159
+ print(result.ok, result.pdf_path, [d.message for d in result.diagnostics])
160
+ ```
161
+
162
+ `session.render_html("doc.md")` (experimental, [#161](https://github.com/tokudiro/text-compositor/issues/161)) writes a self-contained HTML file instead. Diagrams (Mermaid, PlantUML, D2, `svg`) become images next to it. `typst-exec` and raw HTML are not supported yet and are shown as code with a warning. Graphviz is drawn only in the Obunzu Viewer; elsewhere it is shown as code with a warning.
163
+
144
164
  See [sample/text-compositor.config.yaml](sample/text-compositor.config.yaml) for how to write the config file, and the [usage guide](doc/usage/) for details on `document:`/`plugins:`, front matter, Marp directives, and more. The Markdown files listed in `chapters` are concatenated in order to produce the PDF.
145
165
 
146
166
  ## Trying the sample
@@ -150,7 +170,7 @@ cd sample/
150
170
  python ../build.py
151
171
  ```
152
172
 
153
- This generates `sample/System_Specification.pdf`.
173
+ This generates `sample/SampleDocument.pdf`. Two more samples show other templates: `sample/paper/` (two-column paper layout, `template.path: paper`) and `sample/universe-ilm/` (a [Typst Universe](https://typst.app/universe) template used through an adapter; needs network access on the first build).
154
174
 
155
175
  ## Implementation status
156
176
 
@@ -123,6 +123,26 @@ Run `text-compositor --check-env` (or `python build.py --check-env`) to check yo
123
123
 
124
124
  Other flags control runtime behavior only (not document content, which stays entirely in `config.yaml`): `-q`/`--quiet` suppresses `[Info]`-level logging, `-v`/`--verbose` adds extra detail (which chapter is being processed, cache reuse), and `--keep-temp` keeps the intermediate `temp_build.typ` around after a successful build instead of deleting it (useful for debugging; it's always kept after a failed build).
125
125
 
126
+ `--watch` keeps running after the first build and rebuilds whenever it detects a save in the config, the input files, or a custom `.typ` template. A failed build does not stop it; fix the file and save again. Press Ctrl+C to stop. Changes to files outside the project directory (e.g. images referenced via `../`) are not detected.
127
+
128
+ `--if-changed` skips the build, like `make`, when the output PDF is newer than the config, the input files, the template, and text-compositor itself (judged by modification time only). Without it, the PDF is always regenerated. Changes to Typst's version, to files outside the project directory, or to environment variables used by `variables` are not detected. On CI, `actions/checkout` resets every file's modification time, so restore the output directory from a cache if you want the skip to take effect.
129
+
130
+ `--clean` deletes the output PDF and the intermediate files under `.text-compositor/` (`temp_build.typ`, `_template.typ`, `_common.typ`) without building. `--clean-cache` additionally deletes the diagram cache (`.text-compositor/cache/`). Input files and the config are never deleted.
131
+
132
+ ### Python API
133
+
134
+ `text_compositor.Session` and `build_markdown()` turn a single Markdown file into a PDF without a `config.yaml`, and return warnings and errors as structured diagnostics (Markdown file and line included) instead of printing them. A resident worker (`python -m text_compositor.worker`) exposes the same over JSON lines on stdin/stdout, for GUI viewers. See the usage guide chapter "Using from Python" and section 14 of [doc/spec.md](doc/spec.md).
135
+
136
+ ```python
137
+ from text_compositor import Session
138
+
139
+ with Session() as session: # reuses the Mermaid browser and the Typst compiler across builds
140
+ result = session.build("doc.md", "out/doc.pdf")
141
+ print(result.ok, result.pdf_path, [d.message for d in result.diagnostics])
142
+ ```
143
+
144
+ `session.render_html("doc.md")` (experimental, [#161](https://github.com/tokudiro/text-compositor/issues/161)) writes a self-contained HTML file instead. Diagrams (Mermaid, PlantUML, D2, `svg`) become images next to it. `typst-exec` and raw HTML are not supported yet and are shown as code with a warning. Graphviz is drawn only in the Obunzu Viewer; elsewhere it is shown as code with a warning.
145
+
126
146
  See [sample/text-compositor.config.yaml](sample/text-compositor.config.yaml) for how to write the config file, and the [usage guide](doc/usage/) for details on `document:`/`plugins:`, front matter, Marp directives, and more. The Markdown files listed in `chapters` are concatenated in order to produce the PDF.
127
147
 
128
148
  ## Trying the sample
@@ -132,7 +152,7 @@ cd sample/
132
152
  python ../build.py
133
153
  ```
134
154
 
135
- This generates `sample/System_Specification.pdf`.
155
+ This generates `sample/SampleDocument.pdf`. Two more samples show other templates: `sample/paper/` (two-column paper layout, `template.path: paper`) and `sample/universe-ilm/` (a [Typst Universe](https://typst.app/universe) template used through an adapter; needs network access on the first build).
136
156
 
137
157
  ## Implementation status
138
158
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "text-compositor"
7
- version = "0.2.0"
7
+ version = "0.3.5"
8
8
  description = "A tool for composing multiple text files into a PDF document."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -0,0 +1,330 @@
1
+ """Python API(api.py、#167)のテスト。実際にTypstでコンパイルするため、フォント(初回のみ取得)と、
2
+ Typstのパッケージ(テンプレートが使う@preview/…。初回のみ取得)を使う。"""
3
+ import os
4
+ import struct
5
+ import sys
6
+ import zlib
7
+
8
+ import pytest
9
+
10
+ import text_compositor.build as build
11
+ from text_compositor.deps import ensure_fonts
12
+ import text_compositor.project as project_mod
13
+ import time
14
+ from text_compositor import diagnostics
15
+ from text_compositor.api import BuildResult, Session, build_markdown
16
+
17
+
18
+ @pytest.fixture(scope="module")
19
+ def font_dir():
20
+ return ensure_fonts()
21
+
22
+
23
+ @pytest.fixture
24
+ def session(font_dir):
25
+ with Session(font_dir=font_dir) as s:
26
+ yield s
27
+
28
+
29
+ def write(path, text):
30
+ os.makedirs(os.path.dirname(path), exist_ok=True)
31
+ with open(path, "w", encoding="utf-8") as f:
32
+ f.write(text)
33
+
34
+
35
+ def png_bytes(rgb):
36
+ """8x8の単色PNG(標準ライブラリだけで作る)。"""
37
+ def chunk(kind, data):
38
+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
39
+ raw = b"".join(b"\x00" + bytes(rgb) * 8 for _ in range(8))
40
+ return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0))
41
+ + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
42
+
43
+
44
+ def read_bytes(path):
45
+ with open(path, "rb") as f:
46
+ return f.read()
47
+
48
+
49
+ PLAIN = {"mermaid": False, "plantuml": False, "d2": False}
50
+
51
+
52
+ class TestBuild:
53
+ def test_builds_a_pdf_to_the_requested_path(self, session, tmp_path):
54
+ md = tmp_path / "doc.md"
55
+ write(str(md), "# 見出し\n\n本文。\n\n- a\n- b\n")
56
+ out = tmp_path / "out" / "doc.pdf"
57
+ result = session.build(str(md), str(out), plugins=PLAIN)
58
+ assert isinstance(result, BuildResult)
59
+ assert result.ok and not result.errors
60
+ assert result.pdf_path == str(out)
61
+ assert read_bytes(str(out)).startswith(b"%PDF")
62
+
63
+ def test_does_not_create_an_outputs_directory_next_to_the_markdown(self, session, tmp_path):
64
+ md = tmp_path / "doc.md"
65
+ write(str(md), "# T\n\nbody\n")
66
+ session.build(str(md), str(tmp_path / "x" / "o.pdf"), plugins=PLAIN)
67
+ assert not (tmp_path / "outputs").exists()
68
+
69
+ def test_default_output_is_under_the_work_directory(self, session, tmp_path):
70
+ md = tmp_path / "doc.md"
71
+ write(str(md), "# T\n\nbody\n")
72
+ result = session.build(str(md), plugins=PLAIN)
73
+ assert result.ok
74
+ assert result.pdf_path == str(tmp_path / ".text-compositor" / "preview.pdf")
75
+ assert os.path.exists(result.pdf_path)
76
+
77
+ def test_leaves_no_intermediate_files_and_no_temporary_pdf(self, session, tmp_path):
78
+ md = tmp_path / "doc.md"
79
+ write(str(md), "# T\n\nbody\n")
80
+ out = tmp_path / "out" / "doc.pdf"
81
+ session.build(str(md), str(out), plugins=PLAIN)
82
+ assert sorted(os.listdir(str(tmp_path / ".text-compositor"))) == []
83
+ assert sorted(os.listdir(str(out.parent))) == ["doc.pdf"]
84
+
85
+ def test_keep_temp_keeps_the_generated_typst(self, session, tmp_path):
86
+ md = tmp_path / "doc.md"
87
+ write(str(md), "# T\n\nbody\n")
88
+ session.build(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN, keep_temp=True)
89
+ assert (tmp_path / ".text-compositor" / "temp_build.typ").exists()
90
+
91
+ def test_writes_nothing_to_stdout(self, session, tmp_path, capsys):
92
+ md = tmp_path / "doc.md"
93
+ write(str(md), "# T\n\nbefore <span>x</span> after\n")
94
+ session.build(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN)
95
+ write(str(md), "# T\n\n```dot {width=bogus}\ndigraph { a -> b }\n```\n")
96
+ session.build(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN)
97
+ assert capsys.readouterr().out == ""
98
+
99
+ def test_timings_are_reported(self, session, tmp_path):
100
+ md = tmp_path / "doc.md"
101
+ write(str(md), "# T\n\nbody\n")
102
+ result = session.build(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN)
103
+ assert set(result.timings_ms) >= {"render", "compile", "total"}
104
+ assert result.timings_ms["total"] >= result.timings_ms["compile"] > 0
105
+
106
+ def test_first_markdown_heading_is_kept_as_is(self, session, tmp_path):
107
+ """プレビューでは、先頭のH1を落とさない(CLIの既定のcover: noneは、先頭のタイトルを落とす)。"""
108
+ md = tmp_path / "doc.md"
109
+ write(str(md), "# 先頭の見出し\n\n本文。\n")
110
+ session.build(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN, keep_temp=True)
111
+ typst = (tmp_path / ".text-compositor" / "temp_build.typ").read_text(encoding="utf-8")
112
+ assert "= 先頭の見出し" in typst
113
+ assert "cover: false" in typst
114
+
115
+
116
+ class TestOptions:
117
+ @pytest.mark.parametrize("template", ["template", "slide", "paper"])
118
+ def test_bundled_templates(self, session, tmp_path, template):
119
+ md = tmp_path / "doc.md"
120
+ write(str(md), "# T\n\n## 節\n\n本文。\n")
121
+ result = session.build(str(md), str(tmp_path / "o.pdf"), template=template, plugins=PLAIN)
122
+ assert result.ok, result.diagnostics
123
+
124
+ def test_document_and_variables_overrides(self, session, tmp_path):
125
+ md = tmp_path / "doc.md"
126
+ write(str(md), "# T\n\nバージョンは{{VERSION}}。\n")
127
+ result = session.build(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN,
128
+ document={"title": "仕様書", "toc": True}, variables={"VERSION": "1.2"},
129
+ keep_temp=True)
130
+ assert result.ok
131
+ typst = (tmp_path / ".text-compositor" / "temp_build.typ").read_text(encoding="utf-8")
132
+ assert 'title: "仕様書"' in typst and "toc: true" in typst and "バージョンは1.2。" in typst
133
+
134
+ def test_config_override_applies_last(self, session, tmp_path):
135
+ md = tmp_path / "doc.md"
136
+ write(str(md), "# T\n\nbody\n")
137
+ result = session.build(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN, document={"title": "A"},
138
+ config={"document": {"title": "B"}}, keep_temp=True)
139
+ assert result.ok
140
+ assert 'title: "B"' in (tmp_path / ".text-compositor" / "temp_build.typ").read_text(encoding="utf-8")
141
+
142
+ def test_custom_typ_template_by_path(self, session, tmp_path):
143
+ """独自テンプレートは、Markdownの隣からの相対パスで指定できる。"""
144
+ with open(os.path.join(build.__file__ and os.path.dirname(build.__file__), "templates", "template.typ"),
145
+ encoding="utf-8") as f:
146
+ write(str(tmp_path / "my.typ"), f.read())
147
+ md = tmp_path / "doc.md"
148
+ write(str(md), "# T\n\nbody\n")
149
+ result = session.build(str(md), str(tmp_path / "o.pdf"), template="my.typ", plugins=PLAIN)
150
+ assert result.ok, result.diagnostics
151
+
152
+
153
+ class TestFailures:
154
+ def test_missing_markdown_is_reported_not_raised(self, session, tmp_path):
155
+ result = session.build(str(tmp_path / "none.md"), str(tmp_path / "o.pdf"))
156
+ assert not result.ok and result.pdf_path is None
157
+ assert result.errors and "not found" in result.errors[0].message
158
+
159
+ def test_unknown_template_is_reported(self, session, tmp_path):
160
+ md = tmp_path / "doc.md"
161
+ write(str(md), "# T\n")
162
+ result = session.build(str(md), str(tmp_path / "o.pdf"), template="no_such_template", plugins=PLAIN)
163
+ assert not result.ok
164
+ assert any("Template not found" in d.message for d in result.errors)
165
+
166
+ def test_compile_error_points_at_the_markdown_line(self, session, tmp_path):
167
+ md = tmp_path / "doc.md"
168
+ write(str(md), "# 見出し\n\n```dot {width=bogus}\ndigraph { a -> b }\n```\n")
169
+ result = session.build(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN)
170
+ assert not result.ok and result.pdf_path is None
171
+ error = result.errors[0]
172
+ assert "unknown variable: bogus" in error.message
173
+ assert error.file == str(md) and error.line == 3
174
+ assert error.detail and "temp_build.typ" in error.detail
175
+
176
+ def test_a_failed_build_keeps_the_previous_pdf(self, session, tmp_path):
177
+ md = tmp_path / "doc.md"
178
+ out = tmp_path / "o.pdf"
179
+ write(str(md), "# T\n\nok\n")
180
+ assert session.build(str(md), str(out), plugins=PLAIN).ok
181
+ before = read_bytes(str(out))
182
+ write(str(md), "# T\n\n```dot {width=bogus}\ndigraph { a -> b }\n```\n")
183
+ assert not session.build(str(md), str(out), plugins=PLAIN).ok
184
+ assert read_bytes(str(out)) == before
185
+
186
+ def test_the_session_recovers_after_a_failure(self, session, tmp_path):
187
+ md = tmp_path / "doc.md"
188
+ write(str(md), "# T\n\n```dot {width=bogus}\ndigraph { a -> b }\n```\n")
189
+ assert not session.build(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN).ok
190
+ write(str(md), "# T\n\nfine\n")
191
+ assert session.build(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN).ok
192
+
193
+ def test_security_violation_is_a_structured_error(self, session, tmp_path):
194
+ md = tmp_path / "doc.md"
195
+ write(str(md), "# T\n\n```typst-exec\n#panic(\"x\")\n```\n")
196
+ result = session.build(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN)
197
+ assert not result.ok
198
+ assert any("typst-exec" in d.message and d.file == str(md) for d in result.errors)
199
+
200
+ def test_unexpected_exceptions_do_not_escape(self, session, tmp_path, monkeypatch):
201
+ md = tmp_path / "doc.md"
202
+ write(str(md), "# T\n")
203
+
204
+ def boom(*a, **k):
205
+ raise RuntimeError("kaboom")
206
+ monkeypatch.setattr(project_mod, "_build_project", boom)
207
+ result = session.build(str(md), str(tmp_path / "o.pdf"))
208
+ assert not result.ok
209
+ assert "kaboom" in result.errors[0].message and "Traceback" in result.errors[0].detail
210
+
211
+ def test_closed_session_reports_an_error(self, font_dir, tmp_path):
212
+ s = Session(font_dir=font_dir)
213
+ s.close()
214
+ md = tmp_path / "doc.md"
215
+ write(str(md), "# T\n")
216
+ assert not s.build(str(md), str(tmp_path / "o.pdf")).ok
217
+
218
+ def test_output_open_elsewhere_is_reported(self, session, tmp_path, monkeypatch):
219
+ md = tmp_path / "doc.md"
220
+ write(str(md), "# T\n\nbody\n")
221
+
222
+ def denied(src, dst):
223
+ raise PermissionError("in use")
224
+ monkeypatch.setattr(os, "replace", denied)
225
+ monkeypatch.setattr(time, "sleep", lambda s: None)
226
+ result = session.build(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN)
227
+ assert not result.ok
228
+ assert any("Cannot write the PDF" in d.message for d in result.errors)
229
+ assert [n for n in os.listdir(str(tmp_path)) if n.startswith(".tmp-")] == []
230
+
231
+
232
+ class TestWarnings:
233
+ def test_html_warning_carries_file_and_line(self, session, tmp_path):
234
+ md = tmp_path / "doc.md"
235
+ write(str(md), "# T\n\ntext\n\nbefore <span>x</span> after\n")
236
+ result = session.build(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN)
237
+ assert result.ok
238
+ assert result.warnings
239
+ assert all(d.file == str(md) and d.line == 5 for d in result.warnings if "HTML" in d.message)
240
+
241
+ def test_warnings_do_not_leak_between_builds(self, session, tmp_path):
242
+ md = tmp_path / "doc.md"
243
+ write(str(md), "# T\n\nbefore <span>x</span>\n")
244
+ assert session.build(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN).warnings
245
+ write(str(md), "# T\n\nclean\n")
246
+ assert not session.build(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN).warnings
247
+
248
+
249
+ class TestResidentReuse:
250
+ def test_compiler_is_reused_and_changes_are_reflected(self, session, tmp_path):
251
+ md = tmp_path / "doc.md"
252
+ out = tmp_path / "o.pdf"
253
+ write(str(md), "# T\n\nfirst\n")
254
+ assert session.build(str(md), str(out), plugins=PLAIN).ok
255
+ first = read_bytes(str(out))
256
+ write(str(md), "# T\n\nsecond, and a bit longer text\n")
257
+ assert session.build(str(md), str(out), plugins=PLAIN).ok
258
+ assert read_bytes(str(out)) != first
259
+ assert len(session._compilers) == 1
260
+
261
+ def test_a_replaced_image_is_picked_up(self, session, tmp_path):
262
+ """同じパスの画像を差し替えても、使い回したコンパイラが古い画像を返さない。"""
263
+ md = tmp_path / "doc.md"
264
+ img = tmp_path / "img.png"
265
+ out = tmp_path / "o.pdf"
266
+ write(str(md), "# T\n\n![pic](img.png)\n")
267
+ img.write_bytes(png_bytes((255, 0, 0)))
268
+ assert session.build(str(md), str(out), plugins=PLAIN).ok
269
+ red = read_bytes(str(out))
270
+ img.write_bytes(png_bytes((0, 0, 255)))
271
+ assert session.build(str(md), str(out), plugins=PLAIN).ok
272
+ assert read_bytes(str(out)) != red
273
+
274
+ def test_different_documents_in_one_session(self, session, tmp_path):
275
+ a, b = tmp_path / "a" / "a.md", tmp_path / "b" / "b.md"
276
+ write(str(a), "# A\n\nalpha\n")
277
+ write(str(b), "# B\n\nbeta\n")
278
+ assert session.build(str(a), str(tmp_path / "a.pdf"), plugins=PLAIN).ok
279
+ assert session.build(str(b), str(tmp_path / "b.pdf"), plugins=PLAIN).ok
280
+ assert session.build(str(a), str(tmp_path / "a.pdf"), plugins=PLAIN).ok
281
+ assert read_bytes(str(tmp_path / "a.pdf")) != read_bytes(str(tmp_path / "b.pdf"))
282
+
283
+ def test_close_releases_everything_and_is_idempotent(self, font_dir):
284
+ closed = []
285
+
286
+ class FakeBrowser:
287
+ page = None
288
+
289
+ def close(self):
290
+ closed.append(1)
291
+ s = Session(font_dir=font_dir)
292
+ s._mermaid = FakeBrowser()
293
+ s._compilers["k"] = object()
294
+ s.close()
295
+ s.close()
296
+ assert closed == [1, 1] and s._compilers == {}
297
+
298
+
299
+ class TestModuleFunction:
300
+ def test_build_markdown_is_a_one_shot(self, font_dir, tmp_path):
301
+ md = tmp_path / "doc.md"
302
+ write(str(md), "# T\n\nbody\n")
303
+ result = build_markdown(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN)
304
+ assert result.ok and os.path.exists(result.pdf_path)
305
+
306
+ def test_public_names_are_importable_from_the_package(self):
307
+ import text_compositor
308
+ assert text_compositor.Session is Session
309
+ assert text_compositor.build_markdown is build_markdown
310
+ assert text_compositor.BuildResult is BuildResult
311
+ assert text_compositor.Diagnostic is diagnostics.Diagnostic
312
+ with pytest.raises(AttributeError):
313
+ text_compositor.nope
314
+
315
+ def test_plain_import_stays_light(self):
316
+ import subprocess
317
+ code = "import sys, text_compositor; sys.exit(1 if 'text_compositor.build' in sys.modules else 0)"
318
+ repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
319
+ env = dict(os.environ, PYTHONPATH=repo_root + os.pathsep + os.environ.get("PYTHONPATH", ""))
320
+ assert subprocess.run([sys.executable, "-c", code], env=env, cwd=repo_root).returncode == 0
321
+
322
+ def test_result_to_dict_is_json_serializable(self, font_dir, tmp_path):
323
+ import json
324
+ md = tmp_path / "doc.md"
325
+ write(str(md), "# T\n\nbefore <span>x</span>\n")
326
+ result = build_markdown(str(md), str(tmp_path / "o.pdf"), plugins=PLAIN)
327
+ data = json.loads(json.dumps(result.to_dict()))
328
+ assert data["ok"] is True and data["pdf"] == str(tmp_path / "o.pdf")
329
+ assert data["diagnostics"][0]["severity"] == "warning"
330
+ assert set(data["timings_ms"]) >= {"render", "compile", "total"}
@@ -6,7 +6,8 @@ import os
6
6
 
7
7
  import pytest
8
8
 
9
- import text_compositor.build as build
9
+ from text_compositor.config import _resolve_project_image_path
10
+ from text_compositor.renderer import TypstRenderer
10
11
 
11
12
 
12
13
  class TestResolveAsset:
@@ -14,7 +15,7 @@ class TestResolveAsset:
14
15
  temp_build.typの置き場所に依存しないtypst_root起点のルート絶対パスへ変換する。"""
15
16
 
16
17
  def _renderer(self, tmp_path):
17
- renderer = build.TypstRenderer(line_mapping="off", base_dir=str(tmp_path), typst_root=str(tmp_path))
18
+ renderer = TypstRenderer(line_mapping="off", base_dir=str(tmp_path), typst_root=str(tmp_path))
18
19
  renderer.current_dir = str(tmp_path)
19
20
  renderer.current_file = str(tmp_path / "doc.md")
20
21
  return renderer
@@ -44,7 +45,7 @@ class TestResolveAsset:
44
45
  project_dir = tmp_path / "project"
45
46
  project_dir.mkdir()
46
47
  (project_dir / "a.png").write_bytes(b"\x89PNG")
47
- renderer = build.TypstRenderer(line_mapping="off", base_dir=str(project_dir), typst_root=str(tmp_path))
48
+ renderer = TypstRenderer(line_mapping="off", base_dir=str(project_dir), typst_root=str(tmp_path))
48
49
  renderer.current_dir = str(project_dir)
49
50
  renderer.current_file = str(project_dir / "doc.md")
50
51
  assert renderer._resolve_asset("a.png") == "/project/a.png"
@@ -54,20 +55,20 @@ class TestResolveProjectImagePath:
54
55
  """document.background/logo、chapters[].background/logo(project_dir基準)の解決。"""
55
56
 
56
57
  def test_none_path_returns_none(self, tmp_path):
57
- assert build._resolve_project_image_path(None, str(tmp_path), str(tmp_path), "Logo") is None
58
+ assert _resolve_project_image_path(None, str(tmp_path), str(tmp_path), "Logo") is None
58
59
 
59
60
  def test_existing_file_resolves_to_root_absolute_path(self, tmp_path):
60
61
  (tmp_path / "logo.png").write_bytes(b"\x89PNG")
61
- result = build._resolve_project_image_path("logo.png", str(tmp_path), str(tmp_path), "Logo")
62
+ result = _resolve_project_image_path("logo.png", str(tmp_path), str(tmp_path), "Logo")
62
63
  assert result == "/logo.png"
63
64
 
64
65
  def test_missing_file_exits(self, tmp_path):
65
66
  with pytest.raises(SystemExit):
66
- build._resolve_project_image_path("missing.png", str(tmp_path), str(tmp_path), "Logo")
67
+ _resolve_project_image_path("missing.png", str(tmp_path), str(tmp_path), "Logo")
67
68
 
68
69
  def test_resolves_relative_to_typst_root_not_base_dir(self, tmp_path):
69
70
  project_dir = tmp_path / "project"
70
71
  project_dir.mkdir()
71
72
  (project_dir / "logo.png").write_bytes(b"\x89PNG")
72
- result = build._resolve_project_image_path("logo.png", str(project_dir), str(tmp_path), "Logo")
73
+ result = _resolve_project_image_path("logo.png", str(project_dir), str(tmp_path), "Logo")
73
74
  assert result == "/project/logo.png"
@@ -0,0 +1,111 @@
1
+ """共通の補助関数`_common.typ`(#63)のリグレッションテスト。"""
2
+ import os
3
+ import re
4
+
5
+ import pytest
6
+
7
+ import text_compositor.build as build
8
+ from text_compositor.changes import _is_up_to_date
9
+ from text_compositor.config import _load_project_config
10
+ from text_compositor.document import _prepare_template
11
+
12
+ TOOL_DIR = os.path.dirname(os.path.abspath(build.__file__))
13
+ TEMPLATES = os.path.join(TOOL_DIR, "templates")
14
+ HELPERS = ["fit-image", "render-graph", "render-header", "render-footer", "render-background", "callout"]
15
+
16
+
17
+ def read(name):
18
+ with open(os.path.join(TEMPLATES, name), encoding="utf-8") as f:
19
+ return f.read()
20
+
21
+
22
+ def write(path, text="x"):
23
+ os.makedirs(os.path.dirname(path), exist_ok=True)
24
+ with open(path, "w", encoding="utf-8") as f:
25
+ f.write(text)
26
+
27
+
28
+ class TestBundledTemplates:
29
+ def test_common_defines_all_helpers(self):
30
+ common = read("_common.typ")
31
+ for name in HELPERS:
32
+ assert re.search(rf"^#let {re.escape(name)}\(", common, re.MULTILINE), name
33
+
34
+ def test_template_reexports_all_helpers_from_common(self):
35
+ """build.pyの生成コードはtemplate.typからimportするため、全補助関数が見える必要がある。"""
36
+ tpl = read("template.typ")
37
+ m = re.search(r'^#import "_common\.typ": (.+)$', tpl, re.MULTILINE)
38
+ assert m
39
+ assert set(HELPERS) <= {n.strip() for n in m.group(1).split(",")}
40
+
41
+ def test_helpers_are_not_defined_twice_in_template(self):
42
+ for name in ("fit-image", "render-graph", "callout", "render-background"):
43
+ for tpl_name in ("template.typ", "slide.typ"):
44
+ assert not re.search(rf"^#let {re.escape(name)}\(", read(tpl_name), re.MULTILINE), (tpl_name, name)
45
+
46
+ def test_slide_keeps_its_own_header_and_footer(self):
47
+ slide = read("slide.typ")
48
+ assert re.search(r"^#let render-header\(", slide, re.MULTILINE)
49
+ assert re.search(r"^#let render-footer\(", slide, re.MULTILINE)
50
+ m = re.search(r'^#import "_common\.typ": (.+)$', slide, re.MULTILINE)
51
+ assert "render-header" not in m.group(1) and "render-footer" not in m.group(1)
52
+
53
+
54
+ class TestPrepareTemplate:
55
+ @pytest.fixture
56
+ def env(self, tmp_path):
57
+ project_dir = tmp_path / "proj"
58
+ work_dir = project_dir / ".text-compositor"
59
+ work_dir.mkdir(parents=True)
60
+ return project_dir, work_dir
61
+
62
+ def test_common_is_copied_next_to_template(self, env):
63
+ project_dir, work_dir = env
64
+ config = {"template": {"path": "template"}}
65
+ copy_path, _ = _prepare_template(config, TOOL_DIR, str(project_dir), str(work_dir), str(project_dir))
66
+ assert os.path.dirname(copy_path) == str(work_dir)
67
+ assert (work_dir / "_common.typ").read_text(encoding="utf-8") == read("_common.typ")
68
+
69
+ def test_common_is_copied_for_custom_typ_template(self, env):
70
+ """アダプタ(独自の.typ)も、隣の_common.typを相対パスで読み込める。"""
71
+ project_dir, work_dir = env
72
+ write(str(project_dir / "adapter.typ"), '#import "_common.typ": fit-image\n')
73
+ config = {"template": {"path": "adapter.typ"}}
74
+ _prepare_template(config, TOOL_DIR, str(project_dir), str(work_dir), str(project_dir))
75
+ assert (work_dir / "_common.typ").exists()
76
+
77
+
78
+ class TestCleanRemovesCommon:
79
+ def test_clean_removes_common_copy(self, tmp_path):
80
+ cfg = str(tmp_path / "c.yaml")
81
+ write(cfg, "chapters: [a.md]\n")
82
+ work = tmp_path / ".text-compositor"
83
+ write(str(work / "_common.typ"))
84
+ write(str(work / "_template.typ"))
85
+ build._clean_one(cfg, include_cache=False)
86
+ assert not work.exists()
87
+
88
+
89
+ class TestIfChangedDependsOnCommon:
90
+ def test_newer_common_makes_output_stale(self, tmp_path):
91
+ """同梱の補助関数が更新(pip upgrade等)されたら、入力が同じでも再生成する。"""
92
+ tool = tmp_path / "tool"
93
+ for name in ("templates/template.typ", "templates/_common.typ", "build.py"):
94
+ write(str(tool / name))
95
+ cfg = str(tmp_path / "proj" / "c.yaml")
96
+ write(cfg, "chapters: [a.md]\n")
97
+ pdf = str(tmp_path / "proj" / "outputs" / "System_Specification.pdf")
98
+ write(pdf)
99
+
100
+ def mtime(path, sec):
101
+ os.utime(path, ns=(int(sec * 1e9), int(sec * 1e9)))
102
+
103
+ for p in (str(tool / "templates" / "template.typ"), str(tool / "build.py"), cfg):
104
+ mtime(p, 1000)
105
+ mtime(str(tool / "templates" / "_common.typ"), 1000)
106
+ mtime(pdf, 2000)
107
+ project_dir, config, _ = _load_project_config(cfg)
108
+ assert _is_up_to_date(str(tool), cfg, project_dir, config)[0] is True
109
+
110
+ mtime(str(tool / "templates" / "_common.typ"), 3000)
111
+ assert _is_up_to_date(str(tool), cfg, project_dir, config)[0] is False