use crate::error::KubeConfigError;
use crate::models::ClusterContext;
use kube::Config;
pub async fn load_context() -> Result<ClusterContext, KubeConfigError> {
let config = Config::infer()
.await
.map_err(|e| KubeConfigError::InvalidConfig {
reason: format!("Failed to load kubeconfig: {}", e),
})?;
let context_name = std::env::var("KUBECTL_CONTEXT")
.or_else(|_| std::env::var("KUBECONFIG_CONTEXT"))
.unwrap_or_else(|_| "current-context".to_string());
let cluster_server = config.cluster_url.to_string();
let namespace = Some(config.default_namespace.clone());
Ok(ClusterContext::new(
context_name.clone(),
context_name, cluster_server,
namespace,
"current-user".to_string(), ))
}
pub fn load_context_sync() -> Result<ClusterContext, KubeConfigError> {
let runtime = tokio::runtime::Runtime::new()
.map_err(|e| KubeConfigError::Other(format!("Failed to create runtime: {}", e)))?;
runtime.block_on(load_context())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_load_context() {
if std::env::var("KUBECONFIG").is_ok()
|| std::path::Path::new(&format!(
"{}/.kube/config",
std::env::var("HOME").unwrap_or_default()
))
.exists()
{
let result = load_context().await;
let _ = result;
}
}
#[test]
fn test_load_context_sync() {
if std::env::var("KUBECONFIG").is_ok()
|| std::path::Path::new(&format!(
"{}/.kube/config",
std::env::var("HOME").unwrap_or_default()
))
.exists()
{
let result = load_context_sync();
let _ = result;
}
}
}