rwx/rwx/fs/__init__.py
2024-09-17 23:19:29 +02:00

110 lines
2.6 KiB
Python

"""Operations involving FileSystems."""
import os
import shutil
from pathlib import Path
from rwx import ps
CHARSET = "UTF-8"
def create_image(file_path: Path, size_bytes: int) -> None:
"""Create a virtual device image file.
:param file_path: target image file
:type file_path: Path
:param size_bytes: virtual volume
:type size_bytes: int
"""
ps.run(
("qemu-img", "create"),
("-f", "qcow2"),
(str(file_path), str(size_bytes)),
)
def empty_file(path: Path) -> None:
"""Empty the file at provided path.
:param path: target file to empty
:type path: Path
"""
write(path, "")
def get_mount_uuid(path: str) -> str:
"""Return the filesystem UUID of a mountpoint path."""
return ps.run_line(
("findmnt",),
("--noheadings",),
("--output", "UUID"),
(path,),
)
def get_path_mount(path: str) -> str:
"""Return the mountpoint path of an arbitrary path."""
return ps.run_line(
"stat",
("--format", "%m"),
path,
)
def get_path_uuid(path: str) -> str:
"""Return the filesystem UUID of an arbitrary path."""
return get_mount_uuid(get_path_mount(path))
def make_directory(path: Path) -> None:
"""Make a directory (and its parents) from a path.
:param path: directory to create
:type path: Path
"""
path.mkdir(exist_ok=True, parents=True)
def read_file_bytes(file_path: Path) -> bytes:
"""Read whole file bytes."""
with file_path.open("br") as file_object:
return file_object.read()
def read_file_lines(file_path: Path, charset: str = CHARSET) -> list[str]:
"""Read whole file lines."""
return read_file_text(file_path, charset).split(os.linesep)
def read_file_text(file_path: Path, charset: str = CHARSET) -> str:
"""Read whole file text."""
return read_file_bytes(file_path).decode(charset)
def wipe(path: Path) -> None:
"""Wipe provided path, whether directory or file.
:param path: target path
:type path: Path
"""
try:
shutil.rmtree(path)
except NotADirectoryError:
path.unlink(missing_ok=True)
except FileNotFoundError:
pass
def write(file_path: Path, text: str, charset: str = CHARSET) -> None:
"""Write text into a file.
:param file_path: target file path
:type file_path: Path
:param text: content to write
:type text: str
:param charset: charset to use for encoding ouput
:type charset: str
"""
with file_path.open(encoding=charset, mode="w") as file_object:
file_object.write(text)