From ad7fc7871c6de5905e6fa25143d4c0614e8b7f34 Mon Sep 17 00:00:00 2001 From: satoru Date: Fri, 23 Jul 2021 22:08:45 +0800 Subject: [PATCH] Fix #73, add support for fetching remote theme (#85) * Fix #73, add support for fetching remote theme * Close file * Fix texting in example * Anything with the prefix http we should attempt to fetch Co-authored-by: Buildkite Co-authored-by: Maas Lalani --- examples/custom_remote_theme.md | 7 +++++ styles/styles.go | 45 +++++++++++++++++++++++++-------- 2 files changed, 41 insertions(+), 11 deletions(-) create mode 100644 examples/custom_remote_theme.md diff --git a/examples/custom_remote_theme.md b/examples/custom_remote_theme.md new file mode 100644 index 0000000..3762b64 --- /dev/null +++ b/examples/custom_remote_theme.md @@ -0,0 +1,7 @@ +--- +theme: https://github.com/maaslalani/slides/raw/main/styles/theme.json +--- + +# Slides + +The theme of this slide is fetched from https://github.com/maaslalani/slides/raw/main/styles/theme.json, the title above should be green. diff --git a/styles/styles.go b/styles/styles.go index e4451e3..920f667 100644 --- a/styles/styles.go +++ b/styles/styles.go @@ -3,6 +3,8 @@ package styles import ( _ "embed" + "io" + "net/http" "os" "strings" @@ -59,20 +61,41 @@ func SelectTheme(theme string) glamour.TermRendererOption { case "notty": return glamour.WithStyles(glamour.NoTTYStyleConfig) default: - bytes, err := os.ReadFile(theme) + var themeReader io.Reader + var err error + if strings.HasPrefix(theme, "http") { + var resp *http.Response + resp, err = http.Get(theme) + if err != nil { + return getDefaultTheme() + } + defer resp.Body.Close() + themeReader = resp.Body + } else { + file, err := os.Open(theme) + if err != nil { + return getDefaultTheme() + } + defer file.Close() + themeReader = file + } + bytes, err := io.ReadAll(themeReader) if err == nil { return glamour.WithStylesFromJSONBytes(bytes) } // Should log a warning so the user knows we failed to read their theme file - - if termenv.EnvNoColor() { - return glamour.WithStyles(glamour.NoTTYStyleConfig) - } - - if !termenv.HasDarkBackground() { - return glamour.WithStyles(glamour.LightStyleConfig) - } - - return glamour.WithStylesFromJSONBytes(DefaultTheme) + return getDefaultTheme() } } + +func getDefaultTheme() glamour.TermRendererOption { + if termenv.EnvNoColor() { + return glamour.WithStyles(glamour.NoTTYStyleConfig) + } + + if !termenv.HasDarkBackground() { + return glamour.WithStyles(glamour.LightStyleConfig) + } + + return glamour.WithStylesFromJSONBytes(DefaultTheme) +}