sprawl-guard 0.1.0

Repository sprawl checker CLI.
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
use std::collections::HashSet;

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

use super::Cli;
use crate::error::{CliError, Result};

macro_rules! string_newtype {
    ($name:ident, $doc:literal) => {
        #[doc = $doc]
        #[derive(Clone, Serialize)]
        #[serde(transparent)]
        struct $name(String);

        impl $name {
            fn new(value: impl Into<String>) -> Self {
                Self(value.into())
            }
        }
    };
}

/// Renders the public, mechanical CLI reference as JSON for the documentation site.
pub(crate) fn render_cli_reference_json() -> Result<String> {
    let mut command = Cli::command();
    command.build();

    let document = CliReferenceDocument::from_command(&mut command);
    let mut json = serde_json::to_string_pretty(&document)
        .map_err(|source| CliError::RenderCliReference { source })?;
    json.push('\n');
    Ok(json)
}

/// The versioned CLI-reference document consumed by Starlight.
#[derive(Serialize)]
struct CliReferenceDocument {
    schema_version: CliReferenceSchemaVersion,
    commands: Vec<CliReferenceCommand>,
}

impl CliReferenceDocument {
    fn from_command(command: &mut Command) -> Self {
        let mut commands = Vec::new();
        let mut path = Vec::new();
        collect_public_commands(command, &mut path, &HashSet::new(), &mut commands);
        Self {
            schema_version: CliReferenceSchemaVersion::CURRENT,
            commands,
        }
    }
}

/// The mechanical reference for one public command.
#[derive(Serialize)]
struct CliReferenceCommand {
    path: Vec<CommandName>,
    usage: UsageText,
    arguments: Vec<CliReferenceArgument>,
}

impl CliReferenceCommand {
    fn from_command(
        command: &mut Command,
        path: Vec<CommandName>,
        inherited_global_ids: &HashSet<String>,
    ) -> Self {
        let usage = UsageText::new(command.render_usage().to_string());
        let mut arguments = command
            .get_arguments()
            .filter(|argument| {
                argument_is_visible_in_long_help(argument)
                    && !(argument.is_global_set()
                        && inherited_global_ids.contains(argument.get_id().as_str()))
            })
            .collect::<Vec<_>>();
        arguments.sort_by_key(|argument| argument.get_display_order());

        Self {
            path,
            usage,
            arguments: arguments
                .into_iter()
                .map(|argument| CliReferenceArgument::from_arg(command, argument))
                .collect(),
        }
    }
}

fn collect_public_commands(
    command: &mut Command,
    path: &mut Vec<CommandName>,
    inherited_global_ids: &HashSet<String>,
    commands: &mut Vec<CliReferenceCommand>,
) {
    let is_root = path.is_empty();
    if !is_root && (command.is_hide_set() || command.get_name() == "help") {
        return;
    }

    path.push(CommandName::new(command.get_name()));
    commands.push(CliReferenceCommand::from_command(
        command,
        path.clone(),
        inherited_global_ids,
    ));
    let mut descendant_global_ids = inherited_global_ids.clone();
    descendant_global_ids.extend(
        command
            .get_arguments()
            .filter(|argument| argument.is_global_set())
            .map(|argument| argument.get_id().as_str().to_owned()),
    );
    let mut subcommands = command.get_subcommands_mut().collect::<Vec<_>>();
    subcommands.sort_by_key(|subcommand| subcommand.get_display_order());
    for subcommand in subcommands {
        collect_public_commands(subcommand, path, &descendant_global_ids, commands);
    }
    path.pop();
}

/// One visible argument or option row rendered by Starlight.
#[derive(Serialize)]
struct CliReferenceArgument {
    id: ArgumentId,
    syntax: ArgumentSyntax,
    help: Option<HelpText>,
    conflicts_with: Vec<ArgumentSyntax>,
    default_values: Vec<DefaultValue>,
    possible_values: Vec<CliReferencePossibleValue>,
}

impl CliReferenceArgument {
    fn from_arg(command: &Command, argument: &Arg) -> Self {
        Self {
            id: ArgumentId::new(argument.get_id().as_str()),
            syntax: argument_syntax(argument),
            help: argument
                .get_long_help()
                .or_else(|| argument.get_help())
                .map(HelpText::from_styled),
            conflicts_with: command
                .get_arg_conflicts_with(argument)
                .into_iter()
                .filter(|conflict| argument_is_visible_in_long_help(conflict))
                .map(argument_syntax)
                .collect(),
            default_values: visible_default_values(argument),
            possible_values: visible_possible_values(argument),
        }
    }
}

