submod 0.3.0

A headache-free submodule management tool, built on top of gitoxide. Manage sparse checkouts, submodule updates, and adding/removing submodules with ease.
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
#![allow(unreachable_patterns)]

// SPDX-FileCopyrightText: 2025 Adam Poulemanos <89049923+bashandbone@users.noreply.github.com>
//
// SPDX-License-Identifier: LicenseRef-PlainMIT OR MIT

use clap::{ValueEnum, builder::PossibleValue};
use clap_complete::aot::Generator;
use clap_complete::aot::Shell as AotShell;
use clap_complete_nushell::Nushell as NushellShell;

/// Represents the supported shells for command-line completion.
///
/// Wraps the `clap_complete::aot::Shell` and `clap_complete_nushell::Nushell` shells,
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Shell {
    /// Bourne Again `SHell` (bash)
    Bash,
    /// Elvish shell
    Elvish,
    /// Friendly Interactive `SHell` (fish)
    Fish,
    /// `PowerShell`
    PowerShell,
    /// Z `SHell` (zsh)
    Zsh,
    /// `NuSHell`
    Nushell,
}

// Hand-rolled so it can work even when `derive` feature is disabled
impl clap::ValueEnum for Shell {
    /// Returns the possible values for this enum.
    fn value_variants<'a>() -> &'a [Self] {
        &[
            Self::Bash,
            Self::Elvish,
            Self::Fish,
            Self::PowerShell,
            Self::Zsh,
            Self::Nushell,
        ]
    }

    /// Converts the enum variant to a `PossibleValue`.
    fn to_possible_value(&self) -> Option<PossibleValue> {
        Some(match self {
            Self::Bash => PossibleValue::new("bash"),
            Self::Elvish => PossibleValue::new("elvish"),
            Self::Fish => PossibleValue::new("fish"),
            Self::PowerShell => PossibleValue::new("powershell").alias("pwsh"),
            Self::Zsh => PossibleValue::new("zsh"),
            Self::Nushell => PossibleValue::new("nushell"),
        })
    }
}

impl std::fmt::Display for Shell {
    /// Formats the shell as a string.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.to_possible_value()
            .expect("no values are skipped")
            .get_name()
            .fmt(f)
    }
}

impl std::str::FromStr for Shell {
    type Err = String;

    /// Parses a string into a `Shell` enum variant.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        for variant in Self::value_variants() {
            if variant.to_possible_value().unwrap().matches(s, false) {
                return Ok(*variant);
            }
        }
        Err(format!("invalid variant: {s}"))
    }
}

