shipshape-cli 0.11.0

Release & readiness coordinator: the AI-first Rust CLI behind the /shipshape-* skill family.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! Machine-readable CLI help derived from clap's command tree.
//!
//! Text help remains entirely clap-owned. This module is entered only when a
//! successful clap help display also contains the global `--json` flag.

use std::ffi::OsString;

use clap::{Arg, Command, CommandFactory};
use serde::Serialize;

use crate::cli::Cli;
use crate::error::CliError;

const HELP_SCHEMA_VERSION: u32 = 1;

#[derive(Debug, Serialize)]
struct HelpDocument {
    schema_version: u32,
    command: CommandHelp,
}

#[derive(Debug, Serialize)]
struct CommandHelp {
    name: String,
    path: Vec<String>,
    description: Option<String>,
    usage: String,
    subcommands: Vec<SubcommandHelp>,
    flags: Vec<FlagHelp>,
    args: Vec<ArgumentHelp>,
    examples: Vec<Example>,
    exit_codes: Vec<ExitCodeHelp>,
    deprecated: bool,
}

#[derive(Debug, Serialize)]
struct SubcommandHelp {
    name: String,
    description: Option<String>,
    aliases: Vec<String>,
    deprecated: bool,
}

#[derive(Debug, Serialize)]
#[allow(clippy::struct_excessive_bools)] // These independent booleans are the public help schema.
struct FlagHelp {
    id: String,
    long: Option<String>,
    short: Option<char>,
    description: Option<String>,
    required: bool,
    global: bool,
    hidden: bool,
    takes_value: bool,
    value_names: Vec<String>,
    defaults: Vec<String>,
    env: Option<String>,
    accepted_values: Vec<String>,
    deprecated: bool,
}

#[derive(Debug, Serialize)]
struct ArgumentHelp {
    id: String,
    index: usize,
    description: Option<String>,
    required: bool,
    hidden: bool,
    value_names: Vec<String>,
    defaults: Vec<String>,
    env: Option<String>,
    accepted_values: Vec<String>,
    deprecated: bool,
}

#[derive(Debug, Serialize)]
struct Example {
    description: &'static str,
    argv: Vec<&'static str>,
}

#[derive(Debug, Serialize)]
struct ExitCodeHelp {
    code: u8,
    meaning: &'static str,
}

/// Emit structured help for the command selected by a clap help invocation.
pub(crate) fn emit(argv: &[OsString]) -> Result<(), CliError> {
    let mut root = Cli::command();
    root.build();
    let (command, path) = selected_command(&root, argv);
    let document = HelpDocument {
        schema_version: HELP_SCHEMA_VERSION,
        command: command_help(command, &path)?,
    };
    crate::output::emit_json(&document, &[])
}

/// Follow clap-resolved subcommand spellings until help terminates parsing.
/// Intermediate shipshape commands contain no value-taking options (guarded by a
/// unit test), so non-option tokens can only be subcommands at those levels.
fn selected_command<'a>(root: &'a Command, argv: &[OsString]) -> (&'a Command, Vec<String>) {
    let mut command = root;
    let mut path = vec![root.get_name().to_string()];

    for token in argv.iter().skip(1) {
        let Some(token) = token.to_str() else {
            break;
        };
        if matches!(token, "--" | "--help" | "-h") {
            break;
        }
        if let Some(subcommand) = command.get_subcommands().find(|candidate| {
            candidate.get_name() == token || candidate.get_all_aliases().any(|alias| alias == token)
        }) {
            command = subcommand;
            // Extras are keyed by the canonical path, never by an alias spelling.
            path.push(command.get_name().to_string());
        } else if !token.starts_with('-') {
            break;
        }
    }

    (command, path)
}

fn command_help(command: &Command, path: &[String]) -> Result<CommandHelp, CliError> {
    let mut rendered = command.clone();
    let flags = command
        .get_arguments()
        .filter(|arg| !arg.is_positional())
        .map(|arg| flag_help(arg, path))
        .collect();
    let args = command
        .get_arguments()
        .filter(|arg| arg.is_positional())
        .map(argument_help)
        .collect();

    Ok(CommandHelp {
        name: command.get_name().to_string(),
        path: path.to_vec(),
        description: text(command.get_long_about().or_else(|| command.get_about())),
        usage: rendered.render_usage().to_string(),
        subcommands: command
            .get_subcommands()
            .filter(|subcommand| !subcommand.is_hide_set())
            .map(|subcommand| SubcommandHelp {
                name: subcommand.get_name().to_string(),
                description: text(subcommand.get_about()),
                aliases: subcommand
                    .get_visible_aliases()
                    .map(str::to_string)
                    .collect(),
                deprecated: false,
            })
            .collect(),
        flags,
        args,
        examples: examples(path).ok_or_else(|| {
            CliError::system(
                "internal_help_examples",
                format!(
                    "no structured-help example registered for `{}`",
                    path.join(" ")
                ),
            )
        })?,
        exit_codes: vec![
            ExitCodeHelp {
                code: 0,
                meaning: "success, including help and version display",
            },
            ExitCodeHelp {
                code: 1,
                meaning: "caller- or domain-actionable error",
            },
            ExitCodeHelp {
                code: 2,
                meaning: "system or internal error",
            },
        ],
        // The current public CLI has no deprecated commands or arguments.
        // Add an extras registry before introducing the first deprecation.
        deprecated: false,
    })
}

