diff --git a/pkg/yqlib/encoder_toml.go b/pkg/yqlib/encoder_toml.go index 2c297fd0..a5ef74db 100644 --- a/pkg/yqlib/encoder_toml.go +++ b/pkg/yqlib/encoder_toml.go @@ -546,12 +546,20 @@ func (te *tomlEncoder) colorizeToml(input []byte) []byte { color.NoColor = false // Create color functions for different token types - commentColor := color.New(color.FgHiBlack).SprintFunc() - stringColor := color.New(color.FgGreen).SprintFunc() - numberColor := color.New(color.FgHiMagenta).SprintFunc() - keyColor := color.New(color.FgCyan).SprintFunc() - boolColor := color.New(color.FgHiMagenta).SprintFunc() - sectionColor := color.New(color.FgYellow, color.Bold).SprintFunc() + // Use EnableColor() to ensure colors work even when NO_COLOR env is set + commentColorObj := color.New(color.FgHiBlack); commentColorObj.EnableColor() + stringColorObj := color.New(color.FgGreen); stringColorObj.EnableColor() + numberColorObj := color.New(color.FgHiMagenta); numberColorObj.EnableColor() + keyColorObj := color.New(color.FgCyan); keyColorObj.EnableColor() + boolColorObj := color.New(color.FgHiMagenta); boolColorObj.EnableColor() + sectionColorObj := color.New(color.FgYellow, color.Bold); sectionColorObj.EnableColor() + + commentColor := commentColorObj.SprintFunc() + stringColor := stringColorObj.SprintFunc() + numberColor := numberColorObj.SprintFunc() + keyColor := keyColorObj.SprintFunc() + boolColor := boolColorObj.SprintFunc() + sectionColor := sectionColorObj.SprintFunc() // Simple tokenization for TOML colouring i := 0 diff --git a/pkg/yqlib/toml_test.go b/pkg/yqlib/toml_test.go index e3501036..23ccf8e1 100644 --- a/pkg/yqlib/toml_test.go +++ b/pkg/yqlib/toml_test.go @@ -632,6 +632,11 @@ func TestTomlScenarios(t *testing.T) { // TestTomlColourization tests that colourization correctly distinguishes // between table section headers and inline arrays func TestTomlColourization(t *testing.T) { + // Save and restore color state + oldNoColor := color.NoColor + color.NoColor = false + defer func() { color.NoColor = oldNoColor }() + // Test that inline arrays are not coloured as table sections encoder := &tomlEncoder{prefs: TomlPreferences{ColorsEnabled: true}} @@ -655,8 +660,9 @@ alpha = "test" // for actual table sections, not for inline arrays. // Get the ANSI codes for section colour (Yellow + Bold) - sectionColour := color.New(color.FgYellow, color.Bold).SprintFunc() - sampleSection := sectionColour("[database]") + sectionColourObj := color.New(color.FgYellow, color.Bold) + sectionColourObj.EnableColor() + sampleSection := sectionColourObj.Sprint("[database]") // Extract just the ANSI codes from the sample // ANSI codes start with \x1b[