-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
files.go
105 lines (90 loc) · 1.82 KB
/
files.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
package path
import (
"fmt"
"io"
"os"
"path/filepath"
"testing"
)
// CopyDir copies the contents of a directory from 'src' to 'dest'
func CopyDir(src string, dest string) error {
mode, err := os.Stat(src)
if err != nil {
return err
}
if mode.IsDir() {
dirContents, err := os.ReadDir(src)
if err != nil {
return err
}
for _, f := range dirContents {
srcFileaPath := filepath.Join(src, f.Name())
destFilePath := filepath.Join(dest, f.Name())
if err := CopyDir(srcFileaPath, destFilePath); err != nil {
return err
}
}
return nil
}
if err := os.MkdirAll(filepath.Dir(dest), os.ModePerm); err != nil {
return err
}
return copySingleFile(src, dest, mode)
}
func copySingleFile(src string, dest string, mode os.FileInfo) error {
if src == dest {
return nil
}
// Ensure the file is not a directory
file, err := os.Stat(src)
if err != nil {
return err
}
if file.IsDir() {
return fmt.Errorf("unable to copy directories: %s", src)
}
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
destFile, err := os.Create(dest)
if err != nil {
return err
}
defer destFile.Close()
err = os.Chmod(destFile.Name(), mode.Mode())
if err != nil {
return err
}
_, err = io.Copy(destFile, srcFile)
if err != nil {
return err
}
return nil
}
// CreateSymlink creates a symlink with name linkName to file destName in
// workingDir
func CreateSymlink(t *testing.T, workingDir, destName, linkName string) error {
t.Helper()
oldWorkingDir, err := os.Getwd()
if err != nil {
return err
}
if workingDir != "" {
err = os.Chdir(workingDir)
if err != nil {
return err
}
defer func() {
if err := os.Chdir(oldWorkingDir); err != nil {
t.Fatal(err.Error())
}
}()
}
err = os.Symlink(destName, linkName)
if err != nil {
return err
}
return nil
}