-
Notifications
You must be signed in to change notification settings - Fork 176
/
chown_unix.go
64 lines (53 loc) · 1.6 KB
/
chown_unix.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
//go:build !windows
package chown
import (
"fmt"
"os"
"path/filepath"
"syscall"
)
// ChangeHostPathOwnership changes the uid and gid ownership of a directory or file within the host.
// This is used by the volume U flag to change source volumes ownership
func ChangeHostPathOwnership(path string, recursive bool, uid, gid int) error {
// Validate if host path can be chowned
isDangerous, err := DangerousHostPath(path)
if err != nil {
return fmt.Errorf("failed to validate if host path is dangerous: %w", err)
}
if isDangerous {
return fmt.Errorf("chowning host path %q is not allowed. You can manually `chown -R %d:%d %s`", path, uid, gid, path)
}
// Chown host path
if recursive {
err := filepath.Walk(path, func(filePath string, f os.FileInfo, err error) error {
if err != nil {
return err
}
// Get current ownership
currentUID := int(f.Sys().(*syscall.Stat_t).Uid)
currentGID := int(f.Sys().(*syscall.Stat_t).Gid)
if uid != currentUID || gid != currentGID {
return os.Lchown(filePath, uid, gid)
}
return nil
})
if err != nil {
return fmt.Errorf("failed to chown recursively host path: %w", err)
}
} else {
// Get host path info
f, err := os.Lstat(path)
if err != nil {
return fmt.Errorf("failed to get host path information: %w", err)
}
// Get current ownership
currentUID := int(f.Sys().(*syscall.Stat_t).Uid)
currentGID := int(f.Sys().(*syscall.Stat_t).Gid)
if uid != currentUID || gid != currentGID {
if err := os.Lchown(path, uid, gid); err != nil {
return fmt.Errorf("failed to chown host path: %w", err)
}
}
}
return nil
}