@@ -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+
6179def _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 } " )
0 commit comments