package web import ( "bytes" "html" "html/template" "net/url" "path" "regexp" "strings" "github.com/bytesparadise/libasciidoc" "github.com/bytesparadise/libasciidoc/pkg/configuration" "github.com/microcosm-cc/bluemonday" log "github.com/sirupsen/logrus" "github.com/yuin/goldmark" "github.com/yuin/goldmark/extension" "github.com/yuin/goldmark/parser" "veinsforge/internal/data" ) var md = goldmark.New( goldmark.WithExtensions(extension.GFM), goldmark.WithParserOptions(parser.WithAutoHeadingID()), ) // maxRenderedDocBytes caps rendered documents so very large files fall back to // the source view instead of producing an unwieldy page. const maxRenderedDocBytes = 512 << 10 var attrRE = regexp.MustCompile(`(?i)\b(href|src)="([^"]*)"`) var readmePolicy = func() *bluemonday.Policy { policy := bluemonday.UGCPolicy() policy.AllowAttrs("class", "id").Globally() return policy }() func init() { log.SetLevel(log.WarnLevel) } func RenderMarkdown(input string) template.HTML { var buf bytes.Buffer if err := md.Convert([]byte(input), &buf); err != nil { return template.HTML("
Unable to render markdown.
") } return template.HTML(buf.String()) } func RenderRepoDocument(input, name string, repo *data.Repo, rev, dir string) template.HTML { if docFormat(name) == "asciidoc" { return renderRepoAsciidoc(input, repo, rev, dir) } return RenderRepoMarkdown(input, repo, rev, dir) } // docFormat returns the document format for name, or "" when it is not a file // type we render. The result is one of "markdown" or "asciidoc". func docFormat(name string) string { switch strings.ToLower(path.Ext(name)) { case ".md", ".markdown": return "markdown" case ".adoc", ".asciidoc": return "asciidoc" } return "" } // canRenderDoc reports whether a document should be rendered by default. func canRenderDoc(name string, size int64) bool { return docFormat(name) != "" && size <= maxRenderedDocBytes } func RenderRepoMarkdown(input string, repo *data.Repo, rev, dir string) template.HTML { var buf bytes.Buffer if err := md.Convert([]byte(input), &buf); err != nil { return template.HTML("Unable to render markdown.
") } return template.HTML(rewriteRepoHTML(buf.String(), repo, rev, dir)) } func renderRepoAsciidoc(input string, repo *data.Repo, rev, dir string) template.HTML { var safe strings.Builder for _, line := range strings.Split(input, "\n") { if strings.HasPrefix(strings.TrimSpace(line), "include::") { continue } safe.WriteString(line) safe.WriteByte('\n') } var buf bytes.Buffer metadata, err := libasciidoc.Convert(strings.NewReader(safe.String()), &buf, configuration.NewConfiguration()) if err != nil { return template.HTML("Unable to render AsciiDoc.
") } out := buf.String() if metadata.Title != "" && !strings.Contains(out, "