|
| 1 | +import subprocess |
| 2 | +import sys |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +DOCS_DIR = Path("docusaurus/docs") |
| 6 | +REPO_ROOT = Path(".") |
| 7 | + |
| 8 | +def get_created_md_files(): |
| 9 | + """ |
| 10 | + Identify and return a list of Markdown (.md, .mdx) files that were added |
| 11 | + in the current Git branch compared to the main branch. |
| 12 | + The function uses `git diff` to determine the files that have been added |
| 13 | + (status "A") and filters them to include only Markdown files located within |
| 14 | + the documentation directory. |
| 15 | + Returns: |
| 16 | + list[Path]: A list of relative paths to the newly created Markdown files. |
| 17 | + """ |
| 18 | + result = subprocess.run( |
| 19 | + ["git", "diff", "--name-status", "origin/main...HEAD"], |
| 20 | + stdout=subprocess.PIPE, |
| 21 | + text=True, |
| 22 | + check=True |
| 23 | + ) |
| 24 | + |
| 25 | + created_files = [] |
| 26 | + for line in result.stdout.strip().splitlines(): |
| 27 | + status, filepath = line.split(maxsplit=1) |
| 28 | + path = Path(filepath) |
| 29 | + if status == "A" and path.suffix in [".md", ".mdx"] and DOCS_DIR in path.parents: |
| 30 | + created_files.append(path.relative_to(REPO_ROOT)) |
| 31 | + |
| 32 | + return created_files |
| 33 | + |
| 34 | +def is_file_referenced(file_path): |
| 35 | + """ |
| 36 | + Checks if a given file is referenced in the Git repository. |
| 37 | + This function searches the Git repository for occurrences of the file name |
| 38 | + and determines if the file is referenced in any other files. |
| 39 | + Args: |
| 40 | + file_path (Path): The path to the file to check. |
| 41 | + Returns: |
| 42 | + bool: True if the file is referenced in other files, False otherwise. |
| 43 | + """ |
| 44 | + file_name = file_path.name |
| 45 | + result = subprocess.run( |
| 46 | + ["git", "grep", "-l", file_name], |
| 47 | + stdout=subprocess.PIPE, |
| 48 | + text=True |
| 49 | + ) |
| 50 | + |
| 51 | + matches = [line for line in result.stdout.strip().splitlines() if Path(line) != file_path] |
| 52 | + return len(matches) > 0 |
| 53 | + |
| 54 | +def main(): |
| 55 | + created_files = get_created_md_files() |
| 56 | + if not created_files: |
| 57 | + print("No new Markdown files detected.") |
| 58 | + return |
| 59 | + |
| 60 | + print(f"Checking {len(created_files)} new Markdown files...") |
| 61 | + |
| 62 | + unreferenced = [] |
| 63 | + |
| 64 | + for md_file in created_files: |
| 65 | + if not is_file_referenced(md_file): |
| 66 | + unreferenced.append(md_file) |
| 67 | + |
| 68 | + if unreferenced: |
| 69 | + print("❌ The following new files are unreferenced:") |
| 70 | + for f in unreferenced: |
| 71 | + print(f" - {f}") |
| 72 | + sys.exit(1) |
| 73 | + else: |
| 74 | + print("✅ All new Markdown files are referenced.") |
| 75 | + |
| 76 | +if __name__ == "__main__": |
| 77 | + main() |
0 commit comments