haj 0.3.4

the beautiful, cross-distro package manager and tui.
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
use crate::core::package::PackageModel;
use async_trait::async_trait;

#[derive(Debug)]
pub enum BackendError {
    NotFound(String),
    NetworkError(String),
    ExecutionError(i32, String),
    ParseError(String),
    NotSupported(String),
}

impl std::fmt::Display for BackendError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotFound(pkg) => write!(f, "Package not found: {}", pkg),
            Self::NetworkError(err) => write!(f, "Network error: {}", err),
            Self::ExecutionError(code, stderr) => {
                write!(f, "Execution failed ({}): {}", code, stderr)
            }
            Self::ParseError(err) => write!(f, "Parse error: {}", err),
            Self::NotSupported(err) => write!(f, "Not supported: {}", err),
        }
    }
}

impl std::error::Error for BackendError {}

#[derive(Clone, Debug, Default)]
pub struct Capabilities {
    pub supports_external: bool,
    pub supports_downgrade: bool,
    pub supports_interactive_downgrade: bool,
    pub supports_groups: bool,
    pub supports_config_merge: bool,
}

/// Cross-backend options passed to transaction plan builders.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TxOptions {
    pub noconfirm: bool,
    pub needed: bool,
    pub ignore: Vec<String>,
    pub root: Option<String>,
    pub config: Option<String>,
    pub allow_conflict_removal: bool,
}

#[derive(Clone, Debug, Default)]
pub struct CommandPlan {
    pub executable: String,
    pub args: Vec<String>,
    pub env: Vec<(String, String)>,
    pub requires_root: bool,
    pub interactive: bool,
    pub allow_exit_codes: Vec<i32>,
}

impl CommandPlan {
    pub fn new(executable: impl Into<String>, args: Vec<String>, requires_root: bool) -> Self {
        Self {
            executable: executable.into(),
            args,
            requires_root,
            ..Default::default()
        }
    }

    pub fn with_env(mut self, env: Vec<(String, String)>) -> Self {
        self.env = env;
        self
    }

    pub fn with_interactive(mut self, interactive: bool) -> Self {
        self.interactive = interactive;
        self
    }

    pub fn with_allow_exit_codes(mut self, codes: Vec<i32>) -> Self {
        self.allow_exit_codes = codes;
        self
    }

