flagon-io/hello

public

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

Commit

Add --shout flag that upper-cases the greeting

g1t agentcommitted Parent76b3709Browse files
2 files+54−70/2 viewed
+49−4
55 pub struct Options {
66 /// The name to greet, if one was given.
77 pub name: Option<String>,
8+ /// Whether to upper-case the greeting (`--shout`).
9+ pub shout: bool,
810 }
911
1012 /// Parses command-line arguments (excluding the program name).
1113 ///
12−/// Arguments starting with `--` are treated as flags and skipped; the name is
13−/// the first remaining argument.
14+/// `--shout` sets [`Options::shout`]; other arguments starting with `--` are
15+/// treated as flags and skipped. The name is the first remaining argument.
1416 pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Options {
15− let name = args.into_iter().find(|arg| !arg.starts_with("--"));
16− Options { name }
17+ let mut options = Options::default();
18+ for arg in args {
19+ if arg == "--shout" {
20+ options.shout = true;
21+ } else if !arg.starts_with("--") && options.name.is_none() {
22+ options.name = Some(arg);
23+ }
24+ }
25+ options
1726 }
1827
28+/// `text` upper-cased.
29+pub fn shout(text: &str) -> String {
30+ text.to_uppercase()
31+}
32+
1933 /// The greeting for `name`.
2034 pub fn greeting(name: &str) -> String {
2135 let trimmed = name.trim();
5771 }
5872
5973 #[test]
74+ fn parse_args_shout_defaults_off() {
75+ assert!(!parse_args(args(&["Ada"])).shout);
76+ }
77+
78+ #[test]
79+ fn parse_args_shout_before_name() {
80+ let options = parse_args(args(&["--shout", "Ada"]));
81+ assert!(options.shout);
82+ assert_eq!(options.name.as_deref(), Some("Ada"));
83+ }
84+
85+ #[test]
86+ fn parse_args_shout_after_name() {
87+ let options = parse_args(args(&["Ada", "--shout"]));
88+ assert!(options.shout);
89+ assert_eq!(options.name.as_deref(), Some("Ada"));
90+ }
91+
92+ #[test]
93+ fn parse_args_shout_alone() {
94+ let options = parse_args(args(&["--shout"]));
95+ assert!(options.shout);
96+ assert_eq!(options.name, None);
97+ }
98+
99+ #[test]
100+ fn shout_upper_cases_greeting() {
101+ assert_eq!(shout(&greeting("Ada")), "HELLO, ADA!");
102+ }
103+
104+ #[test]
60105 fn greets_by_name() {
61106 assert_eq!(greeting("Ada"), "Hello, Ada!");
62107 }
+5−3
11 use std::env;
22
3−use hello::{greeting, parse_args};
3+use hello::{greeting, parse_args, shout};
44
55 fn main() {
6+ let options = parse_args(env::args().skip(1));
67 // The name given, or whoever is signed in.
7− let name = parse_args(env::args().skip(1))
8+ let name = options
89 .name
910 .or_else(|| env::var("USER").ok())
1011 .unwrap_or_else(|| "world".to_owned());
11− println!("{}", greeting(&name));
12+ let message = greeting(&name);
13+ println!("{}", if options.shout { shout(&message) } else { message });
1214 }