Skip to content

Commit

Permalink
feat(highlight): allow disabling syntax highlighting of caller code (#8)
Browse files Browse the repository at this point in the history
This change allows users to use the `JUSTEST_DISABLE_SOURCE_HIGHLIGHT`
environment variable to disable or enable the source code syntax
highlighting when showing it in failure stack traces.

Syntax highlighting remains enabled by default, but disabling it can be
useful for some testing environments without support for rendering
colors.

The environment variable can be set to the following values:
- "true", "TRUE", "True", "T", "t", "1"
- "false", "FALSE", "False", "F", "f", "0"
  • Loading branch information
arikkfir authored May 11, 2024
1 parent da78562 commit 314c968
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
7 changes: 7 additions & 0 deletions init_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package justest_test

import "os"

func init() {
_ = os.Setenv("JUSTEST_DISABLE_SOURCE_HIGHLIGHT", "false")
}
23 changes: 18 additions & 5 deletions location.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ package justest
import (
"bytes"
"fmt"
"github.com/alecthomas/chroma/v2/quick"
"github.com/arikkfir/justest/internal"
"os"
"os/exec"
"strconv"
"strings"

"github.com/alecthomas/chroma/v2/quick"

"github.com/arikkfir/justest/internal"
)

// Display mode
Expand Down Expand Up @@ -84,9 +86,20 @@ func readSourceAt(file string, line int) string {
lines := strings.Split(fileContents, "\n")
if len(lines) > line {
source = strings.TrimSpace(lines[line-1])
output := bytes.Buffer{}
if err := quick.Highlight(&output, source, "go", goSourceFormatter, goSourceStyle[displayMode]); err == nil {
source = output.String()

highlight := true
if highlightEnv := os.Getenv("JUSTEST_DISABLE_SOURCE_HIGHLIGHT"); highlightEnv != "" {
if val, err := strconv.ParseBool(highlightEnv); err != nil {
panic(fmt.Sprintf("Error parsing JUSTEST_HIGHLIGHT_SOURCE environment variable - illegal value: %s", highlightEnv))
} else {
highlight = val
}
}
if highlight {
output := bytes.Buffer{}
if err := quick.Highlight(&output, source, "go", goSourceFormatter, goSourceStyle[displayMode]); err == nil {
source = output.String()
}
}
}
}
Expand Down

0 comments on commit 314c968

Please sign in to comment.