/
ensure-path-at.go
47 lines (41 loc) 路 1.59 KB
/
ensure-path-at.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
package utils
import (
"os"
"path/filepath"
"strings"
"github.com/snivilised/extendio/xfs/storage"
)
// EnsurePathAt ensures that the specified path exists (including any non
// existing intermediate directories). Given a path and a default filename,
// the specified path is created in the following manner:
// - If the path denotes a file (path does not end is a directory separator), then
// the parent folder is created if it doesn't exist on the file-system provided.
// - If the path denotes a directory, then that directory is created.
//
// The returned string represents the file, so if the path specified was a
// directory path, then the defaultFilename provided is joined to the path
// and returned, otherwise the original path is returned un-modified.
// Note: filepath.Join does not preserve a trailing separator, therefore to make sure
// a path is interpreted as a directory and not a file, then the separator has
// to be appended manually onto the end of the path.
// If vfs is not provided, then the path is ensured directly on the native file
// system.
func EnsurePathAt(path, defaultFilename string, perm int, vfs ...storage.VirtualFS) (at string, err error) {
var (
directory, file string
)
if strings.HasSuffix(path, string(os.PathSeparator)) {
directory = path
file = defaultFilename
} else {
directory, file = filepath.Split(path)
}
if len(vfs) > 0 {
if !vfs[0].DirectoryExists(directory) {
err = vfs[0].MkdirAll(directory, os.FileMode(perm))
}
} else {
err = os.MkdirAll(directory, os.FileMode(perm))
}
return filepath.Clean(filepath.Join(directory, file)), err
}