impl TryFrom<AotShell> for Shell {
    type Error = String;
    /// Converts an `AotShell` to a `Shell`.
    fn try_from(shell: AotShell) -> Result<Self, Self::Error> {
        match shell {
            AotShell::Bash => Ok(Self::Bash),
            AotShell::Elvish => Ok(Self::Elvish),
            AotShell::Fish => Ok(Self::Fish),
            AotShell::PowerShell => Ok(Self::PowerShell),
            AotShell::Zsh => Ok(Self::Zsh),
            _ => Err("Nushell is not supported in AOT mode".to_string()),
        }
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;

    #[test]
    fn test_from_path_bash() {
        assert_eq!(Shell::from_path("/bin/bash"), Some(Shell::Bash));
        assert_eq!(Shell::from_path("bash.exe"), Some(Shell::Bash));
    }

    #[test]
    fn test_from_path_zsh() {
        assert_eq!(Shell::from_path("/usr/bin/zsh"), Some(Shell::Zsh));
        assert_eq!(Shell::from_path("zsh"), Some(Shell::Zsh));
    }

    #[test]
    fn test_from_path_fish() {
        assert_eq!(Shell::from_path("/usr/local/bin/fish"), Some(Shell::Fish));
        assert_eq!(Shell::from_path("fish"), Some(Shell::Fish));
    }

    #[test]
    fn test_from_path_powershell() {
        // Rust's Path parsing behavior depends on the target OS,
        // so to make this test cross-platform we use standard paths
        // or paths that parse as expected on Unix.
        assert_eq!(Shell::from_path("powershell.exe"), Some(Shell::PowerShell));
        assert_eq!(Shell::from_path("/usr/bin/pwsh"), Some(Shell::PowerShell));
        assert_eq!(
            Shell::from_path("powershell_ise.exe"),
            Some(Shell::PowerShell)
        );
    }

    #[test]
    fn test_from_path_elvish() {
        assert_eq!(Shell::from_path("/usr/bin/elvish"), Some(Shell::Elvish));
        assert_eq!(Shell::from_path("elvish"), Some(Shell::Elvish));
    }

    #[test]
    fn test_from_path_nushell() {
        assert_eq!(Shell::from_path("/usr/bin/nu"), Some(Shell::Nushell));
        assert_eq!(Shell::from_path("nu.exe"), Some(Shell::Nushell));
        assert_eq!(Shell::from_path("nushell"), Some(Shell::Nushell));
    }

    #[test]
    fn test_from_path_unknown() {
        assert_eq!(Shell::from_path("/bin/sh"), None);
        assert_eq!(Shell::from_path("cmd.exe"), None);
        assert_eq!(Shell::from_path("python"), None);
        assert_eq!(Shell::from_path("unknown_shell"), None);
    }

    #[test]
    fn test_from_path_empty_and_invalid() {
        assert_eq!(Shell::from_path(""), None);
        assert_eq!(Shell::from_path("/"), None);
        assert_eq!(Shell::from_path("."), None);
        assert_eq!(Shell::from_path(".."), None);

        // .bash file stem is ".bash" which won't match "bash", so it should be None.
        assert_eq!(Shell::from_path(".bash"), None);
    }

    // ================================================================
    // Shell::from_str and Display
    // ================================================================

    #[test]
    fn test_shell_from_str() {
        assert_eq!(
            <Shell as std::str::FromStr>::from_str("bash").unwrap(),
            Shell::Bash
        );
        assert_eq!(
            <Shell as std::str::FromStr>::from_str("zsh").unwrap(),
            Shell::Zsh
        );
        assert_eq!(
            <Shell as std::str::FromStr>::from_str("fish").unwrap(),
            Shell::Fish
        );
        assert_eq!(
            <Shell as std::str::FromStr>::from_str("powershell").unwrap(),
            Shell::PowerShell
        );
        assert_eq!(
            <Shell as std::str::FromStr>::from_str("elvish").unwrap(),
            Shell::Elvish
        );
        assert_eq!(
            <Shell as std::str::FromStr>::from_str("nushell").unwrap(),
            Shell::Nushell
        );
    }

    #[test]
    fn test_shell_from_str_alias() {
        assert_eq!(
            <Shell as std::str::FromStr>::from_str("pwsh").unwrap(),
            Shell::PowerShell
        );
    }

    #[test]
    fn test_shell_from_str_invalid() {
        assert!(<Shell as std::str::FromStr>::from_str("cmd").is_err());
        assert!(<Shell as std::str::FromStr>::from_str("").is_err());
        assert!(<Shell as std::str::FromStr>::from_str("BASH").is_err()); // case-sensitive
    }

    #[test]
    fn test_shell_display() {
        assert_eq!(format!("{}", Shell::Bash), "bash");
        assert_eq!(format!("{}", Shell::Zsh), "zsh");
        assert_eq!(format!("{}", Shell::Fish), "fish");
        assert_eq!(format!("{}", Shell::PowerShell), "powershell");
        assert_eq!(format!("{}", Shell::Elvish), "elvish");
        assert_eq!(format!("{}", Shell::Nushell), "nushell");
    }

    // ================================================================
    // TryFrom conversions: AotShell ↔ Shell ↔ NushellShell
    // ================================================================

    #[test]
    fn test_shell_to_aotshell() {
        let aot: AotShell = Shell::Bash.try_into().unwrap();
        assert_eq!(aot, AotShell::Bash);
        let aot: AotShell = Shell::Zsh.try_into().unwrap();
        assert_eq!(aot, AotShell::Zsh);
        let aot: AotShell = Shell::Fish.try_into().unwrap();
        assert_eq!(aot, AotShell::Fish);
        let aot: AotShell = Shell::PowerShell.try_into().unwrap();
        assert_eq!(aot, AotShell::PowerShell);
        let aot: AotShell = Shell::Elvish.try_into().unwrap();
        assert_eq!(aot, AotShell::Elvish);
    }

    #[test]
    fn test_nushell_to_aotshell_fails() {
        let result: Result<AotShell, _> = Shell::Nushell.try_into();
        assert!(result.is_err());
    }

    #[test]
    fn test_aotshell_to_shell() {
        let shell: Shell = AotShell::Bash.try_into().unwrap();
        assert_eq!(shell, Shell::Bash);
        let shell: Shell = AotShell::Zsh.try_into().unwrap();
        assert_eq!(shell, Shell::Zsh);
        let shell: Shell = AotShell::Fish.try_into().unwrap();
        assert_eq!(shell, Shell::Fish);
        let shell: Shell = AotShell::PowerShell.try_into().unwrap();
        assert_eq!(shell, Shell::PowerShell);
        let shell: Shell = AotShell::Elvish.try_into().unwrap();
        assert_eq!(shell, Shell::Elvish);
    }

    #[test]
    fn test_shell_to_nushell_shell() {
        // NushellShell doesn't implement PartialEq/Debug, so just check it doesn't panic
        let _nu: NushellShell = Shell::Nushell.try_into().unwrap();
    }

    #[test]
    fn test_non_nushell_to_nushell_shell_fails() {
        let result: Result<NushellShell, _> = Shell::Bash.try_into();
        assert!(result.is_err());
        let result: Result<NushellShell, _> = Shell::Zsh.try_into();
        assert!(result.is_err());
    }

    #[test]
    fn test_nushell_shell_to_shell() {
        let shell: Shell = NushellShell.try_into().unwrap();
        assert_eq!(shell, Shell::Nushell);
    }

    // ================================================================
    // try_to_clap_complete
    // ================================================================

    #[test]
    fn test_try_to_clap_complete_all_variants() {
        // All shell variants should successfully convert
        assert!(Shell::Bash.try_to_clap_complete().is_ok());
        assert!(Shell::Zsh.try_to_clap_complete().is_ok());
        assert!(Shell::Fish.try_to_clap_complete().is_ok());
        assert!(Shell::PowerShell.try_to_clap_complete().is_ok());
        assert!(Shell::Elvish.try_to_clap_complete().is_ok());
        assert!(Shell::Nushell.try_to_clap_complete().is_ok());
    }

    // ================================================================
    // ValueEnum
    // ================================================================

    #[test]
    fn test_value_variants_count() {
        assert_eq!(Shell::value_variants().len(), 6);
    }

    #[test]
    fn test_to_possible_value_all_some() {
        for variant in Shell::value_variants() {
            assert!(variant.to_possible_value().is_some());
        }
    }

    // ================================================================
    // Generator: file_name and try_generate
    // ================================================================

    #[test]
    fn test_generator_file_name() {
        let bash_name = <Shell as Generator>::file_name(&Shell::Bash, "submod");
        assert!(!bash_name.is_empty());

        let nu_name = <Shell as Generator>::file_name(&Shell::Nushell, "submod");
        assert!(nu_name.contains("submod"));
    }

    #[test]
    fn test_generator_try_generate_produces_output() {
        use clap::Command;

        for shell in Shell::value_variants() {
            let mut cmd = Command::new("test-cmd").subcommand(Command::new("sub1"));
            let mut buf = Vec::new();
            // clap_complete::generate sets bin_name internally
            clap_complete::generate(*shell, &mut cmd, "test-cmd", &mut buf);
            assert!(!buf.is_empty(), "Empty output for {:?}", shell);
        }
    }
}

impl TryFrom<Shell> for AotShell {
    type Error = String;

