-
Notifications
You must be signed in to change notification settings - Fork 15
/
dir.go
65 lines (59 loc) · 1.74 KB
/
dir.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
package plugins
import (
"fmt"
"os"
"path/filepath"
"github.com/hashicorp/go-multierror"
"github.com/mudler/yip/pkg/logger"
"github.com/mudler/yip/pkg/schema"
"github.com/twpayne/go-vfs/v4"
)
func EnsureDirectories(l logger.Interface, s schema.Stage, fs vfs.FS, console Console) error {
var errs error
for _, dir := range s.Directories {
if err := writePath(l, dir, fs, true); err != nil {
l.Error(err.Error())
errs = multierror.Append(errs, err)
continue
}
}
return errs
}
func writeDirectory(l logger.Interface, dir schema.Directory, fs vfs.FS) error {
l.Debug("Creating directory ", dir.Path)
err := fs.Mkdir(dir.Path, os.FileMode(dir.Permissions))
if err != nil {
return err
}
return fs.Chown(dir.Path, dir.Owner, dir.Group)
}
func writePath(l logger.Interface, dir schema.Directory, fs vfs.FS, topLevel bool) error {
inf, err := fs.Stat(dir.Path)
if err == nil && inf.IsDir() && topLevel {
// The path already exists, apply permissions and ownership only
err = fs.Chmod(dir.Path, os.FileMode(dir.Permissions))
if err != nil {
return err
}
return fs.Chown(dir.Path, dir.Owner, dir.Group)
} else if err == nil && !inf.IsDir() {
return fmt.Errorf("Error, '%s' already exists and it is not a directory", dir.Path)
} else if err == nil {
return nil
} else {
parentDir := filepath.Dir(dir.Path)
_, err = fs.Stat(parentDir)
if parentDir == "/" || parentDir == "." || err == nil {
//There is no parent dir or it already exists
return writeDirectory(l, dir, fs)
} else {
//Parent dir needs to be created
pDir := schema.Directory{parentDir, dir.Permissions, dir.Owner, dir.Group}
err = writePath(l, pDir, fs, false)
if err != nil {
return err
}
return writeDirectory(l, dir, fs)
}
}
}