decompose 0.2.1

A simple and flexible scheduler and orchestrator to manage non-containerized applications
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
//! Shell completion generation.
//!
//! `decompose completion <shell>` prints a ready-to-source completion script
//! for the given shell. Scripts are generated by `clap_complete` from the
//! clap `Command` tree, then post-processed to add dynamic completion that
//! shells out to `decompose config --json` (for service names) and
//! `decompose ls --json` (for active session names) at completion time.
//!
//! The injected helpers forward the pre-subcommand global flags
//! (`--file`, `-e`/`--env-file`, `--session`, `--disable-dotenv`) so dynamic
//! completion works in multi-project / multi-session setups.

use std::io;

use anyhow::{Context, Result};
use clap::CommandFactory;
use clap_complete::{Shell, generate};

use crate::cli::{Cli, CompletionShell};

const BIN_NAME: &str = "decompose";

/// Subcommands whose positional arguments are service names. The dynamic
/// completion injected into the shell scripts completes these by invoking
/// `decompose config --json`.
///
/// Exposed at `pub(crate)` visibility so integration tests can
/// regression-check this list against the clap command tree in `cli.rs`.
pub(crate) const SERVICE_CMDS: &[&str] = &[
    "start", "stop", "restart", "kill", "logs", "exec", "run", "up",
];

pub fn run_completion(shell: CompletionShell) -> Result<()> {
    let clap_shell = to_clap_shell(shell);
    let mut cmd = Cli::command();
    let mut buf: Vec<u8> = Vec::new();
    generate(clap_shell, &mut cmd, BIN_NAME, &mut buf);
    let script = String::from_utf8(buf).context("completion script was not valid UTF-8")?;
    let final_script = match shell {
        CompletionShell::Bash => inject_bash_dynamic(&script),
        CompletionShell::Zsh => inject_zsh_dynamic(&script),
        CompletionShell::Fish => inject_fish_dynamic(&script),
        CompletionShell::PowerShell => inject_powershell_dynamic(&script),
        CompletionShell::Elvish => script,
    };
    use io::Write as _;
    let stdout = io::stdout();
    let mut lock = stdout.lock();
    lock.write_all(final_script.as_bytes())
        .context("failed to write completion script")?;
    Ok(())
}

fn to_clap_shell(shell: CompletionShell) -> Shell {
    match shell {
        CompletionShell::Bash => Shell::Bash,
        CompletionShell::Zsh => Shell::Zsh,
        CompletionShell::Fish => Shell::Fish,
        CompletionShell::PowerShell => Shell::PowerShell,
        CompletionShell::Elvish => Shell::Elvish,
    }
}

/// Append a helper at the end of the generated bash script that:
/// - harvests the pre-subcommand global flags from `COMP_WORDS`,
/// - forwards them to `decompose config --json` for service-name completion,
/// - completes `--session`/`--project-name` values from `decompose ls --json`,
/// - otherwise falls through to the clap-generated `_decompose` function.
fn inject_bash_dynamic(script: &str) -> String {
    let svc_list = SERVICE_CMDS
        .iter()
        .map(|s| format!("\"{s}\""))
        .collect::<Vec<_>>()
        .join(" ");
    let snippet = BASH_DYNAMIC_SNIPPET.replace("__SVC_LIST__", &svc_list);
    format!("{script}{snippet}")
}

/// Append a zsh helper that re-registers `decompose` with a wrapper calling
/// the clap-generated `_decompose` function first and then, if completing a
/// positional arg on a service-taking subcommand, offering service names
/// from `decompose config --json` (with global flags forwarded). Also
/// completes `--session`/`--project-name` from `decompose ls --json`.
fn inject_zsh_dynamic(script: &str) -> String {
    let svc_list = SERVICE_CMDS.join(" ");
    let snippet = ZSH_DYNAMIC_SNIPPET.replace("__SVC_LIST__", &svc_list);
    format!("{script}{snippet}")
}

/// Append fish `complete -c decompose -n ... -a '(...)'` lines that invoke
/// `decompose config --json` (forwarding global flags) for service-name
/// positions, and `decompose ls --json` for `--session`/`--project-name`
/// values.
fn inject_fish_dynamic(script: &str) -> String {
    let svc_list = SERVICE_CMDS.join(" ");
    let snippet = FISH_DYNAMIC_SNIPPET.replace("__SVC_LIST__", &svc_list);
    format!("{script}{snippet}")
}

