Skip to content

Commit

Permalink
Merge pull request #200 from nicklan/specify-kubectl-path
Browse files Browse the repository at this point in the history
  • Loading branch information
nicklan authored May 30, 2022
2 parents 0e65802 + 848d241 commit fdc7f85
Show file tree
Hide file tree
Showing 8 changed files with 137 additions and 18 deletions.
51 changes: 51 additions & 0 deletions src/command/click.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ pub const SET_OPTS: &[&str] = &[
"completion_type",
"edit_mode",
"editor",
"kubectl_binary",
"terminal",
"range_separator",
"describe_include_events",
Expand Down Expand Up @@ -240,6 +241,9 @@ Example:
"terminal" => {
env.set_terminal(Some(value));
}
"kubectl_binary" => {
env.set_kubectl_binary(Some(value));
}
"range_separator" => {
env.click_config.range_separator = value.to_string();
}
Expand All @@ -266,6 +270,53 @@ Example:
}
);

pub const UNSET_OPTS: &[&str] = &["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)
.possible_values(UNSET_OPTS),
)
},
vec!["unset"],
vec![&completer::unsetoptions_values_completer],
no_named_complete!(),
|matches, env, writer| {
let option = matches.value_of("option").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
write!(stderr(), "Invalid option\n").unwrap_or(());
failed = true;
}
}
if !failed {
clickwriteln!(writer, "Unset {}", option);
}
Ok(())
}
);

