|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/spf13/cobra" |
| 9 | + "k8s.io/client-go/tools/clientcmd" |
| 10 | + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" |
| 11 | +) |
| 12 | + |
| 13 | +// RangeCommand range subcommand for delete command |
| 14 | +type RangeCommand struct { |
| 15 | + BaseCommand |
| 16 | + matchMode string // support prefix, suffix, contains |
| 17 | + yes bool // skip confirmation prompt |
| 18 | +} |
| 19 | + |
| 20 | +// Init RangeCommand |
| 21 | +func (rc *RangeCommand) Init() { |
| 22 | + rc.command = &cobra.Command{ |
| 23 | + Use: "range", |
| 24 | + Short: "Delete contexts matching a pattern", |
| 25 | + Long: `Delete all contexts that match a specified pattern from the kubeconfig`, |
| 26 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 27 | + return rc.runRange(cmd, args) |
| 28 | + }, |
| 29 | + Example: rangeExample(), |
| 30 | + } |
| 31 | + |
| 32 | + rc.command.Flags().StringVarP(&rc.matchMode, "mode", "", "prefix", "Match mode: prefix, suffix, or contains") |
| 33 | + rc.command.Flags().BoolVarP(&rc.yes, "yes", "y", false, "Skip confirmation prompt") |
| 34 | + rc.AddCommands(&DocsCommand{}) |
| 35 | +} |
| 36 | + |
| 37 | +func (rc *RangeCommand) runRange(command *cobra.Command, args []string) error { |
| 38 | + if len(args) == 0 { |
| 39 | + return errors.New("no pattern specified") |
| 40 | + } |
| 41 | + |
| 42 | + config, err := clientcmd.LoadFromFile(cfgFile) |
| 43 | + if err != nil { |
| 44 | + return fmt.Errorf("failed to load kubeconfig file %q: %w", cfgFile, err) |
| 45 | + } |
| 46 | + |
| 47 | + // Select contexts to delete |
| 48 | + needDeleteContexts, err := matchContexts(config.Contexts, args[0], rc.matchMode) |
| 49 | + if err != nil { |
| 50 | + return err |
| 51 | + } |
| 52 | + |
| 53 | + if len(needDeleteContexts) == 0 { |
| 54 | + return errors.New("no contexts matched the specified pattern") |
| 55 | + } |
| 56 | + |
| 57 | + // Confirm delete |
| 58 | + fmt.Printf("Found %d contexts matching %s mode with pattern %q:\n", len(needDeleteContexts), rc.matchMode, args[0]) |
| 59 | + for _, ctx := range needDeleteContexts { |
| 60 | + fmt.Printf(" - %s\n", ctx) |
| 61 | + } |
| 62 | + |
| 63 | + // Skip confirmation if -y/--yes flag is set |
| 64 | + if !rc.yes { |
| 65 | + if !strings.EqualFold(BoolUI(fmt.Sprintf("Are you sure you want to delete these %d contexts?", len(needDeleteContexts))), "True") { |
| 66 | + return errors.New("range delete operation cancelled") |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + if err := rangeDeleteContexts(needDeleteContexts, config); err != nil { |
| 71 | + return err |
| 72 | + } |
| 73 | + |
| 74 | + if err := WriteConfig(true, cfgFile, config); err != nil { |
| 75 | + return fmt.Errorf("failed to write kubeconfig file %q: %w", cfgFile, err) |
| 76 | + } |
| 77 | + |
| 78 | + return nil |
| 79 | +} |
| 80 | + |
| 81 | +// matchContexts selects contexts that match the given pattern and mode. |
| 82 | +func matchContexts(contexts map[string]*clientcmdapi.Context, pattern, matchMode string) ([]string, error) { |
| 83 | + if pattern == "" { |
| 84 | + return nil, errors.New("pattern cannot be empty") |
| 85 | + } |
| 86 | + |
| 87 | + validModes := map[string]bool{"prefix": true, "suffix": true, "contains": true} |
| 88 | + if !validModes[matchMode] { |
| 89 | + return nil, fmt.Errorf("invalid match mode: %s, must be one of: prefix, suffix, contains", matchMode) |
| 90 | + } |
| 91 | + |
| 92 | + var matches []string |
| 93 | + for contextName := range contexts { |
| 94 | + var matched bool |
| 95 | + switch matchMode { |
| 96 | + case "prefix": |
| 97 | + matched = strings.HasPrefix(contextName, pattern) |
| 98 | + case "suffix": |
| 99 | + matched = strings.HasSuffix(contextName, pattern) |
| 100 | + case "contains": |
| 101 | + matched = strings.Contains(contextName, pattern) |
| 102 | + } |
| 103 | + if matched { |
| 104 | + matches = append(matches, contextName) |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + return matches, nil |
| 109 | +} |
| 110 | + |
| 111 | +// rangeDeleteContexts deletes the specified contexts and their associated clusters and auth infos if not used elsewhere. |
| 112 | +func rangeDeleteContexts(needDeleteContexts []string, config *clientcmdapi.Config) error { |
| 113 | + for _, ctx := range needDeleteContexts { |
| 114 | + if _, exists := config.Contexts[ctx]; !exists { |
| 115 | + return fmt.Errorf("context %q does not exist", ctx) |
| 116 | + } |
| 117 | + |
| 118 | + delContext := config.Contexts[ctx] |
| 119 | + isClusterNameExist, isUserNameExist := checkClusterAndUserNameExceptContextToDelete(config, delContext) |
| 120 | + |
| 121 | + if !isUserNameExist { |
| 122 | + delete(config.AuthInfos, delContext.AuthInfo) |
| 123 | + } |
| 124 | + if !isClusterNameExist { |
| 125 | + delete(config.Clusters, delContext.Cluster) |
| 126 | + } |
| 127 | + delete(config.Contexts, ctx) |
| 128 | + |
| 129 | + fmt.Printf("Context Delete:「%s」\n", ctx) |
| 130 | + } |
| 131 | + |
| 132 | + return nil |
| 133 | +} |
| 134 | + |
| 135 | +func rangeExample() string { |
| 136 | + return ` |
| 137 | +# Delete all contexts with prefix "dev-" |
| 138 | +kubecm delete range dev- |
| 139 | +or |
| 140 | +kubecm delete range --mode prefix dev- |
| 141 | +
|
| 142 | +# Delete all contexts with suffix "prod" |
| 143 | +kubecm delete range --mode suffix prod |
| 144 | +
|
| 145 | +# Delete all contexts containing "staging" |
| 146 | +kubecm delete range --mode contains staging |
| 147 | +
|
| 148 | +# Force delete all contexts with prefix "dev-" (skip confirmation) |
| 149 | +kubecm delete range dev- -y |
| 150 | +` |
| 151 | +} |
0 commit comments