forked from colinmarc/hdfs
/
mv.go
84 lines (69 loc) · 1.7 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
package main
import (
"os"
"path"
"github.com/colinmarc/hdfs"
)
func mv(paths []string, force, treatDestAsFile bool) {
paths, nn, err := normalizePaths(paths)
if err != nil {
fatal(err)
}
if len(paths) < 2 {
fatalWithUsage("Both a source and destination are required.")
} else if hasGlob(paths[len(paths)-1]) {
fatal("The destination must be a single path.")
}
client, err := getClient(nn)
if err != nil {
fatal(err)
}
dest := paths[len(paths)-1]
sources, err := expandPaths(client, paths[:len(paths)-1])
if err != nil {
fatal(err)
}
destInfo, err := client.Stat(dest)
if err != nil && !os.IsNotExist(err) {
fatal(err)
}
exists := !os.IsNotExist(err)
if exists && !treatDestAsFile && destInfo.IsDir() {
moveInto(client, sources, dest, force)
} else {
if len(sources) > 1 {
fatal("Can't move multiple sources into the same place.")
}
moveTo(client, sources[0], dest, force)
}
}
func moveInto(client *hdfs.Client, sources []string, dest string, force bool) {
for _, source := range sources {
_, name := path.Split(source)
fullDest := path.Join(dest, name)
moveTo(client, source, fullDest, force)
}
}
func moveTo(client *hdfs.Client, source, dest string, force bool) {
sourceInfo, err := client.Stat(source)
if err != nil {
if pathErr, ok := err.(*os.PathError); ok {
pathErr.Op = "rename"
}
fatal(err)
}
destInfo, err := client.Stat(dest)
if err == nil {
if destInfo.IsDir() && !sourceInfo.IsDir() {
fatal("Can't replace directory with non-directory.")
} else if !force {
fatal(&os.PathError{"rename", dest, os.ErrExist})
}
} else if !os.IsNotExist(err) {
fatal(err)
}
err = client.Rename(source, dest)
if err != nil {
fatal(err)
}
}