Skip to content

Commit

Permalink
Merge pull request #51 from nicmr/main
Browse files Browse the repository at this point in the history
Handle and print error instead of panic when passing nonexistent context
  • Loading branch information
Ramilito authored Dec 11, 2023
2 parents 2af59ce + dd1a9f3 commit 97d68e0
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 15 deletions.
26 changes: 23 additions & 3 deletions src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::model::KubeConfig;
use crate::config;

use core::fmt;
use std::process;
use std::{
io::Cursor,
Expand Down Expand Up @@ -91,7 +92,26 @@ pub fn set_namespace(ctx: &str, selection: &str, temp_dir: &str, config: &KubeCo
config::write(choice.unwrap(), Some(selection), temp_dir)
}

pub fn set_context(ctx: &str, temp_dir: &str, config: &KubeConfig) {
let choice = config.contexts.iter().find(|x| x.name == ctx);
config::write(choice.unwrap(), None, temp_dir);
pub fn set_context(ctx: &str, temp_dir: &str, config: &KubeConfig) -> Result<(), SetContextError> {
if let Some(choice) = config.contexts.iter().find(|x| x.name == ctx) {
config::write(choice, None, temp_dir);
Ok(())
} else {
Err(SetContextError::ContextNotFound{ctx: ctx.to_owned()})
}
}

#[derive(Debug, Clone)]
pub enum SetContextError {
ContextNotFound {
ctx : String
},
}

impl fmt::Display for SetContextError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SetContextError::ContextNotFound{ctx} => write!(f, "no context exists with the name: \"{}\"", ctx),
}
}
}
36 changes: 24 additions & 12 deletions src/modes.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use crate::{commands, config, Cli, DEST, KUBECONFIG};
use std::process;

use crate::{commands::{self}, config, Cli, DEST, KUBECONFIG};

fn selection(value: Option<String>, callback: fn() -> String) -> String {
match value {
Expand Down Expand Up @@ -28,9 +30,13 @@ pub fn default_context(args: Cli) {
};

commands::set_default_context(&ctx);
commands::set_context(&ctx, &DEST, &config);

println!("{}", KUBECONFIG.as_str());
match commands::set_context(&ctx, &DEST, &config) {
Ok(()) => println!("{}", KUBECONFIG.as_str()),
Err(e) => {
eprintln!("error: {}", e);
process::exit(1);
}
}
}

pub fn context(args: Cli) {
Expand All @@ -53,14 +59,20 @@ pub fn context(args: Cli) {
Some(x) => x.trim().to_string(),
};

commands::set_context(&ctx, &DEST, &config);

println!(
"{}/{}:{}",
&DEST.as_str(),
str::replace(&ctx, ":", "_"),
KUBECONFIG.to_string()
);
match commands::set_context(&ctx, &DEST, &config) {
Ok(()) => {
println!(
"{}/{}:{}",
&DEST.as_str(),
str::replace(&ctx, ":", "_"),
KUBECONFIG.to_string()
);
},
Err(e) => {
eprintln!("error: {}", e);
process::exit(1);
}
}
}

pub fn namespace(args: Cli) {
Expand Down

0 comments on commit 97d68e0

Please sign in to comment.