    pub fn is_success_code(&self, code: Option<i32>) -> bool {
        code == Some(0) || code.is_some_and(|c| self.allow_exit_codes.contains(&c))
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum TransactionAction {
    Install,
    Upgrade,
    Remove,
    Downgrade,
    Unknown,
}

#[derive(Clone, Debug)]
pub struct InstallSummary {
    pub action: TransactionAction,
    pub name: String,
    pub version: String,
    pub download_size_mb: f64,
    pub install_size_mb: f64,
}

#[derive(Clone, Debug)]
pub struct ConflictInfo {
    pub incoming_pkg: String,
    pub installed_pkg: String,
    pub constraint: Option<String>,
}

#[derive(Clone, Debug)]
pub struct ExternalResolution {
    pub packages: Vec<(String, String, bool, Option<String>)>,
}

#[derive(Clone, Debug)]
pub struct HistoryEntry {
    pub timestamp: String,
    pub action: String,
    pub package: String,
    pub version: String,
}

#[derive(Clone, Debug)]
pub struct LogEntry {
    pub timestamp: String,
    pub message: String,
}

#[derive(Clone, Debug, Default)]
pub struct PackageDetails {
    pub package: PackageModel,
    pub install_reason: Option<String>,
    pub depends: Vec<String>,
    pub required_by: Vec<String>,
    pub opt_depends: Vec<String>,
    pub votes: Option<u64>,
}

#[derive(Clone, Debug)]
pub struct SystemStats {
    pub explicit: usize,
    pub dependencies: usize,
    pub total: usize,
}

#[async_trait]
pub trait PackageManager: Send + Sync {
    fn name(&self) -> &'static str;
    fn capabilities(&self) -> Capabilities;

    async fn search(&self, query: &str) -> Result<Vec<PackageModel>, BackendError>;
    async fn search_filtered(
        &self,
        query: &str,
        _repo_only: bool,
        _aur_only: bool,
    ) -> Result<Vec<PackageModel>, BackendError> {
        self.search(query).await
    }
    async fn info(&self, package: &str) -> Result<Option<PackageModel>, BackendError>;
    async fn details(&self, package: &str) -> Result<Option<PackageDetails>, BackendError> {
        Ok(self.info(package).await?.map(|package| PackageDetails {
            package,
            ..Default::default()
        }))
    }
    async fn list_installed(&self) -> Result<Vec<PackageModel>, BackendError>;
    async fn list_installed_filtered(
        &self,
        _explicit: bool,
        _deps: bool,
        _foreign: bool,
    ) -> Result<Vec<PackageModel>, BackendError> {
        self.list_installed().await
    }
    async fn get_all_packages(&self) -> Result<(Vec<PackageModel>, usize, usize), BackendError>;

    async fn get_install_summaries(
        &self,
        packages: &[&str],
    ) -> Result<Vec<InstallSummary>, BackendError>;
    async fn detect_conflicts(&self, packages: &[&str]) -> Result<Vec<ConflictInfo>, BackendError>;

    async fn resolve_external(&self, packages: &[&str])
    -> Result<ExternalResolution, BackendError>;
    async fn build_external_package(
        &self,
        package: &str,
        verbose: bool,
    ) -> Result<std::path::PathBuf, BackendError>;

    fn build_install(&self, packages: &[&str]) -> Result<CommandPlan, BackendError>;
    fn build_install_with_opts(
        &self,
        packages: &[&str],
        _opts: &TxOptions,
    ) -> Result<CommandPlan, BackendError> {
        self.build_install(packages)
    }
    fn build_remove(&self, packages: &[&str]) -> Result<CommandPlan, BackendError>;
    fn build_remove_with_opts(
        &self,
        packages: &[&str],
        _opts: &TxOptions,
    ) -> Result<CommandPlan, BackendError> {
        self.build_remove(packages)
    }
    fn build_update(&self) -> Result<CommandPlan, BackendError>;
    fn build_update_with_opts(&self, _opts: &TxOptions) -> Result<CommandPlan, BackendError> {
        self.build_update()
    }
    fn build_upgrade(&self) -> Result<CommandPlan, BackendError>;
    fn build_upgrade_with_opts(&self, _opts: &TxOptions) -> Result<CommandPlan, BackendError> {
        self.build_upgrade()
    }
    fn build_upgrade_plans_with_opts(
        &self,
        sync: bool,
        opts: &TxOptions,
    ) -> Result<Vec<CommandPlan>, BackendError> {
        let mut plans = Vec::new();
        if sync {
            plans.push(self.build_update_with_opts(opts)?);
        }
        plans.push(self.build_upgrade_with_opts(opts)?);
        Ok(plans)
    }
    fn build_install_upgraded_with_opts(
        &self,
        packages: &[&str],
        opts: &TxOptions,
    ) -> Result<Vec<CommandPlan>, BackendError> {
        Ok(vec![
            self.build_update_with_opts(opts)?,
            self.build_install_with_opts(packages, opts)?,
        ])
    }
    fn build_install_local(&self, path: &std::path::Path) -> Result<CommandPlan, BackendError>;
    fn build_install_local_with_opts(
        &self,
        path: &std::path::Path,
        _opts: &TxOptions,
    ) -> Result<CommandPlan, BackendError> {
        self.build_install_local(path)
    }

    fn build_downgrade(&self, package: &str, version: &str) -> Result<CommandPlan, BackendError>;
    fn build_interactive_downgrade(&self, package: &str) -> Result<CommandPlan, BackendError>;

    async fn pre_query_check(&self, _root: Option<&str>, _dry_run: bool) {}
    fn list_downgrade_candidates(&self, _package: &str) -> Vec<(std::path::PathBuf, String)> {
        Vec::new()
    }
    fn select_downgrade_target(&self, _package: &str) -> Option<std::path::PathBuf> {
        None
    }
    fn build_config_merge(&self) -> Result<CommandPlan, BackendError> {
        Err(BackendError::NotSupported(
            "config file merging is not supported by this backend.".into(),
        ))
    }
    fn build_clean_external_cache(&self, _keep: usize) -> Vec<CommandPlan> {
        Vec::new()
    }
    fn locate_empty_hint(&self) -> Option<&'static str> {
        None
    }

    async fn list_group_or_meta(&self, name: &str) -> Result<Vec<PackageModel>, BackendError>;
    async fn list_groups(&self) -> Result<Vec<(String, Vec<String>)>, BackendError> {
        Ok(Vec::new())
    }
    async fn get_history(&self, limit: usize) -> Result<Vec<HistoryEntry>, BackendError>;
    async fn get_log(&self, lines: usize) -> Result<Vec<LogEntry>, BackendError>;
    async fn get_stats(&self) -> Result<SystemStats, BackendError>;
    async fn get_orphan_count(&self) -> Result<usize, BackendError>;
    async fn list_orphans(&self) -> Result<Vec<PackageModel>, BackendError> {
        Ok(Vec::new())
    }

    async fn owns_file(&self, path: &str) -> Result<Option<PackageModel>, BackendError>;
    async fn list_files(&self, package: &str) -> Result<Vec<String>, BackendError>;
    async fn locate_file(&self, file: &str) -> Result<Vec<String>, BackendError>;

    fn build_clean(&self) -> Result<CommandPlan, BackendError>;
    fn build_clean_keep(&self, _keep: usize) -> Result<CommandPlan, BackendError> {
        self.build_clean()
    }
    fn build_clean_keep_with_opts(
        &self,
        keep: usize,
        _opts: &TxOptions,
    ) -> Result<CommandPlan, BackendError> {
        self.build_clean_keep(keep)
    }
    fn build_clean_orphans(&self) -> Result<CommandPlan, BackendError>;
    fn build_clean_orphans_with_opts(
        &self,
        _opts: &TxOptions,
    ) -> Result<CommandPlan, BackendError> {
        self.build_clean_orphans()
    }
    fn build_fetch(&self, packages: &[&str]) -> Result<CommandPlan, BackendError>;
    fn build_fetch_with_opts(
        &self,
        packages: &[&str],
        _opts: &TxOptions,
    ) -> Result<CommandPlan, BackendError> {
        self.build_fetch(packages)
    }
    fn build_mark_explicit(&self, package: &str) -> Result<CommandPlan, BackendError>;
    fn build_mark_explicit_with_opts(
        &self,
        package: &str,
        _opts: &TxOptions,
    ) -> Result<CommandPlan, BackendError> {
        self.build_mark_explicit(package)
    }
    fn build_mark_dependency(&self, package: &str) -> Result<CommandPlan, BackendError>;
    fn build_mark_dependency_with_opts(
        &self,
        package: &str,
        _opts: &TxOptions,
    ) -> Result<CommandPlan, BackendError> {
        self.build_mark_dependency(package)
    }
    async fn toggle_mark(
        &self,
        package: &str,
    ) -> Result<(CommandPlan, &'static str), BackendError> {
        Ok((self.build_mark_explicit(package)?, "explicit"))
    }
    async fn toggle_mark_with_opts(
        &self,
        package: &str,
        _opts: &TxOptions,
    ) -> Result<(CommandPlan, &'static str), BackendError> {
        self.toggle_mark(package).await
    }
    async fn check_native_updates(&self) -> Result<Vec<(String, String, String)>, BackendError> {
        Ok(Vec::new())
    }
    async fn check_synced_native_updates(
        &self,
    ) -> Result<Vec<(String, String, String)>, BackendError> {
        self.check_native_updates().await
    }
    async fn check_external_updates(&self) -> Result<Vec<(String, String, String)>, BackendError> {
        Ok(Vec::new())
    }

    fn lock_file_path(&self) -> Option<&'static str> {
        None
    }