/// Append a `Register-ArgumentCompleter` block that completes service names
/// for the `SERVICE_CMDS` subcommands by calling `decompose config --json`.
/// Session-name completion is best-effort via the same completer.
fn inject_powershell_dynamic(script: &str) -> String {
    let svc_list = SERVICE_CMDS
        .iter()
        .map(|s| format!("'{s}'"))
        .collect::<Vec<_>>()
        .join(", ");
    let snippet = POWERSHELL_DYNAMIC_SNIPPET.replace("__SVC_LIST__", &svc_list);
    format!("{script}{snippet}")
}

/// Bash helper.
///
/// Marker strings asserted in integration tests:
///   `__decompose_services`, `__decompose_sessions`,
///   `__decompose_collect_globals`, `complete -F __decompose_wrap`.
const BASH_DYNAMIC_SNIPPET: &str = r#"
# --- decompose dynamic service completion (injected) -------------------------

# Walk COMP_WORDS[1..COMP_CWORD-1] and collect the pre-subcommand global
# flags (--file, -e/--env-file, --session/--project-name, --disable-dotenv)
# so we can forward them to `decompose config --json` / `decompose ls --json`.
# Stops at the first non-flag token (the subcommand).
#
# Populates the global array __DECOMPOSE_GLOBALS and the global string
# __DECOMPOSE_SUBCMD.
__decompose_collect_globals() {
    __DECOMPOSE_GLOBALS=()
    __DECOMPOSE_SUBCMD=""
    local i=1 tok
    while (( i < COMP_CWORD )); do
        tok="${COMP_WORDS[i]}"
        case "$tok" in
            --file=*|--session=*|--project-name=*|--env-file=*)
                __DECOMPOSE_GLOBALS+=("$tok")
                ;;
            --file|--session|--project-name|--env-file|-e)
                __DECOMPOSE_GLOBALS+=("$tok")
                if (( i + 1 < COMP_CWORD )); then
                    (( i++ ))
                    __DECOMPOSE_GLOBALS+=("${COMP_WORDS[i]}")
                fi
                ;;
            --disable-dotenv)
                __DECOMPOSE_GLOBALS+=("$tok")
                ;;
            -*)
                # Unknown flag — keep scanning; might take a value but we
                # don't know, so just treat the token itself as forwarded
                # context and continue.
                ;;
            *)
                __DECOMPOSE_SUBCMD="$tok"
                return 0
                ;;
        esac
        (( i++ ))
    done
    return 0
}

__decompose_services() {
    local svcs raw
    raw=$(decompose "${__DECOMPOSE_GLOBALS[@]}" config --json 2>/dev/null) || return 0
    if command -v jq >/dev/null 2>&1; then
        svcs=$(printf '%s' "$raw" | jq -r '.processes | keys[]' 2>/dev/null)
    else
        svcs=$(printf '%s' "$raw" \
            | sed -n 's/^  *"\([A-Za-z0-9_][A-Za-z0-9_-]*\)": *{.*/\1/p')
    fi
    COMPREPLY=( $(compgen -W "${svcs}" -- "${cur}") )
}

