haj 0.3.5

the beautiful, cross-distro package manager and tui.
use alpm::Alpm;
use std::collections::HashMap;

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

pub fn parse_aur_conflict(raw: &str) -> (&str, Option<String>) {
    for op in ["<=", ">=", "==", "<", ">", "="] {
        if let Some(idx) = raw.find(op) {
            return (&raw[..idx], Some(raw[idx..].to_string()));
        }
    }
    (raw, None)
}

fn find_matching_installed(local_db: &alpm::Db, c_name: &str) -> Vec<String> {
    let mut matches = Vec::new();
    if let Ok(installed) = local_db.pkg(c_name) {
        matches.push(installed.name().to_string());
    }
    for installed in local_db.pkgs() {
        if installed.name() != c_name
            && installed
                .provides()
                .iter()
                .any(|prov| prov.name() == c_name)
        {
            matches.push(installed.name().to_string());
        }
    }
    matches
}

fn format_dep_constraint(dep: &alpm::Dep) -> Option<String> {
    let mod_str = match dep.depmod() {
        alpm::DepMod::Any => "",
        alpm::DepMod::Eq => "=",
        alpm::DepMod::Ge => ">=",
        alpm::DepMod::Le => "<=",
        alpm::DepMod::Gt => ">",
        alpm::DepMod::Lt => "<",
    };
    dep.version().map(|v| format!("{mod_str}{}", v.as_str()))
}

pub fn detect_conflicts(
    alpm_handle: &Alpm,
    native_pkgs: &[String],
    aur_conflicts_map: &HashMap<String, Vec<String>>,
) -> Vec<ConflictInfo> {
    let mut conflicts = Vec::new();
    let local_db = alpm_handle.localdb();

    for raw_target in native_pkgs {
        let (repo_filter, lookup) = match raw_target.split_once('/') {
            Some((repo, name)) => (Some(repo), name),
            None => (None, raw_target.as_str()),
        };
        for db in alpm_handle.syncdbs() {
            if let Some(repo) = repo_filter
                && db.name() != repo
            {
                continue;
            }
            if let Ok(pkg) = db.pkg(lookup) {
                for conflict in pkg.conflicts() {
                    let constraint = format_dep_constraint(conflict);
                    for installed_name in find_matching_installed(local_db, conflict.name()) {
                        if installed_name != lookup {
                            conflicts.push(ConflictInfo {
                                incoming_pkg: lookup.to_string(),
                                installed_pkg: installed_name,
                                constraint: constraint.clone(),
                            });
                        }
                    }
                }
                break;
            }
        }
    }

    for (aur_pkg, aur_conflicts) in aur_conflicts_map {
        for constraint_str in aur_conflicts {
            let (c_name, constraint_val) = parse_aur_conflict(constraint_str);
            for installed_name in find_matching_installed(local_db, c_name) {
                if &installed_name != aur_pkg {
                    conflicts.push(ConflictInfo {
                        incoming_pkg: aur_pkg.clone(),
                        installed_pkg: installed_name,
                        constraint: constraint_val.clone(),
                    });
                }
            }
        }
    }

    for installed in local_db.pkgs() {
        for conflict in installed.conflicts() {
            let c_name = conflict.name();
            let matching_incoming = native_pkgs
                .iter()
                .chain(aur_conflicts_map.keys())
                .find(|p| p.as_str() == c_name);
            if let Some(incoming) = matching_incoming
                && incoming != installed.name()
            {
                conflicts.push(ConflictInfo {
                    incoming_pkg: incoming.clone(),
                    installed_pkg: installed.name().to_string(),
                    constraint: format_dep_constraint(conflict),
                });
            }
        }
    }

    conflicts.sort();
    conflicts.dedup();
    conflicts
}

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

    #[test]
    fn test_parse_aur_conflict_ops() {
        assert_eq!(parse_aur_conflict("nvidia"), ("nvidia", None));
        assert_eq!(
            parse_aur_conflict("nvidia>=550"),
            ("nvidia", Some(">=550".into()))
        );
        assert_eq!(parse_aur_conflict("foo=1.0"), ("foo", Some("=1.0".into())));
    }
}