osp-cli 1.5.1

CLI and REPL for querying and managing OSP infrastructure data
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
use crate::config::ResolvedConfig;
use crate::dsl::{
    model::{ParsedStage, ParsedStageKind},
    parse::pipeline::parse_stage,
    parse_pipeline,
};
use miette::{IntoDiagnostic, Result, WrapErr, miette};

use crate::app::is_sensitive_key;

const MAX_ALIAS_EXPANSION_DEPTH: usize = 100;

pub(crate) fn truncate_display(s: &str, max_len: usize) -> String {
    let trimmed = s.trim();
    let char_count = trimmed.chars().count();
    if char_count <= max_len {
        trimmed.to_string()
    } else {
        let end = trimmed
            .char_indices()
            .nth(max_len)
            .map(|(index, _)| index)
            .unwrap_or(trimmed.len());
        format!("{}... ({} chars)", &trimmed[..end], char_count)
    }
}

/// Parsed command tokens plus trailing DSL stages.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedCommandLine {
    /// Final command tokens after alias expansion and command normalization.
    pub tokens: Vec<String>,
    /// Raw trailing DSL stage strings in execution order.
    pub stages: Vec<String>,
}

/// Parses a raw command line, expands aliases, and separates trailing DSL stages.
///
/// This is the text-entry path used by CLI and REPL surfaces when they need
/// one parser pass that understands both shell words and trailing pipes.
///
/// # Examples
///
/// ```
/// use osp_cli::cli::parse_command_text_with_aliases;
/// use osp_cli::config::{ConfigLayer, ConfigResolver, ResolveOptions};
///
/// let mut defaults = ConfigLayer::default();
/// defaults.set("profile.default", "default");
///
/// let mut resolver = ConfigResolver::default();
/// resolver.set_defaults(defaults);
/// let config = resolver.resolve(ResolveOptions::default()).unwrap();
///
/// let parsed = parse_command_text_with_aliases("theme show dracula | H P", &config).unwrap();
/// assert_eq!(parsed.tokens, vec!["theme", "show", "dracula"]);
/// assert_eq!(parsed.stages, vec!["H P"]);
/// ```
pub fn parse_command_text_with_aliases(
    text: &str,
    config: &ResolvedConfig,
) -> Result<ParsedCommandLine> {
    let parsed = parse_pipeline(text)
        .into_diagnostic()
        .wrap_err_with(|| format!("failed to parse pipeline: {}", truncate_display(text, 60)))?;
    let command_tokens = shell_words::split(&parsed.command)
        .into_diagnostic()
        .wrap_err_with(|| {
            format!(
                "failed to parse command tokens: {}",
                truncate_display(&parsed.command, 60)
            )
        })?;
    finalize_command_with_aliases(command_tokens, parsed.stages, config)
}

/// Finalizes already-tokenized input into command tokens plus DSL stages.
///
/// This is the caller-facing path when tokenization already happened elsewhere
/// and only alias expansion plus pipe splitting are still needed.
///
/// # Examples
///
/// ```
/// use osp_cli::cli::parse_command_tokens_with_aliases;
/// use osp_cli::config::{ConfigLayer, ConfigResolver, ResolveOptions};
///
/// let mut defaults = ConfigLayer::default();
/// defaults.set("profile.default", "default");
///
/// let mut resolver = ConfigResolver::default();
/// resolver.set_defaults(defaults);
/// let config = resolver.resolve(ResolveOptions::default()).unwrap();
///
/// let tokens = vec![
///     "config".to_string(),
///     "show".to_string(),
///     "|".to_string(),
///     "P".to_string(),
///     "ui.format".to_string(),
/// ];
///
/// let parsed = parse_command_tokens_with_aliases(&tokens, &config).unwrap();
/// assert_eq!(parsed.tokens, vec!["config", "show"]);
/// assert_eq!(parsed.stages, vec!["P ui.format"]);
/// ```
pub fn parse_command_tokens_with_aliases(
    tokens: &[String],
    config: &ResolvedConfig,
) -> Result<ParsedCommandLine> {
    if tokens.is_empty() {
        return Ok(ParsedCommandLine {
            tokens: Vec::new(),
            stages: Vec::new(),
        });
    }

    let split = split_command_tokens(tokens);
    finalize_command_with_aliases(split.command_tokens, split.stages, config)
}

fn maybe_expand_alias(
    candidate: &str,
    positional_args: &[String],
    config: &ResolvedConfig,
) -> Result<Option<String>> {
    let Some(value) = config.get_alias_entry(candidate) else {
        return Ok(None);
    };

    let template = value.raw_value.to_string();
    let expanded = expand_alias_template(candidate, &template, positional_args, config)
        .wrap_err_with(|| format!("failed to expand alias `{candidate}`"))?;
    Ok(Some(expanded))
}

