Files
dotfiles/.config/fastfetch/detect_os.py
T

84 lines
2.6 KiB
Python
Executable File

#!/usr/bin/env python3
import os
import platform
import subprocess
import re
def return_os(os_release_path: str) -> tuple[str, str]:
try:
with open(os_release_path) as f:
content = f.read()
id_match = re.search(r'^ID=["\']?([^"\n\']+)', content, re.MULTILINE)
variant_match = re.search(r'^VARIANT_ID=["\']?([^"\n\']+)', content, re.MULTILINE)
os_id = id_match.group(1) if id_match else ""
variant_id = variant_match.group(1) if variant_match else ""
return os_id, variant_id
except Exception:
return "", ""
def detect_os() -> tuple[str, str]:
system = platform.system().lower()
match system:
case "darwin":
return "macos", ""
case "freebsd":
return "freebsd", ""
case "windows":
return "windows", ""
case "linux":
# Check for specific Linux distributions
custom_os_release = os.path.expanduser("~/.os-release")
if os.path.exists(custom_os_release):
return return_os(custom_os_release)
elif os.path.exists("/etc/os-release"):
return return_os("/etc/os-release")
elif os.path.exists("/usr/lib/os-release"):
return return_os("/usr/lib/os-release")
return "", ""
def get_real_terminal() -> str:
if os.environ.get("KITTY_WINDOW_ID"):
return "kitty"
try:
sid = os.getsid(0)
with open(f"/proc/{sid}/stat", "r") as f:
ppid = int(f.read().split()[3])
return os.path.basename(os.readlink(f"/proc/{ppid}/exe"))
except Exception:
return "terminal"
def get_real_shell() -> str:
try:
ppid = os.getppid()
shell_path = os.readlink(f"/proc/{ppid}/exe")
return os.path.basename(shell_path)
except Exception:
return os.path.basename(os.environ.get("SHELL", "bash"))
# Main
target, variant = detect_os()
config_path_base = os.path.expanduser(f"~/.config/fastfetch/{target}")
if os.path.isdir(config_path_base):
config_path = config_path_base + f"/{variant}.jsonc"
if not os.path.exists(config_path):
config_path = config_path_base + f"/default.jsonc"
if not os.path.exists(config_path):
config_path = config_path_base + ".jsonc"
else:
config_path = config_path_base + f"/default.jsonc"
if not os.path.exists(config_path):
config_path = config_path_base + ".jsonc"
os.environ["MY_TERMINAL"] = get_real_terminal()
os.environ["SHELL"] = get_real_shell()
args = ["fastfetch"]
if os.path.exists(config_path):
args.extend(["-c", config_path])
os.execvp("fastfetch", args)