github.com/zsuzhengdu/helm@v3.0.0-beta.3+incompatible/cmd/helm/repo_remove.go (about)

     1  /*
     2  Copyright The Helm Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package main
    18  
    19  import (
    20  	"fmt"
    21  	"io"
    22  	"os"
    23  	"path/filepath"
    24  
    25  	"github.com/pkg/errors"
    26  	"github.com/spf13/cobra"
    27  
    28  	"helm.sh/helm/cmd/helm/require"
    29  	"helm.sh/helm/pkg/helmpath"
    30  	"helm.sh/helm/pkg/repo"
    31  )
    32  
    33  type repoRemoveOptions struct {
    34  	name      string
    35  	repoFile  string
    36  	repoCache string
    37  }
    38  
    39  func newRepoRemoveCmd(out io.Writer) *cobra.Command {
    40  	o := &repoRemoveOptions{}
    41  	cmd := &cobra.Command{
    42  		Use:     "remove [NAME]",
    43  		Aliases: []string{"rm"},
    44  		Short:   "remove a chart repository",
    45  		Args:    require.ExactArgs(1),
    46  		RunE: func(cmd *cobra.Command, args []string) error {
    47  			o.repoFile = settings.RepositoryConfig
    48  			o.repoCache = settings.RepositoryCache
    49  			o.name = args[0]
    50  			return o.run(out)
    51  		},
    52  	}
    53  
    54  	return cmd
    55  }
    56  
    57  func (o *repoRemoveOptions) run(out io.Writer) error {
    58  	r, err := repo.LoadFile(o.repoFile)
    59  	if isNotExist(err) || len(r.Repositories) == 0 {
    60  		return errors.New("no repositories configured")
    61  	}
    62  
    63  	if !r.Remove(o.name) {
    64  		return errors.Errorf("no repo named %q found", o.name)
    65  	}
    66  	if err := r.WriteFile(o.repoFile, 0644); err != nil {
    67  		return err
    68  	}
    69  
    70  	if err := removeRepoCache(o.repoCache, o.name); err != nil {
    71  		return err
    72  	}
    73  
    74  	fmt.Fprintf(out, "%q has been removed from your repositories\n", o.name)
    75  	return nil
    76  }
    77  
    78  func removeRepoCache(root, name string) error {
    79  	idx := filepath.Join(root, helmpath.CacheIndexFile(name))
    80  	if _, err := os.Stat(idx); os.IsNotExist(err) {
    81  		return nil
    82  	} else if err != nil {
    83  		return errors.Wrapf(err, "can't remove index file %s", idx)
    84  	}
    85  	return os.Remove(idx)
    86  }