use crate::backend::traits::{
ConflictInfo, HistoryEntry, InstallSummary, PackageDetails, TransactionAction,
};
use crate::core::package::PackageModel;
use std::collections::{HashMap, HashSet};
pub(crate) fn strip_arch(name: &str) -> String {
name.split(':').next().unwrap_or(name).trim().to_string()
}
pub fn parse_apt_cache_search(stdout: &str) -> Vec<PackageModel> {
let mut results = Vec::new();
for line in stdout.lines() {
if let Some((name, _desc)) = line.split_once(" - ") {
results.push(PackageModel {
name: strip_arch(name.trim()),
version: "Unknown".to_string(),
repo: "apt".to_string(),
is_installed: false,
is_upgradable: false,
size_mb: 0.0,
desc: Some(_desc.to_string()),
});
}
}
results
}
fn split_dep_list(raw: &str) -> Vec<String> {
raw.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(|entry| entry.split('|').next().unwrap_or(entry).trim().to_string())
.collect()
}
fn parse_deb_size_mb(prefix_kib: bool, val_str: &str) -> Option<f64> {
let v: f64 = val_str.trim().parse().ok()?;
Some(if prefix_kib {
v / 1024.0
} else {
v / 1_048_576.0
})
}
pub fn parse_apt_cache_show_details(stdout: &str, package: &str) -> Option<PackageDetails> {
let mut version = String::new();
let mut size_mb = 0.0;
let mut installed_size_mb = 0.0;
let mut desc = None;
let mut depends = Vec::new();
let mut opt_depends = Vec::new();
for line in stdout.lines() {
if line.trim().is_empty() {
if !version.is_empty() {
break; }
continue;
}
if let Some(v) = line.strip_prefix("Version: ") {
if version.is_empty() {
version = v.trim().to_string();
}
} else if let Some(s) = line.strip_prefix("Size: ")
&& let Some(mb) = parse_deb_size_mb(false, s)
{
size_mb = mb;
} else if let Some(s) = line.strip_prefix("Installed-Size: ")
&& let Some(mb) = parse_deb_size_mb(true, s)
{
installed_size_mb = mb;
} else if let Some(d) = line.strip_prefix("Description: ") {
if desc.is_none() {
desc = Some(d.trim().to_string());
}
} else if let Some(d) = line.strip_prefix("Description-en: ") {
if desc.is_none() {
desc = Some(d.trim().to_string());
}
} else if let Some(deps) = line
.strip_prefix("Pre-Depends: ")
.or_else(|| line.strip_prefix("Depends: "))
{
depends.extend(split_dep_list(deps));
} else if let Some(opt) = line
.strip_prefix("Recommends: ")
.or_else(|| line.strip_prefix("Suggests: "))
{
opt_depends.extend(split_dep_list(opt));
}
}
if version.is_empty() {
None
} else {
if size_mb == 0.0 {
size_mb = installed_size_mb;
}
Some(PackageDetails {
package: PackageModel {
name: strip_arch(package),
version,
repo: "apt".to_string(),
is_installed: false,
is_upgradable: false,
size_mb,
desc,
},
install_reason: None,
depends,
required_by: Vec::new(),
opt_depends,
votes: None,
})
}
}
pub fn parse_apt_cache_show(stdout: &str, package: &str) -> Option<PackageModel> {
parse_apt_cache_show_details(stdout, package).map(|d| d.package)
}
pub fn parse_dpkg_query_list(stdout: &str) -> Vec<PackageModel> {
let mut results = Vec::new();
for line in stdout.lines() {
let parts: Vec<&str> = line.split('\t').collect();
if parts.len() >= 3 && parts[2].contains("installed") {
let size_mb = parts
.get(3)
.and_then(|s| s.trim().parse::<f64>().ok())
.map_or(0.0, |kib| kib / 1024.0);
results.push(PackageModel {
name: strip_arch(parts[0]),
version: parts[1].to_string(),
repo: "local".to_string(),
is_installed: true,
is_upgradable: false,
size_mb,
desc: None,
});
}
}
results
}
pub fn parse_apt_dumpavail(
stdout: &str,
installed: &HashMap<String, PackageModel>,
upgradable: &HashSet<String>,
) -> Vec<PackageModel> {
let mut seen: HashMap<String, PackageModel> = HashMap::new();
let mut cur_name = String::new();
let mut cur_ver = String::new();
let mut cur_size = 0.0;
let mut cur_desc = None;
let flush = |seen: &mut HashMap<String, PackageModel>,
name: &mut String,
ver: &mut String,
size: &mut f64,
desc: &mut Option<String>| {
if !name.is_empty() && !ver.is_empty() {
let norm = strip_arch(name);
let inst = installed.get(&norm);
let model = PackageModel {
name: norm.clone(),
version: inst.map_or_else(|| ver.clone(), |p| p.version.clone()),
repo: "apt".to_string(),
is_installed: inst.is_some(),
is_upgradable: upgradable.contains(&norm),
size_mb: if *size > 0.0 {
*size
} else {
inst.map_or(0.0, |p| p.size_mb)
},
desc: desc.take(),
};
seen.entry(norm).or_insert(model);
}
name.clear();
ver.clear();
*size = 0.0;
*desc = None;
};
for line in stdout.lines() {
if line.trim().is_empty() {
flush(
&mut seen,
&mut cur_name,
&mut cur_ver,
&mut cur_size,
&mut cur_desc,
);
continue;
}
if let Some(n) = line.strip_prefix("Package: ") {
cur_name = n.trim().to_string();
} else if let Some(v) = line.strip_prefix("Version: ") {
cur_ver = v.trim().to_string();
} else if let Some(s) = line.strip_prefix("Installed-Size: ") {
if let Some(mb) = parse_deb_size_mb(true, s) {
cur_size = mb;
}
} else if let Some(s) = line.strip_prefix("Size: ") {
if cur_size == 0.0
&& let Some(mb) = parse_deb_size_mb(false, s)
{
cur_size = mb;
}
} else if let Some(d) = line
.strip_prefix("Description: ")
.or_else(|| line.strip_prefix("Description-en: "))
&& cur_desc.is_none()
{
cur_desc = Some(d.trim().to_string());
}
}
flush(
&mut seen,
&mut cur_name,
&mut cur_ver,
&mut cur_size,
&mut cur_desc,
);
let mut out: Vec<PackageModel> = seen.into_values().collect();
for (name, inst_pkg) in installed {
if !out.iter().any(|p| &p.name == name) {
let mut p = inst_pkg.clone();
p.is_upgradable = upgradable.contains(name);
out.push(p);
}
}
out
}
fn parse_apt_human_size_mb(num_str: &str, unit_str: &str) -> Option<f64> {
let cleaned_num = if num_str.contains(',') {
if !num_str.contains('.')
&& num_str
.rsplit_once(',')
.is_some_and(|(_, tail)| tail.len() != 3)
{
num_str.replace(',', ".")
} else {
num_str.replace(',', "")
}
} else {
num_str.to_string()
};
let val: f64 = cleaned_num.parse().ok()?;
let unit = unit_str
.split('/')
.next()
.unwrap_or(unit_str)
.trim_end_matches(['.', ',', ')']);
match unit {
"B" => Some(val / 1_048_576.0),
"kB" | "KiB" => Some(val / 1024.0),
"MB" | "MiB" => Some(val),
"GB" | "GiB" => Some(val * 1024.0),
_ => None,
}
}
fn parse_apt_pkg_list_line(line: &str) -> Vec<(String, String)> {
let mut items = Vec::new();
let mut rest = line.trim();
while !rest.is_empty() {
let token_end = rest.find(char::is_whitespace).unwrap_or(rest.len());
let raw_name = rest[..token_end].trim_end_matches('*');
rest = rest[token_end..].trim_start();
let version = if let Some(after_open) = rest.strip_prefix('(')
&& let Some(close_idx) = after_open.find(')')
{
let inner = after_open[..close_idx].trim();
let ver = inner
.rsplit_once("=>")
.map_or(inner, |(_, new_ver)| new_ver.trim());
rest = after_open[close_idx + 1..].trim_start();
ver.to_string()
} else {
"Unknown".to_string()
};
if !raw_name.is_empty() {
items.push((strip_arch(raw_name), version));
}
}
items
}
fn is_apt_summary_line(line: &str) -> bool {
line.split_whitespace()
.next()
.is_some_and(|w| w.chars().all(|c| c.is_ascii_digit()))
&& line.contains("upgraded")
}
pub fn parse_apt_get_install_dry_run(stdout: &str) -> Vec<InstallSummary> {
let mut summaries = Vec::new();
let mut section: Option<TransactionAction> = None;
let mut total_dl_mb = 0.0;
let mut total_inst_mb = 0.0;
for line in stdout.lines() {
let trimmed = line.trim();
if line.starts_with("The following NEW packages will be installed:")
|| line.starts_with("The following additional packages will be installed:")
{
section = Some(TransactionAction::Install);
continue;
} else if line.starts_with("The following packages will be upgraded:") {
section = Some(TransactionAction::Upgrade);
continue;
} else if line.starts_with("The following packages will be DOWNGRADED:") {
section = Some(TransactionAction::Downgrade);
continue;
} else if line.starts_with("The following packages will be REMOVED:") {
section = Some(TransactionAction::Remove);
continue;
} else if is_apt_summary_line(line) || line.starts_with("The following ") {
section = None;
}
if let Some(rest) = trimmed.strip_prefix("Need to get ") {
let parts: Vec<&str> = rest.split_whitespace().collect();
if parts.len() >= 2
&& let Some(mb) = parse_apt_human_size_mb(parts[0], parts[1])
{
total_dl_mb = mb;
}
} else if let Some(rest) = trimmed.strip_prefix("After this operation, ") {
let parts: Vec<&str> = rest.split_whitespace().collect();
if parts.len() >= 2
&& let Some(mb) = parse_apt_human_size_mb(parts[0], parts[1])
{
total_inst_mb = if trimmed.contains("freed") { -mb } else { mb };
}
}
if let Some(ref action) = section
&& line.starts_with(" ")
{
for (name, version) in parse_apt_pkg_list_line(line) {
summaries.push(InstallSummary {
action: action.clone(),
name,
version,
download_size_mb: 0.0,
install_size_mb: 0.0,
});
}
}
}
if let Some(first) = summaries.first_mut() {
first.download_size_mb = total_dl_mb;
first.install_size_mb = total_inst_mb;
}
summaries
}
pub fn parse_apt_conflicts(stdout: &str, requested: &[&str]) -> Vec<ConflictInfo> {
let req_set: HashSet<String> = requested.iter().map(|s| strip_arch(s)).collect();
let mut conflicts = Vec::new();
let requested_label = requested.join(", ");
for line in stdout.lines() {
if let Some(rest) = line.strip_prefix("Remv ")
&& let Some(name) = rest.split_whitespace().next()
{
let pkg = strip_arch(name);
if !req_set.contains(&pkg) {
conflicts.push(ConflictInfo {
incoming_pkg: requested_label.clone(),
installed_pkg: pkg,
constraint: Some("replaced or removed by apt solver".to_string()),
});
}
}
}
conflicts
}
pub fn parse_apt_upgrades(stdout: &str) -> Vec<(String, String, String)> {
let mut updates = Vec::new();
for line in stdout.lines() {
if let Some(rest) = line.strip_prefix("Inst ") {
let name = match rest.split_whitespace().next() {
Some(n) => strip_arch(n),
None => continue,
};
let old = rest
.split('[')
.nth(1)
.and_then(|s| s.split(']').next())
.unwrap_or("installed")
.trim()
.to_string();
let new = rest
.split('(')
.nth(1)
.and_then(|s| s.split_whitespace().next())
.unwrap_or("latest")
.trim()
.to_string();
updates.push((name, old, new));
} else if line.contains("[upgradable from:")
&& let Some((pkg_part, rest)) = line.split_once('/')
{
let name = strip_arch(pkg_part);
let mut cols = rest.split_whitespace();
let _suite = cols.next();
let new = cols.next().unwrap_or("latest").to_string();
let old = rest
.split("upgradable from:")
.nth(1)
.map(|s| s.trim_end_matches(']').trim().to_string())
.unwrap_or_else(|| "installed".to_string());
updates.push((name, old, new));
}
}
updates
}
pub fn parse_apt_autoremove(stdout: &str) -> Vec<String> {
let mut pkgs = Vec::new();
for line in stdout.lines() {
if let Some(rest) = line.strip_prefix("Remv ")
&& let Some(name) = rest.split_whitespace().next()
{
pkgs.push(strip_arch(name));
}
}
if !pkgs.is_empty() {
return pkgs;
}
let mut in_rem = false;
for line in stdout.lines() {
if line.starts_with("The following packages will be REMOVED:") {
in_rem = true;
} else if is_apt_summary_line(line) {
in_rem = false;
} else if in_rem && line.starts_with(" ") {
pkgs.extend(line.split_whitespace().map(strip_arch));
}
}
pkgs
}
fn push_apt_history_list(
entries: &mut Vec<HistoryEntry>,
date: &str,
action: &str,
list_str: &str,
upgrade_mode: bool,
) {
for pkg in list_str.split("), ") {
let parts: Vec<&str> = pkg.split(" (").collect();
if parts.len() >= 2 {
let name = strip_arch(parts[0].trim());
let ver = if upgrade_mode {
let versions: Vec<&str> = parts[1].split(", ").collect();
if versions.len() >= 2 {
versions[1].trim_end_matches(')').to_string()
} else {
parts[1].trim_end_matches(')').to_string()
}
} else {
parts[1].trim_end_matches(')').to_string()
};
entries.push(HistoryEntry {
timestamp: date.to_string(),
action: action.to_string(),
package: name,
version: ver,
});
}
}
}
pub fn parse_history_log(content: &str) -> Vec<HistoryEntry> {
let mut entries = Vec::new();
let mut current_date = String::new();
for line in content.lines() {
if let Some(date) = line.strip_prefix("Start-Date: ") {
current_date = date.trim().to_string();
} else if let Some(install) = line.strip_prefix("Install: ") {
push_apt_history_list(&mut entries, ¤t_date, "installed", install, false);
} else if let Some(upgrade) = line.strip_prefix("Upgrade: ") {
push_apt_history_list(&mut entries, ¤t_date, "upgraded", upgrade, true);
} else if let Some(remove) = line.strip_prefix("Remove: ") {
push_apt_history_list(&mut entries, ¤t_date, "removed", remove, false);
} else if let Some(purge) = line.strip_prefix("Purge: ") {
push_apt_history_list(&mut entries, ¤t_date, "removed", purge, false);
} else if let Some(downgrade) = line.strip_prefix("Downgrade: ") {
push_apt_history_list(&mut entries, ¤t_date, "downgraded", downgrade, true);
}
}
entries
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_apt_cache_search() {
let output = "rustc - Rust compiler\nrust-gdb - Rust debugger (gdb)\n";
let pkgs = parse_apt_cache_search(output);
assert_eq!(pkgs.len(), 2);
assert_eq!(pkgs[0].name, "rustc");
assert_eq!(pkgs[1].name, "rust-gdb");
}
#[test]
fn test_parse_apt_cache_show() {
let output = "Package: ripgrep\nVersion: 13.0.0-2\nArchitecture: amd64\nInstalled-Size: 4096\nSize: 1234567\nDepends: libc6 (>= 2.34), libpcre2-8-0\nSuggests: bash-completion\nDescription: fast line-oriented search tool\n";
let pkg = parse_apt_cache_show(output, "ripgrep").unwrap();
assert_eq!(pkg.name, "ripgrep");
assert_eq!(pkg.version, "13.0.0-2");
assert!((pkg.size_mb - (1234567.0 / 1_048_576.0)).abs() < 0.001);
let details = parse_apt_cache_show_details(output, "ripgrep").unwrap();
assert_eq!(details.depends, vec!["libc6 (>= 2.34)", "libpcre2-8-0"]);
assert_eq!(details.opt_depends, vec!["bash-completion"]);
assert_eq!(
details.package.desc.as_deref(),
Some("fast line-oriented search tool")
);
}
#[test]
fn test_parse_dpkg_query_list() {
let output = "bash\t5.1-6ubuntu1\tinstall ok installed\t1536\ncurl\t7.81.0\tinstall ok installed\t512\n";
let pkgs = parse_dpkg_query_list(output);
assert_eq!(pkgs.len(), 2);
assert_eq!(pkgs[0].name, "bash");
assert_eq!(pkgs[0].version, "5.1-6ubuntu1");
assert!((pkgs[0].size_mb - 1.5).abs() < 0.001);
assert_eq!(pkgs[1].name, "curl");
}
#[test]
fn test_parse_apt_get_install_dry_run() {
let output = "Reading package lists... Done\nBuilding dependency tree... Done\nThe following NEW packages will be installed:\n ripgrep (13.0.0-2) fzf (0.29.0-1)\n0 upgraded, 2 newly installed, 0 to remove and 0 not upgraded.\nNeed to get 2560 kB of archives.\nAfter this operation, 12.5 MB of additional disk space will be used.\n";
let summaries = parse_apt_get_install_dry_run(output);
assert_eq!(summaries.len(), 2);
assert_eq!(summaries[0].name, "ripgrep");
assert_eq!(summaries[0].version, "13.0.0-2");
assert!((summaries[0].download_size_mb - 2.5).abs() < 0.01);
assert!((summaries[0].install_size_mb - 12.5).abs() < 0.01);
assert_eq!(summaries[1].name, "fzf");
assert_eq!(summaries[1].version, "0.29.0-1");
}
#[test]
fn test_parse_apt_get_install_dry_run_wrapped() {
let output = "Reading package lists... Done\nBuilding dependency tree... Done\nThe following NEW packages will be installed:\n fzf ripgrep zsh\n0 upgraded, 3 newly installed, 0 to remove.\n";
let summaries = parse_apt_get_install_dry_run(output);
assert_eq!(summaries.len(), 3);
assert_eq!(summaries[0].name, "fzf");
assert_eq!(summaries[0].version, "Unknown");
assert_eq!(summaries[1].name, "ripgrep");
assert_eq!(summaries[2].name, "zsh");
}
#[test]
fn test_strip_arch() {
let output = "bash:amd64\t5.1\tinstall ok installed\n";
let pkgs = parse_dpkg_query_list(output);
assert_eq!(pkgs[0].name, "bash");
}
#[test]
fn test_parse_history_log() {
let output = "Start-Date: 2023-10-01 12:00:00\nCommandline: apt-get install vim\nInstall: vim:amd64 (2:8.2.3995-1ubuntu2.1)\nEnd-Date: 2023-10-01 12:00:05\n\nStart-Date: 2023-10-02 14:00:00\nCommandline: apt-get upgrade\nUpgrade: curl:amd64 (7.81.0-1, 7.81.0-1ubuntu1.2)\nRemove: nano:amd64 (6.2-1)\nEnd-Date: 2023-10-02 14:00:10\n";
let history = parse_history_log(output);
assert_eq!(history.len(), 3);
assert_eq!(history[0].action, "installed");
assert_eq!(history[0].package, "vim");
assert_eq!(history[0].version, "2:8.2.3995-1ubuntu2.1");
assert_eq!(history[1].action, "upgraded");
assert_eq!(history[1].package, "curl");
assert_eq!(history[1].version, "7.81.0-1ubuntu1.2");
assert_eq!(history[2].action, "removed");
assert_eq!(history[2].package, "nano");
}
#[test]
fn test_parse_apt_upgrades_and_autoremove_and_conflicts() {
let upgrades_out = "NOTE: This is only a simulation!\nInst bash [5.1-6ubuntu1] (5.2-1 Ubuntu:24.04/noble [amd64])\nInst curl [7.81] (8.5.0 Debian:testing [amd64])\n";
let up = parse_apt_upgrades(upgrades_out);
assert_eq!(up.len(), 2);
assert_eq!(
up[0],
("bash".into(), "5.1-6ubuntu1".into(), "5.2-1".into())
);
let autoremove_out = "The following packages will be REMOVED:\n libfoo* libbar*\n2 upgraded, 0 newly installed, 2 to remove and 1 not upgraded.\nRemv libfoo [1.0-1]\nRemv libbar [2.1-3]\n";
let orphans = parse_apt_autoremove(autoremove_out);
assert_eq!(orphans, vec!["libfoo", "libbar"]);
let wrapped_only = "The following packages will be REMOVED:\n libbaz\n1 upgraded, 0 newly installed, 1 to remove.\n";
assert_eq!(parse_apt_autoremove(wrapped_only), vec!["libbaz"]);
let conflict_out =
"Remv exim4-daemon-light [4.95]\nInst postfix (3.8.6 Ubuntu:24.04/noble)\n";
let conflicts = parse_apt_conflicts(conflict_out, &["postfix"]);
assert_eq!(conflicts.len(), 1);
assert_eq!(conflicts[0].installed_pkg, "exim4-daemon-light");
}
#[test]
fn test_parse_apt_dumpavail_merges_installed_and_upgradable() {
let dump = "Package: ripgrep\nVersion: 14.0.0-1\nInstalled-Size: 2048\nDescription: fast grep\n\nPackage: htop\nVersion: 3.3.0-1\nSize: 524288\nDescription: process viewer\n";
let mut installed = HashMap::new();
installed.insert(
"ripgrep".into(),
PackageModel {
name: "ripgrep".into(),
version: "13.0.0-1".into(),
repo: "local".into(),
is_installed: true,
is_upgradable: false,
size_mb: 1.5,
desc: None,
},
);
let upgradable = HashSet::from(["ripgrep".to_string()]);
let merged = parse_apt_dumpavail(dump, &installed, &upgradable);
assert_eq!(merged.len(), 2);
let rg = merged.iter().find(|p| p.name == "ripgrep").unwrap();
assert!(rg.is_installed);
assert!(rg.is_upgradable);
assert_eq!(rg.version, "13.0.0-1");
}
#[test]
fn test_parse_apt_dry_run_verbose_upgrade_partial_cache_and_downgrade() {
let output = "\
Reading package lists... Done
The following packages will be upgraded:
bash (5.1-6 => 5.2-1) curl (7.88 => 8.5.0)
The following packages will be DOWNGRADED:
nano (7.2-1 => 7.0-1)
1 upgraded, 0 newly installed, 1 downgraded, 0 to remove and 0 not upgraded.
Need to get 1,024 kB/2,048 kB of archives.
After this operation, 1,024 kB of additional disk space will be used.
";
let summaries = parse_apt_get_install_dry_run(output);
assert_eq!(summaries.len(), 3);
assert_eq!(summaries[0].name, "bash");
assert_eq!(summaries[0].version, "5.2-1");
assert_eq!(summaries[0].action, TransactionAction::Upgrade);
assert!((summaries[0].download_size_mb - 1.0).abs() < 0.01);
assert!((summaries[0].install_size_mb - 1.0).abs() < 0.01);
assert_eq!(summaries[1].name, "curl");
assert_eq!(summaries[1].version, "8.5.0");
assert_eq!(summaries[2].name, "nano");
assert_eq!(summaries[2].action, TransactionAction::Downgrade);
assert_eq!(summaries[2].version, "7.0-1");
let partial_zero = "\
The following NEW packages will be installed:
fd (8.7.0)
0 upgraded, 1 newly installed, 0 to remove.
Need to get 0 B/1,536 kB of archives.
After this operation, 4,096 kB of additional disk space will be used.
";
let zero_dl = parse_apt_get_install_dry_run(partial_zero);
assert_eq!(zero_dl.len(), 1);
assert!(zero_dl[0].download_size_mb < 0.001);
assert!((zero_dl[0].install_size_mb - 4.0).abs() < 0.01);
}
}