flagon-io/hello

public

Greets people from the command line. The sample repository for g1t.

Add a --version flag that prints the crate version and exits #26

Mergedg1tbot merged into mainrequested by syntaqx

Approved by g1t

3 files+36−10/3 viewed
+18−1
77 pub name: Option<String>,
88 /// Whether to upper-case the greeting (`--shout`).
99 pub shout: bool,
10+ /// Whether to print the crate version and exit (`--version`).
11+ pub version: bool,
1012 }
1113
1214 /// Parses command-line arguments (excluding the program name).
1315 ///
14−/// `--shout` sets [`Options::shout`]; other arguments starting with `--` are
16+/// `--shout` sets [`Options::shout`] and `--version` sets
17+/// [`Options::version`]; other arguments starting with `--` are
1518 /// treated as flags and skipped. The name is the first remaining argument.
1619 pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Options {
1720 let mut options = Options::default();
1821 for arg in args {
1922 if arg == "--shout" {
2023 options.shout = true;
24+ } else if arg == "--version" {
25+ options.version = true;
2126 } else if !arg.starts_with("--") && options.name.is_none() {
2227 options.name = Some(arg);
2328 }
97102 }
98103
99104 #[test]
105+ fn parse_args_version_defaults_off() {
106+ assert!(!parse_args(args(&["Ada"])).version);
107+ }
108+
109+ #[test]
110+ fn parse_args_version() {
111+ let options = parse_args(args(&["--version"]));
112+ assert!(options.version);
113+ assert_eq!(options.name, None);
114+ }
115+
116+ #[test]
100117 fn shout_upper_cases_greeting() {
101118 assert_eq!(shout(&greeting("Ada")), "HELLO, ADA!");
102119 }
+4−0
44
55 fn main() {
66 let options = parse_args(env::args().skip(1));
7+ if options.version {
8+ println!("{}", env!("CARGO_PKG_VERSION"));
9+ return;
10+ }
711 // The name given, or whoever is signed in.
812 let name = options
913 .name
+14−0
1+use std::process::Command;
2+
3+#[test]
4+fn version_flag_prints_crate_version() {
5+ let output = Command::new(env!("CARGO_BIN_EXE_hello"))
6+ .arg("--version")
7+ .output()
8+ .unwrap();
9+ assert!(output.status.success());
10+ assert_eq!(
11+ String::from_utf8(output.stdout).unwrap(),
12+ format!("{}\n", env!("CARGO_PKG_VERSION"))
13+ );
14+}