forked from jaypipes/ghw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptions.go
59 lines (52 loc) · 1.71 KB
/
options.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
package ghw
import "os"
const (
defaultChroot = "/"
envKeyChroot = "GHW_CHROOT"
)
// optDefaultChroot returns the value of the GHW_CHROOT environs variable or
// the default value of "/" if not set
func envOrDefaultChroot() string {
// Grab options from the environs by default
if val, exists := os.LookupEnv(envKeyChroot); exists {
return val
}
return defaultChroot
}
// WithOption is used to represent optionally-configured settings. Each field
// is a pointer to some concrete value so that we can tell when something has
// been set or left unset.
type WithOption struct {
// To facilitate querying of sysfs filesystems that are bind-mounted to a
// non-default root mountpoint, we allow users to set the GHW_CHROOT environ
// vairable to an alternate mountpoint. For instance, assume that the user of
// ghw is a Golang binary being executed from an application container that has
// certain host filesystems bind-mounted into the container at /host. The user
// would ensure the GHW_CHROOT environ variable is set to "/host" and ghw will
// build its paths from that location instead of /
Chroot *string
}
func WithChroot(dir string) *WithOption {
return &WithOption{Chroot: &dir}
}
func mergeOptions(opts ...*WithOption) *WithOption {
merged := &WithOption{}
for _, opt := range opts {
if opt.Chroot != nil {
merged.Chroot = opt.Chroot
}
}
// Set the default value if missing from mergeOpts
if merged.Chroot == nil {
chroot := envOrDefaultChroot()
merged.Chroot = &chroot
}
return merged
}
// contextFromEnv returns a pointer to a context struct that has been populated
// from the environs or default options values
func contextFromEnv() *context {
return &context{
chroot: envOrDefaultChroot(),
}
}