github.com/secman-team/gh-api@v1.8.2/pkg/markdown/markdown.go (about) 1 package markdown 2 3 import ( 4 "os" 5 "strings" 6 7 "github.com/charmbracelet/glamour" 8 ) 9 10 type RenderOpts []glamour.TermRendererOption 11 12 func WithoutIndentation() glamour.TermRendererOption { 13 overrides := []byte(` 14 { 15 "document": { 16 "margin": 0 17 }, 18 "code_block": { 19 "margin": 0 20 } 21 }`) 22 23 return glamour.WithStylesFromJSONBytes(overrides) 24 } 25 26 func WithoutWrap() glamour.TermRendererOption { 27 return glamour.WithWordWrap(0) 28 } 29 30 func render(text string, opts RenderOpts) (string, error) { 31 // Glamour rendering preserves carriage return characters in code blocks, but 32 // we need to ensure that no such characters are present in the output. 33 text = strings.ReplaceAll(text, "\r\n", "\n") 34 35 tr, err := glamour.NewTermRenderer(opts...) 36 if err != nil { 37 return "", err 38 } 39 40 return tr.Render(text) 41 } 42 43 func Render(text, style string) (string, error) { 44 opts := RenderOpts{ 45 glamour.WithStylePath(style), 46 } 47 48 return render(text, opts) 49 } 50 51 func RenderWithOpts(text, style string, opts RenderOpts) (string, error) { 52 defaultOpts := RenderOpts{ 53 glamour.WithStylePath(style), 54 } 55 opts = append(defaultOpts, opts...) 56 57 return render(text, opts) 58 } 59 60 func RenderWithBaseURL(text, style, baseURL string) (string, error) { 61 opts := RenderOpts{ 62 glamour.WithStylePath(style), 63 glamour.WithBaseURL(baseURL), 64 } 65 66 return render(text, opts) 67 } 68 69 func RenderWithWrap(text, style string, wrap int) (string, error) { 70 opts := RenderOpts{ 71 glamour.WithStylePath(style), 72 glamour.WithWordWrap(wrap), 73 } 74 75 return render(text, opts) 76 } 77 78 func GetStyle(defaultStyle string) string { 79 style := fromEnv() 80 if style != "" && style != "auto" { 81 return style 82 } 83 84 if defaultStyle == "light" || defaultStyle == "dark" { 85 return defaultStyle 86 } 87 88 return "notty" 89 } 90 91 var fromEnv = func() string { 92 return os.Getenv("GLAMOUR_STYLE") 93 }