diff --git a/Cargo.lock b/Cargo.lock index 2f73403..fd5e17f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -271,6 +271,12 @@ version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" +[[package]] +name = "log" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" + [[package]] name = "memchr" version = "2.7.2" @@ -293,6 +299,7 @@ dependencies = [ "const_format", "enum_dispatch", "libc", + "log", "path-absolutize", "regex", "rust-apt", diff --git a/crates/pacdef/Cargo.toml b/crates/pacdef/Cargo.toml index bd71cad..1d47365 100644 --- a/crates/pacdef/Cargo.toml +++ b/crates/pacdef/Cargo.toml @@ -20,6 +20,7 @@ termios = "0.3" walkdir = "2.5" libc = "0.2" enum_dispatch = "0.3" +log = { version = "0.4", features = ["std"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" diff --git a/crates/pacdef/src/backend/actual/rust.rs b/crates/pacdef/src/backend/actual/rust.rs index 95e3058..9bf9612 100644 --- a/crates/pacdef/src/backend/actual/rust.rs +++ b/crates/pacdef/src/backend/actual/rust.rs @@ -47,9 +47,7 @@ impl Backend for Rust { let content = match read_to_string(file) { Ok(string) => string, Err(err) if err.kind() == NotFound => { - eprintln!( - "WARNING: no crates file found for cargo. Assuming no crates installed yet." - ); + log::warn!("no crates file found for cargo. Assuming no crates installed yet."); return Ok(HashSet::new()); } Err(err) => bail!(err), diff --git a/crates/pacdef/src/core.rs b/crates/pacdef/src/core.rs index 417ffb3..2d121ca 100644 --- a/crates/pacdef/src/core.rs +++ b/crates/pacdef/src/core.rs @@ -78,10 +78,6 @@ impl GroupArguments { impl EditGroupAction { fn run(self, groups: &Groups) -> Result<()> { - if groups.is_empty() { - eprintln!("WARNING: no group files found"); - } - let group_files: Vec<_> = find_groups_by_name(&self.edit_groups, groups) .context("getting group files for args")? .into_iter() @@ -171,7 +167,7 @@ impl ImportGroupAction { .context("filename is not valid UTF-8")?; if !target.exists() { - eprintln!("file {target_name} does not exist, skipping"); + log::warn!("file {target_name} does not exist, skipping"); continue; } @@ -179,7 +175,7 @@ impl ImportGroupAction { link.push(target_name); if link.exists() { - eprintln!("group {target_name} already exists, skipping"); + log::warn!("group {target_name} already exists, skipping"); } else { symlink(target, link)?; } @@ -195,10 +191,6 @@ impl ListGroupAction { /// This methods cannot return an error. It returns a `Result` to be consistent /// with other methods. fn run(self, groups: &Groups) -> Result<()> { - if groups.is_empty() { - eprintln!("WARNING: no group files found"); - } - let mut vec: Vec<_> = groups.iter().collect(); vec.sort_unstable(); for g in vec { @@ -264,10 +256,6 @@ impl NewGroupAction { impl RemoveGroupAction { fn run(self, groups: &Groups) -> Result<()> { - if groups.is_empty() { - eprintln!("WARNING: no group files found"); - } - let found = find_groups_by_name(&self.remove_groups, groups)?; for group in found { @@ -280,10 +268,6 @@ impl RemoveGroupAction { impl ShowGroupAction { fn run(self, groups: &Groups) -> Result<()> { - if groups.is_empty() { - eprintln!("WARNING: no group files found"); - } - let mut errors = vec![]; let mut found_groups = vec![]; @@ -416,10 +400,6 @@ impl UnmanagedPackageAction { fn get_missing_packages(groups: &Groups, config: &Config) -> Result { let mut to_install = ToDoPerBackend::new(); - if groups.is_empty() { - eprintln!("WARNING: no group files found"); - } - for mut backend in AnyBackend::iter() { if config .disabled_backends @@ -470,10 +450,6 @@ fn overwrite_values_from_config(backend: &mut AnyBackend, config: &Config) { /// /// This function will propagate errors from the individual backends. fn get_unmanaged_packages(groups: &Groups, config: &Config) -> Result { - if groups.is_empty() { - eprintln!("WARNING: no group files found"); - } - let mut result = ToDoPerBackend::new(); for mut backend in AnyBackend::iter() { @@ -579,12 +555,12 @@ fn find_groups_by_name<'a>(names: &[String], groups: &'a Groups) -> Result() + ); } else { - eprintln!("WARNING: skipping backend '{section}': {error}"); + log::warn!("skipping backend '{section}': {error}"); } } diff --git a/crates/pacdef/src/errors.rs b/crates/pacdef/src/errors.rs index 2207c11..54457e0 100644 --- a/crates/pacdef/src/errors.rs +++ b/crates/pacdef/src/errors.rs @@ -1,5 +1,5 @@ use std::error::Error as ErrorTrait; -use std::fmt::{Display, Write}; +use std::fmt::Display; use std::path::PathBuf; /// Error types for pacdef. @@ -23,26 +23,19 @@ pub enum Error { impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::NoPackagesFound => f.write_str("no packages matching query"), - Self::ConfigFileNotFound => f.write_str("config file not found"), - Self::GroupFileNotFound(name) => f.write_str(&format!("group file '{name}' not found")), - Self::GroupAlreadyExists(path) => f.write_str(&format!( - "group file '{}' already exists", - path.to_string_lossy() - )), - Self::InvalidGroupName(name) => { - f.write_str(&format!("group name '{name}' is not valid")) + Self::NoPackagesFound => write!(f, "no packages matching query"), + 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) => { - f.write_str("could not find the following groups:\n")?; - let mut iter = vec.iter().peekable(); - while let Some(group) = iter.next() { - f.write_str(&format!(" {group}"))?; - if iter.peek().is_some() { - f.write_char('\n')?; - } - } - Ok(()) + write!( + f, + "could not find the following groups: [{}]", + vec.join(", ") + ) } } } diff --git a/crates/pacdef/src/grouping/group.rs b/crates/pacdef/src/grouping/group.rs index 50f6c8b..a579ae4 100644 --- a/crates/pacdef/src/grouping/group.rs +++ b/crates/pacdef/src/grouping/group.rs @@ -153,13 +153,13 @@ impl Group { } Err(e) => { let err = e.root_cause(); - eprintln!("WARNING: could not process a section under group '{name}': {err}"); + log::warn!("could not process a section under group '{name}': {err}"); } } } if sections.is_empty() { - eprintln!("WARNING: no sections found in group '{name}'"); + log::warn!("no sections found in group '{name}'"); } let path = path.into(); diff --git a/crates/pacdef/src/grouping/section.rs b/crates/pacdef/src/grouping/section.rs index 62ffa36..bbb8e07 100644 --- a/crates/pacdef/src/grouping/section.rs +++ b/crates/pacdef/src/grouping/section.rs @@ -41,7 +41,7 @@ fn insert_package(package: Package, packages: &mut HashSet) { let newly_inserted = packages.insert(package); if !newly_inserted { - eprintln!("warning: {package_name} occurs twice in the same section"); + log::warn!("{package_name} occurs twice in the same section"); } } diff --git a/crates/pacdef/src/main.rs b/crates/pacdef/src/main.rs index c1782e2..e716c13 100644 --- a/crates/pacdef/src/main.rs +++ b/crates/pacdef/src/main.rs @@ -31,7 +31,27 @@ Check out https://github.com/steven-omaha/pacdef/blob/main/README.md#configurati 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()) } @@ -43,7 +63,7 @@ fn handle_final_result(result: Result<()>) -> ExitCode { Ok(_) => ExitCode::SUCCESS, Err(ref e) => { if let Some(root_error) = e.root_cause().downcast_ref::() { - eprintln!("{root_error}"); + log::error!("{root_error}"); ExitCode::FAILURE } else { result.report() @@ -75,10 +95,14 @@ fn main_inner() -> Result<()> { let groups = Group::load(&group_dir, config.warn_not_symlinks) .with_context(|| format!("loading groups under {}", group_dir.to_string_lossy()))?; + if groups.is_empty() { + log::warn!("no group files found"); + } + for group in groups.iter() { if group.warn_symlink { - eprintln!( - "WARNING: group file {} is not a symlink", + log::warn!( + "group file {} is not a symlink", group.path.to_string_lossy() ); } diff --git a/crates/pacdef/src/search.rs b/crates/pacdef/src/search.rs index c824670..a56a839 100644 --- a/crates/pacdef/src/search.rs +++ b/crates/pacdef/src/search.rs @@ -20,7 +20,6 @@ use crate::{ /// - no matching packages could be found. pub fn search_packages(regex_str: &str, groups: &Groups) -> Result<()> { if groups.is_empty() { - eprintln!("WARNING: no group files found"); bail!(crate::errors::Error::NoPackagesFound); }