|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import yaml |
| 4 | +import sys # Import the sys module to access command-line arguments |
| 5 | + |
| 6 | +# Define a constant for the default pre-commit config filename |
| 7 | +DEFAULT_PRE_COMMIT_CONFIG_FILE = ".pre-commit-config.yaml" |
| 8 | + |
| 9 | +def generate_pre_commit_table(yaml_path): |
| 10 | + """ |
| 11 | + Generates a Markdown table from a pre-commit-config.yaml file. |
| 12 | +
|
| 13 | + Args: |
| 14 | + yaml_path (str): The path to the pre-commit-config.yaml file. |
| 15 | +
|
| 16 | + Returns: |
| 17 | + str: A Markdown formatted table string or an error message. |
| 18 | + """ |
| 19 | + try: |
| 20 | + with open(yaml_path, 'r', encoding='utf-8') as f: # Added encoding for better compatibility |
| 21 | + config = yaml.safe_load(f) |
| 22 | + except FileNotFoundError: |
| 23 | + return f"Error: The file '{yaml_path}' was not found." |
| 24 | + except yaml.YAMLError as e: |
| 25 | + return f"Error parsing YAML file '{yaml_path}': {e}" |
| 26 | + except Exception as e: |
| 27 | + return f"An unexpected error occurred while reading '{yaml_path}': {e}" |
| 28 | + |
| 29 | + table_header = "| Hook ID | Language | Name | Description | Version |\n" |
| 30 | + table_separator = "|---|---|---|---|---|\n" |
| 31 | + table_rows = [] |
| 32 | + |
| 33 | + # Ensure config is a dictionary and has a 'repos' key that is a list |
| 34 | + if not isinstance(config, dict) or 'repos' not in config or not isinstance(config['repos'], list): |
| 35 | + return f"Error: Invalid pre-commit config structure in '{yaml_path}'. 'repos' section is missing or not a list." |
| 36 | + |
| 37 | + for repo_index, repo in enumerate(config.get("repos", [])): |
| 38 | + if not isinstance(repo, dict): |
| 39 | + print(f"Warning: Repository at index {repo_index} is not a valid dictionary. Skipping.") |
| 40 | + continue |
| 41 | + |
| 42 | + version = repo.get("rev", "N/A") |
| 43 | + url = repo.get("repo", "N/A") |
| 44 | + |
| 45 | + if 'hooks' not in repo or not isinstance(repo['hooks'], list): |
| 46 | + print( |
| 47 | + f"Warning: 'hooks' section not found or is not a list for repo '{url}'. Skipping hooks processing for this repo.") |
| 48 | + continue |
| 49 | + |
| 50 | + for hook_index, hook in enumerate(repo.get("hooks", [])): |
| 51 | + if not isinstance(hook, dict): |
| 52 | + print(f"Warning: Hook at index {hook_index} in repo '{url}' is not a valid dictionary. Skipping.") |
| 53 | + continue |
| 54 | + |
| 55 | + hook_id = hook.get("id", "N/A") |
| 56 | + name = hook.get("name", "N/A") |
| 57 | + description = hook.get("description", "N/A") |
| 58 | + language = hook.get("language", "N/A") |
| 59 | + |
| 60 | + # Construct the entry for the Hook ID column |
| 61 | + if url and url not in ["local", "meta"]: |
| 62 | + entry = f"[{hook_id}]({url})" |
| 63 | + else: |
| 64 | + entry = f"{hook_id}" |
| 65 | + |
| 66 | + table_rows.append(f"| {entry} | {language} | {name} | {description} | {version} |\n") |
| 67 | + |
| 68 | + if not table_rows: |
| 69 | + return f"No hooks found in '{yaml_path}' to generate a table." |
| 70 | + |
| 71 | + return table_header + table_separator + "".join(table_rows) |
| 72 | + |
| 73 | + |
| 74 | +def create_markdown_file(target_file_path, content_to_append): |
| 75 | + """ |
| 76 | + Creates or overwrites a Markdown file with the provided content. |
| 77 | +
|
| 78 | + Args: |
| 79 | + target_file_path (str): The path to the output Markdown file. |
| 80 | + content_to_append (str): The Markdown content to write to the file. |
| 81 | +
|
| 82 | + Returns: |
| 83 | + str: A success message or an error message. |
| 84 | + """ |
| 85 | + try: |
| 86 | + # Ensure the directory exists before writing the file |
| 87 | + import os |
| 88 | + os.makedirs(os.path.dirname(target_file_path), exist_ok=True) |
| 89 | + |
| 90 | + with open(target_file_path, "w", encoding='utf-8') as f: # Changed to 'w' to overwrite, added encoding |
| 91 | + f.write("# pre-commit hook documentation\n\n") |
| 92 | + f.write(content_to_append) |
| 93 | + return f"File content successfully created at '{target_file_path}'." |
| 94 | + except OSError as e: |
| 95 | + return f"Error creating file '{target_file_path}': {e}" |
| 96 | + except Exception as e: |
| 97 | + return f"An unexpected error occurred while writing to '{target_file_path}': {e}" |
| 98 | + |
| 99 | + |
| 100 | +if __name__ == "__main__": |
| 101 | + # Check if a command-line argument for the config file path is provided |
| 102 | + if len(sys.argv) > 1: |
| 103 | + pre_commit_yaml_path = sys.argv[1] |
| 104 | + else: |
| 105 | + # Default file path if no argument is provided |
| 106 | + pre_commit_yaml_path = DEFAULT_PRE_COMMIT_CONFIG_FILE |
| 107 | + print(f"No pre-commit config file path provided. Attempting to use default: '{pre_commit_yaml_path}'") |
| 108 | + |
| 109 | + output_markdown_path = "doc/guides/pre-commit-hooks.md" |
| 110 | + |
| 111 | + # Generate the Markdown table |
| 112 | + markdown_table = generate_pre_commit_table(pre_commit_yaml_path) |
| 113 | + |
| 114 | + # Add the table to the target Markdown file if no error occurred during table generation |
| 115 | + if markdown_table.startswith("Error:"): |
| 116 | + print(markdown_table) # Print the error message from generate_pre_commit_table |
| 117 | + sys.exit(1) # Exit with a non-zero code to indicate failure |
| 118 | + elif markdown_table.startswith("No hooks found:"): |
| 119 | + print(markdown_table) # Print the message if no hooks are found |
| 120 | + sys.exit(0) # Exit with success if no hooks but no other error |
| 121 | + else: |
| 122 | + result = create_markdown_file(output_markdown_path, markdown_table) |
| 123 | + print(result) |
| 124 | + if "Error" in result: |
| 125 | + sys.exit(1) # Exit with failure if create_markdown_file had an error |
| 126 | + else: |
| 127 | + sys.exit(0) # Exit with success |
0 commit comments