flake/scripts/common/common.py

78 lines
2.3 KiB
Python
Raw Normal View History

2024-11-22 09:50:05 -05:00
import os
import subprocess
from pathlib import Path
from shutil import which
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:
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:
args.append("-h")
args.append(f"string:desktop-entry:{desktop_entry}")
args.append(title)
args.append(message)
print(args)
subprocess.run(args)
def read_secret_file(secret: str) -> str:
path = f"/var/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.")
with open(f"/var/secrets/{secret}", "r") as f:
2024-11-22 10:35:19 -05:00
secret = f.read().strip()
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) -> 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 = subprocess.run(
["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"))
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}"
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