Skip to content

Commit

Permalink
Make scan and find path argument optional
Browse files Browse the repository at this point in the history
  • Loading branch information
viktigpetterr committed Dec 7, 2022
1 parent efc56e3 commit 0700150
Show file tree
Hide file tree
Showing 12 changed files with 97 additions and 130 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/debricked.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ jobs:
- run: |
printf "$(go mod graph)\n\n$(go list -mod=readonly -e -m all)" > .debricked-go-dependencies.txt
- run: |
go run cmd/debricked/main.go scan . -t ${{ secrets.DEBRICKED_TOKEN }} -e "**/testdata/**"
go run cmd/debricked/main.go scan -t ${{ secrets.DEBRICKED_TOKEN }} -e "**/testdata/**"
2 changes: 1 addition & 1 deletion pkg/ci/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func (s *Service) Find() (env.Env, error) {
for _, ci := range s.cis {
if ci.Identify() {
m, err := ci.Map()
fmt.Println("Integration", m.Integration)
fmt.Println("Integration:", m.Integration)
return m, err
}
}
Expand Down
29 changes: 5 additions & 24 deletions pkg/cmd/files/find/find.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ package find

import (
"encoding/json"
"errors"
"fmt"
"github.com/debricked/cli/pkg/file"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"os"
"path/filepath"
)

Expand All @@ -27,7 +25,6 @@ func NewFindCmd(finder file.IFinder) *cobra.Command {
Short: "Find all dependency files in inputted path",
Long: `Find all dependency files in inputted path. Related files are grouped together.
For example ` + "`package.json`" + ` with ` + "`package-lock.json`.",
Args: validateArgs,
PreRun: func(cmd *cobra.Command, _ []string) {
_ = viper.BindPFlags(cmd.Flags())
},
Expand Down Expand Up @@ -70,8 +67,11 @@ Format:

func RunE(f file.IFinder) func(_ *cobra.Command, args []string) error {
return func(_ *cobra.Command, args []string) error {
directoryPath := args[0]
fileGroups, err := f.GetGroups(directoryPath, viper.GetStringSlice(ExclusionFlag), viper.GetBool(LockfileOnlyFlag))
path := ""
if len(args) > 0 {
path = args[0]
}
fileGroups, err := f.GetGroups(path, viper.GetStringSlice(ExclusionFlag), viper.GetBool(LockfileOnlyFlag))
if err != nil {
return err
}
Expand All @@ -87,22 +87,3 @@ func RunE(f file.IFinder) func(_ *cobra.Command, args []string) error {
return nil
}
}

func validateArgs(_ *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("requires path")
}
if isValidFilepath(args[0]) {
return nil
}
return fmt.Errorf("invalid path specified: %s", args[0])
}

func isValidFilepath(path string) bool {
_, err := os.ReadDir(path)
if err != nil {
return false
}

return true
}
38 changes: 12 additions & 26 deletions pkg/cmd/files/find/find_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"github.com/debricked/cli/pkg/file"
"github.com/debricked/cli/pkg/file/testdata"
"github.com/spf13/viper"
"strings"
"testing"
)

Expand Down Expand Up @@ -63,6 +62,18 @@ func TestRunE(t *testing.T) {
}
}

func TestRunENoPath(t *testing.T) {
f := testdata.NewFinderMock()
groups := file.Groups{}
groups.Add(file.Group{})
f.SetGetGroupsReturnMock(groups, nil)
runE := RunE(f)
err := runE(nil, []string{})
if err != nil {
t.Fatal("failed to assert that no error occurred. Error:", err)
}
}

func TestRunENoFiles(t *testing.T) {
f := testdata.NewFinderMock()
groups := file.Groups{}
Expand All @@ -86,28 +97,3 @@ func TestRunEError(t *testing.T) {
t.Fatal("failed to assert that error occured")
}
}

func TestValidateArgs(t *testing.T) {
err := validateArgs(nil, []string{"."})
if err != nil {
t.Error("failed to assert that no error occurred")
}
}