fn finalize_command_with_aliases(
    command_tokens: Vec<String>,
    stages: Vec<String>,
    config: &ResolvedConfig,
) -> Result<ParsedCommandLine> {
    if command_tokens.is_empty() {
        return Ok(ParsedCommandLine {
            tokens: Vec::new(),
            stages: Vec::new(),
        });
    }

    let alias_name = &command_tokens[0];
    if let Some(expanded) = maybe_expand_alias(alias_name, &command_tokens[1..], config)? {
        tracing::trace!(
            alias = %alias_name,
            "alias expanded"
        );
        let alias_parsed = parse_pipeline(&expanded)
            .into_diagnostic()
            .wrap_err_with(|| {
                format!(
                    "failed to parse alias `{alias_name}` expansion: {}",
                    truncate_display(&expanded, 60)
                )
            })?;
        let alias_tokens = shell_words::split(&alias_parsed.command)
            .into_diagnostic()
            .wrap_err_with(|| format!("failed to parse alias `{alias_name}` command tokens"))?;
        if alias_tokens.is_empty() {
            return Ok(ParsedCommandLine {
                tokens: Vec::new(),
                stages: Vec::new(),
            });
        }

        let mut merged_stages = alias_parsed.stages;
        merged_stages.extend(stages);
        return finalize_parsed_command(alias_tokens, merged_stages);
    }

    finalize_parsed_command(command_tokens, stages)
}

fn finalize_parsed_command(tokens: Vec<String>, stages: Vec<String>) -> Result<ParsedCommandLine> {
    validate_cli_dsl_stages(&stages)?;
    Ok(ParsedCommandLine {
        tokens: merge_orch_os_tokens(tokens),
        stages,
    })
}

fn merge_orch_os_tokens(tokens: Vec<String>) -> Vec<String> {
    if tokens.len() < 4 || tokens.first().map(String::as_str) != Some("orch") {
        return tokens;
    }
    if tokens.get(1).map(String::as_str) != Some("provision") {
        return tokens;
    }

    let mut merged = Vec::with_capacity(tokens.len());
    let mut index = 0usize;
    while index < tokens.len() {
        if tokens[index] == "--os" && index + 2 < tokens.len() {
            let family = &tokens[index + 1];
            let version = &tokens[index + 2];
            if !version.is_empty() && !version.starts_with('-') {
                merged.push("--os".to_string());
                merged.push(format!("{family}{version}"));
                index += 3;
                continue;
            }
        }

        merged.push(tokens[index].clone());
        index += 1;
    }

    merged
}

/// Validates that every CLI pipe stage is known to the DSL surface.
///
/// Unknown explicit verbs are rejected here so callers can surface a clear
/// "use `| H <verb>` for help" message before execution.
///
/// # Examples
///
/// ```
/// use osp_cli::cli::validate_cli_dsl_stages;
///
/// validate_cli_dsl_stages(&["P uid".to_string(), "H P".to_string()]).unwrap();
/// assert!(validate_cli_dsl_stages(&["R nope".to_string()]).is_err());
/// ```
pub fn validate_cli_dsl_stages(stages: &[String]) -> Result<()> {
    for raw in stages {
        let parsed = parse_stage(raw).into_diagnostic().wrap_err_with(|| {
            format!("failed to parse DSL stage: {}", truncate_display(raw, 80))
        })?;
        if parsed.verb.is_empty() {
            continue;
        }
        if matches!(
            parsed.kind,
            ParsedStageKind::Explicit | ParsedStageKind::Quick
        ) || is_cli_help_stage(&parsed)
        {
            continue;
        }

        return Err(miette!(
            "Unknown DSL verb '{}' in pipe '{}'. Use `| H <verb>` for help.",
            parsed.verb,
            raw.trim()
        ));
    }

    Ok(())
}

