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,
}
#[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,
}
#[derive(Clone, Debug, Default)]
pub struct TuiLocalSnapshot {
pub packages: Vec<PackageModel>,
pub installed_count: usize,
pub updates_count: usize,
pub explicit_count: usize,
pub orphan_count: usize,
pub groups: Vec<(String, Vec<String>)>,
}
#[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_tui_local_snapshot(&self) -> Result<TuiLocalSnapshot, BackendError> {
let (all_res, groups_res, stats_res, orphan_res) = tokio::join!(
self.get_all_packages(),
self.list_groups(),
self.get_stats(),
self.get_orphan_count(),
);
let (packages, installed_count, updates_count) = all_res.unwrap_or_default();
Ok(TuiLocalSnapshot {
packages,
installed_count,
updates_count,
explicit_count: stats_res.map_or(0, |s| s.explicit),
orphan_count: orphan_res.unwrap_or(0),
groups: groups_res.unwrap_or_default(),
})
}
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);
}
}