Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add multiple and multiline help support #138

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ pub struct Report<'a, S: Span = Range<usize>> {
code: Option<String>,
msg: Option<String>,
notes: Vec<String>,
help: Option<String>,
help: Vec<String>,
span: S,
labels: Vec<Label<S>>,
config: Config,
Expand All @@ -219,7 +219,7 @@ impl<S: Span> Report<'_, S> {
code: None,
msg: None,
notes: vec![],
help: None,
help: vec![],
span,
labels: Vec::new(),
config: Config::default(),
Expand Down Expand Up @@ -284,7 +284,7 @@ pub struct ReportBuilder<'a, S: Span> {
code: Option<String>,
msg: Option<String>,
notes: Vec<String>,
help: Option<String>,
help: Vec<String>,
span: S,
labels: Vec<Label<S>>,
config: Config,
Expand Down Expand Up @@ -333,12 +333,24 @@ impl<'a, S: Span> ReportBuilder<'a, S> {

/// Set the help message of this report.
pub fn set_help<N: ToString>(&mut self, note: N) {
self.help = Some(note.to_string());
self.help = vec![note.to_string()];
}

/// Add a help message to this report.
pub fn add_help<N: ToString>(&mut self, note: N) {
self.help.push(note.to_string());
}

/// Set the help messages of this report.
pub fn with_helps<N: IntoIterator<Item = impl ToString>>(&mut self, helps: N) {
for help in helps {
self.add_help(help)
}
}

/// Set the help message of this report.
pub fn with_help<N: ToString>(mut self, note: N) -> Self {
self.set_help(note);
self.add_help(note);
self
}

Expand Down
20 changes: 8 additions & 12 deletions src/source.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use super::*;

use std::io::Error;
use std::{
collections::{hash_map::Entry, HashMap},
fs,
path::{Path, PathBuf},
};
use std::io::Error;

/// A trait implemented by [`Source`] caches.
pub trait Cache<Id: ?Sized> {
Expand Down Expand Up @@ -332,9 +332,7 @@ impl Cache<Path> for FileCache {
Ok::<_, Error>(match self.files.entry(path.to_path_buf()) {
// TODO: Don't allocate here
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(Source::from(
fs::read_to_string(path)?,
)),
Entry::Vacant(entry) => entry.insert(Source::from(fs::read_to_string(path)?)),
})
}
fn display<'a>(&self, path: &'a Path) -> Option<impl fmt::Display + 'a> {
Expand Down Expand Up @@ -403,14 +401,12 @@ where
I: IntoIterator<Item = (Id, S)>,
S: AsRef<str>,
{
FnCache::new(
(move |id| Err(format!("Failed to fetch source '{}'", id))) as fn(&_) -> _,
)
.with_sources(
iter.into_iter()
.map(|(id, s)| (id, Source::from(s)))
.collect(),
)
FnCache::new((move |id| Err(format!("Failed to fetch source '{}'", id))) as fn(&_) -> _)
.with_sources(
iter.into_iter()
.map(|(id, s)| (id, Source::from(s)))
.collect(),
)
}

#[cfg(test)]
Expand Down
65 changes: 59 additions & 6 deletions src/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -856,13 +856,37 @@ impl<S: Span> Report<'_, S> {
let is_final_group = group_idx + 1 == groups_len;

// Help
if let (Some(note), true) = (&self.help, is_final_group) {
if !self.config.compact {
write_margin(&mut w, 0, false, false, true, Some((0, false)), &[], &None)?;
writeln!(w)?;
if is_final_group {
for (i, help) in self.help.iter().enumerate() {
if !self.config.compact {
write_margin(&mut w, 0, false, false, true, Some((0, false)), &[], &None)?;
writeln!(w)?;
}
let help_prefix = format!("{} {}", "Help", i + 1);
let help_prefix_len = if self.help.len() > 1 {
help_prefix.len()
} else {
4
};
let mut lines = help.lines();
if let Some(line) = lines.next() {
write_margin(&mut w, 0, false, false, true, Some((0, false)), &[], &None)?;
if self.help.len() > 1 {
writeln!(
w,
"{}: {}",
help_prefix.fg(self.config.note_color(), s),
line
)?;
} else {
writeln!(w, "{}: {}", "Help".fg(self.config.note_color(), s), line)?;
}
}
for line in lines {
write_margin(&mut w, 0, false, false, true, Some((0, false)), &[], &None)?;
writeln!(w, "{:>pad$}{}", "", line, pad = help_prefix_len + 2)?;
}
}
write_margin(&mut w, 0, false, false, true, Some((0, false)), &[], &None)?;
writeln!(w, "{}: {}", "Help".fg(self.config.note_color(), s), note)?;
}

// Note
Expand Down Expand Up @@ -1522,4 +1546,33 @@ mod tests {
---'
"###)
}

#[test]
fn multi_helps_multi_lines() {
let source = "apple == orange;";
let msg = remove_trailing(
Report::build(ReportKind::Error, 0..0)
.with_config(no_color_and_ascii())
.with_message("can't compare apples with oranges")
.with_label(Label::new(0..15).with_message("This is a strange comparison"))
.with_help("No need to try, they can't be compared.")
.with_help("Yeah, really, please stop.\nIt has no resemblance.")
.finish()
.write_to_string(Source::from(source)),
);
assert_snapshot!(msg, @r###"
Error: can't compare apples with oranges
,-[ <unknown>:1:1 ]
|
1 | apple == orange;
| ^^^^^^^|^^^^^^^
| `--------- This is a strange comparison
|
| Help 1: No need to try, they can't be compared.
|
| Help 2: Yeah, really, please stop.
| It has no resemblance.
---'
"###)
}
}