-
-
Notifications
You must be signed in to change notification settings - Fork 585
/
files.go
365 lines (324 loc) · 9.36 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package fileutil
import (
"bytes"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"math/rand"
"os"
"path/filepath"
"strings"
"runtime"
"github.com/drud/ddev/pkg/output"
"github.com/drud/ddev/pkg/util"
)
// CopyFile copies the contents of the file named src to the file named
// by dst. The file will be created if it does not already exist. If the
// destination file exists, all it's contents will be replaced by the contents
// of the source file. The file mode will be copied from the source and
// the copied data is synced/flushed to stable storage. Credit @m4ng0squ4sh https://gist.github.com/m4ng0squ4sh/92462b38df26839a3ca324697c8cba04
func CopyFile(src string, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer util.CheckClose(in)
out, err := os.Create(dst)
if err != nil {
return fmt.Errorf("Failed to create file %v, err: %v", src, err)
}
defer util.CheckClose(out)
_, err = io.Copy(out, in)
if err != nil {
return fmt.Errorf("Failed to copy file from %v to %v err: %v", src, dst, err)
}
err = out.Sync()
if err != nil {
return err
}
// os.Chmod fails on long path (> 256 characters) on windows.
// A description of this problem with golang is at https://github.com/golang/dep/issues/774#issuecomment-311560825
// It could end up fixed in a future version of golang.
if runtime.GOOS != "windows" {
si, err := os.Stat(src)
if err != nil {
return err
}
err = os.Chmod(dst, si.Mode())
if err != nil {
return fmt.Errorf("Failed to chmod file %v to mode %v, err=%v", dst, si.Mode(), err)
}
}
return nil
}
// CopyDir recursively copies a directory tree, attempting to preserve permissions.
// Source directory must exist, destination directory must *not* exist.
// Symlinks are ignored and skipped. Credit @m4ng0squ4sh https://gist.github.com/m4ng0squ4sh/92462b38df26839a3ca324697c8cba04
func CopyDir(src string, dst string) error {
src = filepath.Clean(src)
dst = filepath.Clean(dst)
si, err := os.Stat(src)
if err != nil {
return err
}
if !si.IsDir() {
return fmt.Errorf("source is not a directory")
}
_, err = os.Stat(dst)
if err != nil && !os.IsNotExist(err) {
return err
}
if err == nil {
return fmt.Errorf("destination already exists")
}
err = os.MkdirAll(dst, si.Mode())
if err != nil {
return err
}
entries, err := ioutil.ReadDir(src)
if err != nil {
return err
}
for _, entry := range entries {
srcPath := filepath.Join(src, entry.Name())
dstPath := filepath.Join(dst, entry.Name())
if entry.IsDir() {
err = CopyDir(srcPath, dstPath)
if err != nil {
return err
}
} else {
err = CopyFile(srcPath, dstPath)
if err != nil && entry.Mode()&os.ModeSymlink != 0 {
output.UserOut.Warnf("failed to copy symlink %s, skipping...\n", srcPath)
continue
}
if err != nil {
return err
}
}
}
return nil
}
// FileExists checks a file's existence
func FileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
// IsDirectory returns true if path is a dir, false on error or not directory
func IsDirectory(path string) bool {
fileInfo, err := os.Stat(path)
if err != nil {
return false
}
return fileInfo.IsDir()
}
// FileIsReadable checks to make sure a file exists and is readable
func FileIsReadable(name string) bool {
file, err := os.OpenFile(name, os.O_RDONLY, 0666)
if err != nil {
return false
}
file.Close()
return true
}
// PurgeDirectory removes all of the contents of a given
// directory, leaving the directory itself intact.
func PurgeDirectory(path string) error {
dir, err := os.Open(path)
if err != nil {
return err
}
defer util.CheckClose(dir)
files, err := dir.Readdirnames(-1)
if err != nil {
return err
}
for _, file := range files {
err = os.Chmod(filepath.Join(path, file), 0777)
if err != nil {
return err
}
err = os.RemoveAll(filepath.Join(path, file))
if err != nil {
return err
}
}
return nil
}
// FgrepStringInFile is a small hammer for looking for a literal string in a file.
// It should only be used against very modest sized files, as the entire file is read
// into a string.
func FgrepStringInFile(fullPath string, needle string) (bool, error) {
fullFileBytes, err := ioutil.ReadFile(fullPath)
if err != nil {
return false, fmt.Errorf("failed to open file %s, err:%v ", fullPath, err)
}
fullFileString := string(fullFileBytes)
return strings.Contains(fullFileString, needle), nil
}
// ListFilesInDir returns an array of files found in a directory
func ListFilesInDir(path string) ([]string, error) {
var fileList []string
files, err := ioutil.ReadDir(path)
if err != nil {
return fileList, err
}
for _, f := range files {
fileList = append(fileList, f.Name())
}
return fileList, nil
}
// RandomFilenameBase generates a temporary filename for use in testing or whatever.
// From https://stackoverflow.com/a/28005931/215713
func RandomFilenameBase() string {
randBytes := make([]byte, 16)
_, _ = rand.Read(randBytes)
return hex.EncodeToString(randBytes)
}
// ReplaceStringInFile takes search and replace strings, an original path, and a dest path, returns error
func ReplaceStringInFile(searchString string, replaceString string, origPath string, destPath string) error {
input, err := ioutil.ReadFile(origPath)
if err != nil {
return err
}
output := bytes.Replace(input, []byte(searchString), []byte(replaceString), -1)
if err = ioutil.WriteFile(destPath, output, 0666); err != nil {
return err
}
return nil
}
// IsSameFile() determines whether two paths refer to the same file/dir
func IsSameFile(path1 string, path2 string) (bool, error) {
path1fi, err := os.Stat(path1)
if err != nil {
return false, err
}
path2fi, err := os.Stat(path2)
if err != nil {
return false, err
}
return os.SameFile(path1fi, path2fi), nil
}
// ReadFileIntoString just gets the contents of file into string
func ReadFileIntoString(path string) (string, error) {
bytes, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
return string(bytes), err
}
type XSymContents struct {
LinkLocation string
LinkTarget string
}
// FindSimulatedXsymSymlinks() searches the basePath provided for files
// whose first line is XSym, which is used in cifs filesystem for simulated
// symlinks.
func FindSimulatedXsymSymlinks(basePath string) ([]XSymContents, error) {
symLinks := make([]XSymContents, 0)
err := filepath.Walk(basePath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
//TODO: Skip a directory named .git? Skip other arbitrary dirs or files?
if !info.IsDir() {
if info.Size() == 1067 {
contents, err := ioutil.ReadFile(path)
if err != nil {
return err
}
lines := strings.Split(string(contents), "\n")
if lines[0] != "XSym" {
return nil
}
if len(lines) < 4 {
return fmt.Errorf("Apparent XSym doesn't have enough lines: %s", path)
}
// target is 4th line
linkTarget := filepath.Clean(lines[3])
symLinks = append(symLinks, XSymContents{LinkLocation: path, LinkTarget: linkTarget})
}
}
return nil
})
return symLinks, err
}
// ReplaceSimulatedXsymSymlinks() walks a list of XSymContents and makes real symlinks
// in their place. This is only valid on Windows host, only works with Docker for Windows
// (cifs filesystem)
func ReplaceSimulatedXsymSymlinks(links []XSymContents) error {
for _, item := range links {
err := os.Remove(item.LinkLocation)
if err != nil {
return err
}
err = os.Symlink(item.LinkTarget, item.LinkLocation)
if err != nil {
return err
}
}
return nil
}
// CanCreateSymlinks tests to see if it's possible to create a symlink
func CanCreateSymlinks() bool {
tmpdir := os.TempDir()
linkPath := filepath.Join(tmpdir, RandomFilenameBase())
// This doesn't attempt to create the real file; we don't need it.
err := os.Symlink(filepath.Join(tmpdir, "realfile.txt"), linkPath)
//nolint: errcheck
defer os.Remove(linkPath)
if err != nil {
return false
}
return true
}
// ReplaceSimulatedLinks() walks the path provided and tries to replace XSym links with real ones.
func ReplaceSimulatedLinks(path string) {
links, err := FindSimulatedXsymSymlinks(path)
if err != nil {
util.Warning("Error finding XSym Symlinks: %v", err)
}
if len(links) == 0 {
return
}
if !CanCreateSymlinks() {
util.Warning("This host computer is unable to create real symlinks, please see the docs to enable developer mode:\n%s\nNote that the simulated symlinks created inside the container will work fine for most projects.", "https://ddev.readthedocs.io/en/stable/users/developer-tools/#windows-os-and-ddev-composer")
return
}
err = ReplaceSimulatedXsymSymlinks(links)
if err != nil {
util.Warning("Failed replacing simulated symlinks: %v", err)
}
replacedLinks := make([]string, 0)
for _, l := range links {
replacedLinks = append(replacedLinks, l.LinkLocation)
}
util.Success("Replaced these simulated symlinks with real symlinks: %v", replacedLinks)
return
}
// RemoveContents removes contents of passed directory
// From https://stackoverflow.com/questions/33450980/how-to-remove-all-contents-of-a-directory-using-golang
func RemoveContents(dir string) error {
d, err := os.Open(dir)
if err != nil {
return err
}
defer d.Close()
names, err := d.Readdirnames(-1)
if err != nil {
return err
}
for _, name := range names {
err = os.RemoveAll(filepath.Join(dir, name))
if err != nil {
return err
}
}
return nil
}