flake/config/xonsh/aliases.py
2024-12-22 11:04:50 -05:00

152 lines
6.5 KiB
Python

from os.path import dirname
from os import environ
from pathlib import Path
import subprocess
from socket import gethostname
import colors
def format_link(link: str, text: str) -> str:
return f"\033]8;;{link}\033\\{text}\033]8;;\033\\"
def run(cmd: list[str], cwd: Path = Path.cwd(), exit_on_error: bool = True, **kwargs) -> subprocess.CompletedProcess:
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, **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")
if path.exists():
c = colors.Colors
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)
print(f"{c.BLUE}Deleting {c.YELLOW}Visual Studio Code{c.BLUE} user settings backup file{c.END}")
run(["rm", ".config/Code/User/settings.json.bak"], 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", "switch", *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]
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",
"create-devenv": "nix flake init --template github:cachix/devenv and direnv allow",
"dev": "nix develop --no-pure-eval",
"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",
"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)