fn argument_is_visible_in_long_help(argument: &Arg) -> bool {
    !argument.is_hide_set() && !argument.is_hide_long_help_set()
}

fn argument_syntax(argument: &Arg) -> ArgumentSyntax {
    if argument.is_positional() {
        return ArgumentSyntax::new(argument.to_string());
    }

    let rendered = argument.to_string();
    let canonical = argument
        .get_long()
        .map(|long| format!("--{long}"))
        .or_else(|| argument.get_short().map(|short| format!("-{short}")))
        .unwrap_or_default();
    let suffix = rendered.strip_prefix(&canonical).unwrap_or(&rendered);
    let mut spellings = Vec::new();
    if let Some(short) = argument.get_short() {
        spellings.push(format!("-{short}"));
    }
    spellings.extend(
        argument
            .get_visible_short_aliases()
            .unwrap_or_default()
            .into_iter()
            .map(|alias| format!("-{alias}")),
    );
    if let Some(long) = argument.get_long() {
        spellings.push(format!("--{long}"));
    }
    spellings.extend(
        argument
            .get_visible_aliases()
            .unwrap_or_default()
            .into_iter()
            .map(|alias| format!("--{alias}")),
    );
    ArgumentSyntax::new(format!("{}{suffix}", spellings.join(", ")))
}

fn visible_default_values(argument: &Arg) -> Vec<DefaultValue> {
    let takes_values = argument
        .get_num_args()
        .is_some_and(|range| range.max_values() > 0);
    if !takes_values || argument.is_hide_default_value_set() {
        return Vec::new();
    }

    argument
        .get_default_values()
        .iter()
        .map(|value| DefaultValue::new(value.to_string_lossy()))
        .collect()
}

fn visible_possible_values(argument: &Arg) -> Vec<CliReferencePossibleValue> {
    if argument.is_hide_possible_values_set() {
        return Vec::new();
    }

    argument
        .get_possible_values()
        .iter()
        .filter(|value| !value.is_hide_set())
        .map(|value| CliReferencePossibleValue {
            name: PossibleValueName::new(value.get_name()),
            help: value.get_help().map(HelpText::from_styled),
        })
        .collect()
}

/// One visible value accepted by an argument.
#[derive(Serialize)]
struct CliReferencePossibleValue {
    name: PossibleValueName,
    help: Option<HelpText>,
}

/// The schema version for the generated document.
#[derive(Serialize)]
#[serde(transparent)]
struct CliReferenceSchemaVersion(u8);

impl CliReferenceSchemaVersion {
    const CURRENT: Self = Self(2);
}

string_newtype!(CommandName, "A canonical Clap command name.");
string_newtype!(ArgumentId, "A canonical Clap argument identifier.");
string_newtype!(
    ArgumentSyntax,
    "Rendered syntax for one argument or option."
);
string_newtype!(DefaultValue, "A visible default value for an argument.");
string_newtype!(
    PossibleValueName,
    "A visible value accepted by an argument."
);

/// Human-facing text supplied by Clap.
#[derive(Serialize)]
#[serde(transparent)]
struct HelpText(String);

impl HelpText {
    fn from_styled(value: &clap::builder::StyledStr) -> Self {
        Self(value.to_string())
    }
}

/// One usage line rendered by Clap.
#[derive(Serialize)]
#[serde(transparent)]
struct UsageText(String);

impl UsageText {
    fn new(value: String) -> Self {
        Self(value)
    }
}

#[cfg(test)]
mod tests {
    use clap::builder::PossibleValue;
    use clap::{Arg, Command};
    use serde_json::json;

    use super::*;

    fn rendered_command(command: &mut Command, path: &[&str]) -> serde_json::Value {
        command.build();
        let document = serde_json::to_value(CliReferenceDocument::from_command(command)).unwrap();
        document["commands"]
            .as_array()
            .unwrap()
            .iter()
            .find(|command| command["path"] == json!(path))
            .unwrap()
            .clone()
    }

