mirror of
https://github.com/dw-0/kiauh.git
synced 2025-12-25 16:53:36 +05:00
refactor(KIAUH): use pathlib instead of os where possible. consistent use of pathlib.
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
This commit is contained in:
@@ -8,12 +8,13 @@
|
||||
# #
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license #
|
||||
# ======================================================================= #
|
||||
import os
|
||||
|
||||
MODULE_PATH = os.path.dirname(os.path.abspath(__file__))
|
||||
from pathlib import Path
|
||||
|
||||
MODULE_PATH = Path(__file__).resolve().parent
|
||||
INVALID_CHOICE = "Invalid choice. Please select a valid value."
|
||||
|
||||
# ================== NGINX =====================#
|
||||
NGINX_SITES_AVAILABLE = "/etc/nginx/sites-available"
|
||||
NGINX_SITES_ENABLED = "/etc/nginx/sites-enabled"
|
||||
NGINX_CONFD = "/etc/nginx/conf.d"
|
||||
NGINX_SITES_AVAILABLE = Path("/etc/nginx/sites-available")
|
||||
NGINX_SITES_ENABLED = Path("/etc/nginx/sites-enabled")
|
||||
NGINX_CONFD = Path("/etc/nginx/conf.d")
|
||||
|
||||
@@ -56,7 +56,7 @@ def check_install_dependencies(deps: List[str]) -> None:
|
||||
install_system_packages(requirements)
|
||||
|
||||
|
||||
def get_repo_name(repo_dir: str) -> str:
|
||||
def get_repo_name(repo_dir: Path) -> str:
|
||||
"""
|
||||
Helper method to extract the organisation and name of a repository |
|
||||
:param repo_dir: repository to extract the values from
|
||||
@@ -72,7 +72,7 @@ def get_repo_name(repo_dir: str) -> str:
|
||||
|
||||
|
||||
def get_install_status_common(
|
||||
instance_type: Type[BaseInstance], repo_dir: str, env_dir: str
|
||||
instance_type: Type[BaseInstance], repo_dir: Path, env_dir: Path
|
||||
) -> str:
|
||||
"""
|
||||
Helper method to get the installation status of software components,
|
||||
@@ -85,10 +85,8 @@ def get_install_status_common(
|
||||
:return: formatted string, containing the status
|
||||
"""
|
||||
im = InstanceManager(instance_type)
|
||||
dir_exist = Path(repo_dir).exists()
|
||||
env_dir_exist = Path(env_dir).exists()
|
||||
instances_exist = len(im.instances) > 0
|
||||
status = [dir_exist, env_dir_exist, instances_exist]
|
||||
status = [repo_dir.exists(), env_dir.exists(), instances_exist]
|
||||
if all(status):
|
||||
return f"{COLOR_GREEN}Installed: {len(im.instances)}{RESET_FORMAT}"
|
||||
elif not any(status):
|
||||
@@ -109,7 +107,7 @@ def get_install_status_webui(
|
||||
:param common_cfg: the required common_vars.conf
|
||||
:return: formatted string, containing the status
|
||||
"""
|
||||
dir_exist = Path(install_dir).exists()
|
||||
dir_exist = install_dir.exists()
|
||||
nginx_cfg_exist = check_file_exist(nginx_cfg)
|
||||
upstreams_cfg_exist = check_file_exist(upstreams_cfg)
|
||||
common_cfg_exist = check_file_exist(common_cfg)
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
import os
|
||||
import pwd
|
||||
from pathlib import Path
|
||||
|
||||
# text colors and formats
|
||||
COLOR_WHITE = "\033[37m" # white
|
||||
@@ -22,4 +23,4 @@ COLOR_CYAN = "\033[96m" # bright cyan
|
||||
RESET_FORMAT = "\033[0m" # reset format
|
||||
# current user
|
||||
CURRENT_USER = pwd.getpwuid(os.getuid())[0]
|
||||
SYSTEMD = "/etc/systemd/system"
|
||||
SYSTEMD = Path("/etc/systemd/system")
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license #
|
||||
# ======================================================================= #
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
@@ -37,27 +36,12 @@ def check_file_exist(file_path: Path, sudo=False) -> bool:
|
||||
except subprocess.CalledProcessError:
|
||||
return False
|
||||
else:
|
||||
if Path(file_path).exists():
|
||||
if file_path.exists():
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def create_directory(_dir: Path) -> None:
|
||||
"""
|
||||
Helper function for creating a directory or skipping if it already exists |
|
||||
:param _dir: the directory to create
|
||||
:return: None
|
||||
"""
|
||||
try:
|
||||
if not os.path.isdir(_dir):
|
||||
os.makedirs(_dir, exist_ok=True)
|
||||
Logger.print_ok(f"Created directory: {_dir}")
|
||||
except OSError as e:
|
||||
Logger.print_error(f"Error creating folder: {e}")
|
||||
raise
|
||||
|
||||
|
||||
def create_symlink(source: Path, target: Path, sudo=False) -> None:
|
||||
try:
|
||||
cmd = ["ln", "-sf", source, target]
|
||||
@@ -79,14 +63,14 @@ def remove_file(file_path: Path, sudo=False) -> None:
|
||||
raise
|
||||
|
||||
|
||||
def unzip(file: str, target_dir: str) -> None:
|
||||
def unzip(filepath: Path, target_dir: Path) -> None:
|
||||
"""
|
||||
Helper function to unzip a zip-archive into a target directory |
|
||||
:param file: the zip-file to unzip
|
||||
:param filepath: the path to the zip-file to unzip
|
||||
:param target_dir: the target directory to extract the files into
|
||||
:return: None
|
||||
"""
|
||||
with ZipFile(file, "r") as _zip:
|
||||
with ZipFile(filepath, "r") as _zip:
|
||||
_zip.extractall(target_dir)
|
||||
|
||||
|
||||
@@ -95,8 +79,8 @@ def copy_upstream_nginx_cfg() -> None:
|
||||
Creates an upstream.conf in /etc/nginx/conf.d
|
||||
:return: None
|
||||
"""
|
||||
source = os.path.join(MODULE_PATH, "res", "upstreams.conf")
|
||||
target = os.path.join(NGINX_CONFD, "upstreams.conf")
|
||||
source = MODULE_PATH.joinpath("res/upstreams.conf")
|
||||
target = NGINX_CONFD.joinpath("upstreams.conf")
|
||||
try:
|
||||
command = ["sudo", "cp", source, target]
|
||||
subprocess.run(command, stderr=subprocess.PIPE, check=True)
|
||||
@@ -111,8 +95,8 @@ def copy_common_vars_nginx_cfg() -> None:
|
||||
Creates a common_vars.conf in /etc/nginx/conf.d
|
||||
:return: None
|
||||
"""
|
||||
source = os.path.join(MODULE_PATH, "res", "common_vars.conf")
|
||||
target = os.path.join(NGINX_CONFD, "common_vars.conf")
|
||||
source = MODULE_PATH.joinpath("res/common_vars.conf")
|
||||
target = NGINX_CONFD.joinpath("common_vars.conf")
|
||||
try:
|
||||
command = ["sudo", "cp", source, target]
|
||||
subprocess.run(command, stderr=subprocess.PIPE, check=True)
|
||||
@@ -122,7 +106,7 @@ def copy_common_vars_nginx_cfg() -> None:
|
||||
raise
|
||||
|
||||
|
||||
def create_nginx_cfg(name: str, port: int, root_dir: str) -> None:
|
||||
def create_nginx_cfg(name: str, port: int, root_dir: Path) -> None:
|
||||
"""
|
||||
Creates an NGINX config from a template file and replaces all placeholders
|
||||
:param name: name of the config to create
|
||||
@@ -130,18 +114,18 @@ def create_nginx_cfg(name: str, port: int, root_dir: str) -> None:
|
||||
:param root_dir: directory of the static files
|
||||
:return: None
|
||||
"""
|
||||
tmp = f"{Path.home()}/{name}.tmp"
|
||||
shutil.copy(os.path.join(MODULE_PATH, "res", "nginx_cfg"), tmp)
|
||||
tmp = Path.home().joinpath(f"{name}.tmp")
|
||||
shutil.copy(MODULE_PATH.joinpath("res/nginx_cfg"), tmp)
|
||||
with open(tmp, "r+") as f:
|
||||
content = f.read()
|
||||
content = content.replace("%NAME%", name)
|
||||
content = content.replace("%PORT%", str(port))
|
||||
content = content.replace("%ROOT_DIR%", root_dir)
|
||||
content = content.replace("%ROOT_DIR%", str(root_dir))
|
||||
f.seek(0)
|
||||
f.write(content)
|
||||
f.truncate()
|
||||
|
||||
target = os.path.join(NGINX_SITES_AVAILABLE, name)
|
||||
target = NGINX_SITES_AVAILABLE.joinpath(name)
|
||||
try:
|
||||
command = ["sudo", "mv", tmp, target]
|
||||
subprocess.run(command, stderr=subprocess.PIPE, check=True)
|
||||
|
||||
@@ -98,7 +98,7 @@ def update_python_pip(target: Path) -> None:
|
||||
"""
|
||||
Logger.print_status("Updating pip ...")
|
||||
try:
|
||||
command = [f"{target}/bin/pip", "install", "-U", "pip"]
|
||||
command = [target.joinpath("bin/pip"), "install", "-U", "pip"]
|
||||
result = subprocess.run(command, stderr=subprocess.PIPE, text=True)
|
||||
if result.returncode != 0 or result.stderr:
|
||||
Logger.print_error(f"{result.stderr}", False)
|
||||
@@ -120,7 +120,7 @@ def install_python_requirements(target: Path, requirements: Path) -> None:
|
||||
update_python_pip(target)
|
||||
Logger.print_status("Installing Python requirements ...")
|
||||
try:
|
||||
command = [f"{target}/bin/pip", "install", "-r", f"{requirements}"]
|
||||
command = [target.joinpath("bin/pip"), "install", "-r", f"{requirements}"]
|
||||
result = subprocess.run(command, stderr=subprocess.PIPE, text=True)
|
||||
if result.returncode != 0 or result.stderr:
|
||||
Logger.print_error(f"{result.stderr}", False)
|
||||
@@ -141,9 +141,12 @@ def update_system_package_lists(silent: bool, rls_info_change=False) -> None:
|
||||
:return: None
|
||||
"""
|
||||
cache_mtime = 0
|
||||
cache_files = ["/var/lib/apt/periodic/update-success-stamp", "/var/lib/apt/lists"]
|
||||
cache_files = [
|
||||
Path("/var/lib/apt/periodic/update-success-stamp"),
|
||||
Path("/var/lib/apt/lists"),
|
||||
]
|
||||
for cache_file in cache_files:
|
||||
if Path(cache_file).exists():
|
||||
if cache_file.exists():
|
||||
cache_mtime = max(cache_mtime, os.path.getmtime(cache_file))
|
||||
|
||||
update_age = int(time.time() - cache_mtime)
|
||||
@@ -244,7 +247,7 @@ def get_ipv4_addr() -> str:
|
||||
|
||||
|
||||
def download_file(
|
||||
url: str, target_folder: str, target_name: str, show_progress=True
|
||||
url: str, target_folder: Path, target_name: str, show_progress=True
|
||||
) -> None:
|
||||
"""
|
||||
Helper method for downloading files from a provided URL |
|
||||
@@ -254,7 +257,7 @@ def download_file(
|
||||
:param show_progress: show download progress or not
|
||||
:return: None
|
||||
"""
|
||||
target_path = os.path.join(target_folder, target_name)
|
||||
target_path = target_folder.joinpath(target_name)
|
||||
try:
|
||||
if show_progress:
|
||||
urllib.request.urlretrieve(url, target_path, download_progress)
|
||||
@@ -298,8 +301,8 @@ def set_nginx_permissions() -> None:
|
||||
This seems to have become necessary with Ubuntu 21+. |
|
||||
:return: None
|
||||
"""
|
||||
cmd1 = f"ls -ld {Path.home()} | cut -d' ' -f1"
|
||||
homedir_perm = subprocess.run(cmd1, shell=True, stdout=subprocess.PIPE, text=True)
|
||||
cmd = f"ls -ld {Path.home()} | cut -d' ' -f1"
|
||||
homedir_perm = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, text=True)
|
||||
homedir_perm = homedir_perm.stdout
|
||||
|
||||
if homedir_perm.count("x") < 3:
|
||||
@@ -321,7 +324,7 @@ def control_systemd_service(
|
||||
Logger.print_status(f"{action.capitalize()} {name}.service ...")
|
||||
command = ["sudo", "systemctl", action, f"{name}.service"]
|
||||
subprocess.run(command, stderr=subprocess.PIPE, check=True)
|
||||
Logger.print_ok(f"OK!")
|
||||
Logger.print_ok("OK!")
|
||||
except subprocess.CalledProcessError as e:
|
||||
log = f"Failed to {action} {name}.service: {e.stderr.decode()}"
|
||||
Logger.print_error(log)
|
||||
|
||||
Reference in New Issue
Block a user