Skip to main content

seal/k8s/
context.rs

1//! Kubernetes cluster context detection and display
2
3use crate::error::KubeConfigError;
4use crate::models::ClusterContext;
5use kube::Config;
6
7/// Load the current Kubernetes context from kubeconfig
8pub async fn load_context() -> Result<ClusterContext, KubeConfigError> {
9    // Load kubeconfig using kube-rs
10    let config = Config::infer()
11        .await
12        .map_err(|e| KubeConfigError::InvalidConfig {
13            reason: format!("Failed to load kubeconfig: {}", e),
14        })?;
15
16    // Extract context information
17    let context_name = std::env::var("KUBECTL_CONTEXT")
18        .or_else(|_| std::env::var("KUBECONFIG_CONTEXT"))
19        .unwrap_or_else(|_| "current-context".to_string());
20
21    let cluster_server = config.cluster_url.to_string();
22    let namespace = Some(config.default_namespace.clone());
23
24    // Create ClusterContext
25    Ok(ClusterContext::new(
26        context_name.clone(),
27        context_name, // kube-rs doesn't expose cluster name separately
28        cluster_server,
29        namespace,
30        "current-user".to_string(), // kube-rs doesn't expose user info directly
31    ))
32}
33
34/// Load context synchronously (blocking wrapper for async function)
35pub fn load_context_sync() -> Result<ClusterContext, KubeConfigError> {
36    // Create a tokio runtime for this blocking call
37    let runtime = tokio::runtime::Runtime::new()
38        .map_err(|e| KubeConfigError::Other(format!("Failed to create runtime: {}", e)))?;
39
40    runtime.block_on(load_context())
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[tokio::test]
48    async fn test_load_context() {
49        // This test will only pass if a valid kubeconfig exists
50        // In CI without kubeconfig, this should be skipped
51        if std::env::var("KUBECONFIG").is_ok()
52            || std::path::Path::new(&format!(
53                "{}/.kube/config",
54                std::env::var("HOME").unwrap_or_default()
55            ))
56            .exists()
57        {
58            let result = load_context().await;
59            // Just verify the function doesn't panic
60            let _ = result;
61        }
62    }
63
64    #[test]
65    fn test_load_context_sync() {
66        // This test will only pass if a valid kubeconfig exists
67        if std::env::var("KUBECONFIG").is_ok()
68            || std::path::Path::new(&format!(
69                "{}/.kube/config",
70                std::env::var("HOME").unwrap_or_default()
71            ))
72            .exists()
73        {
74            let result = load_context_sync();
75            // Just verify the function doesn't panic
76            let _ = result;
77        }
78    }
79}