<commit_before>/*
Copyright 2016 The Kubernetes Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cmd

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"

	"github.com/docker/machine/libmachine/mcnerror"
	"github.com/golang/glog"
	"github.com/mitchellh/go-ps"
	"github.com/pkg/errors"

	"github.com/docker/machine/libmachine"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	cmdcfg "k8s.io/minikube/cmd/minikube/cmd/config"
	"k8s.io/minikube/pkg/drivers/kic/oci"
	"k8s.io/minikube/pkg/minikube/cluster"
	"k8s.io/minikube/pkg/minikube/config"
	pkg_config "k8s.io/minikube/pkg/minikube/config"
	"k8s.io/minikube/pkg/minikube/constants"
	"k8s.io/minikube/pkg/minikube/cruntime"
	"k8s.io/minikube/pkg/minikube/driver"
	"k8s.io/minikube/pkg/minikube/exit"
	"k8s.io/minikube/pkg/minikube/kubeconfig"
	"k8s.io/minikube/pkg/minikube/localpath"
	"k8s.io/minikube/pkg/minikube/machine"
	"k8s.io/minikube/pkg/minikube/out"
)

var deleteAll bool
var purge bool

// deleteCmd represents the delete command
var deleteCmd = &cobra.Command{
	Use:   "delete",
	Short: "Deletes a local kubernetes cluster",
	Long: `Deletes a local kubernetes cluster. This command deletes the VM, and removes all
associated files.`,
	Run: runDelete,
}

type typeOfError int

const (
	// Fatal is a type of DeletionError
	Fatal typeOfError = 0
	// MissingProfile is a type of DeletionError
	MissingProfile typeOfError = 1
	// MissingCluster is a type of DeletionError
	MissingCluster typeOfError = 2
)

// DeletionError can be returned from DeleteProfiles
type DeletionError struct {
	Err     error
	Errtype typeOfError
}

func (error DeletionError) Error() string {
	return error.Err.Error()
}

func init() {
	deleteCmd.Flags().BoolVar(&deleteAll, "all", false, "Set flag to delete all profiles")
	deleteCmd.Flags().BoolVar(&purge, "purge", false, "Set this flag to delete the '.minikube' folder from your user directory.")

	if err := viper.BindPFlags(deleteCmd.Flags()); err != nil {
		exit.WithError("unable to bind flags", err)
	}
	RootCmd.AddCommand(deleteCmd)
}

// runDelete handles the executes the flow of "minikube delete"
func runDelete(cmd *cobra.Command, args []string) {
	if len(args) > 0 {
		exit.UsageT("Usage: minikube delete")
	}
	profileFlag := viper.GetString(config.MachineProfile)

	validProfiles, invalidProfiles, err := pkg_config.ListProfiles()
	if err != nil {
		glog.Warningf("'error loading profiles in minikube home %q: %v", localpath.MiniPath(), err)
	}
	profilesToDelete := append(validProfiles, invalidProfiles...)
	// in the case user has more than 1 profile and runs --purge
	// to prevent abandoned VMs/containers, force user to run with delete --all
	if purge && len(profilesToDelete) > 1 && !deleteAll {
		out.ErrT(out.Notice, "Multiple minikube profiles were found - ")
		for _, p := range profilesToDelete {
			out.T(out.Notice, "    - {{.profile}}", out.V{"profile": p.Name})
		}
		exit.UsageT("Usage: minikube delete --all --purge")
	}

	if deleteAll {
		if profileFlag != constants.DefaultMachineName {
			exit.UsageT("usage: minikube delete --all")
		}
		delLabel := fmt.Sprintf("%s=%s", oci.CreatedByLabelKey, "true")
		errs := oci.DeleteContainersByLabel(oci.Docker, delLabel)
		if len(errs) > 0 { // it will error if there is no container to delete
			glog.Infof("error delete containers by label %q (might be okay): %+v", delLabel, err)
		}

		errs = oci.DeleteAllVolumesByLabel(oci.Docker, delLabel)
		if len(errs) > 0 { // it will not error if there is nothing to delete
			glog.Warningf("error delete volumes by label %q (might be okay): %+v", delLabel, errs)
		}

		errs = oci.PruneAllVolumesByLabel(oci.Docker, delLabel)
		if len(errs) > 0 { // it will not error if there is nothing to delete
			glog.Warningf("error pruning volumes by label %q (might be okay): %+v", delLabel, errs)
		}

		errs = DeleteProfiles(profilesToDelete)
		if len(errs) > 0 {
			HandleDeletionErrors(errs)
		} else {
			out.T(out.DeletingHost, "Successfully deleted all profiles")
		}
	} else {
		if len(args) > 0 {
			exit.UsageT("usage: minikube delete")
		}

		profileName := viper.GetString(pkg_config.MachineProfile)<commit_msg>Fix delete --all if using non default profile<commit_after>/*
Copyright 2016 The Kubernetes Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cmd

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"

	"github.com/docker/machine/libmachine/mcnerror"
	"github.com/golang/glog"
	"github.com/mitchellh/go-ps"
	"github.com/pkg/errors"

	"github.com/docker/machine/libmachine"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	cmdcfg "k8s.io/minikube/cmd/minikube/cmd/config"
	"k8s.io/minikube/pkg/drivers/kic/oci"
	"k8s.io/minikube/pkg/minikube/cluster"
	pkg_config "k8s.io/minikube/pkg/minikube/config"
	"k8s.io/minikube/pkg/minikube/constants"
	"k8s.io/minikube/pkg/minikube/cruntime"
	"k8s.io/minikube/pkg/minikube/driver"
	"k8s.io/minikube/pkg/minikube/exit"
	"k8s.io/minikube/pkg/minikube/kubeconfig"
	"k8s.io/minikube/pkg/minikube/localpath"
	"k8s.io/minikube/pkg/minikube/machine"
	"k8s.io/minikube/pkg/minikube/out"
)

var deleteAll bool
var purge bool

// deleteCmd represents the delete command
var deleteCmd = &cobra.Command{
	Use:   "delete",
	Short: "Deletes a local kubernetes cluster",
	Long: `Deletes a local kubernetes cluster. This command deletes the VM, and removes all
associated files.`,
	Run: runDelete,
}

type typeOfError int

const (
	// Fatal is a type of DeletionError
	Fatal typeOfError = 0
	// MissingProfile is a type of DeletionError
	MissingProfile typeOfError = 1
	// MissingCluster is a type of DeletionError
	MissingCluster typeOfError = 2
)

// DeletionError can be returned from DeleteProfiles
type DeletionError struct {
	Err     error
	Errtype typeOfError
}

func (error DeletionError) Error() string {
	return error.Err.Error()
}

func init() {
	deleteCmd.Flags().BoolVar(&deleteAll, "all", false, "Set flag to delete all profiles")
	deleteCmd.Flags().BoolVar(&purge, "purge", false, "Set this flag to delete the '.minikube' folder from your user directory.")

	if err := viper.BindPFlags(deleteCmd.Flags()); err != nil {
		exit.WithError("unable to bind flags", err)
	}
	RootCmd.AddCommand(deleteCmd)
}

// runDelete handles the executes the flow of "minikube delete"
func runDelete(cmd *cobra.Command, args []string) {
	if len(args) > 0 {
		exit.UsageT("Usage: minikube delete")
	}

	validProfiles, invalidProfiles, err := pkg_config.ListProfiles()
	if err != nil {
		glog.Warningf("'error loading profiles in minikube home %q: %v", localpath.MiniPath(), err)
	}
	profilesToDelete := append(validProfiles, invalidProfiles...)
	// in the case user has more than 1 profile and runs --purge
	// to prevent abandoned VMs/containers, force user to run with delete --all
	if purge && len(profilesToDelete) > 1 && !deleteAll {
		out.ErrT(out.Notice, "Multiple minikube profiles were found - ")
		for _, p := range profilesToDelete {
			out.T(out.Notice, "    - {{.profile}}", out.V{"profile": p.Name})
		}
		exit.UsageT("Usage: minikube delete --all --purge")
	}

	if deleteAll {
		delLabel := fmt.Sprintf("%s=%s", oci.CreatedByLabelKey, "true")
		errs := oci.DeleteContainersByLabel(oci.Docker, delLabel)
		if len(errs) > 0 { // it will error if there is no container to delete
			glog.Infof("error delete containers by label %q (might be okay): %+v", delLabel, err)
		}

		errs = oci.DeleteAllVolumesByLabel(oci.Docker, delLabel)
		if len(errs) > 0 { // it will not error if there is nothing to delete
			glog.Warningf("error delete volumes by label %q (might be okay): %+v", delLabel, errs)
		}

		errs = oci.PruneAllVolumesByLabel(oci.Docker, delLabel)
		if len(errs) > 0 { // it will not error if there is nothing to delete
			glog.Warningf("error pruning volumes by label %q (might be okay): %+v", delLabel, errs)
		}

		errs = DeleteProfiles(profilesToDelete)
		if len(errs) > 0 {
			HandleDeletionErrors(errs)
		} else {
			out.T(out.DeletingHost, "Successfully deleted all profiles")
		}
	} else {
		if len(args) > 0 {
			exit.UsageT("usage: minikube delete")
		}

		profileName := viper.GetString(pkg_config.MachineProfile)
{'fraction_non_alphanumeric': 0.11909965034965035, 'fraction_numerical': 0.007757867132867133, 'mean_word_length': 4.177036199095022, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7027358', 'n_tokens_mistral': 3378, 'n_tokens_neox': 3179, 'n_words': 900}