Skip to content

Commit

Permalink
lint fixes (#542)
Browse files Browse the repository at this point in the history
* lint fixes

* lint fixes

* lint

* lint

* lint

* lint

* try

* try
  • Loading branch information
ChanochShayner authored Jul 25, 2024
1 parent faa4f82 commit b7795e4
Show file tree
Hide file tree
Showing 17 changed files with 50 additions and 65 deletions.
12 changes: 5 additions & 7 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -51,26 +51,24 @@ output:
# make issues output unique by line, default is true
uniq-by-line: true
issues:
max-issues-per-linter: 0
max-same-issues: 0
max-issues-per-linter: 100
max-same-issues: 100
exclude-dirs:
- "tests/yor_plugins"
linters:
enable:
- deadcode
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- structcheck
- typecheck
- unused
- varcheck
- gofmt
- golint
- goimports
- gocritic
- unconvert
- unparam
- gocritic
- golint
- revive
fast: true
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func listTagGroupsCommand() *cli.Command {
return &cli.Command{
Name: "list-tag-groups",
Usage: "List the tag groups that will be applied by yor",
Action: func(c *cli.Context) error {
Action: func(_ *cli.Context) error {
return listTagGroups()
},
}
Expand Down
1 change: 1 addition & 0 deletions src/cloudformation/structure/cloudformation_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ func (p *CloudformationParser) extractTagsAndLines(filePath string, lines *struc
func (p *CloudformationParser) GetExistingTags(tagsValue reflect.Value) []tags.ITag {
existingTags := make([]goformationTags.Tag, 0)
if tagsValue.Kind() == reflect.Slice {
//nolint:ineffassign
ok := true
existingTags, ok = tagsValue.Interface().([]goformationTags.Tag)
if !ok {
Expand Down
14 changes: 7 additions & 7 deletions src/common/clioptions/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
)

func TestCliArgParsing(t *testing.T) {
t.Run("Tag local options flag", func(t *testing.T) {
t.Run("Tag local options flag", func(_ *testing.T) {
options := TagOptions{
Directory: "some/dir",
Tag: nil,
Expand All @@ -26,7 +26,7 @@ func TestCliArgParsing(t *testing.T) {
// Expect the validation to pass without throwing errors
options.Validate()
})
t.Run("Test tag argument parsing - valid output", func(t *testing.T) {
t.Run("Test tag argument parsing - valid output", func(_ *testing.T) {
options := TagOptions{
Directory: "some/dir",
Tag: nil,
Expand All @@ -53,7 +53,7 @@ func TestCliArgParsing(t *testing.T) {
assert.Fail(t, "Should have failed already")
})

t.Run("Test tag argument parsing - valid tag groups", func(t *testing.T) {
t.Run("Test tag argument parsing - valid tag groups", func(_ *testing.T) {
options := TagOptions{
Directory: "some/dir",
Tag: nil,
Expand Down Expand Up @@ -88,7 +88,7 @@ func TestCliArgParsing(t *testing.T) {
assert.Fail(t, "Should have failed already")
})

t.Run("Test CLI argument parsing - list-tags - valid output", func(t *testing.T) {
t.Run("Test CLI argument parsing - list-tags - valid output", func(_ *testing.T) {
options := ListTagsOptions{
TagGroups: []string{"simple", "git"},
}
Expand All @@ -97,7 +97,7 @@ func TestCliArgParsing(t *testing.T) {
})
}

func TestOutputCrasher(t *testing.T) {
func TestOutputCrasher(_ *testing.T) {
if os.Getenv("UT_CRASH") == "RUN" {
options := TagOptions{
Directory: "some/dir",
Expand All @@ -114,7 +114,7 @@ func TestOutputCrasher(t *testing.T) {
}
}

func TestTagGroupCrasher(t *testing.T) {
func TestTagGroupCrasher(_ *testing.T) {
if os.Getenv("UT_CRASH") == "RUN" {
options := TagOptions{
Directory: "some/dir",
Expand All @@ -131,7 +131,7 @@ func TestTagGroupCrasher(t *testing.T) {
}
}

func TestListTagsGroupCrasher(t *testing.T) {
func TestListTagsGroupCrasher(_ *testing.T) {
if os.Getenv("UT_CRASH") == "RUN" {
options := ListTagsOptions{
TagGroups: []string{"custom"},
Expand Down
2 changes: 1 addition & 1 deletion src/common/json/json_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ func AddTagsToResourceStr(fullOriginStr string, resourceBlock structure.IBlock,
// { "Key": "some-key", "Value": "some-val" }
// ]
tagBlockIndent = tagBlockIndent[0 : len(tagBlockIndent)-1]

}

// unmarshal updated tags with the indent matching origin file. This will create the tags with the `[]` wrapping which will be discarded later
Expand Down Expand Up @@ -155,7 +156,6 @@ func AddTagsToResourceStr(fullOriginStr string, resourceBlock structure.IBlock,
parentIdentifier = FindParentIdentifier(jsonResourceStr, parentIdentifier)
if parentIdentifier == "" {
identifiersToAdd = append(identifiersToAdd, resourceBlock.GetResourceID())
parentIdentifier = resourceBlock.GetResourceID()
break
}
indexOfParent = findJSONKeyIndex(resourceStr, parentIdentifier)
Expand Down
11 changes: 5 additions & 6 deletions src/common/logger/logging_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@ import (
)

type loggingService struct {
logLevel LogLevel
stdout *os.File
stderr *os.File
tempWriter *os.File
disabled bool
muteLock sync.Mutex
logLevel LogLevel
stdout *os.File
stderr *os.File
disabled bool
muteLock sync.Mutex
}

type LogLevel int
Expand Down
6 changes: 3 additions & 3 deletions src/common/reports/report_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,10 @@ func init() {

func (r *ReportService) Changed() bool {
changesAccumulator := TagChangeAccumulatorInstance
new_count := len(changesAccumulator.NewBlockTraces)
updated_count := len(changesAccumulator.UpdatedBlockTraces)
newCount := len(changesAccumulator.NewBlockTraces)
updatedCount := len(changesAccumulator.UpdatedBlockTraces)

return new_count > 0 || updated_count > 0
return newCount > 0 || updatedCount > 0
}

func (r *ReportService) GetReport() *Report {
Expand Down
4 changes: 2 additions & 2 deletions src/common/runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ type Runner struct {
skippedResources []string
workersNum int
dryRun bool
localModuleTag bool
}

const WorkersNumEnvKey = "YOR_WORKER_NUM"
Expand Down Expand Up @@ -92,7 +91,8 @@ func (r *Runner) Init(commands *clioptions.TagOptions) error {
r.reportingService = reports.ReportServiceInst
r.dir = commands.Directory
r.skippedTags = commands.SkipTags
r.skipDirs = append(commands.SkipDirs, ".git")
commands.SkipDirs = append(commands.SkipDirs, ".git")
r.skipDirs = commands.SkipDirs
r.configFilePath = commands.ConfigFile
r.dryRun = commands.DryRun
if utils.InSlice(r.skipDirs, r.dir) {
Expand Down
12 changes: 6 additions & 6 deletions src/common/runner/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ func TestRunnerInternals(t *testing.T) {
TagPrefix: "prefix_",
})

_ = filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error {
_ = filepath.Walk(rootDir, func(path string, info os.FileInfo, _ error) error {
if !info.IsDir() {
isFileSkipped := runner.isFileSkipped(&terraformStructure.TerraformParser{}, path)
if isFileSkipped {
Expand Down Expand Up @@ -299,11 +299,11 @@ func Test_YorNameTag(t *testing.T) {
yorNameCounter := 0
for _, newTag := range report.NewResourceTags {
if newTag.TagKey == tags.YorNameTagKey {
yorNameCounter += 1
resourceIdParts := strings.Split(newTag.ResourceID, ".")
resourceName := resourceIdParts[0]
if len(resourceIdParts) > 1 {
resourceName = resourceIdParts[1]
yorNameCounter++
resourceIDParts := strings.Split(newTag.ResourceID, ".")
resourceName := resourceIDParts[0]
if len(resourceIDParts) > 1 {
resourceName = resourceIDParts[1]
}
assert.Equal(t, resourceName, newTag.UpdatedValue)
}
Expand Down
1 change: 1 addition & 0 deletions src/common/tagging/code2cloud/tag_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package code2cloud

import (
"fmt"

"github.com/bridgecrewio/yor/src/common/logger"
"github.com/bridgecrewio/yor/src/common/structure"
"github.com/bridgecrewio/yor/src/common/tagging"
Expand Down
4 changes: 3 additions & 1 deletion src/common/tagging/code2cloud/yor_name.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package code2cloud

import (
"fmt"

"reflect"

"github.com/bridgecrewio/yor/src/common/structure"
"github.com/bridgecrewio/yor/src/common/tagging/tags"
"reflect"
)

type YorNameTag struct {
Expand Down
13 changes: 6 additions & 7 deletions src/common/tagging/external/tag_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,11 @@ func (t Tag) SatisfyFilters(block structure.IBlock) bool {

case "directory":
prefixes := make([]string, 0)
switch filterValue := filterValue.(type) {
case []interface{}:
for _, e := range filterValue {
prefixes = append(prefixes, e.(string))
if filterValues, ok := filterValue.([]interface{}); ok {
for _, prefix := range filterValues {
prefixes = append(prefixes, prefix.(string))
}
case interface{}:
} else {
prefixes = append(prefixes, filterValue.(string))
}
found := false
Expand Down Expand Up @@ -111,7 +110,7 @@ func (t *TagGroup) InitExternalTagGroups(configFilePath string, useCodeOwners bo

}

func (t *TagGroup) InitTagGroup(dir string, skippedTags []string, explicitlySpecifiedTags []string, options ...tagging.InitTagGroupOption) {
func (t *TagGroup) InitTagGroup(dir string, skippedTags []string, explicitlySpecifiedTags []string, _ ...tagging.InitTagGroupOption) {
t.SkippedTags = skippedTags
t.SpecifiedTags = explicitlySpecifiedTags
t.Dir = dir
Expand Down Expand Up @@ -223,7 +222,7 @@ func (t *TagGroup) CalculateTagValue(block structure.IBlock, tag Tag) (tags.ITag
if blockTagKey == tags.GitModifiersTagKey {
for _, val := range strings.Split(blockTagValue, "/") {
if utils.InSlice(tagMatchStrings, val) {
gitModifiersCounts[matchValue] += 1
gitModifiersCounts[matchValue]++
}
}
} else if utils.InSlice(tagMatchStrings, blockTagValue) {
Expand Down
2 changes: 1 addition & 1 deletion src/common/tagging/simple/tag_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type TagGroup struct {
tagging.TagGroup
}

func (t *TagGroup) InitTagGroup(_ string, skippedTags []string, explicitlySpecifiedTags []string, options ...tagging.InitTagGroupOption) {
func (t *TagGroup) InitTagGroup(_ string, skippedTags []string, explicitlySpecifiedTags []string, _ ...tagging.InitTagGroupOption) {
t.SkippedTags = skippedTags
t.SpecifiedTags = explicitlySpecifiedTags
envTagsStr := os.Getenv("YOR_SIMPLE_TAGS")
Expand Down
19 changes: 3 additions & 16 deletions src/common/yaml/yaml_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func WriteYAMLFile(readFilePath string, blocks []structure.IBlock, writeFilePath
}
for _, resourceBlock := range blocks {
rawBlock := resourceBlock.GetRawBlock()
newResourceLines := getYAMLLines(rawBlock, isCfn)
newResourceLines := getYAMLLines(rawBlock)
newResourceTagLineRange, _ := FindTagsLinesYAML(newResourceLines, tagsAttributeName)
oldResourceLinesRange := resourceBlock.GetLines()
oldResourceLines := originLines[oldResourceLinesRange.Start : oldResourceLinesRange.End+1]
Expand Down Expand Up @@ -213,7 +213,7 @@ func computeResourcesLineRange(originLines []string, blocks []structure.IBlock,
return ret
}

func getYAMLLines(rawBlock interface{}, isCfn bool) []string {
func getYAMLLines(rawBlock interface{}) []string {
var textLines []string
yamlBytes, err := yaml.Marshal(rawBlock)
if err != nil {
Expand All @@ -225,20 +225,6 @@ func getYAMLLines(rawBlock interface{}, isCfn bool) []string {
return textLines
}

func removeLineByAttribute(textLines []string, attribute string) []string {
vpcLineIndex := -1
for i, line := range textLines {
if strings.Contains(line, attribute) {
vpcLineIndex = i
break
}
}
if vpcLineIndex != -1 {
textLines = append(textLines[:vpcLineIndex], textLines[vpcLineIndex+1:]...)
}
return textLines
}

func FindTagsLinesYAML(textLines []string, tagsAttributeName string) (structure.Lines, bool) {
tagsLines := structure.Lines{Start: -1, End: -1}
var lineIndent string
Expand Down Expand Up @@ -307,6 +293,7 @@ func MapResourcesLineYAML(filePath string, resourceNames []string, resourcesStar
lineIndent := countLeadingSpaces(line)
if lineIndent <= resourcesIndent && strings.TrimSpace(line) != "" && !strings.Contains(line, "#") {
// No longer inside resources block, get the last line of the previous resource if exists
//nolint:ineffassign
readResources = false
if latestResourceName != "" {
resourceToLines[latestResourceName].End = findLastNonEmptyLine(fileLines, i-1)
Expand Down
6 changes: 2 additions & 4 deletions src/serverless/structure/serverless_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ package structure
import (
"encoding/json"
"fmt"
"github.com/bridgecrewio/goformation/v5/intrinsics"
"math"
"os"
"path/filepath"
"strings"
"sync"

"github.com/bridgecrewio/goformation/v5/intrinsics"
"github.com/bridgecrewio/yor/src/common"
"github.com/bridgecrewio/yor/src/common/logger"
"github.com/bridgecrewio/yor/src/common/structure"
Expand Down Expand Up @@ -38,9 +38,7 @@ func (p *ServerlessParser) Init(rootDir string, _ map[string]string) {
p.YamlParser.RootDir = rootDir
}

func (p *ServerlessParser) Close() {
return
}
func (p *ServerlessParser) Close() {}

func (p *ServerlessParser) GetSkippedDirs() []string {
return []string{}
Expand Down
4 changes: 2 additions & 2 deletions src/terraform/structure/terraform_block.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func (b *TerraformBlock) IsGCPBlock() bool {
}

func (b *TerraformBlock) GetResourceName() string {
resourceId := b.GetResourceID()
resourceID := b.GetResourceID()
resourceType := b.GetResourceType()
return strings.ReplaceAll(resourceId, strings.Join([]string{resourceType, ""}, "."), "")
return strings.ReplaceAll(resourceID, strings.Join([]string{resourceType, ""}, "."), "")
}
2 changes: 1 addition & 1 deletion src/terraform/structure/terraform_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func (p *TerraformParser) Init(rootDir string, args map[string]string) {

func (p *TerraformParser) Close() {
logger.MuteOutputBlock(func() {
p.providerToClientMap.Range(func(provider, iClient interface{}) bool {
p.providerToClientMap.Range(func(_, iClient interface{}) bool {
client := iClient.(tfschema.Client)
client.Close()
return true
Expand Down

0 comments on commit b7795e4

Please sign in to comment.