Browse Source

refactor: format error messages without allocating a string for each line

I added a test to confirm the output matches the old.

Fixes clippy warning clippy::format_collect
https://rust-lang.github.io/rust-clippy/master/index.html#/format_collect
tags/v0.3.4-rc1
Michael-J-Ward 1 year ago
parent
commit
ae9e19e57f
2 changed files with 38 additions and 3 deletions
  1. +32
    -2
      binaries/coordinator/src/lib.rs
  2. +6
    -1
      binaries/daemon/src/spawn.rs

+ 32
- 2
binaries/coordinator/src/lib.rs View File

@@ -575,6 +575,19 @@ async fn stop_dataflow_by_uuid(
Ok(())
}

fn format_error(machine: &str, err: &str) -> String {
let mut error = err
.lines()
.fold(format!("- machine `{machine}`:\n"), |mut output, line| {
output.push_str(" ");
output.push_str(line);
output.push('\n');
output
});
error.push('\n');
error
}

fn dataflow_result(
results: &BTreeMap<String, Result<(), String>>,
dataflow_uuid: Uuid,
@@ -582,8 +595,7 @@ fn dataflow_result(
let mut errors = Vec::new();
for (machine, result) in results {
if let Err(err) = result {
let err: String = err.lines().map(|line| format!(" {line}\n")).collect();
errors.push(format!("- machine `{machine}`:\n{err}\n"));
errors.push(format_error(machine, err));
}
}

@@ -941,3 +953,21 @@ fn set_up_ctrlc_handler() -> Result<impl Stream<Item = Event>, eyre::ErrReport>

Ok(ReceiverStream::new(ctrlc_rx))
}

#[cfg(test)]
mod test {
#[test]
fn test_format_error() {
let machine = "machine A";
let err = "foo\nbar\nbuzz";

// old method
let old_error = {
#[allow(clippy::format_collect)]
let err: String = err.lines().map(|line| format!(" {line}\n")).collect();
format!("- machine `{machine}`:\n{err}\n")
};
let new_error = super::format_error(machine, err);
assert_eq!(old_error, new_error)
}
}

+ 6
- 1
binaries/daemon/src/spawn.rs View File

@@ -405,7 +405,12 @@ pub async fn spawn_node(
.write_all(message.as_bytes())
.await
.map_err(|err| error!("Could not log {message} to file due to {err}"));
let formatted: String = message.lines().map(|l| format!(" {l}\n")).collect();
let formatted = message.lines().fold(String::default(), |mut output, line| {
output.push_str(" ");
output.push_str(line);
output.push('\n');
output
});
debug!("{dataflow_id}/{} logged:\n{formatted}", node.id.clone());
// Make sure that all data has been synced to disk.
let _ = file


Loading…
Cancel
Save