Skip to content

Commit

Permalink
linter fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
TomerHeber committed Sep 24, 2024
1 parent b3ad0f1 commit 4d884a7
Show file tree
Hide file tree
Showing 18 changed files with 163 additions and 37 deletions.
5 changes: 0 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,6 @@ jobs:
- name: Go vet
run: |
! go vet ./... | read
- name: Go staticcheck
uses: dominikh/[email protected]
with:
version: "2023.1.3"
install-go: false
- name: Go Test
run: SKIP_INTEGRATION_TESTS=1 go test -v ./...

Expand Down
33 changes: 33 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
linters:
enable:
- errname
- errorlint
- gocheckcompilerdirectives
- gochecknoglobals
- gochecknoinits
- goconst
- gocritic
- misspell
- nilerr
- nilnil
- nlreturn
- perfsprint
- prealloc
- predeclared
- reassign
- sloglint
- spancheck
- testifylint
- unparam
- unused
- usestdlibvars
- wsl

linters-settings:
errorlint:
asserts: false
errcheck:
exclude-functions:
- (*github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema.ResourceData).Set
goconst:
ignore-tests: true
4 changes: 3 additions & 1 deletion cli/args.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,11 @@ func validate(args Args) error {
if args.Tags == "" {
return errors.New("missing tags")
}

if args.Type != string(common.Terraform) && args.Type != string(common.Terragrunt) {
return fmt.Errorf("invalid type %s, must be either 'terratag' or 'terragrunt'", args.Type)
}

return nil
}

