Feat(lib): File I/O,

This commit is contained in:
minhtrannhat 2023-09-01 20:49:29 -04:00
parent b8fa6d8e18
commit d401122b30
Signed by: minhtrannhat
GPG Key ID: E13CFA85C53F8062

View File

@ -1,6 +1,8 @@
use clap::builder::{Arg, Command};
use clap::{crate_authors, crate_description, crate_name, crate_version, ArgAction, ArgMatches};
use std::error::Error;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
type MyResult<T> = Result<T, Box<dyn Error>>;
@ -34,13 +36,16 @@ pub fn get_args() -> MyResult<Config> {
.arg(
Arg::new("number")
.short('n')
.long("number")
.help("Number lines")
.num_args(0)
.action(ArgAction::SetTrue),
.action(ArgAction::SetTrue)
.conflicts_with("number_nonblank"),
)
.arg(
Arg::new("number_nonblank")
.short('b')
.long("number-nonblank")
.help("Number nonblank lines")
.num_args(0)
.action(ArgAction::SetTrue),
@ -58,8 +63,20 @@ pub fn get_args() -> MyResult<Config> {
})
}
fn open(filename: &str) -> MyResult<Box<dyn BufRead>> {
match filename {
"-" => Ok(Box::new(BufReader::new(io::stdin()))),
_ => Ok(Box::new(BufReader::new(File::open(filename)?))),
}
}
pub fn run(config: Config) -> MyResult<()> {
dbg!(config);
for filepath in config.files {
match open(&filepath) {
Err(err) => eprintln!("Failed to open {}: {}", filepath, err),
Ok(_) => println!("Opened {}", filepath),
}
}
Ok(())
}