Skip to main content

react_traits/
cli.rs

1use anyhow::{Context, Result};
2use clap::{Parser, Subcommand};
3use no_mistakes_core::cli::Format;
4use no_mistakes_core::react_traits;
5use std::path::PathBuf;
6use std::process::ExitCode;
7
8#[derive(Parser)]
9#[command(author, version, about)]
10pub(crate) struct Cli {
11    /// Project root directory.
12    #[arg(long, default_value = ".", global = true)]
13    pub(crate) root: PathBuf,
14    /// Config file path. Relative paths are resolved from --root.
15    #[arg(long, global = true)]
16    pub(crate) config: Option<PathBuf>,
17    /// Output format: json, yml, md, paths, human.
18    #[arg(
19        long,
20        value_enum,
21        default_value = "human",
22        global = true,
23        conflicts_with = "json"
24    )]
25    pub(crate) format: Format,
26    /// Shorthand for --format json.
27    #[arg(long, global = true, conflicts_with = "format")]
28    pub(crate) json: bool,
29    #[command(subcommand)]
30    pub(crate) command: Command,
31}
32
33#[derive(Subcommand)]
34pub(crate) enum Command {
35    /// Analyze component traits and print results.
36    Analyze {
37        #[arg(help = "Glob patterns for component files")]
38        targets: Vec<String>,
39    },
40    /// Check for violations such as components that call fetch.
41    Check {
42        #[arg(help = "Glob patterns for component files")]
43        targets: Vec<String>,
44        /// Exit non-zero if any component or rendered subtree calls fetch.
45        #[arg(long)]
46        assert_no_fetch: bool,
47    },
48}
49
50#[cfg(test)]
51fn parse_cli_args() -> Cli {
52    let raw_args = std::env::var("REACT_TRAITS_TEST_ARGS")
53        .expect("REACT_TRAITS_TEST_ARGS must be set in tests - use with_run_args_env()");
54    Cli::parse_from(raw_args.split('\u{1f}'))
55}
56
57#[cfg(not(test))]
58fn parse_cli_args() -> Cli {
59    Cli::parse()
60}
61
62pub fn run_cli() -> Result<ExitCode> {
63    let cli = parse_cli_args();
64    let base_root = std::env::current_dir().context("reading current directory")?;
65    let root = base_root.join(&cli.root);
66    let format = if cli.json { Format::Json } else { cli.format };
67    match &cli.command {
68        Command::Analyze { targets } => {
69            let results = react_traits::run_analyze(&root, cli.config.as_deref(), targets, None)?;
70            match format {
71                Format::Json => {
72                    println!(
73                        "{}",
74                        serde_json::to_string_pretty(&results)
75                            .context("serializing analysis results")?
76                    );
77                }
78                Format::Yml => {
79                    println!(
80                        "{}",
81                        serde_yaml::to_string(&results)
82                            .context("serializing analysis results to YAML")?
83                    );
84                }
85                Format::Md => react_traits::print_results_md(&results),
86                Format::Paths => {
87                    for result in &results {
88                        println!("{}", result.file);
89                    }
90                }
91                Format::Human => react_traits::print_results(&results, 0),
92            }
93            Ok(ExitCode::SUCCESS)
94        }
95        Command::Check {
96            targets,
97            assert_no_fetch,
98        } => {
99            let violations =
100                react_traits::run_check(&root, cli.config.as_deref(), targets, *assert_no_fetch)?;
101            if violations.is_empty() {
102                Ok(ExitCode::SUCCESS)
103            } else {
104                match format {
105                    Format::Json => {
106                        println!(
107                            "{}",
108                            serde_json::to_string_pretty(&violations)
109                                .context("serializing check violations")?
110                        );
111                    }
112                    Format::Yml => {
113                        println!(
114                            "{}",
115                            serde_yaml::to_string(&violations)
116                                .context("serializing check violations to YAML")?
117                        );
118                    }
119                    Format::Md => react_traits::print_violations_md(&violations),
120                    Format::Paths => {
121                        for violation in &violations {
122                            println!("{}", violation.file);
123                        }
124                    }
125                    Format::Human => react_traits::print_violations(&violations),
126                }
127                Ok(ExitCode::from(1))
128            }
129        }
130    }
131}