diff options
| -rw-r--r-- | Cargo.lock | 2 | ||||
| -rw-r--r-- | Cargo.toml | 2 | ||||
| -rw-r--r-- | src/config.rs | 25 | ||||
| -rw-r--r-- | src/install.rs | 218 | ||||
| -rw-r--r-- | src/main.rs | 89 | ||||
| -rw-r--r-- | src/parallel.rs | 63 | ||||
| -rw-r--r-- | src/progress.rs | 94 | ||||
| -rw-r--r-- | src/rootfs.rs | 188 | ||||
| -rw-r--r-- | src/update.rs | 29 |
9 files changed, 482 insertions, 228 deletions
@@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "ror" -version = "0.1.0" +version = "0.2.0" dependencies = [ "anyhow", "ar", @@ -1,6 +1,6 @@ [package] name = "ror" -version = "0.1.0" +version = "0.2.0" edition = "2021" authors = ["rorka900"] description = "RorkOS package manager" diff --git a/src/config.rs b/src/config.rs index d79ad28..6fc440f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -34,7 +34,7 @@ pub struct Config { impl Config { pub fn load() -> Self { - let path = Path::new("/var/ror/ror.conf"); + let path = Path::new("/etc/ror/ror.conf"); if path.exists() { let content = fs::read_to_string(path).unwrap_or_default(); Self::from_ini(&content).unwrap_or_else(|e| { @@ -49,18 +49,19 @@ impl Config { Config::default() } } + pub fn to_ini(&self) -> Result<String, config::ConfigError> { let mut lines = vec!["[global]".to_string()]; lines.push(format!("ignore_speed = {}", self.global.ignore_speed)); lines.push(format!("strict_gpg = {}", self.global.strict_gpg)); - lines.push("".to_string()); + lines.push(String::new()); for (name, repo) in &self.repositories { lines.push(format!("[repositories.{}]", name)); lines.push(format!("url = \"{}\"", repo.url)); if let Some(m) = &repo.mirror { lines.push(format!("mirror = \"{}\"", m)); } - lines.push("".to_string()); + lines.push(String::new()); } Ok(lines.join("\n")) } @@ -73,16 +74,16 @@ impl Config { } pub fn create_default_config(path: &Path) -> std::io::Result<()> { - let ini = r#"[global] -ignore_speed = false -strict_gpg = false - -[repositories.rorkos] -url = "https: -mirror = "https: -"#; + let ini = concat!( + "[global]\n", + "ignore_speed = false\n", + "strict_gpg = false\n", + "\n", + "[repositories.rorkos]\n", + "url = \"https://github.com/RorkOS/RorkOS_package\"\n", + "mirror = \"https://github.com/rork-os/RorkOS_package\"\n", + ); fs::create_dir_all(path.parent().unwrap())?; fs::write(path, ini) } } - diff --git a/src/install.rs b/src/install.rs index 2785180..b2f0ad5 100644 --- a/src/install.rs +++ b/src/install.rs @@ -10,6 +10,7 @@ use chrono::Local; use std::collections::HashMap; use std::os::unix::fs::symlink; use crate::config; +use crate::progress::{Spinner, format_bytes}; const REPO_ROOT: &str = "/var/ror/packages"; @@ -58,7 +59,7 @@ pub struct BinaryPackage { #[serde(rename = "type", default)] pub pkg_type: Option<String>, #[serde(default)] - pub url: String, + pub url: String, #[serde(default)] pub sha256: String, #[serde(default = "default_install_prefix")] @@ -86,7 +87,7 @@ pub struct InstalledDB { } impl InstalledDB { - pub const PATH: &'static str = "/var/ror/installed.json"; + pub const PATH: &'static str = "/etc/ror/installed.json"; pub fn load() -> Self { if Path::new(Self::PATH).exists() { @@ -116,6 +117,33 @@ impl InstalledDB { } } +fn sort_mirrors_by_speed(mirrors: &[String]) -> Vec<String> { + use std::time::Instant; + let client = match Client::builder() + .timeout(std::time::Duration::from_secs(5)) + .build() + { + Ok(c) => c, + Err(_) => return mirrors.to_vec(), + }; + + let mut timed: Vec<(u128, String)> = mirrors + .iter() + .map(|url| { + let start = Instant::now(); + let ok = client + .head(url) + .send() + .map(|r| r.status().is_success()) + .unwrap_or(false); + let elapsed = start.elapsed().as_millis(); + if ok { (elapsed, url.clone()) } else { (u128::MAX, url.clone()) } + }) + .collect(); + + timed.sort_by_key(|(t, _)| *t); + timed.into_iter().map(|(_, url)| url).collect() +} pub fn extract_deb(archive_path: &Path, dest_root: &Path) -> Result<Vec<String>, String> { let file = fs::File::open(archive_path).map_err(|e| e.to_string())?; @@ -125,7 +153,7 @@ pub fn extract_deb(archive_path: &Path, dest_root: &Path) -> Result<Vec<String>, while let Some(entry_result) = archive.next_entry() { let entry = entry_result.map_err(|e| format!("Failed to read ar entry: {}", e))?; let identifier = std::str::from_utf8(entry.header().identifier()).unwrap_or(""); - + if identifier.contains("data.tar") { let reader: Box<dyn std::io::Read> = if identifier.ends_with(".xz") { Box::new(xz2::read::XzDecoder::new(entry)) @@ -135,11 +163,11 @@ pub fn extract_deb(archive_path: &Path, dest_root: &Path) -> Result<Vec<String>, let mut tar_archive = tar::Archive::new(reader); let entries = tar_archive.entries().map_err(|e: std::io::Error| e.to_string())?; - + for file_result in entries { let mut f = file_result.map_err(|e: std::io::Error| e.to_string())?; let path = f.path().map_err(|e: std::io::Error| e.to_string())?.to_path_buf(); - + f.unpack_in(dest_root).map_err(|e: std::io::Error| e.to_string())?; installed_files.push(path.to_string_lossy().to_string()); } @@ -157,18 +185,22 @@ pub fn select_binary_for_arch<'a>(pkg: &'a Package, arch: &str) -> Result<&'a Bi }, other => other, }; - pkg.binaries.iter().find(|b| b.arch == target_arch || b.arch == "all" || b.arch == "x86_64") - .ok_or_else(|| format!("No binary package for architecture {}", arch)) + pkg.binaries + .iter() + .find(|b| b.arch == target_arch || b.arch == "all" || b.arch == "x86_64") + .ok_or_else(|| format!("No binary package for architecture {}", arch)) } pub fn find_package_file(pkg_name: &str) -> Option<PathBuf> { let repo = Path::new(REPO_ROOT); let read_dir = fs::read_dir(repo).ok()?; - + for entry in read_dir.flatten() { let cat_path = entry.path(); - if !cat_path.is_dir() { continue; } - + if !cat_path.is_dir() { + continue; + } + let pkg_path = cat_path.join(pkg_name).join(format!("{}.yaml", pkg_name)); if pkg_path.exists() && pkg_path.is_file() { return Some(pkg_path); @@ -195,14 +227,16 @@ pub fn install_package(pkg_name: &str, cfg: &config::Config) { } } - pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Result<InstalledPackage, String> { + let mut spinner = Spinner::new(&format!("Resolving {}", pkg_name)); + spinner.tick(&format!("Resolving {}", pkg_name)); + let pkg_path = find_package_file(pkg_name) .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; - + let content = fs::read_to_string(&pkg_path) .map_err(|e| format!("Failed to read package file: {}", e))?; - + let pkg: Package = serde_yaml::from_str(&content) .map_err(|e| format!("YAML structure error: {}", e))?; @@ -212,59 +246,79 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu let binary = select_binary_for_arch(&pkg, "native")?; let db = InstalledDB::load(); - + for conflict in &pkg.conflicts { if db.is_installed(conflict) { - return Err(format!("Package '{}' conflicts with installed package '{}'", pkg_name, conflict)); + return Err(format!( + "Package '{}' conflicts with installed package '{}'", + pkg_name, conflict + )); } } - let urls_to_try: Vec<String> = if !binary.url.is_empty() { + let mut urls_to_try: Vec<String> = if !binary.url.is_empty() { vec![binary.url.clone()] } else if !binary.mirrors.is_empty() { - binary.mirrors.iter().map(|m| m.replace("{filename}", &binary.filename)).collect() + binary + .mirrors + .iter() + .map(|m| m.replace("{filename}", &binary.filename)) + .collect() } else { return Err(format!("No URL or mirrors provided for package {}", pkg_name)); }; + if !cfg.global.ignore_speed && urls_to_try.len() > 1 { + 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])); + } + let mut last_err = None; let mut all_installed_files = Vec::new(); let mut downloaded = false; for url in urls_to_try { - println!("{} Trying source: {}", ">>>".yellow(), url); + spinner.tick(&format!("Downloading {} ...", url.split('/').last().unwrap_or(&url))); let archive_path = match download_and_verify(&url, &binary.sha256, cfg) { Ok(p) => p, Err(e) => { last_err = Some(e); - continue; + continue; } }; + spinner.finish(&format!("Downloaded {}", pkg_name)); + let work_dir = Path::new("/tmp/ror-install").join(&pkg.name); let _ = fs::remove_dir_all(&work_dir); 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"); + let mut sp2 = Spinner::new(&format!("Extracting {}", pkg_name)); + sp2.tick(&format!("Extracting {}...", pkg_name)); + if pkg_type == "deb" { - println!("{} Processing external .deb for {}", ">>>".green(), pkg.name); let mut files = extract_deb(&archive_path, Path::new("/"))?; all_installed_files.append(&mut files); } else { let files = extract_native(&archive_path, &work_dir) .map_err(|e| format!("Extraction failed: {}", e))?; let file_list = if binary.files.is_empty() { files } else { binary.files.clone() }; + sp2.tick(&format!("Installing files for {}...", pkg_name)); let mut installed = install_files(&work_dir, &binary.install_prefix, &file_list) .map_err(|e| format!("Failed to install files: {}", e))?; all_installed_files.append(&mut installed); } + sp2.finish(&format!("Installed {} files", all_installed_files.len())); + let _ = fs::remove_dir_all(&work_dir); let _ = fs::remove_file(&archive_path); downloaded = true; - break; + break; } if !downloaded { @@ -272,7 +326,10 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu } if !pkg.install_steps.is_empty() { + 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"); } Ok(InstalledPackage { @@ -284,28 +341,33 @@ 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<PathBuf, String> { - +pub fn download_and_verify(url: &str, expected_sha: &str, _cfg: &config::Config) -> Result<PathBuf, String> { let client = Client::builder() .connect_timeout(std::time::Duration::from_secs(30)) .build() .map_err(|e| format!("Failed to build HTTP client: {}", e))?; - let response = client.get(url).send() + let response = client + .get(url) + .send() .map_err(|e| format!("Download failed: {}", e))?; if !response.status().is_success() { return Err(format!("HTTP error: {}", response.status())); } + let total_size = response + .headers() + .get(reqwest::header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|s| s.parse::<u64>().ok()); + let tmp_dir = Path::new("/tmp/ror-download"); fs::create_dir_all(tmp_dir).map_err(|e| format!("Failed to create tmp dir: {}", e))?; let file_name = url.split('/').last().unwrap_or("archive.tmp"); let file_path = tmp_dir.join(file_name); - { use std::io::Write; let mut file = fs::File::create(&file_path) @@ -313,76 +375,63 @@ pub fn download_and_verify(url: &str, expected_sha: &str, cfg: &config::Config) let mut hasher = Sha256::new(); let mut reader = response; let mut buf = [0u8; 65536]; + let mut downloaded: u64 = 0; + loop { use std::io::Read; - let n = reader.read(&mut buf) + let n = reader + .read(&mut buf) .map_err(|e| format!("Failed to read response body: {}", e))?; - if n == 0 { break; } + if n == 0 { + break; + } hasher.update(&buf[..n]); file.write_all(&buf[..n]) .map_err(|e| format!("Failed to write to temp file: {}", e))?; + downloaded += n as u64; + + match total_size { + 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) + ); + eprint!( + "\r\x1b[K\x1b[36m[{}]\x1b[0m {} / {}", + bar, + format_bytes(downloaded), + format_bytes(total) + ); + } + _ => { + eprint!("\r\x1b[K{} downloaded", format_bytes(downloaded)); + } + } + use std::io::stderr; + stderr().flush().ok(); } + + eprintln!("\r\x1b[K\x1b[32m✓\x1b[0m Downloaded {}", format_bytes(downloaded)); + if !expected_sha.is_empty() { let hash = format!("{:x}", hasher.finalize()); if hash != expected_sha { let _ = fs::remove_file(&file_path); - return Err(format!("SHA256 mismatch: expected {}, got {}", expected_sha, hash)); + return Err(format!( + "SHA256 mismatch: expected {}, got {}", + expected_sha, hash + )); } } } - if let Err(e) = verify_gpg_signature(&file_path, url, cfg.global.strict_gpg) { - if cfg.global.strict_gpg { - let _ = fs::remove_file(&file_path); - return Err(format!("GPG ERROR: {}", e)); - } else { - eprintln!("{} GPG warning: {}", "[ror]".yellow(), e); - } - } - Ok(file_path) } -fn verify_gpg_signature(file_path: &Path, original_url: &str, _strict_mode: bool) -> Result<(), String> { - let sig_url = format!("{}.sig", original_url); - let client = Client::builder().timeout(std::time::Duration::from_secs(10)).build() - .map_err(|e| format!("Failed to build HTTP client: {}", e))?; - - let response = match client.get(&sig_url).send() { - Ok(r) => r, - Err(_) => return Err("Failed to reach server for .sig file".to_string()) - }; - - if !response.status().is_success() { - return Err(format!("Signature file not found on server (HTTP {})", response.status())); - } - - let sig_bytes = response.bytes() - .map_err(|e| format!("Failed to download signature: {}", e))?.to_vec(); - - let sig_path = file_path.with_extension("sig"); - fs::write(&sig_path, &sig_bytes).map_err(|e| format!("Failed to save signature: {}", e))?; - - println!("{} Verifying GPG signature...", ">>>".cyan()); - let status = Command::new("gpg") - .arg("--verify") - .arg(&sig_path) - .arg(file_path) - .status() - .map_err(|e| format!("Failed to execute 'gpg' (is it installed?): {}", e))?; - - let _ = fs::remove_file(&sig_path); - - if status.success() { - Ok(()) - } else { - Err("GPG Signature mismatch! File might be tampered with.".to_string()) - } -} - pub fn extract_native(archive_path: &Path, target_dir: &Path) -> Result<Vec<String>, String> { - let status = Command::new("tar") .arg("-xf") .arg(archive_path) @@ -404,6 +453,7 @@ pub fn extract_native(archive_path: &Path, target_dir: &Path) -> Result<Vec<Stri } Ok(files) } + fn install_files(source_dir: &Path, prefix: &str, files: &[String]) -> Result<Vec<String>, String> { let prefix_path = Path::new(prefix); let mut installed = Vec::new(); @@ -411,8 +461,7 @@ fn install_files(source_dir: &Path, prefix: &str, files: &[String]) -> Result<Ve for rel_path in files { let src = source_dir.join(rel_path); let dst = prefix_path.join(rel_path); - - + let meta = fs::symlink_metadata(&src) .map_err(|_| format!("File {} not found in package", rel_path))?; @@ -420,12 +469,11 @@ fn install_files(source_dir: &Path, prefix: &str, files: &[String]) -> Result<Ve fs::create_dir_all(parent) .map_err(|e| format!("Failed to create dir {}: {}", parent.display(), e))?; } - - + if meta.is_symlink() { let target = fs::read_link(&src) .map_err(|e| format!("Failed to read link {}: {}", src.display(), e))?; - let _ = fs::remove_file(&dst); + let _ = fs::remove_file(&dst); symlink(&target, &dst) .map_err(|e| format!("Failed to create symlink {}: {}", dst.display(), e))?; } else { @@ -442,7 +490,7 @@ pub fn install_files_with_root(source_dir: &Path, root: &Path, files: &[String]) for rel_path in files { let src = source_dir.join(rel_path); let dst = root.join(rel_path); - + let meta = fs::symlink_metadata(&src) .map_err(|_| format!("File {} not found in package", rel_path))?; @@ -450,8 +498,7 @@ pub fn install_files_with_root(source_dir: &Path, root: &Path, files: &[String]) fs::create_dir_all(parent) .map_err(|e| format!("Failed to create dir {}: {}", parent.display(), e))?; } - - + if meta.is_symlink() { let target = fs::read_link(&src) .map_err(|e| format!("Failed to read link {}: {}", src.display(), e))?; @@ -488,7 +535,8 @@ pub fn get_package_info(pkg_name: &str) -> Option<(String, String)> { let pkg_path = find_package_file(pkg_name)?; let content = fs::read_to_string(pkg_path).ok()?; let name = pkg_name.to_string(); - let version = content.lines() + let version = content + .lines() .find(|l| l.starts_with("version:")) .and_then(|l| l.split(':').nth(1)) .map(|s| s.trim().trim_matches('"').to_string()) diff --git a/src/main.rs b/src/main.rs index 6df2cfc..99b27c8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,65 +12,66 @@ mod delete; mod listinstalled; mod update; mod rootfs; -mod parallel; +mod parallel; mod debug; mod search; mod repo; +mod progress; #[derive(Parser, Debug)] #[command(author, about, arg_required_else_help = true)] struct Args { #[arg(long = "search", value_name = "QUERY")] search: Option<String>, - + #[arg(short = 's', long = "sync")] sync: bool, - + #[arg(short = 'd', long = "delete", value_name = "PACKAGE")] delete: Option<String>, - + #[arg(short = 'l', long = "list-installed")] listinstalled: bool, - + #[arg(long = "info", value_name = "PACKAGE")] info: Option<String>, - + #[arg(short = 'v', long = "version")] version: bool, - + #[arg(short = 'g', long = "gen-config")] gen_config: bool, - + #[arg(short = 'i', long = "install", value_name = "PACKAGE_OR_GROUP", num_args = 1..)] install: Vec<String>, - + #[arg(long = "update", value_name = "PACKAGE")] update: Option<String>, - + #[arg(long = "dry-run")] dry_run: bool, - + #[arg(short = 'u', long = "upgrade")] upgrade: bool, - + #[arg(long = "repo-add", value_names = ["NAME", "URL"])] repo_add: Option<Vec<String>>, - + #[arg(long = "repo-remove", value_name = "NAME")] repo_remove: Option<String>, - + #[arg(long = "repo-list")] repo_list: bool, - + #[arg(long = "build-rootfs")] build_rootfs: bool, - + #[arg(long = "rootfs-group", value_name = "GROUP")] rootfs_group: Option<String>, - + #[arg(long = "rootfs-target", value_name = "TARGET")] rootfs_target: Option<PathBuf>, - + #[arg(long = "rootfs-arch", default_value = "native")] rootfs_arch: String, } @@ -100,7 +101,6 @@ fn main() { } let cfg = Arc::new(config::Config::load()); - if let Some(pkg) = args.info { info::print_package_info(&pkg); @@ -134,8 +134,8 @@ fn main() { return; } if let Some(query) = args.search { - search::search_packages(&query); - return; + search::search_packages(&query); + return; } if !args.install.is_empty() { if args.install[0].starts_with('@') { @@ -155,7 +155,6 @@ fn main() { } return; } - if args.upgrade { if args.dry_run { let upgradable = update::list_upgradable(); @@ -173,44 +172,28 @@ fn main() { return; } if args.repo_list { - repo::list_repositories(); - return; + repo::list_repositories(); + return; } - if args.build_rootfs { - let arch = if args.rootfs_arch == "native" { - "native" - } else { - &args.rootfs_arch - }; - if let (Some(group), Some(target)) = (args.rootfs_group, args.rootfs_target) { - if let Err(e) = rootfs::build_rootfs(&group, &target, &cfg, arch, true) { + if let Some(repo_args) = args.repo_remove { + if let Err(e) = repo::remove_repository(&repo_args) { eprintln!("{} {}", "[ror]".red().bold(), e); - } - } else { - eprintln!("{} --build-rootfs requires --rootfs-group and --rootfs-target", "[ror]".red().bold()); } return; } - if let Some(args) = args.repo_remove { - if let Err(e) = repo::remove_repository(&args) { - eprintln!("{} {}", "[ror]".red().bold(), e); - } - return; - } - - if let Some(args) = args.repo_add { - if args.len() < 2 { - eprintln!("{} Usage: --repo-add <name> <url> [mirror]", "[ror]".red().bold()); + if let Some(repo_args) = args.repo_add { + if repo_args.len() < 2 { + eprintln!("{} Usage: --repo-add <name> <url> [mirror]", "[ror]".red().bold()); + return; + } + let name = &repo_args[0]; + let url = &repo_args[1]; + let mirror = if repo_args.len() > 2 { Some(repo_args[2].as_str()) } else { None }; + if let Err(e) = repo::add_repository(name, url, mirror) { + eprintln!("{} {}", "[ror]".red().bold(), e); + } return; } - let name = &args[0]; - let url = &args[1]; - let mirror = if args.len() > 2 { Some(args[2].as_str()) } else { None }; - if let Err(e) = repo::add_repository(name, url, mirror) { - eprintln!("{} {}", "[ror]".red().bold(), e); - } - return; - } if let Some(pkg) = args.update { update::update_package(&pkg, &cfg, args.dry_run); return; diff --git a/src/parallel.rs b/src/parallel.rs index ff11e79..60f3b5e 100644 --- a/src/parallel.rs +++ b/src/parallel.rs @@ -4,7 +4,7 @@ use std::thread; use crate::config::Config; use crate::install::{self, Dependency, InstalledDB, load_package}; use colored::Colorize; -use crate::debug; +use crate::debug; type Result<T> = std::result::Result<T, String>; @@ -66,10 +66,19 @@ impl DependencyGraph { } } - if in_degree.values().any(|&d| d > 0) { - eprintln!("{} Circular dependency detected!", "[ror]".red().bold()); - debug!("compute_levels: circular dependency detected"); + let cyclic: Vec<_> = in_degree.iter() + .filter(|(_, &d)| d > 0) + .map(|(name, _)| name.as_str()) + .collect(); + + if !cyclic.is_empty() { + eprintln!( + "{} Warning: cycle detected among packages, they will be installed in arbitrary order", + "[ror]".yellow().bold() + ); + debug!("compute_levels: circular dependency among: {:?}", cyclic); } + debug!("compute_levels: levels count = {}", levels.len()); levels } @@ -239,6 +248,7 @@ fn install_single_package(pkg_name: &str, cfg: Arc<Config>, db_mutex: &Mutex<Ins println!("{} Package registered in database", "[ror]".green()); Ok(()) } + pub fn install_packages_parallel(packages: &[String], cfg: Arc<Config>) -> Result<()> { debug!("install_packages_parallel: called with {:?}", packages); let installed_db = InstalledDB::load(); @@ -253,20 +263,38 @@ pub fn install_packages_parallel(packages: &[String], cfg: Arc<Config>) -> Resul let graph = build_graph(&required, &installed_db)?; let mut levels = graph.compute_levels(); - + if levels.is_empty() && !required.is_empty() { debug!("install_packages_parallel: no dependencies, creating single level"); levels.push(required.iter().cloned().collect()); } - + debug!("install_packages_parallel: levels: {:?}", levels); + let total_pkgs: usize = levels.iter().map(|l| l.len()).sum(); + let mut installed_count = 0usize; + + println!( + "{} Installing {} package(s) across {} level(s)", + "[ror]".blue().bold(), + total_pkgs, + levels.len() + ); + let db_mutex = Arc::new(Mutex::new(InstalledDB::load())); for (level_idx, level_pkgs) in levels.into_iter().enumerate() { - println!("{} Level {}: {} packages", ">>>".cyan(), level_idx, level_pkgs.len()); + println!( + "{} Level {}: {} package(s)", + ">>>".cyan(), + level_idx, + level_pkgs.len() + ); debug!("install_packages_parallel: starting level {} with {:?}", level_idx, level_pkgs); + + let level_total = level_pkgs.len(); let mut handles = Vec::new(); + for pkg in level_pkgs { let pkg_name = pkg.clone(); let cfg = Arc::clone(&cfg); @@ -274,13 +302,27 @@ pub fn install_packages_parallel(packages: &[String], cfg: Arc<Config>) -> Resul let handle = thread::spawn(move || { install_single_package(&pkg_name, cfg, &db_mutex) }); - handles.push(handle); + handles.push((pkg, handle)); } let mut errors = Vec::new(); - for handle in handles { + let mut level_done = 0usize; + + for (pkg_name, handle) in handles { match handle.join() { - Ok(Ok(())) => {}, + Ok(Ok(())) => { + installed_count += 1; + level_done += 1; + eprint!( + "\r\x1b[K\x1b[36m[{:>3}/{:<3}]\x1b[0m level {}, total {}/{} {}", + level_done, level_total, + level_idx, + installed_count, total_pkgs, + pkg_name + ); + use std::io::Write; + std::io::stderr().flush().ok(); + } Ok(Err(e)) => { debug!("install_packages_parallel: thread error: {}", e); errors.push(e); @@ -291,6 +333,7 @@ pub fn install_packages_parallel(packages: &[String], cfg: Arc<Config>) -> Resul } } } + eprintln!(); if !errors.is_empty() { eprintln!("{} Errors during level {}: {:?}", "[ror]".red().bold(), level_idx, errors); diff --git a/src/progress.rs b/src/progress.rs new file mode 100644 index 0000000..f6f2227 --- /dev/null +++ b/src/progress.rs @@ -0,0 +1,94 @@ +use std::io::{self, Write}; + +pub struct ProgressBar { + total: usize, + current: usize, + message: String, + width: usize, +} + +impl ProgressBar { + pub fn new(total: usize, message: &str) -> Self { + Self { + total, + current: 0, + message: message.to_string(), + width: 38, + } + } + + + pub fn inc(&mut self, msg: &str) { + self.current += 1; + self.message = msg.to_string(); + self.render(); + } + + fn render(&self) { + let filled = if self.total == 0 { + 0 + } else { + self.current * self.width / self.total + }; + let arrow = if filled < self.width { ">" } else { "=" }; + let bar = format!( + "{}{}{}", + "=".repeat(filled.saturating_sub(1)), + arrow, + " ".repeat(self.width.saturating_sub(filled)) + ); + eprint!( + "\r\x1b[K\x1b[36m[{}]\x1b[0m \x1b[32m{}/{}\x1b[0m {}", + bar, + self.current, + self.total, + self.message + ); + io::stderr().flush().ok(); + } + + pub fn finish(&self, msg: &str) { + let bar = "=".repeat(self.width); + eprintln!( + "\r\x1b[K\x1b[36m[{}]\x1b[0m \x1b[32m{}/{}\x1b[0m {}", + bar, self.total, self.total, msg + ); + } +} + +pub struct Spinner { + frames: &'static [&'static str], + idx: usize, + message: String, +} + +impl Spinner { + pub fn new(message: &str) -> Self { + Self { + frames: &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"], + idx: 0, + message: message.to_string(), + } + } + + pub fn tick(&mut self, msg: &str) { + self.message = msg.to_string(); + eprint!("\r\x1b[K\x1b[36m{}\x1b[0m {}", self.frames[self.idx], self.message); + io::stderr().flush().ok(); + self.idx = (self.idx + 1) % self.frames.len(); + } + + pub fn finish(&self, msg: &str) { + eprintln!("\r\x1b[K\x1b[32m✓\x1b[0m {}", msg); + } +} + +pub fn format_bytes(bytes: u64) -> String { + if bytes < 1024 { + format!("{} B", bytes) + } else if bytes < 1024 * 1024 { + format!("{:.1} KB", bytes as f64 / 1024.0) + } else { + format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0)) + } +} diff --git a/src/rootfs.rs b/src/rootfs.rs index 659032e..8b89efe 100644 --- a/src/rootfs.rs +++ b/src/rootfs.rs @@ -2,20 +2,49 @@ use std::fs; use std::path::Path; use std::collections::HashSet; use std::process::Command; +use std::os::unix::fs::symlink; use colored::Colorize; use crate::config; use crate::group::Group; +use crate::progress::ProgressBar; use crate::install::{ Dependency, Package, load_package, download_and_verify, extract_native, install_files_with_root, select_binary_for_arch, }; +fn setup_usr_merge(target_dir: &Path) -> Result<(), String> { + for dir in &["bin", "lib", "lib64", "sbin"] { + let path = target_dir.join(dir); + if path.symlink_metadata().is_ok() { + if path.is_dir() && !path.is_symlink() { + fs::remove_dir_all(&path) + .map_err(|e| format!("Failed to remove directory {}: {}", dir, e))?; + } else { + fs::remove_file(&path) + .map_err(|e| format!("Failed to remove {}: {}", dir, e))?; + } + } + } + for dir in &["usr/bin", "usr/lib", "usr/lib64", "usr/sbin"] { + fs::create_dir_all(target_dir.join(dir)) + .map_err(|e| format!("Failed to create {}: {}", dir, e))?; + } + for (link, target) in &[ + ("bin", "usr/bin"), + ("lib", "usr/lib"), + ("lib64", "usr/lib64"), + ("sbin", "usr/sbin"), + ] { + symlink(target, target_dir.join(link)) + .map_err(|e| format!("Failed to create symlink {} -> {}: {}", link, target, e))?; + } + Ok(()) +} fn mount_virtual_fs(root_dir: &Path) -> Result<(), String> { - let mounts: &[(&str, &str, &str, bool)] = &[ ("/dev", "dev", "devtmpfs", true), ("/dev/pts", "dev/pts", "devpts", true), @@ -48,7 +77,6 @@ fn mount_virtual_fs(root_dir: &Path) -> Result<(), String> { Ok(()) } - fn umount_virtual_fs(root_dir: &Path) { for rel in &["dev/pts", "dev/shm", "dev", "proc", "sys"] { let target = root_dir.join(rel); @@ -58,49 +86,71 @@ fn umount_virtual_fs(root_dir: &Path) { } } +const SHELL_CANDIDATES: &[(&str, Option<&str>)] = &[ + ("/bin/sh", None), + ("/usr/bin/sh", None), + ("/bin/dash", None), + ("/usr/bin/dash", None), + ("/bin/bash", None), + ("/usr/bin/bash", None), + ("/bin/busybox", Some("sh")), + ("/usr/bin/busybox", Some("sh")), + ("/bin/ash", None), + ("/usr/bin/ash", None), +]; + +fn find_working_shell(root_dir: &Path) -> Option<(&'static str, Option<&'static str>)> { + for &(shell_path, subcmd) in SHELL_CANDIDATES { + if !root_dir.join(shell_path.trim_start_matches('/')).exists() { + continue; + } + let mut cmd = Command::new("chroot"); + cmd.arg(root_dir).arg(shell_path); + if let Some(sub) = subcmd { + cmd.arg(sub); + } + cmd.arg("-c").arg("exit 0"); - - - - -fn find_shell_in_rootfs(root_dir: &Path) -> Option<(&'static str, Option<&'static str>)> { - let candidates: &[(&str, Option<&str>)] = &[ - ("/bin/sh", None), - ("/usr/bin/sh", None), - ("/bin/bash", None), - ("/usr/bin/bash", None), - ("/bin/busybox", Some("sh")), - ("/usr/bin/busybox", Some("sh")), - ]; - candidates.iter() - .find(|(p, _)| root_dir.join(p.trim_start_matches('/')).exists()) - .copied() + match cmd.output() { + Ok(out) if out.status.success() => { + return Some((shell_path, subcmd)); + } + Ok(out) => { + let stderr = String::from_utf8_lossy(&out.stderr); + eprintln!( + "{} Shell {} failed in chroot ({}), trying next...", + "[ror]".yellow(), + shell_path, + stderr.lines().next().unwrap_or("unknown error").trim() + ); + } + Err(e) => { + eprintln!("{} Cannot test shell {}: {}, trying next...", "[ror]".yellow(), shell_path, e); + } + } + } + None } - - - - -fn run_install_steps_in_chroot(pkg_name: &str, steps: &str, root_dir: &Path) -> Result<(), String> { - let (shell, subcmd) = find_shell_in_rootfs(root_dir) - .ok_or_else(|| format!( - "No shell found in rootfs for '{}'. Checked: /bin/sh, /bin/bash, /bin/busybox", - pkg_name - ))?; - - println!("{} Using shell: {}{}", ">>>".cyan(), shell, - subcmd.map(|s| format!(" {}", s)).unwrap_or_default()); - +fn run_install_steps_in_chroot( + pkg_name: &str, + steps: &str, + root_dir: &Path, + shell: &str, + subcmd: Option<&str>, +) -> Result<(), String> { let script_rel = "/.ror-install-steps.sh"; let script_host = root_dir.join(script_rel.trim_start_matches('/')); - + fs::write(&script_host, format!("#!/bin/sh\nset -e\n{}", steps)) .map_err(|e| format!("Failed to write install script: {}", e))?; let mut cmd = Command::new("chroot"); cmd.arg(root_dir).arg(shell); - if let Some(sub) = subcmd { cmd.arg(sub); } + if let Some(sub) = subcmd { + cmd.arg(sub); + } cmd.arg(script_rel); let status = cmd.status() @@ -112,28 +162,25 @@ fn run_install_steps_in_chroot(pkg_name: &str, steps: &str, root_dir: &Path) -> Ok(()) } else { Err(format!( - "install_steps for '{}' failed with exit code {:?}", + "install_steps for \'{}\' failed with exit code {:?}", pkg_name, status.code() )) } } - - - - fn process_dependencies_chroot( pkg: &Package, cfg: &config::Config, root_dir: &Path, installing: &mut HashSet<String>, target_arch: &str, + progress: &mut ProgressBar, ) -> Result<(), String> { for dep in &pkg.depends { match dep { Dependency::Single(name) => { if !installing.contains(name) { - install_package_in_chroot(name, cfg, root_dir, installing, target_arch)?; + install_package_in_chroot(name, cfg, root_dir, installing, target_arch, progress)?; } } Dependency::Any(alternatives) => { @@ -142,7 +189,7 @@ fn process_dependencies_chroot( } let chosen = alternatives.first() .ok_or_else(|| format!("Empty alternative list in package {}", pkg.name))?; - install_package_in_chroot(chosen, cfg, root_dir, installing, target_arch)?; + install_package_in_chroot(chosen, cfg, root_dir, installing, target_arch, progress)?; } } } @@ -155,9 +202,14 @@ pub fn install_package_in_chroot( root_dir: &Path, installing: &mut HashSet<String>, target_arch: &str, + progress: &mut ProgressBar, ) -> Result<(), String> { if installing.contains(pkg_name) { - eprintln!("{} Circular dependency detected: {}", "[ror]".red().bold(), pkg_name); + println!( + "{} {} already queued, dependencies are already installed", + "[ror]".green(), + pkg_name.green() + ); return Ok(()); } installing.insert(pkg_name.to_string()); @@ -165,15 +217,16 @@ pub fn install_package_in_chroot( let pkg = load_package(pkg_name) .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; - process_dependencies_chroot(&pkg, cfg, root_dir, installing, target_arch)?; + process_dependencies_chroot(&pkg, cfg, root_dir, installing, target_arch, progress)?; let binary = select_binary_for_arch(&pkg, target_arch) .map_err(|e| format!("Failed to select binary for {}: {}", pkg_name, e))?; + progress.inc(&format!("Installing {}", pkg_name)); + let mut last_err = None; for mirror in &binary.mirrors { let url = mirror.replace("{filename}", &binary.filename); - println!("{} Trying mirror: {}", ">>>".yellow(), url); let archive_path = match download_and_verify(&url, &binary.sha256, cfg) { Ok(p) => p, @@ -205,10 +258,6 @@ pub fn install_package_in_chroot( Err(last_err.unwrap_or_else(|| "All mirrors failed".into())) } - - - - fn run_all_install_steps( group_order: &[String], all_installed: &HashSet<String>, @@ -216,34 +265,47 @@ fn run_all_install_steps( ) -> Result<(), String> { let mut done: HashSet<String> = HashSet::new(); - let mut queue: Vec<&str> = group_order.iter().map(|s| s.as_str()).collect(); - + let mut extras: Vec<String> = all_installed.iter() .filter(|p| !group_order.contains(p)) .cloned() .collect(); - extras.sort(); + extras.sort(); for e in &extras { queue.push(e.as_str()); } + let steps_pkgs: Vec<String> = queue.iter() + .filter(|&&pkg_name| { + all_installed.contains(pkg_name) && + load_package(pkg_name).map(|p| !p.install_steps.trim().is_empty()).unwrap_or(false) + }) + .map(|s| s.to_string()) + .collect(); + + let total_steps = steps_pkgs.len(); + let mut pb = ProgressBar::new(total_steps.max(1), "Running install steps..."); + + let (shell, subcmd) = find_working_shell(target_dir) + .ok_or_else(|| "No working shell found in rootfs. Tried: sh, dash, bash, busybox, ash".to_string())?; + + println!("{} Using shell: {}{}", ">>>".cyan(), shell, + subcmd.map(|s| format!(" {}", s)).unwrap_or_default()); + for pkg_name in queue { if done.contains(pkg_name) || !all_installed.contains(pkg_name) { continue; } done.insert(pkg_name.to_string()); if let Some(pkg) = load_package(pkg_name) { if !pkg.install_steps.trim().is_empty() { - println!("{} install_steps: {}", ">>>".cyan(), pkg_name); - run_install_steps_in_chroot(pkg_name, &pkg.install_steps, target_dir)?; + pb.inc(&format!("install_steps: {}", pkg_name)); + run_install_steps_in_chroot(pkg_name, &pkg.install_steps, target_dir, shell, subcmd)?; } } } + pb.finish("All install steps done"); Ok(()) } - - - - pub fn build_rootfs( group_name: &str, target_dir: &Path, @@ -274,12 +336,20 @@ pub fn build_rootfs( println!("{} {}", "Description:".yellow(), desc); } - + println!("\n{} Phase 0: UsrMerge...", ">>>".cyan().bold()); + setup_usr_merge(target_dir)?; + println!("{} UsrMerge done: bin/lib/lib64/sbin are now symlinks into usr/", ">>>".green()); + println!("\n{} Phase 1: installing files...", ">>>".cyan().bold()); + + let estimated_total = group.packages.len() * 3; + let mut pb = ProgressBar::new(estimated_total.max(1), "Starting..."); + let mut installing: HashSet<String> = HashSet::new(); for pkg in &group.packages { - install_package_in_chroot(pkg, cfg, target_dir, &mut installing, target_arch)?; + install_package_in_chroot(pkg, cfg, target_dir, &mut installing, target_arch, &mut pb)?; } + pb.finish(&format!("Phase 1 complete: {} packages installed", installing.len())); println!("{} Phase 1 complete: {} packages.", ">>>".green(), installing.len()); if run_ldconfig { diff --git a/src/update.rs b/src/update.rs index f5c2690..1d682c0 100644 --- a/src/update.rs +++ b/src/update.rs @@ -2,16 +2,14 @@ use colored::Colorize; use crate::install::{self, InstalledDB, get_package_info}; use crate::delete; use crate::config; +use crate::progress::ProgressBar; use std::collections::HashSet; use semver::Version; fn is_newer(current: &str, available: &str) -> bool { match (Version::parse(current), Version::parse(available)) { (Ok(cur), Ok(ava)) => ava > cur, - _ => { - - current != available && available > current - } + _ => current != available && available > current, } } @@ -59,24 +57,41 @@ pub fn upgrade_all(cfg: &config::Config, dry_run: bool) { return; } + let total = installed.len(); + let mut pb = ProgressBar::new(total, "Checking for upgrades..."); + let mut updated = HashSet::new(); - let mut failed = Vec::new(); + let failed: Vec<String> = Vec::new(); + let mut skipped = 0usize; for pkg in &installed { if updated.contains(pkg) { + pb.inc(&format!("Skipping {} (already processed)", pkg)); + skipped += 1; continue; } + + pb.inc(&format!("Checking {}...", pkg)); + if update_package(pkg, cfg, dry_run) { updated.insert(pkg.clone()); } else { - failed.push(pkg.clone()); + skipped += 1; } } if dry_run { + pb.finish(&format!("DRY RUN: {} packages would be updated, {} already up-to-date", updated.len(), skipped)); println!("{} DRY RUN: {} packages would be updated.", ">>>".yellow(), updated.len()); } else { - println!("{} Upgrade completed. Updated: {}, failed: {}.", "[ror]".green().bold(), updated.len(), failed.len()); + pb.finish(&format!("Upgrade done: {} updated, {} failed, {} up-to-date", updated.len(), failed.len(), skipped)); + println!( + "{} Upgrade completed. Updated: {}, failed: {}, up-to-date: {}.", + "[ror]".green().bold(), + updated.len(), + failed.len(), + skipped + ); if !failed.is_empty() { println!("{} Failed packages: {:?}", "[ror]".red(), failed); } |