feat: optimize abstracts

Signed-off-by: sisungo <[email protected]>
This commit is contained in:
sisungo committed 2026-10-27 03:16:09 +00:00
1 parent f4b6133614
commit a68d98af30
14 files changed
+239 -121

No files matched your search

+32 -14
View File
@@ -12,21 +12,39 @@ gzip = ["dep:flate2"]
members = ["cli"] members = ["cli"]
[dependencies] [dependencies]
const-hex = "1"
digest = "0.11" # Handling package files (core functions)
flate2 = { version = "1", optional = true }
rustc-hash = "2"
rust-i18n = "4"
rusqlite = { version = "0.40", features = ["bundled"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha3 = "0.12"
tar = "0.4" tar = "0.4"
tempfile = "3" tempfile = "3"
thiserror = "2"
toml = "1" # Remote repository support
itertools = "0.15"
ureq = { version = "3", features = ["socks-proxy"] }
url = { version = "2", features = ["serde"] } url = { version = "2", features = ["serde"] }
nix = { version = "0.31", features = ["fs"] } ureq = { version = "3", features = ["socks-proxy"] }
# Graph algorithms
itertools = "0.15"
# Security
digest = "0.11"
const-hex = "1"
sha3 = "0.12"
# File formats
serde = { version = "1", features = ["derive"] }
serde_json = "1"
toml = "1"
rusqlite = { version = "0.41" }
# Error handling
thiserror = "2"
# Optional features
flate2 = { version = "1", optional = true }
zstd = { version = "0.14", optional = true } zstd = { version = "0.14", optional = true }
# Performance optimizations
rustc-hash = "2"
# Misc
rust-i18n = "4"
nix = { version = "0.31", features = ["fs"] }
+8
View File
@@ -2,6 +2,14 @@
## Building Packie ## Building Packie
### Feature Flags
We have these feature flags that are enabled by default. Generally, you should not disable them, or compatibility
with existing package files might be broken:
- `zstd`: Support of Zstandard-compressed package files
- `gzip`: Support of Gzip-compressed package files
### Environment Variables ### Environment Variables
These environment variables affect building of Packie: These environment variables affect building of Packie:
+4
View File
@@ -1,3 +1,7 @@
# Packie # Packie
Packie is the SemiOS package manager. Packie is the SemiOS package manager.
# Build & Install
Refer to [INSTALL.md](INSTALL.md) for details of building the package manager.
+3
View File
@@ -129,6 +129,9 @@ fn print_info(info: &ComprehensivePackageInfo) {
info.pkg_manifest.description info.pkg_manifest.description
); );
} }
if let Some(license) = &info.pkg_manifest.license {
println!(" {}: {}", t!("info.print_info.license"), license);
}
if !info.pkg_manifest.maintainers.is_empty() { if !info.pkg_manifest.maintainers.is_empty() {
println!(" {}:", t!("info.print_info.maintainers")); println!(" {}:", t!("info.print_info.maintainers"));
for i in info.pkg_manifest.maintainers.iter() { for i in info.pkg_manifest.maintainers.iter() {
+28 -25
View File
@@ -4,37 +4,40 @@ use packie::{PackieBuilder, repo::SyncEvent};
use rust_i18n::t; use rust_i18n::t;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Cli {} pub struct Cli {
repo: Option<String>,
}
pub fn main(cli: Cli) -> Result<(), crate::Error> { pub fn main(cli: Cli) -> Result<(), crate::Error> {
let mut packie = PackieBuilder::new().build()?; let mut packie = PackieBuilder::new().build()?;
let progress_bar = let progress_bar =
ProgressBar::new(0).with_style(crate::common::progress_style_multidownload()); ProgressBar::new(0).with_style(crate::common::progress_style_multidownload());
packie let mut sync_repo = packie.sync_repo().on_event(|ev| match ev {
.sync_repo() SyncEvent::BeginRepo(repo) => {
.on_event(|ev| match ev { progress_bar.set_prefix(repo.clone());
SyncEvent::BeginRepo(repo) => { progress_bar.println(t!("update.begin_repo", repo = repo));
progress_bar.set_prefix(repo.clone()); }
progress_bar.println(t!("update.begin_repo", repo = repo)); SyncEvent::Progress(progress) => {
progress_bar.set_length(progress.total_bytes);
progress_bar.set_position(progress.downloaded_bytes);
}
SyncEvent::Error(repo, url, err) => match (repo, url) {
(Some(repo), Some(url)) => {
progress_bar.println(format!(
"failed to update repository \"{repo}\" from \"{url}\": {err}"
));
} }
SyncEvent::Progress(progress) => { (Some(repo), None) => {
progress_bar.set_length(progress.total_bytes); progress_bar.println(format!("failed to update repository \"{repo}\": {err}"));
progress_bar.set_position(progress.downloaded_bytes);
} }
SyncEvent::Error(repo, url, err) => match (repo, url) { _ => {
(Some(repo), Some(url)) => { progress_bar.println(format!("failed to update repositories: {err}"));
progress_bar.println(format!( }
"failed to update repository \"{repo}\" from \"{url}\": {err}" },
)); });
} if let Some(repo) = cli.repo {
(Some(repo), None) => { sync_repo = sync_repo.repo(repo);
progress_bar.println(format!("failed to update repository \"{repo}\": {err}")); }
} sync_repo.run();
_ => {
progress_bar.println(format!("failed to update repositories: {err}"));
}
},
})
.run();
Ok(()) Ok(())
} }
+2 -2
View File
@@ -15,12 +15,12 @@ pub struct Cli {
#[arg(short, long)] #[arg(short, long)]
yes: bool, yes: bool,
items: Option<Vec<PkgSpec>>, items: Vec<PkgSpec>,
} }
pub fn main(cli: Cli) -> Result<(), crate::Error> { pub fn main(cli: Cli) -> Result<(), crate::Error> {
let mut packie = PackieBuilder::new().build()?; let mut packie = PackieBuilder::new().build()?;
let ops = packie.calculate_upgradation(cli.items.unwrap_or_default())?; let ops = packie.calculate_upgradation(cli.items)?;
if ops.is_empty() { if ops.is_empty() {
eprintln!("{}", t!("upgrade.nothing_to_do")); eprintln!("{}", t!("upgrade.nothing_to_do"));
+4
View File
@@ -103,6 +103,10 @@ info.print_info.description:
en: "Description" en: "Description"
zh-CN: "描述" zh-CN: "描述"
ja: "説明" ja: "説明"
info.print_info.license:
en: "License"
zh-CN: "许可协议"
ja: "ライセンス"
info.print_info.maintainers: info.print_info.maintainers:
en: "Maintainers" en: "Maintainers"
zh-CN: "维护者" zh-CN: "维护者"
+39 -22
View File
@@ -1,41 +1,58 @@
use digest::{Digest, DynDigest}; use digest::{Digest, DynDigest};
use std::{fs::File, io::Read, path::Path}; use std::{fs::File, io::Read, path::Path};
pub const DEFAULT_HASHER: &str = "sha3-512"; pub trait HashAlgorithm: DynDigest {
fn name(&self) -> &'static str;
}
impl HashAlgorithm for sha3::Sha3_512 {
fn name(&self) -> &'static str {
"sha3-512"
}
}
pub fn find_hasher(s: &str) -> std::io::Result<Box<dyn DynDigest>> { pub trait HashAlgorithmExt {
fn hash_reader<R: Read>(self, rdr: &mut R) -> std::io::Result<String>;
fn hash_file(self, path: impl AsRef<Path>) -> std::io::Result<String>;
}
impl HashAlgorithmExt for Box<dyn HashAlgorithm> {
fn hash_reader<R: Read>(mut self, rdr: &mut R) -> std::io::Result<String> {
let mut buf = vec![0u8; 4096];
loop {
let n = rdr.read(&mut buf)?;
self.update(&buf[..n]);
if n == 0 {
break;
}
}
Ok(format!(
"{}:{}",
self.name(),
const_hex::encode(self.finalize()),
))
}
fn hash_file(self, path: impl AsRef<Path>) -> std::io::Result<String> {
self.hash_reader(&mut File::open(path)?)
}
}
pub fn algorithm(s: &str) -> std::io::Result<Box<dyn HashAlgorithm>> {
match s { match s {
"sha3-512" => Ok(Box::new(sha3::Sha3_512::new())), "sha3-512" => Ok(Box::new(sha3::Sha3_512::new())),
_ => Err(std::io::ErrorKind::InvalidInput.into()), _ => Err(std::io::ErrorKind::InvalidInput.into()),
} }
} }
pub fn hash_reader<R: Read>(hasher_name: &str, reader: &mut R) -> std::io::Result<String> { pub fn default_algorithm() -> Box<dyn HashAlgorithm> {
let mut buf = [0u8; 1024]; algorithm("sha3-512").unwrap()
let mut hasher = find_hasher(hasher_name)?;
loop {
let n = reader.read(&mut buf)?;
hasher.update(&buf[..n]);
if n == 0 {
break;
}
}
Ok(format!(
"{hasher_name}:{}",
const_hex::encode(hasher.finalize()),
))
} }
pub fn verify_reader<R: Read>(reader: &mut R, expected: &str) -> std::io::Result<bool> { pub fn verify_reader<R: Read>(reader: &mut R, expected: &str) -> std::io::Result<bool> {
let hasher = expected.split(':').next().unwrap(); let algo = expected.split(':').next().unwrap();
let hash = hash_reader(hasher, reader)?; let hash = algorithm(algo)?.hash_reader(reader)?;
Ok(hash == expected) Ok(hash == expected)
} }
pub fn hash_file<P: AsRef<Path>>(hasher: &str, path: P) -> std::io::Result<String> {
hash_reader(hasher, &mut File::open(path)?)
}
pub fn verify_file<P: AsRef<Path>>(path: P, expected: &str) -> std::io::Result<bool> { pub fn verify_file<P: AsRef<Path>>(path: P, expected: &str) -> std::io::Result<bool> {
verify_reader(&mut File::open(path)?, expected) verify_reader(&mut File::open(path)?, expected)
} }
+44
View File
@@ -0,0 +1,44 @@
use std::io::{Read, Seek, SeekFrom};
pub enum Decompress<R> {
#[cfg(feature = "zstd")]
Zstd(zstd::Decoder<'static, std::io::BufReader<R>>),
#[cfg(feature = "gzip")]
Gzip(flate2::read::GzDecoder<R>),
}
impl<R: Read + Seek + 'static> Decompress<R> {
pub fn new(mut _rdr: R) -> std::io::Result<Self> {
#[cfg(feature = "zstd")]
if stream_starts_with(&mut _rdr, &[0x28, 0xb5, 0x2f, 0xfd])? {
return Ok(Self::Zstd(zstd::Decoder::new(_rdr)?));
}
#[cfg(feature = "gzip")]
if stream_starts_with(&mut _rdr, &[0x1F, 0x8B])? {
return Ok(Self::Gzip(flate2::read::GzDecoder::new(_rdr)));
}
Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Unknown compression algorithm",
))
}
}
impl<R: Read> Read for Decompress<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
match self {
#[cfg(feature = "zstd")]
Self::Zstd(d) => d.read(buf),
#[cfg(feature = "gzip")]
Self::Gzip(d) => d.read(buf),
}
}
}
fn stream_starts_with(stream: &mut (impl Read + Seek), magic: &[u8]) -> std::io::Result<bool> {
let mut magic_buf = vec![0u8; magic.len()];
stream.read_exact(&mut magic_buf)?;
stream.seek(SeekFrom::Start(0))?;
Ok(magic_buf == magic)
}
+3 -36
View File
@@ -1,46 +1,13 @@
pub mod checksum; pub mod checksum;
pub mod fs; pub mod fs;
pub mod io;
pub mod macros; pub mod macros;
pub use fs::*; pub use fs::*;
use std::{
io::{Read, Seek, SeekFrom},
time::SystemTime,
};
pub fn decompress(
mut raw: impl Read + Seek + Send + Sync + 'static,
) -> std::io::Result<Box<dyn Read + Send + Sync>> {
#[cfg(feature = "zstd")]
if stream_starts_with(&mut raw, &[0x28, 0xb5, 0x2f, 0xfd])? {
return Ok(Box::new(zstd::Decoder::new(raw)?));
}
#[cfg(feature = "gzip")]
if stream_starts_with(&mut raw, &[0x1F, 0x8B])? {
return Ok(Box::new(flate2::read::GzDecoder::new(raw)));
}
Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Unknown compression algorithm",
))
}
fn stream_starts_with(
stream: &mut (impl Read + Seek + Send + Sync + 'static),
magic: &[u8],
) -> std::io::Result<bool> {
let mut magic_buf = vec![0u8; magic.len()];
stream.read_exact(&mut magic_buf)?;
stream.seek(SeekFrom::Start(0))?;
Ok(magic_buf == magic)
}
pub fn timestamp_secs() -> i64 { pub fn timestamp_secs() -> i64 {
SystemTime::now() std::time::SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH) .duration_since(std::time::SystemTime::UNIX_EPOCH)
.map(|d| d.as_secs() as i64) .map(|d| d.as_secs() as i64)
.unwrap_or_else(|e| -(e.duration().as_secs() as i64)) .unwrap_or_else(|e| -(e.duration().as_secs() as i64))
} }
+1 -1
View File
@@ -114,7 +114,7 @@ impl super::Packie {
) -> Result<Vec<UpgradationOp>, GraphError> { ) -> Result<Vec<UpgradationOp>, GraphError> {
// Collect all package idents required to upgrade // Collect all package idents required to upgrade
let mut installations = Vec::with_capacity(pkgspecs.len()); let mut installations = Vec::with_capacity(pkgspecs.len());
if installations.is_empty() { if pkgspecs.is_empty() {
self.for_each_installation(|x| Ok::<_, rusqlite::Error>(installations.push(x))) self.for_each_installation(|x| Ok::<_, rusqlite::Error>(installations.push(x)))
.unwrap(); .unwrap();
} else { } else {
+5 -1
View File
@@ -1,4 +1,5 @@
use crate::{ use crate::{
common::io::Decompress,
link::LinksFile, link::LinksFile,
version::{Version, VersionFilter}, version::{Version, VersionFilter},
}; };
@@ -22,7 +23,7 @@ impl Package {
/// Opens a package file. /// Opens a package file.
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, PackageError> { pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, PackageError> {
let open_file = File::open(path.as_ref()).map_err(PackageError::Open)?; let open_file = File::open(path.as_ref()).map_err(PackageError::Open)?;
let decompressed_file = crate::common::decompress(open_file).map_err(PackageError::Open)?; let decompressed_file = Decompress::new(open_file).map_err(PackageError::Open)?;
let mut archive = tar::Archive::new(decompressed_file); let mut archive = tar::Archive::new(decompressed_file);
let extracted_dir = TempDir::new().map_err(PackageError::Open)?; let extracted_dir = TempDir::new().map_err(PackageError::Open)?;
@@ -87,6 +88,9 @@ pub struct PkgManifest {
#[serde(default)] #[serde(default)]
pub description: String, pub description: String,
/// License of the software.
pub license: Option<String>,
/// Package maintainers. /// Package maintainers.
#[serde(default)] #[serde(default)]
pub maintainers: Vec<String>, pub maintainers: Vec<String>,
+64 -18
View File
@@ -5,6 +5,7 @@ use std::{
path::PathBuf, path::PathBuf,
}; };
#[derive(Debug)]
pub struct Download<P> { pub struct Download<P> {
from: String, from: String,
to: PathBuf, to: PathBuf,
@@ -50,16 +51,9 @@ impl<P: FnMut(u64, u64)> Download<P> {
return Ok(()); return Ok(());
} }
let mut temp_file_path = self.to.clone(); let mut file = DownloadingFile::open(&self.to)?;
temp_file_path.add_extension("tmp"); let seek = file.cursor()?;
let mut temp_file = File::options() file.set_expected_checksum(self.checksum_required.clone());
.create(true)
.append(true)
.open(&temp_file_path)
.map_err(DownloadError::Filesystem)?;
let seek = temp_file
.seek(std::io::SeekFrom::Current(0))
.map_err(DownloadError::Filesystem)?;
let mut resp = ureq::get(&self.from) let mut resp = ureq::get(&self.from)
.header(ureq::http::header::RANGE, format!("bytes={seek}-")) .header(ureq::http::header::RANGE, format!("bytes={seek}-"))
@@ -69,7 +63,7 @@ impl<P: FnMut(u64, u64)> Download<P> {
let total = body.content_length().unwrap_or_default() + seek; let total = body.content_length().unwrap_or_default() + seek;
let mut sum = seek; let mut sum = seek;
let mut buf = [0; 1024]; let mut buf = [0; 4096];
let mut body_reader = body.as_reader(); let mut body_reader = body.as_reader();
loop { loop {
@@ -79,27 +73,79 @@ impl<P: FnMut(u64, u64)> Download<P> {
if len == 0 { if len == 0 {
break; break;
} }
temp_file file.write_all(&buf[..len])
.write_all(&buf[..len])
.map_err(DownloadError::Filesystem)?; .map_err(DownloadError::Filesystem)?;
sum += len as u64; sum += len as u64;
(self.on_progress)(sum, total); (self.on_progress)(sum, total);
} }
if let Some(expected) = self.checksum_required.as_ref() { file.finish()?;
let verified =
crate::common::checksum::verify_file(&temp_file_path, expected).unwrap_or_default(); Ok(())
}
}
#[derive(Debug)]
pub struct DownloadingFile {
temp_path: PathBuf,
actual_path: PathBuf,
fd: File,
expected_checksum: Option<String>,
}
impl DownloadingFile {
pub fn open(path: impl Into<PathBuf>) -> Result<Self, DownloadError> {
let actual_path = path.into();
let mut temp_path = actual_path.clone();
temp_path.add_extension("tmp");
let fd = File::options()
.create(true)
.append(true)
.open(&temp_path)
.map_err(DownloadError::Filesystem)?;
Ok(Self {
temp_path,
actual_path,
fd,
expected_checksum: None,
})
}
pub fn cursor(&mut self) -> Result<u64, DownloadError> {
self.fd
.seek(std::io::SeekFrom::Current(0))
.map_err(DownloadError::Filesystem)
}
pub fn set_expected_checksum(&mut self, expected: impl Into<Option<String>>) {
self.expected_checksum = expected.into();
}
pub fn finish(self) -> Result<(), DownloadError> {
drop(self.fd);
if let Some(expected) = self.expected_checksum {
let verified = crate::common::checksum::verify_file(&self.temp_path, &expected)
.unwrap_or_default();
if !verified { if !verified {
_ = std::fs::remove_file(&temp_file_path); _ = std::fs::remove_file(&self.temp_path);
return Err(DownloadError::Checksum); return Err(DownloadError::Checksum);
} }
} }
std::fs::rename(temp_file_path, &self.to).map_err(DownloadError::Filesystem)?; std::fs::rename(self.temp_path, &self.actual_path).map_err(DownloadError::Filesystem)?;
Ok(()) Ok(())
} }
} }
impl Write for DownloadingFile {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.fd.write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
self.fd.flush()
}
}
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum DownloadError { pub enum DownloadError {
+2 -2
View File
@@ -1,5 +1,5 @@
use crate::{ use crate::{
common::checksum::DEFAULT_HASHER, common::checksum::HashAlgorithmExt,
package::{Package, PkgIdent}, package::{Package, PkgIdent},
repo::{RepoDb, RepoPackage, download::Download}, repo::{RepoDb, RepoPackage, download::Download},
}; };
@@ -71,7 +71,7 @@ impl RepoServeDir {
let pkg_manifest = package.manifest()?; let pkg_manifest = package.manifest()?;
let download_size = std::fs::metadata(path)?.len(); let download_size = std::fs::metadata(path)?.len();
let installed_size = package.installed_size()?; let installed_size = package.installed_size()?;
let checksum = crate::common::checksum::hash_file(DEFAULT_HASHER, path)?; let checksum = crate::common::checksum::default_algorithm().hash_file(path)?;
let repo_package = RepoPackage { let repo_package = RepoPackage {
repo_name: None, repo_name: None,