macro_rules! info {
(incoming, $($arg:tt)+) => {
::tracing::info!(status = "incoming", $($arg)+)
};
(outgoing, $($arg:tt)+) => {
::tracing::info!(status = "outgoing", $($arg)+)
};
($($arg:tt)+) => {
::tracing::info!(status = "info", $($arg)+)
};
}
macro_rules! success {
($($arg:tt)+) => {
::tracing::info!(status = "success", $($arg)+)
};
}
macro_rules! error {
($($arg:tt)+) => {
::tracing::error!(status = "error", $($arg)+)
};
}
macro_rules! warn_macro {
($($arg:tt)+) => {
::tracing::warn!(status = "warn", $($arg)+)
};
}
pub(crate) use error;
pub(crate) use info;
pub(crate) use success;
pub(crate) use warn_macro as warn;
pub(crate) fn counted(count: u128, one: &str, many: &str) -> String {
match count {
1 => format!("1 {one}"),
_ => format!("{count} {many}"),
}
}
#[cfg(test)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Logged {
pub(crate) level: tracing::Level,
pub(crate) verbosity: u64,
pub(crate) message: String,
}
#[cfg(test)]
impl tracing::field::Visit for Logged {
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
if field.name() == "message" {
self.message = format!("{value:?}");
}
}
fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
if field.name() == "verbosity" {
self.verbosity = value;
}
}
fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {
if field.name() == "verbosity" {
self.verbosity = u64::try_from(value).unwrap_or(u64::MAX);
}
}
}
#[cfg(test)]
pub(crate) fn logged(run: impl FnOnce()) -> Vec<Logged> {
use std::sync::{Arc, Mutex};
use tracing::span::{Attributes, Id, Record};
struct Recorder(Arc<Mutex<Vec<Logged>>>);
impl tracing::Subscriber for Recorder {
fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
true
}
fn new_span(&self, _: &Attributes<'_>) -> Id {
Id::from_u64(1)
}
fn record(&self, _: &Id, _: &Record<'_>) {}
fn record_follows_from(&self, _: &Id, _: &Id) {}
fn event(&self, event: &tracing::Event<'_>) {
let mut logged = Logged {
level: *event.metadata().level(),
verbosity: 0,
message: String::new(),
};
event.record(&mut logged);
self.0
.lock()
.unwrap_or_else(|held| held.into_inner())
.push(logged);
}
fn enter(&self, _: &Id) {}
fn exit(&self, _: &Id) {}
}
let lines = Arc::new(Mutex::new(Vec::new()));
tracing::subscriber::with_default(Recorder(Arc::clone(&lines)), run);
lines
.lock()
.unwrap_or_else(|held| held.into_inner())
.clone()
}
#[cfg(test)]
mod tests {
#[test]
fn every_diagnostic_is_written_in_one_voice() {
const MACROS: [&str; 4] = ["info!", "success!", "warn!", "error!"];
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut checked = 0;
for file in sources(&root) {
if file.file_name().is_some_and(|name| name == "logging.rs") {
continue;
}
let text = std::fs::read_to_string(&file).expect("a source file");
for (at, _) in MACROS.iter().flat_map(|name| text.match_indices(name)) {
let Some(message) = literal_after(&text, at) else {
continue;
};
let Some(first) = message.split_whitespace().next() else {
continue;
};
if message.len() < 4 || message.starts_with('{') {
continue;
}
checked += 1;
let shouts = first
.chars()
.all(|c| !c.is_alphabetic() || c.is_uppercase());
assert!(
!first.chars().next().is_some_and(char::is_uppercase) || shouts,
"{}: '{message}' begins with a capital that is not an initialism",
file.display()
);
assert!(
!message.trim_end().ends_with('.'),
"{}: '{message}' ends with a full stop",
file.display()
);
assert!(
!message.contains("(s)"),
"{}: '{message}' hedges a plural; count it and use `counted`",
file.display()
);
}
}
assert!(checked > 20, "the scan found only {checked} messages");
}
fn sources(root: &std::path::Path) -> Vec<std::path::PathBuf> {
let mut found = Vec::new();
let Ok(entries) = std::fs::read_dir(root) else {
return found;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
found.extend(sources(&path));
} else if path.extension().is_some_and(|kind| kind == "rs") {
found.push(path);
}
}
found
}
fn literal_after(text: &str, at: usize) -> Option<String> {
let opening = text[at..].find('"')? + at + 1;
let mut message = String::new();
let mut chars = text[opening..].chars();
while let Some(character) = chars.next() {
match character {
'"' => return Some(message),
'\\' => match chars.next() {
Some('\n') => {
while chars.clone().next().is_some_and(char::is_whitespace) {
chars.next();
}
}
Some(escaped) => message.push(escaped),
None => return None,
},
_ => message.push(character),
}
}
None
}
}