chore: ran cargo fmt

This commit is contained in:
Byson94
2025-08-22 19:54:04 +05:30
parent 157edbe1ca
commit 03128c04fc
16 changed files with 219 additions and 197 deletions

View File

@@ -1,8 +1,8 @@
use crate::git::is_upstream_ahead;
use super::load_db;
use std::error::Error;
use log::info;
use crate::git::is_upstream_ahead;
use colored::Colorize;
use log::info;
use std::error::Error;
pub fn check_package_updates(package_name: &Option<String>) -> Result<(), Box<dyn Error>> {
let mut db = load_db()?;
@@ -12,7 +12,7 @@ pub fn check_package_updates(package_name: &Option<String>) -> Result<(), Box<dy
if let Some(pkg) = db.packages.get_mut(name) {
info!("> Checking for '{}' update", name.yellow().bold());
let need_update = is_upstream_ahead(&pkg.repo_path)?;
if need_update {
pkg_needing_update.push(name);
}

View File

@@ -1,9 +1,9 @@
use super::{InstalledPackage, save_db, load_db};
use log::{info, debug};
use std::error::Error;
use std::path::PathBuf;
use std::fs;
use super::{InstalledPackage, load_db, save_db};
use colored::Colorize;
use log::{debug, info};
use std::error::Error;
use std::fs;
use std::path::PathBuf;
pub fn clean_package_cache(package_name: Option<String>) -> Result<(), Box<dyn Error>> {
let mut db = load_db()?;
@@ -29,30 +29,38 @@ pub fn clean_package_cache(package_name: Option<String>) -> Result<(), Box<dyn E
fn clear_file_cache(pkg: &mut InstalledPackage, package_name: &str) -> Result<(), Box<dyn Error>> {
let repo_path = PathBuf::from(&pkg.repo_path);
let home_dir = dirs::home_dir().ok_or("Failed to get home directory")?;
let cache_root = home_dir.join(".eiipm/cache");
if !repo_path.exists() {
info!("Cache of package '{}' doesn't exist. Skipping...", package_name);
info!(
"Cache of package '{}' doesn't exist. Skipping...",
package_name
);
return Ok(());
} else {
debug!("Running catastrophe preventer code before removing cache.");
if !repo_path.starts_with(cache_root.as_path()) {
return Err(format!("Refusing to delete outside cache: {}", repo_path.display()).into());
return Err(
format!("Refusing to delete outside cache: {}", repo_path.display()).into(),
);
}
match fs::remove_dir_all(repo_path) {
Ok(_) => info!("Successfully cleared '{}' cache", package_name.yellow().bold()),
Ok(_) => info!(
"Successfully cleared '{}' cache",
package_name.yellow().bold()
),
Err(e) => {
return Err(format!(
"Error removing cache of '{}'. Caused by: {}",
package_name,
e
).into());
},
"Error removing cache of '{}'. Caused by: {}",
package_name, e
)
.into());
}
}
}
Ok(())
}
}

View File

