I like `xonsh` and all, but integrating it with neovim without incurring a major performance penalty is difficult to say the least. I think switching back to `zsh` is my best option to solve this issue for now.
132 lines
3.9 KiB
Python
132 lines
3.9 KiB
Python
import os
|
|
import subprocess
|
|
from pathlib import Path
|
|
from shutil import which
|
|
|
|
from common.colors import Colors as c
|
|
|
|
|
|
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(os.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()
|
|
|
|
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
|
|
|
|
|
|
def notify(
|
|
application_name: str,
|
|
title: str,
|
|
message: str,
|
|
urgency: str = "low",
|
|
category: str | None = None,
|
|
icon: Path | None = None,
|
|
desktop_entry: str | None = None,
|
|
) -> None:
|
|
if not which("notify-send"):
|
|
raise FileNotFoundError("notify-send is not installed.")
|
|
args = ["notify-send", "-a", application_name, "-u", urgency]
|
|
if category:
|
|
args.append("-c")
|
|
args.append(category)
|
|
if icon:
|
|
args.append("-i")
|
|
args.append(str(icon))
|
|
if desktop_entry:
|
|
if not does_desktop_entry_exist(desktop_entry=desktop_entry):
|
|
raise FileNotFoundError("Desktop entry does not exist.")
|
|
args.append("-h")
|
|
args.append(f"string:desktop-entry:{desktop_entry}")
|
|
args.append(title)
|
|
args.append(message)
|
|
print(args)
|
|
run(cmd=args)
|
|
|
|
|
|
def read_secret_file(secret: str, home: bool = False) -> str:
|
|
if home:
|
|
path = os.path.expanduser(f"~/.secrets/{secret}")
|
|
else:
|
|
path = f"/run/secrets/{secret}"
|
|
if not os.path.exists(path):
|
|
raise FileNotFoundError(f"Secret file {path} does not exist or cannot be read.")
|
|
with open(file=path, mode="r") as secret_file:
|
|
secret = secret_file.read().strip()
|
|
if not secret:
|
|
raise ValueError(f"Secret file {path} is empty.")
|
|
return secret
|
|
|
|
|
|
def does_desktop_entry_exist(desktop_entry: str, show_all_paths: bool = True) -> bool:
|
|
if not desktop_entry:
|
|
raise ValueError("Please provide the full filename of the desktop entry.")
|
|
|
|
if not desktop_entry.endswith(".desktop"):
|
|
desktop_entry += ".desktop"
|
|
|
|
entry_paths = []
|
|
|
|
if which("qtpaths"):
|
|
result = run(
|
|
cmd=["qtpaths", "--paths", "ApplicationsLocation"],
|
|
stdout=subprocess.PIPE,
|
|
text=True,
|
|
)
|
|
entry_paths = result.stdout.strip().split(":")
|
|
else:
|
|
print("qtpaths is not installed, falling back to XDG_DATA_DIRS.")
|
|
xdg_data_dirs = os.getenv("XDG_DATA_DIRS", "/usr/share:/usr/local/share").split(
|
|
":"
|
|
)
|
|
entry_paths = [os.path.join(path, "applications") for path in xdg_data_dirs]
|
|
entry_paths.append(os.path.expanduser("~/.local/share/applications"))
|
|
|
|
if show_all_paths:
|
|
print(
|
|
f"Checking the following paths for {desktop_entry}:\n{entry_paths}\n{'-' * 20}"
|
|
)
|
|
|
|
for entry_path in entry_paths:
|
|
entry_file = Path(entry_path) / f"{desktop_entry}"
|
|
if show_all_paths:
|
|
print(f"Checking for {entry_file}")
|
|
if entry_file.is_file():
|
|
print(f"{desktop_entry} found in {entry_path}")
|
|
return True
|
|
|
|
print(f"Desktop entry {desktop_entry} does not exist.")
|
|
return False
|