-
Notifications
You must be signed in to change notification settings - Fork 394
/
earthlydir.go
85 lines (74 loc) · 2.57 KB
/
earthlydir.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package cliutil
import (
"fmt"
"os"
"os/user"
"path/filepath"
"sync"
"github.com/earthly/earthly/util/fileutil"
"github.com/pkg/errors"
)
var earthlyDir string
var earthlyDirOnce sync.Once
var earthlyDirSudoUser *user.User
var earthlyDirCreateOnce sync.Once
var earthlyDirCreateErr error
// GetEarthlyDir returns the .earthly dir. (Usually ~/.earthly).
// This function will not attempt to create the directory if missing, for that functionality use to the GetOrCreateEarthlyDir function.
func GetEarthlyDir(installName string) string {
if installName == "" {
// if GetEarthlyDir is called by the autocomplete code, this may not be set
installName = "earthly"
}
earthlyDirOnce.Do(func() {
earthlyDir, earthlyDirSudoUser = getEarthlyDirAndUser(installName)
})
return earthlyDir
}
func getEarthlyDirAndUser(installName string) (string, *user.User) {
homeDir, u := fileutil.HomeDir()
earthlyDir := filepath.Join(homeDir, fmt.Sprintf(".%s", installName))
return earthlyDir, u
}
// GetOrCreateEarthlyDir returns the .earthly dir. (Usually ~/.earthly).
// if the directory does not exist, it will attempt to create it.
func GetOrCreateEarthlyDir(installName string) (string, error) {
_ = GetEarthlyDir(installName) // ensure global vars get created so we can reference them below.
earthlyDirCreateOnce.Do(func() {
earthlyDirExists, err := fileutil.DirExists(earthlyDir)
if err != nil {
earthlyDirCreateErr = errors.Wrapf(err, "unable to create dir %s", earthlyDir)
return
}
if !earthlyDirExists {
err := os.MkdirAll(earthlyDir, 0755)
if err != nil {
earthlyDirCreateErr = errors.Wrapf(err, "unable to create dir %s", earthlyDir)
return
}
if earthlyDirSudoUser != nil {
err := fileutil.EnsureUserOwned(earthlyDir, earthlyDirSudoUser)
if err != nil {
earthlyDirCreateErr = errors.Wrapf(err, "failed to ensure %s is owned by %s", earthlyDir, earthlyDirSudoUser)
}
}
}
})
return earthlyDir, earthlyDirCreateErr
}
// IsBootstrapped provides a tentatively correct guess about the state of our bootstrapping.
func IsBootstrapped(installName string) bool {
exists, _ := fileutil.DirExists(GetEarthlyDir(installName))
return exists
}
// EnsurePermissions changes the permissions of all earthly files to be owned by the user and their group.
func EnsurePermissions(installName string) error {
earthlyDir, sudoUser := getEarthlyDirAndUser(installName)
if sudoUser != nil {
err := fileutil.EnsureUserOwned(earthlyDir, sudoUser)
if err != nil {
return errors.Wrapf(err, "failed to ensure %s is owned by %s", earthlyDir, sudoUser)
}
}
return nil
}