Skip to content

Commit

Permalink
Add linter check support (#679)
Browse files Browse the repository at this point in the history
* add linter supports

* add only minor version

* use latest version

* Fix println with format issue

* Fix test

* Fix tests

* For slice with unknown length, preallocating the array

* fix code-coverage

* Removed linter rules

* Reverting linter fixes, adding TODO for later

* Ignore linter error for import

* Remove another err var.

* Ignore shadow error

* Fixes

* Fix issue

* Add back goimports local-prefixes

* Update local prefixes

* Removed extra spaces and merge the imports

* more refactoring

* Update photon.go

Co-authored-by: Teppei Fukuda <[email protected]>
  • Loading branch information
rahul2393 and knqyf263 authored Oct 20, 2020
1 parent 4a94477 commit 793a1aa
Show file tree
Hide file tree
Showing 67 changed files with 519 additions and 148 deletions.
12 changes: 12 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
name: Test
on: pull_request
jobs:
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: golangci-lint
uses: golangci/golangci-lint-action@v2
with:
version: v1.31
args: --deadline=30m

integration:
name: Integration Test
runs-on: ubuntu-latest
Expand Down Expand Up @@ -34,3 +45,4 @@ jobs:
with:
version: latest
args: release --snapshot --rm-dist --skip-publish

71 changes: 71 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
linters-settings:
errcheck:
check-type-assertions: true
check-blank: true
govet:
check-shadowing: false
gofmt:
simplify: false
golint:
min-confidence: 0
gocyclo:
min-complexity: 10
maligned:
suggest-new: true
dupl:
threshold: 100
goconst:
min-len: 3
min-occurrences: 3
misspell:
locale: US
goimports:
local-prefixes: github.com/aquasecurity

linters:
disable-all: true
enable:
- structcheck
- ineffassign
- typecheck
- govet
- errcheck
- varcheck
- deadcode
- golint
- gosec
- unconvert
- goconst
- gocyclo
- gofmt
- goimports
- maligned
- misspell

run:
skip-files:
- ".*._mock.go$"
- ".*._test.go$"
- "integration/*"

issues:
exclude-rules:
- linters:
- gosec
text: "G304: Potential file inclusion"
- linters:
- gosec
text: "Deferring unsafe method"
- linters:
- errcheck
text: "Close` is not checked"
- linters:
- errcheck
text: "os.*` is not checked"
- linters:
- golint
text: "a blank import should be only in a main or test package"
exclude:
- "should have a package comment, unless it's in another file for this package"
exclude-use-default: false
max-same-issues: 0
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@ require (
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1
k8s.io/utils v0.0.0-20191114184206-e782cd3c129f
)
)
2 changes: 1 addition & 1 deletion go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -748,4 +748,4 @@ moul.io/http2curl v1.0.0 h1:6XwpyZOYsgZJrU8exnG87ncVkU1FVCcTRpwzOkTDUi8=
moul.io/http2curl v1.0.0/go.mod h1:f6cULg+e4Md/oW1cYmwW4IWQOVl2lGbmCNGOHvzX2kE=
sigs.k8s.io/structured-merge-diff v0.0.0-20190525122527-15d366b2352e/go.mod h1:wWxsB5ozmmv/SG7nM11ayaAW51xMvak/t1r0CSlcokI=
sigs.k8s.io/structured-merge-diff v1.0.1-0.20191108220359-b1b620dd3f06/go.mod h1:/ULNhyfzRopfcjskuui0cTITekDduZ7ycKN3oUT9R18=
sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o=
sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o=
7 changes: 6 additions & 1 deletion integration/docker/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ import (
"github.com/docker/docker/api/types"
)

// RegistryConfig holds the config for docker registry
type RegistryConfig struct {
URL *url.URL
Username string
Password string
}

