Source code for wads.docs_ignore

"""Remove the legacy ``docs/*`` line from a repo's ``.gitignore`` (i2mint/wads#249).

Old wads templates ignored the whole ``docs/`` directory, which silently drops
hand-written docs. :func:`fix_docs_ignore` deletes those lines, keeps build output
ignored with ``docs/_build/``, and first checks that no file under ``docs/`` that is
ignored today would show up as untracked afterwards.

>>> new_gitignore("*.pyc\\ndocs/*\\n")
'*.pyc\\ndocs/_build/\\n'
>>> new_gitignore("docs/*\\ndocs/_build/\\n")
'docs/_build/\\n'
>>> new_gitignore("*.pyc\\n") is None
True
"""

from __future__ import annotations

import subprocess
from pathlib import Path

from wads.repo_audit import _DOCS_IGNORE_PATTERNS

#: What replaces the legacy line: build output stays ignored.
KEEP_IGNORED = "docs/_build/"


[docs] def new_gitignore(text: str) -> str | None: """``.gitignore`` text without the legacy docs lines, or ``None`` if there are none.""" lines = text.splitlines() kept = [line for line in lines if line.strip() not in _DOCS_IGNORE_PATTERNS] if len(kept) == len(lines): return None if KEEP_IGNORED not in (line.strip() for line in kept): # Put it where the first legacy line was, so the file keeps its shape. first = next( i for i, line in enumerate(lines) if line.strip() in _DOCS_IGNORE_PATTERNS ) kept.insert(min(first, len(kept)), KEEP_IGNORED) return "\n".join(kept) + "\n"
[docs] def exposed_files(repo: str | Path) -> list[str]: """Files under ``docs/`` that are ignored now and would not stay ignored by ``docs/_build/``.""" out = subprocess.run( [ "git", "-C", str(repo), "ls-files", "--others", "--ignored", "--exclude-standard", "--", "docs", ], capture_output=True, text=True, ).stdout.split("\n") return [f for f in out if f and not f.startswith(KEEP_IGNORED)]
[docs] def fix_docs_ignore( repo: str | Path = ".", *, apply: bool = False, force: bool = False ) -> dict: """Plan (and with ``apply=True`` write) the removal of the legacy ``docs/*`` line. Returns ``{"status": ..., "exposed": [...]}`` where status is ``"clean"`` (nothing to do), ``"blocked"`` (files under ``docs/`` would be exposed; pass ``force=True`` to proceed), ``"planned"`` or ``"fixed"``. """ path = Path(repo) / ".gitignore" text = path.read_text() if path.exists() else "" new = new_gitignore(text) if new is None: return {"status": "clean", "exposed": []} exposed = exposed_files(repo) if exposed and not force: return {"status": "blocked", "exposed": exposed} if not apply: return {"status": "planned", "exposed": exposed} path.write_text(new) return {"status": "fixed", "exposed": exposed}