-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
102 lines (83 loc) · 2.34 KB
/
main.go
File metadata and controls
102 lines (83 loc) · 2.34 KB
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
// Package fileutils provides functions to check and manipulate files
package fileutils
import (
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/pkg/errors"
)
// Exists checks if the file exists at the given path
func Exists(filepath string) bool {
_, err := os.Stat(filepath)
return !os.IsNotExist(err)
}
// CopyFile copies a file from the src to dest
func CopyFile(src, dest string) error {
in, err := os.Open(src)
if err != nil {
return errors.Wrap(err, "opening the input file")
}
defer in.Close()
out, err := os.Create(dest)
if err != nil {
return errors.Wrap(err, "creating the output file")
}
if _, err = io.Copy(out, in); err != nil {
return errors.Wrap(err, "copying the file content")
}
if err = out.Sync(); err != nil {
return errors.Wrap(err, "flushing the output file to disk")
}
fi, err := os.Stat(src)
if err != nil {
return errors.Wrap(err, "getting the file info for the input file")
}
if err = os.Chmod(dest, fi.Mode()); err != nil {
return errors.Wrap(err, "copying permission to the output file")
}
// Close the output file
if err = out.Close(); err != nil {
return errors.Wrap(err, "closing the output file")
}
return nil
}
// CopyDir copies a directory from src to dest, recursively copying nested
// directories
func CopyDir(src, dest string) error {
srcPath := filepath.Clean(src)
destPath := filepath.Clean(dest)
fi, err := os.Stat(srcPath)
if err != nil {
return errors.Wrap(err, "getting the file info for the input")
}
if !fi.IsDir() {
return errors.New("source is not a directory")
}
_, err = os.Stat(dest)
if err != nil && !os.IsNotExist(err) {
return errors.Wrap(err, "looking up the destination")
}
err = os.MkdirAll(dest, fi.Mode())
if err != nil {
return errors.Wrap(err, "creating destination")
}
entries, err := ioutil.ReadDir(src)
if err != nil {
return errors.Wrap(err, "reading the directory listing for the input")
}
for _, entry := range entries {
srcEntryPath := filepath.Join(srcPath, entry.Name())
destEntryPath := filepath.Join(destPath, entry.Name())
if entry.IsDir() {
if err = CopyDir(srcEntryPath, destEntryPath); err != nil {
return errors.Wrapf(err, "copying %s", entry.Name())
}
} else {
if err = CopyFile(srcEntryPath, destEntryPath); err != nil {
return errors.Wrapf(err, "copying %s", entry.Name())
}
}
}
return nil
}