aperture-cli 0.1.9

Dynamic CLI generator for OpenAPI specifications
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
//! Command mapping application logic.
//!
//! Applies user-defined command mappings (group renames, operation renames,
//! aliases, hidden flags) to cached commands after spec transformation.

use crate::cache::models::CachedCommand;
use crate::config::models::CommandMapping;
use crate::error::Error;
use crate::utils::to_kebab_case;
use std::collections::{HashMap, HashSet};

/// Names reserved for built-in Aperture commands that cannot be used as group names.
const RESERVED_GROUP_NAMES: &[&str] = &["config", "search", "exec", "docs", "overview"];

/// Result of applying command mappings, including any warnings.
#[derive(Debug)]
pub struct MappingResult {
    /// Warnings about stale or unused mappings
    pub warnings: Vec<String>,
}

/// Applies a `CommandMapping` to a list of cached commands.
///
/// For each command:
/// - If the command's first tag has a group mapping, sets `display_group`.
/// - If the command's `operation_id` has an operation mapping, sets
///   `display_name`, `display_group` (if specified), `aliases`, and `hidden`.
///
/// # Errors
///
/// Returns an error if the resulting mappings produce name collisions.
pub fn apply_command_mapping(
    commands: &mut [CachedCommand],
    mapping: &CommandMapping,
) -> Result<MappingResult, Error> {
    let mut warnings = Vec::new();

    // Track which mapping keys were actually used for stale detection
    let mut used_group_keys: HashSet<String> = HashSet::new();
    let mut used_operation_keys: HashSet<String> = HashSet::new();

    for command in commands.iter_mut() {
        // Apply group mapping based on the command's first tag
        let first_tag = command
            .tags
            .first()
            .map_or_else(|| command.name.clone(), Clone::clone);
        if let Some(display_group) = mapping.groups.get(first_tag.as_str()) {
            command.display_group = Some(display_group.clone());
            used_group_keys.insert(first_tag);
        }

        // Apply operation mapping based on operation_id
        let Some(op_mapping) = mapping.operations.get(&command.operation_id) else {
            continue;
        };
        used_operation_keys.insert(command.operation_id.clone());
        apply_operation_mapping(command, op_mapping);
    }

    // Detect stale group mappings
    for key in mapping.groups.keys() {
        if !used_group_keys.contains(key) {
            warnings.push(format!(
                "Command mapping: group mapping for tag '{key}' did not match any operations"
            ));
        }
    }

    // Detect stale operation mappings
    for key in mapping.operations.keys() {
        if !used_operation_keys.contains(key) {
            warnings.push(format!(
                "Command mapping: operation mapping for '{key}' did not match any operations"
            ));
        }
    }

    // Validate for collisions
    validate_no_collisions(commands)?;

    Ok(MappingResult { warnings })
}

/// Applies an individual operation mapping to a cached command.
fn apply_operation_mapping(
    command: &mut CachedCommand,
    op_mapping: &crate::config::models::OperationMapping,
) {
    command.display_name.clone_from(&op_mapping.name);
    // Operation-level group override takes precedence over tag-level
    if op_mapping.group.is_some() {
        command.display_group.clone_from(&op_mapping.group);
    }
    if !op_mapping.aliases.is_empty() {
        command.aliases.clone_from(&op_mapping.aliases);
    }
    command.hidden = op_mapping.hidden;
}

/// Resolves the effective group name for a command, considering display overrides.
///
/// Mirrors the logic in `engine::generator::effective_group_name` to ensure
/// collision detection matches the actual command tree.
fn effective_group(command: &CachedCommand) -> String {
    command.display_group.as_ref().map_or_else(
        || {
            if command.name.is_empty() {
                crate::constants::DEFAULT_GROUP.to_string()
            } else {
                to_kebab_case(&command.name)
            }
        },
        |g| to_kebab_case(g),
    )
}

/// Resolves the effective subcommand name for a command, considering display overrides.
///
/// Mirrors the logic in `engine::generator::effective_subcommand_name` to ensure
/// collision detection matches the actual command tree.
fn effective_name(command: &CachedCommand) -> String {
    command.display_name.as_ref().map_or_else(
        || {
            if command.operation_id.is_empty() {
                command.method.to_lowercase()
            } else {
                to_kebab_case(&command.operation_id)
            }
        },
        |n| to_kebab_case(n),
    )
}