fn flag_help(arg: &Arg, path: &[String]) -> FlagHelp {
    let takes_value = arg.get_action().takes_values();
    let mut accepted_values = accepted_values(arg);
    // `--bump` predates clap-level enum parsing, so changing its parser would
    // alter text help and error behavior. Surface the core protocol's finite
    // set here without changing that established CLI contract.
    if accepted_values.is_empty()
        && arg.get_id() == "bump"
        && matches!(path, [root, command, action] if root == "shipshape" && command == "release" && matches!(action.as_str(), "plan" | "cut"))
    {
        accepted_values = shipshape_core::protocol::plan::BumpLevel::VALID
            .iter()
            .map(ToString::to_string)
            .collect();
    }

    FlagHelp {
        id: arg.get_id().to_string(),
        long: arg.get_long().map(str::to_string),
        short: arg.get_short(),
        description: text(arg.get_long_help().or_else(|| arg.get_help())),
        required: arg.is_required_set(),
        global: arg.is_global_set(),
        hidden: arg.is_hide_set(),
        takes_value,
        value_names: if takes_value {
            value_names(arg)
        } else {
            Vec::new()
        },
        defaults: defaults(arg),
        env: arg
            .get_env()
            .map(|value| value.to_string_lossy().into_owned()),
        accepted_values,
        deprecated: false,
    }
}

fn argument_help(arg: &Arg) -> ArgumentHelp {
    ArgumentHelp {
        id: arg.get_id().to_string(),
        index: arg
            .get_index()
            .expect("clap positional arguments have an index"),
        description: text(arg.get_long_help().or_else(|| arg.get_help())),
        required: arg.is_required_set(),
        hidden: arg.is_hide_set(),
        value_names: value_names(arg),
        defaults: defaults(arg),
        env: arg
            .get_env()
            .map(|value| value.to_string_lossy().into_owned()),
        accepted_values: accepted_values(arg),
        deprecated: false,
    }
}

fn text(value: Option<&clap::builder::StyledStr>) -> Option<String> {
    value.map(ToString::to_string)
}

fn value_names(arg: &Arg) -> Vec<String> {
    arg.get_value_names()
        .into_iter()
        .flatten()
        .map(ToString::to_string)
        .collect()
}

fn defaults(arg: &Arg) -> Vec<String> {
    arg.get_default_values()
        .iter()
        .map(|value| value.to_string_lossy().into_owned())
        .collect()
}

fn accepted_values(arg: &Arg) -> Vec<String> {
    arg.get_possible_values()
        .into_iter()
        .filter(|value| !value.is_hide_set())
        .map(|value| value.get_name().to_string())
        .collect()
}

