import * as settings from './createClusterSettings' ; import { promptClusterSettings , createClusterInteractive } from './createCluster' ; import { deleteClusterByName } from './deleteCluster' ; import { tryResolveClusterNode } from './utils' ; import * as k3d from '../k3d/k3d' ; import * as model from '../k3d/k3d.objectmodel' ; import * as config from '../utils/config' ; import { shell } from '../utils/shell' ; import * as kubectl from '../utils/kubectl' ; export async function onReplaceCluster ( target ? ) { const defaultSettings = settings . forNewCluster ( settings . getDefaultClusterSettings ( ) ) ; const providedSettings = await promptClusterSettings ( defaultSettings ) ; if ( providedSettings . cancelled ) { return ; } return replaceCluster ( providedSettings . value , target ) ; } export async function onReplaceClusterLast ( target ? ) { const lastSettings = settings . forNewCluster ( settings . getLastClusterSettings ( ) ) ; return replaceCluster ( lastSettings , target ) ; } export async function replaceCluster ( createSettings , target ? ) { let actions = [ ] ; const promisedClusters = await k3d . getClusters ( shell ) ; let clustersByCreation = [ ] ; if ( promisedClusters . succeeded && promisedClusters . result . length > 0 ) { clustersByCreation = promisedClusters . result . orderBy ( ( cluster ) => cluster . created ) ; } let deleteName = "" ; const currentCluster = await k3d . getCurrentCluster ( ) ; const selectedCluster = await tryResolveClusterNode ( target ) ; if ( selectedCluster !== undefined ) { deleteName = selectedCluster . clusterName ; } else if ( currentCluster . succeeded ) { deleteName = currentCluster . result ; } else if ( clustersByCreation . length > 0 ) { deleteName = clustersByCreation [ 0 ] . name ; } if ( deleteName !== "" ) { actions . push ( deleteClusterByName ( deleteName , false ) ) ; } let switchContext = true ; const behaviour = config . getK3DReplaceContext ( ) ; if ( behaviour && ( behaviour === config . ReplaceContext . OldestCluster ) && clustersByCreation . length > 1 ) { const remainingClusters = clustersByCreation . filter ( ( cluster ) => cluster . name !== deleteName ) ; if ( remainingClusters . length > 0 ) { const newContext = kubectl . getContextForCluster ( remainingClusters [ 0 ] . name ) ; actions . push ( kubectl . setContext ( newContext ) ) ; switchContext = false ; } } actions . push ( createClusterInteractive ( createSettings , switchContext ) ) ; if ( target ) { await Promise . all ( actions ) ; return ; } await Promise . all ( [ actions ] ) ; }