Skip to content

Commit

Permalink
Merge pull request #281 from fromanirh/context-fixes
Browse files Browse the repository at this point in the history
context: detect and report conflicting options
  • Loading branch information
jaypipes authored Oct 19, 2021
2 parents cdb1444 + 9172228 commit 5babfbd
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
15 changes: 14 additions & 1 deletion pkg/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
package context

import (
"fmt"

"github.com/jaypipes/ghw/pkg/option"
"github.com/jaypipes/ghw/pkg/snapshot"
)
Expand All @@ -22,6 +24,7 @@ type Context struct {
PathOverrides option.PathOverrides
snapshotUnpackedPath string
alert option.Alerter
err error
}

// WithContext returns an option.Option that contains a pre-existing Context
Expand Down Expand Up @@ -80,10 +83,17 @@ func New(opts ...*option.Option) *Context {
ctx.PathOverrides = merged.PathOverrides
}

// New is not allowed to return error - it would break the established API.
// so the only way out is to actually do the checks here and record the error,
// and return it later, at the earliest possible occasion, in Setup()
if ctx.SnapshotPath != "" && ctx.Chroot != option.DefaultChroot {
// The env/client code supplied a value, but we are will overwrite it when unpacking shapshots!
ctx.err = fmt.Errorf("Conflicting options: chroot %q and snapshot path %q", ctx.Chroot, ctx.SnapshotPath)
}
return ctx
}

// FromEnv returns an Option that has been populated from the environs or
// FromEnv returns a Context that has been populated from the environs or
// default options values
func FromEnv() *Context {
chrootVal := option.EnvOrDefaultChroot()
Expand Down Expand Up @@ -116,6 +126,9 @@ func (ctx *Context) Do(fn func() error) error {
// You should call `Setup` just once. It is safe to call `Setup` if you don't make
// use of optional extra features - `Setup` will do nothing.
func (ctx *Context) Setup() error {
if ctx.err != nil {
return ctx.err
}
if ctx.SnapshotPath == "" {
// nothing to do!
return nil
Expand Down
7 changes: 5 additions & 2 deletions pkg/option/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ import (
)

const (
defaultChroot = "/"
DefaultChroot = "/"
)

const (
envKeyChroot = "GHW_CHROOT"
envKeyDisableWarnings = "GHW_DISABLE_WARNINGS"
envKeyDisableTools = "GHW_DISABLE_TOOLS"
Expand Down Expand Up @@ -57,7 +60,7 @@ func EnvOrDefaultChroot() string {
if val, exists := os.LookupEnv(envKeyChroot); exists {
return val
}
return defaultChroot
return DefaultChroot
}

// EnvOrDefaultSnapshotPath returns the value of the GHW_SNAPSHOT_PATH environs variable
Expand Down

0 comments on commit 5babfbd

Please sign in to comment.