Skip to content

Commit

Permalink
refactor(package): reduce hard-coded collections
Browse files Browse the repository at this point in the history
  • Loading branch information
QaidVoid committed Oct 25, 2024
1 parent ee9d3b7 commit 041e824
Show file tree
Hide file tree
Showing 13 changed files with 110 additions and 107 deletions.
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
[package]
name = "soar"
version = "0.2.0"
authors = ["Rabindra Dhakal <[email protected]>"]
description = "A modern package manager for Linux"
license = "MIT"
version = "0.2.0"
edition = "2021"
repository = "https://github.com/QaidVoid/soar"

[profile.release]
strip = true
Expand Down
4 changes: 4 additions & 0 deletions default.nix
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
with import <nixpkgs> {};
mkShell {
nativeBuildInputs = [
rustc
cargo
clippy
rustfmt
rust-analyzer
];
}
16 changes: 8 additions & 8 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,19 @@ pub enum Commands {
packages: Vec<String>,

/// Whether to force install the package
#[arg(required = false)]
#[arg(short, long)]
#[arg(required = false, short, long)]
force: bool,

/// Set portable dir for home & config
#[arg(required = false)]
#[arg(short, long, num_args = 0..=1)]
#[arg(required = false, short, long, num_args = 0..=1)]
portable: Option<Option<String>>,

/// Set portable home
#[arg(required = false)]
#[arg(long, num_args = 0..=1)]
#[arg(required = false, long, num_args = 0..=1)]
portable_home: Option<Option<String>>,

/// Set portable config
#[arg(required = false)]
#[arg(long, num_args = 0..=1)]
#[arg(required = false, long, num_args = 0..=1)]
portable_config: Option<Option<String>>,
},

Expand All @@ -50,6 +46,10 @@ pub enum Commands {
/// Query to search
#[arg(required = true)]
query: String,

/// Case sensitive search
#[arg(required = false, long)]
case_sensitive: bool
},

/// Query package info
Expand Down
10 changes: 5 additions & 5 deletions src/core/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ pub struct Repository {
/// `metadata.json`
pub registry: Option<String>,

/// Paths for different collections
pub paths: HashMap<String, String>,
/// Download Sources for different collections
pub sources: HashMap<String, String>,
}

