fs.go 4.13 KB
Newer Older
1
2
3
4
package fs

import (
	"crypto/rand"
5
	"encoding/base64"
6
7
8
9
	"encoding/hex"
	"io/ioutil"
	"os"
	"path"
10
	"path/filepath"
11
12
13
14
15

	"github.com/pkg/errors"
)

// AssertPathExists returns nil only if it has been successfully
16
17
18
19
20
21
22
23
24
25
// verified that all specified paths exists.
func AssertPathExists(paths ...string) error {
	for _, p := range paths {
		exist, err := PathExists(p)
		if err != nil {
			return err
		}
		if !exist {
			return errors.Errorf("Path %s does not exist", p)
		}
26
27
28
29
	}
	return nil
}

30
31
32
33
34
35
36
37
38
39
40
41
42
func AssertPathNotExists(paths ...string) error {
	for _, p := range paths {
		exist, err := PathExists(p)
		if err != nil {
			return err
		}
		if exist {
			return errors.Errorf("Path %s exists but should not", p)
		}
	}
	return nil
}

43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// PathExists checks if the specified path exists.
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return true, err
}

func EnsureDirectoryExists(path string) error {
	exists, err := PathExists(path)
	if err != nil {
		return err
	}
	if exists {
		return nil
	}
63
	return os.MkdirAll(path, 0700)
64
65
}

66
67
68
69
70
func Empty(path string) bool {
	matches, _ := filepath.Glob(filepath.Join(path, "*"))
	return len(matches) == 0
}

71
func Copy(src, dest string) error {
72
73
	exists, err := PathExists(src)
	if err != nil || !exists {
74
75
76
77
78
79
80
81
82
		return err
	}
	bts, err := ioutil.ReadFile(src)
	if err != nil {
		return err
	}
	return SaveFile(dest, bts)
}

83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Save the filecontents at the specified path atomically:
// - first save the content in a temp file with a random filename in the same dir
// - then rename the temp file to the specified filepath, overwriting the old file
func SaveFile(filepath string, content []byte) (err error) {
	dir := path.Dir(filepath)

	// Read random data for filename and convert to hex
	randBytes := make([]byte, 16)
	_, err = rand.Read(randBytes)
	if err != nil {
		return
	}
	tempfilename := hex.EncodeToString(randBytes)

	// Create temp file
	err = ioutil.WriteFile(dir+"/"+tempfilename, content, 0600)
	if err != nil {
		return
	}

	// Rename, overwriting old file
	return os.Rename(dir+"/"+tempfilename, filepath)
}
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

func CopyDirectory(src, dest string) error {
	if err := EnsureDirectoryExists(dest); err != nil {
		return err
	}

	return filepath.Walk(src, filepath.WalkFunc(
		func(path string, info os.FileInfo, err error) error {
			if path == src {
				return nil
			}
			subpath := path[len(src):]
			if info.IsDir() {
				if err := EnsureDirectoryExists(dest + subpath); err != nil {
					return err
				}
			} else {
				srcfile, err := os.Open(path)
				if err != nil {
					return err
				}
				defer srcfile.Close()
				bts, err := ioutil.ReadAll(srcfile)
				if err != nil {
					return err
				}
				if err := SaveFile(dest+subpath, bts); err != nil {
					return err
				}
			}
			return nil
		}),
	)
}
140

141
142
143
144
145
146
147
148
// ReadKey returns either the content of the file specified at path, if it exists,
// or []byte(key) otherwise. It is an error to specify both or none arguments, or
// specify an empty or unreadable file. If there is no error then the return []byte is non-empty.
func ReadKey(key, path string) ([]byte, error) {
	if (key != "" && path != "") || (key == "" && path == "") {
		return nil, errors.New("provide either key or path to key")
	}

149
	var bts []byte
150
151
152
153
154
155
156
157

	if path == "" {
		bts = []byte(key)
	} else {
		stat, err := os.Stat(path)
		if err != nil {
			return nil, errors.New("no key found at specified path")
		}
158
159
160
		if stat.IsDir() {
			return nil, errors.New("cannot read key from a directory")
		}
161
		bts, err = ioutil.ReadFile(path)
162
163
164
		if err != nil {
			return nil, err
		}
165
166
167
168
	}

	if len(bts) == 0 {
		return nil, errors.New("empty key provided")
169
170
171
172
	}
	return bts, nil
}

173
174
// Base64Decode decodes the specified bytes as any of the Base64 dialects:
// standard encoding (+, /) and URL encoding (-, _), with or without padding.
175
176
177
178
179
180
181
182
183
184
185
186
187
func Base64Decode(b []byte) ([]byte, error) {
	var (
		err       error
		bts       []byte
		encodings = []*base64.Encoding{base64.RawStdEncoding, base64.URLEncoding, base64.RawURLEncoding, base64.StdEncoding}
	)
	for _, encoding := range encodings {
		if bts, err = encoding.DecodeString(string(b)); err == nil {
			break
		}
	}
	return bts, err
}