Skip to content

Commit

Permalink
cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
andresovela committed Jul 15, 2023
1 parent 783abcf commit 9ef536f
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 47 deletions.
44 changes: 25 additions & 19 deletions decoder/src/log/format.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use nom::IResult;
use nom::branch::alt;
use nom::bytes::complete::{take, take_till1};
use nom::character::complete::char;
use nom::combinator::{map_res, map};
use nom::combinator::{map, map_res};
use nom::error::{FromExternalError, ParseError};
use nom::multi::many0;
use nom::sequence::delimited;
use nom::branch::alt;
use nom::IResult;
use nom::Parser;

#[derive(Debug, PartialEq, Clone)]
Expand All @@ -25,36 +25,42 @@ pub enum LogSegment {
pub struct InvalidArgument;

fn parse_argument<'a, E>(input: &'a str) -> IResult<&'a str, LogSegment, E>
where E: ParseError<&'a str> + FromExternalError<&'a str, InvalidArgument>, {
where
E: ParseError<&'a str> + FromExternalError<&'a str, InvalidArgument>,
{
let parse_enclosed = delimited(char('{'), take(1u32), char('}'));
let mut parse_type = map_res(parse_enclosed, move |s| {
match s {
"t" => Ok(LogSegment::Timestamp),
"f" => Ok(LogSegment::FileName),
"F" => Ok(LogSegment::FilePath),
"m" => Ok(LogSegment::ModulePath),
"l" => Ok(LogSegment::LineNumber),
"L" => Ok(LogSegment::LogLevel),
"s" => Ok(LogSegment::Log),
_ => Err(InvalidArgument),
}
let mut parse_type = map_res(parse_enclosed, move |s| match s {
"t" => Ok(LogSegment::Timestamp),
"f" => Ok(LogSegment::FileName),
"F" => Ok(LogSegment::FilePath),
"m" => Ok(LogSegment::ModulePath),
"l" => Ok(LogSegment::LineNumber),
"L" => Ok(LogSegment::LogLevel),
"s" => Ok(LogSegment::Log),
_ => Err(InvalidArgument),
});

parse_type.parse(input)
}

fn parse_string_segment<'a, E>(input: &'a str) -> IResult<&'a str, LogSegment, E>
where E: ParseError<&'a str>, {
map(take_till1(|c| c == '{'),|s: &str| LogSegment::String(s.to_string())).parse(input)
where
E: ParseError<&'a str>,
{
map(take_till1(|c| c == '{'), |s: &str| {
LogSegment::String(s.to_string())
})
.parse(input)
}

pub fn parse(input: &str) -> Result<Vec<LogSegment>, String> {
let mut parse_all = many0(alt((parse_argument::<()>, parse_string_segment)));

parse_all(input).map(|(_, output)| output).map_err(|e| e.to_string())
parse_all(input)
.map(|(_, output)| output)
.map_err(|e| e.to_string())
}


#[cfg(test)]
mod tests {
use super::*;
Expand Down
5 changes: 4 additions & 1 deletion decoder/src/log/json_logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ impl Log for JsonLogger {
}

impl JsonLogger {
pub fn new(log_format: Option<&str>, should_log: impl Fn(&Metadata) -> bool + Sync + Send + 'static) -> Box<Self> {
pub fn new(
log_format: Option<&str>,
should_log: impl Fn(&Metadata) -> bool + Sync + Send + 'static,
) -> Box<Self> {
Box::new(Self {
should_log: Box::new(should_log),
host_logger: StdoutLogger::new_unboxed(log_format, |_| true),
Expand Down
8 changes: 4 additions & 4 deletions decoder/src/log/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
//! [`log`]: https://crates.io/crates/log
//! [`defmt`]: https://crates.io/crates/defmt

mod format;
mod json_logger;
mod stdout_logger;
mod format;

use log::{Level, LevelFilter, Metadata, Record};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -116,10 +116,10 @@ impl<'a> DefmtRecord<'a> {
/// Initializes a `log` sink that handles defmt frames.
///
/// Defmt frames will be printed to stdout, other logs to stderr.
///
///
/// The caller has to provide a `should_log` closure that determines whether a log record should be
/// printed.
///
///
/// An optional `log_format` string can be provided to format the way
/// logs are printed. A format string could look as follows:
/// "{t} [{L}] Location<{f}:{l}> {s}"
Expand All @@ -133,7 +133,7 @@ impl<'a> DefmtRecord<'a> {
/// - {l} : line number
/// - {L} : log level (e.g. "INFO", "DEBUG", etc)
/// - {s} : the actual log
///
///
/// For example, with the log format shown above, a log would look like this:
/// "23124 [INFO] Location<main.rs:23> Hello, world!"
pub fn init_logger(
Expand Down
44 changes: 21 additions & 23 deletions decoder/src/log/stdout_logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ use log::{Level, Log, Metadata, Record as LogRecord};
use std::{
fmt::Write as _,
io::{self, StderrLock, StdoutLock},
sync::atomic::{AtomicUsize, Ordering}, path::Path,
path::Path,
sync::atomic::{AtomicUsize, Ordering},
};

use super::{DefmtRecord, format::LogSegment};
use super::format;
use super::{format::LogSegment, DefmtRecord};

enum Record<'a> {
Defmt(&'a DefmtRecord<'a>),
Expand Down Expand Up @@ -88,9 +89,9 @@ impl StdoutLogger {
pub(super) fn print_host_record(&self, record: &LogRecord, mut sink: StderrLock) {
let min_timestamp_width = self.timing_align.load(Ordering::Relaxed);
Printer::new(Record::Host(record), &self.format)
.min_timestamp_width(min_timestamp_width)
.print_frame(&mut sink)
.ok();
.min_timestamp_width(min_timestamp_width)
.print_frame(&mut sink)
.ok();
}
}

Expand Down Expand Up @@ -143,23 +144,22 @@ impl<'a> Printer<'a> {
Record::Defmt(record) => record.timestamp().to_string(),
Record::Host(_) => String::from("(HOST)"),
};

write!(
sink,
"{timestamp:>0$}",
self.min_timestamp_width,
)

write!(sink, "{timestamp:>0$}", self.min_timestamp_width,)
}

fn print_log_level<W: io::Write>(&self, sink: &mut W) -> io::Result<()> {
let level = match self.record {
Record::Defmt(record) => record.level(),
Record::Host(record) => Some(record.level()),
};

let level = if let Some(level) = level {
// TODO: Should the color be customizable via the format too?
level.to_string().color(color_for_log_level(level)).to_string()
level
.to_string()
.color(color_for_log_level(level))
.to_string()
} else {
String::from("level")
};
Expand All @@ -171,7 +171,8 @@ impl<'a> Printer<'a> {
let file_path = match self.record {
Record::Defmt(record) => record.file(),
Record::Host(record) => record.file(),
}.unwrap_or("<file>");
}
.unwrap_or("<file>");

write!(sink, "{file_path}")
}
Expand All @@ -181,7 +182,7 @@ impl<'a> Printer<'a> {
Record::Defmt(record) => record.file(),
Record::Host(record) => record.file(),
};

let file_name = if let Some(file) = file {
let file_name = Path::new(file).file_name();
if let Some(file_name) = file_name {
Expand All @@ -200,7 +201,8 @@ impl<'a> Printer<'a> {
let module_path = match self.record {
Record::Defmt(record) => record.module_path(),
Record::Host(record) => record.module_path(),
}.unwrap_or("<mod path>");
}
.unwrap_or("<mod path>");

write!(sink, "{module_path}")
}
Expand All @@ -209,7 +211,8 @@ impl<'a> Printer<'a> {
let line_number = match self.record {
Record::Defmt(record) => record.line(),
Record::Host(record) => record.line(),
}.unwrap_or(0);
}
.unwrap_or(0);

write!(sink, "{line_number}")
}
Expand All @@ -220,13 +223,8 @@ impl<'a> Printer<'a> {
Record::Host(record) => record.args(),
};

write!(
sink,
"{log}",
log = color_diff(args.to_string()),
)
write!(sink, "{log}", log = color_diff(args.to_string()),)
}

}

// color the output of `defmt::assert_eq`
Expand Down

0 comments on commit 9ef536f

Please sign in to comment.