Adds get_paths_to_sync and organise it in a class

This refactors the paths functions in a class called PathsManager
allowing to share some data like the Paths to the various directories
unisync works with.
This commit also creates the get_paths_to_sync method which simply reads
the paths file and returns its content as a list
This commit is contained in:
2025-07-31 11:45:17 +02:00
parent 837cc1bcf4
commit c5992ef19e

View File

@@ -3,13 +3,36 @@
import subprocess import subprocess
def user_select_files(local_dir:str, choice_timeout:int=120) -> list[str]: from pathlib import Path, PosixPath
class PathsManager:
def __init__(self, local_dir:PosixPath, cache_dir:PosixPath):
"""
Creates a PathsManager with the necessary data
Args:
local_dir: Path to the top directory of the synchronisation
cache_dir: Path to the cache directory that contains the paths file
"""
if not local_dir.is_dir():
raise ValueError("Invalid local directory")
self.local_dir = local_dir
if not cache_dir.is_dir():
raise ValueError("Invalid cache directory")
self.cache_dir = cache_dir
self.paths_file:PosixPath = self.cache_dir / "paths"
if not self.paths_file.is_file():
raise ValueError("The paths file does not exist")
def user_select_files(self, choice_timeout:int=120) -> list[str]:
""" """
Make the user select files in the top directory. Make the user select files in the top directory.
Currently uses nnn for the selection. Currently uses nnn for the selection.
The goal is to replace it in order to avoid using external programs. The goal is to replace it in order to avoid using external programs.
Args: Args:
local_dir: The absolute path to the top synchronisation directory
choice_timeout: Time given to make choices in nnn choice_timeout: Time given to make choices in nnn
Returns: Returns:
list[str]: The list of paths that was selected list[str]: The list of paths that was selected
@@ -18,7 +41,7 @@ def user_select_files(local_dir:str, choice_timeout:int=120) -> list[str]:
"/usr/bin/nnn", "/usr/bin/nnn",
"-H", "-H",
"-p", "-", "-p", "-",
local_dir self.local_dir
] ]
nnn_process = subprocess.Popen(command, stdout=subprocess.PIPE) nnn_process = subprocess.Popen(command, stdout=subprocess.PIPE)
try: try:
@@ -35,10 +58,17 @@ def user_select_files(local_dir:str, choice_timeout:int=120) -> list[str]:
while (next_path := nnn_process.stdout.readline()) != b'': while (next_path := nnn_process.stdout.readline()) != b'':
next_path = next_path.decode().strip() next_path = next_path.decode().strip()
# Make the path relative to the top directory # Make the path relative to the top directory
next_path = next_path[len(local_dir):].lstrip("/") next_path = next_path[len(self.local_dir):].lstrip("/")
paths_list.append(next_path) paths_list.append(next_path)
return paths_list return paths_list
def get_paths_to_sync(self) -> list[str]:
"""
Return the paths to synchronise as list.
"""
paths:list[str] = self.paths_file.read_text().split("\n")
if paths[-1] == "":
paths.pop()
return paths