-
Notifications
You must be signed in to change notification settings - Fork 102
/
filesystem.go
67 lines (60 loc) · 1.82 KB
/
filesystem.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
package test
import (
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"testing"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
)
// CopyDirectory copies all files in the given src directory into the given dst directory.
// Both the source and the destination directory must exist.
func CopyDirectory(src, dst string) error {
return filepath.Walk(src, func(srcPath string, fi os.FileInfo, e error) error {
dstPath := strings.Replace(srcPath, src, dst, 1)
// handle directory
if fi.IsDir() {
err := os.Mkdir(dstPath, fi.Mode())
if err != nil {
return errors.Wrap(err, "cannot create target directory")
}
return nil
}
// handle file
sourceContent, err := os.Open(srcPath)
if err != nil {
return errors.Wrapf(err, "cannot read source file %q", srcPath)
}
destFile, err := os.OpenFile(dstPath, os.O_CREATE|os.O_WRONLY, fi.Mode())
if err != nil {
return errors.Wrapf(err, "Cannot create target file %q", srcPath)
}
_, err = io.Copy(destFile, sourceContent)
if err != nil {
return errors.Wrapf(err, "cannot copy %q into %q", srcPath, dstPath)
}
err = sourceContent.Close()
if err != nil {
return errors.Wrapf(err, "cannot close source file %q", srcPath)
}
err = destFile.Close()
return err
})
}
// createFile creates a file with the given filename in the given directory.
func createFile(t *testing.T, dir, filename string) {
filePath := path.Join(dir, filename)
err := os.MkdirAll(path.Dir(filePath), 0744)
assert.Nil(t, err)
err = ioutil.WriteFile(filePath, []byte(filename+" content"), 0644)
assert.Nil(t, err)
}
// createTempDir creates a new empty directory in the system's temp directory and provides the path to it.
func createTempDir(t *testing.T) string {
dir, err := ioutil.TempDir("", "")
assert.Nil(t, err, "cannot create TempDir")
return dir
}