func TestValidateArgsInvalidArgs(t *testing.T) {
err := validateArgs(nil, []string{})
if err == nil {
t.Error("failed to assert that an error occurred")
}
if !strings.Contains(err.Error(), "requires path") {
t.Error("failed to assert error message")
}

err = validateArgs(nil, []string{"invalid-path"})
if err == nil {
t.Error("failed to assert that an error occurred")
}
if !strings.Contains(err.Error(), "invalid path specified") {
t.Error("failed to assert error message")
}
}
28 changes: 5 additions & 23 deletions pkg/cmd/scan/scan.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"github.com/fatih/color"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"os"
"path/filepath"
)

Expand Down Expand Up @@ -46,7 +45,6 @@ func NewScanCmd(c *client.IDebClient) *cobra.Command {
Short: "Start a Debricked dependency scan",
Long: `All supported dependency files will be scanned and analysed.
If the given path contains a git repository all flags but "integration" will be resolved. Otherwise they have to specified.`,
Args: ValidateArgs,
PreRun: func(cmd *cobra.Command, _ []string) {
_ = viper.BindPFlags(cmd.Flags())
},
Expand Down Expand Up @@ -85,9 +83,12 @@ $ debricked scan . `+exampleFlags)

func RunE(s *scan.IScanner) func(_ *cobra.Command, args []string) error {
return func(_ *cobra.Command, args []string) error {
directoryPath := args[0]
path := ""
if len(args) > 0 {
path = args[0]
}
options := scan.DebrickedOptions{
DirectoryPath: directoryPath,
Path: path,
Exclusions: viper.GetStringSlice(ExclusionFlag),
RepositoryName: viper.GetString(RepositoryFlag),
CommitName: viper.GetString(CommitFlag),
Expand All @@ -109,22 +110,3 @@ func RunE(s *scan.IScanner) func(_ *cobra.Command, args []string) error {
return scanCmdError
}
}

func ValidateArgs(_ *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("requires directory path")
}
if isValidFilepath(args[0]) {
return nil
}
return fmt.Errorf("invalid directory path specified: %s", args[0])
}

func isValidFilepath(path string) bool {
_, err := os.ReadDir(path)
if err != nil {
return false
}

return true
}
33 changes: 8 additions & 25 deletions pkg/cmd/scan/scan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,38 +45,21 @@ func TestNewScanCmd(t *testing.T) {
}
}

func TestValidateArgs(t *testing.T) {
err := ValidateArgs(nil, []string{"/"})
func TestRunE(t *testing.T) {
var s scan.IScanner
s = &scannerMock{}
runE := RunE(&s)
err := runE(nil, []string{"."})
if err != nil {
t.Error("failed to assert that no error occurred. Error:", err)
}
}

func TestValidateArgsMissingArg(t *testing.T) {
err := ValidateArgs(nil, []string{})
if err == nil {
t.Error("failed to assert that an error occurred")
}
if !strings.Contains(err.Error(), "requires directory path") {
t.Error("failed assert error")
}
}

func TestValidateArgsInvalidArg(t *testing.T) {
err := ValidateArgs(nil, []string{"invalid-path"})
if err == nil {
t.Error("failed to assert that an error occurred")
}
if !strings.Contains(err.Error(), "invalid directory path specified") {
t.Error("failed assert error")
t.Fatal("failed to assert that no error occurred. Error:", err)
}
}

func TestRunE(t *testing.T) {
func TestRunENoPath(t *testing.T) {
var s scan.IScanner
s = &scannerMock{}
runE := RunE(&s)
err := runE(nil, []string{"."})
err := runE(nil, []string{})
if err != nil {
t.Fatal("failed to assert that no error occurred. Error:", err)
}
Expand Down
3 changes: 3 additions & 0 deletions pkg/file/finder.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ func (finder *Finder) GetGroups(rootPath string, exclusions []string, lockfileOn
if err != nil {
return groups, err
}
if len(rootPath) == 0 {
rootPath = filepath.Base("")
}

// Traverse files to find dependency file groups
err = filepath.Walk(
Expand Down
6 changes: 3 additions & 3 deletions pkg/file/finder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,21 +110,21 @@ func TestGetSupportedFormatsFailed(t *testing.T) {

func TestGetGroups(t *testing.T) {
setUp(true)
directoryPath := "."
path := ""

exclusions := []string{"testdata/go/*.mod", "testdata/misc/**"}
excludedFiles := []string{"testdata/go/go.mod", "testdata/misc/requirements.txt"}
const nbrOfGroups = 2

fileGroups, err := finder.GetGroups(directoryPath, exclusions, false)
fileGroups, err := finder.GetGroups(path, exclusions, false)
if err != nil {
t.Fatal("failed to assert that no error occurred. Error:", err)
}
if fileGroups.Size() != nbrOfGroups {
t.Error(fmt.Sprintf("failed to assert that %d groups were created. %d was found", nbrOfGroups, fileGroups.Size()))
}
for _, fileGroup := range fileGroups.ToSlice() {
hasContent := fileGroup.CompiledFormat != nil && (strings.Contains(fileGroup.FilePath, directoryPath) || len(fileGroup.RelatedFiles) > 0)
hasContent := fileGroup.CompiledFormat != nil && (strings.Contains(fileGroup.FilePath, path) || len(fileGroup.RelatedFiles) > 0)
if !hasContent {
t.Error("failed to assert that format had content")
}
Expand Down
8 changes: 4 additions & 4 deletions pkg/git/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ func FindRemoteUrl(repository *git.Repository) (string, error) {
return remoteURL, err
}

func FindRepositoryName(repository *git.Repository, directoryPath string) (string, error) {
absolutePath, _ := filepath.Abs(directoryPath)
func FindRepositoryName(repository *git.Repository, path string) (string, error) {
absolutePath, _ := filepath.Abs(path)
repositoryName := filepath.Base(absolutePath)
gitRemoteUrl, err := FindRemoteUrl(repository)
if err != nil {
Expand All @@ -108,8 +108,8 @@ func ParseGitRemoteUrl(gitRemoteUrl string) (string, error) {
return gitRemoteUrl, errors.New("failed to parse git remote URL. git/https regular expressions had no matches")
}

func FindRepository(directoryPath string) (*git.Repository, error) {
return git.PlainOpen(directoryPath)
func FindRepository(path string) (*git.Repository, error) {
return git.PlainOpen(path)
}

func FindBranch(repository *git.Repository) (string, error) {
Expand Down
8 changes: 4 additions & 4 deletions pkg/git/meta_object.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ type MetaObject struct {
Author string
}

// NewMetaObject returns MetaObject based on git repository existing on directoryPath. Otherwise, inputted arguments are used
func NewMetaObject(directoryPath string, repositoryName string, commit string, branchName string, commitAuthor string, url string) (*MetaObject, error) {
repository, err := FindRepository(directoryPath)
// NewMetaObject returns MetaObject based on git repository existing on path. Otherwise, inputted arguments are used
func NewMetaObject(path string, repositoryName string, commit string, branchName string, commitAuthor string, url string) (*MetaObject, error) {
repository, err := FindRepository(path)
if err == nil {
isSet := func(attribute string) bool { return len(attribute) > 0 }

if !isSet(repositoryName) {
repositoryName, err = FindRepositoryName(repository, directoryPath)
repositoryName, err = FindRepositoryName(repository, path)
if err != nil {
log.Println(err.Error())
}
Expand Down
11 changes: 5 additions & 6 deletions pkg/scan/scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ type DebrickedScanner struct {
}

type DebrickedOptions struct {
DirectoryPath string
Path string
Exclusions []string
RepositoryName string
CommitName string
Expand Down Expand Up @@ -70,7 +70,7 @@ func (dScanner *DebrickedScanner) Scan(o IOptions) error {
MapEnvToOptions(&dOptions, e)

gitMetaObject, err := git.NewMetaObject(
dOptions.DirectoryPath,
dOptions.Path,
dOptions.RepositoryName,
dOptions.CommitName,
dOptions.BranchName,
Expand All @@ -81,7 +81,7 @@ func (dScanner *DebrickedScanner) Scan(o IOptions) error {
return err
}

fileGroups, err := dScanner.finder.GetGroups(dOptions.DirectoryPath, dOptions.Exclusions, false)
fileGroups, err := dScanner.finder.GetGroups(dOptions.Path, dOptions.Exclusions, false)
if err != nil {
return err
}
Expand Down Expand Up @@ -128,9 +128,8 @@ func MapEnvToOptions(o *DebrickedOptions, env env.Env) {
o.IntegrationName = env.Integration
}
}

if len(o.DirectoryPath) == 0 {
o.DirectoryPath = env.Filepath
if len(env.Filepath) > 0 {
o.Path = env.Filepath
}
}

Expand Down
Loading

0 comments on commit 0700150

Please sign in to comment.