Added parsing commands
This commit is contained in:
9
poem.txt
Normal file
9
poem.txt
Normal file
@@ -0,0 +1,9 @@
|
||||
I'm nobody! Who are you?
|
||||
Are you nobody, too?
|
||||
Then there's a pair of us - don't tell!
|
||||
They'd banish us, you know.
|
||||
|
||||
How dreary to be somebody!
|
||||
How public, like a frog
|
||||
To tell your name the livelong day
|
||||
To an admiring bog!
|
||||
4
src/lib.rs
Normal file
4
src/lib.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
//TODO implement search function
|
||||
pub fn search() {
|
||||
unimplemented!();
|
||||
}
|
||||
61
src/main.rs
61
src/main.rs
@@ -1,15 +1,64 @@
|
||||
use std::fs;
|
||||
use std::env;
|
||||
use std::error::Error;
|
||||
use std::process;
|
||||
|
||||
fn main() {
|
||||
use minigrep::search;
|
||||
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
// Args returns an iterator of args from cli
|
||||
// Collect turns an iterator into a collection
|
||||
// In this case transform values of args into a vector
|
||||
let args: Vec<String> = env::args().collect();
|
||||
let query = &args[0];
|
||||
let file_path = &args[1];
|
||||
|
||||
|
||||
println!("Searching for {query}");
|
||||
println!("In file {file_path}");
|
||||
// TODO handle the case of less or more parameters entered by user
|
||||
// let config = Config::build(&args)?;
|
||||
// or
|
||||
let config = Config::build(&args).unwrap_or_else(|err| {
|
||||
println!("Problem parsing arguments: {err}");
|
||||
process::exit(1);
|
||||
});
|
||||
|
||||
println!("Searching for {}", config.query);
|
||||
println!("In file {}", config.file_path);
|
||||
|
||||
// run(config)?;
|
||||
// or
|
||||
if let Err(e) = run(config) {
|
||||
println!("Application error: {e}");
|
||||
process::exit(1);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run (config: Config) -> Result<(), Box<dyn Error>> {
|
||||
let contents: String = fs::read_to_string(config.file_path)?;
|
||||
println!("With text:\n{contents}");
|
||||
|
||||
search();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Config {
|
||||
query: String,
|
||||
file_path: String,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
fn build(args: &[String]) -> Result<Config, &'static str> {
|
||||
if args.len() > 3 {
|
||||
return Err("Too many arguments. Usage: minigrep <query> <file_path>");
|
||||
}
|
||||
if args.len() < 3 {
|
||||
return Err("Too few arguments. Usage: minigrep <query> <file_path>");
|
||||
}
|
||||
let query = args[1].clone();
|
||||
let file_path = args[2].clone();
|
||||
|
||||
Ok(Config { query, file_path })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user