Skip to content

Commit

Permalink
check file extensions to choose a delimiter (#100)
Browse files Browse the repository at this point in the history
  • Loading branch information
Lireer authored Oct 18, 2021
1 parent a832081 commit f5ee2c1
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,10 @@ struct Cli {
#[structopt(
short = "s",
long = "delimiter",
default_value = ",",
parse(try_from_str = datatype::parse_delimiter),
help = "The delimiter separating the columns."
)]
delimiter: u8,
delimiter: Option<u8>,
//#[structopt(
// short = "sig",
// long = "sigfig",
Expand Down Expand Up @@ -584,16 +583,31 @@ fn get_num_cols_to_print(cols: usize, vp: Vec<Vec<String>>, term_tuple: (u16, u1
}

fn build_reader(opt: &Cli) -> Result<Reader<Box<dyn Read>>, std::io::Error> {
let source: Box<dyn Read> = if let Some(path) = opt.file.clone() {
let mut delimiter = b',';

let source: Box<dyn Read> = if let Some(path) = &opt.file {
let file = File::open(path)?;

// Update the default delimiter by checking the file extension.
delimiter = match path.extension() {
Some(ext) if ext == "tsv" => b'\t',
Some(ext) if ext == "psv" => b'|',
_ => delimiter,
};

Box::new(BufReader::new(file))
} else {
Box::new(io::stdin())
};

// Cli options take precedence.
if let Some(del) = opt.delimiter {
delimiter = del;
}

let reader = ReaderBuilder::new()
.has_headers(false)
.delimiter(opt.delimiter)
.delimiter(delimiter)
.from_reader(source);

Ok(reader)
Expand Down

0 comments on commit f5ee2c1

Please sign in to comment.