command!(
UtcCmd,
"utc",
Expand Down
24 changes: 19 additions & 5 deletions src/command/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ fn do_exec(
writer: &mut ClickWriter,
) -> Result<(), ClickError> {
let ns = pod.namespace.as_ref().unwrap();
let kubectl_binary = env
.click_config
.kubectl_binary
.as_deref()
.unwrap_or("kubectl");
if do_terminal {
let terminal = if let Some(t) = term_opt {
t
Expand All @@ -57,7 +62,7 @@ fn do_exec(
};
let mut targs: Vec<&str> = terminal.split_whitespace().collect();
let mut kubectl_args = vec![
"kubectl",
kubectl_binary,
"--namespace",
ns,
"--context",
Expand All @@ -77,7 +82,7 @@ fn do_exec(
duct::cmd(targs[0], &targs[1..]).start()?;
Ok(())
} else {
let mut command = Command::new("kubectl");
let mut command = Command::new(kubectl_binary);
command
.arg("--namespace")
.arg(ns)
Expand All @@ -103,9 +108,18 @@ fn do_exec(
}
Err(e) => {
if let io::ErrorKind::NotFound = e.kind() {
Err(ClickError::CommandError(
"Could not find kubectl binary. Is it in your PATH?".to_string(),
))
let msg = if kubectl_binary.starts_with('/') {
format!(
"Could not find kubectl binary: '{}'. Does it exist?",
kubectl_binary
)
} else {
format!(
"Could not find kubectl binary: '{}'. Is it in your PATH?",
kubectl_binary
)
};
Err(ClickError::CommandError(msg))
} else {
Err(ClickError::Io(e))
}
Expand Down
27 changes: 21 additions & 6 deletions src/command/portforwards.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,12 @@ Examples:
return Err(ClickError::CommandError("No active context".to_string()));
};

match Command::new("kubectl")
let kubectl_binary = env
.click_config
.kubectl_binary
.as_deref()
.unwrap_or("kubectl");
match Command::new(kubectl_binary)
.arg("--namespace")
.arg(ns)
.arg("--context")
Expand Down Expand Up @@ -151,11 +156,21 @@ Examples:
}
Err(e) => match e.kind() {
io::ErrorKind::NotFound => {
writeln!(
stderr(),
"Could not find kubectl binary. Is it in your PATH?"
)
.unwrap_or(());
if kubectl_binary.starts_with('/') {
writeln!(
stderr(),
"Could not find kubectl binary '{}'. Does it exist?",
kubectl_binary
)
.unwrap_or(());
} else {
writeln!(
stderr(),
"Could not find kubectl binary '{}'. Is it in your PATH.",
kubectl_binary
)
.unwrap_or(());
}
}
_ => {
write!(
Expand Down
1 change: 1 addition & 0 deletions src/command_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ impl CommandProcessor {
Box::new(crate::command::click::Quit::new()),
Box::new(crate::command::click::Range::new()),
Box::new(crate::command::click::SetCmd::new()),
Box::new(crate::command::click::UnSetCmd::new()),
Box::new(crate::command::click::UtcCmd::new()),
Box::new(crate::command::configmaps::ConfigMaps::new()),
Box::new(crate::command::copy::Copy::new()),
Expand Down
4 changes: 4 additions & 0 deletions src/completer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,10 @@ macro_rules! possible_values_completer {
}

possible_values_completer!(setoptions_values_completer, crate::command::click::SET_OPTS);
possible_values_completer!(
unsetoptions_values_completer,
crate::command::click::UNSET_OPTS
);

possible_values_completer!(
portforwardaction_values_completer,
Expand Down
6 changes: 5 additions & 1 deletion src/config/click.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl From<&CompletionType> for String {
}
}

fn default_range_sep() -> String {
pub fn default_range_sep() -> String {
"--- {name} ---".to_string()
}

Expand All @@ -112,6 +112,7 @@ pub struct ClickConfig {
pub context: Option<String>,
pub editor: Option<String>,
pub terminal: Option<String>,
pub kubectl_binary: Option<String>,
#[serde(default = "EditMode::default")]
pub editmode: EditMode,
#[serde(default = "CompletionType::default")]
Expand All @@ -137,6 +138,7 @@ impl Default for ClickConfig {
context: None,
editor: None,
terminal: None,
kubectl_binary: None,
editmode: EditMode::default(),
completiontype: CompletionType::default(),
aliases: vec![],
Expand Down Expand Up @@ -196,6 +198,7 @@ pub mod tests {
namespace: ns
context: ctx
editor: emacs
kubectl_binary: /opt/bin/kubectl
terminal: alacritty -e
editmode: Vi
completiontype: List
Expand All @@ -216,6 +219,7 @@ aliases:
assert_eq!(config.context, Some("ctx".to_owned()));
assert_eq!(config.editor, Some("emacs".to_owned()));
assert_eq!(config.terminal, Some("alacritty -e".to_owned()));
assert_eq!(config.kubectl_binary, Some("/opt/bin/kubectl".to_owned()));
assert_eq!(config.editmode, EditMode::Vi);
assert_eq!(config.completiontype, CompletionType::List);
assert_eq!(config.aliases.len(), 1);
Expand Down
1 change: 1 addition & 0 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ mod click;
mod kube;
mod kubefile;

pub use self::click::default_range_sep;
pub use self::click::Alias;
pub use self::click::ClickConfig;
pub use self::click::CompletionType;
Expand Down
41 changes: 35 additions & 6 deletions src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,10 @@ impl Env {
self.click_config.terminal = terminal.map(|s| s.to_string());
}

pub fn set_kubectl_binary(&mut self, kubectl_binary: Option<&str>) {
self.click_config.kubectl_binary = kubectl_binary.map(|s| s.to_string());
}

pub fn set_completion_type(&mut self, comptype: config::CompletionType) {
self.click_config.completiontype = comptype;
self.need_new_editor = true;
Expand Down Expand Up @@ -473,6 +477,31 @@ impl Env {

impl fmt::Display for Env {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let kubectl_binary = self
.click_config
.kubectl_binary
.as_deref()
.unwrap_or("kubectl");
let kubectl_path = std::process::Command::new("which")
.arg(kubectl_binary)
.output()
.map(|output| {
if output.status.success() {
std::str::from_utf8(&output.stdout)
.unwrap_or("Failed to parse 'which' output")
.to_string()
} else if kubectl_binary.starts_with('/') {
format!("{} not found. Does it exist?", kubectl_binary)
} else {
format!("{} not found. Is it in your PATH?", kubectl_binary)
}
})
.unwrap_or_else(|e| {
format!(
"Error searching for kubectl_binary (which is set to {}): {}",
kubectl_binary, e
)
});
write!(
f,
"Env {{
Expand All @@ -483,6 +512,7 @@ impl fmt::Display for Env {
Edit Mode: {}
Editor: {}
Terminal: {}
kubectl Binary: {}
Range Separator: {}
Describe Shows Events: {}
}}",
Expand All @@ -504,17 +534,16 @@ impl fmt::Display for Env {
self.styles.config_val(
self.click_config
.editor
.as_ref()
.unwrap_or(&"<unset, will use $EDITOR>".to_owned())
.as_str()
.as_deref()
.unwrap_or("<unset, will use $EDITOR>")
),
self.styles.config_val(
self.click_config
.terminal
.as_ref()
.unwrap_or(&"<unset, will use xterm>".to_owned())
.as_str()
.as_deref()
.unwrap_or("<unset, will use xterm>")
),
self.styles.config_val(&kubectl_path),
self.styles
.config_val(self.click_config.range_separator.as_str()),
self.styles.config_val(
Expand Down

0 comments on commit fdc7f85

Please sign in to comment.