@@ -1,24 +1,15 @@
use colored::{Colorize};
use super::{FileEntry, InstalledPackage, http_get_string, load_db, save_db};
use colored::Colorize;
use dirs;
use glob::glob;
use log::{info, trace};
use serde::{Deserialize};
use serde::Deserialize;
use std::env;
use std::error::Error;
use std::fs;
use std::process::Command;
use super::{
FileEntry,
InstalledPackage,
save_db,
load_db,
http_get_string
};
use glob::glob;
use crate::git::{
clone_https,
pull_but_reclone_on_fail
};
use crate::git::{clone_https, pull_but_reclone_on_fail};
#[derive(Deserialize, Debug)]
struct PackageRootMeta {
@@ -63,7 +54,11 @@ pub fn install_package(package_name: &str) -> Result<(), Box<dyn Error>> {
// Clone or pull repo
if !repo_path.exists() {
info!("Cloning repository {} to {}", meta.src.underline(), repo_path.display());
info!(
"Cloning repository {} to {}",
meta.src.underline(),
repo_path.display()
);
let _repo = clone_https(&meta.src, &repo_path, Some(1))
.map_err(|e| format!("Git clone failed: {}", e))?;
} else {
@@ -103,10 +98,7 @@ pub fn install_package(package_name: &str) -> Result<(), Box<dyn Error>> {
.expect("Invalid glob")
.filter_map(Result::ok)
.map(|src| {
let tgt = target_base_dir.join(
src.file_name()
.expect("Invalid file name"),
);
let tgt = target_base_dir.join(src.file_name().expect("Invalid file name"));
(src, tgt)
})
.collect(),
@@ -117,7 +109,7 @@ pub fn install_package(package_name: &str) -> Result<(), Box<dyn Error>> {
.map(|src_path| {
let tgt = match dest {
Some(d) => target_base_dir.join(d),
None => target_base_dir.join(src)
None => target_base_dir.join(src),
};
(src_path, tgt)
})
@@ -134,7 +126,7 @@ pub fn install_package(package_name: &str) -> Result<(), Box<dyn Error>> {
}
fs::copy(&source, &target)?;
installed_files.push(target.to_string_lossy().to_string());
};
}
}
// Update DB
@@ -152,7 +144,9 @@ pub fn install_package(package_name: &str) -> Result<(), Box<dyn Error>> {
);
save_db(&db)?;
info!("Installation complete for '{}'", package_name.yellow().bold());
info!(
"Installation complete for '{}'",
package_name.yellow().bold()
);
Ok(())
}

View File

@@ -1,7 +1,7 @@
use super::load_db;
use log::{info, error};
use std::error::Error;
use super::load_db;
use crate::opts::ListArgs;
use log::{error, info};
use std::error::Error;
pub fn list_packages(list_args: ListArgs) -> Result<(), Box<dyn Error>> {
let db = load_db()?;
@@ -20,7 +20,10 @@ pub fn list_packages(list_args: ListArgs) -> Result<(), Box<dyn Error>> {
pkg,
package.pkg_type,
package.repo_path,
package.build_command.clone().unwrap_or_else(|| "None".into()),
package
.build_command
.clone()
.unwrap_or_else(|| "None".into()),
package.installed_files.join("\n ")
);
} else {
@@ -40,7 +43,10 @@ pub fn list_packages(list_args: ListArgs) -> Result<(), Box<dyn Error>> {
name,
package.pkg_type,
package.repo_path,
package.build_command.clone().unwrap_or_else(|| "None".into()),
package
.build_command
.clone()
.unwrap_or_else(|| "None".into()),
package.installed_files.join("\n ")
);
} else {

View File

@@ -1,5 +1,5 @@
use std::fs;
use log::{error, info};
use std::fs;
pub fn list_all_cache() -> Result<(), Box<dyn std::error::Error>> {
let home_dir = dirs::home_dir().ok_or("Failed to get home directory")?;
@@ -19,4 +19,4 @@ pub fn list_all_cache() -> Result<(), Box<dyn std::error::Error>> {
}
}
Ok(())
}
}

View File

@@ -1,19 +1,19 @@
pub mod install;
pub mod uninstall;
pub mod update;
pub mod list;
pub mod clearcache;
pub mod checkupdate;
pub mod clearcache;
pub mod install;
pub mod list;
pub mod listcache;
pub mod purgecache;
pub mod search;
pub mod uninstall;
pub mod update;
use std::fs;
use std::error::Error;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use dirs;
use reqwest::blocking::get;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error::Error;
use std::fs;
pub const DB_FILE: &str = ".local/share/eiipm/installed.toml";
@@ -42,10 +42,7 @@ pub struct InstalledPackage {
#[serde(untagged)]
pub enum FileEntry {
Flat(String),
Detailed {
src: String,
dest: Option<String>,
},
Detailed { src: String, dest: Option<String> },
}
pub fn load_db() -> Result<PackageDB, Box<dyn Error>> {
@@ -56,7 +53,9 @@ pub fn load_db() -> Result<PackageDB, Box<dyn Error>> {
let db: PackageDB = toml::from_str(&content)?;
Ok(db)
} else {
Ok(PackageDB { packages: HashMap::new() })
Ok(PackageDB {
packages: HashMap::new(),
})
}
}
@@ -80,4 +79,3 @@ pub fn http_get_string(url: &str) -> Result<String, Box<dyn Error>> {
}
Ok(response.text()?)
}