__decompose_sessions() {
    local names raw
    raw=$(decompose ls --json 2>/dev/null) || return 0
    if command -v jq >/dev/null 2>&1; then
        names=$(printf '%s' "$raw" | jq -r '.environments[]?.name' 2>/dev/null)
    else
        names=$(printf '%s' "$raw" \
            | sed -n 's/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
    fi
    COMPREPLY=( $(compgen -W "${names}" -- "${cur}") )
}

__decompose_wrap() {
    local cur prev
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev=""
    if (( COMP_CWORD > 0 )); then
        prev="${COMP_WORDS[COMP_CWORD-1]}"
    fi

    # Session value: `--session <TAB>`, `--project-name <TAB>`, or `--session=<TAB>`.
    case "$prev" in
        --session|--project-name)
            __decompose_sessions
            return 0
            ;;
    esac
    case "$cur" in
        --session=*|--project-name=*)
            local raw="${cur#*=}"
            local names
            local _saved="$cur"
            cur="$raw"
            __decompose_sessions
            cur="$_saved"
            # Re-prepend the flag= prefix to each candidate.
            local prefix="${_saved%%=*}="
            local i
            for (( i=0; i<${#COMPREPLY[@]}; i++ )); do
                COMPREPLY[i]="${prefix}${COMPREPLY[i]}"
            done
            return 0
            ;;
    esac

    __decompose_collect_globals
    case " __SVC_LIST__ " in
        *" \"${__DECOMPOSE_SUBCMD}\" "*)
            if [[ "${cur}" != -* ]]; then
                __decompose_services
                return 0
            fi
            ;;
    esac
    # Fall back to the clap-generated completion function.
    if declare -F _decompose >/dev/null 2>&1; then
        _decompose
    fi
}
complete -F __decompose_wrap -o bashdefault -o default decompose
# -----------------------------------------------------------------------------
"#;

/// Zsh helper.
///
/// Marker strings asserted in integration tests:
///   `__decompose_services`, `__decompose_sessions`,
///   `__decompose_collect_globals`, `compdef __decompose_dyn_wrap decompose`.
const ZSH_DYNAMIC_SNIPPET: &str = r#"
# --- decompose dynamic service completion (injected) -------------------------

# Walk $words[2..CURRENT-1] and collect pre-subcommand global flags.
# Populates the global array __decompose_globals and string __decompose_sub.
__decompose_collect_globals() {
    __decompose_globals=()
    __decompose_sub=""
    local i=2 tok
    while (( i < CURRENT )); do
        tok="${words[i]}"
        case "$tok" in
            --file=*|--session=*|--project-name=*|--env-file=*)
                __decompose_globals+=("$tok")
                ;;
            --file|--session|--project-name|--env-file|-e)
                __decompose_globals+=("$tok")
                if (( i + 1 < CURRENT )); then
                    (( i++ ))
                    __decompose_globals+=("${words[i]}")
                fi
                ;;
            --disable-dotenv)
                __decompose_globals+=("$tok")
                ;;
            -*)
                ;;
            *)
                __decompose_sub="$tok"
                return 0
                ;;
        esac
        (( i++ ))
    done
    return 0
}

