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
+3
View File
@@ -20,6 +20,9 @@ termios = "0.3"
walkdir = "2.5"
libc = "0.2"
enum_dispatch = "0.3"
log = "0.4"
pretty_env_logger = "0.5"
env_logger = "0.11"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
+1 -3
View File
@@ -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),
+7 -31
View File
@@ -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<ToDoPerBackend> {
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<ToDoPerBackend> {
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<Vec<&
fn show_backend_query_error(error: &anyhow::Error, backend: &AnyBackend) {
let section = backend.get_section();
if should_print_debug_info() {
eprintln!("WARNING: skipping backend '{section}':");
for err in error.chain() {
eprintln!(" {err}");
}
log::warn!(
"skipping backend '{section}': {}",
error.chain().map(|x| x.to_string()).collect::<String>()
);
} 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::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(", ")
)
}
}
}
+2 -2
View File
@@ -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();
+1 -1
View File
@@ -41,7 +41,7 @@ fn insert_package(package: Package, packages: &mut HashSet<Package>) {
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");
}
}
+11 -3
View File
@@ -32,6 +32,10 @@ This message will not appear again.
------";
fn main() -> ExitCode {
pretty_env_logger::formatted_builder()
.filter_level(log::LevelFilter::Info)
.init();
handle_final_result(main_inner())
}
@@ -43,7 +47,7 @@ fn handle_final_result(result: Result<()>) -> ExitCode {
Ok(_) => ExitCode::SUCCESS,
Err(ref e) => {
if let Some(root_error) = e.root_cause().downcast_ref::<PacdefError>() {
eprintln!("{root_error}");
log::error!("{root_error}");
ExitCode::FAILURE
} else {
result.report()
@@ -75,10 +79,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()
);
}
-1
View File
@@ -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);
}