Turn any technical book PDF into a Claude Code skill — ready to study, reference, and use while you work.
Python agent-skillsai-agentsbook-to-skillcontext-engineeringdocument-processingedtechknowledge-baseknowledge-managementllmpdf-to-markdownragself-studystudy-tools
fix(extractor): preserve corpus newlines on Windows (#264)
Stamina9c2751f532873
diff --git a/book_to_skill/utils.py b/book_to_skill/utils.pyindex 9b7494d..82cb43e 100644--- a/book_to_skill/utils.py+++ b/book_to_skill/utils.py@@ -1449,8 +1449,11 @@ def main():# Combine textsconsolidated_text = "".join(combined_texts).strip()- # Write combined text- OUTPUT_TEXT.write_text(consolidated_text, encoding="utf-8")+ # Preserve existing source line endings. On Windows, the default newline+ # translation turns an extracted CRLF into CRCRLF and breaks setext headings+ # when the persisted corpus is read back.+ with OUTPUT_TEXT.open("w", encoding="utf-8", newline="\n") as output_file:+ output_file.write(consolidated_text)# Consolidate metadatatotal_file_size_mb = sum(src["file_size_mb"] for src in extracted_sources)diff --git a/tests/test_corpus_newlines.py b/tests/test_corpus_newlines.pynew file mode 100644index 0000000..c0f518d--- /dev/null+++ b/tests/test_corpus_newlines.py@@ -0,0 +1,100 @@+"""The persisted corpus must not gain blank lines from newline translation."""++import json+import os+import subprocess+import sys+from pathlib import Path++import pytest++from book_to_skill.utils import detect_structure+++ROOT = Path(__file__).resolve().parent.parent+SOURCE = (+ "Alpha heading\n=============\n"+ "\talpha body line one\n alpha body line two\n\n"+ "Beta heading\n============\n"+ "beta body line one\nbeta body line two\n"+)+++ "source_bytes",+ [+ SOURCE.encode("utf-8"),+ SOURCE.replace("\n", "\r\n").encode("utf-8"),+ SOURCE.replace("\n", "\r").encode("utf-8"),+ SOURCE.replace("\n", "\r\n", 3).encode("utf-8"),+ SOURCE.replace("\n", "\r\n").encode("utf-8-sig"),+ SOURCE.replace("\n", "\r\n").encode("utf-16"),+ SOURCE.replace("\n", "\r\n").encode("utf-32"),+ ],+ ids=["lf", "crlf", "cr", "mixed", "utf8-bom-crlf", "utf16-crlf", "utf32-crlf"],+)+def test_cli_preserves_source_line_structure(tmp_path, source_bytes):+ source = tmp_path / "synthetic.md"+ source.write_bytes(source_bytes)+ output = tmp_path / "output"+ environment = dict(os.environ, BOOK_SKILL_WORKDIR=str(output))++ result = subprocess.run(+ [+ sys.executable,+ str(ROOT / "scripts" / "extract.py"),+ str(source),+ "--mode",+ "text",+ "--install-missing",+ "no",+ ],+ env=environment,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=30,+ )+ assert result.returncode == 0, result.stdout + result.stderr++ original = detect_structure(SOURCE)+ raw = (output / "full_text.txt").read_bytes()+ reread = (output / "full_text.txt").read_text(encoding="utf-8")+ body = reread.split("=" * 80, 2)[-1].lstrip("\n")+ metadata = json.loads((output / "metadata.json").read_text(encoding="utf-8"))++ assert b"\r\r\n" not in raw+ assert body == SOURCE.strip()+ assert len(body.splitlines()) == len(SOURCE.strip().splitlines())+ assert detect_structure(body)["chapters_detected"] == original["chapters_detected"] == 2+ assert metadata["chapters_detected"] == 2+ assert metadata["chars"] == len(raw.decode("utf-8"))+++def test_corpus_writer_explicitly_disables_host_newline_translation(+ tmp_path, monkeypatch+):+ """The Linux CI leg must also pin the Windows-specific writer contract."""+ source = tmp_path / "synthetic.md"+ source.write_bytes(SOURCE.replace("\n", "\r\n").encode("utf-8"))+ output = tmp_path / "output"+ observed = []+ real_open = Path.open++ def record_open(self, mode="r", *args, **kwargs):+ if self.name == "full_text.txt" and mode == "w":+ observed.append(kwargs.get("newline"))+ return real_open(self, mode, *args, **kwargs)++ monkeypatch.setattr(Path, "open", record_open)+ monkeypatch.setattr("book_to_skill.utils.OUTPUT_DIR", output)+ monkeypatch.setattr("book_to_skill.utils.OUTPUT_TEXT", output / "full_text.txt")+ monkeypatch.setattr("book_to_skill.utils.OUTPUT_META", output / "metadata.json")+ monkeypatch.setattr("sys.argv", ["extract.py", str(source), "--install-missing", "no"])++ from book_to_skill.utils import main++ main()++ assert observed == ["\n"]diff --git a/tests/test_sanitize_extracted_text.py b/tests/test_sanitize_extracted_text.pyindex 564cdbd..55e3e9e 100644--- a/tests/test_sanitize_extracted_text.py+++ b/tests/test_sanitize_extracted_text.py@@ -84,7 +84,9 @@ def test_main_writes_only_sanitized_text_and_metrics(tmp_path, monkeypatch):main()- extracted = output_text.read_text(encoding="utf-8")+ # Read the persisted characters without universal-newline conversion so+ # the length matches the corpus representation counted in metadata.+ extracted = output_text.read_bytes().decode("utf-8")metadata = json.loads(output_meta.read_text(encoding="utf-8"))expected_source, _ = sanitize_extracted_text(source.read_bytes().decode("utf-8")