From 9c9ce088193c2506da372c76685076bbfead0690 Mon Sep 17 00:00:00 2001 From: rorka900 Date: Fri, 24 Apr 2026 17:53:49 +0300 Subject: feat: modernize CLI with clap subcommands and add declarative apply --- src/install.rs | 95 +++++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 67 insertions(+), 28 deletions(-) (limited to 'src/install.rs') diff --git a/src/install.rs b/src/install.rs index a3bd400..3fe5c5c 100644 --- a/src/install.rs +++ b/src/install.rs @@ -120,7 +120,7 @@ fn default_install_prefix() -> String { "/".to_string() } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct InstalledPackage { pub name: String, pub version: String, @@ -138,15 +138,18 @@ impl InstalledDB { pub const PATH: &'static str = "/etc/ror/installed.json"; pub fn load() -> Self { + debug!("Loading installed package database from {}", Self::PATH); if Path::new(Self::PATH).exists() { let content = fs::read_to_string(Self::PATH).unwrap_or_default(); serde_json::from_str(&content).unwrap_or_default() } else { + debug!("No existing database found, starting fresh"); Self::default() } } pub fn save(&self) -> std::io::Result<()> { + debug!("Saving installed package database"); let json = serde_json::to_string_pretty(self) .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?; let path = Path::new(Self::PATH); @@ -157,6 +160,7 @@ impl InstalledDB { } pub fn add_package(&mut self, pkg: InstalledPackage) { + debug!("Registering {} in database", pkg.name); self.packages.insert(pkg.name.clone(), pkg); } @@ -166,6 +170,7 @@ impl InstalledDB { } fn sort_mirrors_by_speed(mirrors: &[String]) -> Vec { + debug!("Sorting {} mirrors by response time", mirrors.len()); use std::time::Instant; let client = match Client::builder() .timeout(std::time::Duration::from_secs(5)) @@ -194,6 +199,7 @@ fn sort_mirrors_by_speed(mirrors: &[String]) -> Vec { } pub fn extract_deb(archive_path: &Path, dest_root: &Path) -> Result, String> { + debug!("Extracting .deb archive {:?} to {:?}", archive_path, dest_root); let file = fs::File::open(archive_path).map_err(|e| e.to_string())?; let mut archive = ar::Archive::new(file); let mut installed_files = Vec::new(); @@ -221,6 +227,7 @@ pub fn extract_deb(archive_path: &Path, dest_root: &Path) -> Result, } } } + debug!("Deb extraction complete: {} files", installed_files.len()); Ok(installed_files) } @@ -249,6 +256,7 @@ fn normalize_libc(libc: &str) -> &str { pub fn select_binary_for_arch<'a>(pkg: &'a Package, arch: &str, libc: &str) -> Result<&'a BinaryPackage, String> { let target_arch = normalize_arch(arch); let target_libc = normalize_libc(libc); + debug!("Selecting binary for arch={}, libc={}", target_arch, target_libc); pkg.binaries .iter() @@ -269,6 +277,7 @@ pub fn select_binary_for_arch<'a>(pkg: &'a Package, arch: &str, libc: &str) -> R } pub fn find_package_file(pkg_name: &str) -> Option { + debug!("Looking for package {} in repository root", pkg_name); let repo = Path::new(REPO_ROOT); let read_dir = fs::read_dir(repo).ok()?; @@ -280,6 +289,7 @@ pub fn find_package_file(pkg_name: &str) -> Option { let pkg_path = cat_path.join(pkg_name).join(format!("{}.yaml", pkg_name)); if pkg_path.exists() && pkg_path.is_file() { + debug!("Found package at {:?}", pkg_path); return Some(pkg_path); } } @@ -287,6 +297,7 @@ pub fn find_package_file(pkg_name: &str) -> Option { } pub fn find_package_with_repo(pkg_name: &str) -> Option<(PathBuf, String)> { + debug!("Searching for package {} with repository info", pkg_name); let repo = Path::new(REPO_ROOT); let read_dir = fs::read_dir(repo).ok()?; @@ -299,13 +310,15 @@ pub fn find_package_with_repo(pkg_name: &str) -> Option<(PathBuf, String)> { let pkg_path = cat_path.join(pkg_name).join(format!("{}.yaml", pkg_name)); if pkg_path.exists() && pkg_path.is_file() { let repo_name = cat_path.file_name()?.to_string_lossy().to_string(); + debug!("Found package in repo {}: {:?}", repo_name, pkg_path); return Some((pkg_path, repo_name)); } } None } -fn verify_gpg_signature(archive_path: &Path, asc_path: &Path, pubkey_path: &Path) -> Result<(), String> { +pub fn verify_gpg_signature(archive_path: &Path, asc_path: &Path, pubkey_path: &Path) -> Result<(), String> { + debug!("Verifying GPG signature for {:?}", archive_path); if !pubkey_path.exists() { return Err(format!( "GPG public key not found: {}", @@ -315,7 +328,7 @@ fn verify_gpg_signature(archive_path: &Path, asc_path: &Path, pubkey_path: &Path if !asc_path.exists() { return Err(format!( - "GPG signature not found: {} — cannot verify package", + "GPG signature not found: {} -- cannot verify package", asc_path.display() )); } @@ -354,6 +367,7 @@ fn verify_gpg_signature(archive_path: &Path, asc_path: &Path, pubkey_path: &Path let _ = fs::remove_file(tmp_keyring); if verify.status.success() { + debug!("GPG signature verification succeeded"); Ok(()) } else { Err(format!( @@ -365,6 +379,7 @@ fn verify_gpg_signature(archive_path: &Path, asc_path: &Path, pubkey_path: &Path } pub fn install_package(pkg_name: &str, cfg: &config::Config) { + debug!("Starting install of package: {}", pkg_name); match install_package_with_result(pkg_name, cfg) { Ok(installed_pkg) => { let mut db = InstalledDB::load(); @@ -383,20 +398,20 @@ pub fn install_package(pkg_name: &str, cfg: &config::Config) { } pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Result { - debug!("install_package_with_result: start '{}'", pkg_name); + debug!("Resolving package {}", pkg_name); let mut spinner = Spinner::new(&format!("Resolving {}", pkg_name)); spinner.tick(&format!("Resolving {}", pkg_name)); let (pkg_path, repo_name) = find_package_with_repo(pkg_name) .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; - debug!("install_package_with_result: '{}' found in repo '{}' at {}", pkg_name, repo_name, pkg_path.display()); + debug!("Package file: {:?}, repository: {}", pkg_path, repo_name); let repo_cfg = cfg.repositories.get(&repo_name); let gpg_enabled = repo_cfg.map(|r| r.gpg_support).unwrap_or(false); let gpg_key = repo_cfg.and_then(|r| r.gpg_key.as_deref()); - debug!("install_package_with_result: repo='{}' gpg_enabled={} gpg_key={:?}", repo_name, gpg_enabled, gpg_key); + debug!("Repository config: GPG enabled = {}", gpg_enabled); if gpg_enabled && gpg_key.is_none() { return Err(format!( @@ -411,20 +426,19 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu let pkg: Package = serde_yaml::from_str(&content) .map_err(|e| format!("YAML structure error: {}", e))?; - debug!("install_package_with_result: '{}' version={} binaries={}", pkg_name, pkg.version, pkg.binaries.len()); + debug!("Loaded package metadata for {} version {}", pkg.name, pkg.version); if pkg.binaries.is_empty() { return Err("No binary packages defined".to_string()); } let binary = select_binary_for_arch(&pkg, &cfg.global.arch, &cfg.global.libc)?; - debug!("install_package_with_result: selected binary arch={} type={:?} libc={:?}", binary.arch, binary.pkg_type, binary.libc); + debug!("Selected binary: arch={}, libc={:?}", binary.arch, binary.libc); let db = InstalledDB::load(); for conflict in &pkg.conflicts { if db.is_installed(conflict) { - debug!("install_package_with_result: '{}' conflicts with '{}'", pkg_name, conflict); return Err(format!( "Package '{}' conflicts with installed package '{}'", pkg_name, conflict @@ -434,10 +448,8 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu let mut urls_to_try = Vec::new(); if !binary.url.is_empty() { - debug!("install_package_with_result: using direct url={}", binary.url); urls_to_try.push(binary.url.clone()); } else if !binary.mirrors.is_empty() { - debug!("install_package_with_result: building urls from mirrors"); urls_to_try = binary .mirrors .iter() @@ -459,14 +471,13 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu return Err(format!("Could not resolve any download URL for package {}", pkg_name)); } - debug!("install_package_with_result: '{}' urls={:?}", pkg_name, urls_to_try); + debug!("Resolved {} download URLs", urls_to_try.len()); if !cfg.global.ignore_speed && urls_to_try.len() > 1 { - debug!("install_package_with_result: testing mirror speeds for '{}'", pkg_name); spinner.tick("Testing mirror speeds..."); urls_to_try = sort_mirrors_by_speed(&urls_to_try); spinner.finish(&format!("Fastest mirror selected: {}", urls_to_try[0])); - debug!("install_package_with_result: fastest mirror={}", urls_to_try[0]); + debug!("Fastest mirror: {}", urls_to_try[0]); } let mut last_err = None; @@ -474,16 +485,16 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu let mut downloaded = false; for url in urls_to_try { - debug!("install_package_with_result: trying url={}", url); spinner.tick(&format!("Downloading {} ...", url.split('/').last().unwrap_or(&url))); + debug!("Downloading {}", url); let archive_path = match download_and_verify(&url, &binary.sha256, cfg) { Ok(p) => { - debug!("install_package_with_result: downloaded to {}", p.display()); + debug!("Download successful: {:?}", p); p } Err(e) => { - debug!("install_package_with_result: download failed: {}", e); + debug!("Download failed: {}", e); last_err = Some(e); continue; } @@ -493,13 +504,15 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu if gpg_enabled { let asc_url = format!("{}.asc", url); - spinner.tick(&format!("Downloading GPG signature...")); + spinner.tick("Downloading GPG signature..."); + debug!("Downloading GPG signature from {}", asc_url); let asc_path = match download_and_verify(&asc_url, "", cfg) { Ok(p) => p, Err(_) => { let _ = fs::remove_file(&archive_path); + debug!("GPG signature missing, aborting"); return Err(format!( - "GPG signature not found for '{}' at {} — installation aborted", + "GPG signature not found for {} at {} - installation aborted", pkg_name, asc_url )); } @@ -510,6 +523,7 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu if let Err(e) = verify_gpg_signature(&archive_path, &asc_path, &pubkey_path) { let _ = fs::remove_file(&archive_path); let _ = fs::remove_file(&asc_path); + debug!("GPG verification error: {}", e); return Err(e); } let _ = fs::remove_file(&asc_path); @@ -521,17 +535,20 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu fs::create_dir_all(&work_dir).map_err(|e| format!("Failed to create temp dir: {}", e))?; let pkg_type = binary.pkg_type.as_deref().unwrap_or("tar.xz"); + debug!("Package type: {}", pkg_type); let mut sp2 = Spinner::new(&format!("Extracting {}", pkg_name)); sp2.tick(&format!("Extracting {}...", pkg_name)); if pkg_type == "deb" { + debug!("Extracting deb package"); let mut files = extract_deb(&archive_path, Path::new("/"))?; all_installed_files.append(&mut files); } else if pkg_type == "ror" { let dict_url = binary.dict.as_ref() - .ok_or_else(|| format!("Package '{}' has type 'ror' but no dict URL", pkg_name))?; + .ok_or_else(|| format!("Package {} has type ror but no dict URL", pkg_name))?; sp2.tick(&format!("Downloading dictionary for {}...", pkg_name)); + debug!("Downloading dictionary: {}", dict_url); let dict_path = download_and_verify(dict_url, "", cfg)?; let files = extract_ror(&archive_path, &dict_path, &work_dir) .map_err(|e| format!("Extraction failed: {}", e))?; @@ -541,6 +558,7 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu .map_err(|e| format!("Failed to install files: {}", e))?; all_installed_files.append(&mut installed); } else if pkg_type == "sror" { + debug!("Extracting sror package"); let files = extract_sror(&archive_path, &work_dir) .map_err(|e| format!("Extraction failed: {}", e))?; sp2.tick(&format!("Installing files for {}...", pkg_name)); @@ -548,6 +566,7 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu .map_err(|e| format!("Failed to install files: {}", e))?; all_installed_files.append(&mut installed); } else { + debug!("Extracting native tar package"); let files = extract_native(&archive_path, &work_dir) .map_err(|e| format!("Extraction failed: {}", e))?; sp2.tick(&format!("Installing files for {}...", pkg_name)); @@ -557,29 +576,28 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu } sp2.finish(&format!("Installed {} files", all_installed_files.len())); + debug!("Total installed files: {}", all_installed_files.len()); let _ = fs::remove_dir_all(&work_dir); let _ = fs::remove_file(&archive_path); downloaded = true; - debug!("install_package_with_result: '{}' extracted {} files", pkg_name, all_installed_files.len()); break; } if !downloaded { - debug!("install_package_with_result: '{}' all mirrors failed", pkg_name); return Err(last_err.unwrap_or_else(|| "All mirrors/URLs failed".to_string())); } if !pkg.install_steps.is_empty() { - debug!("install_package_with_result: '{}' running install_steps", pkg_name); + debug!("Running install steps"); let mut sp3 = Spinner::new(&format!("Running install steps for {}", pkg_name)); sp3.tick(&format!("Running install steps for {}...", pkg_name)); run_commands(&pkg.install_steps, Path::new("/"))?; sp3.finish("Install steps done"); - debug!("install_package_with_result: '{}' install_steps done", pkg_name); } - debug!("install_package_with_result: '{}' complete v={} files={}", pkg_name, pkg.version, all_installed_files.len()); + debug!("Installation complete for {}", pkg_name); + Ok(InstalledPackage { name: pkg.name.clone(), version: pkg.version.clone(), @@ -590,6 +608,7 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu } pub fn download_and_verify(url: &str, expected_sha: &str, _cfg: &config::Config) -> Result { + debug!("Downloading {} (expected SHA256: {})", url, if expected_sha.is_empty() { "none" } else { expected_sha }); let client = Client::builder() .connect_timeout(std::time::Duration::from_secs(30)) .build() @@ -642,7 +661,7 @@ pub fn download_and_verify(url: &str, expected_sha: &str, _cfg: &config::Config) Some(total) if total > 0 => { let pct = downloaded * 40 / total; let bar = format!( - "{}>{}", + "{}>{}", "=".repeat(pct.saturating_sub(1) as usize), " ".repeat((40 - pct) as usize) ); @@ -667,19 +686,21 @@ pub fn download_and_verify(url: &str, expected_sha: &str, _cfg: &config::Config) let hash = format!("{:x}", hasher.finalize()); if hash != expected_sha { let _ = fs::remove_file(&file_path); + debug!("SHA256 mismatch: expected {}, got {}", expected_sha, hash); return Err(format!( "SHA256 mismatch: expected {}, got {}", expected_sha, hash )); } + debug!("SHA256 verified successfully"); } } Ok(file_path) } - pub fn extract_native(archive_path: &Path, target_dir: &Path) -> Result, String> { + debug!("Extracting native tar archive {:?} to {:?}", archive_path, target_dir); let status = Command::new("tar") .arg("-xf") .arg(archive_path) @@ -699,10 +720,12 @@ pub fn extract_native(archive_path: &Path, target_dir: &Path) -> Result Result, String> { + debug!("Extracting .ror archive {:?} using dictionary {:?}", archive_path, dict_path); let zstd_arg = format!("zstd -D {}", dict_path.display()); let status = Command::new("tar") @@ -726,10 +749,12 @@ pub fn extract_ror(archive_path: &Path, dict_path: &Path, target_dir: &Path) -> files.push(rel_path.to_string_lossy().to_string()); } } + debug!("Extracted {} files from .ror", files.len()); Ok(files) } pub fn extract_sror(archive_path: &Path, target_dir: &Path) -> Result, String> { + debug!("Extracting .sror archive {:?} to {:?}", archive_path, target_dir); let status = Command::new("tar") .arg("-I") .arg("zstd") @@ -751,10 +776,12 @@ pub fn extract_sror(archive_path: &Path, target_dir: &Path) -> Result Result, String> { + debug!("Installing {} files from {:?} to prefix {}", files.len(), source_dir, prefix); let prefix_path = Path::new(prefix); let mut installed = Vec::new(); @@ -786,6 +813,7 @@ fn install_files(source_dir: &Path, prefix: &str, files: &[String]) -> Result Result, String> { + debug!("Installing {} files to root {:?}", files.len(), root); let mut installed = Vec::new(); for rel_path in files { let src = source_dir.join(rel_path); @@ -817,6 +845,7 @@ pub fn install_files_with_root(source_dir: &Path, root: &Path, files: &[String]) } pub fn run_commands(steps: &str, work_dir: &Path) -> Result<(), String> { + debug!("Running commands: {}", steps); if steps.trim().is_empty() { return Ok(()); } @@ -825,8 +854,9 @@ pub fn run_commands(steps: &str, work_dir: &Path) -> Result<(), String> { .arg("-c") .arg(steps) .status() - .map_err(|e| format!("Failed to execute 'sh -c': {}", e))?; + .map_err(|e| format!("Failed to execute sh -c: {}", e))?; if status.success() { + debug!("Commands executed successfully"); Ok(()) } else { Err(format!("Command failed with exit code {:?}", status.code())) @@ -834,6 +864,7 @@ pub fn run_commands(steps: &str, work_dir: &Path) -> Result<(), String> { } pub fn get_package_info(pkg_name: &str) -> Option<(String, String)> { + debug!("Getting info for package {}", pkg_name); let pkg_path = find_package_file(pkg_name)?; let content = fs::read_to_string(pkg_path).ok()?; let name = pkg_name.to_string(); @@ -847,12 +878,14 @@ pub fn get_package_info(pkg_name: &str) -> Option<(String, String)> { } pub fn load_package(pkg_name: &str) -> Option { + debug!("Loading full package metadata for {}", pkg_name); let pkg_path = find_package_file(pkg_name)?; let content = fs::read_to_string(pkg_path).ok()?; serde_yaml::from_str(&content).ok() } pub fn install_local_package(archive_path: &Path, cfg: &config::Config) { + debug!("Starting local install from {:?}", archive_path); match install_local_package_with_result(archive_path, cfg) { Ok(installed_pkg) => { let mut db = InstalledDB::load(); @@ -871,6 +904,7 @@ pub fn install_local_package(archive_path: &Path, cfg: &config::Config) { } pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Config) -> Result { + debug!("Processing local package at {:?}", archive_path); if !archive_path.exists() { return Err(format!("File not found: {}", archive_path.display())); } @@ -880,6 +914,7 @@ pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Con let name = stem.to_string(); let version = "local".to_string(); + debug!("Local package: name={}, version={}, extension={}", name, version, ext); let work_dir = Path::new("/tmp/ror-local").join(&name); let _ = fs::remove_dir_all(&work_dir); @@ -889,6 +924,7 @@ pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Con spinner.tick(&format!("Extracting {}...", name)); let installed_files = if ext == "sror" { + debug!("Extracting local sror package"); let files = extract_sror(archive_path, &work_dir) .map_err(|e| format!("Extraction failed: {}", e))?; let installed = install_files_to_root(&work_dir, Path::new("/"), &files) @@ -902,6 +938,7 @@ pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Con dict_path.display() )); } + debug!("Extracting local ror package with dictionary"); let files = extract_ror(archive_path, &dict_path, &work_dir) .map_err(|e| format!("Extraction failed: {}", e))?; let installed = install_files_to_root(&work_dir, Path::new("/"), &files) @@ -912,6 +949,7 @@ pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Con }; spinner.finish(&format!("Installed {} files", installed_files.len())); + debug!("Local installation complete, {} files", installed_files.len()); let _ = fs::remove_dir_all(&work_dir); @@ -925,6 +963,7 @@ pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Con } fn install_files_to_root(source_dir: &Path, root: &Path, files: &[String]) -> Result, String> { + debug!("Copying files from {:?} to root {:?}", source_dir, root); let mut installed = Vec::new(); for rel_path in files { let src = source_dir.join(rel_path); -- cgit v1.2.3