Skip to content

Commit 608433b

Browse files
Merge pull request #303 from grantlemons/span-visualization-command
feat: Span visualization command
2 parents 5a190db + bfffc05 commit 608433b

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

harper-cli/src/main.rs

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ enum Args {
2626
/// The file you wish to parse.
2727
file: PathBuf,
2828
},
29+
/// Parse a provided document and show the spans of the detected tokens.
30+
Spans {
31+
/// The file you wish to display the spans.
32+
file: PathBuf,
33+
},
2934
/// Emit decompressed, line-separated list of words in Harper's dictionary.
3035
Words,
3136
}
@@ -72,7 +77,7 @@ fn main() -> anyhow::Result<()> {
7277
let report = report_builder.finish();
7378
report.print((&filename, Source::from(source)))?;
7479

75-
std::process::exit(1);
80+
Ok(())
7681
}
7782
Args::Parse { file } => {
7883
let (doc, _) = load_file(&file)?;
@@ -84,6 +89,39 @@ fn main() -> anyhow::Result<()> {
8489

8590
Ok(())
8691
}
92+
Args::Spans { file } => {
93+
let (doc, source) = load_file(&file)?;
94+
95+
let primary_color = Color::Blue;
96+
let secondary_color = Color::Magenta;
97+
let filename = file
98+
.file_name()
99+
.map(|s| s.to_string_lossy().into())
100+
.unwrap_or("<file>".to_string());
101+
102+
let mut report_builder =
103+
Report::build(ReportKind::Custom("Spans", primary_color), &filename, 0);
104+
let mut color = primary_color;
105+
for token in doc.tokens() {
106+
report_builder = report_builder.with_label(
107+
Label::new((&filename, token.span.into()))
108+
.with_message(format!("[{}, {})", token.span.start, token.span.end))
109+
.with_color(color),
110+
);
111+
112+
// Alternate colors so spans are clear
113+
color = if color == primary_color {
114+
secondary_color
115+
} else {
116+
primary_color
117+
};
118+
}
119+
120+
let report = report_builder.finish();
121+
report.print((&filename, Source::from(source)))?;
122+
123+
Ok(())
124+
}
87125
Args::Words => {
88126
let dict = FstDictionary::curated();
89127

justfile

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,10 @@ parse file:
200200
lint file:
201201
cargo run --bin harper-cli -- lint {{file}}
202202

203+
# Show the spans of the parsed tokens overlapped on the file.
204+
spans file:
205+
cargo run --bin harper-cli -- spans {{file}}
206+
203207
# Add a noun to Harper's curated dictionary.
204208
addnoun noun:
205209
#! /bin/bash

0 commit comments

Comments
 (0)