11const path = require ( 'path' ) ;
2+ const fs = require ( 'fs' ) ;
23const { KubeConfig, Client } = require ( 'kubernetes-client' ) ;
34const Request = require ( 'kubernetes-client/backends/request' ) ;
45const _ = require ( 'lodash' ) ;
6+ const { homedir } = require ( 'os' ) ;
7+
8+ const _getKubeConfig = ( kubeconfigPath ) => {
9+ const kc = new KubeConfig ( ) ;
10+ const kubePath = kubeconfigPath || process . env . KUBECONFIG || path . join ( homedir ( ) , '.kube' , 'config' ) ;
11+ if ( fs . existsSync ( kubePath ) ) {
12+ kc . loadFromFile ( kubePath ) ;
13+ } else {
14+ kc . loadFromCluster ( ) ;
15+ }
16+
17+ return kc ;
18+ }
519
620const getKubeContext = ( kubeconfigPath ) => {
7- // eslint-disable-next-line global-require
8- const homedir = require ( 'os' ) . homedir ( ) ;
9- const kubePath = kubeconfigPath || process . env . KUBECONFIG || path . join ( homedir , '.kube' , 'config' ) ;
10- const kubeconfig = new KubeConfig ( ) ;
11- kubeconfig . loadFromFile ( kubePath ) ;
21+ const kubeconfig = _getKubeConfig ( kubeconfigPath ) ;
1222 return kubeconfig . currentContext ;
1323} ;
1424const getAllKubeContexts = ( kubeconfigPath ) => {
15- // eslint-disable-next-line global-require
16- const homedir = require ( 'os' ) . homedir ( ) ;
17- const kubePath = kubeconfigPath || process . env . KUBECONFIG || path . join ( homedir , '.kube' , 'config' ) ;
18- const kubeconfig = new KubeConfig ( ) ;
19- kubeconfig . loadFromFile ( kubePath ) ;
25+ const kubeconfig = _getKubeConfig ( kubeconfigPath ) ;
2026 const { contexts } = kubeconfig ;
2127 if ( contexts ) {
2228 return contexts . reduce ( ( acc , curr ) => {
@@ -26,11 +32,7 @@ const getAllKubeContexts = (kubeconfigPath) => {
2632 }
2733} ;
2834const getAllNamespaces = async ( kubeconfigPath , kubeContextName ) => {
29- // eslint-disable-next-line global-require
30- const homedir = require ( 'os' ) . homedir ( ) ;
31- const kubePath = kubeconfigPath || process . env . KUBECONFIG || path . join ( homedir , '.kube' , 'config' ) ;
32- const kubeconfig = new KubeConfig ( ) ;
33- kubeconfig . loadFromFile ( kubePath ) ;
35+ const kubeconfig = _getKubeConfig ( kubeconfigPath ) ;
3436 kubeconfig . setCurrentContext ( kubeContextName ) ;
3537 const backend = new Request ( { kubeconfig } ) ;
3638 const client = new Client ( { backend, version : 1.13 } ) ;
0 commit comments