Skip to content

Commit

Permalink
fix: ensure binary path is not a directory
Browse files Browse the repository at this point in the history
Signed-off-by: nscuro <[email protected]>
  • Loading branch information
nscuro committed Aug 9, 2021
1 parent 2b197e4 commit d5e9f22
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 4 deletions.
14 changes: 11 additions & 3 deletions internal/cli/cmd/bin/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ import (
"errors"
"flag"
"fmt"
"os"

"github.com/CycloneDX/cyclonedx-gomod/internal/cli/options"
"github.com/CycloneDX/cyclonedx-gomod/internal/util"
)

type BinOptions struct {
Expand Down Expand Up @@ -63,8 +63,16 @@ func (b BinOptions) Validate() error {
}
}

if !util.FileExists(b.BinaryPath) {
errs = append(errs, fmt.Errorf("binary at %s does not exist", b.BinaryPath))
fileInfo, err := os.Stat(b.BinaryPath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
errs = append(errs, fmt.Errorf("binary at %s does not exist", b.BinaryPath))
} else {
return err
}
}
if fileInfo != nil && fileInfo.IsDir() {
errs = append(errs, fmt.Errorf("%s is a directory", b.BinaryPath))
}

if len(errs) > 0 {
Expand Down
27 changes: 27 additions & 0 deletions internal/cli/cmd/bin/options_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package bin

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestBinOptions_Validate(t *testing.T) {
t.Run("BinaryPath Not Exists", func(t *testing.T) {
var binOptions BinOptions
binOptions.BinaryPath = "./doesNotExist"

err := binOptions.Validate()
require.Error(t, err)
require.Contains(t, err.Error(), "does not exist")
})

t.Run("BinaryPath Is Dir", func(t *testing.T) {
var binOptions BinOptions
binOptions.BinaryPath = "./"

err := binOptions.Validate()
require.Error(t, err)
require.Contains(t, err.Error(), "is a directory")
})
}
2 changes: 1 addition & 1 deletion internal/cli/cmd/mod/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import (
"github.com/stretchr/testify/require"
)

func TestOptions_Validate(t *testing.T) {
func TestModOptions_Validate(t *testing.T) {
t.Run("InvalidComponentType", func(t *testing.T) {
var modOptions ModOptions
modOptions.ComponentType = "foobar"
Expand Down

0 comments on commit d5e9f22

Please sign in to comment.