|
| 1 | +import importlib.resources |
| 2 | +import shutil |
| 3 | +import subprocess |
| 4 | +import sys |
| 5 | +import tempfile |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +import click |
| 9 | + |
| 10 | +from ... import args4p |
| 11 | +from ...app import Application |
| 12 | + |
| 13 | +DOCSITE_REPO = 'git@github.com:cloudbees/docsite-cloudbees-smart-tests.git' |
| 14 | +OUTPUT_DIR = 'smart-tests-docs' |
| 15 | + |
| 16 | + |
| 17 | +def _find_bundled_docs() -> Path | None: |
| 18 | + """Return the path to the bundled docs/ directory, or None if not present.""" |
| 19 | + pkg = importlib.resources.files('smart_tests') / 'docs' |
| 20 | + # files() returns a Traversable; check it's a real, non-empty directory |
| 21 | + try: |
| 22 | + p = Path(str(pkg)) |
| 23 | + if p.is_dir() and any(p.iterdir()): |
| 24 | + return p |
| 25 | + except (TypeError, OSError): |
| 26 | + pass |
| 27 | + return None |
| 28 | + |
| 29 | + |
| 30 | +def _fetch_docs_via_git() -> Path: |
| 31 | + """ |
| 32 | + Clone the docsite repo into smart_tests/docs/ (relative to this package's |
| 33 | + location) and return the path to the docs/ subdirectory. |
| 34 | +
|
| 35 | + If smart_tests/docs/ already exists, run `git pull` instead of cloning. |
| 36 | + """ |
| 37 | + package_dir = Path(__file__).parent.parent.parent # smart_tests/ |
| 38 | + docs_dst = package_dir / 'docs' |
| 39 | + |
| 40 | + if docs_dst.is_dir(): |
| 41 | + click.echo(f"Updating docs from {DOCSITE_REPO} ...") |
| 42 | + subprocess.run(['git', '-C', str(docs_dst), 'pull'], check=True) |
| 43 | + else: |
| 44 | + click.echo(f"Cloning docs from {DOCSITE_REPO} ...") |
| 45 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 46 | + subprocess.run( |
| 47 | + ['git', 'clone', '--depth=1', DOCSITE_REPO, tmpdir], |
| 48 | + check=True, |
| 49 | + ) |
| 50 | + shutil.copytree(Path(tmpdir) / 'docs', docs_dst) |
| 51 | + |
| 52 | + return docs_dst |
| 53 | + |
| 54 | + |
| 55 | +@args4p.command(help="Copy product documentation into ./smart-tests-docs") |
| 56 | +def docs(app: Application): |
| 57 | + output = Path(OUTPUT_DIR) |
| 58 | + if output.exists(): |
| 59 | + click.secho( |
| 60 | + f"'{OUTPUT_DIR}' already exists. Please delete it first, then re-run this command.", |
| 61 | + fg='red', err=True, |
| 62 | + ) |
| 63 | + sys.exit(1) |
| 64 | + |
| 65 | + docs_src = _find_bundled_docs() |
| 66 | + if docs_src is None: |
| 67 | + # Dev mode: not running from an installed package |
| 68 | + docs_src = _fetch_docs_via_git() |
| 69 | + |
| 70 | + click.echo(f"Copying docs to ./{OUTPUT_DIR} ...") |
| 71 | + shutil.copytree(docs_src, output) |
| 72 | + click.echo(f"Done. Documentation is in ./{OUTPUT_DIR}") |
0 commit comments