summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 447c93a0fcb28c31578cc1a5943a63fbb625a619 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
use clap::{CommandFactory, Parser, Subcommand};
use std::sync::Arc;
use colored::Colorize;
use std::path::{Path, PathBuf};

mod sync;
mod install;
mod config;
mod info;
mod group;
mod delete;
mod listinstalled;
mod update;
mod rootfs;
mod parallel;
mod debug;
mod search;
mod repo;
mod progress;
mod check;
mod apply;
mod resolver;

#[derive(Parser)]
#[command(
    name = "ror",
    about = "ror package manager",
    version = concat!(env!("CARGO_PKG_VERSION"), " MPL 2"),
    disable_help_subcommand = true
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// install one or more packages or groups
    #[command(alias = "i")]
    Install {
        /// package names or @group specifications to install
        #[arg(required = true)]
        packages: Vec<String>,
    },

    /// list available package groups
    #[command(alias = "lg")]
    ListGroups,

    /// synchronize repository package recipes from remote
    #[command(alias = "s")]
    Sync,

    /// remove an installed package
    #[command(alias = "d")]
    Delete {
        /// name of the package to remove
        package: String,
    },

    /// list all installed packages
    #[command(alias = "l")]
    ListInstalled,

    /// print the total count of installed packages
    #[command(alias = "c")]
    Count,

    /// display detailed information about a package
    Info {
        /// name of the package
        package: String,
    },

    /// update a specific package to the latest available version
    Update {
        /// name of the package to update
        package: String,
        /// check for update without making modifications
        #[arg(long)]
        dry_run: bool,
    },

    /// upgrade all installed packages to their latest versions
    #[command(alias = "u")]
    Upgrade,

    /// search for packages by query in repositories
    Search {
        /// search query string
        query: String,
    },

    /// add a new package repository
    RepoAdd {
        /// repository name
        name: String,
        /// repository recipe git url
        url: String,
        /// optional binary package mirror url
        mirror: Option<String>,
    },

    /// remove a configured package repository
    RepoRemove {
        /// name of the repository to remove
        name: String,
    },

    /// list all configured package repositories
    RepoList,

    /// build a rootfs environment from a package group
    BuildRootfs {
        /// package group name to build
        #[arg(long)]
        group: String,
        /// target directory path for rootfs
        #[arg(long)]
        target: PathBuf,
        /// target architecture (default: native)
        #[arg(long, default_value = "native")]
        arch: String,
    },

    /// atomically replace one package with another
    Di {
        /// package to delete
        delete: String,
        /// package to install
        install: String,
    },

    /// apply declarative system configuration state
    #[command(alias = "a")]
    Apply {
        /// show changes without applying them
        #[arg(long)]
        dry_run: bool,
        /// custom system.yaml configuration file path
        #[arg(long)]
        config: Option<PathBuf>,
    },

    /// check integrity of installed packages
    Check,

    /// generate default configuration file at /etc/ror/ror.conf
    GenConfig,

    /// display ror version information
    Version,

    /// print this message or the help of the given subcommand
    Help {
        /// name of the subcommand
        subcommand: Option<String>,
    },
}

