|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# Reads shell scripts from `run` steps in GitHub Actions workflows and outputs |
| 4 | +# them as files so that tools like `shfmt` or ShellCheck can operate on them. |
| 5 | +# |
| 6 | +# Arguments: |
| 7 | +# - Path to output directory where shell scripts will be written. |
| 8 | + |
| 9 | +import os |
| 10 | +import re |
| 11 | +import sys |
| 12 | + |
| 13 | +import argparse |
| 14 | +from pathlib import Path |
| 15 | + |
| 16 | +import yaml |
| 17 | + |
| 18 | + |
| 19 | +def list_str(values): |
| 20 | + return values.split(',') |
| 21 | + |
| 22 | + |
| 23 | +def sanitize(path): |
| 24 | + # Needed filename replacements to satisfy both GHA artifacts and shellcheck. |
| 25 | + replacements = { |
| 26 | + " ": "_", |
| 27 | + "/": "-", |
| 28 | + '"': "", |
| 29 | + "(": "", |
| 30 | + ")": "", |
| 31 | + "&": "", |
| 32 | + "$": "", |
| 33 | + } |
| 34 | + return path.translate(str.maketrans(replacements)) |
| 35 | + |
| 36 | + |
| 37 | +# Replace any GHA placeholders, e.g. ${{ matrix.version }}. |
| 38 | +def sanitize_gha_expression(string): |
| 39 | + return re.sub(r"\${{\s*(.*?)\s*}}", r":\1:", string) |
| 40 | + |
| 41 | + |
| 42 | +def process_workflow_file(workflow_path: Path, output_dir: Path, ignored_errors=[]): |
| 43 | + with workflow_path.open() as f: |
| 44 | + workflow = yaml.safe_load(f) |
| 45 | + workflow_file = workflow_path.name |
| 46 | + # GHA allows workflow names to be defined as empty (e.g. `name:`) |
| 47 | + workflow_name = sanitize(workflow.get("name") or workflow_path.stem) |
| 48 | + workflow_default_shell = workflow.get("defaults", {}).get("run", {}).get("shell") |
| 49 | + workflow_env = workflow.get("env", {}) |
| 50 | + count = 0 |
| 51 | + print(f"Processing {workflow_path} ({workflow_name})") |
| 52 | + for job_key, job in workflow.get("jobs", {}).items(): |
| 53 | + # GHA allows job names to be defined as empty (e.g. `name:`) |
| 54 | + job_name = sanitize(job.get("name") or job_key) |
| 55 | + job_default_shell = ( |
| 56 | + job.get("defaults", {}).get("run", {}).get("shell", workflow_default_shell) |
| 57 | + ) |
| 58 | + job_env = workflow_env | job.get("env", {}) |
| 59 | + for i, step in enumerate(job.get("steps", [])): |
| 60 | + run = step.get("run") |
| 61 | + if not run: |
| 62 | + continue |
| 63 | + run = sanitize_gha_expression(run) |
| 64 | + shell = step.get("shell", job_default_shell) |
| 65 | + if shell and shell not in ["bash", "sh"]: |
| 66 | + print(f"Skipping command with unknown shell '{shell}'") |
| 67 | + continue |
| 68 | + env = job_env | step.get("env", {}) |
| 69 | + # GHA allows step names to be defined as empty (e.g. `name:`) |
| 70 | + step_name = sanitize(step.get("name") or str(i + 1)) |
| 71 | + script_path = ( |
| 72 | + output_dir / workflow_file / f"job={job_name}" / f"step={step_name}.sh" |
| 73 | + ) |
| 74 | + script_path.parent.mkdir(parents=True, exist_ok=True) |
| 75 | + with script_path.open("w") as f: |
| 76 | + # Default shell is bash. |
| 77 | + f.write(f"#!/usr/bin/env {shell or 'bash'}\n") |
| 78 | + # Ignore failure with GitHub expression variables such as: |
| 79 | + # - SC2050: `[[ "${{ github.ref }}" == "refs/heads/main" ]]` |
| 80 | + if ignored_errors: |
| 81 | + f.write(f"# shellcheck disable={','.join(ignored_errors)}\n") |
| 82 | + # Add a no-op command to ensure that additional shellcheck |
| 83 | + # disable directives aren't applied globally |
| 84 | + # https://github.com/koalaman/shellcheck/issues/657#issuecomment-213038218 |
| 85 | + f.write("true\n") |
| 86 | + # Whether or not it was explicitly set determines the arguments. |
| 87 | + # https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsshell |
| 88 | + if not shell or shell == "sh": |
| 89 | + f.write("set -e\n") |
| 90 | + elif shell == "bash": |
| 91 | + f.write("set -eo pipefail\n") |
| 92 | + for k, v in env.items(): |
| 93 | + f.write("# shellcheck disable=SC2016,SC2034\n") |
| 94 | + v = sanitize_gha_expression(str(v)).replace("'", "'\\''") |
| 95 | + f.write(f"{k}='{v}'\n") |
| 96 | + f.write("# ---\n") |
| 97 | + f.write(run) |
| 98 | + if not run.endswith("\n"): |
| 99 | + f.write("\n") |
| 100 | + count += 1 |
| 101 | + print(f"Produced {count} files") |
| 102 | + |
| 103 | + |
| 104 | +if __name__ == "__main__": |
| 105 | + parser = argparse.ArgumentParser() |
| 106 | + parser.add_argument("input_dir", type=Path) |
| 107 | + parser.add_argument("output_dir", type=Path) |
| 108 | + parser.add_argument("--disable", type=list_str) |
| 109 | + args = parser.parse_args() |
| 110 | + |
| 111 | + print(f"Outputting scripts to {args.output_dir}") |
| 112 | + args.output_dir.mkdir(parents=True, exist_ok=True) |
| 113 | + for file in os.listdir(args.input_dir): |
| 114 | + if file.endswith(".yaml") or file.endswith(".yml"): |
| 115 | + process_workflow_file( |
| 116 | + args.input_dir / file, args.output_dir, args.disable |
| 117 | + ) |
0 commit comments