    mod when_arguments_have_hidden_and_visible_help_metadata {
        use super::*;

        #[test]
        fn it_emits_only_the_rows_rendered_by_the_site() {
            let mut command = Command::new("fixture")
                .disable_help_flag(true)
                .arg(
                    Arg::new("option")
                        .long("option")
                        .visible_alias("visible-long-alias")
                        .alias("hidden-long-alias")
                        .short('o')
                        .visible_short_alias('v')
                        .short_alias('x')
                        .value_name("VALUE")
                        .default_value("visible-value")
                        .value_parser([
                            PossibleValue::new("visible-value").help("Shown value"),
                            PossibleValue::new("hidden-value").hide(true),
                        ]),
                )
                .arg(Arg::new("hidden").long("hidden").hide(true))
                .arg(
                    Arg::new("hidden-from-long-help")
                        .long("hidden-from-long-help")
                        .hide_long_help(true),
                );
            command.build();

            let document = CliReferenceDocument::from_command(&mut command);
            let json = serde_json::to_value(document).unwrap();

            assert_eq!(
                json["commands"][0]["arguments"],
                json!([{
                    "id": "option",
                    "syntax": "-o, -v, --option, --visible-long-alias <VALUE>",
                    "help": null,
                    "conflicts_with": [],
                    "default_values": ["visible-value"],
                    "possible_values": [{"name": "visible-value", "help": "Shown value"}],
                }]),
            );
        }
    }

    mod when_an_argument_hides_its_possible_values {
        use super::*;

        #[test]
        fn it_omits_the_values_from_the_site_document() {
            let mut command = Command::new("fixture").disable_help_flag(true).arg(
                Arg::new("option")
                    .long("option")
                    .hide_possible_values(true)
                    .value_parser(["visible-value"]),
            );
            command.build();

            let document =
                serde_json::to_value(CliReferenceDocument::from_command(&mut command)).unwrap();

            assert_eq!(
                document["commands"][0]["arguments"][0]["possible_values"],
                json!([]),
            );
        }
    }

    mod when_a_command_group_declares_a_global_option {
        use super::*;

        #[test]
        fn it_emits_the_option_at_its_declaring_scope_only() {
            let mut command = Command::new("fixture").disable_help_flag(true).subcommand(
                Command::new("group")
                    .disable_help_flag(true)
                    .arg(Arg::new("group-option").long("group-option").global(true))
                    .subcommand(Command::new("child").disable_help_flag(true)),
            );
            command.build();

            let document =
                serde_json::to_value(CliReferenceDocument::from_command(&mut command)).unwrap();
            let commands = document["commands"].as_array().unwrap();
            let group = commands
                .iter()
                .find(|command| command["path"] == json!(["fixture", "group"]))
                .unwrap();
            let child = commands
                .iter()
                .find(|command| command["path"] == json!(["fixture", "group", "child"]))
                .unwrap();

            assert_eq!(group["arguments"][0]["id"], "group-option");
            assert_eq!(child["arguments"], json!([]));
        }
    }

    mod when_a_child_shadows_an_inherited_global_option {
        use super::*;

        #[test]
        fn it_emits_the_child_declaration() {
            let mut command = Command::new("fixture")
                .disable_help_flag(true)
                .arg(Arg::new("scope").long("scope").global(true))
                .subcommand(
                    Command::new("child")
                        .disable_help_flag(true)
                        .arg(Arg::new("scope").long("child-scope")),
                );
            let child = rendered_command(&mut command, &["fixture", "child"]);

            assert_eq!(child["arguments"][0]["syntax"], "--child-scope <scope>");
        }
    }

    mod when_an_argument_conflicts_with_an_inherited_global_option {
        use super::*;

        #[test]
        fn it_preserves_the_cross_scope_conflict() {
            let mut command = Command::new("fixture")
                .disable_help_flag(true)
                .arg(Arg::new("config").long("config").global(true))
                .subcommand(
                    Command::new("child")
                        .disable_help_flag(true)
                        .arg(Arg::new("local").long("local").conflicts_with("config")),
                );
            let child = rendered_command(&mut command, &["fixture", "child"]);

            assert_eq!(
                child["arguments"][0]["conflicts_with"],
                json!(["--config <config>"]),
            );
        }
    }
}