Skip to main content

cargo_axi/
lib.rs

1//! Process boundary for the `cargo axi` Cargo subcommand.
2
3pub mod cargo;
4mod cli;
5pub mod diagnostics;
6pub mod hooks;
7mod output;
8pub mod session;
9mod workspace;
10
11use std::path::Path;
12
13use serde::Serialize;
14
15use crate::{
16    cli::{Command, SessionAction},
17    output::{
18        ErrorResponse, FeaturesResponse, HelpResponse, HomeResponse, PackageResponse,
19        PackagesResponse, ValidationResponse,
20    },
21    workspace::Workspace,
22};
23
24/// A fully rendered response for the process boundary.
25#[derive(Debug)]
26pub struct RunResult {
27    /// The only data written to stdout.
28    pub stdout: String,
29    /// AXI's process status: 0 success, 1 application error, 2 usage error.
30    pub exit_code: i32,
31}
32
33/// Runs one `cargo axi` invocation from a caller-provided current directory.
34pub fn run(args: Vec<String>, current_dir: &Path, executable: &Path) -> RunResult {
35    let command = match cli::parse(&args) {
36        Ok(command) => command,
37        Err(error) => return render_error(error.message, error.help, 2),
38    };
39
40    match command {
41        Command::Help(topic) => render_success(HelpResponse::for_topic(topic)),
42        Command::SetupHooks(options) => {
43            match crate::hooks::execute(&options, current_dir, executable) {
44                Ok(response) => render_success(response),
45                Err(error) => render_error(error.message, error.help, 1),
46            }
47        }
48        Command::Session(action) => match Workspace::load(current_dir) {
49            Ok(workspace) => match action {
50                SessionAction::Start => match crate::session::start(workspace.root()) {
51                    Ok(previous) => {
52                        render_success(HomeResponse::new(&workspace, executable, previous))
53                    }
54                    Err(_) => render_error(
55                        "could not start cargo-axi session capture",
56                        "Check the user state directory and rerun `cargo axi session start`.",
57                        1,
58                    ),
59                },
60                SessionAction::End => match crate::session::end(workspace.root()) {
61                    Ok(response) => render_success(response),
62                    Err(_) => render_error(
63                        "could not finish cargo-axi session capture",
64                        "Check the user state directory and rerun `cargo axi session end`.",
65                        1,
66                    ),
67                },
68                SessionAction::Clear => match crate::session::clear(workspace.root()) {
69                    Ok(response) => render_success(response),
70                    Err(_) => render_error(
71                        "could not clear cargo-axi session capture",
72                        "Check the user state directory and rerun `cargo axi session clear`.",
73                        1,
74                    ),
75                },
76            },
77            Err(_) => render_error(
78                "could not read Cargo workspace metadata",
79                "Run `cargo axi session` from a valid Rust package or workspace.",
80                1,
81            ),
82        },
83        command => match Workspace::load(current_dir) {
84            Ok(workspace) => run_workspace_command(command, &workspace, executable, current_dir),
85            Err(_) => render_error(
86                "could not read Cargo workspace metadata",
87                "Run `cargo axi` from a valid Rust package or workspace.",
88                1,
89            ),
90        },
91    }
92}
93
94fn run_workspace_command(
95    command: Command,
96    workspace: &Workspace,
97    executable: &Path,
98    current_dir: &Path,
99) -> RunResult {
100    match command {
101        Command::Home => render_success(HomeResponse::new(
102            workspace,
103            executable,
104            crate::session::previous(workspace.root()),
105        )),
106        Command::Packages { limit, full } => {
107            render_success(PackagesResponse::new(workspace, limit, full))
108        }
109        Command::Package { package, full } => match workspace.package(&package) {
110            Some(package) => render_success(PackageResponse::new(package, full)),
111            None => render_error(
112                format!("package `{package}` is not a workspace member"),
113                "Run `cargo axi packages` to list workspace packages.",
114                1,
115            ),
116        },
117        Command::Features { package, full } => match workspace.package(&package) {
118            Some(package) => render_success(FeaturesResponse::new(package, full)),
119            None => render_error(
120                format!("package `{package}` is not a workspace member"),
121                "Run `cargo axi packages` to list workspace packages.",
122                1,
123            ),
124        },
125        Command::Validation { kind, options } => {
126            if let crate::cli::Selection::Package(package) = &options.selection {
127                if workspace.package(package).is_none() {
128                    return render_error(
129                        format!("package `{package}` is not a workspace member"),
130                        "Run `cargo axi packages` to list workspace packages.",
131                        1,
132                    );
133                }
134            }
135
136            match crate::cargo::run(kind, &options, current_dir) {
137                Ok(run) => {
138                    let successful = run.successful;
139                    let diagnostics = crate::diagnostics::normalize(&run.stdout, workspace.root());
140                    let response = ValidationResponse::new(
141                        kind,
142                        &options,
143                        successful,
144                        run.duration,
145                        diagnostics,
146                        workspace.root().join("Cargo.lock").is_file(),
147                    );
148                    if let Some(summary) = response.check.as_ref().or(response.clippy.as_ref()) {
149                        crate::session::record_validation(workspace.root(), kind, summary);
150                    }
151                    render(&response, if successful { 0 } else { 1 })
152                }
153                Err(_) => render_error(
154                    "could not start Cargo validation",
155                    "Ensure `cargo` is installed and available on PATH, then rerun the command.",
156                    1,
157                ),
158            }
159        }
160        Command::SetupHooks(_) => unreachable!("hook setup is handled before workspace loading"),
161        Command::Session(_) => unreachable!("session capture is handled before workspace loading"),
162        Command::Help(_) => unreachable!("help is handled before workspace loading"),
163    }
164}
165
166fn render_success(response: impl Serialize) -> RunResult {
167    render(&response, 0)
168}
169
170fn render_error(error: impl Into<String>, help: impl Into<String>, exit_code: i32) -> RunResult {
171    render(
172        &ErrorResponse {
173            error: error.into(),
174            help: vec![help.into()],
175        },
176        exit_code,
177    )
178}
179
180fn render(response: &impl Serialize, exit_code: i32) -> RunResult {
181    match output::encode(response) {
182        Ok(stdout) => RunResult {
183            stdout,
184            exit_code,
185        },
186        Err(_) => RunResult {
187            stdout: "error: internal output encoding failure\nhelp[1]: Run `cargo axi --help` for available commands".to_owned(),
188            exit_code: 1,
189        },
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    #[test]
196    fn bundled_skill_command_reference_matches_cli_metadata() {
197        const START: &str = "<!-- cargo-axi:command-reference:start -->";
198        const END: &str = "<!-- cargo-axi:command-reference:end -->";
199        let skill = include_str!(concat!(
200            env!("CARGO_MANIFEST_DIR"),
201            "/skills/cargo-axi/SKILL.md"
202        ));
203        let (_, generated) = skill
204            .split_once(START)
205            .expect("skill must start its generated command reference");
206        let (generated, _) = generated
207            .split_once(END)
208            .expect("skill must end its generated command reference");
209
210        assert_eq!(
211            generated.trim(),
212            crate::cli::skill_command_reference().trim()
213        );
214    }
215}