Skip to content

Commit

Permalink
Add CSV parser
Browse files Browse the repository at this point in the history
  • Loading branch information
ewpratten committed Apr 12, 2024
1 parent ce270f5 commit 7aa47c1
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 6 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ eframe = "0.27.2"
egui_extras = "0.27.2"
fern = "0.6.2"
log = "0.4.21"
csv = "1.3.0"

[[bin]]
name = "mlv"
Expand Down
4 changes: 3 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,9 @@ pub fn main() {

// Parse the line
let parsed_line = args.parser.parse_line(&line);
parsed_file.add_line(parsed_line);
if let Some(parsed_line) = parsed_line {
parsed_file.add_line(parsed_line);
}
}
log::debug!("File closed");
});
Expand Down
28 changes: 28 additions & 0 deletions src/parse/builtin/csv.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use eframe::egui::RichText;

use crate::parse::ParsedLine;

pub fn parse_line(line: &str) -> Option<ParsedLine> {
// Read the line
let mut reader = csv::ReaderBuilder::new()
.has_headers(false)
.comment(Some(b'#'))
.trim(csv::Trim::All)
.from_reader(line.as_bytes());

// Parse the line
let mut cells = Vec::new();
for result in reader.records() {
let record = result.unwrap();
for field in record.iter() {
cells.push(RichText::new(field.to_string()));
}
}

// If there are no cells, return None
if cells.is_empty() || cells.iter().all(|c| c.text().is_empty()) {
return None;
}

Some(ParsedLine::new(cells))
}
3 changes: 2 additions & 1 deletion src/parse/builtin/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod spaces;
pub mod spaces;
pub mod csv;
6 changes: 3 additions & 3 deletions src/parse/builtin/spaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ use eframe::egui::RichText;

use crate::parse::ParsedLine;

pub fn parse_line(line: &str) -> ParsedLine {
ParsedLine::new(
pub fn parse_line(line: &str) -> Option<ParsedLine> {
Some(ParsedLine::new(
line.split_whitespace()
.map(|s| RichText::new(s.to_string()))
.collect(),
)
))
}
5 changes: 4 additions & 1 deletion src/parse/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@ use eframe::egui::{Label, RichText};
pub enum FileParsers {
/// Space-separated values
Spaces,
/// Comma-separated values
Csv,
}

impl FileParsers {
/// Parse a line using the selected parser
pub fn parse_line(&self, line: &str) -> ParsedLine {
pub fn parse_line(&self, line: &str) -> Option<ParsedLine> {
match self {
FileParsers::Spaces => builtin::spaces::parse_line(line),
FileParsers::Csv => builtin::csv::parse_line(line),
}
}
}
Expand Down

0 comments on commit 7aa47c1

Please sign in to comment.