// GetAuthConfig returns the docker registry authConfig
func (c RegistryConfig) GetAuthConfig() types.AuthConfig {
return types.AuthConfig{
Username: c.Username,
Expand All @@ -29,6 +31,7 @@ func (c RegistryConfig) GetAuthConfig() types.AuthConfig {
}
}

// GetRegistryAuth returns the json encoded docker registry auth
func (c RegistryConfig) GetRegistryAuth() (string, error) {
authConfig := types.AuthConfig{
Username: c.Username,
Expand All @@ -41,10 +44,12 @@ func (c RegistryConfig) GetRegistryAuth() (string, error) {
return base64.URLEncoding.EncodeToString(encodedJSON), nil
}

// Docker returns docker client
type Docker struct {
cli *client.Client
}

// New is the factory method to return docker client
func New() (Docker, error) {
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
Expand Down Expand Up @@ -73,7 +78,7 @@ func (d Docker) ReplicateImage(ctx context.Context, imageRef, imagePath string,
if err != nil {
return err
}
if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil {
if _, err = io.Copy(ioutil.Discard, resp.Body); err != nil {
return err
}
defer resp.Body.Close()
Expand Down
11 changes: 9 additions & 2 deletions internal/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"github.com/aquasecurity/trivy/pkg/vulnerability"
)

// VersionInfo holds the trivy DB version Info
type VersionInfo struct {
Version string `json:",omitempty"`
VulnerabilityDB *db.Metadata `json:",omitempty"`
Expand Down Expand Up @@ -250,6 +251,7 @@ var (
}
)

// NewApp is the factory method to return Trivy CLI
func NewApp(version string) *cli.App {
cli.VersionPrinter = func(c *cli.Context) {
showVersion(c.String("cache-dir"), c.String("format"), c.App.Version, c.App.Writer)
Expand Down Expand Up @@ -307,7 +309,7 @@ func setHidden(flags []cli.Flag, hidden bool) []cli.Flag {
func showVersion(cacheDir, outputFormat, version string, outputWriter io.Writer) {
var dbMeta *db.Metadata

metadata, _ := tdb.NewMetadata(afero.NewOsFs(), cacheDir).Get()
metadata, _ := tdb.NewMetadata(afero.NewOsFs(), cacheDir).Get() // nolint: errcheck
if !metadata.UpdatedAt.IsZero() && !metadata.NextUpdate.IsZero() && metadata.Version != 0 {
dbMeta = &db.Metadata{
Version: metadata.Version,
Expand All @@ -319,7 +321,7 @@ func showVersion(cacheDir, outputFormat, version string, outputWriter io.Writer)

switch outputFormat {
case "json":
b, _ := json.Marshal(VersionInfo{
b, _ := json.Marshal(VersionInfo{ // nolint: errcheck
Version: version,
VulnerabilityDB: dbMeta,
})
Expand All @@ -345,6 +347,7 @@ func showVersion(cacheDir, outputFormat, version string, outputWriter io.Writer)
}
}

// NewImageCommand is the factory method to add image command
func NewImageCommand() *cli.Command {
return &cli.Command{
Name: "image",
Expand All @@ -356,6 +359,7 @@ func NewImageCommand() *cli.Command {
}
}

// NewFilesystemCommand is the factory method to add filesystem command
func NewFilesystemCommand() *cli.Command {
return &cli.Command{
Name: "filesystem",
Expand Down Expand Up @@ -389,6 +393,7 @@ func NewFilesystemCommand() *cli.Command {
}
}

// NewRepositoryCommand is the factory method to add repository command
func NewRepositoryCommand() *cli.Command {
return &cli.Command{
Name: "repository",
Expand Down Expand Up @@ -422,6 +427,7 @@ func NewRepositoryCommand() *cli.Command {
}
}

// NewClientCommand is the factory method to add client command
func NewClientCommand() *cli.Command {
return &cli.Command{
Name: "client",
Expand Down Expand Up @@ -465,6 +471,7 @@ func NewClientCommand() *cli.Command {
}
}

// NewServerCommand is the factory method to add server command
func NewServerCommand() *cli.Command {
return &cli.Command{
Name: "server",
Expand Down
9 changes: 9 additions & 0 deletions internal/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,12 @@ Vulnerability DB:
})
}
}

func TestNewCommands(t *testing.T) {
NewApp("test")
NewClientCommand()
NewFilesystemCommand()
NewImageCommand()
NewRepositoryCommand()
NewServerCommand()
}
12 changes: 11 additions & 1 deletion internal/artifact/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/aquasecurity/trivy/internal/config"
)

// Config holds the artifact config
type Config struct {
config.GlobalConfig
config.ArtifactConfig
Expand All @@ -22,6 +23,7 @@ type Config struct {
autoRefresh bool
}

// New is the factory method to return config
func New(c *cli.Context) (Config, error) {
gc, err := config.NewGlobalConfig(c)
if err != nil {
Expand All @@ -41,6 +43,7 @@ func New(c *cli.Context) (Config, error) {
}, nil
}

// Init initializes the artifact config
func (c *Config) Init(image bool) error {
if err := c.ReportConfig.Init(c.Logger); err != nil {
return err
Expand All @@ -53,7 +56,7 @@ func (c *Config) Init(image bool) error {
}

// --clear-cache, --download-db-only and --reset don't conduct the scan
if c.ClearCache || c.DownloadDBOnly || c.Reset {
if c.skipScan() {
return nil
}

Expand All @@ -69,3 +72,10 @@ func (c *Config) Init(image bool) error {

return nil
}

func (c *Config) skipScan() bool {
if c.ClearCache || c.DownloadDBOnly || c.Reset {
return true
}
return false
}
1 change: 1 addition & 0 deletions internal/artifact/fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ func filesystemScanner(ctx context.Context, dir string, ac cache.ArtifactCache,
return s, cleanup, nil
}

// FilesystemRun runs scan on filesystem
func FilesystemRun(cliCtx *cli.Context) error {
c, err := config.New(cliCtx)
if err != nil {
Expand Down
1 change: 1 addition & 0 deletions internal/artifact/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ func dockerScanner(ctx context.Context, imageName string, ac cache.ArtifactCache
return s, cleanup, nil
}

// ImageRun runs scan on docker image
func ImageRun(cliCtx *cli.Context) error {
c, err := config.New(cliCtx)
if err != nil {
Expand Down
1 change: 1 addition & 0 deletions internal/artifact/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ func repositoryScanner(ctx context.Context, dir string, ac cache.ArtifactCache,
return s, cleanup, nil
}

// RepositoryRun runs scan on repository
func RepositoryRun(cliCtx *cli.Context) error {
c, err := config.New(cliCtx)
if err != nil {
Expand Down
3 changes: 3 additions & 0 deletions internal/artifact/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@ import (
"github.com/aquasecurity/trivy/pkg/utils"
)

// InitializeScanner type to define initialize function signature
type InitializeScanner func(context.Context, string, cache.ArtifactCache, cache.LocalArtifactCache, time.Duration) (
scanner.Scanner, func(), error)

// nolint: gocyclo
// TODO: refactror and fix cyclometic complexity
func run(c config.Config, initializeScanner InitializeScanner) error {
if err := log.InitLogger(c.Debug, c.Quiet); err != nil {
l.Fatal(err)
Expand Down
3 changes: 3 additions & 0 deletions internal/client/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/aquasecurity/trivy/internal/config"
)

// Config holds the Trivy client config
type Config struct {
config.GlobalConfig
config.ArtifactConfig
Expand All @@ -25,6 +26,7 @@ type Config struct {
CustomHeaders http.Header
}

// New is the factory method for Config
func New(c *cli.Context) (Config, error) {
gc, err := config.NewGlobalConfig(c)
if err != nil {
Expand All @@ -43,6 +45,7 @@ func New(c *cli.Context) (Config, error) {
}, nil
}

// Init initializes the config
func (c *Config) Init() (err error) {
// --clear-cache doesn't conduct the scan
if c.ClearCache {
Expand Down
3 changes: 3 additions & 0 deletions internal/client/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/aquasecurity/trivy/pkg/utils"
)

// Run runs the scan
func Run(cliCtx *cli.Context) error {
c, err := config.New(cliCtx)
if err != nil {
Expand All @@ -25,6 +26,8 @@ func Run(cliCtx *cli.Context) error {
return run(c)
}

// nolint: gocyclo
// TODO: refactror and fix cyclometic complexity
func run(c config.Config) (err error) {
if err = log.InitLogger(c.Debug, c.Quiet); err != nil {
return xerrors.Errorf("failed to initialize a logger: %w", err)
Expand Down
5 changes: 4 additions & 1 deletion internal/config/artifact.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"golang.org/x/xerrors"
)

// ArtifactConfig holds the config for a artifact scanning
type ArtifactConfig struct {
Input string
Timeout time.Duration
Expand All @@ -24,6 +25,7 @@ type ArtifactConfig struct {
Target string
}

// NewArtifactConfig is the factory method to return artifact config
func NewArtifactConfig(c *cli.Context) ArtifactConfig {
return ArtifactConfig{
Input: c.String("input"),
Expand All @@ -34,10 +36,11 @@ func NewArtifactConfig(c *cli.Context) ArtifactConfig {
}
}

// Init initialize the CLI context for artifact scanning
func (c *ArtifactConfig) Init(ctx *cli.Context, logger *zap.SugaredLogger) (err error) {
if c.Input == "" && ctx.Args().Len() == 0 {
logger.Debug(`trivy requires at least 1 argument or --input option`)
_ = cli.ShowSubcommandHelp(ctx)
_ = cli.ShowSubcommandHelp(ctx) // nolint: errcheck
os.Exit(0)
} else if ctx.Args().Len() > 1 {
logger.Error(`multiple targets cannot be specified`)
Expand Down
Loading

0 comments on commit 793a1aa

Please sign in to comment.