Skip to content

Commit

Permalink
feat: Add customisable code themes (#1725)
Browse files Browse the repository at this point in the history
* feat: Add customisable code themes
* fix: No syntax highlighting when colours are disabled
  • Loading branch information
liamg committed May 11, 2022
1 parent 0af69d0 commit d825e68
Show file tree
Hide file tree
Showing 7 changed files with 38 additions and 17 deletions.
2 changes: 1 addition & 1 deletion go.mod
Expand Up @@ -5,7 +5,7 @@ go 1.18
require (
github.com/AlecAivazis/survey/v2 v2.3.4
github.com/Masterminds/semver v1.5.0
github.com/aquasecurity/defsec v0.57.2
github.com/aquasecurity/defsec v0.57.3
github.com/hashicorp/go-version v1.4.0
github.com/inconshreveable/go-update v0.0.0-20160112193335-8152e7eb6ccf
github.com/liamg/clinch v1.5.6
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Expand Up @@ -139,8 +139,8 @@ github.com/apparentlymart/go-dump v0.0.0-20180507223929-23540a00eaa3/go.mod h1:o
github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk=
github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw=
github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo=
github.com/aquasecurity/defsec v0.57.2 h1:yqtxc8ZDgmnPnT5mszFkWkkacdN9TnFJgTQy6Mo703k=
github.com/aquasecurity/defsec v0.57.2/go.mod h1:42FxKif2itz+MHFlJ3TJjdroL9Jzj3THoexlueBTU5w=
github.com/aquasecurity/defsec v0.57.3 h1:oiATfUTxOAcxAuXSH31RdgjtXJdQznlVzMJWdVYGmXY=
github.com/aquasecurity/defsec v0.57.3/go.mod h1:42FxKif2itz+MHFlJ3TJjdroL9Jzj3THoexlueBTU5w=
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
Expand Down
2 changes: 2 additions & 0 deletions internal/app/tfsec/cmd/flags.go
Expand Up @@ -54,6 +54,7 @@ var regoPolicyDir string
var printRegoInput bool
var noModuleDownloads bool
var regoOnly bool
var codeTheme string

func configureFlags(cmd *cobra.Command) {

Expand Down Expand Up @@ -91,6 +92,7 @@ func configureFlags(cmd *cobra.Command) {
cmd.Flags().BoolVar(&printRegoInput, "print-rego-input", false, "Print a JSON representation of the input supplied to rego policies.")
cmd.Flags().BoolVar(&noModuleDownloads, "no-module-downloads", false, "Do not download remote modules.")
cmd.Flags().BoolVar(&regoOnly, "rego-only", false, "Run rego policies exclusively.")
cmd.Flags().StringVar(&codeTheme, "code-theme", "dark", "Theme for annotated code. Either 'light' or 'dark'.")

_ = cmd.Flags().MarkHidden("allow-checks-to-panic")
}
Expand Down
6 changes: 3 additions & 3 deletions internal/app/tfsec/cmd/output.go
Expand Up @@ -85,7 +85,7 @@ func outputFormat(w io.Writer, addExtension bool, baseFilename, format, fsRoot,
switch strings.ToLower(format) {
case "lovely", "default":
alsoStdout = true
factory.WithCustomFormatterFunc(formatter.DefaultWithMetrics(metrics, conciseOutput))
factory.WithCustomFormatterFunc(formatter.DefaultWithMetrics(metrics, conciseOutput, codeTheme, !disableColours))
case "json":
factory.AsJSON()
makeRelative = false
Expand All @@ -96,11 +96,11 @@ func outputFormat(w io.Writer, addExtension bool, baseFilename, format, fsRoot,
case "junit":
factory.AsJUnit()
case "text":
factory.WithCustomFormatterFunc(formatter.DefaultWithMetrics(metrics, conciseOutput)).WithColoursEnabled(false)
factory.WithCustomFormatterFunc(formatter.DefaultWithMetrics(metrics, conciseOutput, codeTheme, !disableColours)).WithColoursEnabled(false)
case "sarif":
factory.AsSARIF()
case "gif":
factory.WithCustomFormatterFunc(formatter.GifWithMetrics(metrics))
factory.WithCustomFormatterFunc(formatter.GifWithMetrics(metrics, codeTheme, !disableColours))
default:
return "", fmt.Errorf("invalid format specified: '%s'", format)
}
Expand Down
1 change: 1 addition & 0 deletions internal/app/tfsec/cmd/prerun.go
Expand Up @@ -20,6 +20,7 @@ func prerun(cmd *cobra.Command, args []string) error {
// disable colour if running on windows - colour formatting doesn't work
if disableColours || (runtime.GOOS == "windows" && os.Getenv("TERM") == "") {
tml.DisableFormatting()
disableColours = true // set this to prevent syntax highlighting later
} else {
tml.EnableFormatting()
}
Expand Down
36 changes: 27 additions & 9 deletions internal/pkg/formatter/default.go
Expand Up @@ -17,7 +17,7 @@ import (

var severityFormat map[severity.Severity]string

func DefaultWithMetrics(metrics scanner.Metrics, conciseOutput bool) func(b formatters.ConfigurableFormatter, results scan.Results) error {
func DefaultWithMetrics(metrics scanner.Metrics, conciseOutput bool, codeTheme string, withColours bool) func(b formatters.ConfigurableFormatter, results scan.Results) error {
return func(b formatters.ConfigurableFormatter, results scan.Results) error {

// we initialise the map here so we respect the colour-ignore options
Expand Down Expand Up @@ -53,7 +53,7 @@ func DefaultWithMetrics(metrics scanner.Metrics, conciseOutput bool) func(b form

_, _ = fmt.Fprintln(b.Writer(), "")
for _, group := range groups {
printResult(b, group)
printResult(b, group, codeTheme, withColours)
}

if !conciseOutput {
Expand Down Expand Up @@ -137,7 +137,7 @@ func getOccurrences(first scan.Result, baseDir string) []simpleLocation {
}

// nolint
func printResult(b formatters.ConfigurableFormatter, group formatters.GroupedResult) {
func printResult(b formatters.ConfigurableFormatter, group formatters.GroupedResult, theme string, withColours bool) {

first := group.Results()[0]

Expand Down Expand Up @@ -216,7 +216,7 @@ func printResult(b formatters.ConfigurableFormatter, group formatters.GroupedRes
strings.Repeat("─", width),
)

if err := highlightCode(b, first); err != nil {
if err := highlightCode(b, first, theme, withColours); err != nil {
_, _ = fmt.Fprintf(w, tml.Sprintf(" <red><bold>Failed to render code:</bold> %s", err))
}

Expand Down Expand Up @@ -293,9 +293,22 @@ func printMetadata(w io.Writer, result scan.Result, links []string, isRego bool)
}

// nolint
func highlightCode(b formatters.ConfigurableFormatter, result scan.Result) error {
func highlightCode(b formatters.ConfigurableFormatter, result scan.Result, theme string, withColours bool) error {

code, err := result.GetCode()
codeOpts := []scan.CodeOption{
scan.OptionCodeWithTruncation(true),
}

switch theme {
case "dark":
codeOpts = append(codeOpts, scan.OptionCodeWithDarkTheme())
case "light":
codeOpts = append(codeOpts, scan.OptionCodeWithLightTheme())
default:
codeOpts = append(codeOpts, scan.OptionCodeWithTheme(theme))
}

code, err := result.GetCode(codeOpts...)
if err != nil {
return err
}
Expand All @@ -312,6 +325,11 @@ func highlightCode(b formatters.ConfigurableFormatter, result scan.Result) error

for i, line := range lines {

outputCode := line.Highlighted
if !withColours {
outputCode = line.Content
}

// if we're rendering the actual issue lines, use red
if line.IsCause && result.Status() != scan.StatusPassed {

Expand Down Expand Up @@ -340,9 +358,9 @@ func highlightCode(b formatters.ConfigurableFormatter, result scan.Result) error
_ = tml.Fprintf(
w,
" %s",
line.Highlighted,
outputCode,
)
if line.Annotation != "" {
if line.Annotation != "" && !code.IsCauseMultiline() {
_ = tml.Fprintf(
w,
" <italic><dim>(%s)",
Expand All @@ -369,7 +387,7 @@ func highlightCode(b formatters.ConfigurableFormatter, result scan.Result) error
_ = tml.Fprintf(
w,
" %s",
line.Highlighted,
outputCode,
)
}

Expand Down
4 changes: 2 additions & 2 deletions internal/pkg/formatter/gif.go
Expand Up @@ -8,7 +8,7 @@ import (
"github.com/liamg/gifwrap/pkg/ascii"
)

func GifWithMetrics(metrics scanner.Metrics) func(b formatters.ConfigurableFormatter, results scan.Results) error {
func GifWithMetrics(metrics scanner.Metrics, theme string, withColours bool) func(b formatters.ConfigurableFormatter, results scan.Results) error {
return func(b formatters.ConfigurableFormatter, results scan.Results) error {

failCount := len(results.GetFailed())
Expand All @@ -24,6 +24,6 @@ func GifWithMetrics(metrics scanner.Metrics) func(b formatters.ConfigurableForma
_ = renderer.PlayOnce()
}

return DefaultWithMetrics(metrics, false)(b, results)
return DefaultWithMetrics(metrics, false, theme, withColours)(b, results)
}
}

0 comments on commit d825e68

Please sign in to comment.