diff options
| author | rorka900 <rorka900@gmail.com> | 2026-03-19 11:44:27 +0000 |
|---|---|---|
| committer | rorka900 <rorka900@gmail.com> | 2026-03-19 11:44:27 +0000 |
| commit | 693f5143adb352b9fa1ee262b3537f6e429678f9 (patch) | |
| tree | b8c9bc10fc0901bcbfd3c1d5990b70d601a08828 /src | |
| download | ror-master.tar.gz ror-master.zip | |
Initial commitmaster
Diffstat (limited to 'src')
| -rw-r--r-- | src/.cnofig.rs.swp | bin | 0 -> 4096 bytes | |||
| -rw-r--r-- | src/.delete.rs.swo | bin | 0 -> 12288 bytes | |||
| -rw-r--r-- | src/.group.rs.swp | bin | 0 -> 12288 bytes | |||
| -rw-r--r-- | src/.groups.rs.swp | bin | 0 -> 4096 bytes | |||
| -rw-r--r-- | src/.install.rc.swp | bin | 0 -> 4096 bytes | |||
| -rw-r--r-- | src/.install.rs.swm | bin | 0 -> 16384 bytes | |||
| -rw-r--r-- | src/.install.rs.swn | bin | 0 -> 20480 bytes | |||
| -rw-r--r-- | src/.install.rs.swo | bin | 0 -> 20480 bytes | |||
| -rw-r--r-- | src/.rootfs.rs.swo | bin | 0 -> 16384 bytes | |||
| -rw-r--r-- | src/.rootfs.rs.swp | bin | 0 -> 16384 bytes | |||
| -rw-r--r-- | src/.rootfs.rsr.swp | bin | 0 -> 4096 bytes | |||
| -rw-r--r-- | src/.search-rs.swp | bin | 0 -> 4096 bytes | |||
| -rw-r--r-- | src/.search.rs.swl | bin | 0 -> 4096 bytes | |||
| -rw-r--r-- | src/.search.rs.swm | bin | 0 -> 4096 bytes | |||
| -rw-r--r-- | src/.search.rs.swn | bin | 0 -> 4096 bytes | |||
| -rw-r--r-- | src/.search.rs.swo | bin | 0 -> 4096 bytes | |||
| -rw-r--r-- | src/.sync.rs.swp | bin | 0 -> 12288 bytes | |||
| -rw-r--r-- | src/.sync.s.swp | bin | 0 -> 4096 bytes | |||
| -rw-r--r-- | src/config.rs | 88 | ||||
| -rw-r--r-- | src/debug.rs | 14 | ||||
| -rw-r--r-- | src/delete.rs | 102 | ||||
| -rw-r--r-- | src/group.rs | 66 | ||||
| -rw-r--r-- | src/info.rs | 119 | ||||
| -rw-r--r-- | src/install.rs | 503 | ||||
| -rw-r--r-- | src/listinstalled.rs | 31 | ||||
| -rw-r--r-- | src/main.rs | 218 | ||||
| -rw-r--r-- | src/parallel.rs | 305 | ||||
| -rw-r--r-- | src/repo.rs | 56 | ||||
| -rw-r--r-- | src/rootfs.rs | 307 | ||||
| -rw-r--r-- | src/search.rs | 92 | ||||
| -rw-r--r-- | src/sync.rs | 69 | ||||
| -rw-r--r-- | src/update.rs | 99 |
32 files changed, 2069 insertions, 0 deletions
diff --git a/src/.cnofig.rs.swp b/src/.cnofig.rs.swp Binary files differnew file mode 100644 index 0000000..3ec942c --- /dev/null +++ b/src/.cnofig.rs.swp diff --git a/src/.delete.rs.swo b/src/.delete.rs.swo Binary files differnew file mode 100644 index 0000000..16e6504 --- /dev/null +++ b/src/.delete.rs.swo diff --git a/src/.group.rs.swp b/src/.group.rs.swp Binary files differnew file mode 100644 index 0000000..362497a --- /dev/null +++ b/src/.group.rs.swp diff --git a/src/.groups.rs.swp b/src/.groups.rs.swp Binary files differnew file mode 100644 index 0000000..c38e177 --- /dev/null +++ b/src/.groups.rs.swp diff --git a/src/.install.rc.swp b/src/.install.rc.swp Binary files differnew file mode 100644 index 0000000..986a1da --- /dev/null +++ b/src/.install.rc.swp diff --git a/src/.install.rs.swm b/src/.install.rs.swm Binary files differnew file mode 100644 index 0000000..ca037b0 --- /dev/null +++ b/src/.install.rs.swm diff --git a/src/.install.rs.swn b/src/.install.rs.swn Binary files differnew file mode 100644 index 0000000..e716249 --- /dev/null +++ b/src/.install.rs.swn diff --git a/src/.install.rs.swo b/src/.install.rs.swo Binary files differnew file mode 100644 index 0000000..4b936c2 --- /dev/null +++ b/src/.install.rs.swo diff --git a/src/.rootfs.rs.swo b/src/.rootfs.rs.swo Binary files differnew file mode 100644 index 0000000..0662b03 --- /dev/null +++ b/src/.rootfs.rs.swo diff --git a/src/.rootfs.rs.swp b/src/.rootfs.rs.swp Binary files differnew file mode 100644 index 0000000..1d7dd77 --- /dev/null +++ b/src/.rootfs.rs.swp diff --git a/src/.rootfs.rsr.swp b/src/.rootfs.rsr.swp Binary files differnew file mode 100644 index 0000000..964405b --- /dev/null +++ b/src/.rootfs.rsr.swp diff --git a/src/.search-rs.swp b/src/.search-rs.swp Binary files differnew file mode 100644 index 0000000..1d1ceb6 --- /dev/null +++ b/src/.search-rs.swp diff --git a/src/.search.rs.swl b/src/.search.rs.swl Binary files differnew file mode 100644 index 0000000..0c25979 --- /dev/null +++ b/src/.search.rs.swl diff --git a/src/.search.rs.swm b/src/.search.rs.swm Binary files differnew file mode 100644 index 0000000..a807ccf --- /dev/null +++ b/src/.search.rs.swm diff --git a/src/.search.rs.swn b/src/.search.rs.swn Binary files differnew file mode 100644 index 0000000..2e478ac --- /dev/null +++ b/src/.search.rs.swn diff --git a/src/.search.rs.swo b/src/.search.rs.swo Binary files differnew file mode 100644 index 0000000..248d9f0 --- /dev/null +++ b/src/.search.rs.swo diff --git a/src/.sync.rs.swp b/src/.sync.rs.swp Binary files differnew file mode 100644 index 0000000..0f6869c --- /dev/null +++ b/src/.sync.rs.swp diff --git a/src/.sync.s.swp b/src/.sync.s.swp Binary files differnew file mode 100644 index 0000000..7a6f6aa --- /dev/null +++ b/src/.sync.s.swp diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..d79ad28 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,88 @@ +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::fs; +use std::path::Path; +use colored::Colorize; + +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct RepositoryConfig { + pub url: String, + #[serde(default)] + pub mirror: Option<String>, +} + +#[derive(Debug, Deserialize, Serialize, Default)] +pub struct GlobalConfig { + #[serde(default = "default_ignore_speed")] + pub ignore_speed: bool, + #[serde(default = "default_strict_gpg")] + pub strict_gpg: bool, + #[serde(default)] + pub allow_external_binaries: bool, +} + +fn default_ignore_speed() -> bool { false } +fn default_strict_gpg() -> bool { false } + +#[derive(Debug, Deserialize, Serialize, Default)] +pub struct Config { + #[serde(default)] + pub global: GlobalConfig, + #[serde(default)] + pub repositories: HashMap<String, RepositoryConfig>, +} + +impl Config { + pub fn load() -> Self { + let path = Path::new("/var/ror/ror.conf"); + if path.exists() { + let content = fs::read_to_string(path).unwrap_or_default(); + Self::from_ini(&content).unwrap_or_else(|e| { + eprintln!( + "{} Failed to parse config: {}, using defaults", + "[ror]".red().bold(), + e + ); + Config::default() + }) + } else { + 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()); + 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()); + } + Ok(lines.join("\n")) + } + + pub fn from_ini(ini: &str) -> Result<Self, config::ConfigError> { + let builder = config::Config::builder() + .add_source(config::File::from_str(ini, config::FileFormat::Ini)); + let cfg = builder.build()?; + cfg.try_deserialize() + } + + 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: +"#; + fs::create_dir_all(path.parent().unwrap())?; + fs::write(path, ini) + } +} + diff --git a/src/debug.rs b/src/debug.rs new file mode 100644 index 0000000..2f7da4e --- /dev/null +++ b/src/debug.rs @@ -0,0 +1,14 @@ +use std::env; + +pub fn debug(msg: &str) { + if env::var("ROR_DEBUG").unwrap_or_default() == "1" { + eprintln!("[DEBUG] {}", msg); + } +} + +#[macro_export] +macro_rules! debug { + ($($arg:tt)*) => { + $crate::debug::debug(&format!($($arg)*)); + }; +} diff --git a/src/delete.rs b/src/delete.rs new file mode 100644 index 0000000..c95d661 --- /dev/null +++ b/src/delete.rs @@ -0,0 +1,102 @@ +use std::fs; +use std::path::Path; +use colored::Colorize; +use std::process::Command; +use crate::install::{load_package, InstalledDB, Package, find_package_file}; + +fn has_role(pkg_name: &str, role: &str) -> bool { + if let Some(pkg) = load_package(pkg_name) { + return pkg.provides.contains(&role.to_string()); + } + false +} + +pub fn check_critical_removal(pkg_name: &str, db: &InstalledDB) -> Result<(), String> { + let pkg = load_package(pkg_name).ok_or("Package info not found in repository")?; + + if pkg.provides.contains(&"init-system".to_string()) { + let other_inits_count = db.packages.values() + .filter(|p| p.name != pkg_name && has_role(&p.name, "init-system")) + .count(); + + if other_inits_count == 0 { + return Err(format!( + "{} CRITICAL ERROR: '{}' is your last init-system! Removing it will break RorkOS. Install an alternative first.", + "[ror]".red().bold(), + pkg_name + )); + } + } + Ok(()) +} + +pub fn remove_package(pkg_name: &str) { + let mut db = InstalledDB::load(); + + let record = match db.packages.get(pkg_name) { + Some(r) => r, + None => { + eprintln!("{} Package '{}' is not installed.", "[ror]".red().bold(), pkg_name); + return; + } + }; + + if let Err(e) = check_critical_removal(pkg_name, &db) { + eprintln!("{}", e); + return; + } + + println!("{} Removing package '{}'...", "[ror]".blue().bold(), pkg_name); + + let mut failed = false; + + for rel_path in &record.files { + let full_path = Path::new("/").join(rel_path); + if full_path.exists() { + if let Err(e) = fs::remove_file(&full_path) { + eprintln!("{} Failed to remove {}: {}", "[ror]".red().bold(), full_path.display(), e); + failed = true; + } else { + println!("{} Removed {}", ">>>".green(), full_path.display()); + } + } else { + println!("{} File {} already missing", ">>>".yellow(), full_path.display()); + } + } + + if let Some(pkg_path) = find_package_file(pkg_name) { + if let Ok(content) = fs::read_to_string(pkg_path) { + if let Ok(pkg) = serde_yaml::from_str::<Package>(&content) { + if !pkg.delete_steps.trim().is_empty() { + println!("{} Running delete steps...", ">>>".yellow()); + let status = Command::new("sh") + .arg("-c") + .arg(&pkg.delete_steps) + .status() + .expect("Failed to execute delete steps"); + if !status.success() { + eprintln!("{} Delete steps failed with exit code {:?}", "[ror]".red().bold(), status.code()); + failed = true; + } else { + println!("{} Delete steps completed", ">>>".green()); + } + } + } + } + } else { + println!("{} Package recipe not found, skipping delete steps", ">>>".yellow()); + } + db.packages.remove(pkg_name); + if let Err(e) = db.save() { + eprintln!("{} Failed to update installed DB: {}", "[ror]".red().bold(), e); + failed = true; + } else { + println!("{} Package '{}' removed from database.", "[ror]".green(), pkg_name); + } + + if failed { + eprintln!("{} Some errors occurred during removal.", "[ror]".red().bold()); + } else { + println!("{} Package '{}' successfully removed.", "[ror]".green().bold(), pkg_name); + } +} diff --git a/src/group.rs b/src/group.rs new file mode 100644 index 0000000..a3e5fde --- /dev/null +++ b/src/group.rs @@ -0,0 +1,66 @@ +use serde::Deserialize; +use std::fs; +use std::path::Path; +use colored::Colorize; +use crate::config; +use crate::install; + +#[derive(Debug, Deserialize)] +pub struct Group { + #[allow(dead_code)] + pub name: String, + pub description: Option<String>, + pub packages: Vec<String>, +} + +#[allow(dead_code)] +pub fn install_group(group_name: &str, cfg: &config::Config) { + let group_file = format!("/var/ror/packages/groups/{}.yaml", group_name); + if !Path::new(&group_file).exists() { + eprintln!("{} Group '{}' not found!", "[ror]".red().bold(), group_name); + return; + } + + let content = match fs::read_to_string(&group_file) { + Ok(c) => c, + Err(e) => { + eprintln!("{} Failed to read group file: {}", "[ror]".red().bold(), e); + return; + } + }; + + let group: Group = match serde_yaml::from_str(&content) { + Ok(g) => g, + Err(e) => { + eprintln!("{} Group YAML error: {}", "[ror]".red().bold(), e); + return; + } + }; + + println!( + "{} {} Installing group '{}' ({} packages)", + "[ror]".blue().bold(), + ">>>".green(), + group.name, + group.packages.len() + ); + if let Some(desc) = &group.description { + println!("{} {}", "Description:".yellow(), desc); + } + + for pkg in &group.packages { + println!("{} Installing package: {}", ">>>".cyan(), pkg); + install::install_package(pkg, cfg); + } + + println!("{} Group '{}' installation completed.", "[ror]".blue().bold(), group.name); +} + +pub fn load_group(group_name: &str) -> Result<Group, String> { + let group_file = format!("/var/ror/packages/groups/{}.yaml", group_name); + let content = fs::read_to_string(&group_file) + .map_err(|e| format!("Failed to read group file: {}", e))?; + let group: Group = serde_yaml::from_str(&content) + .map_err(|e| format!("Group YAML error: {}", e))?; + Ok(group) +} diff --git a/src/info.rs b/src/info.rs new file mode 100644 index 0000000..8b07daf --- /dev/null +++ b/src/info.rs @@ -0,0 +1,119 @@ +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::{Path, PathBuf}; +use colored::Colorize; + +const REPO_ROOT: &str = "/var/ror/packages"; + +fn find_package_file(pkg_name: &str) -> Option<PathBuf> { + let repo = Path::new(REPO_ROOT); + for entry in fs::read_dir(repo).ok()? { + let entry = entry.ok()?; + let cat_path = entry.path(); + 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); + } + } + None +} + +#[derive(Debug, Serialize, Deserialize)] +struct Package { + name: String, + version: String, + #[serde(default)] + release: Option<String>, + #[serde(default)] + license: Option<String>, + #[serde(default)] + homepage: Option<String>, + #[serde(default)] + description: Option<String>, + #[serde(default)] + binaries: Vec<BinaryPackage>, +} + +#[derive(Debug, Serialize, Deserialize)] +struct BinaryPackage { + #[serde(rename = "type", default)] + pkg_type: Option<String>, + arch: String, + filename: String, + mirrors: Vec<String>, + sha256: String, +} +pub fn print_package_info(pkg_name: &str) { + let pkg_path = match find_package_file(pkg_name) { + Some(p) => p, + None => { + eprintln!( + "{} Package '{}' not found!", + "[ror]".red().bold(), + pkg_name + ); + return; + } + }; + + let content = match fs::read_to_string(&pkg_path) { + Ok(c) => c, + Err(e) => { + eprintln!( + "{} Failed to read package file: {}", + "[ror]".red().bold(), + e + ); + return; + } + }; + + let pkg: Package = match serde_yaml::from_str(&content) { + Ok(p) => p, + Err(e) => { + eprintln!( + "{} YAML structure error: {}", + "[ror]".red().bold(), + e + ); + return; + } + }; + + println!("\n{} {}", "[ Package Info ]".cyan().bold(), "=".repeat(50).cyan()); + + println!("{} {}{}", + "Name:".yellow().bold(), + pkg.name, + if let Some(rel) = &pkg.release { format!("-{}", rel) } else { String::new() } + ); + println!("{} {}", "Version:".yellow().bold(), pkg.version); + + if let Some(lic) = &pkg.license { + println!("{} {}", "License:".yellow().bold(), lic); + } + if let Some(home) = &pkg.homepage { + println!("{} {}", "Homepage:".yellow().bold(), home); + } + if let Some(desc) = &pkg.description { + println!("{} {}", "Description:".yellow().bold(), desc); + } + + if !pkg.binaries.is_empty() { + println!("\n{}", "[ Binaries ]".green().bold()); + for bin in &pkg.binaries { + if let Some(t) = &bin.pkg_type { + println!(" {} [{}]", "Type:".white(), t); + } + println!(" {} {}", "Arch:".white(), bin.arch); + println!(" {} {}", "Filename:".white(), bin.filename); + println!(" {} {}...", "SHA256:".white(), &bin.sha256[..16]); + println!(" {} {} mirrors", "Mirrors:".white(), bin.mirrors.len()); + println!(); + } +} + println!("{}", "=".repeat(60).cyan()); +} diff --git a/src/install.rs b/src/install.rs new file mode 100644 index 0000000..2785180 --- /dev/null +++ b/src/install.rs @@ -0,0 +1,503 @@ +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::{Path, PathBuf}; +use colored::Colorize; +use std::process::Command; +use reqwest::blocking::Client; +use sha2::{Sha256, Digest}; +use walkdir::WalkDir; +use chrono::Local; +use std::collections::HashMap; +use std::os::unix::fs::symlink; +use crate::config; + +const REPO_ROOT: &str = "/var/ror/packages"; + +#[derive(Debug, Serialize, Deserialize)] +#[serde(untagged)] +pub enum Dependency { + Single(String), + Any(Vec<String>), +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Package { + pub name: String, + pub version: String, + #[serde(default)] + pub release: Option<String>, + #[serde(default)] + pub arch: Option<String>, + #[serde(default)] + pub description: Option<String>, + #[serde(default)] + pub license: Option<String>, + #[serde(default)] + pub homepage: Option<String>, + #[serde(default)] + pub binaries: Vec<BinaryPackage>, + #[serde(default)] + pub provides: Vec<String>, + #[serde(default)] + pub install_steps: String, + #[serde(default)] + pub delete_steps: String, + #[serde(default)] + pub depends: Vec<Dependency>, + #[serde(default)] + pub conflicts: Vec<String>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct BinaryPackage { + pub arch: String, + #[serde(default)] + pub filename: String, + #[serde(default)] + pub mirrors: Vec<String>, + #[serde(rename = "type", default)] + pub pkg_type: Option<String>, + #[serde(default)] + pub url: String, + #[serde(default)] + pub sha256: String, + #[serde(default = "default_install_prefix")] + pub install_prefix: String, + #[serde(default)] + pub files: Vec<String>, +} + +fn default_install_prefix() -> String { + "/".to_string() +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct InstalledPackage { + pub name: String, + pub version: String, + pub build_type: String, + pub files: Vec<String>, + pub installed_at: String, +} + +#[derive(Debug, Serialize, Deserialize, Default)] +pub struct InstalledDB { + pub packages: HashMap<String, InstalledPackage>, +} + +impl InstalledDB { + pub const PATH: &'static str = "/var/ror/installed.json"; + + pub fn load() -> Self { + 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 { + Self::default() + } + } + + pub fn save(&self) -> std::io::Result<()> { + 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); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + fs::write(path, json) + } + + pub fn add_package(&mut self, pkg: InstalledPackage) { + self.packages.insert(pkg.name.clone(), pkg); + } + + pub fn is_installed(&self, name: &str) -> bool { + self.packages.contains_key(name) + } +} + + +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())?; + let mut archive = ar::Archive::new(file); + let mut installed_files = Vec::new(); + + 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)) + } else { + Box::new(entry) + }; + + 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()); + } + } + } + Ok(installed_files) +} + +pub fn select_binary_for_arch<'a>(pkg: &'a Package, arch: &str) -> Result<&'a BinaryPackage, String> { + let target_arch = match arch { + "native" => match std::env::consts::ARCH { + "x86_64" => "amd64", + "aarch64" => "arm64", + other => other, + }, + 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)) +} + +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; } + + 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); + } + } + None +} + +pub fn install_package(pkg_name: &str, cfg: &config::Config) { + match install_package_with_result(pkg_name, cfg) { + Ok(installed_pkg) => { + let mut db = InstalledDB::load(); + db.add_package(installed_pkg); + if let Err(e) = db.save() { + eprintln!("{} Failed to save installed DB: {}", "[ror]".red().bold(), e); + } else { + println!("{} Package registered in database", "[ror]".green()); + } + println!("{} {} Package installed successfully.", "[ror]".blue().bold(), ">>>".green()); + } + Err(e) => { + eprintln!("{} {}", "[ror]".red().bold(), e); + } + } +} + + +pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Result<InstalledPackage, String> { + 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))?; + + if pkg.binaries.is_empty() { + return Err("No binary packages defined".to_string()); + } + + 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)); + } + } + + let 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() + } else { + return Err(format!("No URL or mirrors provided for package {}", pkg_name)); + }; + + 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); + + let archive_path = match download_and_verify(&url, &binary.sha256, cfg) { + Ok(p) => p, + Err(e) => { + last_err = Some(e); + continue; + } + }; + + 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"); + + 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() }; + 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); + } + + let _ = fs::remove_dir_all(&work_dir); + let _ = fs::remove_file(&archive_path); + downloaded = true; + break; + } + + if !downloaded { + return Err(last_err.unwrap_or_else(|| "All mirrors/URLs failed".to_string())); + } + + if !pkg.install_steps.is_empty() { + run_commands(&pkg.install_steps, Path::new("/"))?; + } + + Ok(InstalledPackage { + name: pkg.name.clone(), + version: pkg.version.clone(), + build_type: "binary".to_string(), + files: all_installed_files, + installed_at: Local::now().to_rfc3339(), + }) +} + + +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() + .map_err(|e| format!("Download failed: {}", e))?; + + if !response.status().is_success() { + return Err(format!("HTTP error: {}", response.status())); + } + + 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) + .map_err(|e| format!("Failed to create temp file: {}", e))?; + let mut hasher = Sha256::new(); + let mut reader = response; + let mut buf = [0u8; 65536]; + loop { + use std::io::Read; + let n = reader.read(&mut buf) + .map_err(|e| format!("Failed to read response body: {}", e))?; + if n == 0 { break; } + hasher.update(&buf[..n]); + file.write_all(&buf[..n]) + .map_err(|e| format!("Failed to write to temp file: {}", e))?; + } + 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)); + } + } + } + + 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) + .arg("-C") + .arg(target_dir) + .status() + .map_err(|e| format!("Failed to execute tar: {}", e))?; + + if !status.success() { + return Err(format!("tar failed with exit code {:?}", status.code())); + } + + let mut files = Vec::new(); + for entry in WalkDir::new(target_dir).into_iter().filter_map(|e| e.ok()) { + if entry.file_type().is_file() || entry.file_type().is_symlink() { + let rel_path = entry.path().strip_prefix(target_dir).unwrap(); + files.push(rel_path.to_string_lossy().to_string()); + } + } + 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(); + + 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))?; + + if let Some(parent) = dst.parent() { + 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); + symlink(&target, &dst) + .map_err(|e| format!("Failed to create symlink {}: {}", dst.display(), e))?; + } else { + fs::copy(&src, &dst) + .map_err(|e| format!("Failed to copy {}: {}", src.display(), e))?; + } + installed.push(rel_path.clone()); + } + Ok(installed) +} + +pub fn install_files_with_root(source_dir: &Path, root: &Path, files: &[String]) -> Result<Vec<String>, String> { + let mut installed = Vec::new(); + 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))?; + + if let Some(parent) = dst.parent() { + 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); + symlink(&target, &dst) + .map_err(|e| format!("Failed to create symlink {}: {}", dst.display(), e))?; + } else { + fs::copy(&src, &dst) + .map_err(|e| format!("Failed to copy {}: {}", src.display(), e))?; + } + installed.push(rel_path.clone()); + } + Ok(installed) +} + +pub fn run_commands(steps: &str, work_dir: &Path) -> Result<(), String> { + if steps.trim().is_empty() { + return Ok(()); + } + let status = Command::new("sh") + .current_dir(work_dir) + .arg("-c") + .arg(steps) + .status() + .map_err(|e| format!("Failed to execute 'sh -c': {}", e))?; + if status.success() { + Ok(()) + } else { + Err(format!("Command failed with exit code {:?}", status.code())) + } +} + +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() + .find(|l| l.starts_with("version:")) + .and_then(|l| l.split(':').nth(1)) + .map(|s| s.trim().trim_matches('"').to_string()) + .unwrap_or_default(); + Some((name, version)) +} + +pub fn load_package(pkg_name: &str) -> Option<Package> { + let pkg_path = find_package_file(pkg_name)?; + let content = fs::read_to_string(pkg_path).ok()?; + serde_yaml::from_str(&content).ok() +} diff --git a/src/listinstalled.rs b/src/listinstalled.rs new file mode 100644 index 0000000..d63e942 --- /dev/null +++ b/src/listinstalled.rs @@ -0,0 +1,31 @@ +use colored::Colorize; +use crate::install::InstalledDB; + +pub fn print_installed() { + let db = InstalledDB::load(); + let packages = db.packages; + + if packages.is_empty() { + println!("{} No packages installed.", "[ror]".yellow()); + return; + } + + println!("{} Installed packages:", "[ror]".blue().bold()); + println!("{:-<60}", ""); + println!("{:<20} {:<15} {:<10}", "Name", "Version", "Type"); + println!("{:-<60}", ""); + + let mut sorted: Vec<_> = packages.values().collect(); + sorted.sort_by_key(|p| &p.name); + + for pkg in sorted { + println!( + "{:<20} {:<15} {:<10}", + pkg.name.green(), + pkg.version.cyan(), + pkg.build_type.yellow() + ); + } + println!("{:-<60}", ""); + println!("{} Total: {} packages", ">>>".green(), packages.len()); +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..6df2cfc --- /dev/null +++ b/src/main.rs @@ -0,0 +1,218 @@ +use clap::Parser; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use colored::Colorize; + +mod sync; +mod install; +mod config; +mod info; +mod group; +mod delete; +mod listinstalled; +mod update; +mod rootfs; +mod parallel; +mod debug; +mod search; +mod repo; + +#[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, +} + +fn main() { + let args = Args::parse(); + + if args.version { + println!("ror {}", env!("CARGO_PKG_VERSION")); + return; + } + if args.gen_config { + let config_path = Path::new("/var/ror/ror.conf"); + match config::Config::create_default_config(config_path) { + Ok(()) => println!( + "{} Default config created at {:?}", + "[ror]".blue().bold(), + config_path + ), + Err(e) => eprintln!( + "{} Failed to create config: {}", + "[ror]".red().bold(), + e + ), + } + return; + } + + let cfg = Arc::new(config::Config::load()); + + + if let Some(pkg) = args.info { + info::print_package_info(&pkg); + return; + } + if args.sync { + sync::run_sync(&cfg); + return; + } + if args.listinstalled { + listinstalled::print_installed(); + 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) { + eprintln!("{} {}", "[ror]".red().bold(), e); + } + } else { + eprintln!("{} --build-rootfs requires --rootfs-group and --rootfs-target", "[ror]".red().bold()); + } + return; + } + if let Some(pkg) = args.delete { + delete::remove_package(&pkg); + return; + } + if let Some(query) = args.search { + search::search_packages(&query); + return; + } + if !args.install.is_empty() { + if args.install[0].starts_with('@') { + let group_name = &args.install[0][1..]; + match group::load_group(group_name) { + Ok(group) => { + if let Err(e) = parallel::install_packages_parallel(&group.packages, Arc::clone(&cfg)) { + eprintln!("{} {}", "[ror]".red().bold(), e); + } + } + Err(e) => eprintln!("{} {}", "[ror]".red().bold(), e), + } + } else { + if let Err(e) = parallel::install_packages_parallel(&args.install, Arc::clone(&cfg)) { + eprintln!("{} {}", "[ror]".red().bold(), e); + } + } + return; + } + + if args.upgrade { + if args.dry_run { + let upgradable = update::list_upgradable(); + if upgradable.is_empty() { + println!("{} No packages to upgrade.", "[ror]".green()); + } else { + println!("{} Packages that would be upgraded:", ">>>".yellow()); + for pkg in upgradable { + println!(" - {}", pkg); + } + } + } else { + update::upgrade_all(&cfg, false); + } + return; + } + if args.repo_list { + 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) { + 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()); + 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 new file mode 100644 index 0000000..ff11e79 --- /dev/null +++ b/src/parallel.rs @@ -0,0 +1,305 @@ +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::{Arc, Mutex}; +use std::thread; +use crate::config::Config; +use crate::install::{self, Dependency, InstalledDB, load_package}; +use colored::Colorize; +use crate::debug; + +type Result<T> = std::result::Result<T, String>; + +struct DependencyGraph { + edges: HashMap<String, Vec<String>>, + reverse: HashMap<String, Vec<String>>, +} + +impl DependencyGraph { + fn new() -> Self { + debug!("DependencyGraph::new()"); + Self { edges: HashMap::new(), reverse: HashMap::new() } + } + + fn add_dep(&mut self, pkg: String, dep: String) { + debug!("DependencyGraph::add_dep: {} -> {}", pkg, dep); + self.edges.entry(pkg.clone()).or_insert_with(Vec::new).push(dep.clone()); + self.reverse.entry(dep).or_insert_with(Vec::new).push(pkg); + } + + fn compute_levels(&self) -> Vec<Vec<String>> { + debug!("DependencyGraph::compute_levels: start"); + let mut in_degree: HashMap<String, usize> = HashMap::new(); + for (pkg, deps) in &self.edges { + in_degree.entry(pkg.clone()).or_insert(0); + for dep in deps { + *in_degree.entry(dep.clone()).or_insert(0) += 1; + } + } + for (pkg, children) in &self.reverse { + in_degree.entry(pkg.clone()).or_insert(0); + for child in children { + in_degree.entry(child.clone()).or_insert(0); + } + } + + let mut levels = Vec::new(); + let mut queue: VecDeque<String> = in_degree.iter() + .filter(|(_, °)| deg == 0) + .map(|(pkg, _)| pkg.clone()) + .collect(); + debug!("compute_levels: initial queue: {:?}", queue); + + while !queue.is_empty() { + let level_pkgs: Vec<String> = queue.drain(..).collect(); + debug!("compute_levels: level {}: {:?}", levels.len(), level_pkgs); + levels.push(level_pkgs.clone()); + for pkg in &level_pkgs { + if let Some(children) = self.reverse.get(pkg) { + for child in children { + if let Some(deg) = in_degree.get_mut(child) { + *deg -= 1; + if *deg == 0 { + queue.push_back(child.clone()); + } + } + } + } + } + } + + if in_degree.values().any(|&d| d > 0) { + eprintln!("{} Circular dependency detected!", "[ror]".red().bold()); + debug!("compute_levels: circular dependency detected"); + } + debug!("compute_levels: levels count = {}", levels.len()); + levels + } +} + +fn collect_required_packages(packages: &[String], installed_db: &InstalledDB) -> Result<HashSet<String>> { + debug!("collect_required_packages: start with packages {:?}", packages); + let mut required = HashSet::new(); + let mut stack: Vec<String> = packages.iter().cloned().collect(); + + while let Some(pkg_name) = stack.pop() { + debug!("collect_required_packages: processing {}", pkg_name); + if installed_db.is_installed(&pkg_name) || required.contains(&pkg_name) { + debug!("collect_required_packages: {} already installed or in required set", pkg_name); + continue; + } + required.insert(pkg_name.clone()); + + let pkg = match load_package(&pkg_name) { + Some(p) => p, + None => { + debug!("collect_required_packages: package {} not found", pkg_name); + return Err(format!("Package '{}' not found", pkg_name)); + } + }; + + for dep in &pkg.depends { + match dep { + Dependency::Single(name) => { + debug!("collect_required_packages: single dependency {}", name); + if !installed_db.is_installed(name) && !required.contains(name) { + stack.push(name.clone()); + } + } + Dependency::Any(alternatives) => { + debug!("collect_required_packages: any dependency {:?}", alternatives); + let installed_alt = alternatives.iter().find(|alt| installed_db.is_installed(*alt)); + if installed_alt.is_some() { + debug!("collect_required_packages: an alternative already installed, skipping"); + continue; + } + let chosen = alternatives.iter() + .find(|alt| required.contains(*alt)) + .cloned() + .or_else(|| alternatives.first().cloned()) + .ok_or_else(|| { + debug!("collect_required_packages: empty alternative list"); + format!("Empty alternative list in package {}", pkg_name) + })?; + debug!("collect_required_packages: chosen alternative {}", chosen); + if !required.contains(&chosen) { + stack.push(chosen); + } + } + } + } + } + debug!("collect_required_packages: required set = {:?}", required); + Ok(required) +} + +fn build_graph(packages: &HashSet<String>, installed_db: &InstalledDB) -> Result<DependencyGraph> { + debug!("build_graph: building graph for {} packages", packages.len()); + let mut graph = DependencyGraph::new(); + for pkg_name in packages { + debug!("build_graph: processing {}", pkg_name); + let pkg = match load_package(pkg_name) { + Some(p) => p, + None => { + debug!("build_graph: package {} not found", pkg_name); + return Err(format!("Package '{}' not found", pkg_name)); + } + }; + for dep in &pkg.depends { + match dep { + Dependency::Single(name) => { + if packages.contains(name) { + debug!("build_graph: adding edge {} -> {}", pkg_name, name); + graph.add_dep(pkg_name.clone(), name.clone()); + } else if !installed_db.is_installed(name) { + debug!("build_graph: missing dependency {} for {}", name, pkg_name); + return Err(format!("Dependency '{}' of '{}' is missing", name, pkg_name)); + } + } + Dependency::Any(alternatives) => { + debug!("build_graph: any dependency {:?} for {}", alternatives, pkg_name); + let found = alternatives.iter().find(|alt| packages.contains(*alt)); + if let Some(chosen) = found { + debug!("build_graph: adding edge {} -> {}", pkg_name, chosen); + graph.add_dep(pkg_name.clone(), chosen.clone()); + } else { + let installed = alternatives.iter().any(|alt| installed_db.is_installed(alt)); + if !installed { + debug!("build_graph: no alternative available for {}", pkg_name); + return Err(format!("No alternative from {:?} for package '{}' is available", alternatives, pkg_name)); + } + } + } + } + } + } + Ok(graph) +} + +fn check_conflicts(required: &HashSet<String>, installed_db: &InstalledDB) -> Result<()> { + debug!("check_conflicts: checking {} packages", required.len()); + let mut pkg_map = HashMap::new(); + for pkg_name in required { + let pkg = match load_package(pkg_name) { + Some(p) => p, + None => { + debug!("check_conflicts: package {} not found", pkg_name); + return Err(format!("Package '{}' not found", pkg_name)); + } + }; + pkg_map.insert(pkg_name.clone(), pkg); + } + + for (name, pkg) in &pkg_map { + for conflict in &pkg.conflicts { + if installed_db.is_installed(conflict) { + debug!("check_conflicts: {} conflicts with installed {}", name, conflict); + return Err(format!("Package '{}' conflicts with installed package '{}'", name, conflict)); + } + } + } + + let names: Vec<_> = pkg_map.keys().cloned().collect(); + for i in 0..names.len() { + for j in i+1..names.len() { + let a = &names[i]; + let b = &names[j]; + let pkg_a = &pkg_map[a]; + let pkg_b = &pkg_map[b]; + if pkg_a.conflicts.contains(b) || pkg_b.conflicts.contains(a) { + debug!("check_conflicts: {} and {} conflict", a, b); + return Err(format!("Packages '{}' and '{}' conflict with each other", a, b)); + } + } + } + debug!("check_conflicts: no conflicts found"); + Ok(()) +} + +fn install_single_package(pkg_name: &str, cfg: Arc<Config>, db_mutex: &Mutex<InstalledDB>) -> Result<()> { + debug!("install_single_package: starting {}", pkg_name); + println!("{} Installing {}...", ">>>".cyan(), pkg_name); + let installed_pkg = match install::install_package_with_result(pkg_name, &*cfg) { + Ok(p) => { + debug!("install_single_package: install_package_with_result OK for {}", pkg_name); + p + } + Err(e) => { + debug!("install_single_package: install_package_with_result failed for {}: {}", pkg_name, e); + return Err(e); + } + }; + let mut db = db_mutex.lock().unwrap(); + db.add_package(installed_pkg); + debug!("install_single_package: added to memory DB, saving..."); + if let Err(e) = db.save() { + eprintln!("{} Failed to save installed DB: {}", "[ror]".red().bold(), e); + debug!("install_single_package: save failed: {}", e); + return Err(format!("Failed to save installed DB: {}", e)); + } + debug!("install_single_package: save successful for {}", pkg_name); + 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(); + let required = collect_required_packages(packages, &installed_db)?; + if required.is_empty() { + println!("{} All packages already installed.", "[ror]".green()); + debug!("install_packages_parallel: no packages required"); + return Ok(()); + } + + check_conflicts(&required, &installed_db)?; + + 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 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()); + debug!("install_packages_parallel: starting level {} with {:?}", level_idx, level_pkgs); + let mut handles = Vec::new(); + for pkg in level_pkgs { + let pkg_name = pkg.clone(); + let cfg = Arc::clone(&cfg); + let db_mutex = Arc::clone(&db_mutex); + let handle = thread::spawn(move || { + install_single_package(&pkg_name, cfg, &db_mutex) + }); + handles.push(handle); + } + + let mut errors = Vec::new(); + for handle in handles { + match handle.join() { + Ok(Ok(())) => {}, + Ok(Err(e)) => { + debug!("install_packages_parallel: thread error: {}", e); + errors.push(e); + } + Err(_) => { + debug!("install_packages_parallel: thread panicked"); + errors.push("Thread panicked".to_string()); + } + } + } + + if !errors.is_empty() { + eprintln!("{} Errors during level {}: {:?}", "[ror]".red().bold(), level_idx, errors); + debug!("install_packages_parallel: level {} failed with {} errors", level_idx, errors.len()); + return Err(format!("Installation failed at level {}", level_idx)); + } + } + + println!("{} All packages installed successfully.", "[ror]".green().bold()); + debug!("install_packages_parallel: completed successfully"); + Ok(()) +} diff --git a/src/repo.rs b/src/repo.rs new file mode 100644 index 0000000..bd87ea5 --- /dev/null +++ b/src/repo.rs @@ -0,0 +1,56 @@ + +use colored::Colorize; +use std::fs; +use std::path::Path; +use crate::config::{Config, RepositoryConfig}; + +pub fn add_repository(name: &str, url: &str, mirror: Option<&str>) -> Result<(), String> { + let mut cfg = Config::load(); + if cfg.repositories.contains_key(name) { + return Err(format!("Repository '{}' already exists", name)); + } + let repo = RepositoryConfig { + url: url.to_string(), + mirror: mirror.map(String::from), + }; + cfg.repositories.insert(name.to_string(), repo); + save_config(&cfg)?; + println!("{} Repository '{}' added.", "[ror]".green().bold(), name); + Ok(()) +} + +pub fn remove_repository(name: &str) -> Result<(), String> { + let mut cfg = Config::load(); + if !cfg.repositories.contains_key(name) { + return Err(format!("Repository '{}' not found", name)); + } + cfg.repositories.remove(name); + save_config(&cfg)?; + println!("{} Repository '{}' removed.", "[ror]".green().bold(), name); + Ok(()) +} + +pub fn list_repositories() { + let cfg = Config::load(); + if cfg.repositories.is_empty() { + println!("{} No repositories configured.", "[ror]".yellow()); + return; + } + println!("{} Configured repositories:", "[ror]".blue().bold()); + for (name, repo) in &cfg.repositories { + println!(" {} {}", name.green(), repo.url); + if let Some(m) = &repo.mirror { + println!(" mirror: {}", m); + } + } +} + +fn save_config(cfg: &Config) -> Result<(), String> { + let path = Path::new("/var/ror/ror.conf"); + let ini = cfg.to_ini().map_err(|e| format!("Failed to serialize config: {}", e))?; + fs::write(path, ini).map_err(|e| format!("Failed to write config: {}", e))?; + Ok(()) +} + + + diff --git a/src/rootfs.rs b/src/rootfs.rs new file mode 100644 index 0000000..659032e --- /dev/null +++ b/src/rootfs.rs @@ -0,0 +1,307 @@ +use std::fs; +use std::path::Path; +use std::collections::HashSet; +use std::process::Command; +use colored::Colorize; +use crate::config; +use crate::group::Group; +use crate::install::{ + Dependency, Package, load_package, download_and_verify, + extract_native, install_files_with_root, select_binary_for_arch, +}; + + + + + +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), + ("/dev/shm", "dev/shm", "tmpfs", true), + ("proc", "proc", "proc", false), + ("sysfs", "sys", "sysfs", false), + ]; + + for (src, rel, fstype, bind) in mounts { + let target = root_dir.join(rel); + fs::create_dir_all(&target) + .map_err(|e| format!("Failed to create mountpoint {}: {}", rel, e))?; + + let status = if *bind { + Command::new("mount") + .args(["--bind", src, target.to_str().unwrap()]) + .status() + } else { + Command::new("mount") + .args(["-t", fstype, src, target.to_str().unwrap()]) + .status() + }; + + match status { + Ok(s) if s.success() => {} + Ok(_) => eprintln!("{} Warning: failed to mount {} (non-fatal)", "[ror]".yellow(), rel), + Err(e) => eprintln!("{} Warning: mount {}: {} (non-fatal)", "[ror]".yellow(), rel, e), + } + } + Ok(()) +} + + +fn umount_virtual_fs(root_dir: &Path) { + for rel in &["dev/pts", "dev/shm", "dev", "proc", "sys"] { + let target = root_dir.join(rel); + if target.exists() { + let _ = Command::new("umount").args(["-l", target.to_str().unwrap()]).status(); + } + } +} + + + + + + + +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() +} + + + + + +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()); + + 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); } + cmd.arg(script_rel); + + let status = cmd.status() + .map_err(|e| format!("Failed to execute chroot for {}: {}", pkg_name, e))?; + + let _ = fs::remove_file(&script_host); + + if status.success() { + Ok(()) + } else { + Err(format!( + "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, +) -> 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)?; + } + } + Dependency::Any(alternatives) => { + if alternatives.iter().any(|alt| installing.contains(alt)) { + continue; + } + 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)?; + } + } + } + Ok(()) +} + +pub fn install_package_in_chroot( + pkg_name: &str, + cfg: &config::Config, + root_dir: &Path, + installing: &mut HashSet<String>, + target_arch: &str, +) -> Result<(), String> { + if installing.contains(pkg_name) { + eprintln!("{} Circular dependency detected: {}", "[ror]".red().bold(), pkg_name); + return Ok(()); + } + installing.insert(pkg_name.to_string()); + + 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)?; + + let binary = select_binary_for_arch(&pkg, target_arch) + .map_err(|e| format!("Failed to select binary for {}: {}", pkg_name, e))?; + + 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, + Err(e) => { last_err = Some(e); continue; } + }; + + let work_dir = Path::new("/tmp/ror-install").join(&pkg.name); + if work_dir.exists() { + fs::remove_dir_all(&work_dir) + .map_err(|e| format!("Failed to clean temp dir: {}", e))?; + } + fs::create_dir_all(&work_dir) + .map_err(|e| format!("Failed to create temp dir: {}", e))?; + + 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() }; + + install_files_with_root(&work_dir, root_dir, &file_list)?; + + let _ = fs::remove_dir_all(&work_dir); + let _ = fs::remove_file(&archive_path); + + println!("{} Installed {} into {}", ">>>".green(), pkg_name, root_dir.display()); + return Ok(()); + } + + Err(last_err.unwrap_or_else(|| "All mirrors failed".into())) +} + + + + + +fn run_all_install_steps( + group_order: &[String], + all_installed: &HashSet<String>, + target_dir: &Path, +) -> 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(); + for e in &extras { queue.push(e.as_str()); } + + 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)?; + } + } + } + Ok(()) +} + + + + + +pub fn build_rootfs( + group_name: &str, + target_dir: &Path, + cfg: &config::Config, + target_arch: &str, + run_ldconfig: bool, +) -> Result<(), String> { + if !target_dir.exists() { + fs::create_dir_all(target_dir) + .map_err(|e| format!("Failed to create target directory: {}", e))?; + } else { + let mut entries = target_dir.read_dir() + .map_err(|e| format!("Failed to read target directory: {}", e))?; + if entries.next().is_some() { + return Err(format!("Target directory {} is not empty", target_dir.display())); + } + } + + let group_file = format!("/var/ror/packages/groups/{}.yaml", group_name); + let content = fs::read_to_string(&group_file) + .map_err(|e| format!("Failed to read group file: {}", e))?; + let group: Group = serde_yaml::from_str(&content) + .map_err(|e| format!("Group YAML error: {}", e))?; + + println!("{} Building rootfs in {} with group '{}'", + "[ror]".blue().bold(), target_dir.display(), group_name); + if let Some(desc) = &group.description { + println!("{} {}", "Description:".yellow(), desc); + } + + + println!("\n{} Phase 1: installing files...", ">>>".cyan().bold()); + let mut installing: HashSet<String> = HashSet::new(); + for pkg in &group.packages { + install_package_in_chroot(pkg, cfg, target_dir, &mut installing, target_arch)?; + } + println!("{} Phase 1 complete: {} packages.", ">>>".green(), installing.len()); + + if run_ldconfig { + println!("{} Running ldconfig...", ">>>".cyan()); + match Command::new("ldconfig").arg("-r").arg(target_dir).status() { + Ok(s) if s.success() => println!("{} ldconfig done.", ">>>".green()), + _ => eprintln!("{} ldconfig failed (non-fatal)", "[ror]".yellow()), + } + } + + println!("\n{} Phase 2: running install_steps in chroot...", ">>>".cyan().bold()); + println!("{} Mounting /dev /proc /sys...", ">>>".cyan()); + mount_virtual_fs(target_dir)?; + + let result = run_all_install_steps(&group.packages, &installing, target_dir); + + println!("{} Unmounting virtual filesystems...", ">>>".cyan()); + umount_virtual_fs(target_dir); + + result?; + + println!("\n{} Rootfs created successfully at {}", + "[ror]".green().bold(), target_dir.display()); + Ok(()) +} diff --git a/src/search.rs b/src/search.rs new file mode 100644 index 0000000..fabfb47 --- /dev/null +++ b/src/search.rs @@ -0,0 +1,92 @@ +use colored::Colorize; +use std::fs; +use std::path::Path; +use crate::install::Package; + +const REPOS_ROOT: &str = "/var/ror/packages"; + +fn load_package_from_path(path: &Path) -> Option<Package> { + let content = fs::read_to_string(path).ok()?; + serde_yaml::from_str(&content).ok() +} + +fn find_all_package_files() -> Vec<String> { + let mut results = Vec::new(); + let root = Path::new(REPOS_ROOT); + let Ok(level1) = fs::read_dir(root) else { return results }; + + for entry1 in level1.flatten() { + let path1 = entry1.path(); + if !path1.is_dir() || path1.file_name().unwrap_or_default() == "groups" { + continue; + } + + + let Ok(level2) = fs::read_dir(&path1) else { continue }; + for entry2 in level2.flatten() { + let path2 = entry2.path(); + if !path2.is_dir() { + continue; + } + + + let yaml_path = path2.join(path2.file_name().unwrap()).with_extension("yaml"); + if yaml_path.exists() { + if let Some(s) = yaml_path.to_str() { + results.push(s.to_string()); + } + continue; + } + + + let Ok(level3) = fs::read_dir(&path2) else { continue }; + for entry3 in level3.flatten() { + let path3 = entry3.path(); + if !path3.is_dir() { + continue; + } + let yaml_path = path3.join(path3.file_name().unwrap()).with_extension("yaml"); + if yaml_path.exists() { + if let Some(s) = yaml_path.to_str() { + results.push(s.to_string()); + } + } + } + } + } + results +} + +pub fn search_packages(query: &str) { + let query_lower = query.to_lowercase(); + let files = find_all_package_files(); + + if files.is_empty() { + println!("{} No packages found in repositories.", "[ror]".yellow()); + return; + } + + let mut matches = Vec::new(); + for file in files { + if let Some(pkg) = load_package_from_path(Path::new(&file)) { + let name_lower = pkg.name.to_lowercase(); + let desc_lower = pkg.description.clone().unwrap_or_default().to_lowercase(); + if name_lower.contains(&query_lower) || desc_lower.contains(&query_lower) { + matches.push(pkg); + } + } + } + + if matches.is_empty() { + println!("{} No packages matching '{}'.", "[ror]".yellow(), query); + return; + } + + println!("{} Packages matching '{}':", "[ror]".blue().bold(), query); + println!("{:-<60}", ""); + for pkg in matches { + let name_ver = format!("{} {}", pkg.name, pkg.version).cyan(); + let desc = pkg.description.unwrap_or_default(); + println!(" {} {}", name_ver, desc); + } +} diff --git a/src/sync.rs b/src/sync.rs new file mode 100644 index 0000000..3734a03 --- /dev/null +++ b/src/sync.rs @@ -0,0 +1,69 @@ +use colored::*; +use std::path::Path; +use std::process::Command; +use crate::config::Config; + +const REPOS_DIR: &str = "/var/ror/packages"; + +pub fn run_sync(cfg: &Config) { + if cfg.repositories.is_empty() { + eprintln!("{} No repositories configured.", "[ror]".red().bold()); + return; + } + + for (name, repo) in &cfg.repositories { + println!("{} Syncing repository '{}'...", "[ror]".blue().bold(), name); + let repo_path = Path::new(REPOS_DIR).join(name); + + if repo_path.exists() { + println!("{} Updating {}...", ">>>".green(), name); + let status = Command::new("git") + .args(&["-C", repo_path.to_str().unwrap(), "pull"]) + .status() + .expect("Failed to execute git pull"); + + if !status.success() && repo.mirror.is_some() { + eprintln!("{} Pull failed, trying mirror...", "[ror]".red()); + let mirror_url = repo.mirror.as_ref().unwrap(); + let mirror_status = Command::new("git") + .args(&["-C", repo_path.to_str().unwrap(), "pull", mirror_url]) + .status() + .expect("Failed to execute git pull from mirror"); + if mirror_status.success() { + println!("{} Updated from mirror.", ">>>".green()); + } else { + eprintln!("{} Mirror also failed.", "[ror]".red()); + } + } else if !status.success() { + eprintln!("{} Git pull failed, no mirror configured.", "[ror]".red()); + } else { + println!("{} Repository updated.", ">>>".green()); + } + } else { + println!("{} Cloning {}...", ">>>".green(), name); + let primary_url = &repo.url; + let mut status = Command::new("git") + .args(&["clone", primary_url, repo_path.to_str().unwrap()]) + .status() + .expect("Failed to execute git clone"); + + if !status.success() && repo.mirror.is_some() { + eprintln!("{} Clone from primary failed, trying mirror...", "[ror]".red()); + let mirror_url = repo.mirror.as_ref().unwrap(); + status = Command::new("git") + .args(&["clone", mirror_url, repo_path.to_str().unwrap()]) + .status() + .expect("Failed to execute git clone from mirror"); + if status.success() { + println!("{} Cloned from mirror.", ">>>".green()); + } else { + eprintln!("{} Mirror also failed.", "[ror]".red()); + } + } else if !status.success() { + eprintln!("{} Git clone failed.", "[ror]".red()); + } else { + println!("{} Repository cloned.", ">>>".green()); + } + } + } +} diff --git a/src/update.rs b/src/update.rs new file mode 100644 index 0000000..f5c2690 --- /dev/null +++ b/src/update.rs @@ -0,0 +1,99 @@ +use colored::Colorize; +use crate::install::{self, InstalledDB, get_package_info}; +use crate::delete; +use crate::config; +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 + } + } +} + +pub fn update_package(pkg_name: &str, cfg: &config::Config, dry_run: bool) -> bool { + let db = InstalledDB::load(); + let installed = match db.packages.get(pkg_name) { + Some(p) => p, + None => { + eprintln!("{} Package '{}' is not installed.", "[ror]".red().bold(), pkg_name); + return false; + } + }; + + let info = match get_package_info(pkg_name) { + Some(info) => info, + None => { + eprintln!("{} Package '{}' not found in repository.", "[ror]".red().bold(), pkg_name); + return false; + } + }; + let available_version = info.1; + + if !is_newer(&installed.version, &available_version) { + println!("{} Package '{}' is already up-to-date (version {}).", "[ror]".green(), pkg_name, installed.version); + return false; + } + + println!("{} Updating '{}' from {} to {}...", "[ror]".blue().bold(), pkg_name, installed.version, available_version); + + if dry_run { + println!("{} DRY RUN: would remove and reinstall {}", ">>>".yellow(), pkg_name); + return true; + } + + delete::remove_package(pkg_name); + install::install_package(pkg_name, cfg); + true +} + +pub fn upgrade_all(cfg: &config::Config, dry_run: bool) { + let db = InstalledDB::load(); + let installed: Vec<String> = db.packages.keys().cloned().collect(); + if installed.is_empty() { + println!("{} No packages installed.", "[ror]".yellow()); + return; + } + + let mut updated = HashSet::new(); + let mut failed = Vec::new(); + + for pkg in &installed { + if updated.contains(pkg) { + continue; + } + if update_package(pkg, cfg, dry_run) { + updated.insert(pkg.clone()); + } else { + failed.push(pkg.clone()); + } + } + + if dry_run { + println!("{} DRY RUN: {} packages would be updated.", ">>>".yellow(), updated.len()); + } else { + println!("{} Upgrade completed. Updated: {}, failed: {}.", "[ror]".green().bold(), updated.len(), failed.len()); + if !failed.is_empty() { + println!("{} Failed packages: {:?}", "[ror]".red(), failed); + } + } +} + +pub fn list_upgradable() -> Vec<String> { + let db = InstalledDB::load(); + let mut upgradable = Vec::new(); + for pkg_name in db.packages.keys() { + let installed_version = &db.packages[pkg_name].version; + if let Some(info) = get_package_info(pkg_name) { + let available_version = info.1; + if is_newer(installed_version, &available_version) { + upgradable.push(pkg_name.clone()); + } + } + } + upgradable +} |