Skip to content

Commit 768510b

Browse files
Darshan M Uclaude
andcommitted
Back up uncommitted docs before --update edits them; never clear a repo root
A full-build fallback copied the docs aside only at fallback time, after the update had already deleted and rewritten pages: on this repo the copy was missing 25 of 41 pages. Uncommitted docs are now copied to <docs>.prev-<commit>/ (git-ignored, latest only, without temp/ since the graph is rebuilt from git) when --update starts, before anything writes into docs/; the copy is dropped again when the update succeeds in place. Committed, clean docs still rely on git. Neither path clears or moves a folder that is a repo root (docs written with --output .), which the old move-aside would have done. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CXRqeijND7XPq2srGHndRd
1 parent a6847d1 commit 768510b

2 files changed

Lines changed: 116 additions & 20 deletions

File tree

‎codewiki/cli/adapters/doc_generator.py‎

Lines changed: 71 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,24 @@ def git(*args: str) -> str | None:
5858
return bool(tracked and tracked.strip()) and status is not None and not status.strip()
5959

6060

61+
def _is_repo_root(path: Path) -> bool:
62+
"""True for a git checkout's top folder (never cleared or moved wholesale)."""
63+
if (path / ".git").exists():
64+
return True
65+
import subprocess
66+
67+
try:
68+
out = subprocess.run(
69+
["git", "-C", str(path), "rev-parse", "--show-toplevel"],
70+
capture_output=True,
71+
text=True,
72+
timeout=30,
73+
)
74+
except (OSError, subprocess.SubprocessError):
75+
return False
76+
return out.returncode == 0 and Path(out.stdout.strip()).resolve() == path.resolve()
77+
78+
6179
def _module_file_count(module_info: dict) -> int:
6280
"""Distinct source files in a module and its sub-modules.
6381
@@ -284,6 +302,10 @@ async def _run_backend_generation(self, backend_config: BackendConfig):
284302
# Decide before anything below writes into docs/: if they are committed and
285303
# unmodified now, git holds exactly them, so a full build needs no backup copy.
286304
self._docs_clean_at_start = _committed_and_clean(self.output_dir)
305+
if not self._docs_clean_at_start:
306+
# Not in git: back them up now, while they are still the previous docs (the
307+
# update deletes and rewrites pages before it may fall back to a full build).
308+
self._backup_docs()
287309

288310
prev_graph_path = snapshot_old_graph(
289311
backend_config.dependency_graph_dir, str(self.repo_path)
@@ -339,6 +361,7 @@ async def _run_backend_generation(self, backend_config: BackendConfig):
339361
backend_config.dependency_graph_dir,
340362
keep=graph_file_path(backend_config.dependency_graph_dir, str(self.repo_path)),
341363
)
364+
self._drop_docs_backup() # updated in place: the backup is not needed
342365
return
343366
# full_fallback / detector_failure: preserve the old docs, rebuild from scratch
344367
self._move_docs_aside()
@@ -564,36 +587,64 @@ async def _run_incremental_update(
564587
self.progress_tracker.complete_stage()
565588
return record.outcome
566589

590+
def _backup_docs(self) -> None:
591+
"""Copy the docs to ``<docs>.prev-<commit>`` beside them, before the update edits them.
592+
593+
Git-ignored (outside docs/, `git add .` would otherwise commit a full copy); only the
594+
latest backup is kept. temp/ is left out: it is the bulk of the size, and the graph
595+
is rebuilt from the docs' commit when missing.
596+
"""
597+
import shutil
598+
599+
if not self.output_dir.is_dir() or _is_repo_root(self.output_dir):
600+
return
601+
if not any(self.output_dir.iterdir()):
602+
return
603+
name = self.output_dir.name
604+
for old in self.output_dir.parent.glob(f"{name}.prev-*"):
605+
if old.is_dir():
606+
shutil.rmtree(old, ignore_errors=True)
607+
target = self.output_dir.parent / f"{name}.prev-{(self.commit_id or 'unknown')[:8]}"
608+
shutil.copytree(self.output_dir, target, ignore=shutil.ignore_patterns("temp"))
609+
(target / ".gitignore").write_text(
610+
"# CodeWiki backup of the previous docs. Do not commit; delete when done.\n*\n",
611+
encoding="utf-8",
612+
)
613+
self._preserved_docs_dir = str(target)
614+
615+
def _drop_docs_backup(self) -> None:
616+
import shutil
617+
618+
backup = getattr(self, "_preserved_docs_dir", None)
619+
if backup:
620+
shutil.rmtree(backup, ignore_errors=True)
621+
self._preserved_docs_dir = None
622+
567623
def _move_docs_aside(self) -> None:
568624
"""Clear the output dir for a full rebuild, keeping the previous docs recoverable.
569625
570-
Docs that were committed and unmodified when the update started are safe in git
571-
(the update itself has written into docs/ by now), so nothing is copied. Otherwise
572-
the docs move to ``<docs>.prev-<commit>`` next to the output dir: git-ignored (it
573-
sits outside docs/, where `git add .` would pick up a full copy of the docs) and
574-
only the latest such copy is kept.
626+
Docs that were committed and unmodified when the update started are safe in git;
627+
others were backed up by ``_backup_docs`` before the update touched them. A repo
628+
root is never cleared.
575629
"""
576630
import shutil
577631

578632
record = getattr(self, "_last_update_record", None)
579633
name = self.output_dir.name
580-
if getattr(self, "_docs_clean_at_start", False):
581-
shutil.rmtree(self.output_dir)
582-
self.output_dir.mkdir(parents=True, exist_ok=True)
583-
note = f"previous docs are in git; restore them with: git restore --source=HEAD {name}/"
634+
if _is_repo_root(self.output_dir):
635+
note = "docs are written to the repo root, which is never cleared"
584636
else:
585-
for old in self.output_dir.parent.glob(f"{name}.prev-*"):
586-
if old.is_dir():
587-
shutil.rmtree(old, ignore_errors=True)
588-
target = self.output_dir.parent / f"{name}.prev-{(self.commit_id or 'unknown')[:8]}"
589-
shutil.move(str(self.output_dir), str(target))
590-
(target / ".gitignore").write_text(
591-
"# CodeWiki backup of the previous docs. Do not commit; delete when done.\n*\n",
592-
encoding="utf-8",
593-
)
637+
if getattr(self, "_docs_clean_at_start", False):
638+
note = f"previous docs are in git; restore them with: git restore --source=HEAD {name}/"
639+
else:
640+
if not getattr(self, "_preserved_docs_dir", None):
641+
self._backup_docs()
642+
note = (
643+
f"previous docs saved to {self._preserved_docs_dir} "
644+
"(not committed; delete it when done)"
645+
)
646+
shutil.rmtree(self.output_dir)
594647
self.output_dir.mkdir(parents=True, exist_ok=True)
595-
self._preserved_docs_dir = str(target)
596-
note = f"previous docs moved to {target} (not committed; delete it when done)"
597648
if record is not None:
598649
record.detector_notes.append(note)
599650
self.progress_tracker.note(f"Full rebuild: {note}")

‎tests/test_updater_graph_store.py‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,3 +302,48 @@ def test_saved_graph_holds_no_absolute_paths(tmp_path):
302302

303303
save_graph(components, str(tmp_path / "copy.json")) # the updater's writer too
304304
assert str(tmp_path) not in (tmp_path / "copy.json").read_text(encoding="utf-8")
305+
306+
307+
def test_uncommitted_docs_are_backed_up_before_the_update_edits_them(tmp_path):
308+
"""The backup used to be taken at fallback time, after the update had deleted pages."""
309+
repo = _repo_with_docs(tmp_path)
310+
docs = repo / "docs"
311+
(docs / "overview.md").write_text("# Edited, not committed\n")
312+
(docs / "page.md").write_text("# A page the update deletes\n")
313+
(docs / "temp" / "dependency_graphs").mkdir(parents=True)
314+
(docs / "temp" / "dependency_graphs" / "g.json").write_text("{}")
315+
gen = _gen_for(docs)
316+
gen._docs_clean_at_start = False
317+
gen._backup_docs() # what --update does first when docs are not committed
318+
319+
(docs / "page.md").unlink() # the update invalidates pages...
320+
(docs / "overview.md").write_text("# Half-rewritten\n") # ...and rewrites others
321+
gen._move_docs_aside() # then falls back to a full build
322+
323+
backup = repo / "docs.prev-abcdef12"
324+
assert (backup / "page.md").read_text() == "# A page the update deletes\n"
325+
assert (backup / "overview.md").read_text() == "# Edited, not committed\n"
326+
assert not (backup / "temp").exists() # the graph is rebuilt from git when needed
327+
assert os.listdir(docs) == []
328+
329+
330+
def test_successful_update_drops_the_backup(tmp_path):
331+
repo = _repo_with_docs(tmp_path)
332+
(repo / "docs" / "overview.md").write_text("# Edited\n")
333+
gen = _gen_for(repo / "docs")
334+
gen._backup_docs()
335+
assert (repo / "docs.prev-abcdef12").is_dir()
336+
gen._drop_docs_backup()
337+
assert not list(repo.glob("docs.prev-*"))
338+
339+
340+
def test_a_repo_root_is_never_cleared(tmp_path):
341+
repo = _repo_with_docs(tmp_path)
342+
(repo / "overview.md").write_text("# docs written to the repo root\n")
343+
gen = _gen_for(repo)
344+
gen._docs_clean_at_start = False
345+
gen._backup_docs()
346+
gen._move_docs_aside()
347+
assert (repo / "overview.md").exists() and (repo / ".git").exists()
348+
assert not list(tmp_path.glob("repo.prev-*"))
349+
assert "never cleared" in gen.notes[-1]

0 commit comments

Comments
 (0)