flake/config/xonsh/aliases.py

192 lines
7.8 KiB
Python

from os.path import dirname
from os import environ
from pathlib import Path
import subprocess
from socket import gethostname
import colors
from typing import Mapping
def format_link(link: str, text: str) -> str:
return f"\033]8;;{link}\033\\{text}\033]8;;\033\\"
def get_environment() -> dict[str, str]:
env = dict(environ)
env["DIRENV_DISABLE"] = "1"
return env
def run(cmd: list[str], cwd: Path = Path.cwd(), exit_on_error: bool = True, env: dict[str, str] | None = None, **kwargs) -> subprocess.CompletedProcess:
if not env:
env = get_environment()
c = colors.Colors
print(f"{c.GREEN}Running command: {c.PURPLE}'{' '.join(cmd)}'{c.END}")
if cwd != Path.cwd():
print(f"{c.GREEN} 󱞩 in directory: {c.YELLOW}'{format_link(link="file://" + str(cwd), text=cwd)}'{c.END}")
result = subprocess.run(cmd, cwd=cwd, check=False, env=env, **kwargs)
if result.returncode != 0:
print(f"{c.RED}Command exited with non-zero exit code {c.CYAN}{c.BOLD}{result.returncode}{c.END}")
if exit_on_error is True:
result.check_returncode()
else:
print(f"{c.GREEN}Command exited with exit code {c.CYAN}{c.BOLD}{result.returncode}{c.END}")
return result
@aliases.register
@aliases.return_command
def _sudo(args):
return ["sudo", "--", *aliases.eval_alias(args)]
@aliases.register
def _vm(args):
if not args:
args = ["nixpkgs"]
vm_name = args.pop(0)
build_vm_args = args
if vm_name == "nixpkgs":
build_vm_args.extend(["-I", "nixpkgs=/bulk/home/cswimr/Projects/nixpkgs"])
vm_path = Path(f"/etc/nixos/hosts/virtual-machines/{vm_name}")
if vm_path.exists():
c = colors.Colors
print(f"{c.BLUE}Building virtual machine {c.YELLOW}{vm_name}{c.END}")
run(["nixos-rebuild", "build-vm", "-I", "nixos-config=./default.nix", *build_vm_args, "--no-flake"], cwd=vm_path)
print(f"{c.BLUE}Starting virtual vachine {c.YELLOW}{vm_name}{c.END}")
run(["./result/bin/run-nixos-vm"], cwd=vm_path)
print(f"{c.BLUE}Virtual machine {c.YELLOW}{vm_name} {c.BLUE}has {c.RED}stopped.{c.END}")
else:
raise FileNotFoundError(f"Virtual machine {vm_name} does not exist.")
@aliases.register
def _upd(args: list):
path = Path("/etc/nixos")
possible_subcommands = ("switch", "boot", "test", "build-vm")
subcommand = "switch"
for arg in args:
if arg in possible_subcommands:
subcommand = arg
args.remove(arg)
break
if path.exists():
c = colors.Colors
files_to_delete = {
"Visual Studio Code user settings": ".config/Code/User/settings.json.bak",
"fontconfig": ".config/fontconfig/conf.d/10-hm-fonts.conf.bak"
}
if not "--no-pull" in args:
print(f"{c.BLUE}Pulling {c.YELLOW}NixOS{c.BLUE} configuration from remote{c.END}")
run(["git", "pull"], cwd=path)
else:
args.remove("--no-pull")
if "--rewrite-hardware-configuration" in args:
args.remove("--rewrite-hardware-configuration")
print(f"{c.BLUE}Updating {c.YELLOW}NixOS{c.BLUE} hardware configuration file for {c.YELLOW}{gethostname()}{c.BLUE}{c.END}")
run(["sudo", "nixos-generate-config", "--dir", ".",], cwd=path / "hosts")
print(f"{c.BLUE}Deleting redundant {c.YELLOW}NixOS{c.BLUE} configuration file{c.END}")
run(["sudo", "rm", "configuration.nix"], cwd=path / "hosts")
print(f"{c.BLUE}Moving {c.YELLOW}NixOS{c.BLUE} hardware configuration file{c.END}")
run(["sudo", "mv", "hardware-configuration.nix", "{hostname}.nix".format(hostname=gethostname())], cwd=path / "hosts")
print(f"{c.BLUE}Adding {c.YELLOW}NixOS{c.BLUE} hardware configuration file for {c.YELLOW}{gethostname()}{c.BLUE} to git{c.END}")
run(["git", "add", "hosts/{hostname}.nix".format(hostname=gethostname())], cwd=path)
for file_description, file_path in files_to_delete.items():
print(f"{c.BLUE}Deleting {c.YELLOW}{file_description}{c.BLUE} backup file{c.END}")
run(["rm", file_path], exit_on_error=False, cwd="/home/cswimr")
if "--purge-vscode-extensions" in args:
args.remove("--purge-vscode-extensions")
print(f"{c.BLUE}Killing {c.YELLOW}Visual Studio Code{c.BLUE} processes{c.END}")
run(["killall", "code"], exit_on_error=False)
print(f"{c.BLUE}Purging {c.YELLOW}Visual Studio Code{c.BLUE} extensions{c.END}")
run(["rm", "-rf", ".vscode/extensions"], cwd="/home/cswimr")
print(f"{c.BLUE}Rebuilding {c.YELLOW}NixOS{c.BLUE} configuration{c.END}")
#TODO: Remove --impure once the Starship module is merged - see ../../nixos/shell.nix for more information
args.append("--impure")
if "--impure" in args:
print(f"{c.RED}WARNING: The --impure flag is set!{c.END}")
run(["sudo", "nixos-rebuild", subcommand, *args], cwd=path)
@aliases.register
def _lock(args):
path = Path("/etc/nixos")
if path.exists():
c = colors.Colors
print(f"{c.BLUE}Updating {c.YELLOW}Nix Flake{c.BLUE} lock file{c.END}")
run(["nix", "flake", "update", *args], cwd=path)
@aliases.register
@aliases.return_command
def _edit(args):
if not args:
args = ["."]
if environ.get("SSH_CONNECTION") is not None:
return ["$EDITOR", *args]
return ["$VISUAL", *args]
@aliases.register
def _create_devenv(args):
if not args:
template = "simple"
else:
template = args[0]
run(["nix", "flake", "init", "--template", f"github:cswimr/dev-flakes#{template}"], cwd=Path.cwd(), exit_on_error=False)
run(["direnv", "allow"], cwd=Path.cwd())
alias_dictionary = {
"ff": "fastfetch",
"neofetch": "fastfetch",
"nf": "fastfetch",
"lg": "lazygit",
"lad": "lazydocker",
"clip": "clp",
"paste": "wl-paste",
"cat": "bat",
"git": "hub",
"l": "eza -lhg --time-style=long-iso --icons=auto --hyperlink",
"la": "eza -lAh --time-style=long-iso --icons=auto --hyperlink",
"ll": "eza -lhg --time-style=long-iso --icons=auto --hyperlink",
"ls": "eza --time-style=long-iso --icons=auto --hyperlink",
"lsa": "eza -lah --time-style=long-iso --icons=auto --hyperlink",
"tree": "eza --tree --git-ignore --time-style=long-iso --icons=auto --hyperlink",
"nixpkgs-update": "nix run --option extra-substituters 'https://nix-community.cachix.org/' --option extra-trusted-public-keys 'nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs=' github:ryantm/nixpkgs-update --",
"nixrc": "edit /etc/nixos",
"taildrop": "tailscale file",
"forgejo-runner": "act_runner",
"runactions": "act_runner exec --default-actions-url=https://www.coastalcommits.com --gitea-instance=https://www.coastalcommits.com",
"uvr": "uv run",
"ns": "nix-shell",
"e": "edit",
"c": "clear",
"s": "sudo",
}
# Create aliases for scripts with the file extension stripped
script_path = Path("/etc/nixos/scripts")
if script_path.exists():
for sub_dir in script_path.iterdir():
# ignore files within the nix subdirectory, since they are just nix-shell expressions
# if you aren't using nix, you can remove this if statement
if sub_dir.name == "nix":
continue
if not sub_dir.is_dir():
print(f"{colors.Colors.YELLOW}{colors.Colors.BOLD}WARNING: The path {colors.Colors.PURPLE}'{sub_dir}'{colors.Colors.YELLOW} is not a directory. Skipping alias creation for this path.{colors.Colors.END}")
continue
extension = f".{sub_dir.name}"
for script in sub_dir.glob(f"*{extension}"):
if script.name == "__init__.py":
continue
script_name = script.stem
aliases[script_name] = [str(script)]
aliases.update(alias_dictionary)