diff options
| author | rorka900 <rorka900@gmail.com> | 2026-04-24 17:53:49 +0300 |
|---|---|---|
| committer | rorka900 <rorka900@gmail.com> | 2026-04-24 17:53:49 +0300 |
| commit | 9c9ce088193c2506da372c76685076bbfead0690 (patch) | |
| tree | 8eacd30624a4d6da552f8de44a1e1273bfede3d4 | |
| parent | f2ab400fb6750fbe017309757f06339437b7c4b8 (diff) | |
| download | ror-9c9ce088193c2506da372c76685076bbfead0690.tar.gz ror-9c9ce088193c2506da372c76685076bbfead0690.zip | |
feat: modernize CLI with clap subcommands and add declarative apply1.0.0-r1
| -rw-r--r-- | Cargo.lock | 244 | ||||
| -rw-r--r-- | Cargo.toml | 25 | ||||
| -rw-r--r-- | README.md | 151 | ||||
| -rw-r--r-- | src/apply.rs | 183 | ||||
| -rw-r--r-- | src/check.rs | 2 | ||||
| -rw-r--r-- | src/config.rs | 9 | ||||
| -rw-r--r-- | src/delete.rs | 118 | ||||
| -rw-r--r-- | src/install.rs | 95 | ||||
| -rw-r--r-- | src/main.rs | 570 | ||||
| -rw-r--r-- | src/parallel.rs | 737 | ||||
| -rw-r--r-- | src/resolver.rs | 251 | ||||
| -rw-r--r-- | src/rootfs.rs | 42 | ||||
| -rw-r--r-- | src/update.rs | 6 |
13 files changed, 1374 insertions, 1059 deletions
@@ -3,12 +3,6 @@ version = 4 [[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] name = "android_system_properties" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -119,34 +113,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" [[package]] -name = "bzip2" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdb116a6ef3f6c3698828873ad02c3014b3c85cadb88496095628e3ef1e347f8" -dependencies = [ - "bzip2-sys", - "libc", -] - -[[package]] -name = "bzip2-sys" -version = "0.1.13+1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14" -dependencies = [ - "cc", - "pkg-config", -] - -[[package]] name = "cc" version = "1.2.56" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2" dependencies = [ "find-msvc-tools", - "jobserver", - "libc", "shlex", ] @@ -299,15 +271,6 @@ dependencies = [ ] [[package]] -name = "crc32fast" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" -dependencies = [ - "cfg-if", -] - -[[package]] name = "crunchy" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -402,16 +365,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" [[package]] -name = "flate2" -version = "1.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" -dependencies = [ - "crc32fast", - "miniz_oxide", -] - -[[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -442,6 +395,21 @@ dependencies = [ ] [[package]] +name = "futures" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] name = "futures-channel" version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -458,12 +426,34 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" [[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] name = "futures-io" version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" [[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] name = "futures-sink" version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -481,8 +471,10 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" dependencies = [ + "futures-channel", "futures-core", "futures-io", + "futures-macro", "futures-sink", "futures-task", "memchr", @@ -528,21 +520,6 @@ dependencies = [ ] [[package]] -name = "git2" -version = "0.20.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b88256088d75a56f8ecfa070513a775dd9107f6530ef14919dac831af9cfe2b" -dependencies = [ - "bitflags", - "libc", - "libgit2-sys", - "log", - "openssl-probe 0.1.6", - "openssl-sys", - "url", -] - -[[package]] name = "h2" version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -863,16 +840,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" [[package]] -name = "jobserver" -version = "0.1.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" -dependencies = [ - "getrandom 0.3.4", - "libc", -] - -[[package]] name = "js-sys" version = "0.3.88" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -895,20 +862,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112" [[package]] -name = "libgit2-sys" -version = "0.18.3+1.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9b3acc4b91781bb0b3386669d325163746af5f6e4f73e6d2d630e09a35f3487" -dependencies = [ - "cc", - "libc", - "libssh2-sys", - "libz-sys", - "openssl-sys", - "pkg-config", -] - -[[package]] name = "libredox" version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -920,32 +873,6 @@ dependencies = [ ] [[package]] -name = "libssh2-sys" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "220e4f05ad4a218192533b300327f5150e809b54c4ec83b5a1d91833601811b9" -dependencies = [ - "cc", - "libc", - "libz-sys", - "openssl-sys", - "pkg-config", - "vcpkg", -] - -[[package]] -name = "libz-sys" -version = "1.1.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15d118bbf3771060e7311cc7bb0545b01d08a8b4a7de949198dec1fa0ca1c0f7" -dependencies = [ - "cc", - "libc", - "pkg-config", - "vcpkg", -] - -[[package]] name = "linux-raw-sys" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -999,16 +926,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] name = "mio" version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -1028,7 +945,7 @@ dependencies = [ "libc", "log", "openssl", - "openssl-probe 0.2.1", + "openssl-probe", "openssl-sys", "schannel", "security-framework", @@ -1095,12 +1012,6 @@ dependencies = [ [[package]] name = "openssl-probe" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" - -[[package]] -name = "openssl-probe" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" @@ -1328,12 +1239,14 @@ dependencies = [ "tokio", "tokio-native-tls", "tokio-rustls", + "tokio-util", "tower", "tower-http", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", + "wasm-streams", "web-sys", "webpki-roots", ] @@ -1354,16 +1267,15 @@ dependencies = [ [[package]] name = "ror" -version = "0.9.0" +version = "1.0.0-r1" dependencies = [ "ar", - "bzip2", "chrono", "clap", "colored", "config", - "flate2", - "git2", + "futures", + "once_cell", "reqwest", "semver", "serde", @@ -1372,9 +1284,9 @@ dependencies = [ "sha2", "tar", "tempfile", + "tokio", "walkdir", "xz2", - "zstd", ] [[package]] @@ -1586,10 +1498,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] -name = "simd-adler32" -version = "0.3.8" +name = "signal-hook-registry" +version = "1.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] [[package]] name = "slab" @@ -1771,11 +1687,24 @@ dependencies = [ "libc", "mio", "pin-project-lite", + "signal-hook-registry", "socket2", + "tokio-macros", "windows-sys 0.61.2", ] [[package]] +name = "tokio-macros" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c55a2eff8b69ce66c84f85e1da1c233edc36ceb85a2058d11b0d6a3c7e7569c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] name = "tokio-native-tls" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -2032,6 +1961,19 @@ dependencies = [ ] [[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] name = "web-sys" version = "0.3.88" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -2443,31 +2385,3 @@ name = "zmij" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" - -[[package]] -name = "zstd" -version = "0.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" -dependencies = [ - "zstd-safe", -] - -[[package]] -name = "zstd-safe" -version = "7.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" -dependencies = [ - "zstd-sys", -] - -[[package]] -name = "zstd-sys" -version = "2.0.16+zstd.1.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" -dependencies = [ - "cc", - "pkg-config", -] @@ -1,10 +1,10 @@ [package] name = "ror" -version = "0.9.0" +version = "1.0.0-r1" edition = "2024" authors = ["rorka900"] description = "RorkOS package manager" -license = "GPL-3.0" +license = "AGPL-3.0" [dependencies] clap = { version = "4.5", features = ["derive"] } @@ -12,25 +12,34 @@ colored = "2.1" serde = { version = "1.0", features = ["derive"] } serde_yaml = "0.9" serde_json = "1.0" -git2 = "0.20" -reqwest = { version = "0.12", features = ["blocking", "rustls-tls"] } +reqwest = { version = "0.12", features = ["blocking", "rustls-tls", "stream"] } config = { version = "0.14", default-features = false, features = ["ini"] } xz2 = "0.1" tar = "0.4" -flate2 = "1.0" sha2 = "0.10" walkdir = "2" chrono = "0.4" semver = "1.0" ar = "0.9" -zstd = "0.13" -bzip2 = "0.4" tempfile = "3" +tokio = { version = "1", features = [ + "rt-multi-thread", + "macros", + "sync", + "signal", + "time", + "net", + "io-util", + "fs", +] } +futures = "0.3" +once_cell = "1" [profile.release] -opt-level = 3 +opt-level = "z" lto = true codegen-units = 1 +panic = "abort" strip = true [features] @@ -1,150 +1 @@ -# ror - -The package manager for RorkOS. Installs, removes, and updates binary packages from git-based repositories. - -```sh - --search <QUERY> #search - -s, --sync #synchronizes the repository - -d, --delete <PACKAGE> #removing a package - -l, --list-installed #installed packages - --info <PACKAGE> #package information - -v, --version #package manager version - -g, --gen-config #generating configuration for the package manager - -i, --install <PACKAGE_OR_GROUP>... #example: ror -i @base/bash - --update <PACKAGE> #update one package - --dry-run #simulates the execution of a command - -u, --upgrade #updates the entire system - --up <GROUP> - --repo-add <NAME> <URL>#adding a repository - --repo-remove <NAME> #deletes the repository - --repo-list #list of repositories - --build-rootfs #creates rootfs - --rootfs-group <GROUP> #creates rootfs with group - --rootfs-target <TARGET>#installs root force in a separate folder - --rootfs-arch <ROOTFS_ARCH> [default: native] #installs rootfs for a specific architecture - --di <DELETE> <INSTALL> #will remove and install the package - --lg #displays a list of all groups - --check #package integrity check - -h, --help Print help -``` - - -Config is located at `/var/ror/ror.conf`: - -```ini -[global] -ignore_speed = false -strict_gpg = false -parallel_downloads = 4 - -[repositories.rorkos] -url = "https: -mirror = "https: -urlrepo = "https: -``` - - - ---- - -## Package Format - -Packages are YAML files stored in the repository under `<category>/<n>/<n>.yaml`: - -```yaml -name: vim -version: "9.1.0" -main:rorka900 example @mail.com -description: "Vi IMproved - enhanced vi editor" -arch: "amd64, arm64" -libc: "gm" #that is, support for Glibc and Musl. -license: "Vim" -homepage: "https://www.vim.org" - -provides: - - editor - -depends: - - "depends" - - ["depends1", "depends2"] #choice of dependency - -conflicts: - - vim-tiny #packet conflict - -binaries: - - arch: amd64 - type: ror - filename: "vim-9.1.0-pkg-amd64-glibc-rorkos.ror" - sha256: "" - dict: https://example.com/pkg.dict - mirrors: - - "https://repo.example.com/packages/{filename}" #or - - "rorkos" -binaries: - - arch: amd64 - type: ror - filename: "vim-9.1.0-pkg-amd64-glibc-rorkos.ror" - sha256: "" - dict: https://example.com/pkg.dict - mirrors: - - "https://repo.example.com/packages/{filename}" #or - - "rorkos" - -install_steps: | - update-alternatives --install /usr/bin/vi vi /usr/bin/vim 100 - -``` - ---- - -Group files live at `/var/ror/packages/groups/<n>.yaml`: - -```yaml -name: base -description: "Minimal RorkOS base system" -libc: m *thiss musl -version: "r1" -packages: - - "musl" - - "busybox" - - "runit" - - "ror" -install_steps: | - echo done -``` - ---- - -## Building a Rootfs - -```sh -ror --build-rootfs \ - --rootfs-group base \ - --rootfs-target /mnt/rootfs \ - --rootfs-arch amd64 -``` - -Installs all packages from the group into an empty directory, then runs each package's `install_steps` inside a chroot. - ---- - -## Debug - -```sh -ROR_DEBUG=1 ror -i curl -``` - ---- - -## File Structure - -``` -/etc/ror/ -├── ror.conf # config -├── installed.json # installed package database -/var/ror/packages/ - ├── groups/ # group definitions - └── <category>/ - └── <pkg>/ - └── <pkg>.yaml -``` +Documentation is not available for this version. Please wait for the release. diff --git a/src/apply.rs b/src/apply.rs new file mode 100644 index 0000000..4e4ab44 --- /dev/null +++ b/src/apply.rs @@ -0,0 +1,183 @@ + +use std::collections::HashSet; +use std::fs; +use std::path::Path; +use colored::Colorize; +use serde::Deserialize; + +use crate::config::Config; +use crate::group; +use crate::install::{InstalledDB, load_package}; +use crate::parallel; +use crate::delete; + +const DEFAULT_CONFIG_PATH: &str = "/etc/ror/system.yaml"; + +#[derive(Debug, Deserialize)] +pub struct SystemConfig { + #[serde(default)] + pub roles: Roles, + #[serde(default)] + pub packages: Vec<String>, + #[serde(default)] + pub groups: Vec<String>, + #[serde(default)] + #[allow(dead_code)] + pub conflict_resolution: Option<String>, +} + +#[derive(Debug, Deserialize, Default)] +pub struct Roles { + pub init: Option<String>, + pub libc: Option<String>, + pub core: Option<String>, + pub udev: Option<String>, + pub sh: Option<Vec<String>>, + pub su: Option<Vec<String>>, +} + +fn resolve_single_role(pkg_name: &str, role: &str) -> Option<String> { + let pkg = load_package(pkg_name)?; + if pkg.provides.contains(&role.to_string()) { + Some(pkg_name.to_string()) + } else { + None + } +} + +fn resolve_list_role(candidates: &[String], role: &str) -> Option<String> { + for cand in candidates { + if let Some(pkg) = load_package(cand) { + if pkg.provides.contains(&role.to_string()) { + return Some(cand.clone()); + } + } + } + None +} + +pub fn get_target_packages(sys_config: &SystemConfig, _cfg: &Config) -> Result<Vec<String>, String> { + let mut target = HashSet::new(); + + if let Some(ref pkg) = sys_config.roles.init { + match resolve_single_role(pkg, "init-system") { + Some(name) => { target.insert(name); } + None => return Err(format!("Package '{}' does not provide init-system", pkg)), + } + } + if let Some(ref pkg) = sys_config.roles.libc { + match resolve_single_role(pkg, "libc") { + Some(name) => { target.insert(name); } + None => return Err(format!("Package '{}' does not provide libc", pkg)), + } + } + if let Some(ref pkg) = sys_config.roles.core { + match resolve_single_role(pkg, "core-utils") { + Some(name) => { target.insert(name); } + None => return Err(format!("Package '{}' does not provide core-utils", pkg)), + } + } + if let Some(ref pkg) = sys_config.roles.udev { + match resolve_single_role(pkg, "udev") { + Some(name) => { target.insert(name); } + None => return Err(format!("Package '{}' does not provide udev", pkg)), + } + } + if let Some(ref candidates) = sys_config.roles.sh { + match resolve_list_role(candidates, "sh") { + Some(name) => { target.insert(name); } + None => return Err("No package from sh list provides 'sh'".to_string()), + } + } + if let Some(ref candidates) = sys_config.roles.su { + match resolve_list_role(candidates, "su") { + Some(name) => { target.insert(name); } + None => return Err("No package from su list provides 'su'".to_string()), + } + } + + for pkg in &sys_config.packages { + target.insert(pkg.clone()); + } + + for group_name in &sys_config.groups { + let group = group::load_group(group_name) + .map_err(|e| format!("Failed to load group '{}': {}", group_name, e))?; + for pkg in group.packages { + target.insert(pkg); + } + } + + Ok(target.into_iter().collect()) +} + +fn resolve_dependencies(packages: &[String]) -> Result<Vec<String>, String> { + crate::rootfs::collect_install_order(packages) +} + +pub fn apply_system(cfg: &Config, dry_run: bool, custom_config: Option<&Path>) -> Result<(), String> { + let config_path = custom_config.unwrap_or_else(|| Path::new(DEFAULT_CONFIG_PATH)); + let content = fs::read_to_string(config_path) + .map_err(|e| format!("Failed to read {}: {}", config_path.display(), e))?; + let sys_config: SystemConfig = serde_yaml::from_str(&content) + .map_err(|e| format!("Invalid YAML: {}", e))?; + + let target_packages = get_target_packages(&sys_config, cfg)?; + let ordered = resolve_dependencies(&target_packages)?; + + let db = InstalledDB::load(); + let installed: HashSet<String> = db.packages.keys().cloned().collect(); + let target_set: HashSet<String> = ordered.iter().cloned().collect(); + + let to_install: Vec<String> = target_set.difference(&installed).cloned().collect(); + let to_remove: Vec<String> = installed.difference(&target_set).cloned().collect(); + + println!("{} System apply plan:", "[ror]".blue().bold()); + if to_install.is_empty() && to_remove.is_empty() { + println!("{} System is already in the desired state.", "[ror]".green()); + return Ok(()); + } + if !to_install.is_empty() { + println!("{} Install: {}", ">>>".green(), to_install.join(", ")); + } + if !to_remove.is_empty() { + println!("{} Remove: {}", ">>>".red(), to_remove.join(", ")); + } + + if dry_run { + println!("{} Dry run: no changes made.", "[ror]".yellow()); + return Ok(()); + } + + if !to_install.is_empty() { + let rt = tokio::runtime::Runtime::new() + .map_err(|e| format!("Failed to create async runtime: {}", e))?; + rt.block_on(parallel::install_packages_parallel( + &to_install, + std::sync::Arc::new(cfg.clone()), + ))?; + } + let mut skipped = Vec::new(); + for pkg in &to_remove { + let can_remove = delete::check_critical_removal(pkg, &db).is_ok() + && !delete::has_dependents(pkg, &db, &target_set); + if can_remove { + println!("{} Removing {}...", ">>>".cyan(), pkg); + delete::remove_package(pkg); + } else { + skipped.push(pkg.clone()); + } + } + + if !skipped.is_empty() { + println!( + "{} Skipped removal of {} (still required by other packages or protected): {}", + "[ror]".yellow().bold(), + skipped.len(), + skipped.join(", ") + ); + } + + println!("{} System apply completed.", "[ror]".green().bold()); + Ok(()) +} diff --git a/src/check.rs b/src/check.rs index a98afcb..9e9b775 100644 --- a/src/check.rs +++ b/src/check.rs @@ -146,7 +146,7 @@ pub fn check_integrity(cfg: &Config) { } } } - Ok(_) => {} // не файл (симлинк, папка) — пока не проверяем + Ok(_) => {} Err(_) => { missing.push(rel_path.clone()); } diff --git a/src/config.rs b/src/config.rs index ff83f01..c2d8cdb 100644 --- a/src/config.rs +++ b/src/config.rs @@ -72,6 +72,7 @@ pub struct SystemProfile { pub active_group: Option<String>, } +#[allow(dead_code)] impl SystemProfile { pub fn group_name(&self) -> Option<String> { if let Some(g) = &self.active_group { @@ -108,6 +109,7 @@ impl SystemProfile { list.push(new_pkg.to_string()); } } + #[allow(dead_code)] pub fn remove_from_list_role(&mut self, role: &str, pkg: &str) { let list = match role { @@ -215,11 +217,10 @@ impl Config { "parallel_downloads = 4\n", "arch = x86_64\n", "libc = glibc\n", - "\n", "[repositories.rorkos]\n", - "url = \"https://github.com/RorkOS/RorkOS_package\"\n", - "urlrepo = \"https://github.com/RorkOS/RorkOS_packages_bin/releases/download/latest/\"\n", - "mirror = \"https://github.com/rork-os/RorkOS_package\"\n", + "url = \"https://\"\n", + "urlrepo = \"https://\"\n", + "mirror = \"https://\"\n", "gpg_support = true\n", "gpg_key = \"rorka.pub\"\n", ); diff --git a/src/delete.rs b/src/delete.rs index a07690a..83164a3 100644 --- a/src/delete.rs +++ b/src/delete.rs @@ -3,12 +3,13 @@ use std::path::Path; use colored::Colorize; use crate::install::{load_package, Dependency, parse_dep, InstalledDB}; use crate::debug; +use std::collections::HashSet; const STRICT_ROLES: &[&str] = &["init-system", "libc", "core-utils", "udev"]; const MULTI_ROLES: &[&str] = &["sh", "su"]; fn check_dependents(pkg_name: &str, db: &InstalledDB) -> Result<(), String> { - debug!("check_dependents: checking reverse dependencies for '{}'", pkg_name); + debug!("Checking dependents for package {}", pkg_name); let mut dependents = Vec::new(); for (name, _) in &db.packages { @@ -16,42 +17,33 @@ fn check_dependents(pkg_name: &str, db: &InstalledDB) -> Result<(), String> { continue; } - debug!("check_dependents: examining installed package '{}'", name); - - if let Some(pkg) = load_package(name) { - for dep in &pkg.depends { - match dep { - Dependency::Single(raw) => { - let (dep_name, _) = parse_dep(raw); - debug!(" single dep: '{}'", dep_name); - if dep_name == pkg_name { - debug!(" -> '{}' depends on '{}'!", name, pkg_name); - dependents.push(name.clone()); - break; - } - } - Dependency::Any(alternatives) => { - debug!(" any deps: {:?}", alternatives); - for alt in alternatives { - let (dep_name, _) = parse_dep(alt); - debug!(" alt: '{}'", dep_name); + if let Some(pkg) = load_package(name) { + for dep in &pkg.depends { + match dep { + Dependency::Single(raw) => { + let (dep_name, _) = parse_dep(raw); if dep_name == pkg_name { - debug!(" -> '{}' depends on '{}' (via alt)!", name, pkg_name); + debug!("Found dependent: {}", name); dependents.push(name.clone()); break; } } + Dependency::Any(alternatives) => { + for alt in alternatives { + let (dep_name, _) = parse_dep(alt); + if dep_name == pkg_name { + debug!("Found dependent: {}", name); + dependents.push(name.clone()); + break; + } + } + } } } } - } else { - debug!("check_dependents: could not load package info for '{}'", name); - } - } if !dependents.is_empty() { - debug!("check_dependents: found dependents: {:?}", dependents); return Err(format!( "{} Cannot remove '{}': it is required by installed package(s): {}", "[ror]".red().bold(), @@ -60,11 +52,12 @@ fn check_dependents(pkg_name: &str, db: &InstalledDB) -> Result<(), String> { )); } - debug!("check_dependents: no dependents found for '{}'", pkg_name); + debug!("No dependents found for {}", pkg_name); Ok(()) } fn has_role(pkg_name: &str, role: &str) -> bool { + debug!("Checking if {} provides role {}", pkg_name, role); load_package(pkg_name) .map(|p| p.provides.contains(&role.to_string())) .unwrap_or(false) @@ -72,23 +65,19 @@ fn has_role(pkg_name: &str, role: &str) -> bool { pub fn critical_role_of(pkg_name: &str) -> Option<&'static str> { let pkg = load_package(pkg_name)?; + debug!("Searching critical role for {}", pkg_name); for &role in STRICT_ROLES.iter().chain(MULTI_ROLES.iter()) { if pkg.provides.contains(&role.to_string()) { + debug!("Package {} provides critical role: {}", pkg_name, role); return Some(role); } } None } -pub fn critical_role_of_from_recipe(pkg_name: &str) -> Option<&'static str> { - critical_role_of(pkg_name) -} - -pub fn is_strict_role(role: &str) -> bool { - STRICT_ROLES.contains(&role) -} pub fn check_critical_removal(pkg_name: &str, db: &InstalledDB) -> Result<(), String> { + debug!("Checking critical removal constraints for {}", pkg_name); let pkg = load_package(pkg_name).ok_or("Package info not found in repository")?; for &role in STRICT_ROLES { @@ -111,6 +100,7 @@ pub fn check_critical_removal(pkg_name: &str, db: &InstalledDB) -> Result<(), St .filter(|p| p.name != pkg_name && has_role(&p.name, role)) .count(); if others == 0 { + debug!("{} is the only provider of multi-role {}", pkg_name, role); return Err(format!( "{} CRITICAL: '{}' is your only provider of '{}'. Install an alternative first, or use --di to replace atomically.", "[ror]".red().bold(), @@ -120,10 +110,12 @@ pub fn check_critical_removal(pkg_name: &str, db: &InstalledDB) -> Result<(), St } } + debug!("Critical removal check passed for {}", pkg_name); Ok(()) } pub fn check_critical_removal_with_replacement(pkg_name: &str, replacement: &str, db: &InstalledDB) -> Result<(), String> { + debug!("Checking critical removal with replacement: {} → {}", pkg_name, replacement); let pkg = load_package(pkg_name).ok_or("Package info not found in repository")?; let replacement_pkg = load_package(replacement).ok_or("Replacement package not found in repository")?; @@ -136,6 +128,7 @@ pub fn check_critical_removal_with_replacement(pkg_name: &str, replacement: &str .filter(|p| p.name != pkg_name && has_role(&p.name, role)) .count(); if !replacement_covers && other_installed == 0 { + debug!("Replacement does not cover role {} and no other provider", role); return Err(format!( "{} CRITICAL: removing '{}' would leave the system without a '{}' provider, and '{}' does not provide it.", "[ror]".red().bold(), @@ -146,10 +139,12 @@ pub fn check_critical_removal_with_replacement(pkg_name: &str, replacement: &str } } + debug!("Critical removal with replacement check passed"); Ok(()) } pub fn check_critical_install(pkg_name: &str, db: &InstalledDB) -> Result<(), String> { + debug!("Checking critical install constraints for {}", pkg_name); let pkg = load_package(pkg_name).ok_or("Package info not found in repository")?; for &role in STRICT_ROLES { @@ -157,6 +152,7 @@ pub fn check_critical_install(pkg_name: &str, db: &InstalledDB) -> Result<(), St continue; } if let Some(existing) = db.packages.values().find(|p| has_role(&p.name, role)) { + debug!("Strict role {} already provided by {}", role, existing.name); return Err(format!( "{} CRITICAL: '{}' provides '{}', but '{}' already provides it. Use --di {} {} to replace it atomically.", "[ror]".red().bold(), @@ -169,47 +165,64 @@ pub fn check_critical_install(pkg_name: &str, db: &InstalledDB) -> Result<(), St } } + debug!("Critical install check passed"); Ok(()) } pub fn remove_package_files_only(_pkg_name: &str, files: &[String]) -> bool { + debug!("Removing {} files for package {}", files.len(), _pkg_name); let mut failed = false; for rel_path in files { let full_path = Path::new("/").join(rel_path); if full_path.exists() { + debug!("Removing file {}", full_path.display()); 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 { + debug!("File {} does not exist, skipping", full_path.display()); } } + if failed { + debug!("Some files could not be removed"); + } else { + debug!("All files removed successfully"); + } !failed } pub fn remove_package(pkg_name: &str) { + debug!("Starting removal of package {}", pkg_name); let mut db = InstalledDB::load(); let files: Vec<String> = match db.packages.get(pkg_name) { Some(r) => r.files.iter().cloned().collect(), None => { eprintln!("{} Package '{}' is not installed.", "[ror]".red().bold(), pkg_name); + debug!("Package not found in database"); return; } }; + debug!("Found {} files to remove", files.len()); + if let Err(e) = check_critical_removal(pkg_name, &db) { eprintln!("{}", e); + debug!("Critical removal check failed: {}", e); return; } if let Err(e) = check_dependents(pkg_name, &db) { eprintln!("{}", e); + debug!("Dependents check failed: {}", e); return; } + println!("{} Removing package '{}'...", "[ror]".blue().bold(), pkg_name); let success = remove_package_files_only(pkg_name, &files); @@ -219,6 +232,7 @@ pub fn remove_package(pkg_name: &str) { eprintln!("{} Failed to update installed DB: {}", "[ror]".red().bold(), e); } else { println!("{} Package '{}' removed from database.", "[ror]".green(), pkg_name); + debug!("Database updated"); } if !success { @@ -227,3 +241,39 @@ pub fn remove_package(pkg_name: &str) { println!("{} Package '{}' successfully removed.", "[ror]".green().bold(), pkg_name); } } + +pub fn has_dependents(pkg_name: &str, db: &InstalledDB, keep_set: &HashSet<String>) -> bool { + debug!("Checking if {} has dependents (excluding keep set)", pkg_name); + let mut deps = false; + for (name, _) in &db.packages { + if name == pkg_name || keep_set.contains(name) { + continue; + } + if let Some(pkg) = load_package(name) { + for dep in &pkg.depends { + match dep { + Dependency::Single(raw) => { + let (dep_name, _) = parse_dep(raw); + if dep_name == pkg_name { + debug!("Dependent found: {}", name); + deps = true; + } + } + Dependency::Any(alternatives) => { + for alt in alternatives { + let (dep_name, _) = parse_dep(alt); + if dep_name == pkg_name { + debug!("Dependent found: {}", name); + deps = true; + } + } + } + } + } + } + } + if !deps { + debug!("No dependents found"); + } + deps +} diff --git a/src/install.rs b/src/install.rs index a3bd400..3fe5c5c 100644 --- a/src/install.rs +++ b/src/install.rs @@ -120,7 +120,7 @@ fn default_install_prefix() -> String { "/".to_string() } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct InstalledPackage { pub name: String, pub version: String, @@ -138,15 +138,18 @@ impl InstalledDB { pub const PATH: &'static str = "/etc/ror/installed.json"; pub fn load() -> Self { + debug!("Loading installed package database from {}", Self::PATH); if Path::new(Self::PATH).exists() { let content = fs::read_to_string(Self::PATH).unwrap_or_default(); serde_json::from_str(&content).unwrap_or_default() } else { + debug!("No existing database found, starting fresh"); Self::default() } } pub fn save(&self) -> std::io::Result<()> { + debug!("Saving installed package database"); let json = serde_json::to_string_pretty(self) .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?; let path = Path::new(Self::PATH); @@ -157,6 +160,7 @@ impl InstalledDB { } pub fn add_package(&mut self, pkg: InstalledPackage) { + debug!("Registering {} in database", pkg.name); self.packages.insert(pkg.name.clone(), pkg); } @@ -166,6 +170,7 @@ impl InstalledDB { } fn sort_mirrors_by_speed(mirrors: &[String]) -> Vec<String> { + debug!("Sorting {} mirrors by response time", mirrors.len()); use std::time::Instant; let client = match Client::builder() .timeout(std::time::Duration::from_secs(5)) @@ -194,6 +199,7 @@ fn sort_mirrors_by_speed(mirrors: &[String]) -> Vec<String> { } pub fn extract_deb(archive_path: &Path, dest_root: &Path) -> Result<Vec<String>, String> { + debug!("Extracting .deb archive {:?} to {:?}", archive_path, dest_root); let file = fs::File::open(archive_path).map_err(|e| e.to_string())?; let mut archive = ar::Archive::new(file); let mut installed_files = Vec::new(); @@ -221,6 +227,7 @@ pub fn extract_deb(archive_path: &Path, dest_root: &Path) -> Result<Vec<String>, } } } + debug!("Deb extraction complete: {} files", installed_files.len()); Ok(installed_files) } @@ -249,6 +256,7 @@ fn normalize_libc(libc: &str) -> &str { pub fn select_binary_for_arch<'a>(pkg: &'a Package, arch: &str, libc: &str) -> Result<&'a BinaryPackage, String> { let target_arch = normalize_arch(arch); let target_libc = normalize_libc(libc); + debug!("Selecting binary for arch={}, libc={}", target_arch, target_libc); pkg.binaries .iter() @@ -269,6 +277,7 @@ pub fn select_binary_for_arch<'a>(pkg: &'a Package, arch: &str, libc: &str) -> R } pub fn find_package_file(pkg_name: &str) -> Option<PathBuf> { + debug!("Looking for package {} in repository root", pkg_name); let repo = Path::new(REPO_ROOT); let read_dir = fs::read_dir(repo).ok()?; @@ -280,6 +289,7 @@ pub fn find_package_file(pkg_name: &str) -> Option<PathBuf> { let pkg_path = cat_path.join(pkg_name).join(format!("{}.yaml", pkg_name)); if pkg_path.exists() && pkg_path.is_file() { + debug!("Found package at {:?}", pkg_path); return Some(pkg_path); } } @@ -287,6 +297,7 @@ pub fn find_package_file(pkg_name: &str) -> Option<PathBuf> { } pub fn find_package_with_repo(pkg_name: &str) -> Option<(PathBuf, String)> { + debug!("Searching for package {} with repository info", pkg_name); let repo = Path::new(REPO_ROOT); let read_dir = fs::read_dir(repo).ok()?; @@ -299,13 +310,15 @@ pub fn find_package_with_repo(pkg_name: &str) -> Option<(PathBuf, String)> { let pkg_path = cat_path.join(pkg_name).join(format!("{}.yaml", pkg_name)); if pkg_path.exists() && pkg_path.is_file() { let repo_name = cat_path.file_name()?.to_string_lossy().to_string(); + debug!("Found package in repo {}: {:?}", repo_name, pkg_path); return Some((pkg_path, repo_name)); } } None } -fn verify_gpg_signature(archive_path: &Path, asc_path: &Path, pubkey_path: &Path) -> Result<(), String> { +pub fn verify_gpg_signature(archive_path: &Path, asc_path: &Path, pubkey_path: &Path) -> Result<(), String> { + debug!("Verifying GPG signature for {:?}", archive_path); if !pubkey_path.exists() { return Err(format!( "GPG public key not found: {}", @@ -315,7 +328,7 @@ fn verify_gpg_signature(archive_path: &Path, asc_path: &Path, pubkey_path: &Path if !asc_path.exists() { return Err(format!( - "GPG signature not found: {} — cannot verify package", + "GPG signature not found: {} -- cannot verify package", asc_path.display() )); } @@ -354,6 +367,7 @@ fn verify_gpg_signature(archive_path: &Path, asc_path: &Path, pubkey_path: &Path let _ = fs::remove_file(tmp_keyring); if verify.status.success() { + debug!("GPG signature verification succeeded"); Ok(()) } else { Err(format!( @@ -365,6 +379,7 @@ fn verify_gpg_signature(archive_path: &Path, asc_path: &Path, pubkey_path: &Path } pub fn install_package(pkg_name: &str, cfg: &config::Config) { + debug!("Starting install of package: {}", pkg_name); match install_package_with_result(pkg_name, cfg) { Ok(installed_pkg) => { let mut db = InstalledDB::load(); @@ -383,20 +398,20 @@ pub fn install_package(pkg_name: &str, cfg: &config::Config) { } pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Result<InstalledPackage, String> { - debug!("install_package_with_result: start '{}'", pkg_name); + debug!("Resolving package {}", pkg_name); let mut spinner = Spinner::new(&format!("Resolving {}", pkg_name)); spinner.tick(&format!("Resolving {}", pkg_name)); let (pkg_path, repo_name) = find_package_with_repo(pkg_name) .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; - debug!("install_package_with_result: '{}' found in repo '{}' at {}", pkg_name, repo_name, pkg_path.display()); + debug!("Package file: {:?}, repository: {}", pkg_path, repo_name); let repo_cfg = cfg.repositories.get(&repo_name); let gpg_enabled = repo_cfg.map(|r| r.gpg_support).unwrap_or(false); let gpg_key = repo_cfg.and_then(|r| r.gpg_key.as_deref()); - debug!("install_package_with_result: repo='{}' gpg_enabled={} gpg_key={:?}", repo_name, gpg_enabled, gpg_key); + debug!("Repository config: GPG enabled = {}", gpg_enabled); if gpg_enabled && gpg_key.is_none() { return Err(format!( @@ -411,20 +426,19 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu let pkg: Package = serde_yaml::from_str(&content) .map_err(|e| format!("YAML structure error: {}", e))?; - debug!("install_package_with_result: '{}' version={} binaries={}", pkg_name, pkg.version, pkg.binaries.len()); + debug!("Loaded package metadata for {} version {}", pkg.name, pkg.version); if pkg.binaries.is_empty() { return Err("No binary packages defined".to_string()); } let binary = select_binary_for_arch(&pkg, &cfg.global.arch, &cfg.global.libc)?; - debug!("install_package_with_result: selected binary arch={} type={:?} libc={:?}", binary.arch, binary.pkg_type, binary.libc); + debug!("Selected binary: arch={}, libc={:?}", binary.arch, binary.libc); let db = InstalledDB::load(); for conflict in &pkg.conflicts { if db.is_installed(conflict) { - debug!("install_package_with_result: '{}' conflicts with '{}'", pkg_name, conflict); return Err(format!( "Package '{}' conflicts with installed package '{}'", pkg_name, conflict @@ -434,10 +448,8 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu let mut urls_to_try = Vec::new(); if !binary.url.is_empty() { - debug!("install_package_with_result: using direct url={}", binary.url); urls_to_try.push(binary.url.clone()); } else if !binary.mirrors.is_empty() { - debug!("install_package_with_result: building urls from mirrors"); urls_to_try = binary .mirrors .iter() @@ -459,14 +471,13 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu return Err(format!("Could not resolve any download URL for package {}", pkg_name)); } - debug!("install_package_with_result: '{}' urls={:?}", pkg_name, urls_to_try); + debug!("Resolved {} download URLs", urls_to_try.len()); if !cfg.global.ignore_speed && urls_to_try.len() > 1 { - debug!("install_package_with_result: testing mirror speeds for '{}'", pkg_name); spinner.tick("Testing mirror speeds..."); urls_to_try = sort_mirrors_by_speed(&urls_to_try); spinner.finish(&format!("Fastest mirror selected: {}", urls_to_try[0])); - debug!("install_package_with_result: fastest mirror={}", urls_to_try[0]); + debug!("Fastest mirror: {}", urls_to_try[0]); } let mut last_err = None; @@ -474,16 +485,16 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu let mut downloaded = false; for url in urls_to_try { - debug!("install_package_with_result: trying url={}", url); spinner.tick(&format!("Downloading {} ...", url.split('/').last().unwrap_or(&url))); + debug!("Downloading {}", url); let archive_path = match download_and_verify(&url, &binary.sha256, cfg) { Ok(p) => { - debug!("install_package_with_result: downloaded to {}", p.display()); + debug!("Download successful: {:?}", p); p } Err(e) => { - debug!("install_package_with_result: download failed: {}", e); + debug!("Download failed: {}", e); last_err = Some(e); continue; } @@ -493,13 +504,15 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu if gpg_enabled { let asc_url = format!("{}.asc", url); - spinner.tick(&format!("Downloading GPG signature...")); + spinner.tick("Downloading GPG signature..."); + debug!("Downloading GPG signature from {}", asc_url); let asc_path = match download_and_verify(&asc_url, "", cfg) { Ok(p) => p, Err(_) => { let _ = fs::remove_file(&archive_path); + debug!("GPG signature missing, aborting"); return Err(format!( - "GPG signature not found for '{}' at {} — installation aborted", + "GPG signature not found for {} at {} - installation aborted", pkg_name, asc_url )); } @@ -510,6 +523,7 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu if let Err(e) = verify_gpg_signature(&archive_path, &asc_path, &pubkey_path) { let _ = fs::remove_file(&archive_path); let _ = fs::remove_file(&asc_path); + debug!("GPG verification error: {}", e); return Err(e); } let _ = fs::remove_file(&asc_path); @@ -521,17 +535,20 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu fs::create_dir_all(&work_dir).map_err(|e| format!("Failed to create temp dir: {}", e))?; let pkg_type = binary.pkg_type.as_deref().unwrap_or("tar.xz"); + debug!("Package type: {}", pkg_type); let mut sp2 = Spinner::new(&format!("Extracting {}", pkg_name)); sp2.tick(&format!("Extracting {}...", pkg_name)); if pkg_type == "deb" { + debug!("Extracting deb package"); let mut files = extract_deb(&archive_path, Path::new("/"))?; all_installed_files.append(&mut files); } else if pkg_type == "ror" { let dict_url = binary.dict.as_ref() - .ok_or_else(|| format!("Package '{}' has type 'ror' but no dict URL", pkg_name))?; + .ok_or_else(|| format!("Package {} has type ror but no dict URL", pkg_name))?; sp2.tick(&format!("Downloading dictionary for {}...", pkg_name)); + debug!("Downloading dictionary: {}", dict_url); let dict_path = download_and_verify(dict_url, "", cfg)?; let files = extract_ror(&archive_path, &dict_path, &work_dir) .map_err(|e| format!("Extraction failed: {}", e))?; @@ -541,6 +558,7 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu .map_err(|e| format!("Failed to install files: {}", e))?; all_installed_files.append(&mut installed); } else if pkg_type == "sror" { + debug!("Extracting sror package"); let files = extract_sror(&archive_path, &work_dir) .map_err(|e| format!("Extraction failed: {}", e))?; sp2.tick(&format!("Installing files for {}...", pkg_name)); @@ -548,6 +566,7 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu .map_err(|e| format!("Failed to install files: {}", e))?; all_installed_files.append(&mut installed); } else { + debug!("Extracting native tar package"); let files = extract_native(&archive_path, &work_dir) .map_err(|e| format!("Extraction failed: {}", e))?; sp2.tick(&format!("Installing files for {}...", pkg_name)); @@ -557,29 +576,28 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu } sp2.finish(&format!("Installed {} files", all_installed_files.len())); + debug!("Total installed files: {}", all_installed_files.len()); let _ = fs::remove_dir_all(&work_dir); let _ = fs::remove_file(&archive_path); downloaded = true; - debug!("install_package_with_result: '{}' extracted {} files", pkg_name, all_installed_files.len()); break; } if !downloaded { - debug!("install_package_with_result: '{}' all mirrors failed", pkg_name); return Err(last_err.unwrap_or_else(|| "All mirrors/URLs failed".to_string())); } if !pkg.install_steps.is_empty() { - debug!("install_package_with_result: '{}' running install_steps", pkg_name); + debug!("Running install steps"); let mut sp3 = Spinner::new(&format!("Running install steps for {}", pkg_name)); sp3.tick(&format!("Running install steps for {}...", pkg_name)); run_commands(&pkg.install_steps, Path::new("/"))?; sp3.finish("Install steps done"); - debug!("install_package_with_result: '{}' install_steps done", pkg_name); } - debug!("install_package_with_result: '{}' complete v={} files={}", pkg_name, pkg.version, all_installed_files.len()); + debug!("Installation complete for {}", pkg_name); + Ok(InstalledPackage { name: pkg.name.clone(), version: pkg.version.clone(), @@ -590,6 +608,7 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu } pub fn download_and_verify(url: &str, expected_sha: &str, _cfg: &config::Config) -> Result<PathBuf, String> { + debug!("Downloading {} (expected SHA256: {})", url, if expected_sha.is_empty() { "none" } else { expected_sha }); let client = Client::builder() .connect_timeout(std::time::Duration::from_secs(30)) .build() @@ -642,7 +661,7 @@ pub fn download_and_verify(url: &str, expected_sha: &str, _cfg: &config::Config) Some(total) if total > 0 => { let pct = downloaded * 40 / total; let bar = format!( - "{}>{}", + "{}>{}", "=".repeat(pct.saturating_sub(1) as usize), " ".repeat((40 - pct) as usize) ); @@ -667,19 +686,21 @@ pub fn download_and_verify(url: &str, expected_sha: &str, _cfg: &config::Config) let hash = format!("{:x}", hasher.finalize()); if hash != expected_sha { let _ = fs::remove_file(&file_path); + debug!("SHA256 mismatch: expected {}, got {}", expected_sha, hash); return Err(format!( "SHA256 mismatch: expected {}, got {}", expected_sha, hash )); } + debug!("SHA256 verified successfully"); } } Ok(file_path) } - pub fn extract_native(archive_path: &Path, target_dir: &Path) -> Result<Vec<String>, String> { + debug!("Extracting native tar archive {:?} to {:?}", archive_path, target_dir); let status = Command::new("tar") .arg("-xf") .arg(archive_path) @@ -699,10 +720,12 @@ pub fn extract_native(archive_path: &Path, target_dir: &Path) -> Result<Vec<Stri files.push(rel_path.to_string_lossy().to_string()); } } + debug!("Extracted {} files/dirs", files.len()); Ok(files) } pub fn extract_ror(archive_path: &Path, dict_path: &Path, target_dir: &Path) -> Result<Vec<String>, String> { + debug!("Extracting .ror archive {:?} using dictionary {:?}", archive_path, dict_path); let zstd_arg = format!("zstd -D {}", dict_path.display()); let status = Command::new("tar") @@ -726,10 +749,12 @@ pub fn extract_ror(archive_path: &Path, dict_path: &Path, target_dir: &Path) -> files.push(rel_path.to_string_lossy().to_string()); } } + debug!("Extracted {} files from .ror", files.len()); Ok(files) } pub fn extract_sror(archive_path: &Path, target_dir: &Path) -> Result<Vec<String>, String> { + debug!("Extracting .sror archive {:?} to {:?}", archive_path, target_dir); let status = Command::new("tar") .arg("-I") .arg("zstd") @@ -751,10 +776,12 @@ pub fn extract_sror(archive_path: &Path, target_dir: &Path) -> Result<Vec<String files.push(rel_path.to_string_lossy().to_string()); } } + debug!("Extracted {} files from .sror", files.len()); Ok(files) } fn install_files(source_dir: &Path, prefix: &str, files: &[String]) -> Result<Vec<String>, String> { + debug!("Installing {} files from {:?} to prefix {}", files.len(), source_dir, prefix); let prefix_path = Path::new(prefix); let mut installed = Vec::new(); @@ -786,6 +813,7 @@ fn install_files(source_dir: &Path, prefix: &str, files: &[String]) -> Result<Ve } pub fn install_files_with_root(source_dir: &Path, root: &Path, files: &[String]) -> Result<Vec<String>, String> { + debug!("Installing {} files to root {:?}", files.len(), root); let mut installed = Vec::new(); for rel_path in files { let src = source_dir.join(rel_path); @@ -817,6 +845,7 @@ pub fn install_files_with_root(source_dir: &Path, root: &Path, files: &[String]) } pub fn run_commands(steps: &str, work_dir: &Path) -> Result<(), String> { + debug!("Running commands: {}", steps); if steps.trim().is_empty() { return Ok(()); } @@ -825,8 +854,9 @@ pub fn run_commands(steps: &str, work_dir: &Path) -> Result<(), String> { .arg("-c") .arg(steps) .status() - .map_err(|e| format!("Failed to execute 'sh -c': {}", e))?; + .map_err(|e| format!("Failed to execute sh -c: {}", e))?; if status.success() { + debug!("Commands executed successfully"); Ok(()) } else { Err(format!("Command failed with exit code {:?}", status.code())) @@ -834,6 +864,7 @@ pub fn run_commands(steps: &str, work_dir: &Path) -> Result<(), String> { } pub fn get_package_info(pkg_name: &str) -> Option<(String, String)> { + debug!("Getting info for package {}", pkg_name); let pkg_path = find_package_file(pkg_name)?; let content = fs::read_to_string(pkg_path).ok()?; let name = pkg_name.to_string(); @@ -847,12 +878,14 @@ pub fn get_package_info(pkg_name: &str) -> Option<(String, String)> { } pub fn load_package(pkg_name: &str) -> Option<Package> { + debug!("Loading full package metadata for {}", pkg_name); let pkg_path = find_package_file(pkg_name)?; let content = fs::read_to_string(pkg_path).ok()?; serde_yaml::from_str(&content).ok() } pub fn install_local_package(archive_path: &Path, cfg: &config::Config) { + debug!("Starting local install from {:?}", archive_path); match install_local_package_with_result(archive_path, cfg) { Ok(installed_pkg) => { let mut db = InstalledDB::load(); @@ -871,6 +904,7 @@ pub fn install_local_package(archive_path: &Path, cfg: &config::Config) { } pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Config) -> Result<InstalledPackage, String> { + debug!("Processing local package at {:?}", archive_path); if !archive_path.exists() { return Err(format!("File not found: {}", archive_path.display())); } @@ -880,6 +914,7 @@ pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Con let name = stem.to_string(); let version = "local".to_string(); + debug!("Local package: name={}, version={}, extension={}", name, version, ext); let work_dir = Path::new("/tmp/ror-local").join(&name); let _ = fs::remove_dir_all(&work_dir); @@ -889,6 +924,7 @@ pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Con spinner.tick(&format!("Extracting {}...", name)); let installed_files = if ext == "sror" { + debug!("Extracting local sror package"); let files = extract_sror(archive_path, &work_dir) .map_err(|e| format!("Extraction failed: {}", e))?; let installed = install_files_to_root(&work_dir, Path::new("/"), &files) @@ -902,6 +938,7 @@ pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Con dict_path.display() )); } + debug!("Extracting local ror package with dictionary"); let files = extract_ror(archive_path, &dict_path, &work_dir) .map_err(|e| format!("Extraction failed: {}", e))?; let installed = install_files_to_root(&work_dir, Path::new("/"), &files) @@ -912,6 +949,7 @@ pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Con }; spinner.finish(&format!("Installed {} files", installed_files.len())); + debug!("Local installation complete, {} files", installed_files.len()); let _ = fs::remove_dir_all(&work_dir); @@ -925,6 +963,7 @@ pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Con } fn install_files_to_root(source_dir: &Path, root: &Path, files: &[String]) -> Result<Vec<String>, String> { + debug!("Copying files from {:?} to root {:?}", source_dir, root); let mut installed = Vec::new(); for rel_path in files { let src = source_dir.join(rel_path); diff --git a/src/main.rs b/src/main.rs index 75e2920..609b899 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,7 @@ -use clap::Parser; -use std::path::{Path, PathBuf}; +use clap::{Parser, Subcommand}; use std::sync::Arc; -use std::thread; use colored::Colorize; +use std::path::{Path, PathBuf}; mod sync; mod install; @@ -19,101 +18,318 @@ mod search; mod repo; mod progress; mod check; +mod apply; +mod resolver; + +#[derive(Parser)] +#[command(name = "ror", about = "Ror package manager")] +struct Cli { + #[command(subcommand)] + command: Commands, +} + +#[derive(Subcommand)] +enum Commands { + + #[command(alias = "i")] + Install { + #[arg(required = true)] + packages: Vec<String>, + }, + + #[command(alias = "lg")] + ListGroups, + + #[command(alias = "s")] + Sync, + + #[command(alias = "d")] + Delete { + package: String, + }, + + #[command(alias = "l")] + ListInstalled, + + Info { + package: String, + }, + + Update { + package: String, + #[arg(long)] + dry_run: bool, + }, + + #[command(alias = "u")] + Upgrade, + + Search { + query: String, + }, + + RepoAdd { + name: String, + url: String, + mirror: Option<String>, + }, + + RepoRemove { + name: String, + }, + + RepoList, + + BuildRootfs { + #[arg(long)] + group: Option<String>, + #[arg(long)] + target: PathBuf, + #[arg(long, default_value = "native")] + arch: String, + #[arg(long)] + config: Option<PathBuf>, + }, + + Di { + delete: String, + install: String, + }, + + #[command(alias = "a")] + Apply { + #[arg(long)] + dry_run: bool, + #[arg(long)] + config: Option<PathBuf>, + }, + + Check, + + GenConfig, + + Version, +} -#[derive(Parser, Debug)] -#[command(author, about, arg_required_else_help = true)] -struct Args { - #[arg(long = "search", value_name = "QUERY")] - search: Option<String>, +#[tokio::main] +async fn main() { + let cli = Cli::parse(); + + match cli.command { + Commands::Version => { + println!("ror {}", env!("CARGO_PKG_VERSION")); + } - #[arg(short = 's', long = "sync")] - sync: bool, + Commands::GenConfig => { + let config_path = Path::new("/etc/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 + ), + } + } - #[arg(short = 'd', long = "delete", value_name = "PACKAGE")] - delete: Option<String>, + Commands::Sync => { + let cfg = config::Config::load(); + sync::run_sync(&cfg); + } - #[arg(short = 'l', long = "list-installed")] - listinstalled: bool, + Commands::ListGroups => { + group::list_groups(); + } - #[arg(long = "info", value_name = "PACKAGE")] - info: Option<String>, + Commands::ListInstalled => { + listinstalled::print_installed(); + } - #[arg(short = 'v', long = "version")] - version: bool, + Commands::Info { package } => { + info::print_package_info(&package); + } - #[arg(short = 'g', long = "gen-config")] - gen_config: bool, + Commands::Delete { package } => { + delete::remove_package(&package); + } - #[arg(short = 'i', long = "install", value_name = "PACKAGE_OR_GROUP", num_args = 1..)] - install: Vec<String>, + Commands::Search { query } => { + search::search_packages(&query); + } - #[arg(long = "update", value_name = "PACKAGE")] - update: Option<String>, + Commands::Update { package, dry_run } => { + let cfg = config::Config::load(); + update::update_package(&package, &cfg, dry_run); + } - #[arg(long = "dry-run")] - dry_run: bool, - - #[arg(short = 'u', long = "upgrade")] - upgrade: bool, + Commands::Upgrade => { + let cfg = config::Config::load(); + if let Err(e) = update::upgrade_system(&cfg) { + eprintln!("{} Upgrade failed: {}", "[ror]".red().bold(), e); + } + } - #[arg(long = "up", value_name = "GROUP")] - upgrade_to: Option<String>, + Commands::RepoAdd { name, url, mirror } => { + if let Err(e) = repo::add_repository(&name, &url, mirror.as_deref()) { + eprintln!("{} {}", "[ror]".red().bold(), e); + } + } - #[arg(long = "repo-add", value_names = ["NAME", "URL"])] - repo_add: Option<Vec<String>>, + Commands::RepoRemove { name } => { + if let Err(e) = repo::remove_repository(&name) { + eprintln!("{} {}", "[ror]".red().bold(), e); + } + } - #[arg(long = "repo-remove", value_name = "NAME")] - repo_remove: Option<String>, + Commands::RepoList => { + repo::list_repositories(); + } - #[arg(long = "repo-list")] - repo_list: bool, + Commands::BuildRootfs { group, target, arch, config } => { + let cfg = config::Config::load(); + let arch = if arch == "native" { "native" } else { &arch }; + if let Err(e) = rootfs::build_rootfs( + group.as_deref(), + &target, + &cfg, + arch, + true, + config.as_deref(), + ) { + eprintln!("{} {}", "[ror]".red().bold(), e); + } + } - #[arg(long = "build-rootfs")] - build_rootfs: bool, + Commands::Di { delete, install } => { + let cfg = Arc::new(config::Config::load()); + run_di(delete, install, cfg); + } - #[arg(long = "rootfs-group", value_name = "GROUP")] - rootfs_group: Option<String>, + Commands::Apply { dry_run, config } => { + let cfg = config::Config::load(); + if let Err(e) = apply::apply_system(&cfg, dry_run, config.as_deref()) { + eprintln!("{} {}", "[ror]".red().bold(), e); + } + } - #[arg(long = "rootfs-target", value_name = "TARGET")] - rootfs_target: Option<PathBuf>, + Commands::Check => { + let cfg = config::Config::load(); + check::check_integrity(&cfg); + } - #[arg(long = "rootfs-arch", default_value = "native")] - rootfs_arch: String, + Commands::Install { packages } => { + let cfg = Arc::new(config::Config::load()); + let db = install::InstalledDB::load(); - #[arg(long = "di", value_names = ["DELETE", "INSTALL"], num_args = 2)] - delete_install: Option<Vec<String>>, + + for pkg_name in &packages { + if pkg_name.starts_with('@') { + continue; + } + let is_local = pkg_name.starts_with('/') + || pkg_name.starts_with("./") + || pkg_name.ends_with(".ror") + || pkg_name.ends_with(".sror"); + if is_local { + continue; + } + if let Err(e) = delete::check_critical_install(pkg_name, &db) { + eprintln!("{}", e); + return; + } + } - #[arg(long = "lg", alias = "listgroups")] - listgroups: bool, + if packages[0].starts_with('@') { + + let group_name = &packages[0][1..]; + match group::load_group(group_name) { + Ok(group) => { + if let Err(e) = parallel::install_packages_parallel( + &group.packages, + Arc::clone(&cfg), + ) + .await + { + eprintln!("{} {}", "[ror]".red().bold(), e); + } + } + Err(e) => eprintln!("{} {}", "[ror]".red().bold(), e), + } + } else { + + let (local_pkgs, remote_pkgs): (Vec<String>, Vec<String>) = packages + .iter() + .cloned() + .partition(|p| { + p.starts_with('/') + || p.starts_with("./") + || p.ends_with(".ror") + || p.ends_with(".sror") + }); + + + for path_str in &local_pkgs { + install::install_local_package( + std::path::Path::new(path_str), + &cfg, + ); + } - #[arg(long = "check")] - check: bool, + + if !remote_pkgs.is_empty() { + if let Err(e) = parallel::install_packages_parallel( + &remote_pkgs, + Arc::clone(&cfg), + ) + .await + { + eprintln!("{} {}", "[ror]".red().bold(), e); + } + } + } + } + } } fn run_di(del_pkg: String, inst_pkg: String, cfg: Arc<config::Config>) { let db = install::InstalledDB::load(); if !db.is_installed(&del_pkg) { - eprintln!("{} Package '{}' is not installed.", "[ror]".red().bold(), del_pkg); + eprintln!( + "{} Package '{}' is not installed.", + "[ror]".red().bold(), + del_pkg + ); return; } let del_role = delete::critical_role_of(&del_pkg); - let inst_role = delete::critical_role_of_from_recipe(&inst_pkg); + let inst_role = delete::critical_role_of(&inst_pkg); if let Some(dr) = del_role { match inst_role { None => { eprintln!( "{} '{}' provides critical role '{}' but '{}' does not. Replacement rejected.", - "[ror]".red().bold(), del_pkg, dr, inst_pkg + "[ror]".red().bold(), + del_pkg, + dr, + inst_pkg ); return; } Some(ir) if ir != dr => { eprintln!( "{} Role mismatch: '{}' is '{}' but '{}' is '{}'. Roles must match.", - "[ror]".red().bold(), del_pkg, dr, inst_pkg, ir + "[ror]".red().bold(), + del_pkg, + dr, + inst_pkg, + ir ); return; } @@ -121,7 +337,9 @@ fn run_di(del_pkg: String, inst_pkg: String, cfg: Arc<config::Config>) { } } - if let Err(e) = delete::check_critical_removal_with_replacement(&del_pkg, &inst_pkg, &db) { + if let Err(e) = + delete::check_critical_removal_with_replacement(&del_pkg, &inst_pkg, &db) + { eprintln!("{}", e); return; } @@ -133,234 +351,64 @@ fn run_di(del_pkg: String, inst_pkg: String, cfg: Arc<config::Config>) { } } - let record_files = db.packages.get(&del_pkg).map(|r| r.files.clone()).unwrap_or_default(); - - let full_rebuild = del_role.map(|r| matches!(r, "libc" | "core-utils" | "udev")).unwrap_or(false); + let record_files = db + .packages + .get(&del_pkg) + .map(|r| r.files.clone()) + .unwrap_or_default(); - println!("{} Replacing '{}' with '{}'...", "[ror]".blue().bold(), del_pkg, inst_pkg); - - if full_rebuild { - println!("{} Critical role '{}' — running parallel replace + full system rebuild", ">>>".yellow(), del_role.unwrap()); - } + println!( + "{} Replacing '{}' with '{}'...", + "[ror]".blue().bold(), + del_pkg, + inst_pkg + ); let del_pkg_c = del_pkg.clone(); let inst_pkg_c = inst_pkg.clone(); let cfg_c = Arc::clone(&cfg); - let del_handle = thread::spawn(move || { + let del_handle = std::thread::spawn(move || { delete::remove_package_files_only(&del_pkg_c, &record_files) }); - let inst_handle = thread::spawn(move || { + let inst_handle = std::thread::spawn(move || { install::install_package_with_result(&inst_pkg_c, &cfg_c) }); let del_ok = del_handle.join().unwrap_or(false); - let inst_result = inst_handle.join().unwrap_or_else(|_| Err("panicked".to_string())); + let inst_result = inst_handle + .join() + .unwrap_or_else(|_| Err("panicked".to_string())); let mut db = install::InstalledDB::load(); - if del_ok { db.packages.remove(&del_pkg); } - match inst_result { - Ok(p) => { db.add_package(p); } - Err(e) => { eprintln!("{} Failed to install '{}': {}", "[ror]".red().bold(), inst_pkg, e); } - } - if let Err(e) = db.save() { - eprintln!("{} Failed to save DB: {}", "[ror]".red().bold(), e); - return; - } if del_ok { - if let Some(role) = del_role { - let mut sys_cfg = config::Config::load(); - if delete::is_strict_role(role) { - sys_cfg.profile.set_single_role(role, &inst_pkg); - } else { - sys_cfg.profile.replace_in_list_role(role, &del_pkg, &inst_pkg); - } - if let Err(e) = sys_cfg.save() { - eprintln!("{} Failed to update profile: {}", "[ror]".yellow().bold(), e); - } else { - println!("{} Profile updated: {} = {}", "[ror]".cyan().bold(), role, inst_pkg); - if let Some(name) = sys_cfg.profile.group_name() { - println!("{} Active group: {}", "[ror]".cyan(), name.cyan()); - if full_rebuild { - println!("{} Running full system rebuild...", ">>>".yellow()); - let recipe = PathBuf::from(format!("/var/ror/packages/groups/{}.yaml", name)); - update::rebuild_from_recipe(&recipe, &sys_cfg); - } - } - } - } - } - - println!("{} Replace finished: '{}' -> '{}'", "[ror]".green().bold(), del_pkg, inst_pkg); -} - -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("/etc/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(di_args) = args.delete_install { - run_di(di_args[0].clone(), di_args[1].clone(), cfg); - return; - } - - 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() { - let db = install::InstalledDB::load(); - for pkg_name in &args.install { - if pkg_name.starts_with('@') { continue; } - let is_local = pkg_name.starts_with('/') || pkg_name.starts_with("./") - || pkg_name.ends_with(".ror") || pkg_name.ends_with(".sror"); - if is_local { continue; } - if let Err(e) = delete::check_critical_install(pkg_name, &db) { - eprintln!("{}", e); - return; - } - } - - 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 { - let (local_pkgs, remote_pkgs): (Vec<String>, Vec<String>) = args.install.iter() - .cloned() - .partition(|p| { - p.starts_with('/') || p.starts_with("./") - || p.ends_with(".ror") || p.ends_with(".sror") - }); - for path_str in &local_pkgs { - install::install_local_package(std::path::Path::new(path_str), &cfg); - } - if !remote_pkgs.is_empty() { - if let Err(e) = parallel::install_packages_parallel(&remote_pkgs, Arc::clone(&cfg)) { - eprintln!("{} {}", "[ror]".red().bold(), e); - } - } - } - return; - } - - if args.upgrade { - if let Err(e) = update::upgrade_system(&cfg) { - eprintln!("{} Upgrade failed: {}", "[ror]".red().bold(), e); - } - return; - } - - if let Some(group_name) = args.upgrade_to { - let recipe = PathBuf::from(format!("/var/ror/packages/groups/{}.yaml", group_name)); - if !recipe.exists() { - eprintln!("{} Group '{}' not found at {}", "[ror]".red().bold(), group_name, recipe.display()); - return; - } - let mut sys_cfg = config::Config::load(); - sys_cfg.profile.active_group = Some(group_name.clone()); - if let Err(e) = sys_cfg.save() { - eprintln!("{} Failed to save profile: {}", "[ror]".red().bold(), e); - return; - } - println!("{} Profile set to group: {}", "[ror]".cyan().bold(), group_name.cyan()); - println!("{} Upgrading system...", ">>>".yellow()); - update::rebuild_from_recipe(&recipe, &sys_cfg); - return; - } - - if args.repo_list { - repo::list_repositories(); - return; - } - - if let Some(repo_args) = args.repo_remove { - if let Err(e) = repo::remove_repository(&repo_args) { - eprintln!("{} {}", "[ror]".red().bold(), e); - } - return; + db.packages.remove(&del_pkg); } - if let Some(repo_args) = args.repo_add { - if repo_args.len() < 2 { - eprintln!("{} Usage: --repo-add <name> <url> [mirror]", "[ror]".red().bold()); - return; + match inst_result { + Ok(p) => { + db.add_package(p); } - 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); + Err(e) => { + eprintln!( + "{} Failed to install '{}': {}", + "[ror]".red().bold(), + inst_pkg, + e + ); } - return; } - if let Some(pkg) = args.update { - update::update_package(&pkg, &cfg, args.dry_run); - return; + if let Err(e) = db.save() { + eprintln!("{} Failed to save DB: {}", "[ror]".red().bold(), e); } - if args.listgroups { - group::list_groups(); - return; - } - if args.check { - check::check_integrity(&cfg); - return; - } + println!( + "{} Replace finished: '{}' -> '{}'", + "[ror]".green().bold(), + del_pkg, + inst_pkg + ); } diff --git a/src/parallel.rs b/src/parallel.rs index b8b201b..fbbbcfe 100644 --- a/src/parallel.rs +++ b/src/parallel.rs @@ -1,480 +1,425 @@ -use std::collections::{HashMap, HashSet, VecDeque}; +// parallel.rs +// Asynchronous package installation with race conditions, atomic updates. + +#![allow(dead_code)] +#![allow(unused_imports)] +#![allow(unused_variables)] + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; -use std::thread; -use crate::config::Config; -use crate::install::{self, Dependency, InstalledDB, load_package, parse_dep, version_satisfies, get_package_info}; +use std::time::Duration; +use std::io::Write; + use colored::Colorize; -use crate::debug; +use futures::StreamExt; +use sha2::{Digest, Sha256}; +use tokio::sync::oneshot; +use tokio::task; +use tokio::time::timeout; +use tempfile::NamedTempFile; + +use crate::config::Config; +use crate::install::{ + extract_deb, extract_ror, extract_sror, extract_native, + select_binary_for_arch, InstalledDB, InstalledPackage, Package, + find_package_with_repo, verify_gpg_signature, +}; +use crate::resolver; + +/*global cache for package metadata to avoid repeated yaml parsing. */ +static PACKAGE_CACHE: once_cell::sync::Lazy<Mutex<HashMap<String, Arc<Package>>>> = + once_cell::sync::Lazy::new(|| Mutex::new(HashMap::new())); + +/*flag to detect user interruption. */ +static INTERRUPTED: AtomicBool = AtomicBool::new(false); + +pub fn load_package_cached(name: &str) -> Option<Arc<Package>> { + let mut cache = PACKAGE_CACHE.lock().unwrap(); + if let Some(pkg) = cache.get(name) { + return Some(Arc::clone(pkg)); + } -type Result<T> = std::result::Result<T, String>; + let path = crate::install::find_package_file(name)?; + let content = std::fs::read_to_string(path).ok()?; + let pkg = serde_yaml::from_str::<Package>(&content).ok()?; -struct DependencyGraph { - edges: HashMap<String, Vec<String>>, - reverse: HashMap<String, Vec<String>>, + let arc = Arc::new(pkg); + cache.insert(arc.name.clone(), Arc::clone(&arc)); + Some(arc) } -impl DependencyGraph { - fn new() -> Self { - debug!("DependencyGraph::new()"); - Self { edges: HashMap::new(), reverse: HashMap::new() } +impl InstalledDB { + pub fn save_atomic(&self, path: &Path) -> std::io::Result<()> { + let json = serde_json::to_string_pretty(self)?; + let dir = path.parent().unwrap(); + let mut tmp_file = NamedTempFile::new_in(dir)?; + tmp_file.write_all(json.as_bytes())?; + tmp_file.persist(path)?; + Ok(()) } +} + +struct AtomicInstaller { + shadow: tempfile::TempDir, +} - 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); +impl AtomicInstaller { + fn new(shadow: tempfile::TempDir) -> Self { + Self { shadow } } - fn compute_levels(&self) -> Vec<Vec<String>> { - debug!("DependencyGraph::compute_levels: start, edges={}", self.edges.len()); - 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 zero-degree queue size={}", queue.len()); - while !queue.is_empty() { - let level_pkgs: Vec<String> = queue.drain(..).collect(); - debug!("compute_levels: level {} packages={:?}", 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; - debug!("compute_levels: {} in_degree -> {}", child, deg); - if *deg == 0 { - debug!("compute_levels: {} ready, adding to queue", child); - queue.push_back(child.clone()); - } - } - } - } + fn commit( + self, + files: &[String], + src_dir: &Path, + target_root: &str, + ) -> Result<Vec<String>, String> { + let prefix = Path::new(target_root); + let mut installed = Vec::new(); + let mut backup_paths: Vec<(PathBuf, PathBuf)> = Vec::new(); + + for rel_path in files { + let src = src_dir.join(rel_path); + let dst = prefix.join(rel_path); + + if !src.exists() { + continue; } - } - 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: CYCLE detected among: {:?}", cyclic); - } - debug!("compute_levels: total levels={}", levels.len()); - levels - } -} -#[allow(dead_code)] -fn dep_name(raw: &str) -> String { - let (name, _) = parse_dep(raw); - name -} + let parent = dst.parent().ok_or("Invalid path")?; + std::fs::create_dir_all(parent) + .map_err(|e| format!("Create parent {}: {}", parent.display(), e))?; -fn is_dep_satisfied(raw: &str, db: &InstalledDB) -> bool { - let (name, constraint) = parse_dep(raw); - match db.packages.get(&name) { - None => { - debug!("is_dep_satisfied: '{}' not installed", name); - false - } - Some(installed) => { - match constraint { - None => { - debug!("is_dep_satisfied: '{}' installed (no version req)", name); - true + let bak_path = dst.with_extension("ror-old"); + if dst.exists() && dst.is_file() { + if let Err(e) = std::fs::rename(&dst, &bak_path) { + return Err(format!("Cannot backup {}: {}", dst.display(), e)); } - Some(c) => { - let ok = version_satisfies(&installed.version, &c); - debug!( - "is_dep_satisfied: '{}' installed={} required={:?}{} ok={}", - name, installed.version, c.op, c.version, ok - ); - ok + backup_paths.push((bak_path, dst.clone())); + } + + if let Err(e) = std::fs::rename(&src, &dst) { + if let Some((last_bak, orig)) = backup_paths.pop() { + let _ = std::fs::rename(&last_bak, &orig); } + return Err(format!("Failed to install {}: {}", dst.display(), e)); } + + installed.push(rel_path.clone()); } - } -} -fn needs_update(raw: &str, db: &InstalledDB) -> bool { - let (name, constraint) = parse_dep(raw); - match db.packages.get(&name) { - None => false, - Some(installed) => match constraint { - None => false, - Some(c) => { - let ok = version_satisfies(&installed.version, &c); - if !ok { - debug!("needs_update: '{}' installed={} fails {:?}{}", name, installed.version, c.op, c.version); - } - !ok + for (bak, _) in backup_paths { + if bak.exists() { + let _ = std::fs::remove_file(&bak); } - }, + } + + Ok(installed) } } -fn collect_required_packages( - packages: &[String], - installed_db: &InstalledDB, - outdated: &mut HashSet<String>, -) -> Result<HashSet<String>> { - debug!("collect_required_packages: start with {:?}", 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 required.contains(&pkg_name) { - debug!("collect_required_packages: '{}' already in required set, skip", pkg_name); - continue; +async fn download_one(url: &str, expected_sha: &str, _cfg: &Config) -> Result<PathBuf, String> { + let result = timeout(Duration::from_secs(60), async { + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(30)) + .build() + .map_err(|e| format!("HTTP client builder: {}", e))?; + + let res = client + .get(url) + .send() + .await + .map_err(|e| e.to_string())?; + + if !res.status().is_success() { + return Err(format!("HTTP {} for {}", res.status(), url)); } - if installed_db.is_installed(&pkg_name) { - let needs_ver_update = get_package_info(&pkg_name).map(|(_, avail)| { - let inst_ver = &installed_db.packages[&pkg_name].version; - let newer = avail != *inst_ver && avail > *inst_ver; - debug!("collect_required_packages: '{}' installed={} available={} newer={}", pkg_name, inst_ver, avail, newer); - newer - }).unwrap_or(false); - - if needs_ver_update { - debug!("collect_required_packages: '{}' outdated, queuing for update", pkg_name); - outdated.insert(pkg_name.clone()); - required.insert(pkg_name.clone()); - } else { - debug!("collect_required_packages: '{}' up-to-date, skip", pkg_name); - let pkg = match load_package(&pkg_name) { - Some(p) => p, - None => continue, - }; - for dep in &pkg.depends { - match dep { - Dependency::Single(raw) => { - if needs_update(raw, installed_db) { - let (name, _) = parse_dep(raw); - debug!("collect_required_packages: dep '{}' of '{}' is outdated", name, pkg_name); - outdated.insert(name.clone()); - if !required.contains(&name) { stack.push(name); } - } - } - Dependency::Any(alts) => { - for alt in alts { - if needs_update(alt, installed_db) { - let (name, _) = parse_dep(alt); - debug!("collect_required_packages: alt dep '{}' of '{}' is outdated", name, pkg_name); - outdated.insert(name.clone()); - if !required.contains(&name) { stack.push(name); } - } - } - } - } - } - continue; - } - } else { - required.insert(pkg_name.clone()); - } + let tmp_dir = Path::new("/tmp/ror-download"); + std::fs::create_dir_all(tmp_dir).map_err(|e| e.to_string())?; + let file_name = url.rsplit('/').next().unwrap_or("archive.tmp"); + let file_path = tmp_dir.join(file_name); - let pkg = match load_package(&pkg_name) { - Some(p) => p, - None => { - debug!("collect_required_packages: '{}' not found in repo", pkg_name); - return Err(format!("Package '{}' not found", pkg_name)); - } - }; - - debug!("collect_required_packages: '{}' has {} deps", pkg_name, pkg.depends.len()); - - for dep in &pkg.depends { - match dep { - Dependency::Single(raw) => { - let (name, _) = parse_dep(raw); - debug!("collect_required_packages: single dep '{}' for '{}'", raw, pkg_name); - if !is_dep_satisfied(raw, installed_db) && !required.contains(&name) { - debug!("collect_required_packages: queuing dep '{}'", name); - stack.push(name); - } - } - Dependency::Any(alternatives) => { - debug!("collect_required_packages: any dep {:?} for '{}'", alternatives, pkg_name); - let satisfied = alternatives.iter().any(|a| is_dep_satisfied(a, installed_db)); - if satisfied { - debug!("collect_required_packages: any dep already satisfied for '{}'", pkg_name); - continue; - } - if let Some(first) = alternatives.first() { - let (name, _) = parse_dep(first); - debug!("collect_required_packages: choosing first alt '{}' for '{}'", name, pkg_name); - if !required.contains(&name) { stack.push(name); } - } else { - return Err(format!("Empty alternative list in package '{}'", pkg_name)); - } - } + let mut file = std::fs::File::create(&file_path).map_err(|e| e.to_string())?; + let mut hasher = Sha256::new(); + + let body = res.bytes().await.map_err(|e| e.to_string())?; + hasher.update(&body); + file.write_all(&body).map_err(|e| e.to_string())?; + + drop(file); + + if !expected_sha.is_empty() { + let hash = format!("{:x}", hasher.finalize()); + if hash != expected_sha { + let _ = std::fs::remove_file(&file_path); + return Err(format!( + "SHA256 mismatch: expected {}, got {}", + expected_sha, hash + )); } } - } - debug!("collect_required_packages: required={:?} outdated={:?}", required, outdated); - Ok(required) + Ok(file_path) + }) + .await + .unwrap_or_else(|_| Err("Download timed out".into())); + + result } -fn build_graph(packages: &HashSet<String>, installed_db: &InstalledDB) -> Result<DependencyGraph> { - debug!("build_graph: building 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: '{}' not found", pkg_name); - return Err(format!("Package '{}' not found", pkg_name)); - } - }; - - for dep in &pkg.depends { - match dep { - Dependency::Single(raw) => { - let (name, _) = parse_dep(raw); - if packages.contains(&name) { - debug!("build_graph: edge {} -> {}", pkg_name, name); - graph.add_dep(pkg_name.clone(), name.clone()); - } else if !is_dep_satisfied(raw, installed_db) { - debug!("build_graph: missing dep '{}' for '{}'", name, pkg_name); - return Err(format!("Dependency '{}' of '{}' is missing or unsatisfied", raw, pkg_name)); - } else { - debug!("build_graph: dep '{}' already satisfied outside graph", name); - } - } - Dependency::Any(alternatives) => { - debug!("build_graph: any dep {:?} for '{}'", alternatives, pkg_name); - let found = alternatives.iter().find(|a| { - let (n, _) = parse_dep(a); - packages.contains(&n) - }); - if let Some(chosen) = found { - let (name, _) = parse_dep(chosen); - debug!("build_graph: choosing alt '{}' for '{}'", name, pkg_name); - graph.add_dep(pkg_name.clone(), name.clone()); - } else { - let satisfied = alternatives.iter().any(|a| is_dep_satisfied(a, installed_db)); - if !satisfied { - debug!("build_graph: no available alt for '{}'", pkg_name); - return Err(format!("No alternative from {:?} for '{}' is available", alternatives, pkg_name)); - } - debug!("build_graph: alt dep for '{}' satisfied outside graph", pkg_name); +/*race-condition download: tries all mirrors and returns the first success. */ +async fn race_download( + urls: Vec<String>, + expected_sha: &str, + cfg: Arc<Config>, +) -> Result<(PathBuf, String), String> { + if urls.len() == 1 { + let p = download_one(&urls[0], expected_sha, &cfg).await?; + return Ok((p, urls[0].clone())); + } + + let (tx, rx) = oneshot::channel::<Result<(PathBuf, String), String>>(); + let tx = Arc::new(Mutex::new(Some(tx))); + let mut handles = Vec::new(); + + for url in urls { + let tx_clone = Arc::clone(&tx); + let cfg_clone = cfg.clone(); + let sha = expected_sha.to_string(); + + handles.push(task::spawn(async move { + match download_one(&url, &sha, &cfg_clone).await { + Ok(path) => { + let mut guard = tx_clone.lock().unwrap(); + if let Some(sender) = guard.take() { + let _ = sender.send(Ok((path, url))); } } + Err(_) => {} } - } + })); } - debug!("build_graph: done, graph has {} nodes", graph.edges.len()); - Ok(graph) + match rx.await { + Ok(Ok((path, win_url))) => { + for h in handles { + h.abort(); + } + Ok((path, win_url)) + } + _ => Err("All mirrors failed".into()), + } } -fn check_conflicts(required: &HashSet<String>, installed_db: &InstalledDB) -> Result<()> { - debug!("check_conflicts: checking {} packages", required.len()); - let mut pkg_map = HashMap::new(); +async fn install_single_impl( + pkg_name: &str, + cfg: Arc<Config>, +) -> Result<InstalledPackage, String> { + println!("[{}] Resolving {}...", "[ror]".cyan().bold(), pkg_name); - for pkg_name in required { - let pkg = match load_package(pkg_name) { - Some(p) => p, - None => { - debug!("check_conflicts: '{}' not found", pkg_name); - return Err(format!("Package '{}' not found", pkg_name)); - } - }; - pkg_map.insert(pkg_name.clone(), pkg); - } + let start_time = std::time::Instant::now(); - 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 pkg = load_package_cached(pkg_name) + .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; + + let (_, repo_name) = find_package_with_repo(pkg_name) + .ok_or_else(|| format!("Repository info not found for {}", pkg_name))?; + let repo_cfg = cfg.repositories.get(&repo_name); + + let binary = select_binary_for_arch(&pkg, &cfg.global.arch, &cfg.global.libc)?; + + let mut urls = Vec::new(); + if !binary.url.is_empty() { + urls.push(binary.url.clone()); + } else { + for m in &binary.mirrors { + let url = m.replace("{filename}", &binary.filename); + if url.starts_with("http") { + urls.push(url); } } } - 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 each other", a, b); - return Err(format!("Packages '{}' and '{}' conflict with each other", a, b)); - } - } + if urls.is_empty() { + return Err("No download URLs provided".to_string()); } - debug!("check_conflicts: no conflicts"); - Ok(()) -} + println!("[{}] Downloading {}...", "[ror]".blue(), pkg_name); + let (archive_path, winning_url) = + race_download(urls, &binary.sha256, cfg.clone()).await?; + + /*gpg verification */ + if repo_cfg.map(|r| r.gpg_support).unwrap_or(false) { + if let Some(key_file) = repo_cfg.and_then(|r| r.gpg_key.as_deref()) { + let asc_url = format!("{}.asc", winning_url); + println!("[{}] Verifying GPG...", "[ror]".cyan()); + + let asc_path = match timeout( + Duration::from_secs(30), + download_one(&asc_url, "", &cfg), + ) + .await + { + Ok(Ok(p)) => p, + Ok(Err(e)) => { + return Err(format!( + "GPG signature download failed {}: {}", + asc_url, e + )) + } + Err(_) => { + return Err(format!( + "GPG signature download timed out: {}", + asc_url + )) + } + }; + + let key_full_path = Path::new("/var/ror/packages").join(key_file); -fn install_single_package(pkg_name: &str, cfg: Arc<Config>, db_mutex: &Mutex<InstalledDB>) -> Result<()> { - debug!("install_single_package: start '{}'", pkg_name); - println!("{} Installing {}...", ">>>".cyan(), pkg_name); + verify_gpg_signature(&archive_path, &asc_path, &key_full_path) + .map_err(|e| format!("GPG Verification Failed: {}", e))?; - let installed_pkg = match install::install_package_with_result(pkg_name, &*cfg) { - Ok(p) => { - debug!("install_single_package: '{}' installed successfully v{}", pkg_name, p.version); - p + let _ = std::fs::remove_file(&asc_path); } - Err(e) => { - debug!("install_single_package: '{}' failed: {}", pkg_name, e); - return Err(e); + } + + println!("[{}] Extracting {}...", "[ror]".green(), pkg_name); + let shadow = tempfile::tempdir().map_err(|e| e.to_string())?; + let work_dir = shadow.path().join("root"); + std::fs::create_dir_all(&work_dir).map_err(|e| e.to_string())?; + + let files_extracted = { + let ptype = binary.pkg_type.as_deref().unwrap_or("tar.xz"); + if ptype == "deb" { + extract_deb(&archive_path, &work_dir)? + } else if ptype == "ror" { + let dict = binary.dict.as_ref().ok_or("Missing dict URL")?; + let dict_path = download_one(dict, "", &cfg).await?; + let f = extract_ror(&archive_path, &dict_path, &work_dir)?; + let _ = std::fs::remove_file(&dict_path); + f + } else if ptype == "sror" { + extract_sror(&archive_path, &work_dir)? + } else { + extract_native(&archive_path, &work_dir)? } }; - let mut db = db_mutex.lock().unwrap(); - debug!("install_single_package: acquired db lock for '{}'", pkg_name); - db.add_package(installed_pkg); + println!("[{}] Installing {}...", "[ror]".yellow(), pkg_name); - if let Err(e) = db.save() { - debug!("install_single_package: db save failed for '{}': {}", pkg_name, e); - eprintln!("{} Failed to save installed DB: {}", "[ror]".red().bold(), e); - return Err(format!("Failed to save installed DB: {}", e)); - } + let installer = AtomicInstaller::new(shadow); + let installed_files = + installer.commit(&files_extracted, &work_dir, &binary.install_prefix)?; - debug!("install_single_package: '{}' registered in db", pkg_name); - println!("{} Package registered in database", "[ror]".green()); - Ok(()) + let _ = std::fs::remove_file(&archive_path); + + let elapsed = start_time.elapsed().as_millis(); + println!("[>] Installed {} ({:.2}ms)", pkg_name, elapsed as f64); + + Ok(InstalledPackage { + name: pkg.name.clone(), + version: pkg.version.clone(), + libc: pkg.libc.clone(), + files: installed_files, + installed_at: chrono::Local::now().to_rfc3339(), + }) } -pub fn install_packages_parallel(packages: &[String], cfg: Arc<Config>) -> Result<()> { - debug!("install_packages_parallel: called with {:?}", packages); - let installed_db = InstalledDB::load(); - debug!("install_packages_parallel: loaded installed db, {} packages", installed_db.packages.len()); +pub async fn install_packages_parallel( + packages: &[String], + cfg: Arc<Config>, +) -> Result<(), String> { + println!("[>] Starting package synchronization..."); - let mut outdated: HashSet<String> = HashSet::new(); - let required = collect_required_packages(packages, &installed_db, &mut outdated)?; + let ctrl_c_handle = tokio::spawn(async { + tokio::signal::ctrl_c().await.ok(); + INTERRUPTED.store(true, Ordering::SeqCst); + }); - if !outdated.is_empty() { - println!("{} Outdated dependencies detected: {}", "[ror]".yellow().bold(), outdated.iter().cloned().collect::<Vec<_>>().join(", ").yellow()); - debug!("install_packages_parallel: outdated set={:?}", outdated); - } + let installed_db = InstalledDB::load(); + let mut outdated = HashSet::new(); + let required = + resolver::collect_required_packages(packages, &installed_db, &mut outdated)?; if required.is_empty() { - println!("{} All packages already installed and up-to-date.", "[ror]".green()); - debug!("install_packages_parallel: nothing to install"); + println!("[>] Nothing to install."); + ctrl_c_handle.abort(); return Ok(()); } - debug!("install_packages_parallel: required={:?}", required); - check_conflicts(&required, &installed_db)?; + resolver::check_conflicts(&required, &installed_db)?; + let graph = resolver::build_graph(&required, &installed_db)?; + let levels = graph.compute_levels(); - let graph = build_graph(&required, &installed_db)?; - let mut levels = graph.compute_levels(); + let mut total_installed: Vec<InstalledPackage> = Vec::new(); - if levels.is_empty() && !required.is_empty() { - debug!("install_packages_parallel: no edges, using flat level"); - levels.push(required.iter().cloned().collect()); - } - - 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() - ); - debug!("install_packages_parallel: total={} levels={}", 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 {}: {} package(s)", ">>>".cyan(), level_idx, level_pkgs.len()); - debug!("install_packages_parallel: starting level {} pkgs={:?}", level_idx, level_pkgs); + for (level_idx, level_pkgs) in levels.iter().enumerate() { + if INTERRUPTED.load(Ordering::SeqCst) { + println!("[!] Interrupted by user."); + ctrl_c_handle.abort(); + return Err("Installation aborted".to_string()); + } - let level_total = level_pkgs.len(); - let mut handles = Vec::new(); + println!( + "[>] Level {} installing {} packages...", + level_idx, + level_pkgs.len() + ); + let mut tasks = Vec::new(); for pkg in level_pkgs { + let c = cfg.clone(); let pkg_name = pkg.clone(); - let cfg = Arc::clone(&cfg); - let db_mutex = Arc::clone(&db_mutex); - let is_outdated = outdated.contains(&pkg_name); - debug!("install_packages_parallel: spawning thread for '{}' (outdated={})", pkg_name, is_outdated); - - let handle = thread::spawn(move || { - if is_outdated { - debug!("install_single_package: '{}' is outdated, removing old version first", pkg_name); - let db = db_mutex.lock().unwrap(); - let files = db.packages.get(&pkg_name).map(|p| p.files.clone()).unwrap_or_default(); - drop(db); - crate::delete::remove_package_files_only(&pkg_name, &files); - let mut db = db_mutex.lock().unwrap(); - db.packages.remove(&pkg_name); - drop(db); - } - install_single_package(&pkg_name, cfg, &db_mutex) - }); - handles.push((pkg, handle)); + tasks.push(tokio::spawn(async move { + install_single_impl(&pkg_name, c).await + })); } - let mut errors = Vec::new(); - let mut level_done = 0usize; - - for (pkg_name, handle) in handles { - match handle.join() { - Ok(Ok(())) => { - installed_count += 1; - level_done += 1; - debug!("install_packages_parallel: '{}' done ({}/{})", pkg_name, installed_count, total_pkgs); - 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(); + let results: Vec<_> = futures::future::join_all(tasks).await; + + let mut level_errors = Vec::new(); + for (i, res) in results.into_iter().enumerate() { + match res { + Ok(Ok(pkg)) => { + total_installed.push(pkg); } Ok(Err(e)) => { - debug!("install_packages_parallel: '{}' error: {}", pkg_name, e); - errors.push(e); + level_errors.push((level_pkgs[i].clone(), e)); } - Err(_) => { - debug!("install_packages_parallel: '{}' thread panicked", pkg_name); - errors.push(format!("Thread panicked for '{}'", pkg_name)); + Err(join_err) => { + level_errors.push((level_pkgs[i].clone(), join_err.to_string())); } } } - eprintln!(); + if !level_errors.is_empty() { + println!("[X] Errors at level {}:", level_idx); + for (name, err) in &level_errors { + println!(" [!] {}: {}", name.red(), err); + } + ctrl_c_handle.abort(); + return Err(format!("Level {} failed", level_idx)); + } - if !errors.is_empty() { - eprintln!("{} Errors at 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)); + /*save db after every level to prevent inconsistent state */ + let mut db = InstalledDB::load(); + for pkg in &total_installed { + db.add_package(pkg.clone()); } - debug!("install_packages_parallel: level {} complete", level_idx); + let path = Path::new(InstalledDB::PATH); + if let Err(e) = db.save_atomic(path) { + eprintln!("[X] Failed to save database: {}", e); + ctrl_c_handle.abort(); + return Err(format!("Failed to save DB: {}", e)); + } } - println!("{} All packages installed successfully.", "[ror]".green().bold()); - debug!("install_packages_parallel: all done"); + ctrl_c_handle.abort(); + println!("[>] Synchronization completed successfully."); Ok(()) } diff --git a/src/resolver.rs b/src/resolver.rs new file mode 100644 index 0000000..240119e --- /dev/null +++ b/src/resolver.rs @@ -0,0 +1,251 @@ +use std::collections::{HashMap, HashSet, VecDeque}; +use crate::install::{Dependency, InstalledDB, load_package, parse_dep, version_satisfies, get_package_info}; +use colored::Colorize; + +type Result<T> = std::result::Result<T, String>; + +pub struct DependencyGraph { + edges: HashMap<String, Vec<String>>, + reverse: HashMap<String, Vec<String>>, +} + +impl DependencyGraph { + fn new() -> Self { + Self { edges: HashMap::new(), reverse: HashMap::new() } + } + + fn add_dep(&mut self, pkg: String, dep: String) { + self.edges.entry(pkg.clone()).or_insert_with(Vec::new).push(dep.clone()); + self.reverse.entry(dep).or_insert_with(Vec::new).push(pkg); + } + + pub fn compute_levels(&self) -> Vec<Vec<String>> { + 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(); + + while !queue.is_empty() { + let level_pkgs: Vec<String> = queue.drain(..).collect(); + 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()); + } + } + } + } + } + } + + 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() + ); + } + levels + } +} + +fn is_dep_satisfied(raw: &str, db: &InstalledDB) -> bool { + let (name, constraint) = parse_dep(raw); + match db.packages.get(&name) { + None => false, + Some(installed) => match constraint { + None => true, + Some(c) => version_satisfies(&installed.version, &c), + }, + } +} + +fn needs_update(raw: &str, db: &InstalledDB) -> bool { + let (name, constraint) = parse_dep(raw); + match db.packages.get(&name) { + None => false, + Some(installed) => match constraint { + None => false, + Some(c) => { + let ok = version_satisfies(&installed.version, &c); + !ok + } + }, + } +} + +pub fn collect_required_packages( + packages: &[String], + installed_db: &InstalledDB, + outdated: &mut HashSet<String>, +) -> Result<HashSet<String>> { + let mut required = HashSet::new(); + let mut stack: Vec<String> = packages.iter().cloned().collect(); + + while let Some(pkg_name) = stack.pop() { + if required.contains(&pkg_name) { + continue; + } + + if installed_db.is_installed(&pkg_name) { + let needs_ver_update = get_package_info(&pkg_name).map(|(_, avail)| { + let inst_ver = &installed_db.packages[&pkg_name].version; + avail != *inst_ver && avail > *inst_ver + }).unwrap_or(false); + + if needs_ver_update { + outdated.insert(pkg_name.clone()); + required.insert(pkg_name.clone()); + } else { + let pkg = match load_package(&pkg_name) { + Some(p) => p, + None => continue, + }; + for dep in &pkg.depends { + match dep { + Dependency::Single(raw) => { + if needs_update(raw, installed_db) { + let (name, _) = parse_dep(raw); + outdated.insert(name.clone()); + if !required.contains(&name) { stack.push(name); } + } + } + Dependency::Any(alts) => { + for alt in alts { + if needs_update(alt, installed_db) { + let (name, _) = parse_dep(alt); + outdated.insert(name.clone()); + if !required.contains(&name) { stack.push(name); } + } + } + } + } + } + continue; + } + } else { + required.insert(pkg_name.clone()); + } + + let pkg = match load_package(&pkg_name) { + Some(p) => p, + None => return Err(format!("Package '{}' not found", pkg_name)), + }; + + for dep in &pkg.depends { + match dep { + Dependency::Single(raw) => { + let (name, _) = parse_dep(raw); + if !is_dep_satisfied(raw, installed_db) && !required.contains(&name) { + stack.push(name); + } + } + Dependency::Any(alternatives) => { + let satisfied = alternatives.iter().any(|a| is_dep_satisfied(a, installed_db)); + if satisfied { continue; } + if let Some(first) = alternatives.first() { + let (name, _) = parse_dep(first); + if !required.contains(&name) { stack.push(name); } + } else { + return Err(format!("Empty alternative list in package '{}'", pkg_name)); + } + } + } + } + } + + Ok(required) +} + +pub fn build_graph(packages: &HashSet<String>, installed_db: &InstalledDB) -> Result<DependencyGraph> { + let mut graph = DependencyGraph::new(); + + for pkg_name in packages { + let pkg = load_package(pkg_name) + .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; + + for dep in &pkg.depends { + match dep { + Dependency::Single(raw) => { + let (name, _) = parse_dep(raw); + if packages.contains(&name) { + graph.add_dep(pkg_name.clone(), name.clone()); + } else if !is_dep_satisfied(raw, installed_db) { + return Err(format!("Dependency '{}' of '{}' is missing or unsatisfied", raw, pkg_name)); + } + } + Dependency::Any(alternatives) => { + let found = alternatives.iter().find(|a| { + let (n, _) = parse_dep(a); + packages.contains(&n) + }); + if let Some(chosen) = found { + let (name, _) = parse_dep(chosen); + graph.add_dep(pkg_name.clone(), name.clone()); + } else { + let satisfied = alternatives.iter().any(|a| is_dep_satisfied(a, installed_db)); + if !satisfied { + return Err(format!("No alternative from {:?} for '{}' is available", alternatives, pkg_name)); + } + } + } + } + } + } + + Ok(graph) +} + +pub fn check_conflicts(required: &HashSet<String>, installed_db: &InstalledDB) -> Result<()> { + let mut pkg_map = HashMap::new(); + + for pkg_name in required { + let pkg = load_package(pkg_name) + .ok_or_else(|| 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) { + 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) { + return Err(format!("Packages '{}' and '{}' conflict with each other", a, b)); + } + } + } + + Ok(()) +} diff --git a/src/rootfs.rs b/src/rootfs.rs index 9af2e57..b408741 100644 --- a/src/rootfs.rs +++ b/src/rootfs.rs @@ -1,3 +1,4 @@ +use crate::apply::SystemConfig; use std::collections::{HashMap, HashSet, VecDeque}; use std::fs; use std::path::Path; @@ -9,7 +10,6 @@ use colored::Colorize; use serde::Serialize; use serde_json; use crate::config; -use crate::group::Group; use crate::progress::ProgressBar; use chrono::Local; use crate::install::{ @@ -532,11 +532,12 @@ fn write_installed_json( } pub fn build_rootfs( - group_name: &str, + group_name: Option<&str>, target_dir: &Path, cfg: &config::Config, target_arch: &str, run_ldconfig: bool, + system_config: Option<&Path>, ) -> Result<(), String> { if !target_dir.exists() { fs::create_dir_all(target_dir) @@ -549,17 +550,36 @@ pub fn build_rootfs( } } - 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))?; + let (start_packages, group) = if let Some(config_path) = system_config { + let content = fs::read_to_string(config_path) + .map_err(|e| format!("Failed to read {}: {}", config_path.display(), e))?; + let sys_config: SystemConfig = serde_yaml::from_str(&content) + .map_err(|e| format!("System config YAML error: {}", e))?; + let pkgs = crate::apply::get_target_packages(&sys_config, cfg)?; + let dummy_group = crate::group::Group { + name: "system".into(), + description: Some("from system.yaml".into()), + libc: cfg.global.libc.clone().into(), + version: None, + packages: pkgs.clone(), + install_steps: String::new(), + }; + (pkgs, dummy_group) + } else { + let group_name = group_name.ok_or_else(|| "Either --group or --config is required".to_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: crate::group::Group = serde_yaml::from_str(&content) + .map_err(|e| format!("Group YAML error: {}", e))?; + let pkgs = group.packages.clone(); + (pkgs, group) + }; println!( - "{} Building rootfs in {} with group '{}'", + "{} Building rootfs in {}", "[ror]".blue().bold(), - target_dir.display(), - group_name + target_dir.display() ); if let Some(desc) = &group.description { println!("{} {}", "Description:".yellow(), desc); @@ -574,7 +594,7 @@ pub fn build_rootfs( println!("{} FHS skeleton created.", ">>>".green()); println!("\n{} Phase 1a: Resolving packages...", ">>>".cyan().bold()); - let all_packages = collect_install_order(&group.packages)?; + let all_packages = collect_install_order(&start_packages)?; println!("{} {} packages to install (including dependencies)", ">>>".green(), all_packages.len()); println!("\n{} Phase 1b: Building download queue...", ">>>".cyan().bold()); diff --git a/src/update.rs b/src/update.rs index 5deb228..9703d7a 100644 --- a/src/update.rs +++ b/src/update.rs @@ -40,7 +40,9 @@ pub fn upgrade_system(cfg: &config::Config) -> Result<(), String> { upgradable.join(", ").yellow() ); - parallel::install_packages_parallel(&upgradable, Arc::new(cfg.clone())) + let rt = tokio::runtime::Runtime::new() + .map_err(|e| format!("Failed to create async runtime: {}", e))?; + rt.block_on(parallel::install_packages_parallel(&upgradable, Arc::new(cfg.clone()))) } fn is_newer(current: &str, available: &str) -> bool { @@ -86,6 +88,7 @@ pub fn update_package(pkg_name: &str, cfg: &config::Config, dry_run: bool) -> bo true } +#[allow(dead_code)] pub fn resolve_recipe_path(name_or_path: &Path) -> PathBuf { if name_or_path.exists() { return name_or_path.to_path_buf(); @@ -100,6 +103,7 @@ pub fn resolve_recipe_path(name_or_path: &Path) -> PathBuf { name_or_path.to_path_buf() } +#[allow(dead_code)] pub fn rebuild_from_recipe(recipe_path: &Path, cfg: &config::Config) { let resolved = resolve_recipe_path(recipe_path); |