From e00939a2dae071118314883ddf8b314da026aa39 Mon Sep 17 00:00:00 2001 From: Simon Walker Date: Wed, 9 Aug 2023 10:18:55 +0100 Subject: [PATCH] Add init nix shell command --- home/bin/init-nix-shell | 65 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100755 home/bin/init-nix-shell diff --git a/home/bin/init-nix-shell b/home/bin/init-nix-shell new file mode 100755 index 00000000..ca89796e --- /dev/null +++ b/home/bin/init-nix-shell @@ -0,0 +1,65 @@ +#!/usr/bin/env python + +""" +Create a shell.nix with default settings in the current directory, and set the .envrc file to "use nix" +""" + +import argparse +import logging +from pathlib import Path +import sys + +logging.basicConfig(level=logging.WARNING) +LOG = logging.getLogger(__name__) + + +SHELL_NIX_TEMPLATE = """{ pkgs ? import { } }: +with pkgs; +mkShell { + packages = [ + ]; +} +""" + + +def init_shell_nix(path: Path): + with path.open("w") as outfile: + print(SHELL_NIX_TEMPLATE, file=outfile) + + +def init_envrc(path: Path): + with path.open("w") as outfile: + print("use nix", file=outfile) + + +def init_dir(root: Path, force: bool): + LOG.info(f"initialising {root}") + + shell_nix_path = root.joinpath("shell.nix") + envrc_path = root.joinpath(".envrc") + + if shell_nix_path.is_file() and not force: + raise ValueError(f"file exists at {shell_nix_path}") + + if envrc_path.is_file() and not force: + raise ValueError(f"file exists at {envrc_path}") + + init_shell_nix(shell_nix_path) + init_envrc(envrc_path) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-v", "--verbose", action="store_true", default=False) + parser.add_argument("-r", "--root-dir", required=False, default=Path.cwd(), type=Path) + parser.add_argument("-f", "--force", action="store_true", default=False) + args = parser.parse_args() + + if args.verbose: + LOG.setLevel(logging.DEBUG) + + try: + init_dir(args.root_dir.resolve(), args.force) + except Exception as e: + print(f"Error: {e}", file=sys.stderr) + raise SystemExit(1)