__decompose_services() {
    local -a svcs
    local raw
    raw=$(decompose "${__decompose_globals[@]}" config --json 2>/dev/null) || return 0
    if (( $+commands[jq] )); then
        svcs=(${(f)"$(print -r -- "$raw" | jq -r '.processes | keys[]' 2>/dev/null)"})
    else
        svcs=(${(f)"$(print -r -- "$raw" | sed -n 's/^  *"\([A-Za-z0-9_][A-Za-z0-9_-]*\)": *{.*/\1/p')"})
    fi
    if (( ${#svcs} )); then
        _values 'service' "${svcs[@]}"
    fi
}

__decompose_sessions() {
    local -a names
    local raw
    raw=$(decompose ls --json 2>/dev/null) || return 0
    if (( $+commands[jq] )); then
        names=(${(f)"$(print -r -- "$raw" | jq -r '.environments[]?.name' 2>/dev/null)"})
    else
        names=(${(f)"$(print -r -- "$raw" | sed -n 's/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')"})
    fi
    if (( ${#names} )); then
        _values 'session' "${names[@]}"
    fi
}

__decompose_dyn_wrap() {
    local -a service_cmds
    service_cmds=(__SVC_LIST__)
    local -a __decompose_globals
    local __decompose_sub=""

    # `--session <TAB>` / `--project-name <TAB>`.
    if (( CURRENT >= 2 )); then
        local prev="${words[CURRENT-1]}"
        case "$prev" in
            --session|--project-name)
                __decompose_sessions
                return 0
                ;;
        esac
    fi
    # `--session=<TAB>` / `--project-name=<TAB>`.
    case "${words[CURRENT]}" in
        --session=*|--project-name=*)
            __decompose_sessions
            return 0
            ;;
    esac

    __decompose_collect_globals
    if [[ -n "$__decompose_sub" && "${service_cmds[(r)$__decompose_sub]}" == "$__decompose_sub" && "${words[CURRENT]}" != -* ]]; then
        __decompose_services
        return 0
    fi
    _decompose "$@"
}
compdef __decompose_dyn_wrap decompose
# -----------------------------------------------------------------------------
"#;

/// Fish helper.
///
/// Marker strings asserted in integration tests:
///   `__decompose_services`, `__decompose_sessions`,
///   `__decompose_collect_globals`, `__fish_seen_subcommand_from`.
const FISH_DYNAMIC_SNIPPET: &str = r#"
# --- decompose dynamic service completion (injected) -------------------------

# Walk the current command line and echo the pre-subcommand global flags
# (one token per line) so they can be forwarded to `decompose config --json`.
function __decompose_collect_globals
    set -l tokens (commandline -opc)
    set -l n (count $tokens)
    set -l i 2
    while test $i -le $n
        set -l tok $tokens[$i]
        switch $tok
            case '--file=*' '--session=*' '--project-name=*' '--env-file=*'
                echo -- $tok
            case '--file' '--session' '--project-name' '--env-file' '-e'
                echo -- $tok
                set i (math $i + 1)
                if test $i -le $n
                    echo -- $tokens[$i]
                end
            case '--disable-dotenv'
                echo -- $tok
            case '-*'
                # unknown flag, skip
            case '*'
                return 0
        end
        set i (math $i + 1)
    end
end

function __decompose_services
    set -l globals (__decompose_collect_globals)
    set -l raw (decompose $globals config --json 2>/dev/null)
    if test -z "$raw"
        return 0
    end
    if type -q jq
        printf '%s' $raw | jq -r '.processes | keys[]' 2>/dev/null
    else
        printf '%s' $raw | sed -n 's/^  *"\([A-Za-z0-9_][A-Za-z0-9_-]*\)": *{.*/\1/p'
    end
end

function __decompose_sessions
    set -l raw (decompose ls --json 2>/dev/null)
    if test -z "$raw"
        return 0
    end
    if type -q jq
        printf '%s' $raw | jq -r '.environments[]?.name' 2>/dev/null
    else
        printf '%s' $raw | sed -n 's/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p'
    end
end

# Service-name completion for each service-taking subcommand.
complete -c decompose -n '__fish_seen_subcommand_from __SVC_LIST__' -f -a '(__decompose_services)'

# Session-name completion for --session / --project-name (long-form values).
complete -c decompose -l session -f -a '(__decompose_sessions)'
complete -c decompose -l project-name -f -a '(__decompose_sessions)'
# -----------------------------------------------------------------------------
"#;

/// PowerShell helper.
///
/// Marker strings asserted in integration tests:
///   `Register-ArgumentCompleter`, `__DecomposeServices`,
///   `__DecomposeSessions`.
const POWERSHELL_DYNAMIC_SNIPPET: &str = r#"
# --- decompose dynamic service completion (injected) -------------------------

function __DecomposeCollectGlobals {
    param([string[]]$Words)
    $globals = @()
    # $Words[0] is typically the command name; scan the rest for pre-subcommand
    # global flags. Stop at the first non-flag token.
    for ($i = 1; $i -lt $Words.Length; $i++) {
        $t = $Words[$i]
        switch -Regex ($t) {
            '^(--file|--session|--project-name|--env-file)=.*$' { $globals += $t; continue }
            '^(--file|--session|--project-name|--env-file|-e)$' {
                $globals += $t
                if ($i + 1 -lt $Words.Length) { $i++; $globals += $Words[$i] }
                continue
            }
            '^--disable-dotenv$' { $globals += $t; continue }
            '^-' { continue }
            default { return ,$globals }
        }
    }
    return ,$globals
}

function __DecomposeServices {
    param([string[]]$Words)
    try {
        $globals = __DecomposeCollectGlobals $Words
        $raw = & decompose @globals config --json 2>$null
        if (-not $raw) { return @() }
        $data = $raw | ConvertFrom-Json -ErrorAction Stop
        if ($null -ne $data.processes) {
            return @($data.processes.PSObject.Properties | ForEach-Object { $_.Name })
        }
    } catch { }
    return @()
}

function __DecomposeSessions {
    try {
        $raw = & decompose ls --json 2>$null
        if (-not $raw) { return @() }
        $data = $raw | ConvertFrom-Json -ErrorAction Stop
        if ($null -ne $data.environments) {
            return @($data.environments | ForEach-Object { $_.name })
        }
    } catch { }
    return @()
}

Register-ArgumentCompleter -Native -CommandName decompose -ScriptBlock {
    param($wordToComplete, $commandAst, $cursorPosition)

    $tokens = @($commandAst.CommandElements | ForEach-Object { $_.Extent.Text })
    $svcCmds = @(__SVC_LIST__)

    # Determine the current subcommand (first non-flag token after the binary).
    $subcmd = $null
    for ($i = 1; $i -lt $tokens.Length; $i++) {
        $t = $tokens[$i]
        if ($t -notlike '-*') { $subcmd = $t; break }
    }

    # Session value completion.
    if ($tokens.Length -ge 2) {
        $prev = $tokens[$tokens.Length - 2]
        if ($prev -eq '--session' -or $prev -eq '--project-name') {
            return @(__DecomposeSessions) `
                | Where-Object { $_ -like "$wordToComplete*" } `
                | ForEach-Object {
                    [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
                }
        }
    }
    if ($wordToComplete -match '^(--session|--project-name)=(.*)$') {
        $prefix = $Matches[1] + '='
        $value = $Matches[2]
        return @(__DecomposeSessions) `
            | Where-Object { $_ -like "$value*" } `
            | ForEach-Object {
                $t = $prefix + $_
                [System.Management.Automation.CompletionResult]::new($t, $t, 'ParameterValue', $t)
            }
    }

    # Service-name completion for service-taking subcommands.
    if ($null -ne $subcmd -and $svcCmds -contains $subcmd -and $wordToComplete -notlike '-*') {
        return @(__DecomposeServices $tokens) `
            | Where-Object { $_ -like "$wordToComplete*" } `
            | ForEach-Object {
                [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
            }
    }

    # No dynamic match — let the default clap-generated completer handle it.
    return @()
}
# -----------------------------------------------------------------------------
"#;

#[cfg(test)]
mod tests {
    use super::*;
    use clap::CommandFactory;

    /// Regression guard: every entry in `SERVICE_CMDS` must correspond to a
    /// real subcommand in the clap tree. If a subcommand is renamed or removed
    /// without updating `SERVICE_CMDS`, the dynamic completion will silently
    /// stop working for the stale name.
    #[test]
    fn service_cmds_are_real_subcommands() {
        let cmd = Cli::command();
        let names: Vec<String> = cmd
            .get_subcommands()
            .map(|c| c.get_name().to_string())
            .collect();
        for svc in SERVICE_CMDS {
            assert!(
                names.iter().any(|n| n == svc),
                "SERVICE_CMDS entry {svc:?} has no matching clap subcommand (found: {names:?})"
            );
        }
    }

    /// Ensure every clap subcommand whose positional takes service names is
    /// represented in `SERVICE_CMDS`. We detect "takes service names" by
    /// matching the set of known service-accepting subcommands by name here;
    /// this test is a lightweight twin of the static list so a new
    /// service-taking command added without updating `SERVICE_CMDS` is still
    /// caught by the integration regression test.
    #[test]
    fn service_cmds_list_matches_known_shape() {
        // Hardcoded mirror of SERVICE_CMDS — if they go out of sync, fix both.
        let expected = [
            "start", "stop", "restart", "kill", "logs", "exec", "run", "up",
        ];
        assert_eq!(SERVICE_CMDS, &expected);
    }

    #[test]
    fn bash_snippet_mentions_flag_forwarding_and_sessions() {
        let s = BASH_DYNAMIC_SNIPPET;
        assert!(s.contains("__decompose_collect_globals"));
        assert!(s.contains("__decompose_sessions"));
        assert!(s.contains("decompose \"${__DECOMPOSE_GLOBALS[@]}\" config --json"));
    }

    #[test]
    fn zsh_snippet_mentions_flag_forwarding_and_sessions() {
        let s = ZSH_DYNAMIC_SNIPPET;
        assert!(s.contains("__decompose_collect_globals"));
        assert!(s.contains("__decompose_sessions"));
        assert!(s.contains("decompose \"${__decompose_globals[@]}\" config --json"));
    }

    #[test]
    fn fish_snippet_mentions_flag_forwarding_and_sessions() {
        let s = FISH_DYNAMIC_SNIPPET;
        assert!(s.contains("__decompose_collect_globals"));
        assert!(s.contains("__decompose_sessions"));
        assert!(s.contains("__fish_seen_subcommand_from"));
    }

    #[test]
    fn powershell_snippet_mentions_flag_forwarding_and_sessions() {
        let s = POWERSHELL_DYNAMIC_SNIPPET;
        assert!(s.contains("__DecomposeCollectGlobals"));
        assert!(s.contains("__DecomposeSessions"));
        assert!(s.contains("Register-ArgumentCompleter"));
    }
}