spcd/spcd/util.py
2024-09-16 01:14:52 +02:00

92 lines
2.1 KiB
Python

"""Basic utilities."""
import os
from pathlib import Path
from urllib.parse import urlparse, urlunparse
from rwx import fs
from rwx.log import stream as log
from spcd import shell
from spcd.shell import env
def add_url_path(url: str, extra_path: str) -> str:
"""Append an extra segment to an existing URL.
:param url: base URL
:type url: str
:param extra_path: path to append
:type extra_path: str
:return: new URL
:rtype: str
"""
parts = urlparse(url)
parts = parts._replace(path=str(Path(parts.path) / extra_path))
return urlunparse(parts)
def browse(root: Path) -> None:
"""Frame the browsing of a root directory in the log output.
:param root: directory to browse
:type root: Path
"""
paths = []
for directory, _, files in os.walk(root):
for file in files:
absolute_path = Path(directory) / file
relative_path = os.path.relpath(absolute_path, start=root)
paths.append(relative_path)
text = str(root)
frame(text)
for path in sorted(paths):
log.info(path)
shut(text)
def cat(file: Path) -> None:
"""Frame the content of a file in the log output.
:param file: file to read the content from
:type file: Path
"""
text = str(file)
frame(text)
log.info(fs.read_file_text(file).rstrip())
shut(text)
def frame(text: str) -> None:
"""Open a new frame in the log output.
:param text: text to start the frame with
:type text: str
"""
log.info("%s%s", env.SPCD_OPEN, text)
def shut(text: str) -> None:
"""Close current frame in the log output.
:param text: text to shut the frame with
:type text: str
"""
log.info("%s%s", env.SPCD_SHUT, text)
def split() -> None:
"""Separate previous log outputs from the ones following."""
log.info(env.SPCD_SPLT)
def step(text: str) -> None:
"""Increment the step number of the current build process.
:param text: text to display
:type text: str
"""
shell.STEP += 1
log.info(env.SPCD_DOWN)
log.info("%s %s %s", env.SPCD_VERT, shell.STEP, text)
log.info(env.SPCD___UP)