diff --git a/cli/Cargo.toml b/cli/Cargo.toml index 1ff9603..45fd605 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -13,8 +13,8 @@ chrono = "0.4" clap = { version = "4", features = ["derive"] } console = "0.16" nix = { version = "0.31", features = ["sched"] } -itertools = "0.15" packie = { path = "../" } rust-i18n = "4" +tabled = { version = "0.22", features = ["ansi"] } indicatif = "0.18" dialoguer = "0.12" diff --git a/cli/src/common.rs b/cli/src/common.rs index 9b391da..610632e 100644 --- a/cli/src/common.rs +++ b/cli/src/common.rs @@ -1,8 +1,19 @@ +use std::{fmt::Display, path::PathBuf}; + use chrono::{Local, TimeZone}; use console::{Term, style}; -use indicatif::ProgressStyle; -use packie::{Packie, local::Installation, package::PkgSpec}; +use indicatif::{ProgressBar, ProgressStyle}; +use packie::{ + Packie, + local::Installation, + package::{PkgIdent, PkgSpec}, + repo::{DownloadPackageEvent, RepoPackage}, +}; use rust_i18n::t; +use tabled::{ + Table, Tabled, + settings::{Style, Width}, +}; pub fn progress_style_multidownload() -> ProgressStyle { let mut lines = Vec::with_capacity(3); @@ -45,23 +56,51 @@ pub fn yesno(prompt: &str, default: bool) -> bool { ["y", "Y"].contains(&line) || (line.is_empty() && default) } -pub fn print_list(indent: u32, list: impl Iterator>) { - let (_, cols) = Term::stdout().size(); - let mut line_used: usize = 0; - for i in list { - let mut i = i.as_ref().to_string(); - if line_used >= cols as _ { - line_used = 0; - println!(); +#[derive(Debug, Clone)] +pub struct SummaryItem { + pub pkgspec: PkgSpec, + pub pkgident: PkgIdent, + pub operation: &'static str, +} +impl SummaryItem { + pub const INSTALL: &str = "install"; + pub const REMOVE: &str = "remove"; +} + +#[derive(Debug, Tabled)] +struct PrintedSummaryItem { + pkgspec: String, + version: String, + operation: String, + notes: String, +} +impl From 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()) + } + }; + Self { + pkgspec: wrap_color(&value.pkgspec), + version: wrap_color(&value.pkgident.version), + operation: wrap_color(&value.operation), + notes: String::new(), } - if i.contains(' ') { - i = format!("'{i}'"); - } - let to_print = format!("{}{}", " ".repeat(indent as _), i); - print!("{to_print}"); - line_used += to_print.len(); } - println!(); +} + +pub fn print_summary(summary: Vec) { + let data: Vec<_> = summary.into_iter().map(PrintedSummaryItem::from).collect(); + let mut table = Table::new(data); + let term_width = console::Term::stdout().size().1 as usize; + table.with(Width::wrap(term_width)); + table.with(Style::psql()); + println!("{}", table); } pub fn format_size(bytes: u64) -> String { @@ -96,3 +135,34 @@ pub fn search_unique_package( } Ok(found.remove(0)) } + +pub fn download_packages( + 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(); + let progress_bar = + ProgressBar::new(download_size).with_style(crate::common::progress_style_multidownload()); + for (package, file_path) in packages.iter_mut() { + let repo_pkg = pkginfo(package); + let init_pos = progress_bar.position(); + progress_bar.println(format!( + "Downloading \"{}\"...", + repo_pkg.pkg_manifest.pkg_ident() + )); + 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 { + DownloadPackageEvent::Progress(_, sum, _) => { + progress_bar.set_position(init_pos + sum); + } + DownloadPackageEvent::Error(url, err) => { + progress_bar.println(format!("error: failed to download from \"{url}\": {err}")); + } + })?; + *file_path = path; + progress_bar.set_position(init_pos + repo_pkg.download_size); + } + drop(progress_bar); + Ok(()) +} diff --git a/cli/src/install.rs b/cli/src/install.rs index 8e09d15..5bf578d 100644 --- a/cli/src/install.rs +++ b/cli/src/install.rs @@ -1,12 +1,11 @@ -use crate::common::{format_size, print_list, yesno}; +use crate::common::{SummaryItem, format_size, print_summary, yesno}; use clap::Parser; -use console::style; use indicatif::ProgressBar; -use itertools::Itertools; use packie::{ - PackieBuilder, install::InstallOptions, package::PkgSpec, repo::DownloadPackageEvent, + PackieBuilder, graph::CalculateInstallationOptions, install::InstallOptions, package::PkgSpec, }; use rust_i18n::t; +use std::path::PathBuf; #[derive(Debug, Parser)] pub struct Cli { @@ -31,30 +30,36 @@ pub fn main(cli: Cli) -> Result<(), crate::Error> { return Ok(()); } - let mut packages = Vec::with_capacity(cli.items.len() * 4); + let mut items = Vec::with_capacity(cli.items.len()); for i in cli.items { - packages.append(&mut packie.calculate_depgraph(i.parse::()?)?); + items.push(i.parse::()?); } - let packages: Vec<_> = packages - .into_iter() - .unique_by(|x| x.repo_pkg.pkg_manifest.pkg_ident()) - .collect(); + let mut packages: Vec<(_, PathBuf)> = packie + .calculate_installation(&items, &CalculateInstallationOptions::new())? + .into_iter() + .map(|x| (x, PathBuf::new())) + .collect(); if packages.is_empty() { eprintln!("{}", t!("install.no_package_to_install")); return Ok(()); } - let download_size: u64 = packages.iter().map(|x| x.repo_pkg.download_size).sum(); - let installed_size: u64 = packages.iter().map(|x| x.repo_pkg.installed_size).sum(); + 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")); - print_list( - 4, - packages - .iter() - .map(|x| style(&x.pkgspec).green().to_string()), - ); + println!(); + print_summary(summary); + println!(); println!( "{}", t!("install.download_size", size = format_size(download_size)) @@ -70,35 +75,17 @@ pub fn main(cli: Cli) -> Result<(), crate::Error> { return Ok(()); } - let progress_bar = - ProgressBar::new(download_size).with_style(crate::common::progress_style_multidownload()); - let mut package_files = Vec::with_capacity(packages.len()); - for package in packages.iter() { - let init_pos = progress_bar.position(); - progress_bar.println(format!("Downloading \"{}\"...", package.pkgspec)); - progress_bar.set_prefix(package.repo_pkg.pkg_manifest.pkg_ident().to_string()); - let path = packie.download_package( - &package.repo_name, - &package.repo_pkg.pkg_manifest.pkg_ident(), - |ev| match ev { - DownloadPackageEvent::Progress(_, sum, _) => { - progress_bar.set_position(init_pos + sum); - } - DownloadPackageEvent::Error(url, err) => { - progress_bar - .println(format!("error: failed to download from \"{url}\": {err}")); - } - }, - )?; - package_files.push(path); - progress_bar.set_position(init_pos + package.repo_pkg.download_size); - } - drop(progress_bar); + crate::common::download_packages(&mut packie, &mut packages, |x| &x.repo_pkg)?; + + let progress_bar = ProgressBar::new(packages.len() as _); + for (package, file_path) in packages { + progress_bar.println(format!("Installing \"{}\"...", package.install_pkgspec)); + + 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)?; - let progress_bar = ProgressBar::new(package_files.len() as _); - for package in package_files.iter() { - progress_bar.println(format!("Installing \"{}\"...", package.display())); - packie.install_package_file(package, &InstallOptions::default())?; progress_bar.inc(1); } diff --git a/cli/src/main.rs b/cli/src/main.rs index 6f536ca..1866d9e 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -9,6 +9,7 @@ mod remove; mod repo_admin; mod select; mod update; +mod upgrade; use clap::Parser; use console::style; @@ -40,6 +41,9 @@ enum Subcommand { /// Install one or more packages Install(install::Cli), + /// Upgrade installed packages + Upgrade(upgrade::Cli), + /// Print configuration information Print(print::Cli), @@ -78,6 +82,7 @@ fn main() { Subcommand::Info(cli) => info::main(cli), Subcommand::InitDb(cli) => initdb::main(cli), Subcommand::Install(cli) => install::main(cli), + Subcommand::Upgrade(cli) => upgrade::main(cli), Subcommand::Print(cli) => print::main(cli), Subcommand::Remove(cli) => remove::main(cli), Subcommand::RepoAdmin(cli) => repo_admin::main(cli), diff --git a/cli/src/remove.rs b/cli/src/remove.rs index 0b6b1e2..0357a52 100644 --- a/cli/src/remove.rs +++ b/cli/src/remove.rs @@ -1,7 +1,6 @@ -use crate::common::{print_list, search_unique_package, yesno}; +use crate::common::{SummaryItem, print_summary, search_unique_package, yesno}; use anyhow::anyhow; use clap::Parser; -use console::style; use packie::{PackieBuilder, package::PkgSpec}; use rust_i18n::t; @@ -19,13 +18,19 @@ pub fn main(cli: Cli) -> Result<(), crate::Error> { for pkgspec in cli.items { packages.push(search_unique_package(&mut packie, &pkgspec)?); } + + let summary = packages + .iter() + .map(|x| SummaryItem { + pkgspec: x.install_pkgspec.clone(), + pkgident: x.pkg_manifest.pkg_ident(), + operation: SummaryItem::REMOVE, + }) + .collect(); println!("{}", t!("remove.prompt_to_remove")); - print_list( - 4, - packages - .iter() - .map(|x| style(&x.install_pkgspec).green().to_string()), - ); + println!(); + print_summary(summary); + println!(); if cli.yes { println!("y"); } else if !yesno(&t!("remove.confirm_removal"), false) { diff --git a/cli/src/upgrade.rs b/cli/src/upgrade.rs new file mode 100644 index 0000000..b1e4c35 --- /dev/null +++ b/cli/src/upgrade.rs @@ -0,0 +1,99 @@ +use crate::common::{SummaryItem, format_size, print_summary, yesno}; +use clap::Parser; +use indicatif::ProgressBar; +use packie::{PackieBuilder, install::InstallOptions, package::PkgSpec}; +use rust_i18n::t; +use std::path::PathBuf; + +#[derive(Debug, Parser)] +pub struct Cli { + /// Don't require manual confirmation + #[arg(short, long)] + yes: bool, + + items: Option>, +} + +pub fn main(cli: Cli) -> Result<(), crate::Error> { + let mut packie = PackieBuilder::new().build()?; + let upgradation_summary = packie.calculate_upgradation(cli.items.unwrap_or_default())?; + + if upgradation_summary.is_empty() { + eprintln!("{}", t!("upgrade.nothing_to_do")); + return Ok(()); + } + + println!("{}", t!("upgrade.prompt_to_upgrade")); + println!(); + let mut ui_summary = Vec::new(); + for install in &upgradation_summary.installs { + ui_summary.push(SummaryItem { + pkgspec: install.install_pkgspec.clone(), + pkgident: install.repo_pkg.pkg_manifest.pkg_ident(), + operation: SummaryItem::INSTALL, + }); + } + for remove in &upgradation_summary.removes { + let pkgspec = PkgSpec { + name: remove.name.clone(), + version: packie::version::VersionFilter::Any, + arch: None, + }; + ui_summary.push(SummaryItem { + pkgspec, + pkgident: remove.clone(), + operation: SummaryItem::REMOVE, + }); + } + print_summary(ui_summary); + println!(); + + let mut installs: Vec<_> = upgradation_summary + .installs + .into_iter() + .map(|x| (x, PathBuf::new())) + .collect(); + let removes = upgradation_summary.removes; + + let download_size = installs.iter().map(|(x, _)| x.repo_pkg.download_size).sum(); + let installed_size = installs + .iter() + .map(|(x, _)| x.repo_pkg.installed_size) + .sum(); + println!( + "{}", + t!("upgrade.download_size", size = format_size(download_size)) + ); + println!( + "{}", + t!("upgrade.installed_size", size = format_size(installed_size)) + ); + + if cli.yes { + eprintln!("y"); + } else if !yesno(&t!("upgrade.confirm_upgradation"), true) { + eprintln!("{}", t!("upgrade.aborting")); + return Ok(()); + } + + crate::common::download_packages(&mut packie, &mut installs, |x| &x.repo_pkg)?; + + let progress_bar = ProgressBar::new(installs.len() as u64 + removes.len() as u64); + for removal in removes { + progress_bar.println(format!("Removing \"{removal}\"...")); + packie.remove(&removal.into())?; + progress_bar.inc(1); + } + for (package, file_path) in installs { + progress_bar.println(format!("Installing \"{}\"...", package.install_pkgspec)); + + 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)?; + + progress_bar.inc(1); + } + + Ok(()) +} diff --git a/locales/libpackie/main.yml b/locales/libpackie/main.yml index 3666055..d95d610 100644 --- a/locales/libpackie/main.yml +++ b/locales/libpackie/main.yml @@ -7,10 +7,6 @@ install.InstallError.Database: en: "local database error: %{error}" zh-CN: "本地数据库错误:%{error}" ja: "ローカルデータベースエラー:%{error}" -install.InstallError.NotFound: - en: "item not found: %{item}" - zh-CN: "找不到项目:%{item}" - ja: "項目が見つかりません:%{item}" install.InstallError.DependencyRing: en: "dependency ring detected" zh-CN: "检测到依赖环" @@ -55,6 +51,10 @@ repo.download.DownloadError.Checksum: en: "checksum failed" zh-CN: "文件完整性检查失败" ja: "チェックサム検証に失敗しました" +graph.GraphError.NotFound: + en: "item not found: %{item}" + zh-CN: "找不到项目:%{item}" + ja: "項目が見つかりません:%{item}" BuildPackieError.Lock: en: "failed to lock packie database: %{error}" zh-CN: "无法锁定 Packie 数据库:%{error}" diff --git a/locales/packie-cli/main.yml b/locales/packie-cli/main.yml index 3588aba..8850990 100644 --- a/locales/packie-cli/main.yml +++ b/locales/packie-cli/main.yml @@ -35,6 +35,30 @@ install.no_package_to_install: en: "No packages to install." zh-CN: "没有要安装的包。" ja: "インストールするパッケージがありません。" +upgrade.prompt_to_upgrade: + en: "The following packages are to be changed during upgradation:" + zh-CN: "在更新过程中,将对下列包进行更改:" + ja: "アップグレード中に以下のパッケージが変更されます:" +upgrade.download_size: + en: "Download size: %{size}" + zh-CN: "下载体积:%{size}" + ja: "ダウンロードサイズ:%{size}" +upgrade.installed_size: + en: "Installed size: %{size}" + zh-CN: "安装体积:%{size}" + ja: "インストール後サイズ:%{size}" +upgrade.confirm_upgradation: + en: "Confirm to continue?" + zh-CN: "确认继续?" + ja: "続行してもよろしいですか?" +upgrade.aborting: + en: "Aborting." + zh-CN: "中止。" + ja: "中止します。" +upgrade.nothing_to_do: + en: "Nothing to do today." + zh-CN: "今日无事可做。" + ja: "本日は行うことがありません。" info.no_package_found: en: "The specified package was not found." zh-CN: "找不到指定的包。" diff --git a/src/configure.rs b/src/configure.rs index b095832..b5fd32b 100644 --- a/src/configure.rs +++ b/src/configure.rs @@ -22,12 +22,17 @@ impl super::Packie { return Ok(()); } let dirpath = self.local_data.pkg_configure_scripts_dir(pkg); + let mut items = Vec::new(); for i in std::fs::read_dir(dirpath) .into_iter() .flatten() .filter_map(Result::ok) { - run_script(i.path(), &options)?; + items.push(i.file_name().to_string_lossy().into()); + } + items.sort_unstable(); + for item in items { + self.run_configure(pkg, Some(item), &options)?; } Ok(()) } diff --git a/src/graph.rs b/src/graph.rs new file mode 100644 index 0000000..5642e9f --- /dev/null +++ b/src/graph.rs @@ -0,0 +1,224 @@ +use crate::{ + package::{PkgIdent, PkgSpec}, + repo::RepoPackage, +}; +use itertools::Itertools; +use rust_i18n::t; + +impl super::Packie { + pub fn calculate_installation( + &mut self, + pkgs: &[PkgSpec], + options: &CalculateInstallationOptions, + ) -> Result, GraphError> { + let mut all = Vec::with_capacity(pkgs.len() * 4); + + for pkg in pkgs { + let mut current = self._calculate_installation(pkg, options)?; + all.append(&mut current); + } + + 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(); + + 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(); + } + } + + Ok(all) + } + + fn _calculate_installation( + &mut self, + desired: &PkgSpec, + options: &CalculateInstallationOptions, + ) -> Result, GraphError> { + let prior_arch = self.profile.host_arch.clone(); + + let mut query = self.query_repo(); + + let mut depgraph = Vec::new(); + let mut stack = vec![desired.clone()]; + + loop { + let Some(pkgspec) = stack.pop() else { + break; + }; + let mut found = query.search_package(&pkgspec); + if found.is_empty() { + return Err(GraphError::NotFound(pkgspec.to_string())); + } + let prior_pkg = prior_pkg( + found.iter().map(|x| x.pkg_manifest.pkg_ident()), + &prior_arch, + ); + let prior_pkg = found + .iter() + .enumerate() + .find(|(_, p)| p.pkg_manifest.pkg_ident() == prior_pkg) + .unwrap() + .0; + let repo_pkg = found.remove(prior_pkg); + + let already_installed = !self + .search_installation(&pkgspec) + .unwrap_or_default() + .is_empty(); + if already_installed && !(&pkgspec == desired && options.no_existence_check) { + 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()); + } + + if !options.skip_recommendations { + for recommended in &repo_pkg.pkg_manifest.recommendations { + stack.push(recommended.clone()); + } + } + } + + depgraph.reverse(); + Ok(depgraph) + } + + pub fn calculate_upgradation( + &mut self, + pkgs: Vec, + ) -> Result { + let mut installations = Vec::new(); + if pkgs.is_empty() { + self.for_each_installation(|x| Ok::<_, rusqlite::Error>(installations.push(x))) + .unwrap(); + } else { + for pkg in pkgs { + let mut searched = self.search_installation(&pkg).unwrap_or_default(); + installations.append(&mut searched); + } + } + + let mut removes = Vec::new(); + let mut installs = Vec::new(); + + for pkg in installations { + let mut summary = self._calculate_upgradation(&pkg.pkg_manifest.pkg_ident())?; + removes.append(&mut summary.removes); + installs.append(&mut summary.installs); + } + + let removes = removes.into_iter().unique().collect(); + let installs = installs + .into_iter() + .unique_by(|x| x.repo_pkg.pkg_manifest.pkg_ident()) + .collect(); + + Ok(UpgradationSummary { removes, installs }) + } + + fn _calculate_upgradation(&mut self, pkg: &PkgIdent) -> Result { + let installed = self + .local_db + .select_installation_by_ident(pkg) + .map_err(|_| GraphError::NotFound(pkg.to_string()))?; + let depgraph = self._calculate_installation( + &installed.install_pkgspec, + &CalculateInstallationOptions { + skip_recommendations: false, + no_existence_check: true, + }, + ); + let Ok(depgraph) = depgraph else { + return Ok(UpgradationSummary::empty()); + }; + if depgraph.last().map(|x| x.repo_pkg.pkg_manifest.pkg_ident()) == Some(pkg.clone()) { + return Ok(UpgradationSummary::empty()); + } + Ok(UpgradationSummary { + removes: vec![pkg.clone()], + installs: depgraph, + }) + } +} + +#[derive(Debug, thiserror::Error)] +pub enum GraphError { + #[error("{}", t!("graph.GraphError.NotFound", item = .0))] + NotFound(String), +} + +#[derive(Debug, Default, Clone)] +pub struct CalculateInstallationOptions { + /// True if we don't need to collect recommendations. + skip_recommendations: bool, + + /// True if we don't need to check if the package is already installed. This is used for checking for updates. + no_existence_check: bool, +} +impl CalculateInstallationOptions { + pub fn new() -> Self { + Self::default() + } +} + +#[derive(Debug, Clone)] +pub struct InstallationNode { + pub repo_pkg: RepoPackage, + pub install_pkgspec: PkgSpec, + pub auto_installed: bool, +} + +#[derive(Debug, Clone)] +pub struct UpgradationSummary { + pub removes: Vec, + pub installs: Vec, +} +impl UpgradationSummary { + pub fn empty() -> Self { + Self { + removes: vec![], + installs: vec![], + } + } + + pub fn is_empty(&self) -> bool { + self.removes.is_empty() && self.installs.is_empty() + } +} + +/// Gets prior package that is installed by default in package candidates. +fn prior_pkg(all: impl Iterator, prior_arch: &str) -> PkgIdent { + let mut all = all.collect::>(); + all.sort_by(|x, y| x.version.cmp(&y.version)); + all.reverse(); + for i in &all { + if i.arch == prior_arch { + return i.clone(); + } + } + all.remove(0) +} diff --git a/src/install.rs b/src/install.rs index 38fe6a4..5b0b025 100644 --- a/src/install.rs +++ b/src/install.rs @@ -2,7 +2,7 @@ use crate::{ configure::ConfigureOptions, local::{InstallFlags, Installation}, package::{Package, PackageError, PkgIdent, PkgSpec}, - repo::{RepoError, RepoPackage}, + repo::RepoError, }; use rust_i18n::t; use std::path::Path; @@ -14,12 +14,16 @@ pub struct InstallOptions { /// Whether we should run configure scripts in interactive mode. pub interactive_configure: bool, + + /// Whether this package is auto-installed. + pub auto_installed: bool, } impl InstallOptions { pub fn new() -> Self { Self { install_pkgspec: None, interactive_configure: true, + auto_installed: false, } } } @@ -30,60 +34,6 @@ impl Default for InstallOptions { } impl super::Packie { - pub fn calculate_depgraph( - &mut self, - pkgspec: PkgSpec, - ) -> Result, InstallError> { - let prior_arch = self.profile.host_arch.clone(); - - let mut query = self.query_repo(); - - let mut depgraph = Vec::new(); - let mut stack = vec![pkgspec]; - - loop { - let Some(pkgspec) = stack.pop() else { - break; - }; - let mut found = query.search_package(&pkgspec); - if found.is_empty() { - return Err(InstallError::NotFound(pkgspec.to_string())); - } - let prior_pkg = prior_pkg( - found.iter().map(|(_, x)| x.pkg_manifest.pkg_ident()), - &prior_arch, - ); - let prior_pkg = found - .iter() - .enumerate() - .find(|(_, (_, p))| p.pkg_manifest.pkg_ident() == prior_pkg) - .unwrap() - .0; - let (repo_name, repo_pkg) = found.remove(prior_pkg); - - if !self - .search_installation(&pkgspec) - .unwrap_or_default() - .is_empty() - { - continue; - } - - depgraph.push(DepgraphNode { - repo_name, - pkgspec, - repo_pkg: repo_pkg.clone(), - }); - - for dep in &repo_pkg.pkg_manifest.dependencies { - stack.push(dep.clone()); - } - } - - depgraph.reverse(); - Ok(depgraph) - } - /// Installs a package, from a local package file. pub fn install_package_file>( &mut self, @@ -127,13 +77,17 @@ impl super::Packie { 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 { pkg_manifest: pkg_manifest.clone(), install_pkgspec, install_date: crate::common::timestamp_secs(), update_date: crate::common::timestamp_secs(), installed_size, - install_flags: InstallFlags::default(), + install_flags, }; self.local_db.insert_installation(&installation)?; @@ -191,9 +145,6 @@ impl super::Packie { #[derive(Debug, thiserror::Error)] pub enum InstallError { - #[error("{}", t!("install.InstallError.NotFound", item = .0))] - NotFound(String), - #[error("{}", t!("install.InstallError.DependencyRing"))] DependencyRing, @@ -233,23 +184,3 @@ fn default_install_pkgspec(pkg_ident: PkgIdent) -> PkgSpec { arch: None, } } - -#[derive(Debug, Clone)] -pub struct DepgraphNode { - pub repo_name: String, - pub pkgspec: PkgSpec, - pub repo_pkg: RepoPackage, -} - -/// Gets prior package that is installed by default in package candidates. -fn prior_pkg(all: impl Iterator, prior_arch: &str) -> PkgIdent { - let mut all = all.collect::>(); - all.sort_by(|x, y| x.version.cmp(&y.version)); - all.reverse(); - for i in &all { - if i.arch == prior_arch { - return i.clone(); - } - } - all.remove(0) -} diff --git a/src/lib.rs b/src/lib.rs index 5ef0973..33ff533 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ mod common; pub mod config; pub mod configure; +pub mod graph; pub mod install; pub mod link; pub mod local; diff --git a/src/local.rs b/src/local.rs index 3aba9d4..9b0b662 100644 --- a/src/local.rs +++ b/src/local.rs @@ -268,6 +268,13 @@ impl InstallFlags { pub fn contains(&self, s: &str) -> bool { self.0.iter().any(|x| x == s) } + + pub fn set(&mut self, s: &str) { + if self.contains(s) { + return; + } + self.0.push(s.into()); + } } impl FromStr for InstallFlags { type Err = Infallible; diff --git a/src/package.rs b/src/package.rs index 0204e70..4cb8c5c 100644 --- a/src/package.rs +++ b/src/package.rs @@ -123,7 +123,7 @@ impl PkgManifest { const PKGNAME_FORBIDDEN_CHARS: &str = "~!@#$%^&*()={}[]\\|:;'\"<>,/?\r\n "; /// A package specifier. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct PkgSpec { pub name: String, pub version: VersionFilter, diff --git a/src/repo/mod.rs b/src/repo/mod.rs index 283ebe6..e3aa9d3 100644 --- a/src/repo/mod.rs +++ b/src/repo/mod.rs @@ -15,8 +15,10 @@ use itertools::Itertools; use rusqlite::{OpenFlags, Row, params}; use rust_i18n::t; use rustc_hash::FxHashMap; -use serde::{Deserialize, Serialize}; -use std::path::{Path, PathBuf}; +use std::{ + path::{Path, PathBuf}, + str::FromStr, +}; use url::Url; impl super::Packie { @@ -33,20 +35,23 @@ impl super::Packie { /// Download a package. pub fn download_package( &self, - repo: &str, - pkg_ident: &PkgIdent, + repo_pkg_ident: &RepoPkgIdent, mut on_event: impl FnMut(DownloadPackageEvent), ) -> Result { - let repo_cache_dir = self.cache.repo_dir(repo); + let repo_cache_dir = self.cache.repo_dir(&repo_pkg_ident.repo); - let repo = self.config.repos.get(repo).ok_or(RepoError::NoSuchRepo)?; + let repo = self + .config + .repos + .get(&repo_pkg_ident.repo) + .ok_or(RepoError::NoSuchRepo)?; let repo_db = repo_cache_dir.join(RepoDb::FILENAME); let mut repo_db = RepoDb::open_ro(repo_db).map_err(RepoError::Database)?; let repo_package = repo_db - .select_package_by_ident(pkg_ident) + .select_package_by_ident(&repo_pkg_ident.pkg_ident) .map_err(|_| RepoError::NoSuchPackage)?; - let standard_filename = format!("{pkg_ident}.pkg"); + let standard_filename = format!("{}.pkg", &repo_pkg_ident.pkg_ident); let download_path = repo_cache_dir.join(&standard_filename); @@ -82,7 +87,10 @@ impl super::Packie { } #[derive(Debug)] -pub struct RepoDb(rusqlite::Connection); +pub struct RepoDb { + repo_name: Option, + conn: rusqlite::Connection, +} impl RepoDb { const FILENAME: &str = "repo.db"; @@ -107,27 +115,48 @@ CREATE TABLE IF NOT EXISTS "abspkg"( pub fn open_rw>(path: P) -> rusqlite::Result { let conn = rusqlite::Connection::open(path)?; conn.execute_batch(Self::SCHEMA)?; - Ok(Self(conn)) + Ok(Self { + repo_name: None, + conn, + }) } pub fn open_ro>(path: P) -> rusqlite::Result { - rusqlite::Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY).map(Self) + let conn = rusqlite::Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)?; + Ok(Self { + repo_name: None, + conn, + }) + } + + pub fn set_name(&mut self, name: String) { + self.repo_name = Some(name); } pub fn select_package_by_ident( &mut self, pkg_ident: &PkgIdent, ) -> rusqlite::Result { - self.0.prepare_cached( + let mut stmt = self.conn.prepare_cached( r#"SELECT * FROM "package" 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_repo_package) + )?; + stmt.query_one( + params![ + pkg_ident.name, + pkg_ident.version.to_string(), + pkg_ident.arch + ], + |row| map_repo_package(self.repo_name.clone(), row), + ) } pub fn select_package_by_name(&mut self, pkgname: &str) -> rusqlite::Result> { let mut stmt = self - .0 + .conn .prepare_cached(r#"SELECT * FROM "package" WHERE "pkg_name" = ?1"#)?; - let mapped_rows = stmt.query_map(params![pkgname], map_repo_package)?; + let mapped_rows = stmt.query_map(params![pkgname], |row| { + map_repo_package(self.repo_name.clone(), row) + })?; let mut ret = Vec::with_capacity(16); for mr in mapped_rows { ret.push(mr?); @@ -140,7 +169,7 @@ CREATE TABLE IF NOT EXISTS "abspkg"( ident: &AbsPkgIdent, ) -> rusqlite::Result> { let mut stmt = self - .0 + .conn .prepare_cached(r#"SELECT * FROM "abspkg" WHERE "abspkg_ident" = ?1"#)?; let rows = stmt.query_map(params![ident.to_string()], map_abspkg)?; let mut ret = Vec::with_capacity(16); @@ -154,8 +183,10 @@ CREATE TABLE IF NOT EXISTS "abspkg"( &mut self, mut f: impl FnMut(RepoPackage) -> Result<(), E>, ) -> Result<(), E> { - let mut stmt = self.0.prepare_cached("SELECT * FROM \"package\"")?; - let mapped_rows = stmt.query_map(params![], map_repo_package)?; + let mut stmt = self.conn.prepare_cached("SELECT * FROM \"package\"")?; + let mapped_rows = stmt.query_map(params![], |row| { + map_repo_package(self.repo_name.clone(), row) + })?; for mr in mapped_rows { f(mr?)?; } @@ -165,7 +196,7 @@ CREATE TABLE IF NOT EXISTS "abspkg"( pub fn insert_package(&mut self, package: &RepoPackage) -> rusqlite::Result<()> { let pkg_manifest = serde_json::to_string(&package.pkg_manifest) .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?; - self.0 + self.conn .prepare_cached( r#" INSERT INTO "package"( @@ -188,14 +219,14 @@ CREATE TABLE IF NOT EXISTS "abspkg"( } pub fn insert_abspkg(&mut self, abs: &AbsPkgIdent, real: &PkgIdent) -> rusqlite::Result<()> { - self.0 + self.conn .prepare_cached(r#"INSERT INTO "abspkg"("abspkg_ident", "provider") VALUES(?1, ?2)"#)? .execute(params![abs.to_string(), real.to_string()])?; Ok(()) } pub fn delete_package_by_ident(&mut self, ident: &PkgIdent) -> rusqlite::Result { - self.0 + self.conn .prepare_cached( r#"DELETE FROM "package" WHERE "pkg_name" = ?1 AND "pkg_version" = ?2 AND "pkg_arch" = ?3"#, )? @@ -204,17 +235,37 @@ CREATE TABLE IF NOT EXISTS "abspkg"( } pub fn delete_abspkg_by_provider(&mut self, ident: &PkgIdent) -> rusqlite::Result { - self.0 + self.conn .prepare_cached(r#"DELETE FROM "abspkg" WHERE "provider" = ?1"#)? .execute(params![ident.to_string()]) .map(|x| x > 0) } } -fn map_repo_package(row: &Row) -> rusqlite::Result { +#[derive(Debug, Clone, Hash, PartialEq, Eq)] +pub struct RepoPkgIdent { + pub repo: String, + pub pkg_ident: PkgIdent, +} +impl FromStr for RepoPkgIdent { + type Err = ParseError; + + fn from_str(s: &str) -> Result { + let Some((repo, pkg_ident)) = s.split_once('/') else { + return Err(ParseError::MissingRepo); + }; + Ok(Self { + repo: repo.into(), + pkg_ident: pkg_ident.parse()?, + }) + } +} + +fn map_repo_package(repo_name: Option, row: &Row) -> rusqlite::Result { let pkg_manifest: String = row.get("pkg_manifest")?; let pkg_manifest = serde_json::from_str(&pkg_manifest).map_err(from_sql_error)?; Ok(RepoPackage { + repo_name, pkg_manifest, download_size: row.get::<_, i64>("download_size")? as u64, installed_size: row.get::<_, i64>("installed_size")? as u64, @@ -239,8 +290,11 @@ fn from_sql_error(error: E) -> rus } /// A record representing to a package in a repository. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone)] pub struct RepoPackage { + /// Repository name. + pub repo_name: Option, + /// Package manifest. pub pkg_manifest: PkgManifest, @@ -253,6 +307,14 @@ pub struct RepoPackage { /// Checksum of the package file. pub checksum: String, } +impl RepoPackage { + pub fn repo_pkg_ident(&self) -> Option { + Some(RepoPkgIdent { + repo: self.repo_name.clone()?, + pkg_ident: self.pkg_manifest.pkg_ident(), + }) + } +} /// Session of syncing repositories. pub struct SyncSession<'a, E = fn(SyncEvent)> { @@ -372,20 +434,21 @@ impl QuerySession { let mut repos = FxHashMap::default(); for name in packie.config.repos.keys() { let repo_db = packie.cache.repo_dir(name).join(RepoDb::FILENAME); - let Ok(repo_db) = RepoDb::open_ro(repo_db) else { + let Ok(mut repo_db) = RepoDb::open_ro(repo_db) else { continue; }; + repo_db.set_name(name.clone()); repos.insert(name.into(), repo_db); } Self { repos } } - pub fn search_package(&mut self, pkgspec: &PkgSpec) -> Vec<(String, RepoPackage)> { - let mut all: Vec<(String, RepoPackage)> = Vec::new(); - for (name, db) in self.repos.iter_mut() { + pub fn search_package(&mut self, pkgspec: &PkgSpec) -> Vec { + let mut all = Vec::new(); + for (_, db) in self.repos.iter_mut() { for pkg in db.select_package_by_name(&pkgspec.name).unwrap_or_default() { if pkgspec.matches(&pkg.pkg_manifest.pkg_ident()) { - all.push((name.into(), pkg)); + all.push(pkg); } } let abspkg_ident = AbsPkgIdent { @@ -396,12 +459,10 @@ impl QuerySession { let Ok(real) = db.select_package_by_ident(&provider) else { continue; }; - all.push((name.into(), real)); + all.push(real); } } - all.into_iter() - .unique_by(|(repo, pkg)| (repo.to_string(), pkg.pkg_manifest.pkg_ident())) - .collect() + all.into_iter().unique_by(|x| x.repo_pkg_ident()).collect() } } @@ -422,3 +483,17 @@ pub enum RepoError { #[error("{}", t!("repo.RepoError.AllTriesFailed"))] AllTriesFailed, } + +#[derive(Debug, thiserror::Error)] +pub enum ParseError { + #[error("missing repository name")] + MissingRepo, + + #[error("{0}")] + Pkg(crate::package::ParseError), +} +impl From for ParseError { + fn from(value: crate::package::ParseError) -> Self { + Self::Pkg(value) + } +} diff --git a/src/repo/serve.rs b/src/repo/serve.rs index dd9323e..881e155 100644 --- a/src/repo/serve.rs +++ b/src/repo/serve.rs @@ -74,6 +74,7 @@ impl RepoServeDir { let checksum = crate::common::checksum::hash_file(DEFAULT_HASHER, path)?; let repo_package = RepoPackage { + repo_name: None, pkg_manifest, download_size, installed_size,