Ensure that the style config path is expanded where it is used.

Addresses issue #776

Also adds a test to ensure it expands environment variables in the file
path.
This commit is contained in:
Daniel Hobe 2026-03-24 21:05:38 -07:00
commit 423492d09f
2 changed files with 33 additions and 6 deletions

View file

@ -1,9 +1,33 @@
package main
import (
"os"
"testing"
)
func TestValidateStyle(t *testing.T) {
// Create a temporary file to use as a style
tmpFile, err := os.CreateTemp("", "glow-style-*.json")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpFile.Name())
// Set an environment variable to point to it
os.Setenv("MY_GLOW_STYLE", tmpFile.Name())
defer os.Unsetenv("MY_GLOW_STYLE")
styleToTest := "$MY_GLOW_STYLE"
styleVar, err := validateStyle(styleToTest)
if err != nil {
t.Fatalf("validateStyle failed: %v", err)
}
if styleVar != tmpFile.Name() {
t.Errorf("Style was NOT expanded: %s, expected: %s", styleVar, tmpFile.Name())
}
}
func TestGlowFlags(t *testing.T) {
tt := []struct {
args []string

15
main.go
View file

@ -150,16 +150,16 @@ func sourceFromArg(arg string) (*source, error) {
// validateStyle checks if the style is a default style, if not, checks that
// the custom style exists.
func validateStyle(style string) error {
func validateStyle(style string) (string, error) {
if style != "auto" && styles.DefaultStyles[style] == nil {
style = utils.ExpandPath(style)
if _, err := os.Stat(style); errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("specified style does not exist: %s", style)
return style, fmt.Errorf("specified style does not exist: %s", style)
} else if err != nil {
return fmt.Errorf("unable to stat file: %w", err)
return style, fmt.Errorf("unable to stat file: %w", err)
}
}
return nil
return style, nil
}
func validateOptions(cmd *cobra.Command) error {
@ -178,7 +178,8 @@ func validateOptions(cmd *cobra.Command) error {
// validate the glamour style
style = viper.GetString("style")
if err := validateStyle(style); err != nil {
var err error
if style, err = validateStyle(style); err != nil {
return err
}
@ -349,8 +350,10 @@ func runTUI(path string, content string) error {
}
// use style set in env, or auto if unset
if err := validateStyle(cfg.GlamourStyle); err != nil {
if s, err := validateStyle(cfg.GlamourStyle); err != nil {
cfg.GlamourStyle = style
} else {
cfg.GlamourStyle = s
}
cfg.Path = path