learning rust do not look
1use std::{env, fs, process};
2
3struct Config {
4 file_path: String,
5 command: String
6}
7
8impl Config {
9 fn new(args: &[String]) -> Result<Config, &'static str> {
10
11 if args.len() < 3 || args.len() == 0 {
12 return Err("invalid arguments")
13 }
14
15 let path = args[2].clone();
16 let command = args[1].clone();
17
18 Ok(Config { file_path: path, command })
19 }
20}
21
22fn main() {
23 let args: Vec<String> = env::args().collect();
24
25 let config = Config::new(&args).unwrap_or_else(|_err| {
26 print_help();
27 process::exit(1)
28 });
29
30
31 let file_contents = fs::read_to_string(config.file_path).expect("Invalid file path, please make sure the path to the file is correct");
32
33 match config.command.as_str() {
34 "-c" | "--bytes" => count_bytes(&file_contents),
35 "-l" | "--lines" => count_lines(&file_contents),
36 "-w" | "--words" => count_words(&file_contents),
37 "-m" | "--chars" => count_chars(&file_contents),
38 "-h" | "--help" => print_help(),
39 _ => print_help(),
40 }
41}
42
43
44fn count_bytes(contents: &String) {
45 println!("{}", contents.bytes().len())
46}
47
48fn count_chars(contents: &String) {
49 println!("{}", contents.chars().count())
50}
51
52fn count_lines(contents: &String) {
53 println!("{}", contents.lines().count())
54}
55
56fn count_words(contents: &String) {
57 print!("{}", contents.split_whitespace().count())
58}
59
60fn print_help() {
61 println!("
62 yap [-COMMAND] [PATH_TO_FILE]
63
64 -c, --bytes - count the amount of bytes in a file
65 -l, --lines - count the amount of lines in a file
66 -w, --words - count the amount of words in a file
67 -m, --chars - count the amount of characters in a file
68 -h, --help - list the available command line arguments
69 "
70 );
71}