diff --git a/pkg/context/context.go b/pkg/context/context.go index 255d5ebf..315c2d8b 100644 --- a/pkg/context/context.go +++ b/pkg/context/context.go @@ -14,12 +14,13 @@ import ( // Concrete merged set of configuration switches that act as an execution // context when calling internal discovery methods type Context struct { - Chroot string - EnableTools bool - SnapshotPath string - SnapshotRoot string - SnapshotExclusive bool - alert option.Alerter + Chroot string + EnableTools bool + SnapshotPath string + SnapshotRoot string + SnapshotExclusive bool + snapshotUnpackedPath string + alert option.Alerter } // New returns a Context struct pointer that has had various options set on it @@ -92,6 +93,9 @@ func (ctx *Context) Setup() error { root := ctx.SnapshotRoot if root == "" { root, err = snapshot.Unpack(ctx.SnapshotPath) + if err == nil { + ctx.snapshotUnpackedPath = root + } } else { var flags uint if ctx.SnapshotExclusive { @@ -111,12 +115,12 @@ func (ctx *Context) Setup() error { // You should always call `Teardown` if you called `Setup` to free any resources // acquired by `Setup`. Check `Do` for more automated management. func (ctx *Context) Teardown() error { - if ctx.SnapshotRoot != "" { + if ctx.snapshotUnpackedPath == "" { // if the client code provided the unpack directory, // then it is also in charge of the cleanup. return nil } - return snapshot.Cleanup(ctx.SnapshotRoot) + return snapshot.Cleanup(ctx.snapshotUnpackedPath) } func (ctx *Context) Warn(msg string, args ...interface{}) { diff --git a/pkg/context/context_test.go b/pkg/context/context_test.go new file mode 100644 index 00000000..e12d3f74 --- /dev/null +++ b/pkg/context/context_test.go @@ -0,0 +1,42 @@ +// +// Use and distribution licensed under the Apache license version 2. +// +// See the COPYING file in the root project directory for full text. +// + +package context_test + +import ( + "os" + "testing" + + "github.com/jaypipes/ghw/pkg/context" + "github.com/jaypipes/ghw/pkg/option" +) + +const ( + testDataSnapshot = "../snapshot/testdata.tar.gz" +) + +// nolint: gocyclo +func TestSnapshotContext(t *testing.T) { + ctx := context.New(option.WithSnapshot(option.SnapshotOptions{ + Path: testDataSnapshot, + })) + + var uncompressedDir string + err := ctx.Do(func() error { + uncompressedDir = ctx.Chroot + return nil + }) + + if uncompressedDir == "" { + t.Fatalf("Expected the uncompressed dir path to not be empty") + } + if err != nil { + t.Fatalf("Expected nil err, but got %v", err) + } + if _, err = os.Stat(uncompressedDir); !os.IsNotExist(err) { + t.Fatalf("Expected the uncompressed dir to be deleted: %s", uncompressedDir) + } +}