github.com/GGP1/kure@v0.8.4/commands/file/rm/rm.go (about)

     1  package rm
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"strings"
     7  
     8  	"github.com/GGP1/kure/auth"
     9  	cmdutil "github.com/GGP1/kure/commands"
    10  	"github.com/GGP1/kure/db/file"
    11  	"github.com/GGP1/kure/terminal"
    12  
    13  	"github.com/spf13/cobra"
    14  	bolt "go.etcd.io/bbolt"
    15  )
    16  
    17  const example = `
    18  * Remove a file
    19  kure file rm Sample
    20  
    21  * Remove a directory
    22  kure file rm SampleDir/`
    23  
    24  // NewCmd returns a new command.
    25  func NewCmd(db *bolt.DB, r io.Reader) *cobra.Command {
    26  	return &cobra.Command{
    27  		Use:     "rm <name>",
    28  		Short:   "Remove a file or directory",
    29  		Example: example,
    30  		Args:    cmdutil.MustExist(db, cmdutil.File, true),
    31  		PreRunE: auth.Login(db),
    32  		RunE:    runRm(db, r),
    33  	}
    34  }
    35  
    36  func runRm(db *bolt.DB, r io.Reader) cmdutil.RunEFunc {
    37  	return func(cmd *cobra.Command, args []string) error {
    38  		name := strings.Join(args, " ")
    39  		name = cmdutil.NormalizeName(name, true)
    40  
    41  		if !terminal.Confirm(r, "Are you sure you want to proceed?") {
    42  			return nil
    43  		}
    44  
    45  		// Remove single file
    46  		if !strings.HasSuffix(name, "/") {
    47  			fmt.Println("Remove:", name)
    48  			if err := file.Remove(db, name); err != nil {
    49  				return err
    50  			}
    51  
    52  			return nil
    53  		}
    54  
    55  		// Remove directory
    56  		fmt.Printf("Removing %q directory...\n", name)
    57  		files, err := file.ListNames(db)
    58  		if err != nil {
    59  			return err
    60  		}
    61  
    62  		selected := make([]string, 0)
    63  		for _, f := range files {
    64  			if strings.HasPrefix(f, name) {
    65  				selected = append(selected, f)
    66  				fmt.Println("Remove:", f)
    67  			}
    68  		}
    69  
    70  		return file.Remove(db, selected...)
    71  	}
    72  }