From 64eadb49bca1a30aa6e7c404a9969e23aa5f62e2 Mon Sep 17 00:00:00 2001 From: ripytide Date: Thu, 29 Aug 2024 14:21:41 +0100 Subject: [PATCH 1/3] slimmed down crate --- Cargo.lock | 244 +++++++++++++++++++++++++++++++++++++++-- Cargo.toml | 2 + src/backend/cargo.rs | 15 +-- src/backend/dnf.rs | 2 +- src/backend/flatpak.rs | 4 +- src/config.rs | 20 ++-- src/errors.rs | 44 -------- src/groups.rs | 93 +--------------- src/lib.rs | 5 +- src/main.rs | 97 ++-------------- src/path.rs | 181 ------------------------------ src/prelude.rs | 10 -- 12 files changed, 264 insertions(+), 453 deletions(-) delete mode 100644 src/errors.rs delete mode 100644 src/path.rs diff --git a/Cargo.lock b/Cargo.lock index 73ff53d..ddd42b1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -46,7 +46,7 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648" dependencies = [ - "windows-sys", + "windows-sys 0.52.0", ] [[package]] @@ -56,7 +56,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7" dependencies = [ "anstyle", - "windows-sys", + "windows-sys 0.52.0", ] [[package]] @@ -65,6 +65,18 @@ version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f538837af36e6f6a9be0faa67f9a314f8119e4e4b5867c6ab40ed60360142519" +[[package]] +name = "bitflags" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + [[package]] name = "clap" version = "4.5.4" @@ -150,6 +162,27 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.48.0", +] + [[package]] name = "either" version = "1.11.0" @@ -168,12 +201,36 @@ dependencies = [ "syn 2.0.58", ] +[[package]] +name = "env_logger" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd405aab171cb85d6735e5c8d9db038c17d3ca007a4d2c25f337935c3d90580" +dependencies = [ + "humantime", + "is-terminal", + "log", + "regex", + "termcolor", +] + [[package]] name = "equivalent" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" +[[package]] +name = "getrandom" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "hashbrown" version = "0.14.5" @@ -186,6 +243,18 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hermit-abi" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" + +[[package]] +name = "humantime" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" + [[package]] name = "indexmap" version = "2.2.6" @@ -196,6 +265,17 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "is-terminal" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261f68e344040fbd0edea105bef17c66edf46f984ddb1115b775ce31be948f4b" +dependencies = [ + "hermit-abi", + "libc", + "windows-sys 0.52.0", +] + [[package]] name = "itertools" version = "0.12.1" @@ -213,9 +293,19 @@ checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "libc" -version = "0.2.153" +version = "0.2.158" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" +checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439" + +[[package]] +name = "libredox" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" +dependencies = [ + "bitflags", + "libc", +] [[package]] name = "log" @@ -235,6 +325,12 @@ version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "pacdef" version = "1.6.0" @@ -243,11 +339,13 @@ dependencies = [ "clap", "const_format", "derive_more", + "dirs", "enum_dispatch", "itertools", "libc", "log", "path-absolutize", + "pretty_env_logger", "regex", "serde", "serde_json", @@ -273,6 +371,16 @@ dependencies = [ "once_cell", ] +[[package]] +name = "pretty_env_logger" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "865724d4dbe39d9f3dd3b52b88d859d66bcb2d6a0acfd5ea68a65fb66d4bdc1c" +dependencies = [ + "env_logger", + "log", +] + [[package]] name = "proc-macro2" version = "1.0.79" @@ -291,6 +399,17 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom", + "libredox", + "thiserror", +] + [[package]] name = "regex" version = "1.10.4" @@ -418,6 +537,35 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.58", +] + [[package]] name = "toml" version = "0.8.12" @@ -480,6 +628,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + [[package]] name = "winapi" version = "0.3.9" @@ -511,13 +665,37 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets", + "windows-targets 0.52.5", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", ] [[package]] @@ -526,28 +704,46 @@ version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", + "windows_aarch64_gnullvm 0.52.5", + "windows_aarch64_msvc 0.52.5", + "windows_i686_gnu 0.52.5", "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_i686_msvc 0.52.5", + "windows_x86_64_gnu 0.52.5", + "windows_x86_64_gnullvm 0.52.5", + "windows_x86_64_msvc 0.52.5", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + [[package]] name = "windows_aarch64_msvc" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + [[package]] name = "windows_i686_gnu" version = "0.52.5" @@ -560,24 +756,48 @@ version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + [[package]] name = "windows_i686_msvc" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + [[package]] name = "windows_x86_64_gnu" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + [[package]] name = "windows_x86_64_gnullvm" version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + [[package]] name = "windows_x86_64_msvc" version = "0.52.5" diff --git a/Cargo.toml b/Cargo.toml index 5cde4cb..1c88339 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,6 +25,8 @@ serde_json = "1.0" toml = "0.8" derive_more = "0.99" itertools = "0.12" +dirs = "5.0.1" +pretty_env_logger = "0.5.0" [profile.release] lto = "off" diff --git a/src/backend/cargo.rs b/src/backend/cargo.rs index ac364c6..bae56b5 100644 --- a/src/backend/cargo.rs +++ b/src/backend/cargo.rs @@ -1,6 +1,5 @@ +use std::collections::BTreeMap; use std::io::ErrorKind::NotFound; -use std::path::PathBuf; -use std::{collections::BTreeMap, fs::read_to_string}; use anyhow::{bail, Context, Result}; use serde_json::Value; @@ -23,9 +22,11 @@ impl Backend for Cargo { return Ok(BTreeMap::new()); } - let file = get_crates_file().context("getting path to crates file")?; + let file = dirs::home_dir() + .context("getting the home directory")? + .join(".crates2.json"); - let contents = match read_to_string(file) { + let contents = match std::fs::read_to_string(file) { Ok(string) => string, Err(err) if err.kind() == NotFound => { log::warn!("no crates file found for cargo. Assuming no crates installed yet."); @@ -89,9 +90,3 @@ fn extract_packages(contents: &str) -> Result> { Ok(result) } - -fn get_crates_file() -> Result { - let mut result = crate::path::get_cargo_home().context("getting cargo home dir")?; - result.push(".crates2.json"); - Ok(result) -} diff --git a/src/backend/dnf.rs b/src/backend/dnf.rs index 461402e..f6f4ecf 100644 --- a/src/backend/dnf.rs +++ b/src/backend/dnf.rs @@ -10,7 +10,7 @@ pub struct Dnf; #[derive(Debug, Clone)] pub struct DnfQueryInfo { - user: bool, + pub user: bool, } #[derive(Debug, Clone, Default)] diff --git a/src/backend/flatpak.rs b/src/backend/flatpak.rs index d5a9d64..241c4bc 100644 --- a/src/backend/flatpak.rs +++ b/src/backend/flatpak.rs @@ -10,8 +10,8 @@ pub struct Flatpak; #[derive(Debug, Clone)] pub struct FlatpakQueryInfo { - explicit: bool, - systemwide: bool, + pub explicit: bool, + pub systemwide: bool, } impl Backend for Flatpak { diff --git a/src/config.rs b/src/config.rs index 0ec9928..244424b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,12 +1,10 @@ -use std::fs::{create_dir_all, read_to_string, File}; +use std::fs::{create_dir_all, File}; use std::io::{ErrorKind, Write}; use std::path::Path; use anyhow::{bail, Context, Result}; use serde::{Deserialize, Serialize}; -use crate::prelude::*; - // Update the master README if fields change. /// Config for the program, as listed in `$XDG_CONFIG_HOME/pacdef/pacdef.toml`. #[derive(Debug, Serialize, Deserialize)] @@ -44,20 +42,20 @@ fn pip() -> String { } impl Config { - /// Load the config from the associated file. + /// Load the config file from a users pacdef config folder. /// /// # Errors - /// - /// This function will return an error if the config file exists but cannot be - /// read, its contents are not UTF-8, or the file is malformed. - pub fn load(config_file: &Path) -> Result { - let from_file = read_to_string(config_file); + /// - If a config file cannot be found. + pub fn load() -> Result { + let config_file = dirs::config_dir() + .context("getting the config directory")? + .join("pacdef/config.toml"); - let content = match from_file { + let content = match std::fs::read_to_string(config_file) { Ok(content) => content, Err(e) => { if e.kind() == ErrorKind::NotFound { - bail!(Error::ConfigFileNotFound) + bail!("config file not found") } bail!("unexpected error occurred: {e:?}"); } diff --git a/src/errors.rs b/src/errors.rs deleted file mode 100644 index 0c48f64..0000000 --- a/src/errors.rs +++ /dev/null @@ -1,44 +0,0 @@ -use std::error::Error as ErrorTrait; -use std::fmt::Display; -use std::path::PathBuf; - -/// Error types for pacdef. -#[derive(Debug)] -#[non_exhaustive] -pub enum Error { - /// Config file not found. - ConfigFileNotFound, - /// Group file not found. - GroupFileNotFound(String), - /// Group already exists. - GroupAlreadyExists(PathBuf), - /// Invalid group name ('.' or '..') - InvalidGroupName(String), - /// Multiple groups not found. - MultipleGroupsNotFound(Vec), - /// The backend in not managed by pacdef - InvalidBackend(String), -} - -impl Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::ConfigFileNotFound => write!(f, "config file not found"), - Self::GroupFileNotFound(name) => write!(f, "group file '{name}' not found"), - Self::GroupAlreadyExists(path) => { - write!(f, "group file '{}' already exists", path.to_string_lossy()) - } - Self::InvalidGroupName(name) => write!(f, "group name '{name}' is not valid"), - Self::MultipleGroupsNotFound(vec) => { - write!( - f, - "could not find the following groups: [{}]", - vec.join(", ") - ) - } - Self::InvalidBackend(name) => write!(f, "{name}: No such backend exists"), - } - } -} - -impl ErrorTrait for Error {} diff --git a/src/groups.rs b/src/groups.rs index 98ed1c5..e12d5dc 100644 --- a/src/groups.rs +++ b/src/groups.rs @@ -1,14 +1,9 @@ use crate::prelude::*; -use anyhow::{Context, Result}; -use path_absolutize::Absolutize; -use walkdir::WalkDir; +use anyhow::Result; use std::{ collections::BTreeMap, - fs::{create_dir, read_to_string}, ops::{Deref, DerefMut}, - path::Path, - str::FromStr, }; /// A type representing a users group files with all their packages @@ -32,91 +27,13 @@ impl Groups { Self(BTreeMap::new()) } - /// Loads and parses the [`Groups`] struct from a users group files + /// Loads Groups from a users pacdef config folder. /// /// # Errors - /// - /// Returns an error if a parsing error is encountered in a found group file. - /// - /// # Panics - /// - /// Cannot panic on Linux, since all path types will always be convertible to - /// valid Rust strings. - pub fn load(group_dir: &Path, _config: &Config) -> Result { - let mut groups = Self::new(); - - if !group_dir.is_dir() { - // other direcotories were already created with the config file - create_dir(group_dir).context("group dir does not exist, creating one")?; - } - - let mut files = vec![]; - - for file in WalkDir::new(group_dir).follow_links(true) { - let path = file?.path().absolutize_from(group_dir)?.to_path_buf(); - files.push(path); - } - - for group_file in files.iter().filter(|path| path.is_file()) { - let group = parse_group(group_file).context(format!( - "Failed to parse the group file {}", - group_file.to_string_lossy() - ))?; - - let group_name = get_relative_path(group_file.as_path(), group_dir) - .iter() - .map(|p| p.to_string_lossy().to_string()) - .reduce(|mut a, b| { - a.push('/'); - a.push_str(&b); - a - }) - .expect("must have at least one element") - .to_string(); - groups.insert(group_name, group); - } - - Ok(groups) - } -} - -/// Parse the group and sections from the group file -fn parse_group(group_file: &Path) -> Result { - let content = read_to_string(group_file).context("reading file contents")?; - - let mut backends = PackagesIds::new(); - let mut prev_backend: Option = None; - for (count, line) in content - .lines() - .enumerate() - .filter(|(_, line)| !line.trim_start().is_empty() && !line.trim_start().starts_with('#')) - { - if line.starts_with('[') { - let backend = line - .strip_prefix('[') - .expect("Won't error") - .strip_suffix(']') - .ok_or(Error::InvalidBackend(line.to_string())) - .context(format!("Invalid backend {}", line))?; - - prev_backend = AnyBackend::from_str(backend).ok(); - } else { - let package = line - .split_once('#') - .map_or(line, |value| value.0) - .trim() - .to_string(); - - prev_backend - .map(|backend| backends.insert_backend_package(backend, package)) - .ok_or(Error::InvalidBackend(format!( - "Failed to parse {line} at line number {count} in file {}", - group_file.to_string_lossy() - )))??; - } + /// - If the Group config file cannot be found. + pub fn load() -> Result { + todo!() } - - Ok(PackagesInstall::from_packages_ids_defaults(&backends)) } impl Deref for Groups { diff --git a/src/lib.rs b/src/lib.rs index 9077784..2ba1118 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -28,7 +28,6 @@ mod cmd; mod config; #[allow(clippy::unused_self, clippy::unnecessary_wraps)] mod core; -mod errors; mod groups; mod packages; mod review; @@ -37,7 +36,5 @@ mod ui; #[allow(unused_imports)] mod prelude; -pub mod path; - +pub use prelude::Config; pub use prelude::Groups; -pub use prelude::{Config, Error}; diff --git a/src/main.rs b/src/main.rs index 48a1ac1..87d5a34 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,109 +14,26 @@ missing_docs )] -use std::path::Path; -use std::process::{ExitCode, Termination}; - -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result}; use clap::Parser; use pacdef::cli::MainArguments; -use pacdef::path::{get_config_path, get_config_path_old_version}; -use pacdef::{Config, Error as PacdefError, Groups}; - -const MAJOR_UPDATE_MESSAGE: &str = "VERSION UPGRADE -You seem to have used version 1.x of pacdef before. -In version 2.0 the config file needed to be changed from yaml to toml. -Check out https://github.com/steven-omaha/pacdef/blob/main/README.md#configuration for new syntax information. -This message will not appear again. -------"; - -struct PacdefLogger; - -impl log::Log for PacdefLogger { - fn enabled(&self, _: &log::Metadata) -> bool { - true - } - - fn log(&self, record: &log::Record) { - if self.enabled(record.metadata()) { - eprintln!("{} - {}", record.level(), record.args()); - } - } - - fn flush(&self) {} -} - -fn main() -> ExitCode { - log::set_boxed_logger(Box::new(PacdefLogger)) - .map(|()| log::set_max_level(log::LevelFilter::Info)) - .expect("no other loggers should have been set"); - - handle_final_result(main_inner()) -} +use pacdef::{Config, Groups}; -/// Skip printing the error chain if its a pacdef error, -/// otherwise report error chain. -#[allow(clippy::option_if_let_else)] -fn handle_final_result(result: Result<()>) -> ExitCode { - match result { - Ok(_) => ExitCode::SUCCESS, - Err(ref e) => { - if let Some(root_error) = e.root_cause().downcast_ref::() { - log::error!("{root_error}"); - ExitCode::FAILURE - } else { - result.report() - } - } - } -} +fn main() -> Result<()> { + pretty_env_logger::init(); -fn main_inner() -> Result<()> { let main_arguments = MainArguments::parse(); - let mut config_file = get_config_path().context("getting config file")?; + let config = Config::load().context("loading config file")?; - let config = match Config::load(&config_file).context("loading config file") { - Ok(config) => config, - Err(e) => { - if let Some(crate_error) = e.downcast_ref::() { - match crate_error { - PacdefError::ConfigFileNotFound => load_default_config(&config_file)?, - _ => bail!("unexpected error: {crate_error}"), - } - } else { - bail!("unexpected error: {e:?}"); - } - } - }; - - config_file.pop(); - config_file.push("groups"); - let groups = Groups::load(&config_file, &config).context("failed to load groups")?; + let groups = Groups::load().context("failed to load groups")?; if groups.is_empty() { log::warn!("no group files found"); } - main_arguments.run(&groups, &config) -} - -fn load_default_config(config_file: &Path) -> Result { - if get_config_path_old_version()?.exists() { - println!("{MAJOR_UPDATE_MESSAGE}"); - } - - if !config_file.exists() { - create_empty_config_file(config_file)?; - } - - Ok(Config::default()) -} + main_arguments.run(&groups, &config)?; -fn create_empty_config_file(config_file: &Path) -> Result<()> { - let config_dir = &config_file.parent().context("getting parent dir")?; - std::fs::create_dir_all(config_dir).context("creating parent dir")?; - std::fs::File::create(config_file).context("creating empty config file")?; Ok(()) } diff --git a/src/path.rs b/src/path.rs deleted file mode 100644 index 5c26c5a..0000000 --- a/src/path.rs +++ /dev/null @@ -1,181 +0,0 @@ -/*! -All functions related to `pacdef`'s internal paths. -*/ - -use std::path::PathBuf; -use std::{env, path::Path}; - -use anyhow::{Context, Result}; -use path_absolutize::Absolutize; - -const CONFIG_FILE_NAME: &str = "pacdef.toml"; -const CONFIG_FILE_NAME_OLD: &str = "pacdef.yaml"; - -/// Get the group directory where all group files are located. This is -/// `$XDG_CONFIG_HOME/pacdef/groups`, which defaults to `$HOME/.config/pacdef/groups`. -/// -/// # Errors -/// -/// This function returns an error if both `$XDG_CONFIG_HOME` and `$HOME` are undefined. -pub fn get_group_dir() -> Result { - let mut result = get_pacdef_base_dir().context("getting pacdef base dir")?; - result.push("groups"); - Ok(result) -} - -/// Get the base directory for `pacdef`'s config files. -/// -/// # Errors -/// -/// This function will return an error if `$XDG_CONFIG_HOME` cannot be determined. -pub fn get_pacdef_base_dir() -> Result { - let mut dir = get_xdg_config_home().context("getting XDG_CONFIG_HOME")?; - dir.push("pacdef"); - Ok(dir) -} - -/// Get the path to the cargo home directory. -/// -/// # Errors -/// -/// This function will return an error if neither the `$CARGO_HOME` nor -/// the `$HOME` environment variables are set. -pub fn get_cargo_home() -> Result { - if let Ok(config) = env::var("CARGO_HOME") { - Ok(config.into()) - } else { - let mut config = get_home_dir().context("falling back to $HOME/.cargo")?; - config.push(".cargo"); - Ok(config) - } -} - -/// Get the path to the XDG config directory. -/// -/// # Errors -/// -/// This function will return an error if neither the `$XDG_CONFIG_HOME` nor -/// the `$HOME` environment variables are set. -fn get_xdg_config_home() -> Result { - if let Ok(config) = env::var("XDG_CONFIG_HOME") { - Ok(config.into()) - } else { - let mut config = get_home_dir().context("falling back to $HOME/.config")?; - config.push(".config"); - Ok(config) - } -} - -/// Get the home directory of the current user from the `$HOME` environment -/// variable. -/// -/// # Errors -/// -/// This function will return an error if the `$HOME` variable is not set. -pub fn get_home_dir() -> Result { - Ok(env::var("HOME").context("getting $HOME variable")?.into()) -} - -/// Get the path to the pacdef config file. This is `$XDG_CONFIG_HOME/pacdef/pacdef.toml`. -/// -/// # Errors -/// -/// This function returns an error if both `$XDG_CONFIG_HOME` and `$HOME` are -/// undefined. -pub fn get_config_path() -> Result { - let mut file = get_pacdef_base_dir().context("getting pacdef base dir for config file")?; - file.push(CONFIG_FILE_NAME); - Ok(file) -} - -/// Get the path to the pacdef config file from version 0.x. This is -/// `$XDG_CONFIG_HOME/pacdef/pacdef.conf`. -/// -/// # Errors -/// -/// This function returns an error if both `$XDG_CONFIG_HOME` and `$HOME` are -/// undefined. -pub fn get_config_path_old_version() -> Result { - let mut file = get_pacdef_base_dir().context("getting pacdef base dir for config file")?; - file.push(CONFIG_FILE_NAME_OLD); - Ok(file) -} - -/// Determine if a program `name` exists in the folders in the `$PATH` variable. -/// -/// # Errors -/// -/// This function returns an error if `$PATH` is not set. -pub fn binary_in_path(name: &str) -> Result { - let paths = env::var_os("PATH").context("getting $PATH")?; - for dir in env::split_paths(&paths) { - let full_path = dir.join(name); - if full_path.is_file() { - return Ok(true); - } - } - Ok(false) -} - -/// Determine the relative path of `full_path` in relation to `base_path`. -/// -/// # Panics -/// -/// Panics if at least one element in `base_path` does not match the corresponding -/// element in `full_path`. -pub fn get_relative_path

(full_path: P, base_path: P) -> PathBuf -where - P: AsRef, -{ - let mut file_iter = full_path.as_ref().iter(); - base_path - .as_ref() - .iter() - .zip(&mut file_iter) - .for_each(|(a, b)| assert_eq!(a, b)); - let relative_path: PathBuf = file_iter.collect(); - relative_path -} - -/// For each file argument, return the absolute path to the file. -/// -/// # Errors -/// -/// Returns an error if any of the files cannot be absolutized. -pub fn get_absolutized_file_paths(arg_match: &[String]) -> Result> { - let mut result = vec![]; - - for item in arg_match { - let path: PathBuf = item.into(); - let absolute = path - .absolutize() - .with_context(|| format!("absolutizing {path:?}"))? - .into_owned(); - result.push(absolute); - } - - Ok(result) -} - -#[cfg(test)] -mod tests { - use std::path::PathBuf; - - use super::get_relative_path; - - #[test] - fn relative_path() { - let full = PathBuf::from("/a/b/c/d/e"); - let base = PathBuf::from("/a/b/c"); - let relative = get_relative_path(full, base); - assert_eq!(relative, PathBuf::from("d/e")); - } - - #[test] - #[should_panic] - fn relative_path_panic() { - let full = PathBuf::from("/a/b/z/d/e"); - let base = PathBuf::from("/a/b/c"); - get_relative_path(full, base); - } -} diff --git a/src/prelude.rs b/src/prelude.rs index 21e4dd3..66621ec 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -16,15 +16,5 @@ pub use crate::cli::SyncPackageAction; pub use crate::cli::UnmanagedPackageAction; pub use crate::cli::VersionArguments; pub use crate::config::Config; -pub use crate::errors::Error; pub use crate::groups::Groups; pub use crate::packages::{PackagesIds, PackagesInstall, PackagesQuery, PackagesRemove}; -pub use crate::path::binary_in_path; -pub use crate::path::get_absolutized_file_paths; -pub use crate::path::get_cargo_home; -pub use crate::path::get_config_path; -pub use crate::path::get_config_path_old_version; -pub use crate::path::get_group_dir; -pub use crate::path::get_home_dir; -pub use crate::path::get_pacdef_base_dir; -pub use crate::path::get_relative_path; From 047da58e5ac95aad37947a6e89c5394490bf61c6 Mon Sep 17 00:00:00 2001 From: ripytide Date: Thu, 29 Aug 2024 14:30:28 +0100 Subject: [PATCH 2/3] fix apt prelude imports and macro missing --- src/backend/mod.rs | 1 - src/packages.rs | 1 + src/prelude.rs | 2 +- 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/backend/mod.rs b/src/backend/mod.rs index 8d0e580..b970b14 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -12,7 +12,6 @@ use std::{collections::BTreeMap, str::FromStr}; use crate::prelude::*; use anyhow::{Context, Result}; -use apt::Apt; #[derive(Debug, Copy, Clone, derive_more::Display)] pub enum AnyBackend { diff --git a/src/packages.rs b/src/packages.rs index f6bea36..1df1e3c 100644 --- a/src/packages.rs +++ b/src/packages.rs @@ -289,6 +289,7 @@ macro_rules! generate_structs { } generate_structs!( + apt: Apt, arch: Arch, cargo: Cargo, dnf: Dnf, diff --git a/src/prelude.rs b/src/prelude.rs index 66621ec..4a8ae3b 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -1,4 +1,4 @@ -// pub use crate::backend::apt::{Apt, AptMakeImplicit, AptQueryInfo}; +pub use crate::backend::apt::{Apt, AptMakeImplicit, AptQueryInfo}; pub use crate::backend::arch::{Arch, ArchMakeImplicit, ArchQueryInfo}; pub use crate::backend::cargo::Cargo; pub use crate::backend::dnf::{Dnf, DnfInstallOptions, DnfQueryInfo}; From 820595aa1c8e009472c6cf0dc87cb59cff770feb Mon Sep 17 00:00:00 2001 From: ripytide Date: Thu, 29 Aug 2024 17:31:37 +0100 Subject: [PATCH 3/3] switch to home library for getting the cargo home directory --- Cargo.lock | 10 ++++++++++ Cargo.toml | 1 + src/backend/cargo.rs | 4 ++-- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ddd42b1..a3f8b1d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -249,6 +249,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" +[[package]] +name = "home" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5" +dependencies = [ + "windows-sys 0.52.0", +] + [[package]] name = "humantime" version = "2.1.0" @@ -341,6 +350,7 @@ dependencies = [ "derive_more", "dirs", "enum_dispatch", + "home", "itertools", "libc", "log", diff --git a/Cargo.toml b/Cargo.toml index 1c88339..a0e1649 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,7 @@ toml = "0.8" derive_more = "0.99" itertools = "0.12" dirs = "5.0.1" +home = "0.5.9" pretty_env_logger = "0.5.0" [profile.release] diff --git a/src/backend/cargo.rs b/src/backend/cargo.rs index bae56b5..6e99682 100644 --- a/src/backend/cargo.rs +++ b/src/backend/cargo.rs @@ -22,8 +22,8 @@ impl Backend for Cargo { return Ok(BTreeMap::new()); } - let file = dirs::home_dir() - .context("getting the home directory")? + let file = home::cargo_home() + .context("getting the cargo home directory")? .join(".crates2.json"); let contents = match std::fs::read_to_string(file) {