/// Examples are the only help metadata clap does not model independently of
/// rendered prose. Keeping this exhaustive match means adding a command cannot
/// silently ship without the canon-required structured example.
#[allow(clippy::too_many_lines)] // Exhaustive command-to-example registry is clearer as one table.
fn examples(path: &[String]) -> Option<Vec<Example>> {
    let path: Vec<&str> = path.iter().map(String::as_str).collect();
    let (description, argv): (&'static str, &'static [&'static str]) = match path.as_slice() {
        ["shipshape"] => (
            "Inspect the installed CLI version",
            &["shipshape", "version", "--json"],
        ),
        ["shipshape", "config"] => (
            "Inspect resolved configuration",
            &["shipshape", "config", "show", "--json"],
        ),
        ["shipshape", "config", "path"] => (
            "Print resolved project paths",
            &["shipshape", "config", "path"],
        ),
        ["shipshape", "config", "show"] => (
            "Inspect resolved paths and provenance",
            &["shipshape", "config", "show", "--json"],
        ),
        ["shipshape", "contract"] => (
            "Normalize the release contract",
            &["shipshape", "contract", "show", "--json"],
        ),
        ["shipshape", "contract", "show"] => (
            "Normalize the current repository contract",
            &["shipshape", "contract", "show", "--json"],
        ),
        ["shipshape", "contract", "validate"] => (
            "Validate the current repository contract",
            &["shipshape", "contract", "validate", "--json"],
        ),
        ["shipshape", "facts"] => (
            "Detect facts for the current repository",
            &["shipshape", "facts", "--json"],
        ),
        ["shipshape", "audit"] => (
            "Audit the current repository",
            &["shipshape", "audit", "--json"],
        ),
        ["shipshape", "release"] | ["shipshape", "release", "list"] => (
            "List release runs",
            &["shipshape", "release", "list", "--json"],
        ),
        ["shipshape", "release", "plan"] => (
            "Seal a patch release plan",
            &["shipshape", "release", "plan", "--bump", "patch", "--json"],
        ),
        ["shipshape", "release", "cut"] => (
            "Execute an approved plan",
            &["shipshape", "release", "cut", "--plan", "PLAN_ID", "--json"],
        ),
        ["shipshape", "release", "resume"] => (
            "Resume an interrupted release",
            &["shipshape", "release", "resume", "RUN_ID", "--json"],
        ),
        ["shipshape", "release", "verify"] => (
            "Verify a release against its destinations",
            &["shipshape", "release", "verify", "RUN_ID", "--json"],
        ),
        ["shipshape", "release", "show"] => (
            "Inspect release progress",
            &["shipshape", "release", "show", "RUN_ID", "--json"],
        ),
        ["shipshape", "release", "abandon"] => (
            "Abandon a release run",
            &[
                "shipshape",
                "release",
                "abandon",
                "RUN_ID",
                "--reason",
                "superseded",
                "--json",
            ],
        ),
        ["shipshape", "dist"] | ["shipshape", "dist", "generate"] => (
            "Generate distribution infrastructure",
            &["shipshape", "dist", "generate", "--json"],
        ),
        ["shipshape", "skill"] | ["shipshape", "skill", "list"] => (
            "List bundled companion skills",
            &["shipshape", "skill", "list", "--json"],
        ),
        ["shipshape", "skill", "install"] => (
            "Install the release orchestrator skill",
            &[
                "shipshape",
                "skill",
                "install",
                "shipshape-release",
                "--json",
            ],
        ),
        ["shipshape", "skill", "print"] => (
            "Print the release orchestrator skill",
            &["shipshape", "skill", "print", "shipshape-release", "--json"],
        ),
        ["shipshape", "doctor"] => (
            "Run all self-diagnostic checks",
            &["shipshape", "doctor", "--json"],
        ),
        ["shipshape", "version"] => (
            "Inspect version and build provenance",
            &["shipshape", "version", "--json"],
        ),
        _ => return None,
    };
    Some(vec![Example {
        description,
        argv: argv.to_vec(),
    }])
}

#[cfg(test)]
mod tests {
    use clap::Parser;

    use super::*;

    #[test]
    fn every_real_command_has_a_parseable_structured_example() {
        let mut root = Cli::command();
        root.build();
        assert_examples_cover_tree(&root, &[root.get_name().to_string()]);
    }

    fn assert_examples_cover_tree(command: &Command, path: &[String]) {
        let command_examples =
            examples(path).unwrap_or_else(|| panic!("missing examples for {}", path.join(" ")));
        let path_refs: Vec<&str> = path.iter().map(String::as_str).collect();
        for example in command_examples {
            assert!(
                example.argv.starts_with(&path_refs),
                "example does not target {}: {:?}",
                path.join(" "),
                example.argv
            );
            Cli::try_parse_from(&example.argv)
                .unwrap_or_else(|error| panic!("invalid example for {}: {error}", path.join(" ")));
        }
        for subcommand in command.get_subcommands() {
            let mut child_path = path.to_vec();
            child_path.push(subcommand.get_name().to_string());
            assert_examples_cover_tree(subcommand, &child_path);
        }
    }

    #[test]
    fn alias_selection_uses_the_canonical_command_path() {
        let mut root = Command::new("shipshape").subcommand(Command::new("list").alias("ls"));
        root.build();
        let argv = [OsString::from("shipshape"), OsString::from("ls")];
        let (command, path) = selected_command(&root, &argv);
        assert_eq!(command.get_name(), "list");
        assert_eq!(path, ["shipshape", "list"]);
    }

    #[test]
    fn commands_with_subcommands_have_no_value_taking_options() {
        fn walk(command: &Command) {
            if command.get_subcommands().next().is_some() {
                for arg in command.get_arguments() {
                    assert!(
                        !arg.get_action().takes_values(),
                        "{} option {} takes a value and would make structured help selection ambiguous",
                        command.get_name(),
                        arg.get_id()
                    );
                }
            }
            command.get_subcommands().for_each(walk);
        }

        let mut root = Cli::command();
        root.build();
        walk(&root);
    }
}