GitRoot
Craft your forge, Build your project, Grow your community freely
1// SPDX-FileCopyrightText: 2025 Romain Maneschi <romain@gitroot.dev>
2//
3// SPDX-License-Identifier: EUPL-1.2
4
5package main
6
7import (
8 "fmt"
9 "strings"
10
11 "github.com/alecthomas/chroma"
12 codeHtml "github.com/alecthomas/chroma/formatters/html"
13 "github.com/alecthomas/chroma/lexers"
14 "github.com/alecthomas/chroma/styles"
15 gitroot "gitroot.dev/libs/golang/plugin"
16 "gitroot.dev/libs/golang/plugin/model"
17)
18
19var defaultRun = []model.PluginRun{{
20 Func: []model.PluginFunc{{FuncName: "renderCode", Args: []string{"code", "lang"}, Res: []string{"html"}}},
21}}
22
23type Plugin struct {
24 server model.Server
25}
26
27func (p *Plugin) Init(repoName string, confHasChanged bool, serializedConf string) error { return nil }
28func (p *Plugin) StartCommit(commit model.Commit) error { return nil }
29func (p *Plugin) AddFile(file model.File) error { return nil }
30func (p *Plugin) ModFile(file model.File) error { return nil }
31func (p *Plugin) DelFile(file model.File) error { return nil }
32func (p *Plugin) EndCommit(commit model.Commit) error { return nil }
33func (p *Plugin) Finish() error { return nil }
34
35func Build(server model.Server) model.Plugin {
36 p := &Plugin{
37 server: server,
38 }
39 server.ExportFunc("renderCode", func(args map[string]string) (map[string]string, error) {
40 code := args["code"]
41 lang := args["lang"]
42 html, err := renderCode(code, lang)
43 if err != nil {
44 return nil, err
45 }
46 return map[string]string{
47 "html": html,
48 }, nil
49 })
50 return p
51}
52
53func renderCode(source, lang string) (string, error) {
54 l := lexers.Get(lang)
55 if l == nil {
56 l = lexers.Analyse(source)
57 }
58 if l == nil {
59 l = lexers.Fallback
60 }
61 l = chroma.Coalesce(l)
62
63 it, err := l.Tokenise(nil, source)
64 if err != nil {
65 return "", err
66 }
67 highlightStyle := styles.Get("dracula")
68 if highlightStyle == nil {
69 return "", fmt.Errorf("didn't find style '%s'", "dracula")
70 }
71 var builder strings.Builder
72 if err := codeHtml.New(codeHtml.WithLineNumbers(true), codeHtml.LinkableLineNumbers(true, "L")).Format(&builder, highlightStyle, it); err != nil {
73 return "", err
74 }
75 return builder.String(), nil
76}
77
78//go:wasmexport install
79func main() {
80 gitroot.Register(defaultRun, Build)
81}