Skip to content

Commit

Permalink
fix: normalize block labels
Browse files Browse the repository at this point in the history
Signed-off-by: nikpivkin <[email protected]>
  • Loading branch information
nikpivkin committed Nov 1, 2024
1 parent 387bb0a commit f2ecd76
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
2 changes: 1 addition & 1 deletion pkg/iac/scan/highlighting.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func highlight(fsKey, filename string, startLine, endLine int, input, theme stri
return nil
}

lines := strings.Split(string(highlighted), "\n")
lines := strings.Split(highlighted, "\n")
globalCache.Set(key, lines)
return lines
}
Expand Down
19 changes: 17 additions & 2 deletions pkg/iac/scanners/terraform/executor/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,21 +119,36 @@ func renderCause(modules terraform.Modules, causeRng types.Range) scan.RenderedC
}

f := hclwrite.NewEmptyFile()
block := f.Body().AppendNewBlock(tfBlock.Type(), tfBlock.Labels())
block := hclwrite.NewBlock(tfBlock.Type(), normalizeBlockLables(tfBlock))

if !writeBlock(tfBlock, block, causeRng) {
return scan.RenderedCause{}
}

f.Body().AppendBlock(block)

cause := string(hclwrite.Format(f.Bytes()))
cause = strings.TrimSuffix(string(cause), "\n")
cause = strings.TrimSuffix(cause, "\n")
highlighted, _ := scan.Highlight(causeRng.GetFilename(), cause, scan.DarkTheme)
return scan.RenderedCause{
Raw: cause,
Highlighted: highlighted,
}
}

func normalizeBlockLables(block *terraform.Block) []string {
labels := block.Labels()
if block.IsExpanded() {
nameLabel := labels[len(labels)-1]
idx := strings.LastIndex(nameLabel, "[")
if idx != -1 {
labels[len(labels)-1] = nameLabel[:idx]
}
}

return labels
}

func writeBlock(tfBlock *terraform.Block, block *hclwrite.Block, causeRng types.Range) bool {
var found bool
for _, attr := range tfBlock.Attributes() {
Expand Down

0 comments on commit f2ecd76

Please sign in to comment.