View File

@@ -1,12 +1,12 @@
use super::load_db;
use colored::Colorize;
use log::{info, error};
use log::{error, info};
use std::collections::HashSet;
use std::fs;
use std::path::Path;
use super::load_db;
pub fn purge_cache() -> Result<(), Box<dyn std::error::Error>> {
let db = load_db()?;
let db = load_db()?;
let home_dir = dirs::home_dir().ok_or("Failed to get home directory")?;
let cache_root = home_dir.join(".eiipm/cache");
@@ -47,7 +47,15 @@ pub fn purge_cache() -> Result<(), Box<dyn std::error::Error>> {
if orphan_count == 0 {
info!("{}", "Cache is clean. Nothing to remove.".green());
} else {
info!("{}", format!("\nRemoved {} orphaned cache director{}", orphan_count, if orphan_count == 1 { "y" } else { "ies" }).yellow());
info!(
"{}",
format!(
"\nRemoved {} orphaned cache director{}",
orphan_count,
if orphan_count == 1 { "y" } else { "ies" }
)
.yellow()
);
}
Ok(())

View File

@@ -1,13 +1,10 @@
use super::http_get_string;
use crate::opts::SearchArgs;
use colored::Colorize;
use log::info;
use std::error::Error;
use colored::Colorize;
use crate::opts::SearchArgs;
pub fn search_package(
package_name: &str,
flags: SearchArgs
) -> Result<(), Box<dyn Error>> {
pub fn search_package(package_name: &str, flags: SearchArgs) -> Result<(), Box<dyn Error>> {
info!("> Searching for '{}'", package_name.yellow().bold());
let raw_manifest_url = format!(
@@ -16,23 +13,30 @@ pub fn search_package(
);
if let Ok(response) = http_get_string(&raw_manifest_url) {
info!("{}", format!(
"\nPackage with name '{}' is found in eii-manifests!",
package_name
).green());
info!(
"{}",
format!(
"\nPackage with name '{}' is found in eii-manifests!",
package_name
)
.green()
);
if flags.log_metadata {
info!("{}", format!(
"\n--- Metadata for '{}' ---\n{}",
package_name.cyan().bold(),
indent_lines(&response, 4)
));
info!(
"{}",
format!(
"\n--- Metadata for '{}' ---\n{}",
package_name.cyan().bold(),
indent_lines(&response, 4)
)
);
}
} else {
info!("{}", format!(
"Package '{}' not found.",
package_name.red().bold()
));
info!(
"{}",
format!("Package '{}' not found.", package_name.red().bold())
);
}
Ok(())

View File

@@ -1,9 +1,9 @@
use super::{load_db, save_db};
use colored::Colorize;
use log::{info};
use log::info;
use std::error::Error;
use std::fs;
use std::path::PathBuf;
use super::{load_db, save_db};
pub fn uninstall_package(package_name: &str) -> Result<(), Box<dyn Error>> {
info!("> Uninstalling package '{}'", package_name.yellow().bold());
@@ -18,10 +18,13 @@ pub fn uninstall_package(package_name: &str) -> Result<(), Box<dyn Error>> {
}
}
save_db(&db)?;
info!("Successfully uninstalled '{}'", package_name.yellow().bold());
info!(
"Successfully uninstalled '{}'",
package_name.yellow().bold()
);
} else {
info!("Package '{}' not found in database", package_name.yellow());
}
Ok(())
}
}

View File

@@ -1,23 +1,14 @@
use log::{info, debug, error};
use std::error::Error;
use std::path::PathBuf;
use std::fs;
use std::process::Command;
use colored::Colorize;
use glob::glob;
use log::{debug, error, info};
use std::error::Error;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use super::{
save_db,
load_db,
FileEntry,
InstalledPackage,
};
use super::{FileEntry, InstalledPackage, load_db, save_db};
use crate::git::{
clone_https,
pull_but_reclone_on_fail,
is_upstream_ahead,
};
use crate::git::{clone_https, is_upstream_ahead, pull_but_reclone_on_fail};
pub fn update_package(package_name: &Option<String>) -> Result<(), Box<dyn Error>> {
let mut db = load_db()?;
@@ -48,7 +39,11 @@ pub fn update_package(package_name: &Option<String>) -> Result<(), Box<dyn Error
} else {
info!("> Updating all packages...");
for (name, pkg) in db.packages.iter_mut() {
info!("Checking package '{}' [{}]", name.yellow().bold(), pkg.pkg_type);
info!(
"Checking package '{}' [{}]",
name.yellow().bold(),
pkg.pkg_type
);
if pkg.pkg_type == "theme" {
info!("Skipping theme package '{}'", name.yellow().bold());
@@ -77,7 +72,11 @@ fn update_file(pkg: &mut InstalledPackage, package_name: &str) -> Result<(), Box
debug!("Pulling latest version of {} using git...", package_name);
if !repo_path.exists() {
info!("Cache not found. Cloning repository {} to {}", pkg.upstream_src.underline(), repo_path.display());
info!(
"Cache not found. Cloning repository {} to {}",
pkg.upstream_src.underline(),
repo_path.display()
);
let _repo = clone_https(&pkg.upstream_src, &repo_path, Some(1))
.map_err(|e| format!("Git clone failed: {}", e))?;
} else {
@@ -123,10 +122,7 @@ fn update_file(pkg: &mut InstalledPackage, package_name: &str) -> Result<(), Box
.expect("Invalid glob")
.filter_map(Result::ok)
.map(|src| {
let tgt = target_base_dir.join(
src.file_name()
.expect("Invalid file name"),
);
let tgt = target_base_dir.join(src.file_name().expect("Invalid file name"));
(src, tgt)
})
.collect(),
@@ -137,7 +133,7 @@ fn update_file(pkg: &mut InstalledPackage, package_name: &str) -> Result<(), Box
.map(|src_path| {
let tgt = match dest {
Some(d) => target_base_dir.join(d),
None => target_base_dir.join(src)
None => target_base_dir.join(src),
};
(src_path, tgt)
})
@@ -155,7 +151,7 @@ fn update_file(pkg: &mut InstalledPackage, package_name: &str) -> Result<(), Box
fs::copy(&source, &target)?;
info!("Copied {} -> {}", source.display(), target.display());
};
}
}
Ok(())

View File

@@ -1,12 +1,9 @@
//! Working with git2 API's
use git2::{
Repository, Cred, RemoteCallbacks,
FetchOptions, build::RepoBuilder, Error
};
use std::path::Path;
use std::fs;
use crate::other::confirm_action::confirm;
use git2::{Cred, Error, FetchOptions, RemoteCallbacks, Repository, build::RepoBuilder};
use std::fs;
use std::path::Path;
pub fn clone_https(repo_url: &str, path: &Path, depth: Option<u32>) -> Result<Repository, Error> {
let callbacks = RemoteCallbacks::new();
@@ -64,14 +61,16 @@ pub fn pull_https(repo: &Repository) -> Result<(), Error> {
let head_tree = repo.find_commit(head_commit.id())?.tree()?;
let fetch_tree = repo.find_commit(fetch_commit.id())?.tree()?;
let ancestor_commit = repo.merge_base(head_commit.id(), fetch_commit.id())
let ancestor_commit = repo
.merge_base(head_commit.id(), fetch_commit.id())
.and_then(|oid| repo.find_commit(oid))?;
let ancestor_tree = ancestor_commit.tree()?;
let mut idx = repo.merge_trees(&ancestor_tree, &head_tree, &fetch_tree, None)?;
if idx.has_conflicts() {
return Err(Error::from_str("Merge conflicts detected. Please resolve manually."));
return Err(Error::from_str(
"Merge conflicts detected. Please resolve manually.",
));
}
// Write the merged tree
@@ -100,7 +99,11 @@ pub fn pull_https(repo: &Repository) -> Result<(), Error> {
Ok(())
}
pub fn pull_but_reclone_on_fail(repo_url: &str, repo_path: &Path, depth: Option<u32>) -> Result<Repository, Error> {
pub fn pull_but_reclone_on_fail(
repo_url: &str,
repo_path: &Path,
depth: Option<u32>,
) -> Result<Repository, Error> {
// Try opening the repo if it exists
if let Ok(repo) = Repository::open(repo_path) {
// Try to pull
@@ -111,15 +114,20 @@ pub fn pull_but_reclone_on_fail(repo_url: &str, repo_path: &Path, depth: Option<
let user_confirm = confirm("Failed to update cache (outdated). Remove and retry?");
let home_dir = dirs::home_dir().ok_or_else(|| Error::from_str("Failed to get home directory"))?;
let home_dir = dirs::home_dir()
.ok_or_else(|| Error::from_str("Failed to get home directory"))?;
let cache_root = home_dir.join(".eiipm/cache");
if user_confirm {
if !repo_path.starts_with(cache_root.as_path()) {
return Err(Error::from_str(&format!("Refusing to delete outside cache: {}", repo_path.display())));
return Err(Error::from_str(&format!(
"Refusing to delete outside cache: {}",
repo_path.display()
)));
}
fs::remove_dir_all(repo_path).map_err(|e| Error::from_str(&format!("Failed to remove dir: {}", e)))?;
fs::remove_dir_all(repo_path)
.map_err(|e| Error::from_str(&format!("Failed to remove dir: {}", e)))?;
} else {
// user refused, so just return the repo as-is
return Ok(repo);
@@ -136,12 +144,13 @@ pub fn pull_but_reclone_on_fail(repo_url: &str, repo_path: &Path, depth: Option<
/// Returns `Ok(true)` if the upstream has commits the local branch doesn't have.
pub fn is_upstream_ahead(repo_path: &str) -> Result<bool, Error> {
let repo = Repository::open(repo_path)?;
// Get the current branch
let head_ref = repo.head()?;
let branch_name = head_ref.shorthand()
let branch_name = head_ref
.shorthand()
.ok_or_else(|| Error::from_str("Invalid branch name"))?;
// Set up fetch options with authentication callbacks
let mut callbacks = RemoteCallbacks::new();
callbacks.credentials(|_url, username_from_url, _allowed_types| {
@@ -149,19 +158,25 @@ pub fn is_upstream_ahead(repo_path: &str) -> Result<bool, Error> {
});
let mut fetch_options = FetchOptions::new();
fetch_options.remote_callbacks(callbacks);
// Fetch from origin
let mut remote = repo.find_remote("origin")?;
remote.fetch(&[branch_name], Some(&mut fetch_options), None)?;
// Resolve upstream
let local_branch = repo.find_branch(branch_name, git2::BranchType::Local)?;
let upstream_branch = local_branch.upstream()?;
let local_oid = local_branch.get().target().ok_or_else(|| Error::from_str("Local branch has no commit"))?;
let upstream_oid = upstream_branch.get().target().ok_or_else(|| Error::from_str("Upstream branch has no commit"))?;
let local_oid = local_branch
.get()
.target()
.ok_or_else(|| Error::from_str("Local branch has no commit"))?;
let upstream_oid = upstream_branch
.get()
.target()
.ok_or_else(|| Error::from_str("Upstream branch has no commit"))?;
let (_ahead, behind) = repo.graph_ahead_behind(local_oid, upstream_oid)?;
Ok(behind > 0)
}
}

View File

@@ -1,27 +1,18 @@
mod opts;
mod functions;
mod other;
mod git;
mod opts;
mod other;
use opts::{PMArgs, Commands};
use functions::{
install::install_package,
uninstall::uninstall_package,
update::update_package,
list::list_packages,
clearcache::clean_package_cache,
checkupdate::check_package_updates,
listcache::list_all_cache,
purgecache::purge_cache,
search::search_package,
};
use other::{
confirm_action::confirm,
run_checks::check_eiipm_in_path,
checkupdate::check_package_updates, clearcache::clean_package_cache, install::install_package,
list::list_packages, listcache::list_all_cache, purgecache::purge_cache,
search::search_package, uninstall::uninstall_package, update::update_package,
};
use opts::{Commands, PMArgs};
use other::{confirm_action::confirm, run_checks::check_eiipm_in_path};
use clap::Parser;
use log::{info, error, Level};
use log::{Level, error, info};
fn main() {
let args = PMArgs::parse();
@@ -43,20 +34,18 @@ fn main() {
error!("Error uninstalling '{}': {}", package, e);
}
}
Commands::Update { package } => {
match &package {
Some(name) => {
if let Err(e) = update_package(&Some(name.clone())) {
error!("Error updating '{}'. Caused by: {}", name, e);
}
}
None => {
if let Err(e) = update_package(&None) {
error!("Error updating all packages: {}", e);
}
Commands::Update { package } => match &package {
Some(name) => {
if let Err(e) = update_package(&Some(name.clone())) {
error!("Error updating '{}'. Caused by: {}", name, e);
}
}
}
None => {
if let Err(e) = update_package(&None) {
error!("Error updating all packages: {}", e);
}
}
},
Commands::List(list_args) => {
if let Err(e) = list_packages(list_args) {
error!("Error listing packages: {}", e);
@@ -87,20 +76,18 @@ fn main() {
}
}
}
Commands::CheckUpdates { package } => {
match &package {
Some(name) => {
if let Err(e) = check_package_updates(&Some(name.clone())) {
error!("Error checking for updates in '{}'. Caused by: {}", name, e);
}
}
None => {
if let Err(e) = check_package_updates(&None) {
error!("Error checking for updates in all packages: {}", e);
}
Commands::CheckUpdates { package } => match &package {
Some(name) => {
if let Err(e) = check_package_updates(&Some(name.clone())) {
error!("Error checking for updates in '{}'. Caused by: {}", name, e);
}
}
}
None => {
if let Err(e) = check_package_updates(&None) {
error!("Error checking for updates in all packages: {}", e);
}
}
},
Commands::ListCacheDir => {
if let Err(e) = list_all_cache() {
error!("Error listing cache: {}", e);
@@ -131,16 +118,17 @@ fn set_debug_levels(debug_mode: bool) {
.format_module_path(true)
.format_level(true);
} else {
builder.format(|buf, record| {
use std::io::Write;
builder
.format(|buf, record| {
use std::io::Write;
match record.level() {
Level::Warn => writeln!(buf, "[WARN] {}", record.args()),
Level::Error => writeln!(buf, "[ERROR] {}", record.args()),
_ => writeln!(buf, "{}", record.args()),
}
})
.filter_level(log::LevelFilter::Info);
match record.level() {
Level::Warn => writeln!(buf, "[WARN] {}", record.args()),
Level::Error => writeln!(buf, "[ERROR] {}", record.args()),
_ => writeln!(buf, "{}", record.args()),
}
})
.filter_level(log::LevelFilter::Info);
}
builder.init();

View File

@@ -1,4 +1,4 @@
use clap::{Parser, Subcommand, Args};
use clap::{Args, Parser, Subcommand};
/// Eiipm package manager for ewwii.
#[derive(Parser, Debug)]
@@ -8,7 +8,7 @@ pub struct PMArgs {
/// Show debug logs
#[arg(long, global = true)]
pub debug: bool,
#[command(subcommand)]
pub command: Commands,
}
@@ -72,7 +72,7 @@ pub enum Commands {
package: String,
#[command(flatten)]
flags: SearchArgs
flags: SearchArgs,
},
}

View File

@@ -7,4 +7,4 @@ pub fn confirm(prompt: &str) -> bool {
io::stdin().read_line(&mut input).unwrap();
matches!(input.trim().to_lowercase().as_str(), "y" | "yes")
}
}

View File

@@ -1,2 +1,2 @@
pub mod confirm_action;
pub mod run_checks;
pub mod run_checks;

View File

@@ -1,7 +1,7 @@
use colored::Colorize;
use log::{error, info};
use std::env;
use std::path::PathBuf;
use log::{error, info};
use colored::Colorize;
pub fn check_eiipm_in_path() {
let target_dir: PathBuf = match dirs::home_dir() {
@@ -30,7 +30,9 @@ pub fn check_eiipm_in_path() {
target_dir.display(),
"export PATH=\"$HOME/.eiipm/bin:$PATH\"".yellow(),
"(adjust if necessary)".dimmed(),
"https://ewwii-sh.github.io/docs/package-manager/overview/#adding-eiipm-to-path".underline().blue()
"https://ewwii-sh.github.io/docs/package-manager/overview/#adding-eiipm-to-path"
.underline()
.blue()
);
info!("{}", msg.yellow()); // dont use warn!() as it will add [WARN] label