    /// Attempts to convert a `Shell` to an `AotShell`.
    fn try_from(shell: Shell) -> Result<Self, Self::Error> {
        match shell {
            Shell::Bash => Ok(Self::Bash),
            Shell::Elvish => Ok(Self::Elvish),
            Shell::Fish => Ok(Self::Fish),
            Shell::PowerShell => Ok(Self::PowerShell),
            Shell::Zsh => Ok(Self::Zsh),
            Shell::Nushell => Err("Nushell is not supported in AOT mode".to_string()),
        }
    }
}

impl TryFrom<Shell> for NushellShell {
    type Error = String;

    /// Attempts to convert a `Shell` to a `NushellShell`.
    fn try_from(shell: Shell) -> Result<Self, Self::Error> {
        if shell == Shell::Nushell {
            Ok(Self)
        } else {
            Err("Only Nushell can be converted to NushellShell".to_string())
        }
    }
}

impl TryFrom<NushellShell> for Shell {
    type Error = String;
    /// Converts a `NushellShell` to a `Shell`.
    fn try_from(shell: NushellShell) -> Result<Self, String> {
        match shell {
            NushellShell => Ok(Self::Nushell),
            _ => Err("Only NushellShell can be converted to Shell::Nushell".to_string()),
        }
    }
}

impl Shell {
    /// Converts the `Shell` enum to a shell enum implementing `clap_complete::Generator` (as a Box pointer).
    pub fn try_to_clap_complete(&self) -> Result<Box<dyn Generator>, String> {
        match self {
            Self::Bash => Ok(Box::new(AotShell::Bash)),
            Self::Elvish => Ok(Box::new(AotShell::Elvish)),
            Self::Fish => Ok(Box::new(AotShell::Fish)),
            Self::PowerShell => Ok(Box::new(AotShell::PowerShell)),
            Self::Zsh => Ok(Box::new(AotShell::Zsh)),
            Self::Nushell => Ok(Box::new(NushellShell)),
        }
    }

