flake/scripts/py/common/common.py

133 lines
3.9 KiB
Python
Raw Permalink Normal View History

2024-11-22 09:50:05 -05:00
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
2024-11-22 09:50:05 -05:00
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:
2024-12-02 20:50:24 -05:00
if not which("notify-send"):
raise FileNotFoundError("notify-send is not installed.")
2024-11-22 09:50:05 -05:00
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:
2024-12-02 20:50:24 -05:00
if not does_desktop_entry_exist(desktop_entry=desktop_entry):
raise FileNotFoundError("Desktop entry does not exist.")
2024-11-22 09:50:05 -05:00
args.append("-h")
args.append(f"string:desktop-entry:{desktop_entry}")
args.append(title)
args.append(message)
print(args)
run(cmd=args)
2024-11-22 09:50:05 -05:00
2024-12-02 20:50:24 -05:00
def read_secret_file(secret: str, home: bool = False) -> str:
if home:
path = os.path.expanduser(f"~/.secrets/{secret}")
else:
2024-12-02 20:52:24 -05:00
path = f"/run/secrets/{secret}"
2024-11-22 10:35:19 -05:00
if not os.path.exists(path):
raise FileNotFoundError(f"Secret file {path} does not exist or cannot be read.")
2024-12-02 20:50:24 -05:00
with open(file=path, mode="r") as secret_file:
secret = secret_file.read().strip()
2024-11-22 10:35:19 -05:00
if not secret:
raise ValueError(f"Secret file {path} is empty.")
return secret
2024-11-22 09:50:05 -05:00
def does_desktop_entry_exist(desktop_entry: str, show_all_paths: bool = True) -> bool:
2024-11-22 09:50:05 -05:00
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"],
2024-11-22 09:50:05 -05:00
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}"
)
2024-11-22 09:50:05 -05:00
for entry_path in entry_paths:
entry_file = Path(entry_path) / f"{desktop_entry}"
if show_all_paths:
print(f"Checking for {entry_file}")
2024-11-22 09:50:05 -05:00
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