logging refactor

This commit is contained in:
ripytide
2024-04-23 14:56:36 +01:00
parent 86880212c1
commit c290247c7a
9 changed files with 115 additions and 60 deletions
Generated
+78
View File
@@ -228,6 +228,42 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "env_filter"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a009aa4810eb158359dda09d0c87378e4bbb89b5a801f016885a4707ba24f7ea"
dependencies = [
"log",
"regex",
]
[[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 = "env_logger"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38b35839ba51819680ba087cd351788c9a3c476841207e0b8cee0b04722343b9"
dependencies = [
"anstream",
"anstyle",
"env_filter",
"humantime",
"log",
]
[[package]] [[package]]
name = "errno" name = "errno"
version = "0.3.8" version = "0.3.8"
@@ -244,6 +280,29 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hermit-abi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
[[package]]
name = "humantime"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
[[package]]
name = "is-terminal"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f23ff5ef2b80d608d61efee834934d862cd92461afc0560dedf493e4c033738b"
dependencies = [
"hermit-abi",
"libc",
"windows-sys 0.52.0",
]
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.11" version = "1.0.11"
@@ -271,6 +330,12 @@ version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c"
[[package]]
name = "log"
version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
[[package]] [[package]]
name = "memchr" name = "memchr"
version = "2.7.2" version = "2.7.2"
@@ -292,8 +357,11 @@ dependencies = [
"clap", "clap",
"const_format", "const_format",
"enum_dispatch", "enum_dispatch",
"env_logger 0.11.3",
"libc", "libc",
"log",
"path-absolutize", "path-absolutize",
"pretty_env_logger",
"regex", "regex",
"rust-apt", "rust-apt",
"serde", "serde",
@@ -327,6 +395,16 @@ version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec"
[[package]]
name = "pretty_env_logger"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "865724d4dbe39d9f3dd3b52b88d859d66bcb2d6a0acfd5ea68a65fb66d4bdc1c"
dependencies = [
"env_logger 0.10.2",
"log",
]
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.79" version = "1.0.79"
+3
View File
@@ -20,6 +20,9 @@ termios = "0.3"
walkdir = "2.5" walkdir = "2.5"
libc = "0.2" libc = "0.2"
enum_dispatch = "0.3" enum_dispatch = "0.3"
log = "0.4"
pretty_env_logger = "0.5"
env_logger = "0.11"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
+1 -3
View File
@@ -47,9 +47,7 @@ impl Backend for Rust {
let content = match read_to_string(file) { let content = match read_to_string(file) {
Ok(string) => string, Ok(string) => string,
Err(err) if err.kind() == NotFound => { Err(err) if err.kind() == NotFound => {
eprintln!( log::warn!("no crates file found for cargo. Assuming no crates installed yet.");
"WARNING: no crates file found for cargo. Assuming no crates installed yet."
);
return Ok(HashSet::new()); return Ok(HashSet::new());
} }
Err(err) => bail!(err), Err(err) => bail!(err),
+7 -31
View File
@@ -78,10 +78,6 @@ impl GroupArguments {
impl EditGroupAction { impl EditGroupAction {
fn run(self, groups: &Groups) -> Result<()> { 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) let group_files: Vec<_> = find_groups_by_name(&self.edit_groups, groups)
.context("getting group files for args")? .context("getting group files for args")?
.into_iter() .into_iter()
@@ -171,7 +167,7 @@ impl ImportGroupAction {
.context("filename is not valid UTF-8")?; .context("filename is not valid UTF-8")?;
if !target.exists() { if !target.exists() {
eprintln!("file {target_name} does not exist, skipping"); log::warn!("file {target_name} does not exist, skipping");
continue; continue;
} }
@@ -179,7 +175,7 @@ impl ImportGroupAction {
link.push(target_name); link.push(target_name);
if link.exists() { if link.exists() {
eprintln!("group {target_name} already exists, skipping"); log::warn!("group {target_name} already exists, skipping");
} else { } else {
symlink(target, link)?; symlink(target, link)?;
} }
@@ -195,10 +191,6 @@ impl ListGroupAction {
/// This methods cannot return an error. It returns a `Result` to be consistent /// This methods cannot return an error. It returns a `Result` to be consistent
/// with other methods. /// with other methods.
fn run(self, groups: &Groups) -> Result<()> { fn run(self, groups: &Groups) -> Result<()> {
if groups.is_empty() {
eprintln!("WARNING: no group files found");
}
let mut vec: Vec<_> = groups.iter().collect(); let mut vec: Vec<_> = groups.iter().collect();
vec.sort_unstable(); vec.sort_unstable();
for g in vec { for g in vec {
@@ -264,10 +256,6 @@ impl NewGroupAction {
impl RemoveGroupAction { impl RemoveGroupAction {
fn run(self, groups: &Groups) -> Result<()> { 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)?; let found = find_groups_by_name(&self.remove_groups, groups)?;
for group in found { for group in found {
@@ -280,10 +268,6 @@ impl RemoveGroupAction {
impl ShowGroupAction { impl ShowGroupAction {
fn run(self, groups: &Groups) -> Result<()> { fn run(self, groups: &Groups) -> Result<()> {
if groups.is_empty() {
eprintln!("WARNING: no group files found");
}
let mut errors = vec![]; let mut errors = vec![];
let mut found_groups = vec![]; let mut found_groups = vec![];
@@ -416,10 +400,6 @@ impl UnmanagedPackageAction {
fn get_missing_packages(groups: &Groups, config: &Config) -> Result<ToDoPerBackend> { fn get_missing_packages(groups: &Groups, config: &Config) -> Result<ToDoPerBackend> {
let mut to_install = ToDoPerBackend::new(); let mut to_install = ToDoPerBackend::new();
if groups.is_empty() {
eprintln!("WARNING: no group files found");
}
for mut backend in AnyBackend::iter() { for mut backend in AnyBackend::iter() {
if config if config
.disabled_backends .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. /// This function will propagate errors from the individual backends.
fn get_unmanaged_packages(groups: &Groups, config: &Config) -> Result<ToDoPerBackend> { fn get_unmanaged_packages(groups: &Groups, config: &Config) -> Result<ToDoPerBackend> {
if groups.is_empty() {
eprintln!("WARNING: no group files found");
}
let mut result = ToDoPerBackend::new(); let mut result = ToDoPerBackend::new();
for mut backend in AnyBackend::iter() { for mut backend in AnyBackend::iter() {
@@ -579,12 +555,12 @@ fn find_groups_by_name<'a>(names: &[String], groups: &'a Groups) -> Result<Vec<&
fn show_backend_query_error(error: &anyhow::Error, backend: &AnyBackend) { fn show_backend_query_error(error: &anyhow::Error, backend: &AnyBackend) {
let section = backend.get_section(); let section = backend.get_section();
if should_print_debug_info() { if should_print_debug_info() {
eprintln!("WARNING: skipping backend '{section}':"); log::warn!(
for err in error.chain() { "skipping backend '{section}': {}",
eprintln!(" {err}"); error.chain().map(|x| x.to_string()).collect::<String>()
} );
} else { } else {
eprintln!("WARNING: skipping backend '{section}': {error}"); log::warn!("skipping backend '{section}': {error}");
} }
} }
+12 -19
View File
@@ -1,5 +1,5 @@
use std::error::Error as ErrorTrait; use std::error::Error as ErrorTrait;
use std::fmt::{Display, Write}; use std::fmt::Display;
use std::path::PathBuf; use std::path::PathBuf;
/// Error types for pacdef. /// Error types for pacdef.
@@ -23,26 +23,19 @@ pub enum Error {
impl Display for Error { impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
Self::NoPackagesFound => f.write_str("no packages matching query"), Self::NoPackagesFound => write!(f, "no packages matching query"),
Self::ConfigFileNotFound => f.write_str("config file not found"), Self::ConfigFileNotFound => write!(f, "config file not found"),
Self::GroupFileNotFound(name) => f.write_str(&format!("group file '{name}' not found")), Self::GroupFileNotFound(name) => write!(f, "group file '{name}' not found"),
Self::GroupAlreadyExists(path) => f.write_str(&format!( Self::GroupAlreadyExists(path) => {
"group file '{}' already exists", write!(f, "group file '{}' already exists", path.to_string_lossy())
path.to_string_lossy()
)),
Self::InvalidGroupName(name) => {
f.write_str(&format!("group name '{name}' is not valid"))
} }
Self::InvalidGroupName(name) => write!(f, "group name '{name}' is not valid"),
Self::MultipleGroupsNotFound(vec) => { Self::MultipleGroupsNotFound(vec) => {
f.write_str("could not find the following groups:\n")?; write!(
let mut iter = vec.iter().peekable(); f,
while let Some(group) = iter.next() { "could not find the following groups: [{}]",
f.write_str(&format!(" {group}"))?; vec.join(", ")
if iter.peek().is_some() { )
f.write_char('\n')?;
}
}
Ok(())
} }
} }
} }
+2 -2
View File
@@ -153,13 +153,13 @@ impl Group {
} }
Err(e) => { Err(e) => {
let err = e.root_cause(); 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() { if sections.is_empty() {
eprintln!("WARNING: no sections found in group '{name}'"); log::warn!("no sections found in group '{name}'");
} }
let path = path.into(); let path = path.into();
+1 -1
View File
@@ -41,7 +41,7 @@ fn insert_package(package: Package, packages: &mut HashSet<Package>) {
let newly_inserted = packages.insert(package); let newly_inserted = packages.insert(package);
if !newly_inserted { if !newly_inserted {
eprintln!("warning: {package_name} occurs twice in the same section"); log::warn!("{package_name} occurs twice in the same section");
} }
} }
+11 -3
View File
@@ -32,6 +32,10 @@ This message will not appear again.
------"; ------";
fn main() -> ExitCode { fn main() -> ExitCode {
pretty_env_logger::formatted_builder()
.filter_level(log::LevelFilter::Info)
.init();
handle_final_result(main_inner()) handle_final_result(main_inner())
} }
@@ -43,7 +47,7 @@ fn handle_final_result(result: Result<()>) -> ExitCode {
Ok(_) => ExitCode::SUCCESS, Ok(_) => ExitCode::SUCCESS,
Err(ref e) => { Err(ref e) => {
if let Some(root_error) = e.root_cause().downcast_ref::<PacdefError>() { if let Some(root_error) = e.root_cause().downcast_ref::<PacdefError>() {
eprintln!("{root_error}"); log::error!("{root_error}");
ExitCode::FAILURE ExitCode::FAILURE
} else { } else {
result.report() result.report()
@@ -75,10 +79,14 @@ fn main_inner() -> Result<()> {
let groups = Group::load(&group_dir, config.warn_not_symlinks) let groups = Group::load(&group_dir, config.warn_not_symlinks)
.with_context(|| format!("loading groups under {}", group_dir.to_string_lossy()))?; .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() { for group in groups.iter() {
if group.warn_symlink { if group.warn_symlink {
eprintln!( log::warn!(
"WARNING: group file {} is not a symlink", "group file {} is not a symlink",
group.path.to_string_lossy() group.path.to_string_lossy()
); );
} }
-1
View File
@@ -20,7 +20,6 @@ use crate::{
/// - no matching packages could be found. /// - no matching packages could be found.
pub fn search_packages(regex_str: &str, groups: &Groups) -> Result<()> { pub fn search_packages(regex_str: &str, groups: &Groups) -> Result<()> {
if groups.is_empty() { if groups.is_empty() {
eprintln!("WARNING: no group files found");
bail!(crate::errors::Error::NoPackagesFound); bail!(crate::errors::Error::NoPackagesFound);
} }