forked from localstack/lambda-runtime-init
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_utils.go
More file actions
68 lines (62 loc) · 1.84 KB
/
file_utils.go
File metadata and controls
68 lines (62 loc) · 1.84 KB
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
package main
import (
"encoding/json"
log "github.com/sirupsen/logrus"
"io"
"os"
"path/filepath"
"strconv"
)
type Chmod struct {
Path string `json:"path"`
Mode string `json:"mode"`
}
// AdaptFilesystemPermissions Adapts the file system permissions to the mode specified in the chmodInfoString parameter
// chmodInfoString should be a json encoded list of `Chmod` structs.
// example: '[{"path": "/opt", "mode": "0755"}]'. The mode string should be an octal representation of the targeted file mode.
func AdaptFilesystemPermissions(chmodInfoString string) error {
var chmodInfo []Chmod
err := json.Unmarshal([]byte(chmodInfoString), &chmodInfo)
if err != nil {
return err
}
for _, chmod := range chmodInfo {
mode, err := strconv.ParseInt(chmod.Mode, 0, 32)
if err != nil {
return err
}
if err := ChmodRecursively(chmod.Path, os.FileMode(mode)); err != nil {
log.Warnf("Could not change file mode recursively of directory %s: %s\n", chmod.Path, err)
}
}
return nil
}
// Inspired by https://stackoverflow.com/questions/73864379/golang-change-permission-os-chmod-and-os-chowm-recursively
// but using the more efficient WalkDir API
func ChmodRecursively(root string, mode os.FileMode) error {
return filepath.WalkDir(root,
func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
err = os.Chmod(path, mode)
if err != nil {
return err
}
return nil
})
}
// Check if a directory is empty
// Source: https://stackoverflow.com/questions/30697324/how-to-check-if-directory-on-path-is-empty/30708914#30708914
func IsDirEmpty(name string) (bool, error) {
f, err := os.Open(name)
if err != nil {
return false, err
}
defer f.Close()
_, err = f.Readdirnames(1) // faster than f.Readdir(1)
if err == io.EOF {
return true, nil
}
return false, err // Either not empty or error, suits both cases
}