/
mv.go
111 lines (90 loc) · 2.6 KB
/
mv.go
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
110
111
package mv
import (
"fmt"
"path/filepath"
"strings"
"github.com/GGP1/kure/auth"
cmdutil "github.com/GGP1/kure/commands"
"github.com/GGP1/kure/db/file"
"github.com/pkg/errors"
"github.com/spf13/cobra"
bolt "go.etcd.io/bbolt"
)
const example = `
* Move a file
kure file mv oldFile newFile
* Move a directory
kure file mv oldDir/ newDir/
* Move a file into a directory
kure file mv oldDir/test.txt newDir/`
// NewCmd returns a new command.
func NewCmd(db *bolt.DB) *cobra.Command {
return &cobra.Command{
Use: "mv <src> <dst>",
Short: "Move a file or directory",
Long: `Move a file or directory.
In case any of the paths contains spaces within it, it must be enclosed by double quotes.`,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 2 {
return errors.Errorf("accepts 2 arg(s), received %d", len(args))
}
oldName := cmdutil.NormalizeName(args[0], true)
if err := cmdutil.Exists(db, oldName, cmdutil.File); err == nil {
return errors.Errorf("there's no file nor directory named %q", strings.TrimSuffix(oldName, "/"))
}
return nil
},
Example: example,
PreRunE: auth.Login(db),
RunE: runMv(db),
}
}
func runMv(db *bolt.DB) cmdutil.RunEFunc {
return func(cmd *cobra.Command, args []string) error {
oldName := args[0]
newName := args[1]
if oldName == "" || newName == "" {
return errors.New("invalid format, use: kure file mv <oldName> <newName>")
}
oldName = cmdutil.NormalizeName(oldName, true)
newName = cmdutil.NormalizeName(newName, true)
oldNameIsDir := strings.HasSuffix(oldName, "/")
newNameIsDir := strings.HasSuffix(newName, "/")
if oldNameIsDir {
if !newNameIsDir {
return errors.New("cannot move a directory into a file")
}
return mvDir(db, oldName, newName)
}
// Move file into directory
if !oldNameIsDir && newNameIsDir {
newName += filepath.Base(oldName)
}
if filepath.Ext(newName) == "" {
newName += filepath.Ext(oldName)
}
if err := cmdutil.Exists(db, newName, cmdutil.File); err != nil {
return err
}
if err := file.Rename(db, oldName, newName); err != nil {
return err
}
fmt.Printf("\n%q moved to %q\n", oldName, newName)
return nil
}
}
func mvDir(db *bolt.DB, oldName, newName string) error {
names, err := file.ListNames(db)
if err != nil {
return err
}
fmt.Printf("Moving %q directory into %q...\n", strings.TrimSuffix(oldName, "/"), strings.TrimSuffix(newName, "/"))
for _, name := range names {
if strings.HasPrefix(name, oldName) {
if err := file.Rename(db, name, newName+strings.TrimPrefix(name, oldName)); err != nil {
return err
}
}
}
return nil
}