1use crate::error::KubeConfigError;
4use crate::models::ClusterContext;
5use kube::Config;
6
7pub async fn load_context() -> Result<ClusterContext, KubeConfigError> {
9 let config = Config::infer()
11 .await
12 .map_err(|e| KubeConfigError::InvalidConfig {
13 reason: format!("Failed to load kubeconfig: {}", e),
14 })?;
15
16 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 Ok(ClusterContext::new(
26 context_name.clone(),
27 context_name, cluster_server,
29 namespace,
30 "current-user".to_string(), ))
32}
33
34pub fn load_context_sync() -> Result<ClusterContext, KubeConfigError> {
36 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 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 let _ = result;
61 }
62 }
63
64 #[test]
65 fn test_load_context_sync() {
66 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 let _ = result;
77 }
78 }
79}