forked from laher/someutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mv.go
95 lines (85 loc) · 1.71 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
package someutils
import (
"errors"
"fmt"
"github.com/laher/uggo"
"os"
"path/filepath"
)
func init() {
Register(Util{
"mv",
mv})
}
func mv(call []string) error {
flagSet := uggo.NewFlagSetDefault("mv", "[options] [src...] [dest]", VERSION)
err := flagSet.Parse(call[1:])
if err != nil {
fmt.Fprintf(os.Stderr, "Flag error: %v\n\n", err.Error())
flagSet.Usage()
return err
}
if flagSet.ProcessHelpOrVersion() {
return nil
}
args := flagSet.Args()
if len(args) < 2 {
fmt.Fprintf(os.Stderr, "Error: not enough arguments\n\n")
flagSet.Usage()
return errors.New("Not enough arguments")
}
srcGlobs := args[0 : len(args)-1]
dest := args[len(args)-1]
for _, srcGlob := range srcGlobs {
srces, err := filepath.Glob(srcGlob)
if err != nil {
return err
}
if len(srces) < 1 {
return errors.New(fmt.Sprintf("Source glob '%s' does not match any files\n", srcGlob))
}
for _, src := range srces {
err = moveFile(src, dest)
if err != nil {
fmt.Fprintf(os.Stderr, "Error %v\n", err)
return err
}
}
}
return nil
}
func moveFile(src, dest string) error {
fmt.Printf("%s -> %s\n", src, dest)
srcFile, err := os.Open(src)
if err != nil {
return err
}
sinf, err := srcFile.Stat()
if err != nil {
return err
}
err = srcFile.Close()
if err != nil {
return err
}
//check if destination given is full filename or its (existing) parent dir
var destFull string
dinf, err := os.Stat(dest)
if err != nil {
if !os.IsNotExist(err) {
return err
} else {
//doesnt exist
destFull = dest
}
} else {
if dinf.IsDir() {
//copy file name
destFull = filepath.Join(dest, sinf.Name())
} else {
destFull = dest
}
}
err = os.Rename(src, destFull)
return err
}