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 <dev@flexport.com>
Co-authored-by: Maas Lalani <maaslalani0@gmail.com>
This commit is contained in:
satoru
2021-07-23 22:08:45 +08:00
committed by GitHub
parent c1f6ab72e4
commit ad7fc7871c
2 changed files with 41 additions and 11 deletions

View File

@@ -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.

View File

@@ -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)
}