From d9242c9a7220e194b1fe4165cf3669d3b642e2e7 Mon Sep 17 00:00:00 2001 From: Nicolas Martin Date: Wed, 16 Dec 2020 16:23:58 +0100 Subject: [PATCH] Expand the path for a specified style file --- go.mod | 1 + main.go | 19 ++++++++++++++++--- utils/utils.go | 16 +++++++++++++++- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index a2e7086..fbf0a23 100644 --- a/go.mod +++ b/go.mod @@ -14,6 +14,7 @@ require ( github.com/mattn/go-runewidth v0.0.9 github.com/meowgorithm/babyenv v1.3.0 github.com/microcosm-cc/bluemonday v1.0.4 // indirect + github.com/mitchellh/go-homedir v1.1.0 github.com/muesli/gitcha v0.1.2-0.20200908172931-5aa4fdccf2f6 github.com/muesli/go-app-paths v0.2.1 github.com/muesli/reflow v0.2.0 diff --git a/main.go b/main.go index 1584de0..f506f9d 100644 --- a/main.go +++ b/main.go @@ -135,13 +135,23 @@ func sourceFromArg(arg string) (*source, error) { return &source{r, u}, err } -func validateOptions(cmd *cobra.Command) { +func validateOptions(cmd *cobra.Command) error { // grab config values from Viper - style = viper.GetString("style") width = viper.GetUint("width") localOnly = viper.GetBool("local") mouse = viper.GetBool("mouse") + // validate the glamour style + style = viper.GetString("style") + if style != "auto" && glamour.DefaultStyles[style] == nil { + style = utils.ExpandPath(style) + if _, err := os.Stat(style); os.IsNotExist(err) { + return fmt.Errorf("Specified style does not exist: %s", style) + } else if err != nil { + return err + } + } + isTerminal := terminal.IsTerminal(int(os.Stdout.Fd())) // We want to use a special no-TTY style, when stdout is not a terminal // and there was no specific style passed by arg @@ -163,11 +173,14 @@ func validateOptions(cmd *cobra.Command) { if width == 0 { width = 80 } + return nil } func execute(cmd *cobra.Command, args []string) error { initConfig() - validateOptions(cmd) + if err := validateOptions(cmd); err != nil { + return err + } if len(args) == 0 { return executeArg(cmd, "", os.Stdout) diff --git a/utils/utils.go b/utils/utils.go index e03298c..8146f82 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -1,6 +1,11 @@ package utils -import "regexp" +import ( + "os" + "regexp" + + "github.com/mitchellh/go-homedir" +) func RemoveFrontmatter(content []byte) []byte { if frontmatterBoundaries := detectFrontmatter(content); frontmatterBoundaries[0] == 0 { @@ -17,3 +22,12 @@ func detectFrontmatter(c []byte) []int { } return []int{-1, -1} } + +// Expands tilde and all environment variables from the given path. +func ExpandPath(path string) string { + s, err := homedir.Expand(path) + if err == nil { + return os.ExpandEnv(s) + } + return os.ExpandEnv(path) +}