Compare commits

3 Commits
Author SHA256 Message Date
sisungo 57a6f5e936 fix: invalid chinese translations in packie-cli
Signed-off-by: sisungo <[email protected]>
2026-11-25 07:16:55 +00:00
sisungo 35b29cb3a7 feat(breaking): refactor local database format to allow multi-pkgspec
Signed-off-by: sisungo <[email protected]>
2026-11-25 06:52:22 +00:00
sisungo e13995eab2 feat: use migrations for database
Signed-off-by: sisungo <[email protected]>
2026-11-22 13:06:19 +00:00
26 changed files with 1086 additions and 499 deletions

No files matched your search

+2 -2
View File
@@ -33,7 +33,7 @@ sha3 = "0.12"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
toml = "1" toml = "1"
rusqlite = { version = "0.41" } rusqlite = { version = "0.43" }
# Error handling # Error handling
thiserror = "2" thiserror = "2"
@@ -47,4 +47,4 @@ rustc-hash = "2"
# Misc # Misc
rust-i18n = "4" rust-i18n = "4"
nix = { version = "0.31", features = ["fs"] } nix = { version = "0.32", features = ["fs"] }
+2 -1
View File
@@ -12,9 +12,10 @@ anyhow = "1"
chrono = "0.4" chrono = "0.4"
clap = { version = "4", features = ["derive"] } clap = { version = "4", features = ["derive"] }
console = "0.16" console = "0.16"
nix = { version = "0.31", features = ["sched"] } nix = { version = "0.32", features = ["sched"] }
packie = { path = "../" } packie = { path = "../" }
rust-i18n = "4" rust-i18n = "4"
rustc-hash = "2"
tabled = { version = "0.22", features = ["ansi"] } tabled = { version = "0.22", features = ["ansi"] }
indicatif = "0.18" indicatif = "0.18"
dialoguer = "0.12" dialoguer = "0.12"
+58
View File
@@ -0,0 +1,58 @@
use crate::common::{SummaryItem, print_summary, yesno};
use anyhow::anyhow;
use clap::Parser;
use console::style;
use indicatif::ProgressBar;
use packie::PackieBuilder;
use rust_i18n::t;
#[derive(Debug, Parser)]
pub struct Cli {
#[arg(short, long)]
yes: bool,
}
pub fn main(cli: Cli) -> Result<(), crate::Error> {
let mut packie = PackieBuilder::new().build()?;
let packages = packie.calculate_autoremove()?;
if packages.is_empty() {
Err(anyhow!("{}", t!("autoremove.no_packages_to_remove")))?;
}
let summary = packages
.iter()
.map(|x| SummaryItem {
pkgspec: x.clone().into(),
pkgident: x.clone(),
operation: SummaryItem::REMOVE,
})
.collect();
println!("{}", t!("autoremove.prompt_to_remove"));
println!();
print_summary(summary);
println!();
if cli.yes {
println!("y");
} else if !yesno(&t!("autoremove.confirm_removal"), false) {
println!("{}", t!("autoremove.aborting"));
return Ok(());
}
let nr_packages = packages.len();
let progress_bar = ProgressBar::new(nr_packages as _);
for (c, i) in packages.into_iter().enumerate() {
progress_bar.println(format!(
"[{}/{}] {}",
c + 1,
nr_packages,
t!("autoremove.action_hint", package = style(&i).red()),
));
packie
.remove(&i.clone().into())
.map_err(|error| anyhow!("{}", t!("autoremove.action_failure", error = error)))?;
progress_bar.inc(1);
}
Ok(())
}
+36 -29
View File
@@ -4,11 +4,12 @@ use dialoguer::Confirm;
use indicatif::{HumanBytes, ProgressBar, ProgressStyle}; use indicatif::{HumanBytes, ProgressBar, ProgressStyle};
use packie::{ use packie::{
Packie, Packie,
local::Installation, local::LocalPackage,
package::{PkgIdent, PkgSpec}, package::{PkgIdent, PkgSpec},
repo::{DownloadPackageEvent, RepoPackage}, repo::{DownloadPackageEvent, RepoPackage},
}; };
use rust_i18n::t; use rust_i18n::t;
use rustc_hash::FxHashMap;
use std::{fmt::Display, path::PathBuf}; use std::{fmt::Display, path::PathBuf};
use tabled::{ use tabled::{
Table, Tabled, Table, Tabled,
@@ -58,6 +59,7 @@ pub struct SummaryItem {
impl SummaryItem { impl SummaryItem {
pub const INSTALL: &str = "install"; pub const INSTALL: &str = "install";
pub const REMOVE: &str = "remove"; pub const REMOVE: &str = "remove";
pub const SET_MANUAL_INSTALL: &str = "set-manual-install";
} }
#[derive(Debug, Tabled)] #[derive(Debug, Tabled)]
@@ -69,19 +71,23 @@ struct PrintedSummaryItem {
} }
impl From<SummaryItem> for PrintedSummaryItem { impl From<SummaryItem> for PrintedSummaryItem {
fn from(value: SummaryItem) -> Self { fn from(value: SummaryItem) -> Self {
let wrap_color = |s: &dyn Display| { let wrap_color = |s: &dyn Display| match value.operation {
if value.operation == SummaryItem::INSTALL { SummaryItem::INSTALL => console::style(s.to_string()).green(),
format!("{}", console::style(s).green()) SummaryItem::REMOVE => console::style(s.to_string()).red(),
} else if value.operation == SummaryItem::REMOVE { SummaryItem::SET_MANUAL_INSTALL => console::style(s.to_string()).blue(),
format!("{}", console::style(s).red()) _ => console::style(s.to_string()).blue(),
} else {
format!("{}", console::style(s).blue())
}
}; };
let operation = wrap_color(&match value.operation {
SummaryItem::INSTALL => t!("common.SummaryItem.INSTALL"),
SummaryItem::REMOVE => t!("common.SummaryItem.REMOVE"),
SummaryItem::SET_MANUAL_INSTALL => t!("common.SummaryItem.SET_MANUAL_INSTALL"),
other => other.into(),
})
.to_string();
Self { Self {
pkgspec: wrap_color(&value.pkgspec), pkgspec: wrap_color(&value.pkgspec).to_string(),
version: wrap_color(&value.pkgident.version), version: wrap_color(&value.pkgident.version).to_string(),
operation: wrap_color(&value.operation), operation,
notes: String::new(), notes: String::new(),
} }
} }
@@ -97,7 +103,7 @@ pub fn print_summary(summary: Vec<SummaryItem>) {
} }
pub fn format_size(bytes: i64) -> String { pub fn format_size(bytes: i64) -> String {
if bytes.is_positive() { if !bytes.is_negative() {
HumanBytes(bytes as u64).to_string() HumanBytes(bytes as u64).to_string()
} else { } else {
format!("-{}", HumanBytes(bytes.abs() as u64)) format!("-{}", HumanBytes(bytes.abs() as u64))
@@ -114,8 +120,8 @@ pub fn format_datetime(timestamp: i64) -> String {
pub fn search_unique_package( pub fn search_unique_package(
packie: &mut Packie, packie: &mut Packie,
pkgspec: &PkgSpec, pkgspec: &PkgSpec,
) -> Result<Installation, crate::Error> { ) -> Result<LocalPackage, crate::Error> {
let mut found = packie.search_installation(&pkgspec)?; let mut found = packie.search_local_package(&pkgspec)?;
if found.is_empty() { if found.is_empty() {
return Err(crate::error!("common.package_not_found", pkgspec = pkgspec)); return Err(crate::error!("common.package_not_found", pkgspec = pkgspec));
} }
@@ -136,29 +142,29 @@ pub fn search_unique_package(
Ok(found.remove(0)) Ok(found.remove(0))
} }
pub fn download_packages<T>( pub fn download_packages<'a>(
packie: &mut Packie, packie: &mut Packie,
packages: &mut Vec<(T, PathBuf)>, all: impl IntoIterator<Item = &'a RepoPackage> + Clone,
pkginfo: impl Fn(&T) -> &RepoPackage, ) -> Result<FxHashMap<PkgIdent, PathBuf>, crate::Error> {
) -> Result<(), crate::Error> { let mut result = FxHashMap::default();
let download_size = packages.iter().map(|x| pkginfo(&x.0).download_size).sum();
let download_size = all.clone().into_iter().map(|x| x.download_size).sum();
let progress_bar = let progress_bar =
ProgressBar::new(download_size).with_style(crate::common::progress_style_multidownload()); ProgressBar::new(download_size).with_style(crate::common::progress_style_multidownload());
let nr_packages = packages.len(); let nr_packages = all.clone().into_iter().count();
for (count, (package, file_path)) in packages.iter_mut().enumerate() { for (count, it) in all.into_iter().enumerate() {
let repo_pkg = pkginfo(package);
let init_pos = progress_bar.position(); let init_pos = progress_bar.position();
progress_bar.println(format!( progress_bar.println(format!(
"[{}/{nr_packages}] {}", "[{}/{nr_packages}] {}",
count + 1, count + 1,
t!( t!(
"common.download_packages.downloading_hint", "common.download_packages.downloading_hint",
pkg = style(repo_pkg.pkg_manifest.pkg_ident()).green(), pkg = style(it.pkg_manifest.pkg_ident()).green(),
), ),
)); ));
progress_bar.set_prefix(repo_pkg.pkg_manifest.pkg_ident().to_string()); progress_bar.set_prefix(it.pkg_manifest.pkg_ident().to_string());
let path = packie.download_package(&repo_pkg.repo_pkg_ident().unwrap(), |ev| match ev { let path = packie.download_package(&it.repo_pkg_ident().unwrap(), |ev| match ev {
DownloadPackageEvent::Progress(_, sum, _) => { DownloadPackageEvent::Progress(_, sum, _) => {
progress_bar.set_position(init_pos + sum); progress_bar.set_position(init_pos + sum);
} }
@@ -174,9 +180,10 @@ pub fn download_packages<T>(
)); ));
} }
})?; })?;
*file_path = path; result.insert(it.pkg_manifest.pkg_ident(), path);
progress_bar.set_position(init_pos + repo_pkg.download_size); progress_bar.set_position(init_pos + it.download_size);
} }
drop(progress_bar); drop(progress_bar);
Ok(()) Ok(result)
} }
+6 -8
View File
@@ -3,7 +3,7 @@ use clap::Parser;
use console::style; use console::style;
use packie::{ use packie::{
PackieBuilder, PackieBuilder,
local::{InstallFlags, Installation}, local::LocalPackage,
package::{PkgManifest, PkgSpec}, package::{PkgManifest, PkgSpec},
repo::RepoPackage, repo::RepoPackage,
}; };
@@ -36,15 +36,13 @@ pub fn main(cli: Cli) -> Result<(), crate::Error> {
); );
} }
let local = packie.search_installation(&cli.pkgspec)?; let local = packie.search_local_package(&cli.pkgspec)?;
for i in local { for i in local {
let val = everything let val = everything
.entry(i.pkg_manifest.pkg_ident()) .entry(i.pkg_manifest.pkg_ident())
.or_insert_with(|| ComprehensivePackageInfo::from(i.clone())); .or_insert_with(|| ComprehensivePackageInfo::from(i.clone()));
val.installed = true; val.installed = true;
val.installed_size = i.installed_size; val.installed_size = i.installed_size;
val.install_pkgspec = Some(i.install_pkgspec);
val.auto_installed = Some(i.install_flags.contains(InstallFlags::AUTO_INSTALL));
val.install_date = Some(i.install_date); val.install_date = Some(i.install_date);
} }
@@ -83,16 +81,16 @@ impl From<RepoPackage> for ComprehensivePackageInfo {
} }
} }
} }
impl From<Installation> for ComprehensivePackageInfo { impl From<LocalPackage> for ComprehensivePackageInfo {
fn from(value: Installation) -> Self { fn from(value: LocalPackage) -> Self {
Self { Self {
pkg_manifest: value.pkg_manifest, pkg_manifest: value.pkg_manifest,
installed: true, installed: true,
install_pkgspec: Some(value.install_pkgspec), install_pkgspec: None,
install_date: Some(value.install_date), install_date: Some(value.install_date),
download_size: None, download_size: None,
installed_size: value.installed_size, installed_size: value.installed_size,
auto_installed: Some(value.install_flags.contains(InstallFlags::AUTO_INSTALL)), auto_installed: None,
} }
} }
} }
+109 -36
View File
@@ -3,10 +3,13 @@ use clap::Parser;
use console::style; use console::style;
use indicatif::ProgressBar; use indicatif::ProgressBar;
use packie::{ use packie::{
PackieBuilder, graph::CalculateInstallationOptions, install::InstallOptions, package::PkgSpec, Packie, PackieBuilder,
graph::{CalculateInstallationOptions, InstallationAction},
install::InstallOptions,
local::InstallFlags,
package::PkgSpec,
}; };
use rust_i18n::t; use rust_i18n::t;
use std::path::PathBuf;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Cli { pub struct Cli {
@@ -36,27 +39,30 @@ pub fn main(cli: Cli) -> Result<(), crate::Error> {
items.push(i.parse::<PkgSpec>()?); items.push(i.parse::<PkgSpec>()?);
} }
let mut packages: Vec<(_, PathBuf)> = packie let actions: Vec<_> =
.calculate_installation(&items, &CalculateInstallationOptions::new())? packie.calculate_installation(&items, &CalculateInstallationOptions::new())?;
.into_iter()
.map(|x| (x, PathBuf::new())) let download_size: u64 = actions
.collect(); .iter()
if packages.is_empty() { .map(|x| match x {
InstallationAction::InstallFromRepo(ir) => ir.repo_pkg.download_size,
_ => 0,
})
.sum();
let installed_size: u64 = actions
.iter()
.map(|x| match x {
InstallationAction::InstallFromRepo(ir) => ir.repo_pkg.installed_size,
_ => 0,
})
.sum();
let summary = summarize_actions(&mut packie, &actions);
if summary.is_empty() {
eprintln!("{}", t!("install.no_package_to_install")); eprintln!("{}", t!("install.no_package_to_install"));
return Ok(()); return Ok(());
} }
let download_size: u64 = packages.iter().map(|x| x.0.repo_pkg.download_size).sum();
let installed_size: u64 = packages.iter().map(|x| x.0.repo_pkg.installed_size).sum();
let summary = packages
.iter()
.map(|(x, _)| SummaryItem {
pkgspec: x.install_pkgspec.clone(),
pkgident: x.repo_pkg.pkg_manifest.pkg_ident(),
operation: SummaryItem::INSTALL,
})
.collect();
println!("{}", t!("install.prompt_to_install")); println!("{}", t!("install.prompt_to_install"));
println!(); println!();
print_summary(summary); print_summary(summary);
@@ -82,27 +88,94 @@ pub fn main(cli: Cli) -> Result<(), crate::Error> {
return Ok(()); return Ok(());
} }
crate::common::download_packages(&mut packie, &mut packages, |x| &x.repo_pkg)?; let downloaded = crate::common::download_packages(
&mut packie,
actions.iter().filter_map(|x| match x {
InstallationAction::InstallFromRepo(ir) => Some(&ir.repo_pkg),
_ => None,
}),
)?;
let nr_packages = packages.len(); let nr_actions = actions
let progress_bar = ProgressBar::new(nr_packages as _); .iter()
for (count, (package, file_path)) in packages.into_iter().enumerate() { .filter(|x| matches!(x, InstallationAction::InstallFromRepo(_)))
progress_bar.println(format!( .count();
"[{}/{nr_packages}] {}", let progress_bar = ProgressBar::new(nr_actions as _);
count + 1, let mut count = 1;
t!( for action in actions {
"install.installing_hint", match action {
pkgspec = style(&package.install_pkgspec).green() InstallationAction::InstallFromRepo(req) => {
) progress_bar.println(format!(
)); "[{}/{nr_actions}] {}",
count,
t!(
"install.installing_hint",
pkgspec = style(&req.repo_pkg.pkg_manifest.pkg_ident()).green()
)
));
let mut options = InstallOptions::default(); packie.install_package_file(
options.auto_installed = package.auto_installed; downloaded
options.install_pkgspec = Some(package.install_pkgspec); .get(&req.repo_pkg.pkg_manifest.pkg_ident())
packie.install_package_file(file_path, &options)?; .unwrap(),
&InstallOptions::default(),
)?;
progress_bar.inc(1); count += 1;
progress_bar.inc(1);
}
InstallationAction::EnsureInstallation(req) => {
let mut install_flags = InstallFlags::default();
if req.auto_installed {
install_flags.set(InstallFlags::AUTO_INSTALL);
}
packie.ensure_installation(
req.install_pkgspec,
req.pkg_ident,
install_flags,
req.force,
)?;
}
}
} }
Ok(()) Ok(())
} }
fn summarize_actions(packie: &mut Packie, actions: &[InstallationAction]) -> Vec<SummaryItem> {
let mut result = Vec::with_capacity(actions.len());
for action in actions {
match action {
InstallationAction::InstallFromRepo(x) => {
result.push(SummaryItem {
pkgspec: x.repo_pkg.pkg_manifest.pkg_ident().into(),
pkgident: x.repo_pkg.pkg_manifest.pkg_ident(),
operation: SummaryItem::INSTALL,
});
}
InstallationAction::EnsureInstallation(x) => {
let needs_update = match packie.select_installation(&x.install_pkgspec) {
Ok(existing) => {
let has_auto_installed =
existing.install_flags.contains(InstallFlags::AUTO_INSTALL);
let needs_manual_install = !x.auto_installed;
needs_manual_install && has_auto_installed
}
Err(_) => {
let installed = packie.select_local_package(&x.pkg_ident).is_ok();
let needs_manual_install = !x.auto_installed;
installed && needs_manual_install
}
};
if needs_update {
result.push(SummaryItem {
pkgspec: x.install_pkgspec.clone(),
pkgident: x.pkg_ident.clone(),
operation: SummaryItem::SET_MANUAL_INSTALL,
});
}
}
}
}
result
}
+5
View File
@@ -1,3 +1,4 @@
mod autoremove;
mod clean; mod clean;
mod common; mod common;
mod info; mod info;
@@ -50,6 +51,9 @@ enum Subcommand {
/// Remove one or more packages /// Remove one or more packages
Remove(remove::Cli), Remove(remove::Cli),
/// Auto-remove orphan packages
Autoremove(autoremove::Cli),
/// Administrate repository service /// Administrate repository service
RepoAdmin(repo_admin::Cli), RepoAdmin(repo_admin::Cli),
@@ -85,6 +89,7 @@ fn main() {
Subcommand::Upgrade(cli) => upgrade::main(cli), Subcommand::Upgrade(cli) => upgrade::main(cli),
Subcommand::Print(cli) => print::main(cli), Subcommand::Print(cli) => print::main(cli),
Subcommand::Remove(cli) => remove::main(cli), Subcommand::Remove(cli) => remove::main(cli),
Subcommand::Autoremove(cli) => autoremove::main(cli),
Subcommand::RepoAdmin(cli) => repo_admin::main(cli), Subcommand::RepoAdmin(cli) => repo_admin::main(cli),
Subcommand::Update(cli) => update::main(cli), Subcommand::Update(cli) => update::main(cli),
Subcommand::Select(cli) => select::main(cli), Subcommand::Select(cli) => select::main(cli),
+2 -2
View File
@@ -27,10 +27,10 @@ fn profile(other: &[&str]) -> anyhow::Result<String> {
} }
fn package(other: &[&str]) -> anyhow::Result<String> { fn package(other: &[&str]) -> anyhow::Result<String> {
let mut packie = PackieBuilder::new().readonly(true).build()?; let packie = PackieBuilder::new().readonly(true).build()?;
match other { match other {
["prefix", ..] => { ["prefix", ..] => {
let mut found = packie.search_installation(&other[1..].join(".").parse()?)?; let mut found = packie.search_local_package(&other[1..].join(".").parse()?)?;
if found.is_empty() { if found.is_empty() {
return Err(anyhow!("package not found")); return Err(anyhow!("package not found"));
} }
+3 -3
View File
@@ -28,7 +28,7 @@ pub fn main(cli: Cli) -> Result<(), crate::Error> {
let summary = packages let summary = packages
.iter() .iter()
.map(|x| SummaryItem { .map(|x| SummaryItem {
pkgspec: x.install_pkgspec.clone(), pkgspec: x.pkg_ident.clone().into(),
pkgident: x.pkg_manifest.pkg_ident(), pkgident: x.pkg_manifest.pkg_ident(),
operation: SummaryItem::REMOVE, operation: SummaryItem::REMOVE,
}) })
@@ -48,7 +48,7 @@ pub fn main(cli: Cli) -> Result<(), crate::Error> {
let progress_bar = ProgressBar::new(nr_packages as _); let progress_bar = ProgressBar::new(nr_packages as _);
for (c, i) in packages.into_iter().enumerate() { for (c, i) in packages.into_iter().enumerate() {
println!( progress_bar.println(format!(
"[{}/{}] {}", "[{}/{}] {}",
c + 1, c + 1,
nr_packages, nr_packages,
@@ -56,7 +56,7 @@ pub fn main(cli: Cli) -> Result<(), crate::Error> {
"remove.action_hint", "remove.action_hint",
package = style(i.pkg_manifest.pkg_ident()).red() package = style(i.pkg_manifest.pkg_ident()).red()
), ),
); ));
packie packie
.remove(&i.pkg_manifest.pkg_ident().into()) .remove(&i.pkg_manifest.pkg_ident().into())
.map_err(|error| anyhow!("{}", t!("remove.action_failure", error = error)))?; .map_err(|error| anyhow!("{}", t!("remove.action_failure", error = error)))?;
+3 -3
View File
@@ -47,7 +47,7 @@ fn non_interactive(
file: PathBuf, file: PathBuf,
pkg: PkgSpec, pkg: PkgSpec,
) -> Result<Option<(PkgIdent, LinkDescription)>, crate::Error> { ) -> Result<Option<(PkgIdent, LinkDescription)>, crate::Error> {
let installations = packie.search_installation(&pkg)?; let installations = packie.search_local_package(&pkg)?;
let mut candidates = Vec::with_capacity(installations.len()); let mut candidates = Vec::with_capacity(installations.len());
for pkgident in installations.iter().map(|x| x.pkg_manifest.pkg_ident()) { for pkgident in installations.iter().map(|x| x.pkg_manifest.pkg_ident()) {
let links = packie.links_of_pkg(&pkgident); let links = packie.links_of_pkg(&pkgident);
@@ -79,8 +79,8 @@ fn interactive(
) -> Result<Option<(PkgIdent, LinkDescription)>, crate::Error> { ) -> Result<Option<(PkgIdent, LinkDescription)>, crate::Error> {
let mut all_pkgs = Vec::with_capacity(1024); let mut all_pkgs = Vec::with_capacity(1024);
let mut candidates = Vec::new(); let mut candidates = Vec::new();
packie.for_each_installation::<anyhow::Error>(|inst| { packie.for_each_local_package::<anyhow::Error>(|inst| {
all_pkgs.push(inst.pkg_manifest.pkg_ident()); all_pkgs.push(inst.pkg_ident.clone());
Ok(()) Ok(())
})?; })?;
for pkgident in all_pkgs { for pkgident in all_pkgs {
+79 -69
View File
@@ -3,11 +3,10 @@ use clap::Parser;
use console::style; use console::style;
use indicatif::ProgressBar; use indicatif::ProgressBar;
use packie::{ use packie::{
PackieBuilder, graph::UpgradationOp, install::InstallOptions, local::InstallFlags, PackieBuilder, graph::UpgradationAction, install::InstallOptions, local::InstallFlags,
package::PkgSpec, package::PkgSpec,
}; };
use rust_i18n::t; use rust_i18n::t;
use std::path::PathBuf;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Cli { pub struct Cli {
@@ -20,56 +19,54 @@ pub struct Cli {
pub fn main(cli: Cli) -> Result<(), crate::Error> { pub fn main(cli: Cli) -> Result<(), crate::Error> {
let mut packie = PackieBuilder::new().build()?; let mut packie = PackieBuilder::new().build()?;
let ops = packie.calculate_upgradation(cli.items)?; let actions = packie.calculate_upgradation(cli.items)?;
if ops.is_empty() { let mut ui_summary = Vec::with_capacity(actions.len());
for action in &actions {
match action {
UpgradationAction::InstallFromRepo(req) => {
ui_summary.push(SummaryItem {
pkgspec: req.repo_pkg.pkg_manifest.pkg_ident().into(),
pkgident: req.repo_pkg.pkg_manifest.pkg_ident(),
operation: SummaryItem::INSTALL,
});
}
UpgradationAction::Remove(pkg) => {
ui_summary.push(SummaryItem {
pkgspec: pkg.clone().into(),
pkgident: pkg.clone(),
operation: SummaryItem::REMOVE,
});
}
_ => (),
}
}
if ui_summary.is_empty() {
eprintln!("{}", t!("upgrade.nothing_to_do")); eprintln!("{}", t!("upgrade.nothing_to_do"));
return Ok(()); return Ok(());
} }
println!("{}", t!("upgrade.prompt_to_upgrade")); println!("{}", t!("upgrade.prompt_to_upgrade"));
println!(); println!();
let mut ui_summary = Vec::with_capacity(ops.len()); print_summary(ui_summary.clone());
for op in &ops {
match op {
UpgradationOp::Install(dep) => {
ui_summary.push(SummaryItem {
pkgspec: dep.install_pkgspec.clone(),
pkgident: dep.repo_pkg.pkg_manifest.pkg_ident(),
operation: SummaryItem::INSTALL,
});
}
UpgradationOp::Replace(rep) => {
ui_summary.push(SummaryItem {
pkgspec: rep.original.install_pkgspec.clone(),
pkgident: rep.new.pkg_manifest.pkg_ident(),
operation: SummaryItem::INSTALL,
});
ui_summary.push(SummaryItem {
pkgspec: rep.original.install_pkgspec.clone(),
pkgident: rep.original.pkg_manifest.pkg_ident(),
operation: SummaryItem::REMOVE,
});
}
}
}
print_summary(ui_summary);
println!(); println!();
let download_size: u64 = ops let download_size: u64 = actions
.iter() .iter()
.map(|x| match x { .map(|x| match x {
UpgradationOp::Install(dep) => dep.repo_pkg.download_size, UpgradationAction::InstallFromRepo(req) => req.repo_pkg.download_size,
UpgradationOp::Replace(rep) => rep.new.download_size, _ => 0,
}) })
.sum(); .sum();
let installed_size = ops let installed_size = actions
.iter() .iter()
.map(|x| match x { .map(|x| match x {
UpgradationOp::Install(dep) => dep.repo_pkg.installed_size as i64, UpgradationAction::InstallFromRepo(req) => req.repo_pkg.installed_size as i64,
UpgradationOp::Replace(rep) => { UpgradationAction::Remove(pkg_ident) => packie
(rep.new.installed_size as i64) - (rep.original.installed_size as i64) .select_local_package(pkg_ident)
} .map(|y| -(y.installed_size as i64))
.unwrap_or_default(),
_ => 0,
}) })
.sum(); .sum();
@@ -92,52 +89,65 @@ pub fn main(cli: Cli) -> Result<(), crate::Error> {
return Ok(()); return Ok(());
} }
let mut ops = ops.into_iter().map(|x| (x, PathBuf::new())).collect(); let downloaded = crate::common::download_packages(
crate::common::download_packages(&mut packie, &mut ops, |x| match x { &mut packie,
UpgradationOp::Install(x) => &x.repo_pkg, actions.iter().filter_map(|x| match x {
UpgradationOp::Replace(x) => &x.new, UpgradationAction::InstallFromRepo(req) => Some(&req.repo_pkg),
})?; _ => None,
}),
)?;
let nr_ops = ops.len(); let nr_actions = ui_summary.len();
let progress_bar = ProgressBar::new(ops.len() as _); let progress_bar = ProgressBar::new(nr_actions as _);
for (op, file_path) in ops { let mut count = 1;
match op { for action in actions {
UpgradationOp::Install(dep) => { match action {
UpgradationAction::InstallFromRepo(req) => {
progress_bar.println(format!( progress_bar.println(format!(
"[{}/{}] {}", "[{}/{}] {}",
progress_bar.position() + 1, count,
nr_ops, nr_actions,
t!( t!(
"upgrade.installing_hint", "upgrade.installing_hint",
pkg = style(&dep.install_pkgspec).green(), pkg = style(&req.repo_pkg.pkg_manifest.pkg_ident()).green(),
) )
)); ));
progress_bar.inc(1);
count += 1;
let mut options = InstallOptions::default(); let mut options = InstallOptions::default();
options.auto_installed = dep.auto_installed; if req.override_links {
options.install_pkgspec = Some(dep.install_pkgspec); options.override_links = true;
packie.install_package_file(file_path, &options)?; }
packie.install_package_file(
downloaded
.get(&req.repo_pkg.pkg_manifest.pkg_ident())
.unwrap(),
&options,
)?;
} }
UpgradationOp::Replace(rep) => { UpgradationAction::EnsureInstallation(req) => {
let mut install_flags = InstallFlags::default();
if req.auto_installed {
install_flags.set(InstallFlags::AUTO_INSTALL);
}
packie.ensure_installation(
req.install_pkgspec,
req.pkg_ident,
install_flags,
req.force,
)?;
}
UpgradationAction::Remove(pkg_ident) => {
progress_bar.println(format!( progress_bar.println(format!(
"[{}/{}] {}", "[{}/{}] {}",
progress_bar.position() + 1, count,
nr_ops, nr_actions,
t!( t!("upgrade.removing_hint", pkg = style(&pkg_ident).green(),)
"upgrade.installing_hint",
pkg = style(&rep.new.pkg_manifest.pkg_ident()).green(),
)
)); ));
let mut options = InstallOptions::default(); packie.remove(&pkg_ident.into())?;
options.auto_installed = rep
.original
.install_flags
.contains(InstallFlags::AUTO_INSTALL);
options.install_pkgspec = Some(rep.original.install_pkgspec);
options.is_upgradation_of = Some(rep.original.pkg_manifest.pkg_ident());
packie.install_package_file(file_path, &options)?;
} }
} }
progress_bar.inc(1);
} }
Ok(()) Ok(())
+4
View File
@@ -63,6 +63,10 @@ graph.GraphError.NotFound:
en: "item not found: %{item}" en: "item not found: %{item}"
zh-CN: "找不到项目:%{item}" zh-CN: "找不到项目:%{item}"
ja: "項目が見つかりません:%{item}" ja: "項目が見つかりません:%{item}"
graph.InstallError.Database:
en: "local database error: %{error}"
zh-CN: "本地数据库错误:%{error}"
ja: "ローカルデータベースエラー:%{error}"
BuildPackieError.Lock: BuildPackieError.Lock:
en: "failed to lock packie database: %{error}" en: "failed to lock packie database: %{error}"
zh-CN: "无法锁定 Packie 数据库:%{error}" zh-CN: "无法锁定 Packie 数据库:%{error}"
+40
View File
@@ -67,6 +67,10 @@ upgrade.installing_hint:
en: "Installing \"%{pkg}\"..." en: "Installing \"%{pkg}\"..."
zh-CN: "正在安装 \"%{pkg}\"..." zh-CN: "正在安装 \"%{pkg}\"..."
ja: "「%{pkg}」をインストールしています..." ja: "「%{pkg}」をインストールしています..."
upgrade.removing_hint:
en: "Removing \"%{pkg}\"..."
zh-CN: "正在移除 \"%{pkg}\"..."
ja: "「%{pkg}』 を削除中..."
info.no_package_found: info.no_package_found:
en: "The specified package was not found." en: "The specified package was not found."
zh-CN: "找不到指定的包。" zh-CN: "找不到指定的包。"
@@ -163,6 +167,30 @@ remove.no_packages_to_remove:
en: "No packages specified to remove." en: "No packages specified to remove."
zh-CN: "未指定要移除的包。" zh-CN: "未指定要移除的包。"
ja: "削除するパッケージが指定されていません。" ja: "削除するパッケージが指定されていません。"
autoremove.no_packages_to_remove:
en: "No packages available to auto-remove."
zh-CN: "没有可以自动移除的包。"
ja: "自動削除できるパッケージはありません。"
autoremove.prompt_to_remove:
en: "The following packages are to be removed:"
zh-CN: "将要移除下面的包:"
ja: "以下のパッケージを削除します:"
autoremove.confirm_removal:
en: "Confirm to remove?"
zh-CN: "确认移除?"
ja: "削除を続行しますか?"
autoremove.aborting:
en: "Aborting."
zh-CN: "中止。"
ja: "中止します。"
autoremove.action_hint:
en: "Removing package %{package} ..."
zh-CN: "正在移除包 %{package} ..."
ja: "パッケージ %{package} を削除中 ..."
autoremove.action_failure:
en: "Failed to remove the specified package: %{error}"
zh-CN: "无法移除指定的包:%{error}"
ja: "指定されたパッケージの削除に失敗しました:%{error}"
common.progress_style.speed: common.progress_style.speed:
en: "Speed: " en: "Speed: "
zh-CN: "速度:" zh-CN: "速度:"
@@ -199,6 +227,18 @@ common.download_packages.download_error:
en: "error: failed to download from \"%{url}\": %{error}" en: "error: failed to download from \"%{url}\": %{error}"
zh-CN: "错误:无法下载 \"%{url}\": %{error}" zh-CN: "错误:无法下载 \"%{url}\": %{error}"
ja: "エラー: \"%{url}\" からのダウンロードに失敗しました: %{error}" ja: "エラー: \"%{url}\" からのダウンロードに失敗しました: %{error}"
common.SummaryItem.INSTALL:
en: "Install"
zh-CN: "安装"
ja: "インストール"
common.SummaryItem.REMOVE:
en: "Remove"
zh-CN: "移除"
ja: "削除"
common.SummaryItem.SET_MANUAL_INSTALL:
en: "Set to Manual Install"
zh-CN: "设置为手动安装"
ja: "手動インストールに設定"
clean.warn_repos_dir: clean.warn_repos_dir:
en: "warning: failed to read repository cache directory: %{error}" en: "warning: failed to read repository cache directory: %{error}"
zh-CN: "警告:无法读取软件包仓库缓存目录:%{error}" zh-CN: "警告:无法读取软件包仓库缓存目录:%{error}"
+31
View File
@@ -0,0 +1,31 @@
use rusqlite::params;
#[derive(Debug, Clone)]
pub struct MigrationItem {
pub name: &'static str,
pub sql: &'static str,
}
const INIT_MIGRATION_TABLE: &'static str =
r#"CREATE TABLE IF NOT EXISTS "_migration"("name" TEXT PRIMARY KEY);"#;
pub fn run_migration(db: &rusqlite::Connection, items: &[MigrationItem]) -> rusqlite::Result<()> {
db.execute_batch(INIT_MIGRATION_TABLE)?;
for i in items {
let migrated = db
.query_one(
r#"SELECT * FROM "_migration" WHERE "name" = ?1"#,
params![i.name],
|x| x.get::<_, String>("name"),
)
.is_ok();
if !migrated {
db.execute(i.sql, params![])?;
db.execute(
r#"INSERT INTO "_migration"("name") VALUES(?1)"#,
params![i.name],
)?;
}
}
Ok(())
}
+1
View File
@@ -1,4 +1,5 @@
pub mod checksum; pub mod checksum;
pub mod db;
pub mod fs; pub mod fs;
pub mod io; pub mod io;
pub mod macros; pub mod macros;
+22
View File
@@ -1,3 +1,5 @@
//! Package configuration.
use crate::package::PkgIdent; use crate::package::PkgIdent;
use std::{ use std::{
fmt::Display, fmt::Display,
@@ -5,6 +7,10 @@ use std::{
}; };
impl super::Packie { impl super::Packie {
/// Runs configuration scripts for the provided package.
///
/// If `item` is `Some(_)`, it runs the required configuration script. Otherwise, it runs all configuration
/// scripts in the alphabetic order.
pub fn run_configure( pub fn run_configure(
&self, &self,
pkg: &PkgIdent, pkg: &PkgIdent,
@@ -38,14 +44,28 @@ impl super::Packie {
} }
} }
/// Options of package configuration.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ConfigureOptions { pub struct ConfigureOptions {
/// Action that is passed to the script.
pub action: Action, pub action: Action,
/// Whether we should run the script in interactive mode.
pub interactive: bool, pub interactive: bool,
/// Prefix of the package.
///
/// For most users, you should set this to `None`, since `run_configure()` internally resets this to the
/// correct value.
pub prefix: Option<PathBuf>, pub prefix: Option<PathBuf>,
/// Extra arguments to the configuration script.
///
/// This is usually used to set non-default options in non-interactive mode.
pub extra_args: Vec<String>, pub extra_args: Vec<String>,
} }
/// Action of package configuration.
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum Action { pub enum Action {
Install, Install,
@@ -63,6 +83,7 @@ impl Display for Action {
} }
} }
/// Runs a configuration script, setting the correct environment up.
pub fn run_script( pub fn run_script(
path: impl AsRef<Path>, path: impl AsRef<Path>,
options: &ConfigureOptions, options: &ConfigureOptions,
@@ -85,6 +106,7 @@ pub fn run_script(
} }
} }
/// Error occurred while running a configuration script.
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum ConfigureError { pub enum ConfigureError {
#[error("{0}")] #[error("{0}")]
+267 -117
View File
@@ -1,46 +1,50 @@
//! Calculation of the package relationship graph.
use crate::{ use crate::{
local::Installation, local::InstallFlags,
package::{PkgIdent, PkgSpec}, package::{PkgIdent, PkgSpec},
repo::RepoPackage, repo::RepoPackage,
}; };
use itertools::Itertools;
use rust_i18n::t; use rust_i18n::t;
impl super::Packie { impl super::Packie {
/// Calculates actions required to install provided packages from repositories.
pub fn calculate_installation( pub fn calculate_installation(
&mut self, &mut self,
pkgs: &[PkgSpec], items: &[PkgSpec],
options: &CalculateInstallationOptions, options: &CalculateInstallationOptions,
) -> Result<Vec<InstallationNode>, GraphError> { ) -> Result<Vec<InstallationAction>, GraphError> {
let mut all = Vec::with_capacity(pkgs.len() * 4); let mut all = Vec::with_capacity(items.len() * 4);
for pkg in pkgs { for pkgspec in items {
let mut current = self._calculate_installation(pkg, options)?; let current = self._calculate_installation(pkgspec, options)?;
all.append(&mut current); for i in current {
} match i {
InstallationAction::InstallFromRepo(ir) => {
// Filter out existing `InstallFromRepo` records
let has_install_from_repo = all.iter().any(|x| matches!(x, InstallationAction::InstallFromRepo(y) if y.repo_pkg.repo_pkg_ident() == ir.repo_pkg.repo_pkg_ident()));
if has_install_from_repo {
continue;
}
let manual_install: Vec<(PkgIdent, PkgSpec)> = all // Collect result
.iter() all.push(InstallationAction::InstallFromRepo(ir));
.filter(|x| !x.auto_installed) }
.map(|x| { InstallationAction::EnsureInstallation(ei) => {
( // Filter out existing `EnsureInstallation` records
x.repo_pkg.pkg_manifest.pkg_ident(), for i in &mut all {
x.install_pkgspec.clone(), if let InstallationAction::EnsureInstallation(y) = i
) && y.install_pkgspec == ei.install_pkgspec
}) {
.collect(); y.auto_installed &= ei.auto_installed;
continue;
}
}
let mut all: Vec<_> = all // Collect result
.into_iter() all.push(InstallationAction::EnsureInstallation(ei));
.unique_by(|x| x.repo_pkg.pkg_manifest.pkg_ident()) }
.collect(); }
for pkg in &mut all {
let manual = manual_install
.iter()
.find(|(pkgid, _)| pkgid == &pkg.repo_pkg.pkg_manifest.pkg_ident());
if let Some((_, install_pkgspec)) = manual {
pkg.auto_installed = false;
pkg.install_pkgspec = install_pkgspec.clone();
} }
} }
@@ -51,7 +55,7 @@ impl super::Packie {
&mut self, &mut self,
desired: &PkgSpec, desired: &PkgSpec,
options: &CalculateInstallationOptions, options: &CalculateInstallationOptions,
) -> Result<Vec<InstallationNode>, GraphError> { ) -> Result<Vec<InstallationAction>, GraphError> {
let prior_arch = self.profile.host_arch.clone(); let prior_arch = self.profile.host_arch.clone();
let mut query = self.query_repo(); let mut query = self.query_repo();
@@ -67,32 +71,33 @@ impl super::Packie {
if found.is_empty() { if found.is_empty() {
return Err(GraphError::NotFound(pkgspec.to_string())); return Err(GraphError::NotFound(pkgspec.to_string()));
} }
let prior_pkg = prior_pkg( let prior = prior_pkg(
found.iter().map(|x| x.pkg_manifest.pkg_ident()), found.iter().map(|x| x.pkg_manifest.pkg_ident()),
&prior_arch, &prior_arch,
); );
let prior_pkg = found let prior = found
.iter() .iter()
.enumerate() .enumerate()
.find(|(_, p)| p.pkg_manifest.pkg_ident() == prior_pkg) .find(|(_, p)| p.pkg_manifest.pkg_ident() == prior)
.unwrap() .unwrap()
.0; .0;
let repo_pkg = found.remove(prior_pkg); let repo_pkg = found.remove(prior);
let already_installed = !self let local_matches = self.search_local_package(&pkgspec).unwrap_or_default();
.search_installation(&pkgspec) if !local_matches.is_empty() && !(pkgspec == *desired && options.no_existence_check) {
.unwrap_or_default() let prior = prior_pkg(
.is_empty(); local_matches.iter().map(|x| x.pkg_ident.clone()),
if already_installed && !(&pkgspec == desired && options.no_existence_check) { &prior_arch,
);
depgraph.push(InstallationAction::EnsureInstallation(EnsureInstallation {
auto_installed: pkgspec != *desired,
install_pkgspec: pkgspec,
pkg_ident: prior,
force: false,
}));
continue; continue;
} }
depgraph.push(InstallationNode {
repo_pkg: repo_pkg.clone(),
auto_installed: &pkgspec != desired,
install_pkgspec: pkgspec,
});
for dep in &repo_pkg.pkg_manifest.dependencies { for dep in &repo_pkg.pkg_manifest.dependencies {
stack.push(dep.clone()); stack.push(dep.clone());
} }
@@ -102,94 +107,209 @@ impl super::Packie {
stack.push(recommended.clone()); stack.push(recommended.clone());
} }
} }
// The final result it reversed, so we push in a reversed order.
depgraph.push(InstallationAction::EnsureInstallation(EnsureInstallation {
auto_installed: pkgspec != *desired,
install_pkgspec: pkgspec.clone(),
pkg_ident: repo_pkg.pkg_manifest.pkg_ident(),
force: false,
}));
depgraph.push(InstallationAction::InstallFromRepo(InstallFromRepo {
repo_pkg,
override_links: false,
}));
} }
depgraph.reverse(); depgraph.reverse();
Ok(depgraph) Ok(depgraph)
} }
/// Calculates actions required to upgrade provided packages from repositories. If no package specs are
/// provided, it scans all installed packages.
pub fn calculate_upgradation( pub fn calculate_upgradation(
&mut self, &mut self,
pkgspecs: Vec<PkgSpec>, pkgspecs: Vec<PkgSpec>,
) -> Result<Vec<UpgradationOp>, GraphError> { ) -> Result<Vec<UpgradationAction>, GraphError> {
// Collect all package idents required to upgrade // Collect all install package specs required to upgrade
let mut installations = Vec::with_capacity(pkgspecs.len()); let mut installations = Vec::with_capacity(pkgspecs.len());
if pkgspecs.is_empty() { if pkgspecs.is_empty() {
self.for_each_installation(|x| Ok::<_, rusqlite::Error>(installations.push(x))) self.for_each_installation(|x| {
.unwrap(); Ok::<_, rusqlite::Error>(installations.push(x.install_pkgspec))
})
.unwrap();
} else { } else {
for pkgspec in pkgspecs { for i in pkgspecs {
let mut searched = self.search_installation(&pkgspec).unwrap_or_default(); if let Ok(exact) = self.select_installation(&i) {
installations.append(&mut searched); installations.push(exact.install_pkgspec);
continue;
};
let non_exact = self.search_local_package(&i).unwrap_or_default();
for j in non_exact {
let this_installations = self
.local_db
.select_installation_by_pkgident(&j.pkg_ident)
.unwrap_or_default();
for k in this_installations {
installations.push(k.install_pkgspec);
}
}
} }
} }
// Calculate upgradation nodes for each package ident required to upgrade let mut all = Vec::with_capacity(installations.len() * 8);
let mut nodes = Vec::with_capacity(installations.len() / 3); for install_pkgspec in installations {
for i in installations { let current = self._calculate_upgradation(&install_pkgspec)?;
let Some(node) = self._calculate_upgradation(&i.pkg_manifest.pkg_ident())? else { for i in current {
continue; match &i {
}; UpgradationAction::InstallFromRepo(req) => {
nodes.push(node); let has_this = all.iter().any(|x| matches!(x, UpgradationAction::InstallFromRepo(x) if x.repo_pkg.repo_pkg_ident() == req.repo_pkg.repo_pkg_ident()));
} if !has_this {
all.push(i);
// Collect upgradation summary }
let mut ops = Vec::with_capacity(nodes.len()); }
for node in &nodes { UpgradationAction::Remove(req) => {
let mut ti = self.calculate_installation( let has_this = all
&[node.new.pkg_manifest.pkg_ident().into()], .iter()
&CalculateInstallationOptions { .any(|x| matches!(x, UpgradationAction::Remove(x) if x == req));
skip_recommendations: false, if !has_this {
no_existence_check: false, all.push(i);
}, }
)?; }
ti.pop(); UpgradationAction::EnsureInstallation(_) => {
ti.retain(|x| { all.push(i);
!nodes }
.iter() }
.any(|y| y.new.pkg_manifest.pkg_ident() == x.repo_pkg.pkg_manifest.pkg_ident())
});
for i in ti {
ops.push(UpgradationOp::Install(i));
} }
ops.push(UpgradationOp::Replace(node.clone()));
} }
Ok(ops) Ok(all)
} }
fn _calculate_upgradation( fn _calculate_upgradation(
&mut self, &mut self,
pkg: &PkgIdent, install_pkgspec: &PkgSpec,
) -> Result<Option<UpgradationNode>, GraphError> { ) -> Result<Vec<UpgradationAction>, GraphError> {
let original = self // Collect the existing installation (matching the install package spec)
let orig = self
.local_db .local_db
.select_installation_by_ident(pkg) .select_installation(install_pkgspec)
.map_err(|_| GraphError::NotFound(pkg.to_string()))?; .map_err(|_| GraphError::NotFound(install_pkgspec.to_string()))?;
let depgraph = self._calculate_installation(
&original.install_pkgspec,
&CalculateInstallationOptions {
skip_recommendations: false,
no_existence_check: true,
},
);
let Ok(mut depgraph) = depgraph else {
return Ok(None);
};
if depgraph.last().map(|x| x.repo_pkg.pkg_manifest.pkg_ident()) == Some(pkg.clone()) {
return Ok(None);
}
Ok(Some(UpgradationNode {
original,
new: depgraph.pop().unwrap().repo_pkg,
}))
}
}
#[derive(Debug, thiserror::Error)] // Search the repository for "latest" matching package
pub enum GraphError { let mut depgraph = self
#[error("{}", t!("graph.GraphError.NotFound", item = .0))] ._calculate_installation(
NotFound(String), install_pkgspec,
&CalculateInstallationOptions {
skip_recommendations: false,
no_existence_check: true,
},
)
.unwrap_or_default();
// The returned dependency graph looks like:
//
// --------------------
// | dependency a
// | dependency b
// | ...
// | our package: install from repo
// | our package: ensure installation
// --------------------
//
// The last "InstallFromRepo" action is what we need to check.
let install_new = depgraph
.iter()
.enumerate()
.rev()
.find_map(|(c, i)| match i {
InstallationAction::InstallFromRepo(req) => Some((c, req.clone())),
_ => None,
});
let Some((install_new_idx, install_new)) = install_new else {
// The package does not exist in any repository
return Ok(vec![]);
};
depgraph.truncate(install_new_idx);
// We don't need to upgrade it if the original is same as the new
if install_new.repo_pkg.pkg_manifest.pkg_ident() == orig.pkg_ident {
return Ok(vec![]);
}
// Build new actions, forced and inheriting the original flags, and overriding links.
let ensure_installation = EnsureInstallation {
install_pkgspec: install_pkgspec.clone(),
pkg_ident: install_new.repo_pkg.pkg_manifest.pkg_ident(),
auto_installed: orig.install_flags.contains(InstallFlags::AUTO_INSTALL),
force: true,
};
let has_new_installed = self
.local_db
.select_package(&install_new.repo_pkg.pkg_manifest.pkg_ident())
.is_ok();
let install_new = if has_new_installed {
None
} else {
Some(InstallFromRepo {
repo_pkg: install_new.repo_pkg,
override_links: true,
})
};
let mut all = Vec::with_capacity(depgraph.len());
let do_upgrade = [
install_new.map(UpgradationAction::InstallFromRepo),
Some(UpgradationAction::EnsureInstallation(ensure_installation)),
Some(UpgradationAction::Remove(orig.pkg_ident)),
];
for i in depgraph {
all.push(i.into());
}
for i in do_upgrade {
if let Some(i) = i {
all.push(i);
}
}
Ok(all)
}
/// Calculate packages that is no longer needed, which includes package that:
///
/// - is no longer bound to an installation
/// - is auto-installed, but no longer referenced as a dependency
pub fn calculate_autoremove(&mut self) -> Result<Vec<PkgIdent>, GraphError> {
let mut all = Vec::new();
self.local_db.for_each_package::<GraphError>(|i| {
let orphan = self
.local_db
.select_installation_by_pkgident(&i.pkg_ident)
.unwrap_or_default()
.is_empty();
if orphan {
all.push(i.pkg_ident);
}
Ok(())
})?;
self.local_db.for_each_installation::<GraphError>(|i| {
if !i.install_flags.contains(InstallFlags::AUTO_INSTALL) {
return Ok(());
}
let orphan = self
.local_db
.select_dependents(&i.install_pkgspec)
.unwrap_or_default()
.is_empty();
if orphan {
all.push(i.pkg_ident);
}
Ok(())
})?;
Ok(all)
}
} }
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
@@ -207,22 +327,38 @@ impl CalculateInstallationOptions {
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct InstallationNode { pub struct InstallFromRepo {
pub repo_pkg: RepoPackage, pub repo_pkg: RepoPackage,
pub override_links: bool,
}
#[derive(Debug, Clone)]
pub struct EnsureInstallation {
pub install_pkgspec: PkgSpec, pub install_pkgspec: PkgSpec,
pub pkg_ident: PkgIdent,
pub auto_installed: bool, pub auto_installed: bool,
pub force: bool,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct UpgradationNode { pub enum InstallationAction {
pub original: Installation, InstallFromRepo(InstallFromRepo),
pub new: RepoPackage, EnsureInstallation(EnsureInstallation),
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum UpgradationOp { pub enum UpgradationAction {
Install(InstallationNode), InstallFromRepo(InstallFromRepo),
Replace(UpgradationNode), EnsureInstallation(EnsureInstallation),
Remove(PkgIdent),
}
impl From<InstallationAction> for UpgradationAction {
fn from(value: InstallationAction) -> Self {
match value {
InstallationAction::InstallFromRepo(x) => Self::InstallFromRepo(x),
InstallationAction::EnsureInstallation(x) => Self::EnsureInstallation(x),
}
}
} }
/// Gets prior package that is installed by default in package candidates. /// Gets prior package that is installed by default in package candidates.
@@ -237,3 +373,17 @@ pub(crate) fn prior_pkg(all: impl Iterator<Item = PkgIdent>, prior_arch: &str) -
} }
all.remove(0) all.remove(0)
} }
#[derive(Debug, thiserror::Error)]
pub enum GraphError {
#[error("{}", t!("graph.GraphError.NotFound", item = .0))]
NotFound(String),
#[error("{}", t!("graph.GraphError.Database", error = .0))]
Database(rusqlite::Error),
}
impl From<rusqlite::Error> for GraphError {
fn from(value: rusqlite::Error) -> Self {
Self::Database(value)
}
}
+29 -63
View File
@@ -1,33 +1,29 @@
//! Package installation.
use crate::{ use crate::{
configure::ConfigureOptions, configure::ConfigureOptions,
local::{DependencyRecord, InstallFlags, Installation}, local::{DependencyRecord, InstallFlags, LocalPackage},
package::{Package, PackageError, PkgIdent, PkgSpec}, package::{Package, PackageError, PkgSpec},
repo::RepoError, repo::RepoError,
}; };
use rust_i18n::t; use rust_i18n::t;
use std::path::Path; use std::path::Path;
/// Options of installing a package.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct InstallOptions { pub struct InstallOptions {
/// Package spec to record for this installation.
pub install_pkgspec: Option<PkgSpec>,
/// Whether we should run configure scripts in interactive mode. /// Whether we should run configure scripts in interactive mode.
pub interactive_configure: bool, pub interactive_configure: bool,
/// Whether this package is auto-installed. /// Whether we should override existing links to what is required by this package.
pub auto_installed: bool, pub override_links: bool,
/// Mark this installation as an upgradation of an installed package.
pub is_upgradation_of: Option<PkgIdent>,
} }
impl InstallOptions { impl InstallOptions {
/// Returns an [`InstallOptions`] instance using the defaults.
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
install_pkgspec: None,
interactive_configure: true, interactive_configure: true,
auto_installed: false, override_links: false,
is_upgradation_of: None,
} }
} }
} }
@@ -58,33 +54,18 @@ impl super::Packie {
let pkg_manifest = package.manifest()?; let pkg_manifest = package.manifest()?;
let pkg_ident = pkg_manifest.pkg_ident(); let pkg_ident = pkg_manifest.pkg_ident();
let installed_size = package.installed_size()?; let installed_size = package.installed_size()?;
let install_pkgspec = options
.install_pkgspec
.clone()
.unwrap_or_else(|| default_install_pkgspec(pkg_ident.clone()));
// Check if the package is previously installed // Check if the package is previously installed
if !self if !self
.search_installation(&pkg_ident.clone().into())? .search_local_package(&pkg_ident.clone().into())?
.is_empty() .is_empty()
{ {
return Err(InstallError::AlreadyInstalled); return Err(InstallError::AlreadyInstalled);
} }
// Check if the package spec is valid // Check dependencies
let real_matches = install_pkgspec.matches(&pkg_ident);
let concept_matches = pkg_manifest
.provides
.iter()
.any(|x| install_pkgspec.concept_matches(x));
if !(real_matches || concept_matches) {
return Err(InstallError::PkgSpec);
}
// Check & Collect "real" dependencies
let mut real_dependencies = Vec::with_capacity(pkg_manifest.dependencies.len());
for pkg_spec_b in pkg_manifest.dependencies.iter() { for pkg_spec_b in pkg_manifest.dependencies.iter() {
let candidates = self.search_installation(pkg_spec_b)?; let candidates = self.search_local_package(pkg_spec_b)?;
if candidates.is_empty() { if candidates.is_empty() {
return Err(InstallError::DependencyNotSatisfied(pkg_spec_b.clone())); return Err(InstallError::DependencyNotSatisfied(pkg_spec_b.clone()));
} }
@@ -92,45 +73,43 @@ impl super::Packie {
candidates.iter().map(|x| x.pkg_manifest.pkg_ident()), candidates.iter().map(|x| x.pkg_manifest.pkg_ident()),
&self.profile().host_arch, &self.profile().host_arch,
); );
real_dependencies.push((pkg_spec_b.clone(), prior)); self.ensure_installation(
pkg_spec_b.clone(),
prior,
InstallFlags::new(&[InstallFlags::AUTO_INSTALL]),
false,
)?;
} }
// Copy package files // Copy package files
let dest_dir = self.profile.pkg_dir.join(pkg_ident.prefix_name()); let dest_dir = self.profile.pkg_dir.join(pkg_ident.prefix_name());
crate::common::copy_dir(package.bundle_dir(), dest_dir).map_err(InstallError::Copy)?; crate::common::copy_dir(package.bundle_dir(), dest_dir).map_err(InstallError::Copy)?;
// Record installation in the database // Record package in the database
let mut install_flags = InstallFlags::default(); let local_package = LocalPackage {
if options.auto_installed { pkg_ident: pkg_ident.clone(),
install_flags.set(InstallFlags::AUTO_INSTALL);
}
let installation = Installation {
pkg_manifest: pkg_manifest.clone(), pkg_manifest: pkg_manifest.clone(),
install_pkgspec,
install_date: crate::common::timestamp_secs(), install_date: crate::common::timestamp_secs(),
update_date: crate::common::timestamp_secs(),
installed_size, installed_size,
install_flags,
}; };
self.local_db.insert_installation(&installation)?; self.local_db.insert_package(&local_package)?;
// Record "real" dependencies in the database // Record "real" dependencies in the database
for (pkg_spec_b, pkg_ident_b) in real_dependencies { for pkg_spec_b in &pkg_manifest.dependencies {
self.local_db.insert_dependency(&DependencyRecord { self.local_db.insert_dependency(&DependencyRecord {
pkg_ident_a: pkg_ident.clone(), pkg_ident_a: pkg_ident.clone(),
pkg_spec_b, pkg_spec_b: pkg_spec_b.clone(),
pkg_ident_b,
})?; })?;
} }
// Record concept provision in the database // Record concept provision in the database
for i in installation.pkg_manifest.provides.iter() { for i in pkg_manifest.provides.iter() {
self.local_db.insert_concept(&i, &pkg_ident)?; self.local_db.insert_concept(&i, &pkg_ident)?;
} }
// Copy links file // Copy links file
if let Some(links) = package.links() { if let Some(links) = package.links() {
std::fs::copy(&links.0, self.local_data.links_file(&pkg_ident)) std::fs::copy(links.path(), self.local_data.links_file(&pkg_ident))
.map_err(|err| InstallError::Database(Box::new(err)))?; .map_err(|err| InstallError::Database(Box::new(err)))?;
} }
@@ -146,14 +125,6 @@ impl super::Packie {
std::fs::copy(i.path(), dst).map_err(|err| InstallError::Database(Box::new(err)))?; std::fs::copy(i.path(), dst).map_err(|err| InstallError::Database(Box::new(err)))?;
} }
// Process upgradation
if let Some(original) = &options.is_upgradation_of {
self.local_db
.update_dependency(None, original, &pkg_ident)?;
self.remove(&PkgSpec::from(original.clone()))
.map_err(InstallError::Remove)?;
}
// Enable default links // Enable default links
if let Some(links) = package.links() { if let Some(links) = package.links() {
for linkdes in links.iter().ok().into_iter().flatten() { for linkdes in links.iter().ok().into_iter().flatten() {
@@ -163,6 +134,9 @@ impl super::Packie {
if !linkdes.default { if !linkdes.default {
continue; continue;
} }
if options.override_links {
_ = crate::link::remove(&linkdes.to);
}
_ = crate::link::activate_by_description(self, &pkg_ident, &linkdes); _ = crate::link::activate_by_description(self, &pkg_ident, &linkdes);
} }
} }
@@ -222,11 +196,3 @@ impl From<rusqlite::Error> for InstallError {
Self::Database(Box::new(value)) Self::Database(Box::new(value))
} }
} }
fn default_install_pkgspec(pkg_ident: PkgIdent) -> PkgSpec {
PkgSpec {
name: pkg_ident.name,
version: crate::version::VersionFilter::Any,
arch: None,
}
}
+4
View File
@@ -1,3 +1,7 @@
//! # The Packie Package Manager
//!
//! This is the core algorithm library for the Packie package manager.
mod common; mod common;
pub mod config; pub mod config;
pub mod configure; pub mod configure;
+38 -4
View File
@@ -1,3 +1,5 @@
//! Tools for managing package manager links.
use crate::{Packie, package::PkgIdent}; use crate::{Packie, package::PkgIdent};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{ use std::{
@@ -7,17 +9,34 @@ use std::{
}; };
impl super::Packie { impl super::Packie {
pub fn links_of_pkg(&self, pkgident: &PkgIdent) -> LinksFile { /// Returns the installed [`LinksFile`] instance of required package.
LinksFile(self.local_data.links_file(pkgident)) ///
/// Note that this does not check if any links file has been installed for the required package.
pub fn links_of_pkg(&self, pkg_ident: &PkgIdent) -> LinksFile {
LinksFile(self.local_data.links_file(pkg_ident))
} }
} }
/// Iterator over link descriptions in a links file. /// A links file.
///
/// Instances of this type may not map to an existing links file.
#[derive(Debug)] #[derive(Debug)]
pub struct LinksFile(pub PathBuf); pub struct LinksFile(PathBuf);
impl LinksFile { impl LinksFile {
/// File name of a links file in an extracted package tree.
pub const FILENAME: &str = "_links"; pub const FILENAME: &str = "_links";
/// Creates a [`LinksFile`] instance, internally wrapping the path provided.
pub fn new(path: impl Into<PathBuf>) -> Self {
Self(path.into())
}
/// Returns path of the links file.
pub fn path(&self) -> &Path {
&self.0
}
/// Returns an iterator over the links file, if it exists.
pub fn iter(&self) -> std::io::Result<impl Iterator<Item = std::io::Result<LinkDescription>>> { pub fn iter(&self) -> std::io::Result<impl Iterator<Item = std::io::Result<LinkDescription>>> {
Ok(BufReader::new(File::open(&self.0)?) Ok(BufReader::new(File::open(&self.0)?)
.lines() .lines()
@@ -45,6 +64,7 @@ pub struct LinkDescription {
pub default: bool, pub default: bool,
} }
/// Activates a link by provided link description in the provided package ident.
pub fn activate_by_description( pub fn activate_by_description(
packie: &mut Packie, packie: &mut Packie,
pkg_ident: &PkgIdent, pkg_ident: &PkgIdent,
@@ -55,6 +75,7 @@ pub fn activate_by_description(
create(from, &description.to) create(from, &description.to)
} }
/// Deactivates a link by provided link description in the provided package ident.
pub fn deactivate_by_description( pub fn deactivate_by_description(
packie: &mut Packie, packie: &mut Packie,
pkg_ident: &PkgIdent, pkg_ident: &PkgIdent,
@@ -69,6 +90,17 @@ pub fn deactivate_by_description(
remove(&description.to) remove(&description.to)
} }
/// Helper function to create a link from a path to another path. Recursively creates parent directories of the
/// destination path.
///
/// Note that this is not an atomic oepration. Take care of TOCTOU and race condition.
///
/// # Errors
/// It would return an standard library IO error in given error kind:
///
/// - `InvalidInput`: The destination path is relative and has no parents.
///
/// Or any error that underlying syscalls may return.
pub fn create(from: impl AsRef<Path>, to: impl AsRef<Path>) -> std::io::Result<()> { pub fn create(from: impl AsRef<Path>, to: impl AsRef<Path>) -> std::io::Result<()> {
std::fs::create_dir_all( std::fs::create_dir_all(
to.as_ref() to.as_ref()
@@ -89,6 +121,8 @@ pub fn create(from: impl AsRef<Path>, to: impl AsRef<Path>) -> std::io::Result<(
/// ///
/// - `NotFound`: The file could not be located. /// - `NotFound`: The file could not be located.
/// - `InvalidData`: The file is not a link. /// - `InvalidData`: The file is not a link.
///
/// Or any error that [`std::fs::remove_file`] may return.
pub fn remove(path: impl Into<PathBuf>) -> std::io::Result<()> { pub fn remove(path: impl Into<PathBuf>) -> std::io::Result<()> {
let mut path = path.into(); let mut path = path.into();
if !path.exists() { if !path.exists() {
+276 -132
View File
@@ -1,4 +1,7 @@
//! Types and functions for reading from and writing to the local data storage.
use crate::{ use crate::{
common::db::MigrationItem,
package::{ConceptIdent, PkgIdent, PkgManifest, PkgSpec}, package::{ConceptIdent, PkgIdent, PkgManifest, PkgSpec},
version::VersionFilter, version::VersionFilter,
}; };
@@ -12,39 +15,95 @@ use std::{
}; };
impl super::Packie { impl super::Packie {
pub fn search_installation( /// Search for local packages *matching* the provided package spec.
&mut self, ///
pkgspec: &PkgSpec, /// The provided package spec don't need to be exactly equal to an existing install package spec.
) -> rusqlite::Result<Vec<Installation>> { pub fn search_local_package(&self, pkgspec: &PkgSpec) -> rusqlite::Result<Vec<LocalPackage>> {
// 1. Collect "real" matches (by package name, not concept)
let mut real = self let mut real = self
.local_db .local_db
.select_installation_by_name(&pkgspec.name)? .select_package_by_name(&pkgspec.name)?
.into_iter() .into_iter()
.filter(|x| pkgspec.matches(&x.pkg_manifest.pkg_ident())) .filter(|x| pkgspec.matches(&x.pkg_manifest.pkg_ident()))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
// With an restrictive version filter we cannot match concepts
if !matches!(pkgspec.version, VersionFilter::Any) { if !matches!(pkgspec.version, VersionFilter::Any) {
return Ok(real); return Ok(real);
} }
// 2. Collect concept matches
let concept = ConceptIdent { let concept = ConceptIdent {
name: pkgspec.name.clone(), name: pkgspec.name.clone(),
arch: pkgspec.arch.clone(), arch: pkgspec.arch.clone(),
}; };
let abs = self.local_db.select_concept_by_ident(&concept)?; let abs = self.local_db.select_concept_by_ident(&concept)?;
for (_, provider) in abs { for (_, provider) in abs {
real.push(self.local_db.select_installation_by_ident(&provider)?); real.push(self.local_db.select_package(&provider)?);
} }
// 3. Collect final result (deduplicated)
Ok(real Ok(real
.into_iter() .into_iter()
.unique_by(|x| x.pkg_manifest.pkg_ident()) .unique_by(|x| x.pkg_manifest.pkg_ident())
.collect()) .collect())
} }
pub fn select_installation(&self, install_pkgspec: &PkgSpec) -> rusqlite::Result<Installation> {
self.local_db.select_installation(install_pkgspec)
}
pub fn select_local_package(&self, pkg_ident: &PkgIdent) -> rusqlite::Result<LocalPackage> {
self.local_db.select_package(pkg_ident)
}
/// Executes the provided function on each installation record.
pub fn for_each_installation<E: From<rusqlite::Error>>( pub fn for_each_installation<E: From<rusqlite::Error>>(
&mut self, &self,
f: impl FnMut(Installation) -> Result<(), E>, f: impl FnMut(Installation) -> Result<(), E>,
) -> Result<(), E> { ) -> Result<(), E> {
self.local_db.for_each_installation(f) self.local_db.for_each_installation(f)
} }
/// Executes the provided function on each local package record.
pub fn for_each_local_package<E: From<rusqlite::Error>>(
&self,
f: impl FnMut(LocalPackage) -> Result<(), E>,
) -> Result<(), E> {
self.local_db.for_each_package(f)
}
/// Ensures the provided installation exists. If it didn't exist, create it using the provided arguments.
pub fn ensure_installation(
&self,
install_pkgspec: PkgSpec,
pkg_ident: PkgIdent,
install_flags: InstallFlags,
force: bool,
) -> rusqlite::Result<()> {
match self.local_db.select_installation(&install_pkgspec) {
Ok(inst) => {
let manual_install = !install_flags.contains(InstallFlags::AUTO_INSTALL);
let has_auto_install = inst.install_flags.contains(InstallFlags::AUTO_INSTALL);
if (manual_install && has_auto_install) || force {
self.local_db.update_installation(
&install_pkgspec,
&pkg_ident,
&install_flags,
)?;
}
}
Err(_) => {
self.local_db.insert_installation(&Installation {
install_pkgspec,
pkg_ident,
install_date: crate::common::timestamp_secs(),
update_date: crate::common::timestamp_secs(),
install_flags,
})?;
}
}
Ok(())
}
} }
#[derive(Debug)] #[derive(Debug)]
@@ -111,31 +170,52 @@ pub struct LocalDb(rusqlite::Connection);
impl LocalDb { impl LocalDb {
pub const FILENAME: &str = "local.db"; pub const FILENAME: &str = "local.db";
pub const SCHEMA: &str = r#" pub const MIGRATIONS: &[MigrationItem] = &[
CREATE TABLE IF NOT EXISTS "installation"( MigrationItem {
"id" INTEGER PRIMARY KEY AUTOINCREMENT, name: "20261122-create-table-package",
"pkg_name" TEXT NOT NULL, sql: r#"
"pkg_version" TEXT NOT NULL, CREATE TABLE "package"(
"pkg_arch" TEXT NOT NULL, "pkg_ident" TEXT PRIMARY KEY,
"pkg_manifest" TEXT NOT NULL, "pkg_manifest" TEXT NOT NULL,
"install_pkgspec" TEXT NOT NULL, "installed_size" INTEGER NOT NULL,
"install_date" INTEGER NOT NULL, "install_date" INTEGER NOT NULL
"update_date" INTEGER NOT NULL, )
"installed_size" INTEGER NOT NULL, "#,
"install_flags" TEXT NOT NULL },
); MigrationItem {
CREATE TABLE IF NOT EXISTS "dependency"( name: "20261122-create-table-installation",
"id" INTEGER PRIMARY KEY AUTOINCREMENT, sql: r#"
"pkg_ident_a" TEXT NOT NULL, CREATE TABLE "installation"(
"pkg_spec_b" TEXT NOT NULL, "id" INTEGER PRIMARY KEY AUTOINCREMENT,
"pkg_ident_b" TEXT NOT NULL "install_pkgspec" TEXT NOT NULL,
); "pkg_ident" TEXT NOT NULL,
CREATE TABLE IF NOT EXISTS "concept"( "install_date" INTEGER NOT NULL,
"id" INTEGER PRIMARY KEY AUTOINCREMENT, "update_date" INTEGER NOT NULL,
"concept_ident" TEXT NOT NULL, "install_flags" TEXT NOT NULL
"provider" TEXT NOT NULL )
); "#,
"#; },
MigrationItem {
name: "20261122-create-table-dependency",
sql: r#"
CREATE TABLE "dependency"(
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"pkg_ident_a" TEXT NOT NULL,
"pkg_spec_b" TEXT NOT NULL
)
"#,
},
MigrationItem {
name: "20261122-create-table-concept",
sql: r#"
CREATE TABLE "concept"(
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"concept_ident" TEXT NOT NULL,
"provider" TEXT NOT NULL
)
"#,
},
];
// ==- Opening the database -== // ==- Opening the database -==
@@ -145,48 +225,44 @@ CREATE TABLE IF NOT EXISTS "concept"(
pub fn open_rw<P: AsRef<Path>>(path: P) -> rusqlite::Result<Self> { pub fn open_rw<P: AsRef<Path>>(path: P) -> rusqlite::Result<Self> {
let conn = rusqlite::Connection::open(path)?; let conn = rusqlite::Connection::open(path)?;
conn.execute_batch(Self::SCHEMA)?; crate::common::db::run_migration(&conn, Self::MIGRATIONS)?;
Ok(Self(conn)) Ok(Self(conn))
} }
// ==- Installation management -== // ==- Local package record management -==
pub fn insert_installation(&mut self, installation: &Installation) -> rusqlite::Result<()> { pub fn insert_package(&self, package: &LocalPackage) -> rusqlite::Result<()> {
let pkg_manifest = serde_json::to_string(&installation.pkg_manifest) let pkg_manifest = serde_json::to_string(&package.pkg_manifest)
.map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?; .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
self.0 self.0
.prepare_cached( .prepare_cached(
r#" r#"
INSERT INTO "installation"( INSERT INTO "package"("pkg_ident", "pkg_manifest", "install_date", "installed_size")
"pkg_name", "pkg_version", "pkg_arch", "pkg_manifest", VALUES(?1, ?2, ?3, ?4)
"install_pkgspec", "install_date", "update_date", "installed_size",
"install_flags"
)
VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
"#, "#,
)? )?
.execute(params![ .execute(params![
installation.pkg_manifest.name, package.pkg_ident.to_string(),
installation.pkg_manifest.version.to_string(),
installation.pkg_manifest.arch,
pkg_manifest, pkg_manifest,
installation.install_pkgspec.to_string(), package.install_date,
installation.install_date, package.installed_size as i64,
installation.update_date,
installation.installed_size as i64,
installation.install_flags.to_string(),
])?; ])?;
Ok(()) Ok(())
} }
pub fn select_installation_by_name( /// Selects a package, unique by package identifier.
&mut self, pub fn select_package(&self, pkg_ident: &PkgIdent) -> rusqlite::Result<LocalPackage> {
pkg_name: &str, self.0
) -> rusqlite::Result<Vec<Installation>> { .prepare_cached(r#"SELECT * FROM "package" WHERE "pkg_ident" = ?1"#)?
.query_one(params![pkg_ident.to_string()], map_package)
}
/// Selects all local package records with the provided package name.
pub fn select_package_by_name(&self, name: &str) -> rusqlite::Result<Vec<LocalPackage>> {
let mut stmt = self let mut stmt = self
.0 .0
.prepare_cached(r#"SELECT * FROM "installation" WHERE "pkg_name" = ?1"#)?; .prepare_cached(r#"SELECT * FROM "package" WHERE "pkg_ident" LIKE ?1 || '=%'"#)?;
let mapped_rows = stmt.query_map(params![pkg_name], map_installation)?; let mapped_rows = stmt.query_map(params![name], map_package)?;
let mut ret = Vec::with_capacity(16); let mut ret = Vec::with_capacity(16);
for mr in mapped_rows { for mr in mapped_rows {
ret.push(mr?); ret.push(mr?);
@@ -194,17 +270,92 @@ CREATE TABLE IF NOT EXISTS "concept"(
Ok(ret) Ok(ret)
} }
pub fn select_installation_by_ident( /// Iterates over all local package records in the database.
&mut self, pub fn for_each_package<E: From<rusqlite::Error>>(
pkg_ident: &PkgIdent, &self,
) -> rusqlite::Result<Installation> { mut f: impl FnMut(LocalPackage) -> Result<(), E>,
self.0.prepare_cached(r#" ) -> Result<(), E> {
SELECT * FROM "installation" WHERE "pkg_name" = ?1 AND "pkg_version" = ?2 AND "pkg_arch" = ?3 let mut stmt = self.0.prepare_cached("SELECT * FROM \"package\"")?;
"#)?.query_one(params![pkg_ident.name, pkg_ident.version.to_string(), pkg_ident.arch], map_installation) for i in stmt.query_map(params![], map_package)? {
f(i?)?;
}
Ok(())
} }
/// Removes an unique package record with provided package identifier.
///
/// # Return Value
///
/// Returns `Ok(true)` if the package exists and is now removed. Returns `Ok(false)` if the package does not
/// exist. Returns `Err(_)` if an error occurred while accessing to the database and the state is unknown.
pub fn remove_package(&self, pkg_ident: &PkgIdent) -> rusqlite::Result<bool> {
self.0
.prepare_cached(r#"DELETE FROM "package" WHERE "pkg_ident" = ?1"#)?
.execute(params![pkg_ident.to_string()])
.map(|x| x > 0)
}
// ==- Installation management -==
pub fn insert_installation(&self, installation: &Installation) -> rusqlite::Result<()> {
self.0
.prepare_cached(
r#"
INSERT INTO
"installation"("install_pkgspec", "pkg_ident", "install_date", "update_date", "install_flags")
VALUES(?1, ?2, ?3, ?4, ?5)
"#,
)?
.execute(params![
installation.install_pkgspec.to_string(),
installation.pkg_ident.to_string(),
installation.install_date,
installation.update_date,
installation.install_flags.to_string(),
])?;
Ok(())
}
/// Selects an installation, unique by install package spec.
pub fn select_installation(&self, install_pkgspec: &PkgSpec) -> rusqlite::Result<Installation> {
self.0
.prepare_cached(r#"SELECT * FROM "installation" WHERE "install_pkgspec" = ?1"#)?
.query_one(params![install_pkgspec.to_string()], map_installation)
}
/// Selects all local installation records bound to the provided package ident.
pub fn select_installation_by_pkgident(
&self,
pkg_ident: &PkgIdent,
) -> rusqlite::Result<Vec<Installation>> {
let mut stmt = self
.0
.prepare_cached(r#"SELECT * FROM "installation" WHERE "pkg_ident" = ?1"#)?;
let mapped_rows = stmt.query_map(params![pkg_ident.to_string()], map_installation)?;
let mut ret = Vec::with_capacity(16);
for mr in mapped_rows {
ret.push(mr?);
}
Ok(ret)
}
pub fn update_installation(
&self,
install_pkgspec: &PkgSpec,
pkg_ident: &PkgIdent,
install_flags: &InstallFlags,
) -> rusqlite::Result<bool> {
self.0
.prepare_cached(
r#"UPDATE "installation" SET "pkg_ident" = ?1, "install_flags" = ?2, "update_date" = ?3 WHERE "install_pkgspec" = ?4"#,
)?
.execute(params![pkg_ident.to_string(), install_flags.to_string(), crate::common::timestamp_secs(), install_pkgspec.to_string()])
.map(|x| x > 0)
}
/// Iterates over all local installation records in the database.
pub fn for_each_installation<E: From<rusqlite::Error>>( pub fn for_each_installation<E: From<rusqlite::Error>>(
&mut self, &self,
mut f: impl FnMut(Installation) -> Result<(), E>, mut f: impl FnMut(Installation) -> Result<(), E>,
) -> Result<(), E> { ) -> Result<(), E> {
let mut stmt = self.0.prepare_cached("SELECT * FROM \"installation\"")?; let mut stmt = self.0.prepare_cached("SELECT * FROM \"installation\"")?;
@@ -214,95 +365,77 @@ CREATE TABLE IF NOT EXISTS "concept"(
Ok(()) Ok(())
} }
pub fn remove_installation(&mut self, pkg_ident: &PkgIdent) -> rusqlite::Result<bool> { /// Removes an unique installation record with provided install package spec.
self ///
.0 /// # Return Value
.prepare_cached(r#"DELETE FROM "installation" WHERE "pkg_name" = ?1 AND "pkg_version" = ?2 AND "pkg_arch" = ?3"#)? ///
.execute(params![pkg_ident.name, pkg_ident.version.to_string(), pkg_ident.arch]) /// Returns `Ok(true)` if the installation exists and is now removed. Returns `Ok(false)` if the installation
/// does not exist. Returns `Err(_)` if an error occurred while accessing to the database and the state is
/// unknown.
pub fn remove_installation(&self, install_pkgspec: &PkgSpec) -> rusqlite::Result<bool> {
self.0
.prepare_cached(r#"DELETE FROM "installation" WHERE "install_pkgspec" = ?1"#)?
.execute(params![install_pkgspec.to_string()])
.map(|x| x > 0) .map(|x| x > 0)
} }
// ==- Dependency management -== // ==- Dependency management -==
pub fn insert_dependency(&mut self, dependency: &DependencyRecord) -> rusqlite::Result<()> { pub fn insert_dependency(&self, dependency: &DependencyRecord) -> rusqlite::Result<()> {
self.0 self.0
.prepare_cached( .prepare_cached(
r#"INSERT INTO "dependency"("pkg_ident_a", "pkg_spec_b", "pkg_ident_b") VALUES(?1, ?2, ?3)"#, r#"INSERT INTO "dependency"("pkg_ident_a", "pkg_spec_b") VALUES(?1, ?2)"#,
)? )?
.execute(params![ .execute(params![
dependency.pkg_ident_a.to_string(), dependency.pkg_ident_a.to_string(),
dependency.pkg_spec_b.to_string(), dependency.pkg_spec_b.to_string(),
dependency.pkg_ident_b.to_string(),
])?; ])?;
Ok(()) Ok(())
} }
/// Selects all package that the provided package depends on. /// Selects all package that the provided package depends on.
pub fn select_dependencies( pub fn select_dependencies(
&mut self, &self,
pkg_ident_a: &PkgIdent, pkg_ident_a: &PkgIdent,
) -> rusqlite::Result<Vec<DependencyRecord>> {
self._select_dependency_by_pkg_ident("pkg_ident_a", pkg_ident_a)
}
/// Selects all packages depending on the provided package.
pub fn select_dependents(
&mut self,
pkg_ident_b: &PkgIdent,
) -> rusqlite::Result<Vec<DependencyRecord>> {
self._select_dependency_by_pkg_ident("pkg_ident_b", pkg_ident_b)
}
fn _select_dependency_by_pkg_ident(
&mut self,
provided: &str,
data: &PkgIdent,
) -> rusqlite::Result<Vec<DependencyRecord>> { ) -> rusqlite::Result<Vec<DependencyRecord>> {
let mut all = Vec::with_capacity(32); let mut all = Vec::with_capacity(32);
let mut stmt = self.0.prepare_cached(&format!( let mut stmt = self
"SELECT * FROM \"dependency\" WHERE \"{provided}\" == ?1" .0
))?; .prepare_cached(r#"SELECT * FROM "dependency" WHERE "pkg_ident_a" == ?1"#)?;
let rows = stmt.query_map(params![data.to_string()], map_dependency)?; let rows = stmt.query_map(params![pkg_ident_a.to_string()], map_dependency)?;
for row in rows { for row in rows {
all.push(row?); all.push(row?);
} }
Ok(all) Ok(all)
} }
pub fn remove_dependency_by_a(&mut self, pkg_ident_a: &PkgIdent) -> rusqlite::Result<bool> { /// Selects all packages depending on the provided package.
pub fn select_dependents(
&self,
pkg_spec_b: &PkgSpec,
) -> rusqlite::Result<Vec<DependencyRecord>> {
let mut all = Vec::with_capacity(32);
let mut stmt = self
.0
.prepare_cached(r#"SELECT * FROM "dependency" WHERE "pkg_spec_b" == ?1"#)?;
let rows = stmt.query_map(params![pkg_spec_b.to_string()], map_dependency)?;
for row in rows {
all.push(row?);
}
Ok(all)
}
pub fn remove_dependency_by_a(&self, pkg_ident_a: &PkgIdent) -> rusqlite::Result<bool> {
self.0 self.0
.prepare_cached(r#"DELETE FROM "dependency" WHERE "pkg_ident_a" = ?1"#)? .prepare_cached(r#"DELETE FROM "dependency" WHERE "pkg_ident_a" = ?1"#)?
.execute(params![pkg_ident_a.to_string()]) .execute(params![pkg_ident_a.to_string()])
.map(|x| x > 0) .map(|x| x > 0)
} }
pub fn update_dependency(
&mut self,
pkg_ident_a: Option<&PkgIdent>,
pkg_ident_b_orig: &PkgIdent,
pkg_ident_b_new: &PkgIdent,
) -> rusqlite::Result<bool> {
let (sql, params) = match pkg_ident_a {
Some(pkg_ident_a) => (
r#"UPDATE "dependency" SET "pkg_ident_b" = ?1 WHERE "pkg_ident_a" = ?2 AND "pkg_ident_b" = ?3"#,
params![
pkg_ident_b_new.to_string(),
pkg_ident_a.to_string(),
pkg_ident_b_orig.to_string()
],
),
None => (
r#"UPDATE "dependency" SET "pkg_ident_b" = ?1 WHERE "pkg_ident_b" = ?2"#,
params![pkg_ident_b_new.to_string(), pkg_ident_b_orig.to_string()],
),
};
self.0.prepare_cached(sql)?.execute(params).map(|x| x > 0)
}
// ==- Concept management -== // ==- Concept management -==
pub fn insert_concept( pub fn insert_concept(
&mut self, &self,
concept_ident: &ConceptIdent, concept_ident: &ConceptIdent,
provider: &PkgIdent, provider: &PkgIdent,
) -> rusqlite::Result<()> { ) -> rusqlite::Result<()> {
@@ -313,7 +446,7 @@ CREATE TABLE IF NOT EXISTS "concept"(
} }
pub fn select_concept_by_ident( pub fn select_concept_by_ident(
&mut self, &self,
ident: &ConceptIdent, ident: &ConceptIdent,
) -> rusqlite::Result<Vec<(ConceptIdent, PkgIdent)>> { ) -> rusqlite::Result<Vec<(ConceptIdent, PkgIdent)>> {
let mut stmt = self let mut stmt = self
@@ -327,7 +460,7 @@ CREATE TABLE IF NOT EXISTS "concept"(
Ok(concept) Ok(concept)
} }
pub fn remove_concept_provided_by(&mut self, provider: &PkgIdent) -> rusqlite::Result<bool> { pub fn remove_concept_provided_by(&self, provider: &PkgIdent) -> rusqlite::Result<bool> {
self.0 self.0
.prepare_cached(r#"DELETE FROM "concept" WHERE "provider" = ?1"#)? .prepare_cached(r#"DELETE FROM "concept" WHERE "provider" = ?1"#)?
.execute(params![provider.to_string()]) .execute(params![provider.to_string()])
@@ -335,14 +468,22 @@ CREATE TABLE IF NOT EXISTS "concept"(
} }
} }
/// Record of an installation. /// A local database package record.
#[derive(Debug, Clone)]
pub struct LocalPackage {
pub pkg_ident: PkgIdent,
pub pkg_manifest: PkgManifest,
pub install_date: i64,
pub installed_size: u64,
}
/// A local database installation record.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Installation { pub struct Installation {
pub pkg_manifest: PkgManifest,
pub install_pkgspec: PkgSpec, pub install_pkgspec: PkgSpec,
pub pkg_ident: PkgIdent,
pub install_date: i64, pub install_date: i64,
pub update_date: i64, pub update_date: i64,
pub installed_size: u64,
pub install_flags: InstallFlags, pub install_flags: InstallFlags,
} }
@@ -387,25 +528,32 @@ impl Display for InstallFlags {
} }
} }
/// A dependency record. /// A local database dependency record.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct DependencyRecord { pub struct DependencyRecord {
pub pkg_ident_a: PkgIdent, pub pkg_ident_a: PkgIdent,
pub pkg_spec_b: PkgSpec, pub pkg_spec_b: PkgSpec,
pub pkg_ident_b: PkgIdent, }
fn map_package(row: &Row) -> rusqlite::Result<LocalPackage> {
Ok(LocalPackage {
pkg_ident: row.get::<_, String>("pkg_ident")?.parse().unwrap(),
pkg_manifest: serde_json::from_str(&row.get::<_, String>("pkg_manifest")?)
.map_err(from_sql_error)?,
install_date: row.get("install_date")?,
installed_size: row.get::<_, i64>("installed_size")? as _,
})
} }
fn map_installation(row: &Row) -> rusqlite::Result<Installation> { fn map_installation(row: &Row) -> rusqlite::Result<Installation> {
Ok(Installation { Ok(Installation {
pkg_manifest: serde_json::from_str(&row.get::<_, String>("pkg_manifest")?)
.map_err(from_sql_error)?,
install_pkgspec: row install_pkgspec: row
.get::<_, String>("install_pkgspec")? .get::<_, String>("install_pkgspec")?
.parse() .parse()
.map_err(from_sql_error)?, .map_err(from_sql_error)?,
pkg_ident: row.get::<_, String>("pkg_ident")?.parse().unwrap(),
install_date: row.get("install_date")?, install_date: row.get("install_date")?,
update_date: row.get("update_date")?, update_date: row.get("update_date")?,
installed_size: row.get::<_, i64>("installed_size")? as _,
install_flags: row.get::<_, String>("install_flags")?.parse().unwrap(), install_flags: row.get::<_, String>("install_flags")?.parse().unwrap(),
}) })
} }
@@ -420,10 +568,6 @@ fn map_dependency(row: &Row) -> rusqlite::Result<DependencyRecord> {
.get::<_, String>("pkg_spec_b")? .get::<_, String>("pkg_spec_b")?
.parse() .parse()
.map_err(from_sql_error)?, .map_err(from_sql_error)?,
pkg_ident_b: row
.get::<_, String>("pkg_ident_b")?
.parse()
.map_err(from_sql_error)?,
}) })
} }
+3 -1
View File
@@ -1,3 +1,5 @@
//! Types and functions for describing and operating packages.
use crate::{ use crate::{
common::io::Decompress, common::io::Decompress,
link::LinksFile, link::LinksFile,
@@ -50,7 +52,7 @@ impl Package {
pub fn links(&self) -> Option<LinksFile> { pub fn links(&self) -> Option<LinksFile> {
let path = self.extracted_dir.path().join(LinksFile::FILENAME); let path = self.extracted_dir.path().join(LinksFile::FILENAME);
if path.exists() { if path.exists() {
Some(LinksFile(path)) Some(LinksFile::new(path))
} else { } else {
None None
} }
+4
View File
@@ -1,6 +1,9 @@
//! The Packie profile, which is compile-time configuration applied to Packie.
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::path::PathBuf; use std::path::PathBuf;
/// A Packie profile.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Profile { pub struct Profile {
/// Directory for storing package bundles, e.g. `/pkg`. /// Directory for storing package bundles, e.g. `/pkg`.
@@ -19,6 +22,7 @@ pub struct Profile {
pub host_arch: String, pub host_arch: String,
} }
impl Profile { impl Profile {
/// Returns the built-in [`Profile`] instance.
pub fn builtin() -> Self { pub fn builtin() -> Self {
Self { Self {
pkg_dir: option_env!("PACKIE_PKG_DIR").unwrap_or("/pkg").into(), pkg_dir: option_env!("PACKIE_PKG_DIR").unwrap_or("/pkg").into(),
+28 -10
View File
@@ -1,11 +1,16 @@
use crate::{configure::ConfigureOptions, link::LinksFile, package::PkgSpec}; //! Functions for removing a package.
use crate::{configure::ConfigureOptions, package::PkgSpec};
use rust_i18n::t; use rust_i18n::t;
impl super::Packie { impl super::Packie {
/// Removes *one* package *matching* the provided package spec.
///
/// If multiple installations matches the matched package, all the installations are to be removed.
pub fn remove(&mut self, pkgspec: &PkgSpec) -> Result<(), RemoveError> { pub fn remove(&mut self, pkgspec: &PkgSpec) -> Result<(), RemoveError> {
// Find the installation to remove // Find the package to remove
let mut found = self let mut found = self
.search_installation(pkgspec) .search_local_package(pkgspec)
.map_err(RemoveError::Database)?; .map_err(RemoveError::Database)?;
if found.is_empty() { if found.is_empty() {
return Err(RemoveError::NotFound); return Err(RemoveError::NotFound);
@@ -14,13 +19,21 @@ impl super::Packie {
return Err(RemoveError::NotUniquePkgSpec); return Err(RemoveError::NotUniquePkgSpec);
} }
assert_eq!(found.len(), 1); assert_eq!(found.len(), 1);
let found = found.remove(0); let package = found.remove(0);
let pkg_ident = found.pkg_manifest.pkg_ident(); let pkg_ident = package.pkg_manifest.pkg_ident();
// Find installations bound to the package
let installations = self
.local_db
.select_installation_by_pkgident(&pkg_ident)
.map_err(RemoveError::Database)?;
// Check for dependencies // Check for dependencies
let dependents = self.local_db.select_dependents(&pkg_ident)?; for i in &installations {
if !dependents.is_empty() { let dependents = self.local_db.select_dependents(&i.install_pkgspec)?;
return Err(RemoveError::HasDependents); if !dependents.is_empty() {
return Err(RemoveError::HasDependents);
}
} }
// Run configure scripts // Run configure scripts
@@ -39,7 +52,7 @@ impl super::Packie {
_ = std::fs::remove_dir_all(&self.local_data.pkg_configure_scripts_dir(&pkg_ident)); _ = std::fs::remove_dir_all(&self.local_data.pkg_configure_scripts_dir(&pkg_ident));
// Remove all links // Remove all links
let links = LinksFile(self.local_data.links_file(&pkg_ident)); let links = self.links_of_pkg(&pkg_ident);
if let Ok(links) = links.iter() { if let Ok(links) = links.iter() {
for link in links { for link in links {
let Ok(link) = link else { let Ok(link) = link else {
@@ -54,8 +67,13 @@ impl super::Packie {
std::fs::remove_dir_all(&bundle_dir).map_err(RemoveError::RemoveFiles)?; std::fs::remove_dir_all(&bundle_dir).map_err(RemoveError::RemoveFiles)?;
// Remove database records // Remove database records
for i in &installations {
self.local_db
.remove_installation(&i.install_pkgspec)
.map_err(RemoveError::Database)?;
}
self.local_db self.local_db
.remove_installation(&pkg_ident) .remove_package(&pkg_ident)
.map_err(RemoveError::Database)?; .map_err(RemoveError::Database)?;
self.local_db self.local_db
.remove_concept_provided_by(&pkg_ident) .remove_concept_provided_by(&pkg_ident)
+29 -18
View File
@@ -8,6 +8,7 @@ pub use serve::RepoServeDir;
use crate::{ use crate::{
Packie, Packie,
common::db::MigrationItem,
package::{ConceptIdent, PkgIdent, PkgManifest, PkgSpec}, package::{ConceptIdent, PkgIdent, PkgManifest, PkgSpec},
}; };
use download::Download; use download::Download;
@@ -94,27 +95,37 @@ pub struct RepoDb {
impl RepoDb { impl RepoDb {
const FILENAME: &str = "repo.db"; const FILENAME: &str = "repo.db";
const SCHEMA: &str = r#" const MIGRATIONS: &[MigrationItem] = &[
CREATE TABLE IF NOT EXISTS "package"( MigrationItem {
"pkg_name" TEXT NOT NULL, name: "20261122-create-table-package",
"pkg_version" TEXT NOT NULL, sql: r#"
"pkg_arch" TEXT NOT NULL, CREATE TABLE IF NOT EXISTS "package"(
"pkg_manifest" TEXT NOT NULL, "pkg_name" TEXT NOT NULL,
"download_size" INTEGER NOT NULL, "pkg_version" TEXT NOT NULL,
"installed_size" INTEGER NOT NULL, "pkg_arch" TEXT NOT NULL,
"checksum" TEXT NOT NULL, "pkg_manifest" TEXT NOT NULL,
PRIMARY KEY ("pkg_name", "pkg_version", "pkg_arch") "download_size" INTEGER NOT NULL,
); "installed_size" INTEGER NOT NULL,
CREATE TABLE IF NOT EXISTS "concept"( "checksum" TEXT NOT NULL,
"id" INTEGER PRIMARY KEY AUTOINCREMENT, PRIMARY KEY ("pkg_name", "pkg_version", "pkg_arch")
"concept_ident" TEXT NOT NULL, )
"provider" TEXT NOT NULL "#,
); },
"#; MigrationItem {
name: "20261122-create-table-concept",
sql: r#"
CREATE TABLE IF NOT EXISTS "concept"(
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"concept_ident" TEXT NOT NULL,
"provider" TEXT NOT NULL
)
"#,
},
];
pub fn open_rw<P: AsRef<Path>>(path: P) -> rusqlite::Result<Self> { pub fn open_rw<P: AsRef<Path>>(path: P) -> rusqlite::Result<Self> {
let conn = rusqlite::Connection::open(path)?; let conn = rusqlite::Connection::open(path)?;
conn.execute_batch(Self::SCHEMA)?; crate::common::db::run_migration(&conn, Self::MIGRATIONS)?;
Ok(Self { Ok(Self {
repo_name: None, repo_name: None,
conn, conn,
+5 -1
View File
@@ -1,8 +1,9 @@
//! Parsing and matching of software versions. //! Parsing and matching of software versions.
use std::{cmp::Ordering, fmt::Display, str::FromStr};
use rust_i18n::t; use rust_i18n::t;
use std::{cmp::Ordering, fmt::Display, str::FromStr};
/// A parsed package version.
#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Version { pub struct Version {
/// Version namespace. By default, the value is `0`. The value needs to be changed if the versioning /// Version namespace. By default, the value is `0`. The value needs to be changed if the versioning
@@ -102,6 +103,7 @@ impl Display for Version {
crate::impl_serde_str!(Version); crate::impl_serde_str!(Version);
impl Version {} impl Version {}
/// Prerelease part of a version.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Prerelease { pub struct Prerelease {
pub tag: String, pub tag: String,
@@ -126,6 +128,7 @@ impl Display for Prerelease {
} }
} }
/// Filter that matches versions.
#[derive(Debug, Clone, Default, PartialEq, Eq)] #[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum VersionFilter { pub enum VersionFilter {
/// The '*' filter, matching any versions. /// The '*' filter, matching any versions.
@@ -151,6 +154,7 @@ pub enum VersionFilter {
WithMeta(String), WithMeta(String),
} }
impl VersionFilter { impl VersionFilter {
/// Returns `true` if the version is covered by this filter.
pub fn matches(&self, version: &Version) -> bool { pub fn matches(&self, version: &Version) -> bool {
match self { match self {
Self::Any => true, Self::Any => true,