flagon-io/hello

public

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

hello/src/lib.rs

351 lines9,959 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Greet people from the command line1//! Greetings.
2
Merge #53: Add a --lang option (en, es, fr) to the greeter3/// A supported greeting language.
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
5pub enum Lang {
6 #[default]
7 En,
8 Es,
9 Fr,
10}
11
12impl Lang {
13 /// Parses a language code (`en`, `es` or `fr`).
14 pub fn parse(code: &str) -> Option<Lang> {
15 match code {
16 "en" => Some(Lang::En),
17 "es" => Some(Lang::Es),
18 "fr" => Some(Lang::Fr),
19 _ => None,
20 }
21 }
22}
23
Extract argument parsing into parse_args in lib.rs24/// Parsed command-line options.
Add --times N flag that prints the greeting N times25#[derive(Debug, PartialEq, Eq)]
Extract argument parsing into parse_args in lib.rs26pub struct Options {
27 /// The name to greet, if one was given.
28 pub name: Option<String>,
Add --shout flag that upper-cases the greeting29 /// Whether to upper-case the greeting (`--shout`).
30 pub shout: bool,
Add --version flag that prints the crate version and exits31 /// Whether to print the crate version and exit (`--version`).
32 pub version: bool,
Add --times N flag that prints the greeting N times33 /// How many times to print the greeting (`--times N`).
34 pub times: usize,
Merge #53: Add a --lang option (en, es, fr) to the greeter35 /// The greeting language (`--lang CODE`).
36 pub lang: Lang,
Add --quiet flag that prints nothing37 /// Whether to print nothing (`--quiet`).
38 pub quiet: bool,
Add --loud flag that ends the greeting with three exclamation marks39 /// Whether to end the greeting with three exclamation marks (`--loud`).
40 pub loud: bool,
Merge #64: Add a --bye flag41 /// Whether to print a goodbye after the greeting (`--bye`).
42 pub bye: bool,
Add --wave flag that prints o/ after the greeting43 /// Whether to print a wave after the greeting (`--wave`).
44 pub wave: bool,
Add --times N flag that prints the greeting N times45}
46
47impl Default for Options {
48 fn default() -> Self {
49 Options {
50 name: None,
51 shout: false,
52 version: false,
53 times: 1,
Merge #53: Add a --lang option (en, es, fr) to the greeter54 lang: Lang::En,
Add --quiet flag that prints nothing55 quiet: false,
Add --loud flag that ends the greeting with three exclamation marks56 loud: false,
Merge #64: Add a --bye flag57 bye: false,
Add --wave flag that prints o/ after the greeting58 wave: false,
Add --times N flag that prints the greeting N times59 }
60 }
Extract argument parsing into parse_args in lib.rs61}
62
63/// Parses command-line arguments (excluding the program name).
64///
Add --times N flag that prints the greeting N times65/// `--shout` sets [`Options::shout`], `--version` sets
66/// [`Options::version`], and `--times N` sets [`Options::times`] (the
Merge #53: Add a --lang option (en, es, fr) to the greeter67/// next argument is consumed as the value), and `--lang CODE` sets
68/// [`Options::lang`] (likewise consuming the next argument); other
69/// arguments starting with `--` are treated as flags and skipped. The
70/// name is the first remaining argument.
Add --times N flag that prints the greeting N times71///
Merge #53: Add a --lang option (en, es, fr) to the greeter72/// Returns an error message if `--times` has a missing or non-numeric
73/// value, or if `--lang` has a missing or unsupported value.
Add --times N flag that prints the greeting N times74pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Options, String> {
Add --shout flag that upper-cases the greeting75 let mut options = Options::default();
Add --times N flag that prints the greeting N times76 let mut args = args.into_iter();
77 while let Some(arg) = args.next() {
Add --shout flag that upper-cases the greeting78 if arg == "--shout" {
79 options.shout = true;
Add --version flag that prints the crate version and exits80 } else if arg == "--version" {
81 options.version = true;
Add --quiet flag that prints nothing82 } else if arg == "--quiet" {
83 options.quiet = true;
Accept -L as a short alias for --loud84 } else if arg == "--loud" || arg == "-L" {
Add --loud flag that ends the greeting with three exclamation marks85 options.loud = true;
Merge #64: Add a --bye flag86 } else if arg == "--bye" {
87 options.bye = true;
Add --wave flag that prints o/ after the greeting88 } else if arg == "--wave" {
89 options.wave = true;
Add --times N flag that prints the greeting N times90 } else if arg == "--times" {
91 let value = args
92 .next()
93 .ok_or_else(|| "--times requires a value".to_owned())?;
94 options.times = value
95 .parse()
96 .map_err(|_| format!("--times value must be a number, got {value:?}"))?;
Merge #53: Add a --lang option (en, es, fr) to the greeter97 } else if arg == "--lang" {
98 let value = args
99 .next()
100 .ok_or_else(|| "--lang requires a value".to_owned())?;
101 options.lang = Lang::parse(&value).ok_or_else(|| {
102 format!("--lang value must be one of en, es, fr, got {value:?}")
103 })?;
Add --shout flag that upper-cases the greeting104 } else if !arg.starts_with("--") && options.name.is_none() {
105 options.name = Some(arg);
106 }
107 }
Add --times N flag that prints the greeting N times108 Ok(options)
Extract argument parsing into parse_args in lib.rs109}
110
Add --shout flag that upper-cases the greeting111/// `text` upper-cased.
112pub fn shout(text: &str) -> String {
113 text.to_uppercase()
114}
115
Add --loud flag that ends the greeting with three exclamation marks116/// `text` with its final exclamation mark replaced by three.
117pub fn loud(text: &str) -> String {
118 format!("{}!!!", text.strip_suffix('!').unwrap_or(text))
119}
120
Greet people from the command line121/// The greeting for `name`.
Merge main into wave flag branch122pub fn hail(name: &str) -> String {
Merge #53: Add a --lang option (en, es, fr) to the greeter123 greeting_in(name, Lang::En)
124}
125
126/// The greeting for `name` in `lang`.
127pub fn greeting_in(name: &str, lang: Lang) -> String {
Handle empty and whitespace-only names, trim whitespace from input128 let trimmed = name.trim();
129 let display_name = if trimmed.is_empty() { "world" } else { trimmed };
Merge #53: Add a --lang option (en, es, fr) to the greeter130 match lang {
131 Lang::En => format!("Hi, {display_name}!"),
132 Lang::Es => format!("¡Hola, {display_name}!"),
133 Lang::Fr => format!("Bonjour, {display_name} !"),
134 }
Greet people from the command line135}
136
Add --wave flag that prints o/ after the greeting137/// The wave printed by `--wave`.
138pub fn wave() -> &'static str {
139 "o/"
140}
141
Add farewell function alongside greeting142/// The farewell for `name`.
Merge main into wave flag branch143pub fn part(name: &str) -> String {
Add farewell function alongside greeting144 let trimmed = name.trim();
145 let display_name = if trimmed.is_empty() { "world" } else { trimmed };
146 format!("Goodbye, {display_name}!")
147}
148
Greet people from the command line149#[cfg(test)]
150mod tests {
151 use super::*;
152
Extract argument parsing into parse_args in lib.rs153 fn args(list: &[&str]) -> Vec<String> {
154 list.iter().map(|s| s.to_string()).collect()
155 }
156
157 #[test]
Add --quiet flag that prints nothing158 fn parse_args_quiet() {
159 assert!(parse_args(args(&["--quiet", "Ada"])).unwrap().quiet);
160 assert!(!parse_args(args(&["Ada"])).unwrap().quiet);
161 }
162
163 #[test]
Merge #64: Add a --bye flag164 fn parse_args_bye() {
165 assert!(parse_args(args(&["--bye", "Ada"])).unwrap().bye);
166 assert!(!parse_args(args(&["Ada"])).unwrap().bye);
167 }
168
169 #[test]
Add --wave flag that prints o/ after the greeting170 fn parse_args_wave() {
171 assert!(parse_args(args(&["--wave", "Ada"])).unwrap().wave);
172 assert!(!parse_args(args(&["Ada"])).unwrap().wave);
173 }
174
175 #[test]
176 fn wave_is_o_slash() {
177 assert_eq!(wave(), "o/");
178 }
179
180 #[test]
Add --loud flag that ends the greeting with three exclamation marks181 fn parse_args_loud() {
182 assert!(parse_args(args(&["--loud", "Ada"])).unwrap().loud);
Accept -L as a short alias for --loud183 assert!(parse_args(args(&["-L", "Ada"])).unwrap().loud);
Add --loud flag that ends the greeting with three exclamation marks184 assert!(!parse_args(args(&["Ada"])).unwrap().loud);
185 }
186
187 #[test]
188 fn loud_uses_three_exclamation_marks() {
Merge main into wave flag branch189 assert_eq!(loud(&hail("Ada")), "Hi, Ada!!!");
Add --loud flag that ends the greeting with three exclamation marks190 }
191
192 #[test]
Extract argument parsing into parse_args in lib.rs193 fn parse_args_no_args() {
Add --times N flag that prints the greeting N times194 assert_eq!(parse_args(args(&[])).unwrap().name, None);
Extract argument parsing into parse_args in lib.rs195 }
196
197 #[test]
198 fn parse_args_name() {
Add --times N flag that prints the greeting N times199 assert_eq!(parse_args(args(&["Ada"])).unwrap().name.as_deref(), Some("Ada"));
Extract argument parsing into parse_args in lib.rs200 }
201
202 #[test]
203 fn parse_args_skips_leading_flag() {
204 assert_eq!(
Add --times N flag that prints the greeting N times205 parse_args(args(&["--unknown", "Ada"])).unwrap().name.as_deref(),
Extract argument parsing into parse_args in lib.rs206 Some("Ada")
207 );
208 }
209
Greet people from the command line210 #[test]
Add --shout flag that upper-cases the greeting211 fn parse_args_shout_defaults_off() {
Add --times N flag that prints the greeting N times212 assert!(!parse_args(args(&["Ada"])).unwrap().shout);
Add --shout flag that upper-cases the greeting213 }
214
215 #[test]
216 fn parse_args_shout_before_name() {
Add --times N flag that prints the greeting N times217 let options = parse_args(args(&["--shout", "Ada"])).unwrap();
Add --shout flag that upper-cases the greeting218 assert!(options.shout);
219 assert_eq!(options.name.as_deref(), Some("Ada"));
220 }
221
222 #[test]
223 fn parse_args_shout_after_name() {
Add --times N flag that prints the greeting N times224 let options = parse_args(args(&["Ada", "--shout"])).unwrap();
Add --shout flag that upper-cases the greeting225 assert!(options.shout);
226 assert_eq!(options.name.as_deref(), Some("Ada"));
227 }
228
229 #[test]
230 fn parse_args_shout_alone() {
Add --times N flag that prints the greeting N times231 let options = parse_args(args(&["--shout"])).unwrap();
Add --shout flag that upper-cases the greeting232 assert!(options.shout);
233 assert_eq!(options.name, None);
234 }
235
236 #[test]
Add --version flag that prints the crate version and exits237 fn parse_args_version_defaults_off() {
Add --times N flag that prints the greeting N times238 assert!(!parse_args(args(&["Ada"])).unwrap().version);
Add --version flag that prints the crate version and exits239 }
240
241 #[test]
242 fn parse_args_version() {
Add --times N flag that prints the greeting N times243 let options = parse_args(args(&["--version"])).unwrap();
Add --version flag that prints the crate version and exits244 assert!(options.version);
245 assert_eq!(options.name, None);
246 }
247
248 #[test]
Add --times N flag that prints the greeting N times249 fn parse_args_times_defaults_to_one() {
250 assert_eq!(parse_args(args(&["Ada"])).unwrap().times, 1);
251 }
252
253 #[test]
254 fn parse_args_times_valid() {
255 let options = parse_args(args(&["--times", "3", "Ada"])).unwrap();
256 assert_eq!(options.times, 3);
257 assert_eq!(options.name.as_deref(), Some("Ada"));
258 }
259
260 #[test]
261 fn parse_args_times_missing_value() {
262 assert!(parse_args(args(&["--times"])).is_err());
263 }
264
265 #[test]
266 fn parse_args_times_non_number() {
267 assert!(parse_args(args(&["--times", "abc", "Ada"])).is_err());
268 }
269
270 #[test]
Merge #53: Add a --lang option (en, es, fr) to the greeter271 fn parse_args_lang_defaults_to_en() {
272 assert_eq!(parse_args(args(&["Ada"])).unwrap().lang, Lang::En);
273 }
274
275 #[test]
276 fn parse_args_lang_valid() {
277 let options = parse_args(args(&["--lang", "es", "Ana"])).unwrap();
278 assert_eq!(options.lang, Lang::Es);
279 assert_eq!(options.name.as_deref(), Some("Ana"));
280 assert_eq!(parse_args(args(&["--lang", "fr"])).unwrap().lang, Lang::Fr);
281 }
282
283 #[test]
284 fn parse_args_lang_missing_value() {
285 assert_eq!(
286 parse_args(args(&["--lang"])).unwrap_err(),
287 "--lang requires a value"
288 );
289 }
290
291 #[test]
292 fn parse_args_lang_unknown() {
293 assert_eq!(
294 parse_args(args(&["--lang", "de"])).unwrap_err(),
295 "--lang value must be one of en, es, fr, got \"de\""
296 );
297 }
298
299 #[test]
300 fn greeting_in_each_language() {
301 assert_eq!(greeting_in("Ada", Lang::En), "Hi, Ada!");
302 assert_eq!(greeting_in("Ana", Lang::Es), "¡Hola, Ana!");
303 assert_eq!(greeting_in("Luc", Lang::Fr), "Bonjour, Luc !");
304 }
305
306 #[test]
307 fn greeting_in_trims_and_falls_back_to_world() {
308 assert_eq!(greeting_in(" Ana ", Lang::Es), "¡Hola, Ana!");
309 assert_eq!(greeting_in(" ", Lang::Fr), "Bonjour, world !");
310 }
311
312 #[test]
Add --shout flag that upper-cases the greeting313 fn shout_upper_cases_greeting() {
Merge main into wave flag branch314 assert_eq!(shout(&hail("Ada")), "HI, ADA!");
Add --shout flag that upper-cases the greeting315 }
316
317 #[test]
Greet people from the command line318 fn greets_by_name() {
Merge main into wave flag branch319 assert_eq!(hail("Ada"), "Hi, Ada!");
Greet people from the command line320 }
Handle empty and whitespace-only names, trim whitespace from input321
322 #[test]
323 fn greets_world_with_empty_string() {
Merge main into wave flag branch324 assert_eq!(hail(""), "Hi, world!");
Handle empty and whitespace-only names, trim whitespace from input325 }
326
327 #[test]
328 fn greets_world_with_whitespace_only() {
Merge main into wave flag branch329 assert_eq!(hail(" "), "Hi, world!");
Handle empty and whitespace-only names, trim whitespace from input330 }
331
332 #[test]
333 fn trims_whitespace_from_name() {
Merge main into wave flag branch334 assert_eq!(hail(" Ada "), "Hi, Ada!");
Handle empty and whitespace-only names, trim whitespace from input335 }
Add farewell function alongside greeting336
337 #[test]
338 fn says_goodbye_by_name() {
Merge main into wave flag branch339 assert_eq!(part("Ada"), "Goodbye, Ada!");
Add farewell function alongside greeting340 }
341
342 #[test]
343 fn says_goodbye_to_world_when_blank() {
Merge main into wave flag branch344 assert_eq!(part(" "), "Goodbye, world!");
Add farewell function alongside greeting345 }
346
347 #[test]
348 fn farewell_trims_whitespace() {
Merge main into wave flag branch349 assert_eq!(part(" Ada "), "Goodbye, Ada!");
Add farewell function alongside greeting350 }
Greet people from the command line351}

This file's history is long; its oldest lines are credited to the oldest commit read.