|
| 1 | +#!/usr/bin/env python |
| 2 | +# Copyright Celeritas contributors: see top-level COPYRIGHT file for details |
| 3 | +# SPDX-License-Identifier: (Apache-2.0 OR MIT) |
| 4 | +#!/usr/bin/env python3 |
| 5 | +""" |
| 6 | +A Python script that runs cloc on a given git commit in a source directory, |
| 7 | +processes its CSV output into pandas tables, and concatenates the results with |
| 8 | +section header rows. The script uses fixed cloc flags --csv and --quiet. |
| 9 | +
|
| 10 | +Usage: |
| 11 | + python script.py [--source_dir PATH] [--commit COMMIT] [--cloc_path PATH] |
| 12 | +
|
| 13 | +If --source_dir is not provided, it defaults to the top-level git directory of the script. |
| 14 | +If --cloc_path is not provided, it defaults to 'cloc' (available in PATH). |
| 15 | +""" |
| 16 | + |
| 17 | +import os |
| 18 | +import sys |
| 19 | +import argparse |
| 20 | +import subprocess |
| 21 | +import shutil |
| 22 | +from io import StringIO |
| 23 | +from pathlib import Path |
| 24 | + |
| 25 | +import pandas as pd |
| 26 | + |
| 27 | +LANG_MAP = { |
| 28 | + "hip": "CUDA", |
| 29 | +} |
| 30 | + |
| 31 | + |
| 32 | +class RunCloc: |
| 33 | + """Class to execute cloc with configured language mappings and base options.""" |
| 34 | + |
| 35 | + def __init__(self, commit, cloc_path="cloc", cwd=None): |
| 36 | + """ |
| 37 | + Initialize with the git commit to analyze and optional language mappings. |
| 38 | +
|
| 39 | + Args: |
| 40 | + commit: Git commit to analyze |
| 41 | + cloc_path: Path to the cloc executable |
| 42 | + lang_map: Dictionary mapping file extensions to language names |
| 43 | + """ |
| 44 | + self.commit = commit |
| 45 | + |
| 46 | + # Validate cloc path |
| 47 | + if isinstance(cloc_path, str): |
| 48 | + cloc_path = shutil.which(cloc_path) |
| 49 | + self.cloc_path = Path(cloc_path) |
| 50 | + if not self.cloc_path.exists(): |
| 51 | + sys.stderr.write("This script requires https://github.com/AlDanial/cloc\n") |
| 52 | + raise RuntimeError(f"Cloc executable not found at: {self.cloc_path}") |
| 53 | + |
| 54 | + self.cwd = cwd |
| 55 | + |
| 56 | + # Build base command with language mappings |
| 57 | + self.base_cmd = [str(self.cloc_path), "--git", commit, "--csv", "--quiet"] |
| 58 | + |
| 59 | + # Add language mappings as force-lang options |
| 60 | + for ext, lang in LANG_MAP.items(): |
| 61 | + self.base_cmd.append(f"--force-lang={lang},{ext}") |
| 62 | + |
| 63 | + def _validate_cloc(self): |
| 64 | + """Validate that the cloc executable exists and is executable""" |
| 65 | + |
| 66 | + return self.cloc_path.exists() and os.access(self.cloc_path, os.X_OK) |
| 67 | + |
| 68 | + def __call__(self, extra_options): |
| 69 | + """ |
| 70 | + Run cloc with the base command plus any additional options. |
| 71 | +
|
| 72 | + Args: |
| 73 | + extra_options: List of additional cloc command line options |
| 74 | +
|
| 75 | + Returns: |
| 76 | + String containing the CSV output from cloc |
| 77 | + """ |
| 78 | + command = self.base_cmd.copy() |
| 79 | + command.extend(extra_options) |
| 80 | + return subprocess.check_output(command, text=True, cwd=self.cwd) |
| 81 | + |
| 82 | + |
| 83 | +def process_csv_output(csv_output): |
| 84 | + """ |
| 85 | + Processes cloc's CSV output into a pandas DataFrame. |
| 86 | + Drops the annotation column, removes the sum row, and reorders/renames columns to: |
| 87 | + Language, Files, Comment, Code. |
| 88 | + """ |
| 89 | + # Read the CSV using only the first 5 columns (drop the annotation column) |
| 90 | + # Expected CSV header: files,language,blank,comment,code,... |
| 91 | + df = pd.read_csv(StringIO(csv_output)).fillna(0) |
| 92 | + # Remove the sum row |
| 93 | + if df.iloc[-1, 1] == "SUM": |
| 94 | + df = df.iloc[:-1] |
| 95 | + # Rename and reorder columns |
| 96 | + df = df.rename(columns=str.capitalize)[["Language", "Files", "Comment", "Code", "Blank"]] |
| 97 | + # Coerce all but the first column to integers |
| 98 | + for col in df.columns[1:]: |
| 99 | + df[col] = df[col].astype(int) |
| 100 | + return df |
| 101 | + |
| 102 | + |
| 103 | +def main(): |
| 104 | + parser = argparse.ArgumentParser( |
| 105 | + description="Run cloc on a git commit and process its CSV output into concatenated pandas tables." |
| 106 | + ) |
| 107 | + parser.add_argument( |
| 108 | + "--source_dir", |
| 109 | + type=str, |
| 110 | + default=None, |
| 111 | + help="Source directory (defaults to the top-level git directory where the script resides)", |
| 112 | + ) |
| 113 | + parser.add_argument( |
| 114 | + "--commit", |
| 115 | + type=str, |
| 116 | + default="HEAD", |
| 117 | + help="Git commit to run cloc against (default: HEAD)", |
| 118 | + ) |
| 119 | + parser.add_argument( |
| 120 | + "--cloc_path", |
| 121 | + type=str, |
| 122 | + default="cloc", |
| 123 | + help="Path to the cloc executable (default: cloc)", |
| 124 | + ) |
| 125 | + args = parser.parse_args() |
| 126 | + |
| 127 | + # Determine the source directory: |
| 128 | + if args.source_dir is None: |
| 129 | + script_dir = os.path.dirname(os.path.abspath(__file__)) |
| 130 | + try: |
| 131 | + args.source_dir = subprocess.check_output( |
| 132 | + ["git", "rev-parse", "--show-toplevel"], cwd=script_dir, text=True |
| 133 | + ).strip() |
| 134 | + except subprocess.CalledProcessError: |
| 135 | + sys.stderr.write( |
| 136 | + "Unable to determine git top-level directory. Please specify --source_dir\n" |
| 137 | + ) |
| 138 | + sys.exit(1) |
| 139 | + |
| 140 | + # Create the cloc runner |
| 141 | + run_cloc = RunCloc(args.commit, args.cloc_path, args.source_dir) |
| 142 | + |
| 143 | + # Define each section with its label and specific cloc options. |
| 144 | + EXCLUDE_DOC = "--exclude-ext=rst,md,tex" |
| 145 | + sections = [ |
| 146 | + ("Library code", ["--exclude-dir=app,example,scripts,test", EXCLUDE_DOC]), |
| 147 | + ("App code", ["--fullpath", "--match-d=/app/", EXCLUDE_DOC]), |
| 148 | + ("Example code", ["--fullpath", "--match-d=/example/", EXCLUDE_DOC]), |
| 149 | + ("Test code", ["--fullpath", "--match-d=/test/", EXCLUDE_DOC]), |
| 150 | + ("Documentation", [r"--match-f=\.(rst|md|tex)$"]), |
| 151 | + ] |
| 152 | + |
| 153 | + final_tables = [] |
| 154 | + for section_label, options in sections: |
| 155 | + # Print section info to stderr. |
| 156 | + sys.stderr.write(f"{section_label}...\n") |
| 157 | + # Run cloc with the options for this section. |
| 158 | + csv_output = run_cloc(options) |
| 159 | + # Process the CSV output into a DataFrame. |
| 160 | + df_section = process_csv_output(csv_output) |
| 161 | + # Create a header row DataFrame with the section label. |
| 162 | + header_row = pd.DataFrame( |
| 163 | + [{"Language": section_label, "Files": "", "Comment": "", "Code": ""}] |
| 164 | + ) |
| 165 | + # Append the header row and the section's table to the final list. |
| 166 | + final_tables.append(header_row) |
| 167 | + final_tables.append(df_section) |
| 168 | + |
| 169 | + # Concatenate all tables vertically. |
| 170 | + final_df = pd.concat(final_tables, ignore_index=True) |
| 171 | + # Output the final DataFrame as CSV to stdout. |
| 172 | + print(final_df.to_csv(index=False)) |
| 173 | + |
| 174 | + |
| 175 | +if __name__ == "__main__": |
| 176 | + main() |
0 commit comments