click 0.6.3

A command-line REPL for Kubernetes that integrates into existing cli workflows
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
// Copyright 2021 Databricks, Inc.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use chrono::offset::Utc;
use clap::{Arg, Command as ClapCommand};
use comfy_table::Table;
use rustyline::completion::Pair as RustlinePair;

use crate::{
    command::command_def::{exec_match, identity, start_clap, Cmd},
    completer, config,
    env::Env,
    output::ClickWriter,
    table::CellSpec,
};

use std::cell::RefCell;
use std::collections::HashMap;
use std::io::{stderr, Write};

command!(
    Clear,
    "clear",
    "Clear the currently selected kubernetes object",
    identity,
    vec!["clear"],
    noop_complete!(),
    no_named_complete!(),
    |_, env, _| {
        env.clear_current();
        Ok(())
    }
);

fn print_contexts(env: &Env, writer: &mut ClickWriter) {
    let mut contexts: Vec<&String> = env.config.contexts.keys().collect();
    contexts.sort();
    let ctxs = contexts
        .iter()
        .map(|context| {
            let mut row: Vec<CellSpec> = Vec::new();
            let cluster = match env.config.clusters.get(*context) {
                Some(c) => c.server.as_str(),
                None => "[no cluster for context]",
            };
            row.push(CellSpec::with_colors(
                (*context).clone().into(),
                Some(env.styles.context_table_color().into()),
                None,
            ));
            row.push(cluster.into());
            row
        })
        .collect();
    crate::table::print_table(vec!["Context", "Api Server Address"], ctxs, env, writer);
}

command!(
    Context,
    "context",
    "Set the current context (will clear any selected pod). \
     With no argument, lists available contexts.",
    |clap: ClapCommand<'static>| clap.arg(
        Arg::new("context")
            .help("The name of the context")
            .required(false)
            .index(1)
    ),
    vec!["ctx", "context"],
    vec![&completer::context_complete],
    no_named_complete!(),
    |matches, env, writer| {
        if matches.contains_id("context") {
            let context = matches.get_one::<String>("context").map(|s| s.as_str());
            if let (Some(cur), Some(c)) = (&env.context, context) {
                if cur.name == c {
                    // no-op if we're already in the specified context1
                    return Ok(());
                }
            }
            env.set_context(context);
            env.clear_current();
        } else {
            print_contexts(env, writer);
        }
        Ok(())
    }
);

command!(
    Contexts,
    "contexts",
    "List available contexts",
    identity,
    vec!["contexts", "ctxs"],
    noop_complete!(),
    no_named_complete!(),
    |_, env, writer| {
        print_contexts(env, writer);
        Ok(())
    }
);

command!(
    EnvCmd,
    "env",
    "Print information about the current environment",
    identity,
    vec!["env"],
    noop_complete!(),
    no_named_complete!(),
    |_matches, env, writer| {
        clickwriteln!(writer, "{}", env);
        Ok(())
    }
);

command!(
    As,
    "as",
    "Set the username to impersonate for requests. With no arg, shows the current setting",
    |clap: ClapCommand<'static>| {
        clap.arg(
            Arg::new("user")
                .help("The name of the user to impersonate")
                .required(false)
                .index(1),
        )
        .arg(
            Arg::new("clear")
                .short('c')
                .long("clear")
                .help("revert to the default user"),
        )
    },
    vec!["as"],
    noop_complete!(),
    no_named_complete!(),
    |matches, env, writer| {
        if matches.contains_id("clear") {
            env.set_impersonate_user(None);
            clickwriteln!(writer, "Impersonate user cleared");
        } else if matches.contains_id("user") {
            let user = matches
                .get_one::<String>("user")
                .map(|s| s.as_str())
                .map(|s| s.to_string());
            clickwriteln!(
                writer,
                "Set impersonate user to: {}",
                user.as_deref().unwrap()
            );
            env.set_impersonate_user(user);
        } else {
            match env.get_impersonate_user() {
                Some(user) => {
                    clickwriteln!(writer, "Impersonate user: {}", user);
                }
                None => {
                    clickwriteln!(writer, "Using default user from config");
                }
            }
        }
        Ok(())
    }
);

command!(
    Quit,
    "quit",
    "Quit click",
    identity,
    vec!["q", "quit", "exit"],
    noop_complete!(),
    no_named_complete!(),
    |_, env, _| {
        env.quit = true;
        Ok(())
    }
);

command!(
    Range,
    "range",
    "List the objects that are in the currently selected range (see 'help ranges' for general \
     information about ranges)",
    identity,
    vec!["range"],
    noop_complete!(),
    no_named_complete!(),
    |_, env, writer| {
        let mut table = Table::new();
        table.set_header(vec!["Name", "Type", "Namespace"]);
        env.apply_to_selection(writer, None, |obj, _| {
            table.add_row(vec![
                obj.name(),
                obj.type_str(),
                obj.namespace.as_deref().unwrap_or(""),
            ]);
            Ok(())
        })?;
        crate::table::print_filled_table(&mut table, writer);
        Ok(())
    }
);

