aoc_utils/args.rs
1use std::path::PathBuf;
2
3use crate::bufwrap::{file_reader, stdin_reader, BufferedInput};
4
5use clap::{value_parser, Arg, Command};
6
7/// CLI command that provides an input source to an AOC problem.
8///
9/// Supports input from a given file as well as from STDIN.
10/// Implements `std::io::BufRead` for the convenience of the `BufRead::lines` iterator.
11///
12/// # Example
13///
14/// If your executable is named `prog` and the description is "Example description",
15/// then the help (`prog --help`) will look like this:
16///
17/// ```console
18/// Example description
19///
20/// USAGE:
21/// prog [FILE]
22///
23/// FLAGS:
24/// -h, --help Prints help information
25/// -V, --version Prints version information
26///
27/// ARGS:
28/// <FILE> Input file (defaults to STDIN if not provided)
29/// ```
30pub struct AocCommand {
31 description: String,
32}
33
34impl AocCommand {
35 /// Returns this struct with the description configured.
36 ///
37 /// # Arguments
38 ///
39 /// * `description` - provides an "about" section in the usage manual.
40 pub fn new(description: &str) -> Self {
41 Self {
42 description: description.to_string(),
43 }
44 }
45
46 /// Parse cmdline arguments and create a new object
47 /// to read lines from an arbitrary input source.
48 ///
49 /// The application optionally expects a path argument
50 /// that specifies the file to read from.
51 /// If not present, the input is read from STDIN.
52 ///
53 /// # Example
54 ///
55 /// ```
56 /// use std::io::BufRead;
57 /// use aoc_utils::AocCommand;
58 ///
59 /// let input = AocCommand::new("Example solution").parse_args().unwrap();
60 /// let lines: Vec<String> = input.lines().map(Result::unwrap).collect();
61 /// ```
62 pub fn parse_args(&self) -> std::io::Result<BufferedInput> {
63 let input_arg = Arg::new("input")
64 .value_parser(value_parser!(PathBuf))
65 .value_name("FILE")
66 .help("Input file (defaults to STDIN if not provided)");
67 let app = Command::new("").about(&self.description).arg(input_arg);
68
69 let matches = app.get_matches();
70
71 let result = match matches.get_one::<PathBuf>("input") {
72 Some(path) => BufferedInput::File(file_reader(path)?),
73 _ => BufferedInput::Stdin(stdin_reader()),
74 };
75
76 Ok(result)
77 }
78}