-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
129 lines (109 loc) · 2.33 KB
/
main.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
)
func main() {
if ln := len(os.Args); ln == 1 {
fmt.Fprintln(os.Stderr, "[args] srcfile dstpath")
os.Exit(2)
} else if ln != 3 {
fmt.Fprintln(os.Stderr, "invalid args length")
os.Exit(2)
}
srcfile := os.Args[1]
if fi, err := os.Stat(srcfile); err != nil {
fmt.Fprintln(os.Stderr, "invalid srcfile")
os.Exit(2)
} else if fi.IsDir() {
fmt.Fprintln(os.Stderr, "srcfile is directory")
os.Exit(2)
}
dstpath := os.Args[2]
if fi, err := os.Stat(dstpath); err != nil {
fmt.Fprintln(os.Stderr, "invalid dstpath")
os.Exit(2)
} else if !fi.IsDir() {
fmt.Fprintln(os.Stderr, "dstpath is not directory")
os.Exit(2)
}
dstfiles, err := find(dstpath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if err := update(srcfile, dstfiles); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func find(path string) ([]string, error) {
pathfiles, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
var allfiles []string
for _, pathfile := range pathfiles {
fullpath := filepath.Join(path, pathfile.Name())
if pathfile.IsDir() {
files, err := find(fullpath)
if err != nil {
return files, err
}
allfiles = append(allfiles, files...)
} else {
allfiles = append(allfiles, fullpath)
}
}
return allfiles, nil
}
func update(srcfile string, dstfiles []string) error {
srcabs, err := filepath.Abs(srcfile)
if err != nil {
return err
}
srcbase := filepath.Base(srcfile)
for _, dstfile := range dstfiles {
dstabs, err := filepath.Abs(dstfile)
if err != nil {
return err
}
// srcfile does not copy.
if srcabs == dstabs {
continue
}
if _, dstbase := filepath.Split(dstfile); srcbase == dstbase {
if err := copy(dstfile, srcfile); err != nil {
return err
}
}
}
return nil
}
func copy(dstfile, srcfile string) error {
src, err := os.Open(srcfile)
if err != nil {
return err
}
defer src.Close()
// backup dstfile.
nows := strings.Split(time.Now().Format("20060102150405.000"), ".")
newfile := dstfile + "." + nows[0] + nows[1]
if err := os.Rename(dstfile, newfile); err != nil {
return err
}
dst, err := os.Create(dstfile)
if err != nil {
return err
}
defer dst.Close()
if _, err := io.Copy(dst, src); err != nil {
return err
}
return nil
}