command!(
    Last,
    "last",
    "List target objects from the last executed query",
    identity,
    vec!["last"],
    noop_complete!(),
    no_named_complete!(),
    |_, env, writer| {
        if let Some(table) = env.get_last_table() {
            clickwriteln!(writer, "{table}");
        } else {
            clickwriteln!(writer, "no last objects to display");
        }
        Ok(())
    }
);

pub const SET_OPTS: [&str; 7] = [
    "completion_type",
    "edit_mode",
    "editor",
    "kubectl_binary",
    "terminal",
    "range_separator",
    "describe_include_events",
];

command!(
    SetCmd,
    "set",
    "Set click options. (See 'help completion' and 'help edit_mode' for more information",
    |clap: ClapCommand<'static>| {
        clap.arg(
            Arg::new("option")
                .help("The click option to set")
                .required(true)
                .index(1)
                .value_parser(SET_OPTS),
        )
        .arg(
            Arg::new("value")
                .help("The value to set the option to")
                .required(true)
                .index(2),
        )
        .after_help(
            "Note that if your value contains a -, you'll need to tell click it's not an option by
passing '--' before.

Example:
  # Set the range_separator (needs the '--' after set since the value contains a -)
  set -- range_separator \"---- {name} [{namespace}] ----\"

  # set edit_mode
  set edit_mode emacs",
        )
    },
    vec!["set"],
    vec![&completer::setoptions_values_completer],
    no_named_complete!(),
    |matches, env, writer| {
        let option = matches
            .get_one::<String>("option")
            .map(|s| s.as_str())
            .unwrap(); // safe, required
        let value = matches
            .get_one::<String>("value")
            .map(|s| s.as_str())
            .unwrap(); // safe, required
        let mut failed = false;
        match option {
            "completion_type" => match value {
                "circular" => env.set_completion_type(config::CompletionType::Circular),
                "list" => env.set_completion_type(config::CompletionType::List),
                _ => {
                    clickwriteln!(
                        writer,
                        "Invalid completion type.  Possible values are: [circular, list]"
                    );
                    failed = true;
                }
            },
            "edit_mode" => match value {
                "vi" => env.set_edit_mode(config::EditMode::Vi),
                "emacs" => env.set_edit_mode(config::EditMode::Emacs),
                _ => {
                    clickwriteln!(
                        writer,
                        "Invalid edit_mode.  Possible values are: [emacs, vi]"
                    );
                    failed = true;
                }
            },
            "editor" => {
                env.set_editor(Some(value));
            }
            "terminal" => {
                env.set_terminal(Some(value));
            }
            "kubectl_binary" => {
                env.set_kubectl_binary(Some(value));
            }
            "range_separator" => {
                env.click_config.range_separator = value.to_string();
            }
            "describe_include_events" => match value.parse() {
                Ok(b) => env.click_config.describe_include_events = b,
                Err(_) => {
                    clickwriteln!(
                        writer,
                        "describe_include_events must be set to 'true' or 'false'"
                    );
                    failed = true;
                }
            },
            _ => {
                // this shouldn't happen
                writeln!(stderr(), "Invalid option").unwrap_or(());
                failed = true;
            }
        }
        if !failed {
            clickwriteln!(writer, "Set {} to '{}'", option, value);
        }
        Ok(())
    }
);

pub const UNSET_OPTS: [&str; 4] = ["editor", "kubectl_binary", "terminal", "range_separator"];

command!(
    UnSetCmd,
    "unset",
    "Unset a click option. This returns to option to its default value.",
    |clap: ClapCommand<'static>| {
        clap.arg(
            Arg::new("option")
                .help("The click option to unset")
                .required(true)
                .index(1)
                .value_parser(UNSET_OPTS),
        )
    },
    vec!["unset"],
    vec![&completer::unsetoptions_values_completer],
    no_named_complete!(),
    |matches, env, writer| {
        let option = matches
            .get_one::<String>("option")
            .map(|s| s.as_str())
            .unwrap(); // safe, required
        let mut failed = false;
        match option {
            "editor" => {
                env.set_editor(None);
            }
            "terminal" => {
                env.set_terminal(None);
            }
            "kubectl_binary" => {
                env.set_kubectl_binary(None);
            }
            "range_separator" => {
                env.click_config.range_separator = crate::config::default_range_sep();
            }
            _ => {
                // this shouldn't happen
                writeln!(stderr(), "Invalid option").unwrap_or(());
                failed = true;
            }
        }
        if !failed {
            clickwriteln!(writer, "Unset {}", option);
        }
        Ok(())
    }
);

command!(
    UtcCmd,
    "utc",
    "Print current time in UTC",
    identity,
    vec!["utc"],
    noop_complete!(),
    no_named_complete!(),
    |_, _, writer| {
        clickwriteln!(writer, "{}", Utc::now());
        Ok(())
    }
);