|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Bulk S3 redirect creator. |
| 3 | +
|
| 4 | +Reads redirects from scripts/redirects_v2.yml (expects list of mapping with |
| 5 | +`old` and `new` keys) and calls `scripts/create-redirect.sh` for each redirect. |
| 6 | +
|
| 7 | +Usage: |
| 8 | + python scripts/create-redirect.py <bucket_name> [--start N] [--end M] |
| 9 | +
|
| 10 | +Options: |
| 11 | + --start N Start index (inclusive) in redirects list to process. Default 0. |
| 12 | + --end M End index (exclusive). Default len(list). |
| 13 | +
|
| 14 | +The slice options are useful for testing a subset. |
| 15 | +""" |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import argparse |
| 19 | +import subprocess |
| 20 | +import sys |
| 21 | +from pathlib import Path |
| 22 | + |
| 23 | +try: |
| 24 | + import yaml # type: ignore |
| 25 | +except ImportError: # pragma: no cover |
| 26 | + sys.stderr.write("[ERROR] PyYAML is required. Install with: pip install pyyaml\n") |
| 27 | + sys.exit(1) |
| 28 | + |
| 29 | +ROOT_DIR = Path(__file__).resolve().parent.parent # repo root (circleci-docs-static) |
| 30 | +REDIRECTS_FILE = ROOT_DIR / "scripts" / "redirects_v2.yml" |
| 31 | +SH_SCRIPT = ROOT_DIR / "scripts" / "create-redirect.sh" |
| 32 | + |
| 33 | + |
| 34 | +def load_redirects(path: Path) -> list[dict[str, str]]: |
| 35 | + """Load redirects YAML file into list of dicts with 'old' and 'new'.""" |
| 36 | + if not path.exists(): |
| 37 | + raise FileNotFoundError(f"Redirects YAML not found: {path}") |
| 38 | + |
| 39 | + with path.open("r", encoding="utf-8") as fh: |
| 40 | + data = yaml.safe_load(fh) |
| 41 | + |
| 42 | + if not isinstance(data, list): |
| 43 | + raise ValueError("Redirects YAML should be a list of mappings.") |
| 44 | + |
| 45 | + redirects: list[dict[str, str]] = [] |
| 46 | + for item in data: |
| 47 | + if not isinstance(item, dict): |
| 48 | + continue |
| 49 | + old = item.get("old") |
| 50 | + new = item.get("new") |
| 51 | + if old and new: |
| 52 | + redirects.append({"old": str(old), "new": str(new)}) |
| 53 | + return redirects |
| 54 | + |
| 55 | + |
| 56 | +def create_redirect(bucket: str, old_path: str, new_path: str) -> None: |
| 57 | + """Call the shell script to create a single redirect.""" |
| 58 | + cmd = [ |
| 59 | + "bash", |
| 60 | + str(SH_SCRIPT), |
| 61 | + bucket, |
| 62 | + old_path, |
| 63 | + new_path, |
| 64 | + ] |
| 65 | + subprocess.run(cmd, check=True) |
| 66 | + |
| 67 | + |
| 68 | +def main() -> None: |
| 69 | + parser = argparse.ArgumentParser(description="Bulk S3 redirect creator") |
| 70 | + parser.add_argument("bucket", help="Target S3 bucket name") |
| 71 | + parser.add_argument("--start", type=int, default=0, help="Start index (inclusive)") |
| 72 | + parser.add_argument("--end", type=int, default=None, help="End index (exclusive)") |
| 73 | + args = parser.parse_args() |
| 74 | + |
| 75 | + redirects = load_redirects(REDIRECTS_FILE) |
| 76 | + end = args.end if args.end is not None else len(redirects) |
| 77 | + |
| 78 | + slice_redirects = redirects[args.start : end] |
| 79 | + total = len(slice_redirects) |
| 80 | + print(f"[INFO] Processing {total} redirects (indexes {args.start}-{end-1})...") |
| 81 | + |
| 82 | + for idx, entry in enumerate(slice_redirects, start=args.start): |
| 83 | + old = entry["old"] |
| 84 | + new = entry["new"] |
| 85 | + try: |
| 86 | + print(f"[INFO] ({idx}) Creating redirect {old} -> {new}") |
| 87 | + create_redirect(args.bucket, old, new) |
| 88 | + except subprocess.CalledProcessError as exc: |
| 89 | + print(f"[ERROR] Failed to create redirect for {old}: {exc}", file=sys.stderr) |
| 90 | + |
| 91 | + |
| 92 | +if __name__ == "__main__": |
| 93 | + main() |
0 commit comments