1
0
mirror of https://github.com/Llewellynvdm/starship.git synced 2024-12-01 01:04:00 +00:00

feat(kubernetes): implements regex matching for context aliases (#2883)

This commit is contained in:
David Herberth 2021-08-03 23:56:28 +02:00 committed by GitHub
parent 43a86f1a29
commit cd6fc9cea0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 114 additions and 16 deletions

View File

@ -1723,6 +1723,33 @@ format = 'on [⛵ $context \($namespace\)](dimmed green) '
disabled = false disabled = false
[kubernetes.context_aliases] [kubernetes.context_aliases]
"dev.local.cluster.k8s" = "dev" "dev.local.cluster.k8s" = "dev"
".*/openshift-cluster/.*" = "openshift"
"gke_.*_(?P<cluster>[\\w-]+)" = "gke-$cluster"
```
#### Regex Matching
Additional to simple aliasing, `context_aliases` also supports
extended matching and renaming using regular expressions.
The regular expression must match on the entire kube context,
capture groups can be referenced using `$name` and `$N` in the replacement.
This is more explained in the [regex crate](https://docs.rs/regex/1.5.4/regex/struct.Regex.html#method.replace) documentation.
Long and automatically generated cluster names can be identified
and shortened using regular expressions:
```toml
[kubernetes.context_aliases]
# OpenShift contexts carry the namespace and user in the kube context: `namespace/name/user`:
".*/openshift-cluster/.*" = "openshift"
# Or better, to rename every OpenShift cluster at once:
".*/(?P<cluster>[\\w-]+)/.*" = "$cluster"
# Contexts from GKE, AWS and other cloud providers usually carry additional information, like the region/zone.
# The following entry matches on the GKE format (`gke_projectname_zone_cluster-name`)
# and renames every matching kube context into a more readable format (`gke-cluster-name`):
"gke_.*_(?P<cluster>[\\w-]+)" = "gke-$cluster"
``` ```
## Line Break ## Line Break

View File

@ -1,5 +1,6 @@
use yaml_rust::YamlLoader; use yaml_rust::YamlLoader;
use std::borrow::Cow;
use std::env; use std::env;
use std::path; use std::path;
@ -49,6 +50,24 @@ fn get_kube_ns(filename: path::PathBuf, current_ctx: String) -> Option<String> {
Some(ns.to_owned()) Some(ns.to_owned())
} }
fn get_kube_context_name<'a>(config: &'a KubernetesConfig, kube_ctx: &'a str) -> Cow<'a, str> {
if let Some(val) = config.context_aliases.get(kube_ctx) {
return Cow::Borrowed(val);
}
config
.context_aliases
.iter()
.find_map(|(k, v)| {
let re = regex::Regex::new(&format!("^{}$", k)).ok()?;
match re.replace(kube_ctx, *v) {
Cow::Owned(replaced) => Some(Cow::Owned(replaced)),
_ => None,
}
})
.unwrap_or(Cow::Borrowed(kube_ctx))
}
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> { pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("kubernetes"); let mut module = context.new_module("kubernetes");
let config: KubernetesConfig = KubernetesConfig::try_load(module.config); let config: KubernetesConfig = KubernetesConfig::try_load(module.config);
@ -81,11 +100,8 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
_ => None, _ => None,
}) })
.map(|variable| match variable { .map(|variable| match variable {
"context" => match config.context_aliases.get(&kube_ctx) { "context" => Some(Ok(get_kube_context_name(&config, &kube_ctx))),
None => Some(Ok(kube_ctx.as_str())), "namespace" => kube_ns.as_ref().map(|s| Ok(Cow::Borrowed(s.as_str()))),
Some(&alias) => Some(Ok(alias)),
},
"namespace" => kube_ns.as_ref().map(|s| Ok(s.as_str())),
_ => None, _ => None,
}) })
.parse(None) .parse(None)
@ -144,41 +160,96 @@ users: []
dir.close() dir.close()
} }
#[test] fn base_test_ctx_alias(ctx_name: &str, config: toml::Value, expected: &str) -> io::Result<()> {
fn test_ctx_alias() -> io::Result<()> {
let dir = tempfile::tempdir()?; let dir = tempfile::tempdir()?;
let filename = dir.path().join("config"); let filename = dir.path().join("config");
let mut file = File::create(&filename)?; let mut file = File::create(&filename)?;
file.write_all( file.write_all(
b" format!(
"
apiVersion: v1 apiVersion: v1
clusters: [] clusters: []
contexts: [] contexts: []
current-context: test_context current-context: {}
kind: Config kind: Config
preferences: {} preferences: {{}}
users: [] users: []
", ",
ctx_name
)
.as_bytes(),
)?; )?;
file.sync_all()?; file.sync_all()?;
let actual = ModuleRenderer::new("kubernetes") let actual = ModuleRenderer::new("kubernetes")
.path(dir.path()) .path(dir.path())
.env("KUBECONFIG", filename.to_string_lossy().as_ref()) .env("KUBECONFIG", filename.to_string_lossy().as_ref())
.config(toml::toml! { .config(config)
.collect();
let expected = Some(format!("{} in ", Color::Cyan.bold().paint(expected)));
assert_eq!(expected, actual);
dir.close()
}
#[test]
fn test_ctx_alias_simple() -> io::Result<()> {
base_test_ctx_alias(
"test_context",
toml::toml! {
[kubernetes] [kubernetes]
disabled = false disabled = false
[kubernetes.context_aliases] [kubernetes.context_aliases]
"test_context" = "test_alias" "test_context" = "test_alias"
}) ".*" = "literal match has precedence"
.collect(); },
"☸ test_alias",
)
}
let expected = Some(format!("{} in ", Color::Cyan.bold().paint("☸ test_alias"))); #[test]
assert_eq!(expected, actual); fn test_ctx_alias_regex() -> io::Result<()> {
base_test_ctx_alias(
"namespace/openshift-cluster/user",
toml::toml! {
[kubernetes]
disabled = false
[kubernetes.context_aliases]
".*/openshift-cluster/.*" = "test_alias"
},
"☸ test_alias",
)
}
dir.close() #[test]
fn test_ctx_alias_regex_replace() -> io::Result<()> {
base_test_ctx_alias(
"gke_infra-cluster-28cccff6_europe-west4_cluster-1",
toml::toml! {
[kubernetes]
disabled = false
[kubernetes.context_aliases]
"gke_.*_(?P<cluster>[\\w-]+)" = "example: $cluster"
},
"☸ example: cluster-1",
)
}
#[test]
fn test_ctx_alias_broken_regex() -> io::Result<()> {
base_test_ctx_alias(
"input",
toml::toml! {
[kubernetes]
disabled = false
[kubernetes.context_aliases]
"input[.*" = "this does not match"
},
"☸ input",
)
} }
#[test] #[test]