    fn cache_size(&self) -> Option<String> {
        None
    }

    fn last_sync_timestamp(&self) -> Option<i64> {
        None
    }
}

pub(crate) fn dir_size_bytes(root: &std::path::Path) -> u64 {
    let mut total = 0u64;
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(dir) else {
            continue;
        };
        for entry in entries.filter_map(Result::ok) {
            let Ok(meta) = std::fs::symlink_metadata(entry.path()) else {
                continue;
            };
            if meta.file_type().is_symlink() {
                continue;
            }
            if meta.is_dir() {
                stack.push(entry.path());
            } else if meta.is_file() {
                total = total.saturating_add(meta.len());
            }
        }
    }
    total
}

pub(crate) fn newest_mtime_epoch(
    root: &std::path::Path,
    ext_filter: Option<&str>,
    recursive: bool,
) -> Option<i64> {
    let mut newest: Option<i64> = None;
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(dir) else {
            continue;
        };
        for entry in entries.filter_map(Result::ok) {
            let path = entry.path();
            if path.file_name().and_then(|n| n.to_str()) == Some("lock") {
                continue;
            }
            let Ok(meta) = std::fs::symlink_metadata(&path) else {
                continue;
            };
            if meta.file_type().is_symlink() {
                continue;
            }
            if meta.is_dir() {
                if recursive {
                    stack.push(path);
                }
                continue;
            }
            if !meta.is_file() {
                continue;
            }
            if let Some(ext) = ext_filter
                && path.extension().and_then(|e| e.to_str()) != Some(ext)
            {
                continue;
            }
            if let Ok(modified) = meta.modified()
                && let Ok(secs) = modified.duration_since(std::time::UNIX_EPOCH)
            {
                let ts = secs.as_secs() as i64;
                newest = Some(newest.map_or(ts, |cur| cur.max(ts)));
            }
        }
    }
    newest
}

