clan-core/pkgs/clan-cli/clan_cli/dirs.py

90 lines
2.4 KiB
Python
Raw Normal View History

2023-10-18 16:29:51 +00:00
import logging
import os
import sys
from pathlib import Path
from typing import Optional
2023-07-28 10:12:37 +00:00
from .errors import ClanError
from .types import FlakeName
2023-07-28 10:12:37 +00:00
log = logging.getLogger(__name__)
2023-10-18 16:29:51 +00:00
def get_clan_flake_toplevel() -> Optional[Path]:
return find_toplevel([".clan-flake", ".git", ".hg", ".svn", "flake.nix"])
def find_git_repo_root() -> Optional[Path]:
try:
return find_toplevel([".git"])
except ClanError:
return None
def find_toplevel(top_level_files: list[str]) -> Optional[Path]:
"""Returns the path to the toplevel of the clan flake"""
for project_file in top_level_files:
initial_path = Path(os.getcwd())
path = Path(initial_path)
while path.parent != path:
if (path / project_file).exists():
return path
path = path.parent
return None
2023-07-29 12:21:28 +00:00
def user_config_dir() -> Path:
if sys.platform == "win32":
2023-07-29 12:21:28 +00:00
return Path(os.getenv("APPDATA", os.path.expanduser("~\\AppData\\Roaming\\")))
elif sys.platform == "darwin":
return Path(os.path.expanduser("~/Library/Application Support/"))
else:
2023-07-29 12:21:28 +00:00
return Path(os.getenv("XDG_CONFIG_HOME", os.path.expanduser("~/.config")))
def clan_config_dir() -> Path:
path = user_config_dir() / "clan"
path.mkdir(parents=True, exist_ok=True)
return path.resolve()
def clan_flakes_dir() -> Path:
path = clan_config_dir() / "flakes"
path.mkdir(parents=True, exist_ok=True)
return path.resolve()
2023-10-14 13:17:58 +00:00
def specific_flake_dir(flake_name: FlakeName) -> Path:
flake_dir = clan_flakes_dir() / flake_name
2023-10-24 14:54:10 +00:00
if not flake_dir.exists():
raise ClanError(f"Flake '{flake_name}' does not exist in {clan_flakes_dir()}")
2023-10-24 14:54:10 +00:00
return flake_dir
2023-10-14 13:17:58 +00:00
def machines_dir(flake_name: FlakeName) -> Path:
return specific_flake_dir(flake_name) / "machines"
2023-10-24 14:54:10 +00:00
2023-10-14 13:17:58 +00:00
def specific_machine_dir(flake_name: FlakeName, machine: str) -> Path:
2023-10-24 14:54:10 +00:00
return machines_dir(flake_name) / machine
2023-10-14 13:17:58 +00:00
def machine_settings_file(flake_name: FlakeName, machine: str) -> Path:
2023-10-24 14:54:10 +00:00
return specific_machine_dir(flake_name, machine) / "settings.json"
def module_root() -> Path:
return Path(__file__).parent
2023-09-06 15:29:49 +00:00
def nixpkgs_flake() -> Path:
return (module_root() / "nixpkgs").resolve()
2023-09-06 15:29:49 +00:00
def nixpkgs_source() -> Path:
return (module_root() / "nixpkgs" / "path").resolve()
def unfree_nixpkgs() -> Path:
return module_root() / "nixpkgs" / "unfree"