kcfg 0.2.1

KUBECONFIG manipulation 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
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
use crate::common::check_file_path;
use crate::error::KcfgError;
use clap::{Parser, ValueEnum, ValueHint};
use indoc::formatdoc;

/// Options for the `init` command
#[derive(Clone, Parser, Debug)]
pub struct InitOptions {
    #[clap(value_enum)]
    /// target shell type
    pub shell_type: Option<InitShellType>,
    #[clap(short = 'p', long = "path", value_hint = ValueHint::DirPath)]
    /// Defines a custom path to kcfg program, otherwise the current filesystem path to kcfg will be used
    pub custom_path: Option<String>,
    /// Print for shell double evaluation
    #[clap(short, long)]
    pub full: bool,
}

/// Shell type you can run with the Init command
///
/// # Example
///
/// * kcfg init <SHELL-TYPE>
///
#[derive(Parser, Debug, ValueEnum, Clone)]
pub enum InitShellType {
    Zsh,
    Bash,
    Fish,
}

/// Match with the shell type the User has
/// entered for `kcfg init`
///
/// # Arguments
///
/// * `params` - options for the `init` command
///
/// # Returns
///
/// A `String` containing the produced code is returned on success.
/// An error is returned if the current path is unavailable (`FileSystem` error) or invalid.
///
pub fn init(params: InitOptions) -> Result<String, KcfgError> {
    let path = match params.custom_path {
        None => {
            let current_path = std::env::current_exe()?;
            current_path
                .to_str()
                .ok_or_else(|| KcfgError::InvalidPath(current_path.clone()))?
                .to_string()
        }
        Some(custom_path) => {
            check_file_path(&custom_path)?;
            custom_path
        }
    };
    let res = match params.shell_type {
        Some(shell_type) => match shell_type {
            InitShellType::Bash => init_bash(&path, params.full),
            InitShellType::Zsh => init_zsh(&path, params.full),
            InitShellType::Fish => init_fish(&path, params.full),
        },
        None => return Err(KcfgError::MissingShellType),
    };
    Ok(res)
}

