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_json = "1"
toml = "1"
rusqlite = { version = "0.41" }
rusqlite = { version = "0.43" }
# Error handling
thiserror = "2"
@@ -47,4 +47,4 @@ rustc-hash = "2"
# Misc
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"
clap = { version = "4", features = ["derive"] }
console = "0.16"
nix = { version = "0.31", features = ["sched"] }
nix = { version = "0.32", features = ["sched"] }
packie = { path = "../" }
rust-i18n = "4"
rustc-hash = "2"
tabled = { version = "0.22", features = ["ansi"] }
indicatif = "0.18"
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 packie::{
Packie,
local::Installation,
local::LocalPackage,
package::{PkgIdent, PkgSpec},
repo::{DownloadPackageEvent, RepoPackage},
};
use rust_i18n::t;
use rustc_hash::FxHashMap;
use std::{fmt::Display, path::PathBuf};
use tabled::{
Table, Tabled,
@@ -58,6 +59,7 @@ pub struct SummaryItem {
impl SummaryItem {
pub const INSTALL: &str = "install";
pub const REMOVE: &str = "remove";
pub const SET_MANUAL_INSTALL: &str = "set-manual-install";
}
#[derive(Debug, Tabled)]
@@ -69,19 +71,23 @@ struct PrintedSummaryItem {
}
impl From<SummaryItem> for PrintedSummaryItem {
fn from(value: SummaryItem) -> Self {
let wrap_color = |s: &dyn Display| {
if value.operation == SummaryItem::INSTALL {
format!("{}", console::style(s).green())
} else if value.operation == SummaryItem::REMOVE {
format!("{}", console::style(s).red())
} else {
format!("{}", console::style(s).blue())
}
let wrap_color = |s: &dyn Display| match value.operation {
SummaryItem::INSTALL => console::style(s.to_string()).green(),
SummaryItem::REMOVE => console::style(s.to_string()).red(),
SummaryItem::SET_MANUAL_INSTALL => console::style(s.to_string()).blue(),
_ => console::style(s.to_string()).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 {
pkgspec: wrap_color(&value.pkgspec),
version: wrap_color(&value.pkgident.version),
operation: wrap_color(&value.operation),
pkgspec: wrap_color(&value.pkgspec).to_string(),
version: wrap_color(&value.pkgident.version).to_string(),
operation,
notes: String::new(),
}
}
@@ -97,7 +103,7 @@ pub fn print_summary(summary: Vec<SummaryItem>) {
}
pub fn format_size(bytes: i64) -> String {
if bytes.is_positive() {
if !bytes.is_negative() {
HumanBytes(bytes as u64).to_string()
} else {
format!("-{}", HumanBytes(bytes.abs() as u64))
@@ -114,8 +120,8 @@ pub fn format_datetime(timestamp: i64) -> String {
pub fn search_unique_package(
packie: &mut Packie,
pkgspec: &PkgSpec,
) -> Result<Installation, crate::Error> {
let mut found = packie.search_installation(&pkgspec)?;
) -> Result<LocalPackage, crate::Error> {
let mut found = packie.search_local_package(&pkgspec)?;
if found.is_empty() {
return Err(crate::error!("common.package_not_found", pkgspec = pkgspec));
}
@@ -136,29 +142,29 @@ pub fn search_unique_package(
Ok(found.remove(0))
}
pub fn download_packages<T>(
pub fn download_packages<'a>(
packie: &mut Packie,
packages: &mut Vec<(T, PathBuf)>,
pkginfo: impl Fn(&T) -> &RepoPackage,
) -> Result<(), crate::Error> {
let download_size = packages.iter().map(|x| pkginfo(&x.0).download_size).sum();
all: impl IntoIterator<Item = &'a RepoPackage> + Clone,
) -> Result<FxHashMap<PkgIdent, PathBuf>, crate::Error> {
let mut result = FxHashMap::default();
let download_size = all.clone().into_iter().map(|x| x.download_size).sum();
let progress_bar =
ProgressBar::new(download_size).with_style(crate::common::progress_style_multidownload());
let nr_packages = packages.len();
for (count, (package, file_path)) in packages.iter_mut().enumerate() {
let repo_pkg = pkginfo(package);
let nr_packages = all.clone().into_iter().count();
for (count, it) in all.into_iter().enumerate() {
let init_pos = progress_bar.position();
progress_bar.println(format!(
"[{}/{nr_packages}] {}",
count + 1,
t!(
"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());
let path = packie.download_package(&repo_pkg.repo_pkg_ident().unwrap(), |ev| match ev {
progress_bar.set_prefix(it.pkg_manifest.pkg_ident().to_string());
let path = packie.download_package(&it.repo_pkg_ident().unwrap(), |ev| match ev {
DownloadPackageEvent::Progress(_, sum, _) => {
progress_bar.set_position(init_pos + sum);
}
@@ -174,9 +180,10 @@ pub fn download_packages<T>(
));
}
})?;
*file_path = path;
progress_bar.set_position(init_pos + repo_pkg.download_size);
result.insert(it.pkg_manifest.pkg_ident(), path);
progress_bar.set_position(init_pos + it.download_size);
}
drop(progress_bar);
Ok(())
Ok(result)
}
+6 -8
View File
@@ -3,7 +3,7 @@ use clap::Parser;
use console::style;
use packie::{
PackieBuilder,
local::{InstallFlags, Installation},
local::LocalPackage,
package::{PkgManifest, PkgSpec},
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 {
let val = everything
.entry(i.pkg_manifest.pkg_ident())
.or_insert_with(|| ComprehensivePackageInfo::from(i.clone()));
val.installed = true;
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);
}
@@ -83,16 +81,16 @@ impl From<RepoPackage> for ComprehensivePackageInfo {
}
}
}
impl From<Installation> for ComprehensivePackageInfo {
fn from(value: Installation) -> Self {
impl From<LocalPackage> for ComprehensivePackageInfo {
fn from(value: LocalPackage) -> Self {
Self {
pkg_manifest: value.pkg_manifest,
installed: true,
install_pkgspec: Some(value.install_pkgspec),
install_pkgspec: None,
install_date: Some(value.install_date),
download_size: None,
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 indicatif::ProgressBar;
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 std::path::PathBuf;
#[derive(Debug, Parser)]
pub struct Cli {
@@ -36,27 +39,30 @@ pub fn main(cli: Cli) -> Result<(), crate::Error> {
items.push(i.parse::<PkgSpec>()?);
}
let mut packages: Vec<(_, PathBuf)> = packie
.calculate_installation(&items, &CalculateInstallationOptions::new())?
.into_iter()
.map(|x| (x, PathBuf::new()))
.collect();
if packages.is_empty() {
let actions: Vec<_> =
packie.calculate_installation(&items, &CalculateInstallationOptions::new())?;
let download_size: u64 = actions
.iter()
.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"));
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!();
print_summary(summary);
@@ -82,27 +88,94 @@ pub fn main(cli: Cli) -> Result<(), crate::Error> {
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 progress_bar = ProgressBar::new(nr_packages as _);
for (count, (package, file_path)) in packages.into_iter().enumerate() {
progress_bar.println(format!(
"[{}/{nr_packages}] {}",
count + 1,
t!(
"install.installing_hint",
pkgspec = style(&package.install_pkgspec).green()
)
));
let nr_actions = actions
.iter()
.filter(|x| matches!(x, InstallationAction::InstallFromRepo(_)))
.count();
let progress_bar = ProgressBar::new(nr_actions as _);
let mut count = 1;
for action in actions {
match action {
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();
options.auto_installed = package.auto_installed;
options.install_pkgspec = Some(package.install_pkgspec);
packie.install_package_file(file_path, &options)?;
packie.install_package_file(
downloaded
.get(&req.repo_pkg.pkg_manifest.pkg_ident())
.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(())
}
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 common;
mod info;
@@ -50,6 +51,9 @@ enum Subcommand {
/// Remove one or more packages
Remove(remove::Cli),
/// Auto-remove orphan packages
Autoremove(autoremove::Cli),
/// Administrate repository service
RepoAdmin(repo_admin::Cli),
@@ -85,6 +89,7 @@ fn main() {
Subcommand::Upgrade(cli) => upgrade::main(cli),
Subcommand::Print(cli) => print::main(cli),
Subcommand::Remove(cli) => remove::main(cli),
Subcommand::Autoremove(cli) => autoremove::main(cli),
Subcommand::RepoAdmin(cli) => repo_admin::main(cli),
Subcommand::Update(cli) => update::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> {
let mut packie = PackieBuilder::new().readonly(true).build()?;
let packie = PackieBuilder::new().readonly(true).build()?;
match other {
["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() {
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
.iter()
.map(|x| SummaryItem {
pkgspec: x.install_pkgspec.clone(),
pkgspec: x.pkg_ident.clone().into(),
pkgident: x.pkg_manifest.pkg_ident(),
operation: SummaryItem::REMOVE,
})
@@ -48,7 +48,7 @@ pub fn main(cli: Cli) -> Result<(), crate::Error> {
let progress_bar = ProgressBar::new(nr_packages as _);
for (c, i) in packages.into_iter().enumerate() {
println!(
progress_bar.println(format!(
"[{}/{}] {}",
c + 1,
nr_packages,
@@ -56,7 +56,7 @@ pub fn main(cli: Cli) -> Result<(), crate::Error> {
"remove.action_hint",
package = style(i.pkg_manifest.pkg_ident()).red()
),
);
));
packie
.remove(&i.pkg_manifest.pkg_ident().into())
.map_err(|error| anyhow!("{}", t!("remove.action_failure", error = error)))?;
+3 -3
View File
@@ -47,7 +47,7 @@ fn non_interactive(
file: PathBuf,
pkg: PkgSpec,
) -> 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());
for pkgident in installations.iter().map(|x| x.pkg_manifest.pkg_ident()) {
let links = packie.links_of_pkg(&pkgident);
@@ -79,8 +79,8 @@ fn interactive(
) -> Result<Option<(PkgIdent, LinkDescription)>, crate::Error> {
let mut all_pkgs = Vec::with_capacity(1024);
let mut candidates = Vec::new();
packie.for_each_installation::<anyhow::Error>(|inst| {
all_pkgs.push(inst.pkg_manifest.pkg_ident());
packie.for_each_local_package::<anyhow::Error>(|inst| {
all_pkgs.push(inst.pkg_ident.clone());
Ok(())
})?;
for pkgident in all_pkgs {
+79 -69
View File
@@ -3,11 +3,10 @@ use clap::Parser;
use console::style;
use indicatif::ProgressBar;
use packie::{
PackieBuilder, graph::UpgradationOp, install::InstallOptions, local::InstallFlags,
PackieBuilder, graph::UpgradationAction, install::InstallOptions, local::InstallFlags,
package::PkgSpec,
};
use rust_i18n::t;
use std::path::PathBuf;
#[derive(Debug, Parser)]
pub struct Cli {
@@ -20,56 +19,54 @@ pub struct Cli {
pub fn main(cli: Cli) -> Result<(), crate::Error> {
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"));
return Ok(());
}
println!("{}", t!("upgrade.prompt_to_upgrade"));
println!();
let mut ui_summary = Vec::with_capacity(ops.len());
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);
print_summary(ui_summary.clone());
println!();
let download_size: u64 = ops
let download_size: u64 = actions
.iter()
.map(|x| match x {
UpgradationOp::Install(dep) => dep.repo_pkg.download_size,
UpgradationOp::Replace(rep) => rep.new.download_size,
UpgradationAction::InstallFromRepo(req) => req.repo_pkg.download_size,
_ => 0,
})
.sum();
let installed_size = ops
let installed_size = actions
.iter()
.map(|x| match x {
UpgradationOp::Install(dep) => dep.repo_pkg.installed_size as i64,
UpgradationOp::Replace(rep) => {
(rep.new.installed_size as i64) - (rep.original.installed_size as i64)
}
UpgradationAction::InstallFromRepo(req) => req.repo_pkg.installed_size as i64,
UpgradationAction::Remove(pkg_ident) => packie
.select_local_package(pkg_ident)
.map(|y| -(y.installed_size as i64))
.unwrap_or_default(),
_ => 0,
})
.sum();
@@ -92,52 +89,65 @@ pub fn main(cli: Cli) -> Result<(), crate::Error> {
return Ok(());
}
let mut ops = ops.into_iter().map(|x| (x, PathBuf::new())).collect();
crate::common::download_packages(&mut packie, &mut ops, |x| match x {
UpgradationOp::Install(x) => &x.repo_pkg,
UpgradationOp::Replace(x) => &x.new,
})?;
let downloaded = crate::common::download_packages(
&mut packie,
actions.iter().filter_map(|x| match x {
UpgradationAction::InstallFromRepo(req) => Some(&req.repo_pkg),
_ => None,
}),
)?;
let nr_ops = ops.len();
let progress_bar = ProgressBar::new(ops.len() as _);
for (op, file_path) in ops {
match op {
UpgradationOp::Install(dep) => {
let nr_actions = ui_summary.len();
let progress_bar = ProgressBar::new(nr_actions as _);
let mut count = 1;
for action in actions {
match action {
UpgradationAction::InstallFromRepo(req) => {
progress_bar.println(format!(
"[{}/{}] {}",
progress_bar.position() + 1,
nr_ops,
count,
nr_actions,
t!(
"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();
options.auto_installed = dep.auto_installed;
options.install_pkgspec = Some(dep.install_pkgspec);
packie.install_package_file(file_path, &options)?;
if req.override_links {
options.override_links = true;
}
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.position() + 1,
nr_ops,
t!(
"upgrade.installing_hint",
pkg = style(&rep.new.pkg_manifest.pkg_ident()).green(),
)
count,
nr_actions,
t!("upgrade.removing_hint", pkg = style(&pkg_ident).green(),)
));
let mut options = InstallOptions::default();
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)?;
packie.remove(&pkg_ident.into())?;
}
}
progress_bar.inc(1);
}
Ok(())
+4
View File
@@ -63,6 +63,10 @@ graph.GraphError.NotFound:
en: "item not found: %{item}"
zh-CN: "找不到项目:%{item}"
ja: "項目が見つかりません:%{item}"
graph.InstallError.Database:
en: "local database error: %{error}"
zh-CN: "本地数据库错误:%{error}"
ja: "ローカルデータベースエラー:%{error}"
BuildPackieError.Lock:
en: "failed to lock packie database: %{error}"
zh-CN: "无法锁定 Packie 数据库:%{error}"
+40
View File
@@ -67,6 +67,10 @@ upgrade.installing_hint:
en: "Installing \"%{pkg}\"..."
zh-CN: "正在安装 \"%{pkg}\"..."
ja: "「%{pkg}」をインストールしています..."
upgrade.removing_hint:
en: "Removing \"%{pkg}\"..."
zh-CN: "正在移除 \"%{pkg}\"..."
ja: "「%{pkg}』 を削除中..."
info.no_package_found:
en: "The specified package was not found."
zh-CN: "找不到指定的包。"
@@ -163,6 +167,30 @@ remove.no_packages_to_remove:
en: "No packages specified to remove."
zh-CN: "未指定要移除的包。"
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:
en: "Speed: "
zh-CN: "速度:"
@@ -199,6 +227,18 @@ common.download_packages.download_error:
en: "error: failed to download from \"%{url}\": %{error}"
zh-CN: "错误:无法下载 \"%{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:
en: "warning: failed to read repository cache directory: %{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 db;
pub mod fs;
pub mod io;
pub mod macros;
+22
View File
@@ -1,3 +1,5 @@
//! Package configuration.
use crate::package::PkgIdent;
use std::{
fmt::Display,
@@ -5,6 +7,10 @@ use std::{
};
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(
&self,
pkg: &PkgIdent,
@@ -38,14 +44,28 @@ impl super::Packie {
}
}
/// Options of package configuration.
#[derive(Debug, Clone)]
pub struct ConfigureOptions {
/// Action that is passed to the script.
pub action: Action,
/// Whether we should run the script in interactive mode.
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>,
/// Extra arguments to the configuration script.
///
/// This is usually used to set non-default options in non-interactive mode.
pub extra_args: Vec<String>,
}
/// Action of package configuration.
#[derive(Debug, Clone, Copy)]
pub enum Action {
Install,
@@ -63,6 +83,7 @@ impl Display for Action {
}
}
/// Runs a configuration script, setting the correct environment up.
pub fn run_script(
path: impl AsRef<Path>,
options: &ConfigureOptions,
@@ -85,6 +106,7 @@ pub fn run_script(
}
}
/// Error occurred while running a configuration script.
#[derive(Debug, thiserror::Error)]
pub enum ConfigureError {
#[error("{0}")]
+267 -117
View File
@@ -1,46 +1,50 @@
//! Calculation of the package relationship graph.
use crate::{
local::Installation,
local::InstallFlags,
package::{PkgIdent, PkgSpec},
repo::RepoPackage,
};
use itertools::Itertools;
use rust_i18n::t;
impl super::Packie {
/// Calculates actions required to install provided packages from repositories.
pub fn calculate_installation(
&mut self,
pkgs: &[PkgSpec],
items: &[PkgSpec],
options: &CalculateInstallationOptions,
) -> Result<Vec<InstallationNode>, GraphError> {
let mut all = Vec::with_capacity(pkgs.len() * 4);
) -> Result<Vec<InstallationAction>, GraphError> {
let mut all = Vec::with_capacity(items.len() * 4);
for pkg in pkgs {
let mut current = self._calculate_installation(pkg, options)?;
all.append(&mut current);
}
for pkgspec in items {
let current = self._calculate_installation(pkgspec, options)?;
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
.iter()
.filter(|x| !x.auto_installed)
.map(|x| {
(
x.repo_pkg.pkg_manifest.pkg_ident(),
x.install_pkgspec.clone(),
)
})
.collect();
// Collect result
all.push(InstallationAction::InstallFromRepo(ir));
}
InstallationAction::EnsureInstallation(ei) => {
// Filter out existing `EnsureInstallation` records
for i in &mut all {
if let InstallationAction::EnsureInstallation(y) = i
&& y.install_pkgspec == ei.install_pkgspec
{
y.auto_installed &= ei.auto_installed;
continue;
}
}
let mut all: Vec<_> = all
.into_iter()
.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();
// Collect result
all.push(InstallationAction::EnsureInstallation(ei));
}
}
}
}
@@ -51,7 +55,7 @@ impl super::Packie {
&mut self,
desired: &PkgSpec,
options: &CalculateInstallationOptions,
) -> Result<Vec<InstallationNode>, GraphError> {
) -> Result<Vec<InstallationAction>, GraphError> {
let prior_arch = self.profile.host_arch.clone();
let mut query = self.query_repo();
@@ -67,32 +71,33 @@ impl super::Packie {
if found.is_empty() {
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()),
&prior_arch,
);
let prior_pkg = found
let prior = found
.iter()
.enumerate()
.find(|(_, p)| p.pkg_manifest.pkg_ident() == prior_pkg)
.find(|(_, p)| p.pkg_manifest.pkg_ident() == prior)
.unwrap()
.0;
let repo_pkg = found.remove(prior_pkg);
let repo_pkg = found.remove(prior);
let already_installed = !self
.search_installation(&pkgspec)
.unwrap_or_default()
.is_empty();
if already_installed && !(&pkgspec == desired && options.no_existence_check) {
let local_matches = self.search_local_package(&pkgspec).unwrap_or_default();
if !local_matches.is_empty() && !(pkgspec == *desired && options.no_existence_check) {
let prior = prior_pkg(
local_matches.iter().map(|x| x.pkg_ident.clone()),
&prior_arch,
);
depgraph.push(InstallationAction::EnsureInstallation(EnsureInstallation {
auto_installed: pkgspec != *desired,
install_pkgspec: pkgspec,
pkg_ident: prior,
force: false,
}));
continue;
}
depgraph.push(InstallationNode {
repo_pkg: repo_pkg.clone(),
auto_installed: &pkgspec != desired,
install_pkgspec: pkgspec,
});
for dep in &repo_pkg.pkg_manifest.dependencies {
stack.push(dep.clone());
}
@@ -102,94 +107,209 @@ impl super::Packie {
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();
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(
&mut self,
pkgspecs: Vec<PkgSpec>,
) -> Result<Vec<UpgradationOp>, GraphError> {
// Collect all package idents required to upgrade
) -> Result<Vec<UpgradationAction>, GraphError> {
// Collect all install package specs required to upgrade
let mut installations = Vec::with_capacity(pkgspecs.len());
if pkgspecs.is_empty() {
self.for_each_installation(|x| Ok::<_, rusqlite::Error>(installations.push(x)))
.unwrap();
self.for_each_installation(|x| {
Ok::<_, rusqlite::Error>(installations.push(x.install_pkgspec))
})
.unwrap();
} else {
for pkgspec in pkgspecs {
let mut searched = self.search_installation(&pkgspec).unwrap_or_default();
installations.append(&mut searched);
for i in pkgspecs {
if let Ok(exact) = self.select_installation(&i) {
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 nodes = Vec::with_capacity(installations.len() / 3);
for i in installations {
let Some(node) = self._calculate_upgradation(&i.pkg_manifest.pkg_ident())? else {
continue;
};
nodes.push(node);
}
// Collect upgradation summary
let mut ops = Vec::with_capacity(nodes.len());
for node in &nodes {
let mut ti = self.calculate_installation(
&[node.new.pkg_manifest.pkg_ident().into()],
&CalculateInstallationOptions {
skip_recommendations: false,
no_existence_check: false,
},
)?;
ti.pop();
ti.retain(|x| {
!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));
let mut all = Vec::with_capacity(installations.len() * 8);
for install_pkgspec in installations {
let current = self._calculate_upgradation(&install_pkgspec)?;
for i in current {
match &i {
UpgradationAction::InstallFromRepo(req) => {
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);
}
}
UpgradationAction::Remove(req) => {
let has_this = all
.iter()
.any(|x| matches!(x, UpgradationAction::Remove(x) if x == req));
if !has_this {
all.push(i);
}
}
UpgradationAction::EnsureInstallation(_) => {
all.push(i);
}
}
}
ops.push(UpgradationOp::Replace(node.clone()));
}
Ok(ops)
Ok(all)
}
fn _calculate_upgradation(
&mut self,
pkg: &PkgIdent,
) -> Result<Option<UpgradationNode>, GraphError> {
let original = self
install_pkgspec: &PkgSpec,
) -> Result<Vec<UpgradationAction>, GraphError> {
// Collect the existing installation (matching the install package spec)
let orig = self
.local_db
.select_installation_by_ident(pkg)
.map_err(|_| GraphError::NotFound(pkg.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,
}))
}
}
.select_installation(install_pkgspec)
.map_err(|_| GraphError::NotFound(install_pkgspec.to_string()))?;
#[derive(Debug, thiserror::Error)]
pub enum GraphError {
#[error("{}", t!("graph.GraphError.NotFound", item = .0))]
NotFound(String),
// Search the repository for "latest" matching package
let mut depgraph = self
._calculate_installation(
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)]
@@ -207,22 +327,38 @@ impl CalculateInstallationOptions {
}
#[derive(Debug, Clone)]
pub struct InstallationNode {
pub struct InstallFromRepo {
pub repo_pkg: RepoPackage,
pub override_links: bool,
}
#[derive(Debug, Clone)]
pub struct EnsureInstallation {
pub install_pkgspec: PkgSpec,
pub pkg_ident: PkgIdent,
pub auto_installed: bool,
pub force: bool,
}
#[derive(Debug, Clone)]
pub struct UpgradationNode {
pub original: Installation,
pub new: RepoPackage,
pub enum InstallationAction {
InstallFromRepo(InstallFromRepo),
EnsureInstallation(EnsureInstallation),
}
#[derive(Debug, Clone)]
pub enum UpgradationOp {
Install(InstallationNode),
Replace(UpgradationNode),
pub enum UpgradationAction {
InstallFromRepo(InstallFromRepo),
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.
@@ -237,3 +373,17 @@ pub(crate) fn prior_pkg(all: impl Iterator<Item = PkgIdent>, prior_arch: &str) -
}
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::{
configure::ConfigureOptions,
local::{DependencyRecord, InstallFlags, Installation},
package::{Package, PackageError, PkgIdent, PkgSpec},
local::{DependencyRecord, InstallFlags, LocalPackage},
package::{Package, PackageError, PkgSpec},
repo::RepoError,
};
use rust_i18n::t;
use std::path::Path;
/// Options of installing a package.
#[derive(Debug, Clone)]
pub struct InstallOptions {
/// Package spec to record for this installation.
pub install_pkgspec: Option<PkgSpec>,
/// Whether we should run configure scripts in interactive mode.
pub interactive_configure: bool,
/// Whether this package is auto-installed.
pub auto_installed: bool,
/// Mark this installation as an upgradation of an installed package.
pub is_upgradation_of: Option<PkgIdent>,
/// Whether we should override existing links to what is required by this package.
pub override_links: bool,
}
impl InstallOptions {
/// Returns an [`InstallOptions`] instance using the defaults.
pub fn new() -> Self {
Self {
install_pkgspec: None,
interactive_configure: true,
auto_installed: false,
is_upgradation_of: None,
override_links: false,
}
}
}
@@ -58,33 +54,18 @@ impl super::Packie {
let pkg_manifest = package.manifest()?;
let pkg_ident = pkg_manifest.pkg_ident();
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
if !self
.search_installation(&pkg_ident.clone().into())?
.search_local_package(&pkg_ident.clone().into())?
.is_empty()
{
return Err(InstallError::AlreadyInstalled);
}
// Check if the package spec is valid
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());
// Check dependencies
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() {
return Err(InstallError::DependencyNotSatisfied(pkg_spec_b.clone()));
}
@@ -92,45 +73,43 @@ impl super::Packie {
candidates.iter().map(|x| x.pkg_manifest.pkg_ident()),
&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
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)?;
// Record installation in the database
let mut install_flags = InstallFlags::default();
if options.auto_installed {
install_flags.set(InstallFlags::AUTO_INSTALL);
}
let installation = Installation {
// Record package in the database
let local_package = LocalPackage {
pkg_ident: pkg_ident.clone(),
pkg_manifest: pkg_manifest.clone(),
install_pkgspec,
install_date: crate::common::timestamp_secs(),
update_date: crate::common::timestamp_secs(),
installed_size,
install_flags,
};
self.local_db.insert_installation(&installation)?;
self.local_db.insert_package(&local_package)?;
// 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 {
pkg_ident_a: pkg_ident.clone(),
pkg_spec_b,
pkg_ident_b,
pkg_spec_b: pkg_spec_b.clone(),
})?;
}
// 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)?;
}
// Copy links file
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)))?;
}
@@ -146,14 +125,6 @@ impl super::Packie {
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
if let Some(links) = package.links() {
for linkdes in links.iter().ok().into_iter().flatten() {
@@ -163,6 +134,9 @@ impl super::Packie {
if !linkdes.default {
continue;
}
if options.override_links {
_ = crate::link::remove(&linkdes.to);
}
_ = crate::link::activate_by_description(self, &pkg_ident, &linkdes);
}
}
@@ -222,11 +196,3 @@ impl From<rusqlite::Error> for InstallError {
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;
pub mod config;
pub mod configure;
+38 -4
View File
@@ -1,3 +1,5 @@
//! Tools for managing package manager links.
use crate::{Packie, package::PkgIdent};
use serde::{Deserialize, Serialize};
use std::{
@@ -7,17 +9,34 @@ use std::{
};
impl super::Packie {
pub fn links_of_pkg(&self, pkgident: &PkgIdent) -> LinksFile {
LinksFile(self.local_data.links_file(pkgident))
/// Returns the installed [`LinksFile`] instance of required package.
///
/// 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)]
pub struct LinksFile(pub PathBuf);
pub struct LinksFile(PathBuf);
impl LinksFile {
/// File name of a links file in an extracted package tree.
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>>> {
Ok(BufReader::new(File::open(&self.0)?)
.lines()
@@ -45,6 +64,7 @@ pub struct LinkDescription {
pub default: bool,
}
/// Activates a link by provided link description in the provided package ident.
pub fn activate_by_description(
packie: &mut Packie,
pkg_ident: &PkgIdent,
@@ -55,6 +75,7 @@ pub fn activate_by_description(
create(from, &description.to)
}
/// Deactivates a link by provided link description in the provided package ident.
pub fn deactivate_by_description(
packie: &mut Packie,
pkg_ident: &PkgIdent,
@@ -69,6 +90,17 @@ pub fn deactivate_by_description(
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<()> {
std::fs::create_dir_all(
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.
/// - `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<()> {
let mut path = path.into();
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::{
common::db::MigrationItem,
package::{ConceptIdent, PkgIdent, PkgManifest, PkgSpec},
version::VersionFilter,
};
@@ -12,39 +15,95 @@ use std::{
};
impl super::Packie {
pub fn search_installation(
&mut self,
pkgspec: &PkgSpec,
) -> rusqlite::Result<Vec<Installation>> {
/// Search for local packages *matching* the provided package spec.
///
/// The provided package spec don't need to be exactly equal to an existing install package spec.
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
.local_db
.select_installation_by_name(&pkgspec.name)?
.select_package_by_name(&pkgspec.name)?
.into_iter()
.filter(|x| pkgspec.matches(&x.pkg_manifest.pkg_ident()))
.collect::<Vec<_>>();
// With an restrictive version filter we cannot match concepts
if !matches!(pkgspec.version, VersionFilter::Any) {
return Ok(real);
}
// 2. Collect concept matches
let concept = ConceptIdent {
name: pkgspec.name.clone(),
arch: pkgspec.arch.clone(),
};
let abs = self.local_db.select_concept_by_ident(&concept)?;
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
.into_iter()
.unique_by(|x| x.pkg_manifest.pkg_ident())
.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>>(
&mut self,
&self,
f: impl FnMut(Installation) -> Result<(), E>,
) -> Result<(), E> {
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)]
@@ -111,31 +170,52 @@ pub struct LocalDb(rusqlite::Connection);
impl LocalDb {
pub const FILENAME: &str = "local.db";
pub const SCHEMA: &str = r#"
CREATE TABLE IF NOT EXISTS "installation"(
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"pkg_name" TEXT NOT NULL,
"pkg_version" TEXT NOT NULL,
"pkg_arch" TEXT NOT NULL,
"pkg_manifest" TEXT NOT NULL,
"install_pkgspec" TEXT NOT NULL,
"install_date" INTEGER NOT NULL,
"update_date" INTEGER NOT NULL,
"installed_size" INTEGER NOT NULL,
"install_flags" TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS "dependency"(
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"pkg_ident_a" TEXT NOT NULL,
"pkg_spec_b" TEXT NOT NULL,
"pkg_ident_b" TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS "concept"(
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"concept_ident" TEXT NOT NULL,
"provider" TEXT NOT NULL
);
"#;
pub const MIGRATIONS: &[MigrationItem] = &[
MigrationItem {
name: "20261122-create-table-package",
sql: r#"
CREATE TABLE "package"(
"pkg_ident" TEXT PRIMARY KEY,
"pkg_manifest" TEXT NOT NULL,
"installed_size" INTEGER NOT NULL,
"install_date" INTEGER NOT NULL
)
"#,
},
MigrationItem {
name: "20261122-create-table-installation",
sql: r#"
CREATE TABLE "installation"(
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"install_pkgspec" TEXT NOT NULL,
"pkg_ident" TEXT NOT NULL,
"install_date" INTEGER NOT NULL,
"update_date" INTEGER NOT NULL,
"install_flags" 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 -==
@@ -145,48 +225,44 @@ CREATE TABLE IF NOT EXISTS "concept"(
pub fn open_rw<P: AsRef<Path>>(path: P) -> rusqlite::Result<Self> {
let conn = rusqlite::Connection::open(path)?;
conn.execute_batch(Self::SCHEMA)?;
crate::common::db::run_migration(&conn, Self::MIGRATIONS)?;
Ok(Self(conn))
}
// ==- Installation management -==
// ==- Local package record management -==
pub fn insert_installation(&mut self, installation: &Installation) -> rusqlite::Result<()> {
let pkg_manifest = serde_json::to_string(&installation.pkg_manifest)
pub fn insert_package(&self, package: &LocalPackage) -> rusqlite::Result<()> {
let pkg_manifest = serde_json::to_string(&package.pkg_manifest)
.map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
self.0
.prepare_cached(
r#"
INSERT INTO "installation"(
"pkg_name", "pkg_version", "pkg_arch", "pkg_manifest",
"install_pkgspec", "install_date", "update_date", "installed_size",
"install_flags"
)
VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
INSERT INTO "package"("pkg_ident", "pkg_manifest", "install_date", "installed_size")
VALUES(?1, ?2, ?3, ?4)
"#,
)?
.execute(params![
installation.pkg_manifest.name,
installation.pkg_manifest.version.to_string(),
installation.pkg_manifest.arch,
package.pkg_ident.to_string(),
pkg_manifest,
installation.install_pkgspec.to_string(),
installation.install_date,
installation.update_date,
installation.installed_size as i64,
installation.install_flags.to_string(),
package.install_date,
package.installed_size as i64,
])?;
Ok(())
}
pub fn select_installation_by_name(
&mut self,
pkg_name: &str,
) -> rusqlite::Result<Vec<Installation>> {
/// Selects a package, unique by package identifier.
pub fn select_package(&self, pkg_ident: &PkgIdent) -> rusqlite::Result<LocalPackage> {
self.0
.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
.0
.prepare_cached(r#"SELECT * FROM "installation" WHERE "pkg_name" = ?1"#)?;
let mapped_rows = stmt.query_map(params![pkg_name], map_installation)?;
.prepare_cached(r#"SELECT * FROM "package" WHERE "pkg_ident" LIKE ?1 || '=%'"#)?;
let mapped_rows = stmt.query_map(params![name], map_package)?;
let mut ret = Vec::with_capacity(16);
for mr in mapped_rows {
ret.push(mr?);
@@ -194,17 +270,92 @@ CREATE TABLE IF NOT EXISTS "concept"(
Ok(ret)
}
pub fn select_installation_by_ident(
&mut self,
pkg_ident: &PkgIdent,
) -> rusqlite::Result<Installation> {
self.0.prepare_cached(r#"
SELECT * FROM "installation" WHERE "pkg_name" = ?1 AND "pkg_version" = ?2 AND "pkg_arch" = ?3
"#)?.query_one(params![pkg_ident.name, pkg_ident.version.to_string(), pkg_ident.arch], map_installation)
/// Iterates over all local package records in the database.
pub fn for_each_package<E: From<rusqlite::Error>>(
&self,
mut f: impl FnMut(LocalPackage) -> Result<(), E>,
) -> Result<(), E> {
let mut stmt = self.0.prepare_cached("SELECT * FROM \"package\"")?;
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>>(
&mut self,
&self,
mut f: impl FnMut(Installation) -> Result<(), E>,
) -> Result<(), E> {
let mut stmt = self.0.prepare_cached("SELECT * FROM \"installation\"")?;
@@ -214,95 +365,77 @@ CREATE TABLE IF NOT EXISTS "concept"(
Ok(())
}
pub fn remove_installation(&mut self, pkg_ident: &PkgIdent) -> rusqlite::Result<bool> {
self
.0
.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])
/// Removes an unique installation record with provided install package spec.
///
/// # Return Value
///
/// 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)
}
// ==- Dependency management -==
pub fn insert_dependency(&mut self, dependency: &DependencyRecord) -> rusqlite::Result<()> {
pub fn insert_dependency(&self, dependency: &DependencyRecord) -> rusqlite::Result<()> {
self.0
.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![
dependency.pkg_ident_a.to_string(),
dependency.pkg_spec_b.to_string(),
dependency.pkg_ident_b.to_string(),
])?;
Ok(())
}
/// Selects all package that the provided package depends on.
pub fn select_dependencies(
&mut self,
&self,
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>> {
let mut all = Vec::with_capacity(32);
let mut stmt = self.0.prepare_cached(&format!(
"SELECT * FROM \"dependency\" WHERE \"{provided}\" == ?1"
))?;
let rows = stmt.query_map(params![data.to_string()], map_dependency)?;
let mut stmt = self
.0
.prepare_cached(r#"SELECT * FROM "dependency" WHERE "pkg_ident_a" == ?1"#)?;
let rows = stmt.query_map(params![pkg_ident_a.to_string()], map_dependency)?;
for row in rows {
all.push(row?);
}
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
.prepare_cached(r#"DELETE FROM "dependency" WHERE "pkg_ident_a" = ?1"#)?
.execute(params![pkg_ident_a.to_string()])
.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 -==
pub fn insert_concept(
&mut self,
&self,
concept_ident: &ConceptIdent,
provider: &PkgIdent,
) -> rusqlite::Result<()> {
@@ -313,7 +446,7 @@ CREATE TABLE IF NOT EXISTS "concept"(
}
pub fn select_concept_by_ident(
&mut self,
&self,
ident: &ConceptIdent,
) -> rusqlite::Result<Vec<(ConceptIdent, PkgIdent)>> {
let mut stmt = self
@@ -327,7 +460,7 @@ CREATE TABLE IF NOT EXISTS "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
.prepare_cached(r#"DELETE FROM "concept" WHERE "provider" = ?1"#)?
.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)]
pub struct Installation {
pub pkg_manifest: PkgManifest,
pub install_pkgspec: PkgSpec,
pub pkg_ident: PkgIdent,
pub install_date: i64,
pub update_date: i64,
pub installed_size: u64,
pub install_flags: InstallFlags,
}
@@ -387,25 +528,32 @@ impl Display for InstallFlags {
}
}
/// A dependency record.
/// A local database dependency record.
#[derive(Debug, Clone)]
pub struct DependencyRecord {
pub pkg_ident_a: PkgIdent,
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> {
Ok(Installation {
pkg_manifest: serde_json::from_str(&row.get::<_, String>("pkg_manifest")?)
.map_err(from_sql_error)?,
install_pkgspec: row
.get::<_, String>("install_pkgspec")?
.parse()
.map_err(from_sql_error)?,
pkg_ident: row.get::<_, String>("pkg_ident")?.parse().unwrap(),
install_date: row.get("install_date")?,
update_date: row.get("update_date")?,
installed_size: row.get::<_, i64>("installed_size")? as _,
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")?
.parse()
.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::{
common::io::Decompress,
link::LinksFile,
@@ -50,7 +52,7 @@ impl Package {
pub fn links(&self) -> Option<LinksFile> {
let path = self.extracted_dir.path().join(LinksFile::FILENAME);
if path.exists() {
Some(LinksFile(path))
Some(LinksFile::new(path))
} else {
None
}
+4
View File
@@ -1,6 +1,9 @@
//! The Packie profile, which is compile-time configuration applied to Packie.
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
/// A Packie profile.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Profile {
/// Directory for storing package bundles, e.g. `/pkg`.
@@ -19,6 +22,7 @@ pub struct Profile {
pub host_arch: String,
}
impl Profile {
/// Returns the built-in [`Profile`] instance.
pub fn builtin() -> Self {
Self {
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;
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> {
// Find the installation to remove
// Find the package to remove
let mut found = self
.search_installation(pkgspec)
.search_local_package(pkgspec)
.map_err(RemoveError::Database)?;
if found.is_empty() {
return Err(RemoveError::NotFound);
@@ -14,13 +19,21 @@ impl super::Packie {
return Err(RemoveError::NotUniquePkgSpec);
}
assert_eq!(found.len(), 1);
let found = found.remove(0);
let pkg_ident = found.pkg_manifest.pkg_ident();
let package = found.remove(0);
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
let dependents = self.local_db.select_dependents(&pkg_ident)?;
if !dependents.is_empty() {
return Err(RemoveError::HasDependents);
for i in &installations {
let dependents = self.local_db.select_dependents(&i.install_pkgspec)?;
if !dependents.is_empty() {
return Err(RemoveError::HasDependents);
}
}
// Run configure scripts
@@ -39,7 +52,7 @@ impl super::Packie {
_ = std::fs::remove_dir_all(&self.local_data.pkg_configure_scripts_dir(&pkg_ident));
// 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() {
for link in links {
let Ok(link) = link else {
@@ -54,8 +67,13 @@ impl super::Packie {
std::fs::remove_dir_all(&bundle_dir).map_err(RemoveError::RemoveFiles)?;
// Remove database records
for i in &installations {
self.local_db
.remove_installation(&i.install_pkgspec)
.map_err(RemoveError::Database)?;
}
self.local_db
.remove_installation(&pkg_ident)
.remove_package(&pkg_ident)
.map_err(RemoveError::Database)?;
self.local_db
.remove_concept_provided_by(&pkg_ident)
+29 -18
View File
@@ -8,6 +8,7 @@ pub use serve::RepoServeDir;
use crate::{
Packie,
common::db::MigrationItem,
package::{ConceptIdent, PkgIdent, PkgManifest, PkgSpec},
};
use download::Download;
@@ -94,27 +95,37 @@ pub struct RepoDb {
impl RepoDb {
const FILENAME: &str = "repo.db";
const SCHEMA: &str = r#"
CREATE TABLE IF NOT EXISTS "package"(
"pkg_name" TEXT NOT NULL,
"pkg_version" TEXT NOT NULL,
"pkg_arch" TEXT NOT NULL,
"pkg_manifest" TEXT NOT NULL,
"download_size" INTEGER NOT NULL,
"installed_size" INTEGER NOT NULL,
"checksum" TEXT NOT NULL,
PRIMARY KEY ("pkg_name", "pkg_version", "pkg_arch")
);
CREATE TABLE IF NOT EXISTS "concept"(
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"concept_ident" TEXT NOT NULL,
"provider" TEXT NOT NULL
);
"#;
const MIGRATIONS: &[MigrationItem] = &[
MigrationItem {
name: "20261122-create-table-package",
sql: r#"
CREATE TABLE IF NOT EXISTS "package"(
"pkg_name" TEXT NOT NULL,
"pkg_version" TEXT NOT NULL,
"pkg_arch" TEXT NOT NULL,
"pkg_manifest" TEXT NOT NULL,
"download_size" INTEGER NOT NULL,
"installed_size" INTEGER NOT NULL,
"checksum" TEXT NOT NULL,
PRIMARY KEY ("pkg_name", "pkg_version", "pkg_arch")
)
"#,
},
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> {
let conn = rusqlite::Connection::open(path)?;
conn.execute_batch(Self::SCHEMA)?;
crate::common::db::run_migration(&conn, Self::MIGRATIONS)?;
Ok(Self {
repo_name: None,
conn,
+5 -1
View File
@@ -1,8 +1,9 @@
//! Parsing and matching of software versions.
use std::{cmp::Ordering, fmt::Display, str::FromStr};
use rust_i18n::t;
use std::{cmp::Ordering, fmt::Display, str::FromStr};
/// A parsed package version.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Version {
/// 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);
impl Version {}
/// Prerelease part of a version.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Prerelease {
pub tag: String,
@@ -126,6 +128,7 @@ impl Display for Prerelease {
}
}
/// Filter that matches versions.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum VersionFilter {
/// The '*' filter, matching any versions.
@@ -151,6 +154,7 @@ pub enum VersionFilter {
WithMeta(String),
}
impl VersionFilter {
/// Returns `true` if the version is covered by this filter.
pub fn matches(&self, version: &Version) -> bool {
match self {
Self::Any => true,