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, initKind model.InitKind, serializedConf string) error {
28 return nil
29}
30func (p *Plugin) StartCommit(commit model.Commit) error { return nil }
31func (p *Plugin) AddFile(file model.File) error { return nil }
32func (p *Plugin) ModFile(file model.File) error { return nil }
33func (p *Plugin) DelFile(file model.File) error { return nil }
34func (p *Plugin) EndCommit(commit model.Commit) error { return nil }
35func (p *Plugin) Finish() error { return nil }
36
37func Build(server model.Server) model.Plugin {
38 p := &Plugin{
39 server: server,
40 }
41 server.ExportFunc("renderCode", func(args map[string]string) (map[string]string, error) {
42 code := args["code"]
43 lang := args["lang"]
44 html, err := renderCode(code, lang)
45 if err != nil {
46 return nil, err
47 }
48 return map[string]string{
49 "html": html,
50 }, nil
51 })
52 return p
53}
54
55func renderCode(source, lang string) (string, error) {
56 l := lexers.Get(lang)
57 if l == nil {
58 l = lexers.Analyse(source)
59 }
60 if l == nil {
61 l = lexers.Fallback
62 }
63 l = chroma.Coalesce(l)
64
65 it, err := l.Tokenise(nil, source)
66 if err != nil {
67 return "", err
68 }
69 highlightStyle := styles.Get("dracula")
70 if highlightStyle == nil {
71 return "", fmt.Errorf("didn't find style '%s'", "dracula")
72 }
73 var builder strings.Builder
74 if err := codeHtml.New(codeHtml.WithLineNumbers(true), codeHtml.LinkableLineNumbers(true, "L")).Format(&builder, highlightStyle, it); err != nil {
75 return "", err
76 }
77 return builder.String(), nil
78}
79
80//go:wasmexport install
81func main() {
82 gitroot.Register(defaultRun, Build)
83}