    /// Tries to find the shell from a path to its executable.
    pub fn from_path<P: AsRef<std::path::Path>>(path: P) -> Option<Self> {
        Self::parse_shell_from_path(path.as_ref())
    }

    fn parse_shell_from_path(path: &std::path::Path) -> Option<Self> {
        let name = path.file_stem()?.to_str()?;
        match name {
            "bash" => Some(Self::Bash),
            "elvish" => Some(Self::Elvish),
            "fish" => Some(Self::Fish),
            "powershell" | "pwsh" | "powershell_ise" => Some(Self::PowerShell),
            "zsh" => Some(Self::Zsh),
            "nu" | "nushell" => Some(Self::Nushell),
            _ => None,
        }
    }

    /// Attempts to find the shell from the `SHELL` environment variable.
    #[must_use] pub fn from_env() -> Option<Self> {
        if let Some(env_shell) = std::env::var_os("SHELL") {
            Self::parse_shell_from_path(std::path::Path::new(&env_shell))
        } else {
            None
        }
    }
}

impl Generator for Shell {
    /// Returns the file name for the completion file.
    fn file_name(&self, name: &str) -> String {
        let shell_self = self.try_to_clap_complete();
        shell_self.map_or_else(|_| format!("{name}.nu"), |s| s.file_name(name)) // Default to Nushell if conversion fails
    }

    /// Generates the completion file for the given command and writes it to the provided buffer.
    fn generate(&self, cmd: &clap::Command, buf: &mut dyn std::io::Write) {
        let shell_self = self.try_to_clap_complete();
        shell_self
            .map(|s| {
                s.try_generate(cmd, buf)
                    .unwrap_or_else(|e| panic!("failed to write completion file: {e}"));
            })
            .unwrap_or_else(|_| panic!("failed to write completion file"));
    }

    /// Attempts to generate the completion file for the given command and writes it to the provided buffer.
    fn try_generate(
        &self,
        cmd: &clap::Command,
        buf: &mut dyn std::io::Write,
    ) -> Result<(), std::io::Error> {
        let shell_self = self.try_to_clap_complete();
        match shell_self {
            Ok(s) => s.try_generate(cmd, buf),
            Err(e) => Err(std::io::Error::other(e)),
        }
    }
}