This repository has been archived by the owner on Mar 6, 2020. It is now read-only.
/
fileutils.go
104 lines (93 loc) · 2.29 KB
/
fileutils.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
// Package fileutils provides utililty methods to copy and move files and directories.
package fileutils
import (
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/pkg/errors"
)
const debugCopypath = false
const debugCopyfile = false
// Copypath copies the contents of src to dst, excluding any file or
// directory that starts with a period.
func Copypath(dst string, src string) error {
err := filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if strings.HasPrefix(filepath.Base(path), ".") {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
if info.IsDir() {
return nil
}
if info.Mode()&os.ModeSymlink != 0 {
if debugCopypath {
fmt.Printf("skipping symlink: %v\n", path)
}
return nil
}
dst := filepath.Join(dst, path[len(src):])
return Copyfile(dst, path)
})
if err != nil {
// if there was an error during copying, remove the partial copy.
RemoveAll(dst)
}
return err
}
// Copyfile copies file to destination creating destination directory if needed
func Copyfile(dst, src string) error {
err := mkdir(filepath.Dir(dst))
if err != nil {
return errors.Wrap(err, "copyfile: mkdirall")
}
r, err := os.Open(src)
if err != nil {
return errors.Wrapf(err, "copyfile: open(%q)", src)
}
defer r.Close()
w, err := os.Create(dst)
if err != nil {
return errors.Wrapf(err, "copyfile: create(%q)", dst)
}
defer w.Close()
if debugCopyfile {
fmt.Printf("copyfile(dst: %v, src: %v)\n", dst, src)
}
_, err = io.Copy(w, r)
return err
}
// RemoveAll removes path and any children it contains. Unlike os.RemoveAll it
// deletes read only files on Windows.
func RemoveAll(path string) error {
if runtime.GOOS == "windows" {
// Simple case: if Remove works, we're done.
err := os.Remove(path)
if err == nil || os.IsNotExist(err) {
return nil
}
// make sure all files are writable so we can delete them
filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
// walk gave us some error, give it back.
return err
}
mode := info.Mode()
if mode|0200 == mode {
return nil
}
return os.Chmod(path, mode|0200)
})
}
return os.RemoveAll(path)
}
func mkdir(path string) error {
return os.MkdirAll(path, 0755)
}