flagon-io/hello

public

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

Greet with Hi instead of Hello #42

Mergedg1tbot merged into maing1t-agenton g1t

Approved by g1t-agent

11 files+436−00/11 viewed
+19−0
1+root = true
2+
3+[*]
4+charset = utf-8
5+end_of_line = lf
6+insert_final_newline = true
7+trim_trailing_whitespace = true
8+
9+[*.rs]
10+indent_style = space
11+indent_size = 4
12+
13+[*.md]
14+indent_style = space
15+trim_trailing_whitespace = true
16+
17+[*.toml]
18+indent_style = space
19+indent_size = 4
+1−0
1+/target
+14−0
1+# Changelog
2+
3+All notable changes to this project will be documented in this file.
4+
5+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7+
8+## [Unreleased]
9+
10+### Added
11+
12+- `--shout` flag that upper-cases the greeting
13+- `--version` flag that prints the crate version and exits
14+- `--times N` flag that prints the greeting N times (default 1)
+33−0
1+# Contributing
2+
3+Thanks for helping improve `hello`. This guide explains how to build the project, run its tests and propose a change.
4+
5+## Build
6+
7+The crate is written in Rust (2021 edition). The logic lives in `src/lib.rs` (`parse_args`), the entry point is `src/main.rs`, and integration tests are in `tests/cli.rs`.
8+
9+```sh
10+cargo build
11+```
12+
13+To try your changes, run the binary through Cargo:
14+
15+```sh
16+cargo run -- --shout Ada
17+```
18+
19+## Test
20+
21+```sh
22+cargo test
23+```
24+
25+## Propose a change
26+
27+1. Fork the repository and clone your fork.
28+2. Create a branch for your change.
29+3. Make a focused change that does one thing, and add or update tests for it.
30+4. Run `cargo test` and make sure it passes.
31+5. If you add or change a flag, update the usage section in `README.md`.
32+6. Add an entry under Unreleased in `CHANGELOG.md`.
33+7. Open a pull request that describes what you changed and why.
+7−0
1+# This file is automatically @generated by Cargo.
2+# It is not intended for manual editing.
3+version = 4
4+
5+[[package]]
6+name = "hello"
7+version = "0.1.0"
+6−0
1+[package]
2+name = "hello"
3+version = "0.1.0"
4+edition = "2021"
5+description = "Greets people from the command line."
6+license = "MIT"
+21−0
1+MIT License
2+
3+Copyright (c) 2026 hello contributors
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
+58−0
1+# hello
2+
3+Greets people from the command line.
4+
5+## Usage
6+
7+| Argument | Description |
8+| -------- | ----------- |
9+| `NAME` | Optional. The name to greet. Only the first argument is read. Defaults to the `USER` environment variable, then to `world`. |
10+| `--shout` | Upper-cases the greeting. |
11+| `--version` | Prints the crate version and exits. |
12+| `--times N` | Prints the greeting `N` times. Defaults to 1. |
13+
14+```sh
15+$ cargo run -- Ada
16+Hi, Ada!
17+```
18+
19+```sh
20+$ cargo run -- --shout Ada
21+HI, ADA!
22+```
23+
24+```sh
25+$ cargo run -- --times 2 Ada
26+Hi, Ada!
27+Hi, Ada!
28+```
29+
30+```sh
31+$ cargo run -- --version
32+0.1.0
33+```
34+
35+With no name it greets whoever is signed in.
36+
37+## Develop
38+
39+This project uses the Rust 2021 edition.
40+
41+```sh
42+cargo test
43+```
44+
45+## Troubleshooting
46+
47+**`error: --times value must be a number, got "abc"`**
48+
49+`--times` needs a whole number of zero or more. If the value is anything else, such as `abc`, `-1` or `2.5`, the program prints this error to stderr and exits with status 2 without greeting anyone. Pass a plain number, for example `--times 3`. A `--times` with no value after it also fails, with `--times requires a value`.
50+
51+**The greeting says `Hi, world!` when I gave a name**
52+
53+An empty or whitespace-only name, such as `cargo run -- ""`, is treated as no name and the greeting uses `world`. It does not fall back to the `USER` environment variable; that only happens when no name argument is given at all. Check that your shell is not expanding the name to an empty string, for example from an unset variable like `"$NAME"`.
54+
55+## License
56+
57+This project is licensed under the MIT License.
58+The full license text is available at https://opensource.org/license/mit.
+202−0
1+//! Greetings.
2+
3+/// Parsed command-line options.
4+#[derive(Debug, PartialEq, Eq)]
5+pub struct Options {
6+ /// The name to greet, if one was given.
7+ pub name: Option<String>,
8+ /// Whether to upper-case the greeting (`--shout`).
9+ pub shout: bool,
10+ /// Whether to print the crate version and exit (`--version`).
11+ pub version: bool,
12+ /// How many times to print the greeting (`--times N`).
13+ pub times: usize,
14+}
15+
16+impl Default for Options {
17+ fn default() -> Self {
18+ Options {
19+ name: None,
20+ shout: false,
21+ version: false,
22+ times: 1,
23+ }
24+ }
25+}
26+
27+/// Parses command-line arguments (excluding the program name).
28+///
29+/// `--shout` sets [`Options::shout`], `--version` sets
30+/// [`Options::version`], and `--times N` sets [`Options::times`] (the
31+/// next argument is consumed as the value); other arguments starting
32+/// with `--` are treated as flags and skipped. The name is the first
33+/// remaining argument.
34+///
35+/// Returns an error message if `--times` has a missing or non-numeric value.
36+pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Options, String> {
37+ let mut options = Options::default();
38+ let mut args = args.into_iter();
39+ while let Some(arg) = args.next() {
40+ if arg == "--shout" {
41+ options.shout = true;
42+ } else if arg == "--version" {
43+ options.version = true;
44+ } else if arg == "--times" {
45+ let value = args
46+ .next()
47+ .ok_or_else(|| "--times requires a value".to_owned())?;
48+ options.times = value
49+ .parse()
50+ .map_err(|_| format!("--times value must be a number, got {value:?}"))?;
51+ } else if !arg.starts_with("--") && options.name.is_none() {
52+ options.name = Some(arg);
53+ }
54+ }
55+ Ok(options)
56+}
57+
58+/// `text` upper-cased.
59+pub fn shout(text: &str) -> String {
60+ text.to_uppercase()
61+}
62+
63+/// The greeting for `name`.
64+pub fn greeting(name: &str) -> String {
65+ let trimmed = name.trim();
66+ let display_name = if trimmed.is_empty() { "world" } else { trimmed };
67+ format!("Hi, {display_name}!")
68+}
69+
70+/// The farewell for `name`.
71+pub fn farewell(name: &str) -> String {
72+ let trimmed = name.trim();
73+ let display_name = if trimmed.is_empty() { "world" } else { trimmed };
74+ format!("Goodbye, {display_name}!")
75+}
76+
77+#[cfg(test)]
78+mod tests {
79+ use super::*;
80+
81+ fn args(list: &[&str]) -> Vec<String> {
82+ list.iter().map(|s| s.to_string()).collect()
83+ }
84+
85+ #[test]
86+ fn parse_args_no_args() {
87+ assert_eq!(parse_args(args(&[])).unwrap().name, None);
88+ }
89+
90+ #[test]
91+ fn parse_args_name() {
92+ assert_eq!(parse_args(args(&["Ada"])).unwrap().name.as_deref(), Some("Ada"));
93+ }
94+
95+ #[test]
96+ fn parse_args_skips_leading_flag() {
97+ assert_eq!(
98+ parse_args(args(&["--unknown", "Ada"])).unwrap().name.as_deref(),
99+ Some("Ada")
100+ );
101+ }
102+
103+ #[test]
104+ fn parse_args_shout_defaults_off() {
105+ assert!(!parse_args(args(&["Ada"])).unwrap().shout);
106+ }
107+
108+ #[test]
109+ fn parse_args_shout_before_name() {
110+ let options = parse_args(args(&["--shout", "Ada"])).unwrap();
111+ assert!(options.shout);
112+ assert_eq!(options.name.as_deref(), Some("Ada"));
113+ }
114+
115+ #[test]
116+ fn parse_args_shout_after_name() {
117+ let options = parse_args(args(&["Ada", "--shout"])).unwrap();
118+ assert!(options.shout);
119+ assert_eq!(options.name.as_deref(), Some("Ada"));
120+ }
121+
122+ #[test]
123+ fn parse_args_shout_alone() {
124+ let options = parse_args(args(&["--shout"])).unwrap();
125+ assert!(options.shout);
126+ assert_eq!(options.name, None);
127+ }
128+
129+ #[test]
130+ fn parse_args_version_defaults_off() {
131+ assert!(!parse_args(args(&["Ada"])).unwrap().version);
132+ }
133+
134+ #[test]
135+ fn parse_args_version() {
136+ let options = parse_args(args(&["--version"])).unwrap();
137+ assert!(options.version);
138+ assert_eq!(options.name, None);
139+ }
140+
141+ #[test]
142+ fn parse_args_times_defaults_to_one() {
143+ assert_eq!(parse_args(args(&["Ada"])).unwrap().times, 1);
144+ }
145+
146+ #[test]
147+ fn parse_args_times_valid() {
148+ let options = parse_args(args(&["--times", "3", "Ada"])).unwrap();
149+ assert_eq!(options.times, 3);
150+ assert_eq!(options.name.as_deref(), Some("Ada"));
151+ }
152+
153+ #[test]
154+ fn parse_args_times_missing_value() {
155+ assert!(parse_args(args(&["--times"])).is_err());
156+ }
157+
158+ #[test]
159+ fn parse_args_times_non_number() {
160+ assert!(parse_args(args(&["--times", "abc", "Ada"])).is_err());
161+ }
162+
163+ #[test]
164+ fn shout_upper_cases_greeting() {
165+ assert_eq!(shout(&greeting("Ada")), "HI, ADA!");
166+ }
167+
168+ #[test]
169+ fn greets_by_name() {
170+ assert_eq!(greeting("Ada"), "Hi, Ada!");
171+ }
172+
173+ #[test]
174+ fn greets_world_with_empty_string() {
175+ assert_eq!(greeting(""), "Hi, world!");
176+ }
177+
178+ #[test]
179+ fn greets_world_with_whitespace_only() {
180+ assert_eq!(greeting(" "), "Hi, world!");
181+ }
182+
183+ #[test]
184+ fn trims_whitespace_from_name() {
185+ assert_eq!(greeting(" Ada "), "Hi, Ada!");
186+ }
187+
188+ #[test]
189+ fn says_goodbye_by_name() {
190+ assert_eq!(farewell("Ada"), "Goodbye, Ada!");
191+ }
192+
193+ #[test]
194+ fn says_goodbye_to_world_when_blank() {
195+ assert_eq!(farewell(" "), "Goodbye, world!");
196+ }
197+
198+ #[test]
199+ fn farewell_trims_whitespace() {
200+ assert_eq!(farewell(" Ada "), "Goodbye, Ada!");
201+ }
202+}
+27−0
1+use std::{env, process};
2+
3+use hello::{greeting, parse_args, shout};
4+
5+fn main() {
6+ let options = match parse_args(env::args().skip(1)) {
7+ Ok(options) => options,
8+ Err(message) => {
9+ eprintln!("error: {message}");
10+ process::exit(2);
11+ }
12+ };
13+ if options.version {
14+ println!("{}", env!("CARGO_PKG_VERSION"));
15+ return;
16+ }
17+ // The name given, or whoever is signed in.
18+ let name = options
19+ .name
20+ .or_else(|| env::var("USER").ok())
21+ .unwrap_or_else(|| "world".to_owned());
22+ let message = greeting(&name);
23+ let line = if options.shout { shout(&message) } else { message };
24+ for _ in 0..options.times {
25+ println!("{line}");
26+ }
27+}
+48−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+}
15+
16+fn run(args: &[&str]) -> std::process::Output {
17+ Command::new(env!("CARGO_BIN_EXE_hello"))
18+ .args(args)
19+ .output()
20+ .unwrap()
21+}
22+
23+#[test]
24+fn times_prints_greeting_repeatedly() {
25+ let output = run(&["--times", "3", "Ada"]);
26+ assert!(output.status.success());
27+ assert_eq!(
28+ String::from_utf8(output.stdout).unwrap(),
29+ "Hi, Ada!\n".repeat(3)
30+ );
31+}
32+
33+#[test]
34+fn times_combines_with_shout() {
35+ let output = run(&["--times", "2", "--shout", "Ada"]);
36+ assert!(output.status.success());
37+ assert_eq!(
38+ String::from_utf8(output.stdout).unwrap(),
39+ "HI, ADA!\n".repeat(2)
40+ );
41+}
42+
43+#[test]
44+fn times_with_bad_value_fails() {
45+ let output = run(&["--times", "abc"]);
46+ assert!(!output.status.success());
47+ assert!(!output.stderr.is_empty());
48+}