/// Reports whether a parsed stage is the special CLI help form `| H <verb>`.
pub fn is_cli_help_stage(parsed: &ParsedStage) -> bool {
    matches!(parsed.kind, ParsedStageKind::UnknownExplicit) && parsed.verb.eq_ignore_ascii_case("H")
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct SplitCommandTokens {
    command_tokens: Vec<String>,
    stages: Vec<String>,
}

fn split_command_tokens(tokens: &[String]) -> SplitCommandTokens {
    let mut segments = Vec::new();
    let mut current = Vec::new();

    for token in tokens {
        if token == "|" {
            if !current.is_empty() {
                segments.push(std::mem::take(&mut current));
            }
            continue;
        }
        current.push(token.clone());
    }

    if !current.is_empty() {
        segments.push(current);
    }

    let mut iter = segments.into_iter();
    let command_tokens = iter.next().unwrap_or_default();
    let stages = iter
        .map(|segment| {
            segment
                .into_iter()
                .map(|token| quote_token(&token))
                .collect::<Vec<_>>()
                .join(" ")
        })
        .collect();

    SplitCommandTokens {
        command_tokens,
        stages,
    }
}

fn expand_alias_template(
    alias_name: &str,
    template: &str,
    positional_args: &[String],
    config: &ResolvedConfig,
) -> Result<String> {
    let mut current = template.to_string();

    for _ in 0..MAX_ALIAS_EXPANSION_DEPTH {
        if !current.contains("${") {
            return Ok(current);
        }

        let mut out = String::new();
        let mut cursor = 0usize;

        while let Some(rel_start) = current[cursor..].find("${") {
            let start = cursor + rel_start;
            out.push_str(&current[cursor..start]);

            let after_open = start + 2;
            let Some(rel_end) = current[after_open..].find('}') else {
                return Err(miette!(
                    "invalid alias placeholder syntax in alias '{alias_name}': '{template}'"
                ));
            };
            let end = after_open + rel_end;
            let placeholder = current[after_open..end].trim();
            if placeholder.is_empty() {
                return Err(miette!(
                    "invalid alias placeholder syntax in alias '{alias_name}': '{template}'"
                ));
            }

            let (key_part, default) = split_placeholder(placeholder);
            let replacement =
                resolve_alias_placeholder(alias_name, key_part, default, positional_args, config)?;
            out.push_str(&replacement);
            cursor = end + 1;
        }

        out.push_str(&current[cursor..]);
        if out == current {
            return Ok(out);
        }
        current = out;
    }

    Err(miette!(
        "Expansion depth exceeded 100 on alias '{alias_name}'."
    ))
}

fn split_placeholder(placeholder: &str) -> (&str, Option<&str>) {
    if let Some((key, default)) = placeholder.split_once(':') {
        (key.trim(), Some(default))
    } else {
        (placeholder.trim(), None)
    }
}

fn resolve_alias_placeholder(
    alias_name: &str,
    key_part: &str,
    default: Option<&str>,
    positional_args: &[String],
    config: &ResolvedConfig,
) -> Result<String> {
    if key_part.is_empty() {
        return Err(miette!(
            "invalid alias placeholder syntax in alias '{alias_name}'"
        ));
    }

    if let Ok(index) = key_part.parse::<usize>()
        && index > 0
        && index <= positional_args.len()
    {
        return Ok(positional_args[index - 1].clone());
    }

    if key_part == "*" || key_part == "@" {
        let joined = positional_args
            .iter()
            .map(|arg| quote_token(arg))
            .collect::<Vec<String>>()
            .join(" ");
        return Ok(joined);
    }

    if is_sensitive_key(key_part) {
        return Err(miette!(
            "Alias '{alias_name}' cannot expand sensitive config placeholder '{key_part}'"
        ));
    }

    if let Some(value) = config.get(key_part) {
        return Ok(value.to_string());
    }

    if let Some(default_value) = default {
        return Ok(default_value.to_string());
    }

    Err(miette!(
        "Alias '{alias_name}' requires value for placeholder '{key_part}'"
    ))
}

fn quote_token(token: &str) -> String {
    if token.is_empty() {
        return "''".to_string();
    }
    let needs_quotes = token.chars().any(|ch| {
        ch.is_whitespace()
            || matches!(
                ch,
                '\'' | '"'
                    | '\\'
                    | '$'
                    | '`'
                    | '|'
                    | '&'
                    | ';'
                    | '<'
                    | '>'
                    | '('
                    | ')'
                    | '{'
                    | '}'
                    | '*'
                    | '?'
                    | '['
                    | ']'
                    | '!'
            )
    });
    if !needs_quotes {
        return token.to_string();
    }

    if !token.contains('\'') {
        return format!("'{token}'");
    }

    let mut out = String::new();
    out.push('\'');
    for ch in token.chars() {
        if ch == '\'' {
            out.push_str("'\"'\"'");
        } else {
            out.push(ch);
        }
    }
    out.push('\'');
    out
}

#[cfg(test)]
mod tests {
    use super::{
        expand_alias_template, parse_command_text_with_aliases, parse_command_tokens_with_aliases,
        truncate_display, validate_cli_dsl_stages,
    };
    use crate::config::{ConfigLayer, ConfigResolver, ResolveOptions};

    fn test_config(entries: &[(&str, &str)]) -> crate::config::ResolvedConfig {
        let mut defaults = ConfigLayer::default();
        defaults.set("profile.default", "default");
        for (key, value) in entries {
            defaults.set(*key, *value);
        }
        let mut resolver = ConfigResolver::default();
        resolver.set_defaults(defaults);
        resolver
            .resolve(ResolveOptions::default())
            .expect("test config should resolve")
    }

    #[test]
    fn alias_and_command_parsing_cover_config_values_following_stages_shell_words_and_empty_input_unit()
     {
        let config = test_config(&[("alias.demo", "echo ${ui.format}"), ("ui.format", "json")]);

        let parsed = parse_command_tokens_with_aliases(&["demo".to_string()], &config)
            .expect("alias should expand");
        assert_eq!(parsed.tokens, vec!["echo".to_string(), "json".to_string()]);

        let config = test_config(&[("alias.demo", "orch provision --os alma 9 | P uid")]);

        let parsed = parse_command_tokens_with_aliases(
            &["demo".to_string(), "|".to_string(), "alice".to_string()],
            &config,
        )
        .expect("alias should expand");

        assert_eq!(
            parsed.tokens,
            vec![
                "orch".to_string(),
                "provision".to_string(),
                "--os".to_string(),
                "alma9".to_string()
            ]
        );
        assert_eq!(
            parsed.stages,
            vec!["P uid".to_string(), "alice".to_string()]
        );

        let config = test_config(&[]);
        let parsed = parse_command_text_with_aliases("ldap user \"alice smith\" | P uid", &config)
            .expect("command text should parse");

        assert_eq!(
            parsed.tokens,
            vec![
                "ldap".to_string(),
                "user".to_string(),
                "alice smith".to_string()
            ]
        );
        assert_eq!(parsed.stages, vec!["P uid".to_string()]);
        let parsed =
            parse_command_tokens_with_aliases(&[], &config).expect("empty command should parse");

        assert!(parsed.tokens.is_empty());
        assert!(parsed.stages.is_empty());
    }

    #[test]
    fn alias_placeholders_support_positionals_defaults_and_quoting_unit() {
        let config = test_config(&[]);

        let expanded = expand_alias_template(
            "demo",
            "echo ${1} ${2:guest} ${*}",
            &[
                "alice".to_string(),
                "two words".to_string(),
                "O'Neil".to_string(),
            ],
            &config,
        )
        .expect("alias should expand");

        assert_eq!(
            expanded,
            "echo alice two words alice 'two words' 'O'\"'\"'Neil'"
        );
    }

    #[test]
    fn cli_dsl_stage_validation_covers_help_and_unknown_verbs_unit() {
        validate_cli_dsl_stages(&["H sort".to_string()]).expect("help stage should be allowed");

        let err =
            validate_cli_dsl_stages(&["R uid".to_string()]).expect_err("unknown verb should fail");
        assert!(err.to_string().contains("Unknown DSL verb"));
    }

    #[test]
    fn alias_and_parse_errors_are_reported_cleanly_unit() {
        let config = test_config(&[]);

        let err = expand_alias_template("danger", "echo ${auth.api_key}", &[], &config)
            .expect_err("sensitive placeholder should be rejected");
        assert!(
            err.to_string()
                .contains("cannot expand sensitive config placeholder")
        );

        let err = expand_alias_template("demo", "echo ${}", &[], &config)
            .expect_err("empty placeholder should fail");
        assert!(err.to_string().contains("invalid alias placeholder syntax"));

        let err = expand_alias_template("demo", "echo ${user", &[], &config)
            .expect_err("unterminated placeholder should fail");
        assert!(err.to_string().contains("invalid alias placeholder syntax"));

        let pipeline_err = parse_command_text_with_aliases("ldap user 'oops | P uid", &config)
            .expect_err("invalid pipeline should fail");
        assert!(
            pipeline_err
                .to_string()
                .contains("failed to parse pipeline")
        );

        let config = test_config(&[("alias.demo", "ldap user 'oops | P uid")]);
        let err = parse_command_tokens_with_aliases(&["demo".to_string()], &config)
            .expect_err("broken alias command should fail");
        assert!(
            err.to_string()
                .contains("failed to parse alias `demo` expansion")
        );

        let plain = test_config(&[]);
        let err = expand_alias_template("loop", "echo ${next}", &[], &plain)
            .expect_err("missing placeholder should fail");
        let message = err.to_string();
        assert!(message.contains("requires value for placeholder"));
        assert!(message.contains("next"));
    }

    #[test]
    fn truncate_display_respects_utf8_boundaries() {
        assert_eq!(truncate_display("  å🙂bcdef  ", 3), "å🙂b... (7 chars)");
    }
}