|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import sys |
| 3 | +import subprocess |
| 4 | +import json |
| 5 | +import base64 |
| 6 | +import argparse |
| 7 | +from typing import Optional, Tuple |
| 8 | + |
| 9 | +from ssg.rule_yaml import find_section_lines |
| 10 | + |
| 11 | + |
| 12 | +def run_command(command: list[str]) -> tuple[int, str, str]: |
| 13 | + """Runs a shell command and returns its exit code, stdout, and stderr.""" |
| 14 | + res = subprocess.run(command, capture_output=True, text=True, check=False) |
| 15 | + return res.returncode, res.stdout, res.stderr |
| 16 | + |
| 17 | + |
| 18 | +def get_file_content_from_pr(owner: str, repo: str, sha: str, file_path: str) -> str: |
| 19 | + """Fetches file content for a given commit SHA using the GitHub API. |
| 20 | + The base64 encoding and decoding step is necessary because of how the |
| 21 | + GitHub API is designed to transmit file content. |
| 22 | + """ |
| 23 | + api_path = f"/repos/{owner}/{repo}/contents/{file_path}?ref={sha}" |
| 24 | + print(f"-> Fetching file content for '{file_path}' from commit {sha[:7]}...") |
| 25 | + returncode, stdout, stderr = run_command(["gh", "api", api_path]) |
| 26 | + |
| 27 | + if returncode != 0: |
| 28 | + print(f"Exception: Could not fetch file. It may be new or deleted. " |
| 29 | + f"(stderr: {stderr.strip()})") |
| 30 | + return "" |
| 31 | + |
| 32 | + try: |
| 33 | + content_json = json.loads(stdout) |
| 34 | + encoded_content = content_json.get('content', '') |
| 35 | + if not encoded_content: |
| 36 | + return "" |
| 37 | + |
| 38 | + return base64.b64decode(encoded_content).decode('utf-8') |
| 39 | + except (json.JSONDecodeError, KeyError, TypeError) as e: |
| 40 | + print(f"Exception: Could not parse or decode content. Error: {e}", file=sys.stderr) |
| 41 | + return "" |
| 42 | + |
| 43 | + |
| 44 | +def get_section_from_content(content: str, section: str) -> Optional[str]: |
| 45 | + """ |
| 46 | + Extracts a section's value from a string containing the file content. |
| 47 | + """ |
| 48 | + if not content: |
| 49 | + return None |
| 50 | + |
| 51 | + lines = content.splitlines() |
| 52 | + found_ranges = find_section_lines(lines, section) |
| 53 | + |
| 54 | + if found_ranges: |
| 55 | + start, end = found_ranges[0] |
| 56 | + section_content = lines[start: end + 1] |
| 57 | + return '\n'.join(section_content) |
| 58 | + |
| 59 | + return None |
| 60 | + |
| 61 | + |
| 62 | +def get_pr_shas(owner: str, repo: str, pr_number: int) -> Tuple[str, str]: |
| 63 | + """ |
| 64 | + Fetches the base and head commit SHAs for a PR. |
| 65 | + """ |
| 66 | + gh_pr_command = [ |
| 67 | + "gh", "pr", "view", str(pr_number), |
| 68 | + "--repo", f"{owner}/{repo}", |
| 69 | + "--json", "baseRefOid,headRefOid" |
| 70 | + ] |
| 71 | + returncode, stdout, stderr = run_command(gh_pr_command) |
| 72 | + |
| 73 | + if returncode != 0: |
| 74 | + raise RuntimeError(f"Failed to get PR details. GitHub CLI stderr: {stderr.strip()}") |
| 75 | + |
| 76 | + try: |
| 77 | + shas = json.loads(stdout) |
| 78 | + base_sha = shas['baseRefOid'] |
| 79 | + head_sha = shas['headRefOid'] |
| 80 | + return base_sha, head_sha |
| 81 | + except (json.JSONDecodeError, KeyError) as e: |
| 82 | + raise ValueError(f"Could not parse commit SHAs from API response. Error: {e}") from e |
| 83 | + |
| 84 | + |
| 85 | +def get_value_from_commit( |
| 86 | + owner: str, |
| 87 | + repo: str, |
| 88 | + file_path: str, |
| 89 | + key: str, |
| 90 | + sha: str |
| 91 | +) -> Optional[str]: |
| 92 | + """ |
| 93 | + Fetches a file from a specific commit and extracts the value of a given key. |
| 94 | +
|
| 95 | + Args: |
| 96 | + owner: The repository owner. |
| 97 | + repo: The repository name. |
| 98 | + file_path: The path to the file within the repository. |
| 99 | + key: The section to extract from the file's content. |
| 100 | + sha: The commit SHA from which to retrieve the file. |
| 101 | +
|
| 102 | + Returns: |
| 103 | + The extracted value as a string, or None if the file or key is not found. |
| 104 | + """ |
| 105 | + # 1. Fetch the file's content for the given commit SHA. |
| 106 | + content = get_file_content_from_pr(owner, repo, sha, file_path) |
| 107 | + |
| 108 | + # 2. Parse the content to get the desired value. |
| 109 | + value = get_section_from_content(content, key) |
| 110 | + |
| 111 | + return value |
| 112 | + |
| 113 | + |
| 114 | +def main(): |
| 115 | + """Main function to fetch PR files, parse them, and compare keys.""" |
| 116 | + parser = argparse.ArgumentParser( |
| 117 | + description="Compare specific keys in a YAML file between a PR's base and head branches." |
| 118 | + ) |
| 119 | + parser.add_argument("--owner", required=True, help="The owner of the repository.") |
| 120 | + parser.add_argument("--repo", required=True, help="The name of the repository.") |
| 121 | + parser.add_argument("pr_number", type=int, help="The Pull Request number.") |
| 122 | + parser.add_argument("file_path", type=str, help="The file path within the repository.") |
| 123 | + parser.add_argument("key", type=str, help="The key will be checked.") |
| 124 | + |
| 125 | + args = parser.parse_args() |
| 126 | + |
| 127 | + print(f"--- Analyzing '{args.file_path}' in PR #{args.pr_number} for key: {args.key} ---") |
| 128 | + print(f"Repository: {args.owner}/{args.repo}") |
| 129 | + |
| 130 | + # 1. Get the base and head commit SHAs. |
| 131 | + base_sha, head_sha = get_pr_shas(args.owner, args.repo, args.pr_number) |
| 132 | + |
| 133 | + # 2. Fetch and parse the values of the key from the base and head commits. |
| 134 | + before_value = get_value_from_commit( |
| 135 | + args.owner, args.repo, args.file_path, args.key, base_sha |
| 136 | + ) |
| 137 | + after_value = get_value_from_commit( |
| 138 | + args.owner, args.repo, args.file_path, args.key, head_sha |
| 139 | + ) |
| 140 | + |
| 141 | + # 3. Compare the results and print the final output. |
| 142 | + print("\n--- Comparison Result ---") |
| 143 | + print(f"Value(s) in base branch:\n---\n{before_value}\n---") |
| 144 | + print(f"Value(s) in PR branch:\n---\n{after_value}\n---") |
| 145 | + |
| 146 | + if before_value == after_value: |
| 147 | + print("\nNo changes detected for the specified key.") |
| 148 | + sys.exit(0) |
| 149 | + else: |
| 150 | + print("\nChange detected for one of the specified key!") |
| 151 | + print("\nCHANGE_FOUND=true") |
| 152 | + sys.exit(1) |
| 153 | + |
| 154 | + |
| 155 | +if __name__ == "__main__": |
| 156 | + main() |
0 commit comments