|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Quick & Dirty script to get the bash commands from a markdown file and run them""" |
| 3 | + |
| 4 | +import argparse |
| 5 | +import re |
| 6 | +import subprocess |
| 7 | +import shlex |
| 8 | + |
| 9 | +from typing import List |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | + |
| 13 | +def get_commands( |
| 14 | + mdfile: Path, exclude_patterns: List[str] = None, cell_type: str = "bash" |
| 15 | +) -> List[str]: |
| 16 | + """Get all commands (assuming they are all on the same line) from the |
| 17 | + markdown file in the given cell_type. Filtering out commands that match any |
| 18 | + of the patterns in exclude_patterns |
| 19 | + """ |
| 20 | + # Thanks ChatGPT |
| 21 | + file_content = Path(mdfile).read_text() |
| 22 | + cell_content_rgx = re.compile(rf"```{cell_type}(.*?)```", re.DOTALL) |
| 23 | + cell_code_blocks = cell_content_rgx.findall(file_content) |
| 24 | + |
| 25 | + exclude_rgxs = [re.compile(r"^#")] |
| 26 | + if exclude_patterns: |
| 27 | + exclude_rgxs.extend([re.compile(p) for p in exclude_patterns]) |
| 28 | + |
| 29 | + def _excluded(cmd: str): |
| 30 | + return any(r.search(cmd) for r in exclude_rgxs) |
| 31 | + |
| 32 | + return [ |
| 33 | + line |
| 34 | + for block in cell_code_blocks |
| 35 | + for line in block.splitlines() |
| 36 | + if line and not _excluded(line) |
| 37 | + ] |
| 38 | + |
| 39 | + |
| 40 | +def run_commands(cmds: List[str]) -> None: |
| 41 | + """Run all the commands that have been found. Assume that there are only |
| 42 | + runnable commands left in cmds!""" |
| 43 | + for cmd in cmds: |
| 44 | + try: |
| 45 | + result = subprocess.run( |
| 46 | + shlex.split(cmd), check=True, capture_output=True, text=True |
| 47 | + ) |
| 48 | + print(f"Command: {cmd}\n{result.stdout}") |
| 49 | + except subprocess.CalledProcessError as e: |
| 50 | + print(f"Error executing command: {cmd}\nError: {e.stderr}") |
| 51 | + except FileNotFoundError as fnf_error: |
| 52 | + print(f"Command not found: {cmd}\nError: {fnf_error}") |
| 53 | + |
| 54 | + |
| 55 | +def main(): |
| 56 | + """Main""" |
| 57 | + parser = argparse.ArgumentParser( |
| 58 | + description="Script to parse and run commands from a markdown file" |
| 59 | + ) |
| 60 | + parser.add_argument("inputfile", help="name of the input markdown file", type=Path) |
| 61 | + parser.add_argument( |
| 62 | + "-x", |
| 63 | + "--exclude", |
| 64 | + action="append", |
| 65 | + type=str, |
| 66 | + help="pattern to use for commands that should not be executed", |
| 67 | + ) |
| 68 | + parser.add_argument( |
| 69 | + "-t", |
| 70 | + "--celltype", |
| 71 | + type=str, |
| 72 | + default="bash", |
| 73 | + help="Which cell type to execute", |
| 74 | + ) |
| 75 | + args = parser.parse_args() |
| 76 | + |
| 77 | + cmds = get_commands(args.inputfile, args.exclude, args.celltype) |
| 78 | + run_commands(cmds) |
| 79 | + |
| 80 | + |
| 81 | +if __name__ == "__main__": |
| 82 | + main() |
0 commit comments