|
| 1 | +## Basic Argument Parsing |
| 2 | +This section covers a basic implementation of commandline argument parsing. |
| 3 | +Use [`args`] to get the arguments this process was started with: |
| 4 | + |
| 5 | +```rust,edition2024 |
| 6 | +use std::env; |
| 7 | +
|
| 8 | +fn main() { |
| 9 | + let args: Vec<String> = env::args().collect(); |
| 10 | + assert!(!args.is_empty()); |
| 11 | +
|
| 12 | + // Skip the program name, it's usually the first argument |
| 13 | + let args: Vec<String> = env::args().skip(1).collect(); |
| 14 | +} |
| 15 | +``` |
| 16 | + |
| 17 | +Some args, e.g. file paths, may not be valid UTF-8. Use [`args_os`] to handle those safely: |
| 18 | + |
| 19 | +```rust,edition2024 |
| 20 | +use std::{env, ffi::OsString}; |
| 21 | +
|
| 22 | +fn main() { |
| 23 | + let os_args: Vec<OsString> = env::args_os().collect(); |
| 24 | + assert!(!os_args.is_empty()); |
| 25 | +} |
| 26 | +``` |
| 27 | + |
| 28 | +## Calculate File Stats |
| 29 | +In this section we parse CLI args and compute per-file stats (line/word counts). A mini [`wc`]-like |
| 30 | +utility |
| 31 | + |
| 32 | +Flags: |
| 33 | +- --lines, -l Count lines per file |
| 34 | +- --words, -w Count words per file |
| 35 | +- --paths, -p Remaining args treated as file paths |
| 36 | + |
| 37 | +> `-p` acts as a terminator. Everything after it is consumed as file paths and parsing stops |
| 38 | +> immediately. |
| 39 | +
|
| 40 | +`CliArgs` holds the parsed state of the process args. It uses [`args_os`] over [`args`] to |
| 41 | +safely handle non-UTF-8 paths, which can occur on Linux. [`skip(1)`] drops the bin name since it is |
| 42 | +always the first arg. Once `-p` flag is is encountered, all remaining args are collected into paths. |
| 43 | + |
| 44 | +`Stats<'p>` represents the computed result for a single file. It borrows filepath directly from |
| 45 | +`CliArgs` rather than cloning it, with the lifetime 'p tying each Stats instance to its source |
| 46 | +`CliArgs`. Both `lines` and `words` are `Option<usize>`, where `None` means the flag was absent and |
| 47 | +the stat was never computed, while `Some(n)` means the flag was set and the count is `n`. This |
| 48 | +distinction matters because it avoids confusing "not requested" with a legitimate count of zero. |
| 49 | + |
| 50 | +`stat_files` is the core logic. Iterates over `cli_args.paths` and builds a `Vec<Stats<'_>>`. |
| 51 | +Non-files and IO errors are skipped silently via `continue` for simplicity. Each file is read |
| 52 | +to a string buffer with fs::[`read_to_string()`] for processing. Line count uses |
| 53 | +content.[`lines()`].[`count()`]. Word count splits each line on whitespace via |
| 54 | +[`split_whitespace()`], counts tokens per line, then sums across all lines, which correctly handles |
| 55 | +tabs and multiple consecutive spaces. Both stats are computed only if their respective flag was set, |
| 56 | +so there is no wasted work. |
| 57 | + |
| 58 | +The result is output as one line per file. Stats omitted by the user are excluded from the output |
| 59 | +entirely rather than printed as zero or a placeholder. |
| 60 | + |
| 61 | +```rust,edition2024,no_run |
| 62 | +use std::env; |
| 63 | +use std::fs; |
| 64 | +use std::path::{Path, PathBuf}; |
| 65 | +
|
| 66 | +// Represents the arguments passed to this process during initialization |
| 67 | +#[derive(Debug)] |
| 68 | +struct CliArgs { |
| 69 | + lines: bool, |
| 70 | + words: bool, |
| 71 | + paths: Vec<PathBuf>, |
| 72 | +} |
| 73 | +
|
| 74 | +impl CliArgs { |
| 75 | + fn parse() -> Self { |
| 76 | + let mut lines = false; |
| 77 | + let mut words = false; |
| 78 | + let mut paths = Vec::new(); |
| 79 | +
|
| 80 | + let args = env::args_os().skip(1); |
| 81 | + let mut args = args.into_iter(); |
| 82 | + while let Some(arg) = args.next() { |
| 83 | + match arg.to_str().unwrap_or_default() { |
| 84 | + "-l" | "--lines" => lines = true, |
| 85 | + "-w" | "--words" => words = true, |
| 86 | + "-p" | "--paths" => { |
| 87 | + paths.extend(args.by_ref().map(PathBuf::from)); |
| 88 | + break; |
| 89 | + } |
| 90 | + _ => {} |
| 91 | + } |
| 92 | + } |
| 93 | +
|
| 94 | + CliArgs { |
| 95 | + lines, |
| 96 | + words, |
| 97 | + paths, |
| 98 | + } |
| 99 | + } |
| 100 | +} |
| 101 | +
|
| 102 | +// Represents the statistics of a given filepath |
| 103 | +struct Stats<'p> { |
| 104 | + filepath: &'p Path, |
| 105 | + lines: Option<usize>, |
| 106 | + words: Option<usize>, |
| 107 | +} |
| 108 | +
|
| 109 | +fn stat_files(cli_args: &CliArgs) -> Vec<Stats<'_>> { |
| 110 | + let mut stat_collection: Vec<Stats> = Vec::new(); |
| 111 | + // If no flag is set, do no work |
| 112 | + if !cli_args.words && !cli_args.lines { |
| 113 | + return stat_collection; |
| 114 | + } |
| 115 | +
|
| 116 | + for filepath in &cli_args.paths { |
| 117 | + // Skip anything that ain't a file |
| 118 | + if !filepath.is_file() { |
| 119 | + continue; |
| 120 | + } |
| 121 | +
|
| 122 | + let Ok(content) = fs::read_to_string(filepath) else { |
| 123 | + continue; |
| 124 | + }; |
| 125 | +
|
| 126 | + let lines = match cli_args.lines { |
| 127 | + true => Some(content.lines().count()), |
| 128 | + false => None, |
| 129 | + }; |
| 130 | +
|
| 131 | + let words = match cli_args.words { |
| 132 | + true => Some( |
| 133 | + content |
| 134 | + .lines() |
| 135 | + .map(|line| line.split_whitespace().count()) |
| 136 | + .sum(), |
| 137 | + ), |
| 138 | + false => None, |
| 139 | + }; |
| 140 | +
|
| 141 | + let stats = Stats { |
| 142 | + filepath, |
| 143 | + lines, |
| 144 | + words, |
| 145 | + }; |
| 146 | +
|
| 147 | + stat_collection.push(stats); |
| 148 | + } |
| 149 | +
|
| 150 | + stat_collection |
| 151 | +} |
| 152 | +
|
| 153 | +fn main() { |
| 154 | + let cli_args = CliArgs::parse(); |
| 155 | + let stats = stat_files(&cli_args); |
| 156 | + // Print individual file statistics |
| 157 | + for stat in stats { |
| 158 | + println!( |
| 159 | + "Path: {:?} {} {}", |
| 160 | + stat.filepath, |
| 161 | + if let Some(words) = stat.words { |
| 162 | + format!("Words: {}", words) |
| 163 | + } else { |
| 164 | + "".to_string() |
| 165 | + }, |
| 166 | + if let Some(lines) = stat.lines { |
| 167 | + format!("Lines: {}", lines) |
| 168 | + } else { |
| 169 | + "".to_string() |
| 170 | + }, |
| 171 | + ); |
| 172 | + } |
| 173 | +} |
| 174 | +``` |
| 175 | + |
| 176 | +Example Usage: |
| 177 | + |
| 178 | +```bash |
| 179 | +cargo run --release -- -l -w -p src/main.rs Cargo.toml |
| 180 | +# Path: "src/main.rs" Words: 312 Lines: 84 |
| 181 | +# Path: "Cargo.toml" Words: 21 Lines: 9 |
| 182 | + |
| 183 | +cargo run --release -- -l -p src/main.rs |
| 184 | +# Path: "src/main.rs" Lines: 84 |
| 185 | +``` |
| 186 | + |
| 187 | +[`args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html |
| 188 | +[`args`]: https://doc.rust-lang.org/std/env/fn.args.html |
| 189 | +[`count()`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.count |
| 190 | +[`env`]: https://doc.rust-lang.org/std/env/index.html |
| 191 | +[`lines()`]: https://doc.rust-lang.org/std/primitive.str.html#method.lines |
| 192 | +[`read_to_string()`]: https://doc.rust-lang.org/std/fs/fn.read_to_string.html |
| 193 | +[`skip(1)`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.skip |
| 194 | +[`split_whitespace()`]: https://doc.rust-lang.org/std/primitive.str.html#method.split_whitespace |
| 195 | +[`wc`]: https://www.man7.org/linux/man-pages/man1/wc.1.html |
0 commit comments