Replace print_warning and print_error utility functions with macros

- Implement `eprintln_warn` and `eprintln_warn` macros.
- Move generalised, utility macros to the utils module.
- Refactor `format_str` to `format_static`.
- Remove re-exports of ansi functions from utils module.
This commit is contained in:
Xavier Moffett 2025-02-09 23:03:42 -05:00
parent f5e5c01697
commit e790ddaaa3
Signed by: Sapphirus
GPG key ID: A6C061B2CEA1A7AC
15 changed files with 101 additions and 95 deletions

View file

@ -28,6 +28,7 @@ use serde::Deserialize;
use pacwrap_core::{
config::Global,
constants::{VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH},
eprintln_warn,
err,
log::{Level, Logger},
sync::{
@ -42,7 +43,7 @@ use pacwrap_core::{
AlpmConfigData,
SyncError,
},
utils::{bytebuffer::ByteBuffer, print_warning},
utils::{ansi::*, bytebuffer::ByteBuffer},
Error,
ErrorGeneric,
Result,
@ -139,7 +140,7 @@ fn conduct_transaction(
if error.kind() != NotFound {
let message = &format!("Failed to propagate ld.so.cache: {}", error);
print_warning(message);
eprintln_warn!("{}", message);
logger.log(Level::Warn, message)?;
}
}

View file

@ -26,8 +26,9 @@ use crate::{
permission::{Condition::Success, *},
Permission,
},
eprintln_warn,
exec::args::ExecutionArgs,
utils::print_warning,
utils::ansi::*,
};
#[derive(Debug, Clone, Serialize, Deserialize)]
@ -78,7 +79,7 @@ fn env_var(var: &String, set: &String) -> String {
match env::var(var) {
Ok(env) => env,
Err(_) => {
print_warning(&format!("Environment variable {} is unset.", var));
eprintln_warn!("Environment variable {} is unset.", var);
"".into()
}
}

View file

@ -26,11 +26,12 @@ use crate::{
Dbus,
Permission,
},
eprintln_warn,
err,
error,
error::*,
exec::args::ExecutionArgs,
utils::print_warning,
utils::ansi::*,
};
pub fn register_filesystems(per: &Vec<Box<dyn Filesystem>>, vars: &ContainerVariables, args: &mut ExecutionArgs) -> Result<()> {
@ -55,7 +56,7 @@ pub fn register_permissions(per: &[Box<dyn Permission>], args: &mut ExecutionArg
p.register(args);
if let Condition::SuccessWarn(warning) = b {
print_warning(&format!("{}: {} ", p.module(), warning));
eprintln_warn!("{}: {} ", p.module(), warning);
}
}
None => continue,

View file

@ -22,7 +22,7 @@ use std::{env::var, process::id, time::Duration};
use nix::unistd::{getegid, geteuid};
use signal_hook::consts::*;
use crate::{error, utils::unix_epoch_time, Error, ErrorKind};
use crate::{error, format_static, lazy_lock, utils::unix_epoch_time, Error, ErrorKind};
pub use crate::utils::ansi::*;
@ -40,29 +40,6 @@ const PACWRAP_CONFIG_DIR: &str = "/.config/pacwrap";
const PACWRAP_DATA_DIR: &str = "/.local/share/pacwrap";
const PACWRAP_CACHE_DIR: &str = "/.cache/pacwrap";
#[macro_export]
macro_rules! lazy_lock {
( $v:vis static ref $x:ident: $y:ty = $z: expr; $($t:tt)* ) => {
$v static $x: std::sync::LazyLock<$y> = std::sync::LazyLock::new(|| $z);
lazy_lock!($($t)*);
};
() => ()
}
#[macro_export]
macro_rules! format_str {
( $( $x:expr ),+ ) => {
format!($( $x, )+).leak()
};
}
#[macro_export]
macro_rules! to_static_str {
( $x:expr ) => {
$x.to_string().leak()
};
}
lazy_lock! {
pub static ref VERBOSE: bool = var("PACWRAP_VERBOSE").is_ok_and(|v| v == "1");
pub static ref UID: u32 = geteuid().as_raw();
@ -78,16 +55,16 @@ lazy_lock! {
pub static ref EDITOR: &'static str = env_default("EDITOR", "vi");
pub static ref X11_DISPLAY: &'static str = env_opt("DISPLAY");
pub static ref XAUTHORITY: &'static str = env_opt("XAUTHORITY");
pub static ref LOCK_FILE: &'static str = format_str!("{}/pacwrap.lck", *DATA_DIR);
pub static ref CONTAINER_DIR: &'static str = format_str!("{}/root/", *DATA_DIR);
pub static ref LOCK_FILE: &'static str = format_static!("{}/pacwrap.lck", *DATA_DIR);
pub static ref CONTAINER_DIR: &'static str = format_static!("{}/root/", *DATA_DIR);
pub static ref CACHE_DIR: &'static str = env_default_dir("PACWRAP_CACHE_DIR", PACWRAP_CACHE_DIR);
pub static ref CONFIG_DIR: &'static str = env_default_dir("PACWRAP_CONFIG_DIR", PACWRAP_CONFIG_DIR);
pub static ref DATA_DIR: &'static str = env_default_dir("PACWRAP_DATA_DIR", PACWRAP_DATA_DIR);
pub static ref CONFIG_FILE: &'static str = format_str!("{}/pacwrap.yml", *CONFIG_DIR);
pub static ref CONFIG_FILE: &'static str = format_static!("{}/pacwrap.yml", *CONFIG_DIR);
pub static ref XDG_RUNTIME_DIR: String = format!("/run/user/{}", *UID);
pub static ref DBUS_SOCKET: String = format!("/run/user/{}/pacwrap_dbus_{}", *UID, &id());
pub static ref WAYLAND_SOCKET: String = format!("{}/{}", *XDG_RUNTIME_DIR, *WAYLAND_DISPLAY);
pub static ref LOG_LOCATION: &'static str = format_str!("{}/pacwrap.log", *DATA_DIR);
pub static ref LOG_LOCATION: &'static str = format_static!("{}/pacwrap.log", *DATA_DIR);
pub static ref UNIX_TIMESTAMP: u64 = unix_epoch_time().as_secs();
}
@ -104,5 +81,5 @@ fn env_default(env: &str, default: &'static str) -> &'static str {
}
fn env_default_dir(env: &str, default: &str) -> &'static str {
var(env).map_or_else(|_| format_str!("{}{}", *HOME, default), |var| var.leak())
var(env).map_or_else(|_| format_static!("{}{}", *HOME, default), |var| var.leak())
}

View file

@ -1,7 +1,7 @@
/*
* pacwrap-core
*
* Copyright (C) 2023-2024 Xavier Moffett <sapphirus@azorium.net>
* Copyright (C) 2023-2025 Xavier Moffett <sapphirus@azorium.net>
* SPDX-License-Identifier: GPL-3.0-only
*
* This library is free software: you can redistribute it and/or modify
@ -27,7 +27,7 @@ use std::{
result::Result as StdResult,
};
use crate::{config::ContainerCache, constants::CONTAINER_DIR, utils::print_warning, ErrorGeneric, Result};
use crate::{config::ContainerCache, constants::CONTAINER_DIR, eprintln_warn, utils::ansi::*, ErrorGeneric, Result};
use indexmap::IndexMap;
pub struct ProcessList {
@ -197,7 +197,7 @@ pub fn list<'a>(cache: &'a ContainerCache<'a>) -> Result<ProcessList> {
Some(vec) => vec.push(pid),
None => {
if cache.get_instance_option(&ins).is_none() {
print_warning(&format!("Container {ins} doesn't exist."));
eprintln_warn!("Container {ins} doesn't exist.");
}
groups.insert(ins.clone(), vec![pid]);

View file

@ -33,8 +33,9 @@ use zstd::Decoder;
use crate::{
config::ContainerHandle,
constants::{VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH},
eprintln_warn,
err,
utils::{bytebuffer::ByteBuffer, print_warning},
utils::{ansi::*, bytebuffer::ByteBuffer},
Error,
ErrorGeneric,
ErrorKind,
@ -181,7 +182,7 @@ pub fn version(inshandle: &ContainerHandle) -> Result<SchemaStatus> {
file.rewind().prepend_io(|| schema)?;
if magic != MAGIC_NUMBER {
print_warning(&format!("'{}': Magic number mismatch ({MAGIC_NUMBER} != {magic})", schema));
eprintln_warn!("'{}': Magic number mismatch ({MAGIC_NUMBER} != {magic})", schema);
Ok(OutOfDate(None))
} else if major.0 != major.1 || minor.0 != minor.1 || patch.0 != patch.1 {
Ok(OutOfDate(Some(

View file

@ -27,7 +27,7 @@ use serde::{Deserialize, Serialize};
use self::{SyncState::*, TransactionMode::*, TransactionType::*};
use crate::{
config::{global, ContainerHandle, Global},
constants::{ARROW_CYAN, BAR_CYAN, BOLD, BOLD_GREEN, BOLD_YELLOW, RESET},
eprintln_warn,
err,
log::{Level, Logger},
sync::{
@ -38,7 +38,7 @@ use crate::{
utils::AlpmUtils,
SyncError,
},
utils::{print_warning, prompt::prompt},
utils::{ansi::*, prompt::prompt},
Error,
};
@ -386,10 +386,15 @@ impl<'a> TransactionHandle<'a> {
let ver = package.version();
let ver_new = new.version();
print_warning(&format!(
eprintln_warn!(
"{}{name}{}: Ignoring package upgrade ({}{ver}{} => {}{ver_new}{})",
*BOLD, *RESET, *BOLD_YELLOW, *RESET, *BOLD_GREEN, *RESET
));
*BOLD,
*RESET,
*BOLD_YELLOW,
*RESET,
*BOLD_GREEN,
*RESET
);
}
Ok(())

View file

@ -1,7 +1,7 @@
/*
* pacwrap-core
*
* Copyright (C) 2023-2024 Xavier Moffett <sapphirus@azorium.net>
* Copyright (C) 2023-2025 Xavier Moffett <sapphirus@azorium.net>
* SPDX-License-Identifier: GPL-3.0-only
*
* This library is free software: you can redistribute it and/or modify
@ -31,15 +31,7 @@ use alpm::{
};
use signal_hook::iterator::Signals;
use crate::{
constants::{BOLD, BOLD_WHITE, RESET, SIGNAL_LIST},
err,
error,
sync::SyncError,
utils::{print_error, print_warning},
Error,
Result,
};
use crate::{constants::SIGNAL_LIST, eprintln_error, eprintln_warn, err, error, sync::SyncError, utils::ansi::*, Error, Result};
pub trait AlpmUtils {
fn get_local_package(&self, pkg: &str) -> Option<&Package>;
@ -103,16 +95,16 @@ pub fn erroneous_transaction(error: CommitError) -> Result<()> {
FileConflictType::Filesystem => {
let file = conflict.file();
let target = conflict.target();
print_warning(&format!("{}: '{}' already exists.", target, file));
eprintln_warn!("{}: '{}' already exists.", target, file);
}
FileConflictType::Target => {
let file = conflict.file();
let target = format!("{}{}{}", *BOLD_WHITE, conflict.target(), *RESET);
if let Some(conflicting) = conflict.conflicting_target() {
let conflicting = format!("{}{conflicting}{}", *BOLD_WHITE, *RESET);
print_warning(&format!("{conflicting}: '{target}' is owned by {file}"));
eprintln_warn!("{conflicting}: '{target}' is owned by {file}");
} else {
print_warning(&format!("{target}: '{file}' is owned by foreign target"));
eprintln_warn!("{target}: '{file}' is owned by foreign target");
}
}
}
@ -122,7 +114,7 @@ pub fn erroneous_transaction(error: CommitError) -> Result<()> {
}
CommitData::PkgInvalid(p) =>
for pkg in p.iter() {
print_error(&format!("Invalid package: {}{}{}", *BOLD_WHITE, pkg, *RESET));
eprintln_error!("Invalid package: {}{}{}", *BOLD_WHITE, pkg, *RESET);
},
}
}
@ -152,7 +144,7 @@ pub fn erroneous_preparation(error: PrepareError) -> Result<()> {
match error.data() {
PrepareData::PkgInvalidArch(list) =>
for package in list.iter() {
print_error(&format!(
eprintln_error!(
"Invalid architecture {}{}{} for {}{}{}",
*BOLD,
package.arch().unwrap_or("UNKNOWN"),
@ -160,11 +152,11 @@ pub fn erroneous_preparation(error: PrepareError) -> Result<()> {
*BOLD,
package.name(),
*RESET
));
);
},
PrepareData::UnsatisfiedDeps(list) =>
for missing in list.iter() {
print_error(&format!(
eprintln_error!(
"Unsatisifed dependency {}{}{} for target {}{}{}",
*BOLD,
missing.depend(),
@ -172,11 +164,11 @@ pub fn erroneous_preparation(error: PrepareError) -> Result<()> {
*BOLD,
missing.target(),
*RESET
));
);
},
PrepareData::ConflictingDeps(list) =>
for conflict in list.iter() {
print_error(&format!(
eprintln_error!(
"Conflict between {}{}{} and {}{}{}: {}",
*BOLD,
conflict.package1().name(),
@ -185,7 +177,7 @@ pub fn erroneous_preparation(error: PrepareError) -> Result<()> {
conflict.package2().name(),
*RESET,
conflict.reason()
));
);
},
}
}

View file

@ -1,7 +1,7 @@
/*
* pacwrap-core
*
* Copyright (C) 2023-2024 Xavier Moffett <sapphirus@azorium.net>
* Copyright (C) 2023-2025 Xavier Moffett <sapphirus@azorium.net>
* SPDX-License-Identifier: GPL-3.0-only
*
* This library is free software: you can redistribute it and/or modify
@ -25,14 +25,13 @@ use std::{
};
use crate::{
constants::{BOLD_RED, BOLD_YELLOW, GID, RESET, UID},
constants::{GID, UID},
err,
Error,
ErrorKind,
Result,
};
pub use ansi::{is_color_terminal, is_truecolor_terminal};
pub use arguments::Arguments;
pub use termcontrol::TermControl;
@ -43,24 +42,43 @@ pub mod prompt;
pub mod table;
pub mod termcontrol;
pub fn print_warning(message: &str) {
eprintln!("{}warning:{} {}", *BOLD_YELLOW, *RESET, message);
#[macro_export]
macro_rules! lazy_lock {
( $v:vis static ref $x:ident: $y:ty = $z: expr; $($t:tt)* ) => {
$v static $x: std::sync::LazyLock<$y> = std::sync::LazyLock::new(|| $z);
lazy_lock!($($t)*);
};
() => ()
}
pub fn print_error(message: &str) {
eprintln!("{}error:{} {}", *BOLD_RED, *RESET, message);
#[macro_export]
macro_rules! eprintln_warn {
( $( $x:expr ),+ ) => {
eprint!("{}warning:{} ", *BOLD_YELLOW, *RESET);
eprintln!($( $x, )+);
};
}
pub fn check_socket(socket: &String) -> bool {
UnixStream::connect(Path::new(socket)).is_ok()
#[macro_export]
macro_rules! eprintln_error {
( $( $x:expr ),+ ) => {
eprint!("{}error:{} ", *BOLD_RED, *RESET);
eprintln!($( $x, )+);
};
}
pub fn unix_epoch_time() -> Duration {
SystemTime::now().duration_since(UNIX_EPOCH).expect("SystemTime")
#[macro_export]
macro_rules! format_static {
( $( $x:expr ),+ ) => {
format!($( $x, )+).leak()
};
}
pub fn whitespace(amt: usize) -> String {
" ".repeat(amt)
#[macro_export]
macro_rules! to_static_str {
( $x:expr ) => {
$x.to_string().leak()
};
}
pub fn env_var(env: &'static str) -> Result<String> {
@ -77,3 +95,11 @@ pub fn check_root() -> Result<()> {
Ok(())
}
pub fn check_socket(socket: &String) -> bool {
UnixStream::connect(Path::new(socket)).is_ok()
}
pub fn unix_epoch_time() -> Duration {
SystemTime::now().duration_since(UNIX_EPOCH).expect("SystemTime")
}

View file

@ -21,7 +21,7 @@ use std::{collections::HashMap, path::Path};
use pacwrap_core::{
config::{cache, compose_handle, init::init, ContainerCache, ContainerHandle, ContainerType::*},
constants::{ARROW_GREEN, BAR_GREEN, BOLD, RESET},
eprintln_warn,
err,
lock::Lock,
log::{Level::Info, Logger},
@ -31,9 +31,9 @@ use pacwrap_core::{
transaction::{TransactionAggregator, TransactionFlags, TransactionType},
},
utils::{
ansi::*,
arguments::{Arguments, InvalidArgument::*, Operand as Op},
check_root,
print_warning,
prompt::prompt_targets,
},
Error,
@ -249,9 +249,9 @@ fn engage_aggregator(args: &mut Arguments, lock: &Lock) -> Result<()> {
}
if flags.contains(TransactionFlags::LAZY_LOAD_DB) {
print_warning("Database lazy-loading triggered by `-l/--lazy-load`; this feature is experimental.");
print_warning("In future, manual intervention may be required for missing dependencies.");
print_warning("See `--help compose` or the pacwrap(1) man page for further information.");
eprintln_warn!("Database lazy-loading triggered by `-l/--lazy-load`; this feature is experimental.");
eprintln_warn!("In future, manual intervention may be required for missing dependencies.");
eprintln_warn!("See `--help compose` or the pacwrap(1) man page for further information.");
}
cache = instantiate(compose_handles(&cache, compose)?, cache, lock, &mut logger)?;

View file

@ -23,7 +23,7 @@ use std::fmt::{Display, Formatter, Result as FmtResult};
use pacwrap_core::{
err,
impl_error,
utils::{arguments::Operand, is_color_terminal, Arguments},
utils::{ansi::is_color_terminal, arguments::Operand, Arguments},
Error,
ErrorTrait,
Result,

View file

@ -18,7 +18,7 @@
*/
use pacwrap_core::{
utils::{arguments::Operand, is_truecolor_terminal, Arguments},
utils::{ansi::is_truecolor_terminal, arguments::Operand, Arguments},
Result,
};

View file

@ -30,12 +30,13 @@ use nix::{
use pacwrap_core::{
config::cache,
constants::{ARROW_GREEN, BOLD, DIM, RESET},
eprintln_warn,
err,
impl_error,
process::{self, Process},
utils::{
ansi::*,
arguments::{InvalidArgument, Operand},
print_warning,
prompt::prompt_targets,
table::{ColumnAttribute, Table},
Arguments,
@ -288,7 +289,7 @@ fn process_kill(args: &mut Arguments) -> Result<()> {
}
fn fork_warn(process: &Process) {
print_warning(&format!(
eprintln_warn!(
"Process fork detected with PID {}{}{} from an instance of {}{}{}.",
*BOLD,
process.pid(),
@ -296,7 +297,7 @@ fn fork_warn(process: &Process) {
*BOLD,
process.instance(),
*RESET
));
);
}
fn kill_processes(process_list: &Vec<&Process>, sigint: Signal) -> Result<()> {

View file

@ -22,7 +22,7 @@ use std::collections::{HashMap, HashSet};
use indexmap::IndexMap;
use pacwrap_core::{
config::{cache, init::init, ConfigError::AlreadyExists, ContainerCache, ContainerType},
constants::{ARROW_GREEN, BAR_GREEN, BOLD, RESET},
eprintln_warn,
err,
error::*,
lock::Lock,
@ -33,9 +33,9 @@ use pacwrap_core::{
transaction::{TransactionAggregator, TransactionFlags, TransactionType},
},
utils::{
ansi::*,
arguments::{Arguments, InvalidArgument::*, Operand as Op},
check_root,
print_warning,
},
ErrorKind,
};
@ -246,9 +246,9 @@ fn engage_aggregator<'a>(
}
if flags.contains(TransactionFlags::LAZY_LOAD_DB) {
print_warning("Database lazy-loading triggered by `-l/--lazy-load`; this feature is experimental.");
print_warning("In future, manual intervention may be required for missing dependencies.");
print_warning("See `--help sync` or the pacwrap(1) man page for further information.");
eprintln_warn!("Database lazy-loading triggered by `-l/--lazy-load`; this feature is experimental.");
eprintln_warn!("In future, manual intervention may be required for missing dependencies.");
eprintln_warn!("See `--help sync` or the pacwrap(1) man page for further information.");
}
if !create_targets.is_empty() || init {

View file

@ -21,10 +21,11 @@ use std::process::Command;
use pacwrap_core::{
config,
eprintln_warn,
err,
utils::{
ansi::*,
arguments::{InvalidArgument, Operand},
print_warning,
Arguments,
},
Error,
@ -51,7 +52,7 @@ pub fn engage_utility(args: &mut Arguments) -> Result<()> {
Operand::Short('l') | Operand::Long("list") | Operand::Value("list") => Some("list"),
_ => None,
} {
print_warning(&format!("Command flow is deprecated. See `$ pacwrap --help {}` for further information.", option));
eprintln_warn!("Command flow is deprecated. See `$ pacwrap --help {}` for further information.", option);
}
match arg {