ytil_sys/cli.rs
1const HELP_ARG: &str = "--help";
2
3/// Abstraction over command-line argument collections for help detection and access.
4///
5/// # Type Parameters
6/// - `T` The type of individual arguments, typically string-like (e.g., `String`, `&str`).
7///
8/// # Rationale
9/// - Enables polymorphic argument handling without coupling to specific collection types.
10/// - Centralizes help flag detection logic for consistency across binaries.
11/// - Supports both owned and borrowed argument slices for flexibility.
12///
13/// # Performance
14/// - `has_help` performs a linear scan; suitable for small argument lists (typical CLI usage).
15/// - `all` clones arguments; use borrowed types (`T = &str`) to avoid allocation overhead.
16pub trait Args<T> {
17 /// Checks if the help flag (`--help`) is present in the arguments.
18 ///
19 ///
20 /// # Rationale
21 /// - Standardized help detection avoids ad-hoc string comparisons in binaries.
22 /// - Case-sensitive matching aligns with common CLI conventions.
23 fn has_help(&self) -> bool;
24
25 /// Returns a copy of all arguments.
26 ///
27 ///
28 /// # Rationale
29 /// - Provides uniform access to arguments regardless of underlying storage.
30 /// - Cloning ensures caller ownership; consider `T = &str` for zero-copy variants.
31 fn all(&self) -> Vec<T>;
32}
33
34impl<T: AsRef<str> + Clone> Args<T> for Vec<T> {
35 fn has_help(&self) -> bool {
36 self.iter().any(|arg| arg.as_ref() == HELP_ARG)
37 }
38
39 fn all(&self) -> Self {
40 self.clone()
41 }
42}
43
44impl Args<String> for pico_args::Arguments {
45 fn has_help(&self) -> bool {
46 self.clone().contains(HELP_ARG)
47 }
48
49 fn all(&self) -> Vec<String> {
50 self.clone()
51 .finish()
52 .into_iter()
53 .map(|arg| arg.to_string_lossy().to_string())
54 .collect()
55 }
56}
57
58/// Retrieves command-line arguments excluding the program name, returning them as a [`Vec`] of [`String`].
59pub fn get() -> Vec<String> {
60 let mut args = std::env::args();
61 args.next();
62 args.collect::<Vec<String>>()
63}