#[tokio::main]
async fn main() {
    let cli = Cli::parse();

    match cli.command {
        Commands::Help { subcommand } => {
            let mut cmd = Cli::command();
            if let Some(sub) = subcommand {
                if let Some(subcmd) = cmd.find_subcommand_mut(&sub) {
                    let _ = subcmd.print_help();
                } else {
                    let _ = cmd.print_help();
                }
            } else {
                let _ = cmd.print_help();
            }
            println!();
        }

        Commands::Version => {
            println!("ror {} MPL 2", env!("CARGO_PKG_VERSION"));
        }

        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
                ),
            }
        }

        Commands::Sync => {
            let cfg = config::Config::load();
            sync::run_sync(&cfg);
        }

        Commands::ListGroups => {
            group::list_groups();
        }

        Commands::ListInstalled => {
            listinstalled::print_installed();
        }

        Commands::Count => {
            listinstalled::print_count();
        }

        Commands::Info { package } => {
            info::print_package_info(&package);
        }

        Commands::Delete { package } => {
            delete::remove_package(&package);
        }

        Commands::Search { query } => {
            search::search_packages(&query);
        }

        Commands::Update { package, dry_run } => {
            let cfg = config::Config::load();
            update::update_package(&package, &cfg, dry_run);
        }

        Commands::Upgrade => {
            let cfg = config::Config::load();
            if let Err(e) = update::upgrade_system(&cfg) {
                eprintln!("{} Upgrade failed: {}", "[ror]".red().bold(), e);
            }
        }

        Commands::RepoAdd { name, url, mirror } => {
            if let Err(e) = repo::add_repository(&name, &url, mirror.as_deref()) {
                eprintln!("{} {}", "[ror]".red().bold(), e);
            }
        }

        Commands::RepoRemove { name } => {
            if let Err(e) = repo::remove_repository(&name) {
                eprintln!("{} {}", "[ror]".red().bold(), e);
            }
        }

        Commands::RepoList => {
            repo::list_repositories();
        }

        Commands::BuildRootfs { group, target, arch } => {
            let cfg = config::Config::load();
            let arch = if arch == "native" { "native" } else { &arch };
            if let Err(e) = rootfs::build_rootfs(
                &group,
                &target,
                &cfg,
                arch,
            ) {
                eprintln!("{} {}", "[ror]".red().bold(), e);
            }
        }

        Commands::Di { delete, install } => {
            let cfg = Arc::new(config::Config::load());
            run_di(delete, install, cfg);
        }

        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);
            }
        }

        Commands::Check => {
            let cfg = config::Config::load();
            check::check_integrity(&cfg);
        }

        Commands::Install { packages } => {
            let cfg = Arc::new(config::Config::load());
            let db = install::InstalledDB::load();

            
            let mut all_packages = Vec::new();
            for item in packages {
                if let Some(group_name) = item.strip_prefix('@') {
                    match group::load_group(group_name) {
                        Ok(grp) => all_packages.extend(grp.packages),
                        Err(e) => {
                            eprintln!("{} Failed to load group '{}': {}", "[ror]".red().bold(), group_name, e);
                            return;
                        }
                    }
                } else {
                    all_packages.push(item);
                }
            }

            for pkg_name in &all_packages {
                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;
                }
            }

            let (local_pkgs, remote_pkgs): (Vec<String>, Vec<String>) = all_packages
                .into_iter()
                .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,
                );
            }

            let remote_pkgs: Vec<String> = remote_pkgs.into_iter().map(|p| {
                let (name, variant) = install::parse_package_spec(&p);
                install::resolve_package_name(&name).map(|canonical| {
                    match variant {
                        Some(v) => format!("{}{{{}}}", canonical, v),
                        None => canonical,
                    }
                }).unwrap_or(p)
            }).collect();

            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
        );
        return;
    }

    let del_role = delete::critical_role_of(&del_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
                );
                return;
            }
            Some(ir) if ir != dr => {
                eprintln!(
                    "{} Role mismatch: '{}' is '{}' but '{}' is '{}'. Roles must match.",
                    "[ror]".red().bold(),
                    del_pkg,
                    dr,
                    inst_pkg,
                    ir
                );
                return;
            }
            _ => {}
        }
    }

    if let Err(e) =
        delete::check_critical_removal_with_replacement(&del_pkg, &inst_pkg, &db)
    {
        eprintln!("{}", e);
        return;
    }

    if let Err(e) = delete::check_critical_install(&inst_pkg, &db) {
        if !db.packages.contains_key(&inst_pkg) && !e.contains(&del_pkg) {
            eprintln!("{}", e);
            return;
        }
    }

    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
    );

    let installed_pkg = match install::install_package_with_result(&inst_pkg, &cfg) {
        Ok(pkg) => pkg,
        Err(e) => {
            eprintln!(
                "{} Failed to install '{}': {}. Old package remains intact.",
                "[ror]".red().bold(),
                inst_pkg,
                e
            );
            return;
        }
    };

    let new_files: std::collections::HashSet<_> = installed_pkg.files.iter().collect();
    let obsolete_files: Vec<_> = record_files.into_iter()
        .filter(|f| !new_files.contains(f))
        .collect();

    let del_ok = if obsolete_files.is_empty() {
        true
    } else {
        delete::remove_package_files_only(&del_pkg, &obsolete_files)
    };

    let mut db = install::InstalledDB::load();

    if del_ok {
        db.packages.remove(&del_pkg);
    }

    db.add_package(installed_pkg);

    if let Err(e) = db.save() {
        eprintln!("{} Failed to save DB: {}", "[ror]".red().bold(), e);
    }

    println!(
        "{} Replace finished: '{}' -> '{}'",
        "[ror]".green().bold(),
        del_pkg,
        inst_pkg
    );
}