impl Repository {
Expand Down Expand Up @@ -72,7 +72,7 @@ impl Config {
}

fn generate(config_path: PathBuf) -> Vec<u8> {
let paths = HashMap::from([
let sources = HashMap::from([
("bin".to_owned(), format!("https://bin.ajam.dev/{ARCH}")),
(
"base".to_owned(),
Expand All @@ -85,9 +85,9 @@ impl Config {
soar_path: "$HOME/.soar".to_owned(),
repositories: vec![Repository {
name: "ajam".to_owned(),
url: "https://bin.ajam.dev".to_owned(),
url: "https://bin.ajam.dev/{ARCH}".to_owned(),
registry: Some("METADATA.AIO.json".to_owned()),
paths,
sources,
}],
parallel: Some(true),
parallel_limit: Some(2),
Expand Down
7 changes: 4 additions & 3 deletions src/core/constant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use std::{path::PathBuf, sync::LazyLock};

use super::{config::CONFIG, util::build_path};

pub static CACHE_PATH: LazyLock<PathBuf> =
LazyLock::new(|| build_path(&CONFIG.soar_path).unwrap().join("cache"));
pub static REGISTRY_PATH: LazyLock<PathBuf> =
LazyLock::new(|| build_path(&CONFIG.soar_path).unwrap().join("registry"));
pub static BIN_PATH: LazyLock<PathBuf> =
Expand All @@ -11,9 +13,8 @@ pub static INSTALL_TRACK_PATH: LazyLock<PathBuf> =
pub static PACKAGES_PATH: LazyLock<PathBuf> =
LazyLock::new(|| build_path(&CONFIG.soar_path).unwrap().join("packages"));

pub const APPIMAGE_MAGIC_BYTES: [u8; 16] = [
0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, 0x41, 0x49, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
];
pub const APPIMAGE_MAGIC_OFFSET: u64 = 8;
pub const APPIMAGE_MAGIC_BYTES: [u8; 4] = [0x41, 0x49, 0x02, 0x00];
pub const ELF_MAGIC_BYTES: [u8; 4] = [0x7f, 0x45, 0x4c, 0x46];

pub const CAP_SYS_ADMIN: i32 = 21;
Expand Down
36 changes: 12 additions & 24 deletions src/core/util.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
use std::{
env::{
self,
consts::{ARCH, OS},
},
mem,
env, mem,
path::{Path, PathBuf},
};

Expand All @@ -17,7 +13,7 @@ use tokio::{

use super::{
color::{Color, ColorExt},
constant::{BIN_PATH, INSTALL_TRACK_PATH, PACKAGES_PATH},
constant::{BIN_PATH, CACHE_PATH, INSTALL_TRACK_PATH, PACKAGES_PATH},
};

pub fn home_path() -> String {
Expand Down Expand Up @@ -73,14 +69,6 @@ pub fn build_path(path: &str) -> Result<PathBuf> {
Ok(PathBuf::from(result))
}

/// Retrieves the platform string in the format `ARCH-Os`.
///
/// This function combines the architecture (e.g., `x86_64`) and the operating
/// system (e.g., `Linux`) into a single string to identify the platform.
pub fn get_platform() -> String {
format!("{ARCH}-{}{}", &OS[..1].to_uppercase(), &OS[1..])
}

pub fn format_bytes(bytes: u64) -> String {
let kb = 1024u64;
let mb = kb * 1024;
Expand Down Expand Up @@ -211,19 +199,19 @@ pub async fn download(url: &str, what: &str, silent: bool) -> Result<Vec<u8>> {
}

pub async fn cleanup() -> Result<()> {
let mut cache_dir = home_cache_path();
cache_dir.push_str("/soar");
let cache_dir = build_path(&cache_dir)?;
let mut tree = fs::read_dir(&*CACHE_PATH).await?;

if cache_dir.exists() {
let mut tree = fs::read_dir(&cache_dir).await?;
while let Some(entry) = tree.next_entry().await? {
let path = entry.path();
if xattr::get(&path, "user.managed_by")?.as_deref() != Some(b"soar") {
continue;
};

while let Some(entry) = tree.next_entry().await? {
let path = entry.path();
if xattr::get(&path, "user.managed_by")?.as_deref() != Some(b"soar") {
continue;
};
let modified_at = path.metadata()?.modified()?;
let elapsed = modified_at.elapsed()?.as_secs();
let cache_ttl = 28800u64;

if cache_ttl.saturating_sub(elapsed) == 0 {
fs::remove_file(path).await?;
}
}
Expand Down
7 changes: 4 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ pub async fn init() -> Result<()> {
);
}

let _ = cleanup().await;

match args.command {
Commands::Install {
packages,
Expand Down Expand Up @@ -62,7 +64,6 @@ pub async fn init() -> Result<()> {
.await?;
}
Commands::Sync => {
cleanup().await?;
let mut registry = registry;
registry.fetch().await?;
}
Expand All @@ -75,8 +76,8 @@ pub async fn init() -> Result<()> {
Commands::ListInstalledPackages { packages } => {
registry.info(packages.as_deref()).await?;
}
Commands::Search { query } => {
registry.search(&query).await?;
Commands::Search { query, case_sensitive} => {
registry.search(&query, case_sensitive).await?;
}
Commands::Query { query } => {
registry.query(&query).await?;
Expand Down
14 changes: 4 additions & 10 deletions src/registry/fetcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use tokio::fs;
use crate::core::{
color::{Color, ColorExt},
config::Repository,
util::{download, get_platform},
util::download,
};

use super::package::Package;
Expand All @@ -26,11 +26,9 @@ impl RegistryFetcher {
}

pub async fn execute(&self, repository: &Repository) -> Result<Vec<u8>> {
let platform = get_platform();
let url = format!(
"{}/{}/{}",
"{}/{}",
repository.url,
platform,
repository
.registry
.to_owned()
Expand All @@ -55,9 +53,7 @@ impl RegistryFetcher {
.rev()
.nth(1)
.map(|v| v.to_owned())
.filter(|v| {
v != ARCH && v != &platform && v != &platform.replace('-', "_")
}),
.filter(|v| v != ARCH),
..package.clone()
});
acc
Expand Down Expand Up @@ -88,11 +84,9 @@ impl RegistryFetcher {
}

pub async fn checksum(&self, repository: &Repository) -> Result<Vec<u8>> {
let platform = get_platform();
let url = format!(
"{}/{}/{}",
"{}/{}",
repository.url,
platform,
repository
.registry
.to_owned()
Expand Down
8 changes: 4 additions & 4 deletions src/registry/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ impl PackageRegistry {

// fetch default icons
let icon_futures: Vec<_> = repo
.paths
.sources
.iter()
.map(|(key, base_url)| {
let base_url = format!("{}/{}.default.png", base_url, key);
Expand All @@ -98,7 +98,7 @@ impl PackageRegistry {
.collect();
let icons = try_join_all(icon_futures).await?;

for (key, icon) in repo.paths.keys().zip(icons) {
for (key, icon) in repo.sources.keys().zip(icons) {
let icon_path = REGISTRY_PATH
.join("icons")
.join(format!("{}-{}.png", repo.name, key));
Expand Down Expand Up @@ -143,9 +143,9 @@ impl PackageRegistry {
self.storage.remove_packages(package_names).await
}

pub async fn search(&self, package_name: &str) -> Result<()> {
pub async fn search(&self, package_name: &str, case_sensitive: bool) -> Result<()> {
let installed_guard = self.installed_packages.lock().await;
let result = self.storage.search(package_name).await;
let result = self.storage.search(package_name, case_sensitive).await;

if result.is_empty() {
Err(anyhow::anyhow!("No packages found"))
Expand Down
22 changes: 12 additions & 10 deletions src/registry/package/appimage.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{
collections::HashSet,
fs::File,
io::{BufReader, BufWriter, Read, Seek, Write},
io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write},
path::{Path, PathBuf},
};

Expand All @@ -13,7 +13,7 @@ use tokio::{fs, try_join};
use crate::{
core::{
color::{Color, ColorExt},
constant::{APPIMAGE_MAGIC_BYTES, BIN_PATH, PACKAGES_PATH},
constant::{APPIMAGE_MAGIC_BYTES, APPIMAGE_MAGIC_OFFSET, BIN_PATH, PACKAGES_PATH},
util::{download, home_data_path},
},
error, info,
Expand Down Expand Up @@ -79,9 +79,11 @@ fn normalize_image(image: DynamicImage) -> DynamicImage {
}

fn is_appimage(file: &mut BufReader<File>) -> bool {
let mut magic_bytes = [0_u8; 16];
if file.read_exact(&mut magic_bytes).is_ok() {
return APPIMAGE_MAGIC_BYTES == magic_bytes;
if file.seek(SeekFrom::Start(APPIMAGE_MAGIC_OFFSET)).is_ok() {
let mut magic_bytes = [0_u8; 4];
if file.read_exact(&mut magic_bytes).is_ok() {
return APPIMAGE_MAGIC_BYTES == magic_bytes;
}
}
false
}
Expand Down Expand Up @@ -144,12 +146,11 @@ pub async fn remove_applinks(name: &str, bin_name: &str, file_path: &Path) -> Re
Ok(())
}

pub async fn extract_appimage(package: &Package, file_path: &Path) -> Result<()> {
pub async fn integrate_appimage(package: &Package, file_path: &Path) -> Result<bool> {
let mut file = BufReader::new(File::open(file_path)?);

if !is_appimage(&mut file) {
use_remote_files(package, file_path).await?;
return Ok(());
return Ok(false);
}

let offset = find_offset(&mut file).await?;
Expand Down Expand Up @@ -183,7 +184,7 @@ pub async fn extract_appimage(package: &Package, file_path: &Path) -> Result<()>
}
}

Ok(())
Ok(true)
}

fn resolve_and_extract(
Expand Down Expand Up @@ -300,7 +301,8 @@ async fn process_desktop(
Ok(())
}

pub async fn use_remote_files(package: &Package, file_path: &Path) -> Result<()> {
// TODO: use this if the package don't contain the required files
pub async fn _use_remote_files(package: &Package, file_path: &Path) -> Result<()> {
let home_data = home_data_path();
let data_path = Path::new(&home_data);

Expand Down
11 changes: 5 additions & 6 deletions src/registry/package/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::{
error,
registry::{
installed::InstalledPackages,
package::appimage::{extract_appimage, setup_portable_dir},
package::appimage::{integrate_appimage, setup_portable_dir},
},
warn,
};
Expand Down Expand Up @@ -64,8 +64,7 @@ impl Installer {
);

if !force && is_installed {
error!("{}: Package is already installed", prefix);
return Err(anyhow::anyhow!(""));
return Err(anyhow::anyhow!("{}: Package is already installed", prefix));
}

if is_installed && !is_update {
Expand Down Expand Up @@ -166,9 +165,9 @@ impl Installer {

self.save_file().await?;
self.symlink_bin(&installed_packages).await?;
// TODO: use magic bytes instead
if self.resolved_package.collection == "pkg" {
extract_appimage(package, &self.install_path).await?;

let ai_integrated = integrate_appimage(package, &self.install_path).await?;
if ai_integrated {
setup_portable_dir(
&package.bin_name,
&self.install_path,
Expand Down
2 changes: 1 addition & 1 deletion src/registry/package/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ impl Runner {
let result = validate_checksum(&package.bsum, &self.temp_path).await;
if result.is_err() {
error!(
"\n{}: Checksum verification failed.",
"{}: Checksum verification failed.",
package_name.color(Color::Blue)
);
}
Expand Down
Loading

0 comments on commit 041e824

Please sign in to comment.