|
| 1 | +import argparse |
| 2 | +import os |
| 3 | +import sys |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | + |
| 7 | +def parse_changed_totals(report_path): |
| 8 | + changed_comments = 0 |
| 9 | + changed_code = 0 |
| 10 | + |
| 11 | + for raw_line in report_path.read_text(encoding="utf-8").splitlines(): |
| 12 | + if "|" not in raw_line: |
| 13 | + continue |
| 14 | + |
| 15 | + cells = [cell.strip() for cell in raw_line.split("|")] |
| 16 | + if cells and cells[-1] == "": |
| 17 | + cells = cells[:-1] |
| 18 | + |
| 19 | + if not cells or cells[0] in {"Language", "File"}: |
| 20 | + continue |
| 21 | + if cells[0].startswith((":", "-", "SUM:")) or len(cells) < 17: |
| 22 | + continue |
| 23 | + |
| 24 | + try: |
| 25 | + changed_comments += sum(int(cells[index]) for index in (10, 11, 12)) |
| 26 | + changed_code += sum(int(cells[index]) for index in (14, 15, 16)) |
| 27 | + except ValueError: |
| 28 | + continue |
| 29 | + |
| 30 | + return changed_comments, changed_code |
| 31 | + |
| 32 | + |
| 33 | +def main(): |
| 34 | + parser = argparse.ArgumentParser() |
| 35 | + parser.add_argument("report") |
| 36 | + parser.add_argument("--limit", type=float, default=10.0) |
| 37 | + args = parser.parse_args() |
| 38 | + |
| 39 | + report_path = Path(args.report) |
| 40 | + if not report_path.exists(): |
| 41 | + sys.exit(f"{report_path} was not generated by the comment ratio action.") |
| 42 | + |
| 43 | + changed_comments, changed_code = parse_changed_totals(report_path) |
| 44 | + total_changed_nonblank = changed_comments + changed_code |
| 45 | + comment_percentage = ( |
| 46 | + 0.0 |
| 47 | + if total_changed_nonblank == 0 |
| 48 | + else changed_comments * 100.0 / total_changed_nonblank |
| 49 | + ) |
| 50 | + |
| 51 | + print(f"Comment percentage for PR changes: {comment_percentage:.2f}%") |
| 52 | + |
| 53 | + github_output = os.getenv("GITHUB_OUTPUT") |
| 54 | + if github_output: |
| 55 | + with Path(github_output).open("a", encoding="utf-8") as output: |
| 56 | + output.write(f"changed_comments={changed_comments}\n") |
| 57 | + output.write(f"changed_code={changed_code}\n") |
| 58 | + output.write(f"comment_percentage={comment_percentage:.2f}\n") |
| 59 | + |
| 60 | + if comment_percentage > args.limit: |
| 61 | + print( |
| 62 | + f"Comment percentage for PR changes is {comment_percentage:.2f}%, " |
| 63 | + f"which exceeds {args.limit:.2f}%.", |
| 64 | + file=sys.stderr, |
| 65 | + ) |
| 66 | + sys.exit(1) |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + main() |
0 commit comments