/// # Arguments
///
/// `current_path` - string slice that contains the current path
///
/// # Returns
///
/// Return a string that contains the shell command to use in the `full` `zsh` or `bash` case
///
fn init_full_zsh_or_bash(current_path: &str) -> String {
    formatdoc! {"
        function kcfg() {{
            result=$(\"{cmd}\" $@)
            if [[ $result = 'export '* ]] then
                eval $result
            else
                echo $result
            fi
        }}
        ",
        cmd = current_path
    }
}

/// # Arguments
///
/// `current_path` - string slice that contains the current path
///
/// # Returns
///
/// Return a string that contains the shell command to use in the `full` `fish` case
///
fn init_full_fish(current_path: &str) -> String {
    formatdoc! {"
        function kcfg -d \"interpret kcfg\"
            set result $(\"{cmd}\" $argv)
            if string match -q -- \"export *\" $result
                eval $result
            else
                echo $result
            end
        end
        ",
        cmd = current_path
    }
}

/// # Arguments
///
/// `current_path` - string slice that contains the current path
///
/// # Returns
///
/// Return a string that contains the shell command to use in the `zsh` case
///
fn init_simple_zsh(current_path: &str) -> String {
    format!("source <({} init zsh --full)", current_path)
}

/// # Arguments
///
/// `current_path` - string slice that contains the current path
///
/// # Returns
///
/// Return a string that contains the shell code to use in the `bash` case
///
fn init_simple_bash(current_path: &str) -> String {
    formatdoc! {"
        __kcfg() {{
            local major=\"${{BASH_VERSINFO[0]}}\"
            local minor=\"${{BASH_VERSINFO[1]}}\"

            if ((major > 4)) || {{ ((major == 4)) && ((minor >= 1)); }}; then
                source <(\"{cmd}\" init bash --print-full-init)
            else
                source /dev/stdin <<<\"$(\"{cmd}\" init bash --full)\"
            fi
        }}
        __kcfg
        unset -f __kcfg
        ",
        cmd = current_path
    }
}

/// # Arguments
///
/// `current_path` - string slice that contains the current path
///
/// # Returns
///
/// Return a string that contains the shell command to use in the `fish` case
///
fn init_simple_fish(current_path: &str) -> String {
    format!("source <({} init fish --full)", current_path)
}

/// # Arguments
///
/// `current_path` - string slice that contains the current path
/// `is_full` - bool for full command. Double eval.
///
/// # Returns
///
/// Return a string that contains the shell command to use in the `zsh` case, with double eval if `is_full`is true
///
fn init_zsh(current_path: &str, is_full: bool) -> String {
    if is_full {
        init_full_zsh_or_bash(current_path)
    } else {
        init_simple_zsh(current_path)
    }
}

/// # Arguments
///
/// `current_path` - string slice that contains the current path
/// `is_full` - bool for full command. Double eval.
///
/// # Returns
///
/// Return a string that contains the shell code to use in the `bash` case. Double eval if `is_full`is true
///
fn init_bash(current_path: &str, is_full: bool) -> String {
    if is_full {
        init_full_zsh_or_bash(current_path)
    } else {
        init_simple_bash(current_path)
    }
}
/// # Arguments
///
/// `current_path` - string slice that contains the current path
/// `is_full` - bool for full command. Double eval.
///
/// # Returns
///
/// Return a string that contains the shell command to use in the `fish` case, with double eval if `is_full`is true
///
fn init_fish(current_path: &str, is_full: bool) -> String {
    if is_full {
        init_full_fish(current_path)
    } else {
        init_simple_fish(current_path)
    }
}

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

    mod router {
        use super::*;

        #[test]
        fn can_fail_with_wrong_path() {
            let params = InitOptions {
                shell_type: Some(InitShellType::Bash),
                custom_path: Some("toto".to_string()),
                full: false,
            };
            match init(params) {
                Ok(_) => panic!("Test should have failed"),
                Err(e) => {
                    if !matches!(e, KcfgError::PathDoesNotExist(_)) {
                        panic!("Test failed with wrong error");
                    }
                }
            }
        }

        #[test]
        fn can_fail_with_wrong_filr() {
            let params = InitOptions {
                shell_type: Some(InitShellType::Bash),
                custom_path: Some("src".to_string()),
                full: false,
            };
            match init(params) {
                Ok(_) => panic!("Test should have failed"),
                Err(e) => {
                    if !matches!(e, KcfgError::WrongFile(_)) {
                        panic!("Test failed with wrong error");
                    }
                }
            }
        }

        #[test]
        fn can_succeed_with_bash() {
            let params = InitOptions {
                shell_type: Some(InitShellType::Bash),
                custom_path: Some("src/main.rs".to_string()),
                full: false,
            };
            let res = init(params).unwrap();
            assert_eq!(
                formatdoc! {"
                    __kcfg() {{
                        local major=\"${{BASH_VERSINFO[0]}}\"
                        local minor=\"${{BASH_VERSINFO[1]}}\"

                        if ((major > 4)) || {{ ((major == 4)) && ((minor >= 1)); }}; then
                            source <(\"src/main.rs\" init bash --print-full-init)
                        else
                            source /dev/stdin <<<\"$(\"src/main.rs\" init bash --full)\"
                        fi
                    }}
                    __kcfg
                    unset -f __kcfg
                "},
                res,
            )
        }

        #[test]
        fn can_succeed_with_bash_full() {
            let params = InitOptions {
                shell_type: Some(InitShellType::Bash),
                custom_path: Some("src/main.rs".to_string()),
                full: true,
            };
            let res = init(params).unwrap();
            assert_eq!(
                formatdoc! {"
                    function kcfg() {{
                        result=$(\"src/main.rs\" $@)
                        if [[ $result = 'export '* ]] then
                            eval $result
                        else
                            echo $result
                        fi
                    }}
                "},
                res,
            )
        }

        #[test]
        fn can_succeed_with_zsh() {
            let params = InitOptions {
                shell_type: Some(InitShellType::Zsh),
                custom_path: Some("src/main.rs".to_string()),
                full: false,
            };
            let res = init(params).unwrap();
            assert_eq!("source <(src/main.rs init zsh --full)".to_string(), res,);
        }

        #[test]
        fn can_succeed_with_zsh_full() {
            let params = InitOptions {
                shell_type: Some(InitShellType::Zsh),
                custom_path: Some("src/main.rs".to_string()),
                full: true,
            };
            let res = init(params).unwrap();
            assert_eq!(
                formatdoc! {"
                    function kcfg() {{
                        result=$(\"src/main.rs\" $@)
                        if [[ $result = 'export '* ]] then
                            eval $result
                        else
                            echo $result
                        fi
                    }}
                "},
                res,
            )
        }

        #[test]
        fn can_succeed_with_fish() {
            let params = InitOptions {
                shell_type: Some(InitShellType::Fish),
                custom_path: Some("src/main.rs".to_string()),
                full: false,
            };
            let res = init(params).unwrap();
            assert_eq!("source <(src/main.rs init fish --full)".to_string(), res,);
        }

        #[test]
        fn can_succeed_with_fish_full() {
            let params = InitOptions {
                shell_type: Some(InitShellType::Fish),
                custom_path: Some("src/main.rs".to_string()),
                full: true,
            };
            let res = init(params).unwrap();
            assert_eq!(
                formatdoc! {"
                    function kcfg -d \"interpret kcfg\"
                        set result $(\"src/main.rs\" $argv)
                        if string match -q -- \"export *\" $result
                            eval $result
                        else
                            echo $result
                        end
                    end
                "},
                res,
            )
        }

        #[test]
        fn can_fail_without_shell_type() {
            let params = InitOptions {
                shell_type: None,
                custom_path: Some("src/main.rs".to_string()),
                full: false,
            };
            match init(params) {
                Ok(_) => panic!("Test should have failed"),
                Err(e) => {
                    if !matches!(e, KcfgError::MissingShellType) {
                        panic!("Test failed with wrong error");
                    }
                }
            }
        }
    }

    mod init {
        use super::*;

        #[test]
        fn test_init_zsh() {
            assert_eq!(
                "source <(test init zsh --full)".to_string(),
                init_zsh("test", false)
            );
        }

        #[test]
        fn test_init_zsh_full() {
            assert_eq!(
                formatdoc! {"
                    function kcfg() {{
                        result=$(\"test\" $@)
                        if [[ $result = 'export '* ]] then
                            eval $result
                        else
                            echo $result
                        fi
                    }}
                "},
                init_zsh("test", true)
            );
        }

        #[test]
        fn test_init_bash() {
            assert_eq!(
                formatdoc! {"
                    __kcfg() {{
                        local major=\"${{BASH_VERSINFO[0]}}\"
                        local minor=\"${{BASH_VERSINFO[1]}}\"

                        if ((major > 4)) || {{ ((major == 4)) && ((minor >= 1)); }}; then
                            source <(\"test\" init bash --print-full-init)
                        else
                            source /dev/stdin <<<\"$(\"test\" init bash --full)\"
                        fi
                    }}
                    __kcfg
                    unset -f __kcfg
                "},
                init_bash("test", false)
            );
        }

        #[test]
        fn test_init_bash_full() {
            assert_eq!(
                formatdoc! {"
                    function kcfg() {{
                        result=$(\"test\" $@)
                        if [[ $result = 'export '* ]] then
                            eval $result
                        else
                            echo $result
                        fi
                    }}
                "},
                init_bash("test", true)
            );
        }

        #[test]
        fn test_init_fish() {
            assert_eq!(
                "source <(test init fish --full)".to_string(),
                init_fish("test", false)
            );
        }

        #[test]
        fn test_init_fish_full() {
            assert_eq!(
                formatdoc! {"
                    function kcfg -d \"interpret kcfg\"
                        set result $(\"test\" $argv)
                        if string match -q -- \"export *\" $result
                            eval $result
                        else
                            echo $result
                        end
                    end
                "},
                init_fish("test", true)
            );
        }
    }
}