|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Parse CNB launch.toml files for buildpack scripts. |
| 4 | +
|
| 5 | +Supports two output formats: |
| 6 | +- --yaml: YAML for bin/release |
| 7 | +- --process <type>: Command for a single process type (e.g., as used in `bin/test`) |
| 8 | +""" |
| 9 | + |
| 10 | +import sys |
| 11 | +import shlex |
| 12 | +from pathlib import Path |
| 13 | + |
| 14 | +# `tomli`/`tomllib` compatibility layer: Use `tomllib` if available in the |
| 15 | +# standard library (Python 3.11+), and fallback to `tomli` (available in |
| 16 | +# `heroku/heroku:22-build`) when the standard library module is not available. |
| 17 | +# See https://github.com/hukkin/tomli#building-a-tomlitomllib-compatibility-layer |
| 18 | +if sys.version_info >= (3, 11): |
| 19 | + import tomllib |
| 20 | +else: |
| 21 | + import tomli as tomllib |
| 22 | + |
| 23 | + |
| 24 | +def parse_processes(toml_path): |
| 25 | + """Parse launch.toml and return process type -> command mapping.""" |
| 26 | + try: |
| 27 | + with open(toml_path, "rb") as f: |
| 28 | + data = tomllib.load(f) |
| 29 | + except (FileNotFoundError, tomllib.TOMLDecodeError): |
| 30 | + return {} |
| 31 | + |
| 32 | + processes = {} |
| 33 | + for proc in data.get("processes", []): |
| 34 | + proc_type = proc.get("type") |
| 35 | + command_list = proc.get("command") |
| 36 | + |
| 37 | + if not proc_type or not isinstance(command_list, list): |
| 38 | + continue |
| 39 | + |
| 40 | + # Extract script content from bash -c commands, otherwise join with escaping |
| 41 | + if len(command_list) >= 3 and command_list[:2] == ["bash", "-c"]: |
| 42 | + processes[proc_type] = command_list[2] |
| 43 | + else: |
| 44 | + processes[proc_type] = shlex.join(command_list) |
| 45 | + |
| 46 | + return processes |
| 47 | + |
| 48 | + |
| 49 | +def main(): |
| 50 | + if len(sys.argv) not in [3, 4]: |
| 51 | + print( |
| 52 | + "Usage: parse_launch_toml.py <launch.toml> [--yaml|--process <type>]", |
| 53 | + file=sys.stderr, |
| 54 | + ) |
| 55 | + sys.exit(1) |
| 56 | + |
| 57 | + toml_path, mode = sys.argv[1], sys.argv[2] |
| 58 | + |
| 59 | + if not Path(toml_path).exists(): |
| 60 | + sys.exit(1) |
| 61 | + |
| 62 | + processes = parse_processes(toml_path) |
| 63 | + |
| 64 | + if mode == "--yaml": |
| 65 | + if processes: |
| 66 | + print("---\ndefault_process_types:") |
| 67 | + for proc_type, command in processes.items(): |
| 68 | + print(f" {proc_type}: {command}") |
| 69 | + |
| 70 | + elif mode == "--process" and len(sys.argv) == 4: |
| 71 | + command = processes.get(sys.argv[3]) |
| 72 | + if command: |
| 73 | + print(command) |
| 74 | + else: |
| 75 | + sys.exit(1) |
| 76 | + |
| 77 | + else: |
| 78 | + print( |
| 79 | + "Usage: parse_launch_toml.py <launch.toml> [--yaml|--process <type>]", |
| 80 | + file=sys.stderr, |
| 81 | + ) |
| 82 | + sys.exit(1) |
| 83 | + |
| 84 | + |
| 85 | +if __name__ == "__main__": |
| 86 | + main() |
0 commit comments