pub(crate) fn format_byte_size(bytes: u64) -> String {
    const KIB: f64 = 1024.0;
    const MIB: f64 = KIB * 1024.0;
    const GIB: f64 = MIB * 1024.0;
    let b = bytes as f64;
    if b >= GIB {
        format!("{:.1} gib", b / GIB)
    } else if b >= MIB {
        format!("{:.1} mib", b / MIB)
    } else if b >= KIB {
        format!("{:.1} kib", b / KIB)
    } else {
        format!("{bytes} b")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_command_plan_allow_exit_codes() {
        let plan = CommandPlan::new("dnf", vec!["check-update".into()], false)
            .with_allow_exit_codes(vec![100]);
        assert!(plan.is_success_code(Some(0)));
        assert!(plan.is_success_code(Some(100)));
        assert!(!plan.is_success_code(Some(1)));
        assert!(!plan.is_success_code(None));
    }

    #[test]
    fn test_format_byte_size_units() {
        assert_eq!(format_byte_size(512), "512 b");
        assert_eq!(format_byte_size(2048), "2.0 kib");
        assert_eq!(format_byte_size(5 * 1024 * 1024), "5.0 mib");
        assert_eq!(format_byte_size(3 * 1024 * 1024 * 1024 / 2), "1.5 gib");
    }

    #[test]
    fn test_dir_size_and_newest_mtime_helpers() {
        let unique = format!(
            "haj-traits-test-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        );
        let root = std::env::temp_dir().join(unique);
        let sub = root.join("nested");
        std::fs::create_dir_all(&sub).unwrap();
        std::fs::write(root.join("core.db"), vec![b'a'; 128]).unwrap();
        std::fs::write(root.join("lock"), vec![b'x'; 64]).unwrap();
        std::fs::write(sub.join("extra.xml"), vec![b'b'; 256]).unwrap();

        assert_eq!(dir_size_bytes(&root), 128 + 64 + 256);
        assert!(newest_mtime_epoch(&root, Some("db"), false).is_some());
        assert!(newest_mtime_epoch(&root, Some("xml"), false).is_none());
        assert!(newest_mtime_epoch(&root, Some("xml"), true).is_some());

        let _ = std::fs::remove_dir_all(&root);
    }
}