cargo_e/
e_cli.rs

1use clap::Parser;
2
3#[derive(Parser, Debug, Clone)]
4#[command(author,version, about = "cargo-e is for Example.", long_about = None)]
5#[command(disable_version_flag = true)]
6pub struct Cli {
7    /// Run all examples for a given number of seconds.
8
9    /// Path to read/write the stdout of the executed command.
10    #[arg(
11        long,
12        value_name = "PATH",
13        help = "Path to read/write the stdout of the executed command."
14    )]
15    pub stdout: Option<std::path::PathBuf>,
16
17    /// Path to read/write the stderr of the executed command.
18    #[arg(
19        long,
20        value_name = "PATH",
21        help = "Path to read/write the stderr of the executed command."
22    )]
23    pub stderr: Option<std::path::PathBuf>,
24    ///
25    /// If provided with a value (e.g. `--run-all 10`), each target will run for 10 seconds.
26    /// If provided without a value (i.e. just `--run-all`), it means run forever.
27    /// If not provided at all, then the default wait time is used.
28    #[arg(
29        long,
30        num_args = 0..=1,
31        default_value_t = RunAll::NotSpecified,
32        default_missing_value ="",
33        value_parser,
34        help = "Run all optionally specifying run time (in seconds) per target. \
35                If the flag is present without a value, run forever."
36    )]
37    pub run_all: RunAll,
38
39    #[arg(long, help = "Create GIST run_report.md on exit.")]
40    pub gist: bool,
41    #[arg(long, help = "Build and run in release mode.")]
42    pub release: bool,
43    #[arg(
44        long,
45        short = 'q',
46        help = "Suppress cargo output when running the sample."
47    )]
48    pub quiet: bool,
49    // /// Comma-separated list of package names.
50    // #[clap(long, value_delimiter = ',', help = "Optional list of package names to run examples for. If omitted, defaults to ALL_PACKAGES.")]
51    // pub specified_packages: Vec<String>,
52    /// Pre-build examples before running.
53    #[clap(
54        long,
55        help = "If enabled, pre-build the examples before executing them."
56    )]
57    pub pre_build: bool,
58
59    /// Enable passthrough mode (no cargo output filtering, stdout is captured).
60    #[arg(
61        long = "filter",
62        short = 'f',
63        help = "Enable passthrough mode. No cargo output is filtered, and stdout is captured."
64    )]
65    pub filter: bool,
66    /// Print version and feature flags in JSON format.
67    #[arg(
68        long,
69        short = 'v',
70        help = "Print version and feature flags in JSON format."
71    )]
72    pub version: bool,
73
74    #[arg(
75        long,
76        short = 't',
77        help = "Launch the text-based user interface (TUI)."
78    )]
79    pub tui: bool,
80
81    #[arg(long, short = 'w', help = "Operate on the entire workspace.")]
82    pub workspace: bool,
83
84    /// Print the exit code of the process when run.
85    #[arg(
86        long = "pX",
87        default_value_t = false,
88        value_parser = clap::value_parser!(bool),
89        help = "Print the exit code of the process when run. (default: false)"
90    )]
91    pub print_exit_code: bool,
92
93    /// Print the program name before execution.
94    #[arg(
95        long = "pN",
96        default_value_t = false,
97        value_parser = clap::value_parser!(bool),
98        help = "Print the program name before execution. (default: false)"
99    )]
100    pub print_program_name: bool,
101
102    /// Print the program name before execution.
103    #[arg(
104        long = "pI",
105        default_value_t = true,
106        value_parser = clap::value_parser!(bool),
107        help = "Print the user instruction. (default: true)"
108    )]
109    pub print_instruction: bool,
110
111    #[arg(
112        long,
113        short = 'p',
114        default_value_t = true,
115        help = "Enable or disable paging (default: enabled)."
116    )]
117    pub paging: bool,
118
119    #[arg(
120        long,
121        short = 'r',
122        default_value_t = false,
123        help = "Relative numbers (default: enabled)."
124    )]
125    pub relative_numbers: bool,
126
127    #[arg(
128        long = "wait",
129        short = 'W',
130        default_value_t = 15,
131        help = "Set wait time in seconds (default: 15)."
132    )]
133    pub wait: u64,
134
135    /// Subcommands to run (e.g., `build|b`, `test|t`).
136    #[arg(
137        long = "subcommand",
138        short = 's',
139        value_parser,
140        default_value = "run",
141        help = "Specify subcommands (e.g., `build|b`, `test|t`)."
142    )]
143    pub subcommand: String,
144
145    #[arg(help = "Specify an explicit target to run.")]
146    pub explicit_example: Option<String>,
147
148    #[arg(
149        long = "run-at-a-time",
150        short = 'J',
151        default_value_t = 1,
152        value_parser = clap::value_parser!(usize),
153        help = "Number of targets to run at a time in --run-all mode (--run-at-a-time)"
154    )]
155    pub run_at_a_time: usize,
156
157    #[arg(
158        long = "nS",
159        default_value_t = false,
160        help = "Disable status lines during runtime loop output."
161    )]
162    pub no_status_lines: bool,
163
164    #[arg(
165        long = "nT",
166        default_value_t = false,
167        help = "Disable text-to-speech output."
168    )]
169    pub no_tts: bool,
170
171    #[arg(long = "nW", default_value_t = false, help = "Disable window popups.")]
172    pub no_window: bool,
173
174    #[arg(last = true, help = "Additional arguments passed to the command.")]
175    pub extra: Vec<String>,
176}
177
178/// Print the version and the JSON array of feature flags.
179pub fn print_version_and_features() {
180    // Print the version string.
181    let version = option_env!("CARGO_PKG_VERSION").unwrap_or("unknown");
182
183    // Build a list of feature flags. Enabled features are printed normally,
184    // while disabled features are prefixed with an exclamation mark.
185    let mut features = Vec::new();
186
187    if cfg!(feature = "tui") {
188        features.push("tui");
189    } else {
190        features.push("!tui");
191    }
192    if cfg!(feature = "concurrent") {
193        features.push("concurrent");
194    } else {
195        features.push("!concurrent");
196    }
197    if cfg!(target_os = "windows") {
198        features.push("windows");
199    } else {
200        features.push("!windows");
201    }
202    if cfg!(feature = "equivalent") {
203        features.push("equivalent");
204    } else {
205        features.push("!equivalent");
206    }
207
208    let json_features = format!(
209        "[{}]",
210        features
211            .iter()
212            .map(|f| format!("\"{}\"", f))
213            .collect::<Vec<String>>()
214            .join(", ")
215    );
216    println!("cargo-e {}", version);
217    println!("{}", json_features);
218    std::process::exit(0);
219}
220
221/// Returns a vector of feature flag strings.  
222/// Enabled features are listed as-is while disabled ones are prefixed with "!".
223pub fn get_feature_flags() -> Vec<&'static str> {
224    let mut flags = Vec::new();
225    if cfg!(feature = "tui") {
226        flags.push("tui");
227    } else {
228        flags.push("!tui");
229    }
230    if cfg!(feature = "concurrent") {
231        flags.push("concurrent");
232    } else {
233        flags.push("!concurrent");
234    }
235    if cfg!(target_os = "windows") {
236        flags.push("windows");
237    } else {
238        flags.push("!windows");
239    }
240    if cfg!(feature = "equivalent") {
241        flags.push("equivalent");
242    } else {
243        flags.push("!equivalent");
244    }
245    flags
246}
247
248use std::str::FromStr;
249
250/// Represents the state of the `--run-all` flag.
251#[derive(Debug, Clone, PartialEq, Default)]
252pub enum RunAll {
253    /// The flag was not specified.
254    #[default]
255    NotSpecified,
256    /// The flag was specified without a value—indicating “run forever.”
257    Forever,
258    /// The flag was specified with a timeout value.
259    Timeout(u64),
260}
261
262impl FromStr for RunAll {
263    type Err = String;
264    fn from_str(s: &str) -> Result<Self, Self::Err> {
265        // An empty string means the flag was provided without a value → run forever.
266        if s.is_empty() {
267            Ok(RunAll::Forever)
268        } else if s.eq_ignore_ascii_case("not_specified") {
269            Ok(RunAll::NotSpecified)
270        } else {
271            // Otherwise, try parsing a u64 value.
272            s.parse::<u64>()
273                .map(RunAll::Timeout)
274                .map_err(|e| e.to_string())
275        }
276    }
277}
278
279impl std::fmt::Display for RunAll {
280    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
281        match self {
282            RunAll::NotSpecified => write!(f, "not_specified"),
283            RunAll::Forever => write!(f, "forever"),
284            RunAll::Timeout(secs) => write!(f, "{}", secs),
285        }
286    }
287}
288
289pub fn custom_cli(args: &mut Vec<String>) -> (Option<usize>, Vec<&String>) {
290    // If the first argument after the binary name is "e", remove it.
291    if args.len() > 1 && args[1].as_str() == "e" {
292        args.remove(1);
293    }
294    let mut run_at_a_time: Option<usize> = None;
295    // default
296    let mut filtered_args = vec![];
297    for arg in &*args {
298        if let Some(num) = arg
299            .strip_prefix("--run-")
300            .and_then(|s| s.strip_suffix("-at-a-time"))
301        {
302            if let Ok(n) = num.parse() {
303                println!("run-at-a-time: {}", n);
304                run_at_a_time = Some(n);
305            }
306            // Don't push this arg to filtered_args
307            continue;
308        }
309        filtered_args.push(arg);
310    }
311    (run_at_a_time, filtered_args)
312}