#!/usr/bin/env python3 import shutil import contextlib import typing as t from pathlib import Path import click shebangs = { "bash": None, "python3": None, "perl": None, "zsh": None, "elixir": None, "node": None, "php": None, "sh": "#!/bin/sh", # use absolute path for compatibility } body = { "python3": """ def main() -> None: print("hello world") if __name__ == "__main__": main()""", "bash": """ set -o pipefail main() { echo hello world } main || exit $?""", "php": r""" t.List[str]: return [n for n in names if n.startswith(incomplete)] @click.command() @click.option( "-o", "--output", type=click.Path(exists=False, dir_okay=False, path_type=Path), default=None, help="Write to output file, instead of STDOUT", ) @click.argument("SHEBANG", shell_complete=_autocomplete, required=True) def main(shebang: str, output: t.Optional[Path]) -> None: """ Create a SCRIPT with a SHEBANG If the shebang is known, adds a basic body as well """ computed_shebang: str if shebang in shebangs: if shebangs[shebang] is None: computed_shebang = f"#!/usr/bin/env {shebang}" else: shebang_value = shebangs[shebang] assert shebang_value is not None # use string computed_shebang = shebang_value else: path = shutil.which(shebang) if path is None: click.echo(f"Warning: Could not find {shebang} on your $PATH", err=True) computed_shebang = f"#!/usr/bin/env {shebang}" buf = str(computed_shebang) if shebang in body: buf += "\n" buf += body[shebang] if output is None: click.echo(buf) else: output.write_text(buf + "\n") output.chmod(0o700) click.secho(f"Created '{output}' with contents:", fg="green", err=True) click.echo(buf, err=True) if __name__ == "__main__": with contextlib.suppress(KeyboardInterrupt): main()