Expand All @@ -52,7 +54,7 @@ func InitArgs() (Args, error) {
fs.BoolVar(&args.DefaultToTerraform, "default-to-terraform", false, "By default uses OpenTofu (if installed), if set will use Terraform even when Opentofu is installed")

// Set cli args based on environment variables.
//The command line flags have precedence over environment variables.
// The command line flags have precedence over environment variables.
fs.VisitAll(func(f *flag.Flag) {
if f.Name == "version" {
return
Expand Down
4 changes: 4 additions & 0 deletions cmd/terratag/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,19 @@ func main() {
if err != nil {
fmt.Println(err)
fmt.Println("Usage: terratag -tags='{ \"some_tag\": \"value\" }' [-dir=\".\"]")

return
}

if args.Version {
var versionPrefix string

if !strings.HasPrefix(version, "v") {
versionPrefix = "v"
}

fmt.Printf("Terratag %s%s\n", versionPrefix, version)

return
}

Expand Down
10 changes: 10 additions & 0 deletions internal/convert/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ func GetExistingTagsExpression(tokens hclwrite.Tokens) string {

func isHclMap(tokens hclwrite.Tokens) bool {
maybeHclMap := strings.TrimSpace(string(tokens.Bytes()))

return strings.HasPrefix(maybeHclMap, "{") && strings.HasSuffix(maybeHclMap, "}")
}

Expand All @@ -42,6 +43,7 @@ func AppendLocalsBlock(file *hclwrite.File, filename string, terratag common.Ter
if block.Type() != "locals" {
continue
}

if block.Body().GetAttribute(key) == nil {
continue
}
Expand All @@ -64,7 +66,9 @@ func AppendTagBlocks(resource *hclwrite.Block, tags string) error {
if err := json.Unmarshal([]byte(tags), &tagsMap); err != nil {
return err
}

keys := utils.SortObjectKeys(tagsMap)

for _, key := range keys {
resource.Body().AppendNewline()
tagBlock := resource.Body().AppendNewBlock("tag", nil)
Expand All @@ -91,6 +95,7 @@ func UnquoteTagsAttribute(swappedTagsStrings []string, text string) string {

text = strings.ReplaceAll(text, escapedByWriter, swappedTagString)
}

return text
}

Expand All @@ -103,6 +108,7 @@ func MoveExistingTags(filename string, terratag common.TerratagLocal, block *hcl
if tagsAttribute != nil {
// If attribute found, get its value
log.Print("Pre-existing " + tagId + " ATTRIBUTE found on resource. Merging.")

existingTags = quoteAttributeKeys(tagsAttribute)
} else {
// Otherwise, we try to get tags as block
Expand All @@ -120,8 +126,10 @@ func MoveExistingTags(filename string, terratag common.TerratagLocal, block *hcl

if existingTags != nil {
terratag.Found[tag_keys.GetResourceExistingTagsKey(filename, block)] = existingTags

return true, nil
}

return false, nil
}

Expand All @@ -132,6 +140,7 @@ func quoteBlockKeys(tagsBlock *hclwrite.Block) *hclwrite.Block {
for key, value := range tagsBlock.Body().Attributes() {
quotedTagBlock.Body().SetAttributeRaw("\""+key+"\"", value.Expr().BuildTokens(hclwrite.Tokens{}))
}

return quotedTagBlock
}

Expand All @@ -141,6 +150,7 @@ func isTagKeyUnquoted(tags hclwrite.Tokens, index int) bool {

func quoteAttributeKeys(tagsAttribute *hclwrite.Attribute) hclwrite.Tokens {
var newTags hclwrite.Tokens

tags := tagsAttribute.Expr().BuildTokens(hclwrite.Tokens{})

// if attribute is a variable
Expand Down
8 changes: 6 additions & 2 deletions internal/convert/terratag_locals.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,13 @@ func decodeTerratagLocals(locals Locals, s string) error {
func encodeTerratagLocals(locals Locals) string {
ret := "{"

// Return it in ordered manner for order consistency (primarly when running tests).
var keys []string
// Return it in ordered manner for order consistency (primarily when running tests).
keys := []string{}

for key := range locals {
keys = append(keys, key)
}

sort.Strings(keys)

for _, key := range keys {
Expand All @@ -47,13 +49,15 @@ func encodeTerratagLocals(locals Locals) string {

ret = strings.TrimSuffix(ret, ", ")
ret += "}"

return ret
}

func MergeTerratagLocals(attribute *hclwrite.Attribute, added string) (string, error) {
localsAttribute := Locals{}
tokens := hclwrite.Tokens{}
existingLocalsExpression := stringifyExpression(attribute.BuildTokens(tokens))

if err := decodeTerratagLocals(localsAttribute, existingLocalsExpression); err != nil {
return "", err
}
Expand Down
3 changes: 3 additions & 0 deletions internal/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ func ReplaceWithTerratagFile(path string, textContent string, rename bool) error
}

log.Print("[INFO] Backing up ", path, " to ", backupFilename)

if err := os.Rename(path, backupFilename); err != nil {
return err
}
Expand All @@ -37,13 +38,15 @@ func ReplaceWithTerratagFile(path string, textContent string, rename bool) error

func CreateFile(path string, textContent string) error {
log.Print("[INFO] Creating file ", path)

return os.WriteFile(path, []byte(textContent), 0644)
}

func GetFilename(path string) string {
_, filename := filepath.Split(path)
filename = strings.TrimSuffix(filename, filepath.Ext(path))
filename = strings.ReplaceAll(filename, ".", "-")

return filename
}

Expand Down
22 changes: 14 additions & 8 deletions internal/providers/providers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,23 @@ import (
"strings"
)

const AWS = "aws"
const GCP = "gcp"
const AZURE = "azure"

var resourcesToSkip = []string{"azurerm_api_management_named_value"}

func getProviderByResource(resourceType string) Provider {
if strings.HasPrefix(resourceType, "aws_") {
return "aws"
} else if strings.HasPrefix(resourceType, "google_") {
return "gcp"
} else if strings.HasPrefix(resourceType, "azurerm_") || strings.HasPrefix(resourceType, "azurestack_") {
return "azure"
switch {
case strings.HasPrefix(resourceType, "aws_"):
return AWS
case strings.HasPrefix(resourceType, "google_"):
return GCP
case strings.HasPrefix(resourceType, "azurerm_") || strings.HasPrefix(resourceType, "azurestack_"):
return AZURE
default:
return ""
}

return ""
}

func IsTaggableByAttribute(resourceType string, attribute string) bool {
Expand All @@ -25,6 +30,7 @@ func IsTaggableByAttribute(resourceType string, attribute string) bool {
if (provider != "") && attribute == tagBlockId {
return true
}

return false
}

Expand Down
4 changes: 3 additions & 1 deletion internal/tag_keys/tag_keys.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package tag_keys

import (
"github.com/hashicorp/hcl/v2/hclwrite"
"strings"

"github.com/hashicorp/hcl/v2/hclwrite"
)

func GetTerratagAddedKey(filname string) string {
Expand All @@ -11,5 +12,6 @@ func GetTerratagAddedKey(filname string) string {

func GetResourceExistingTagsKey(filename string, resource *hclwrite.Block) string {
delimiter := "__"

return "terratag_found_" + filename + delimiter + strings.Join(resource.Labels(), delimiter)
}
9 changes: 8 additions & 1 deletion internal/tagging/aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ func tagAwsInstance(args TagBlockArgs) (*Result, error) {
if err != nil {
return nil, err
}

swappedTagsStrings = append(swappedTagsStrings, tagBlock)

// Tag 'volume_tags' if it exists.
Expand All @@ -28,10 +29,12 @@ func tagAwsInstance(args TagBlockArgs) (*Result, error) {
// Add tags to 'volume_tags' attribute.
volumeTagBlockArgs := args
volumeTagBlockArgs.TagId = "volume_tags"

volumeTagBlock, err := TagBlock(volumeTagBlockArgs)
if err != nil {
return nil, err
}

swappedTagsStrings = append(swappedTagsStrings, volumeTagBlock)
} else {
rootBlockDevice := args.Block.Body().FirstMatchingBlock("root_block_device", nil)
Expand All @@ -43,11 +46,14 @@ func tagAwsInstance(args TagBlockArgs) (*Result, error) {
// Add tags to 'root_block_device' block.
origArgsBlock := args.Block
args.Block = rootBlockDevice

tagBlock, err := TagBlock(args)
if err != nil {
return nil, err
}

swappedTagsStrings = append(swappedTagsStrings, tagBlock)

args.Block = origArgsBlock

// Add tags to any 'ebs_block_device' blocks (if any exist).
Expand All @@ -58,10 +64,12 @@ func tagAwsInstance(args TagBlockArgs) (*Result, error) {

origArgsBlock := args.Block
args.Block = block

tagBlock, err := TagBlock(args)
if err != nil {
return nil, err
}

swappedTagsStrings = append(swappedTagsStrings, tagBlock)
args.Block = origArgsBlock
}
Expand All @@ -72,7 +80,6 @@ func tagAwsInstance(args TagBlockArgs) (*Result, error) {

func tagAutoscalingGroup(args TagBlockArgs) (*Result, error) {
// https://www.terraform.io/docs/providers/aws/r/autoscaling_group.html

var tagsMap map[string]string
if err := json.Unmarshal([]byte(args.Tags), &tagsMap); err != nil {
return nil, err
Expand Down
3 changes: 3 additions & 0 deletions internal/tagging/azure.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,19 @@ func tagAksK8sCluster(args TagBlockArgs) (*Result, error) {
if err != nil {
return nil, err
}

swappedTagsStrings = append(swappedTagsStrings, tagBlock)

// handle default_node_pool tags attribute
nodePool := args.Block.Body().FirstMatchingBlock("default_node_pool", nil)
if nodePool != nil {
args.Block = nodePool

tagBlock, err := TagBlock(args)
if err != nil {
return nil, err
}

swappedTagsStrings = append(swappedTagsStrings, tagBlock)
}

Expand Down
2 changes: 2 additions & 0 deletions internal/tagging/gcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ func tagContainerCluster(args TagBlockArgs) (*Result, error) {
rootBlockArgs := args
rootBlockArgs.TagId = "resource_labels"
tagBlock, err := TagBlock(rootBlockArgs)

if err != nil {
return nil, err
}

rootBlockSwappedTagsStrings := []string{tagBlock}

return &Result{SwappedTagsStrings: rootBlockSwappedTagsStrings}, nil
Expand Down
2 changes: 2 additions & 0 deletions internal/tagging/tagging.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ func ParseHclValueStringToTokens(hclValueString string) hclwrite.Tokens {
log.Print("error parsing hcl value string " + hclValueString)
panic(diags.Errs()[0])
}

tempAttribute := file.Body().GetAttribute("tempKey")

return tempAttribute.Expr().BuildTokens(hclwrite.Tokens{})
}

Expand Down
Loading

0 comments on commit 4d884a7

Please sign in to comment.