/// Validates that no two commands resolve to the same (group, name) pair,
/// and that aliases don't collide with names or other aliases within the same group.
fn validate_no_collisions(commands: &[CachedCommand]) -> Result<(), Error> {
    // Map from (group, name) → operation_id for collision detection
    let mut seen: HashMap<(String, String), &str> = HashMap::new();

    for command in commands {
        let group = effective_group(command);
        let name = effective_name(command);

        // Check reserved group names
        if RESERVED_GROUP_NAMES.contains(&group.as_str()) {
            return Err(Error::invalid_config(format!(
                "Command mapping collision: group name '{group}' (from operation '{}') \
                 conflicts with built-in command '{group}'",
                command.operation_id
            )));
        }

        // Check primary name collision
        let key = (group.clone(), name.clone());
        if let Some(existing_op) = seen.get(&key) {
            return Err(Error::invalid_config(format!(
                "Command mapping collision: operations '{}' and '{}' both resolve to '{} {}'",
                existing_op, command.operation_id, key.0, key.1
            )));
        }
        seen.insert(key, &command.operation_id);

        // Check alias collisions within the same group
        for alias in &command.aliases {
            let alias_kebab = to_kebab_case(alias);
            let alias_key = (group.clone(), alias_kebab.clone());
            if let Some(existing_op) = seen.get(&alias_key) {
                return Err(Error::invalid_config(format!(
                    "Command mapping collision: alias '{alias_kebab}' for operation '{}' \
                     conflicts with '{}' in group '{group}'",
                    command.operation_id, existing_op
                )));
            }
            seen.insert(alias_key, &command.operation_id);
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cache::models::PaginationInfo;
    use crate::config::models::{CommandMapping, OperationMapping};
    use std::collections::HashMap;

    fn make_command(tag: &str, operation_id: &str) -> CachedCommand {
        CachedCommand {
            name: tag.to_string(),
            description: None,
            summary: None,
            operation_id: operation_id.to_string(),
            method: "GET".to_string(),
            path: format!("/{tag}"),
            parameters: vec![],
            request_body: None,
            responses: vec![],
            security_requirements: vec![],
            tags: vec![tag.to_string()],
            deprecated: false,
            external_docs_url: None,
            examples: vec![],
            display_group: None,
            display_name: None,
            aliases: vec![],
            hidden: false,
            pagination: PaginationInfo::default(),
        }
    }

    #[test]
    fn test_apply_group_mapping() {
        let mut commands = vec![
            make_command("User Management", "getUser"),
            make_command("User Management", "createUser"),
        ];
        let mapping = CommandMapping {
            groups: HashMap::from([("User Management".to_string(), "users".to_string())]),
            operations: HashMap::new(),
        };

        let result = apply_command_mapping(&mut commands, &mapping).unwrap();
        assert!(result.warnings.is_empty());
        assert_eq!(commands[0].display_group, Some("users".to_string()));
        assert_eq!(commands[1].display_group, Some("users".to_string()));
    }

    #[test]
    fn test_apply_operation_mapping() {
        let mut commands = vec![make_command("users", "getUserById")];
        let mapping = CommandMapping {
            groups: HashMap::new(),
            operations: HashMap::from([(
                "getUserById".to_string(),
                OperationMapping {
                    name: Some("fetch".to_string()),
                    group: Some("accounts".to_string()),
                    aliases: vec!["get".to_string(), "show".to_string()],
                    hidden: false,
                },
            )]),
        };

        let result = apply_command_mapping(&mut commands, &mapping).unwrap();
        assert!(result.warnings.is_empty());
        assert_eq!(commands[0].display_name, Some("fetch".to_string()));
        assert_eq!(commands[0].display_group, Some("accounts".to_string()));
        assert_eq!(commands[0].aliases, vec!["get", "show"]);
    }

    #[test]
    fn test_hidden_operation() {
        let mut commands = vec![make_command("users", "deleteUser")];
        let mapping = CommandMapping {
            groups: HashMap::new(),
            operations: HashMap::from([(
                "deleteUser".to_string(),
                OperationMapping {
                    hidden: true,
                    ..Default::default()
                },
            )]),
        };

        let result = apply_command_mapping(&mut commands, &mapping).unwrap();
        assert!(result.warnings.is_empty());
        assert!(commands[0].hidden);
    }

    #[test]
    fn test_stale_group_mapping_warns() {
        let mut commands = vec![make_command("users", "getUser")];
        let mapping = CommandMapping {
            groups: HashMap::from([("NonExistentTag".to_string(), "nope".to_string())]),
            operations: HashMap::new(),
        };

        let result = apply_command_mapping(&mut commands, &mapping).unwrap();
        assert_eq!(result.warnings.len(), 1);
        assert!(result.warnings[0].contains("NonExistentTag"));
    }

    #[test]
    fn test_stale_operation_mapping_warns() {
        let mut commands = vec![make_command("users", "getUser")];
        let mapping = CommandMapping {
            groups: HashMap::new(),
            operations: HashMap::from([("nonExistentOp".to_string(), OperationMapping::default())]),
        };

        let result = apply_command_mapping(&mut commands, &mapping).unwrap();
        assert_eq!(result.warnings.len(), 1);
        assert!(result.warnings[0].contains("nonExistentOp"));
    }

    #[test]
    fn test_collision_detection_same_name() {
        let mut commands = vec![
            make_command("users", "getUser"),
            make_command("users", "fetchUser"),
        ];
        let mapping = CommandMapping {
            groups: HashMap::new(),
            operations: HashMap::from([(
                "fetchUser".to_string(),
                OperationMapping {
                    name: Some("get-user".to_string()),
                    ..Default::default()
                },
            )]),
        };

        let result = apply_command_mapping(&mut commands, &mapping);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("collision"), "Error: {err_msg}");
    }

    #[test]
    fn test_collision_detection_alias_vs_name() {
        let mut commands = vec![
            make_command("users", "getUser"),
            make_command("users", "fetchUser"),
        ];
        let mapping = CommandMapping {
            groups: HashMap::new(),
            operations: HashMap::from([(
                "fetchUser".to_string(),
                OperationMapping {
                    aliases: vec!["get-user".to_string()],
                    ..Default::default()
                },
            )]),
        };

        let result = apply_command_mapping(&mut commands, &mapping);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("collision"), "Error: {err_msg}");
    }

    #[test]
    fn test_reserved_group_name_rejected() {
        let mut commands = vec![make_command("users", "getUser")];
        let mapping = CommandMapping {
            groups: HashMap::from([("users".to_string(), "config".to_string())]),
            operations: HashMap::new(),
        };

        let result = apply_command_mapping(&mut commands, &mapping);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("config"), "Error: {err_msg}");
    }

    #[test]
    fn test_operation_group_overrides_tag_group() {
        let mut commands = vec![make_command("User Management", "getUser")];
        let mapping = CommandMapping {
            groups: HashMap::from([("User Management".to_string(), "users".to_string())]),
            operations: HashMap::from([(
                "getUser".to_string(),
                OperationMapping {
                    group: Some("accounts".to_string()),
                    ..Default::default()
                },
            )]),
        };

        let result = apply_command_mapping(&mut commands, &mapping).unwrap();
        assert!(result.warnings.is_empty());
        // Operation-level group override wins
        assert_eq!(commands[0].display_group, Some("accounts".to_string()));
    }

    #[test]
    fn test_no_mapping_leaves_commands_unchanged() {
        let mut commands = vec![make_command("users", "getUser")];
        let mapping = CommandMapping::default();

        let result = apply_command_mapping(&mut commands, &mapping).unwrap();
        assert!(result.warnings.is_empty());
        assert_eq!(commands[0].display_group, None);
        assert_eq!(commands[0].display_name, None);
        assert!(commands[0].aliases.is_empty());
        assert!(!commands[0].hidden);
    }

    #[test]
    fn test_empty_name_uses_default_group() {
        // A command with empty name should use DEFAULT_GROUP, not empty string
        let mut cmd = make_command("", "getUser");
        cmd.name = String::new();
        cmd.tags = vec![];
        let mut commands = vec![cmd];
        let mapping = CommandMapping::default();

        let result = apply_command_mapping(&mut commands, &mapping).unwrap();
        assert!(result.warnings.is_empty());
        // Verify effective_group resolves to DEFAULT_GROUP for collision detection
        assert_eq!(
            super::effective_group(&commands[0]),
            crate::constants::DEFAULT_GROUP
        );
    }

    #[test]
    fn test_empty_operation_id_uses_method() {
        let mut cmd = make_command("users", "");
        cmd.operation_id = String::new();
        cmd.method = "POST".to_string();
        let mut commands = vec![cmd];
        let mapping = CommandMapping::default();

        let result = apply_command_mapping(&mut commands, &mapping).unwrap();
        assert!(result.warnings.is_empty());
        assert_eq!(super::effective_name(&commands[0]), "post");
    }
}