Merge pull request #103 from anchore/issue-81

scope: do not create scope if path is invalid
This commit is contained in:
Alfredo Deza 2020-07-24 15:33:30 -04:00 committed by GitHub
commit 578952986f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 58 additions and 1 deletions

View File

@ -2,6 +2,7 @@ package scope
import (
"fmt"
"os"
"github.com/anchore/stereoscope"
@ -32,7 +33,11 @@ func NewScope(userInput string, o Option) (Scope, func(), error) {
switch protocol.Type {
case directoryProtocol:
// populate the scope object for dir
err := isValidPath(protocol.Value)
if err != nil {
return Scope{}, func() {}, fmt.Errorf("unable to process path, must exist and be a directory: %w", err)
}
s, err := NewScopeFromDir(protocol.Value, o)
if err != nil {
return Scope{}, func() {}, fmt.Errorf("could not populate scope from path (%s): %w", protocol.Value, err)
@ -115,3 +120,18 @@ func (s Scope) Source() interface{} {
return nil
}
// isValidPath ensures that the user-provided input will correspond to a path
// that exists and is a directory
func isValidPath(userInput string) error {
fileMeta, err := os.Stat(userInput)
if err != nil {
return err
}
if fileMeta.IsDir() {
return nil
}
return fmt.Errorf("path is not a directory: %s", userInput)
}

View File

@ -213,3 +213,40 @@ func TestFilesByGlob(t *testing.T) {
})
}
}
func TestIsValidPath(t *testing.T) {
testCases := []struct {
desc string
input string
isError bool
}{
{
desc: "path is valid",
input: "test-fixtures",
isError: false,
},
{
desc: "file is invalid",
input: "test-fixtures/.vimrc",
isError: true,
},
{
desc: "path does not exist",
input: "foo/bar/baz",
isError: true,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
err := isValidPath(test.input)
if err != nil && !test.isError {
t.Errorf("did not expect and error, got: %w", err)
}
if err == nil && test.isError {
t.Errorf("expected an error but didn't get one")
}
})
}
}