aboutsummaryrefslogtreecommitdiff
path: root/weed/shell/command_fs_rm.go
blob: 4f0848682fc204e928e0978eac18abca92b20527 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package shell

import (
	"context"
	"fmt"
	"io"
	"strings"

	"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
	"github.com/seaweedfs/seaweedfs/weed/util"
)

func init() {
	Commands = append(Commands, &commandFsRm{})
}

type commandFsRm struct {
}

func (c *commandFsRm) Name() string {
	return "fs.rm"
}

func (c *commandFsRm) Help() string {
	return `remove file and directory entries

	fs.rm [-rf] <entry1> <entry2> ...

	fs.rm /dir/file_name1 dir/file_name2
	fs.rm /dir

	The option "-r" can be recursive.
	The option "-f" can be ignored by recursive error.
`
}

func (c *commandFsRm) HasTag(CommandTag) bool {
	return false
}

func (c *commandFsRm) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {

	if handleHelpRequest(c, args, writer) {
		return nil
	}

	isRecursive := false
	ignoreRecursiveError := false
	var entries []string
	for _, arg := range args {
		if !strings.HasPrefix(arg, "-") {
			entries = append(entries, arg)
			continue
		}
		for _, t := range arg {
			switch t {
			case 'r':
				isRecursive = true
			case 'f':
				ignoreRecursiveError = true
			}
		}
	}
	if len(entries) < 1 {
		return fmt.Errorf("need to have arguments")
	}

	commandEnv.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
		for _, entry := range entries {
			targetPath, err := commandEnv.parseUrl(entry)
			if err != nil {
				fmt.Fprintf(writer, "rm: %s: %v\n", targetPath, err)
				continue
			}

			targetDir, targetName := util.FullPath(targetPath).DirAndName()

			lookupRequest := &filer_pb.LookupDirectoryEntryRequest{
				Directory: targetDir,
				Name:      targetName,
			}
			_, err = filer_pb.LookupEntry(context.Background(), client, lookupRequest)
			if err != nil {
				fmt.Fprintf(writer, "rm: %s: %v\n", targetPath, err)
				continue
			}

			request := &filer_pb.DeleteEntryRequest{
				Directory:            targetDir,
				Name:                 targetName,
				IgnoreRecursiveError: ignoreRecursiveError,
				IsDeleteData:         true,
				IsRecursive:          isRecursive,
				IsFromOtherCluster:   false,
				Signatures:           nil,
			}
			if resp, err := client.DeleteEntry(context.Background(), request); err != nil {
				fmt.Fprintf(writer, "rm: %s: %v\n", targetPath, err)
			} else {
				if resp.Error != "" {
					fmt.Fprintf(writer, "rm: %s: %v\n", targetPath, resp.Error)
				}
			}
		}
		return nil
	})

	return
}