forked from taikoxyz/taiko-mono
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
337 lines (307 loc) · 9.76 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package main
import (
"bytes"
"context"
"crypto/rand"
"embed"
"encoding/hex"
"errors"
"flag"
"fmt"
t2html "github.com/buildkite/terminal-to-html/v3"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/format/diff"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/html"
"github.com/gomarkdown/markdown/parser"
"gopkg.in/yaml.v3"
"os"
"path/filepath"
"sort"
"strings"
"text/template"
)
//go:embed page.gohtml
var page embed.FS
func main() {
repoPathStr := flag.String("repo", ".", "path to local git repository (fork)")
upstreamRepoPathStr := flag.String("upstream-repo", "", "path to local git repository (upstream)")
forkPagePathStr := flag.String("fork", "fork.yaml", "fork page definition")
outStr := flag.String("out", "index.html", "output")
flag.Parse()
// Upstream repo path defaults to the same value as repoPathStr if not set
if *upstreamRepoPathStr == "" {
upstreamRepoPathStr = repoPathStr
}
must := func(err error, msg string, args ...any) {
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, msg, args...)
_, _ = fmt.Fprintf(os.Stderr, "\nerror: %v", err)
os.Exit(1)
}
}
pageDefinition, err := readPageYaml(*forkPagePathStr)
must(err, "failed to read page definition %q", *forkPagePathStr)
if pageDefinition.Def == nil {
must(errors.New("no fork definition defined"), "need to root fork definition")
}
forkRepo, err := git.PlainOpen(*repoPathStr)
must(err, "failed to open git repository %q", *repoPathStr)
baseRepo, err := git.PlainOpen(*upstreamRepoPathStr)
must(err, "failed to open git repository %q", *upstreamRepoPathStr)
findCommit := func(rr *RefRepo, repo *git.Repository) *object.Commit {
if rr.Ref != "" && rr.Hash != "" {
must(errors.New("hash and ref"), "cannot use both hash and reference")
}
if rr.Ref == "" && rr.Hash == "" {
must(errors.New("no hash and no ref"), "need either hash or reference")
}
if rr.Ref != "" {
ref, err := repo.Reference(plumbing.ReferenceName(rr.Ref), true)
must(err, "failed to find git ref %q", rr.Ref)
commit, err := repo.CommitObject(ref.Hash())
must(err, "failed to open commit %s", ref.Hash())
return commit
}
commit, err := repo.CommitObject(plumbing.NewHash(rr.Hash))
must(err, "failed to find commit hash %s", rr.Hash)
return commit
}
baseCommit := findCommit(&pageDefinition.Base, baseRepo)
baseTree, err := baseCommit.Tree()
must(err, "failed to open base git tree")
forkCommit := findCommit(&pageDefinition.Fork, forkRepo)
forkTree, err := forkCommit.Tree()
must(err, "failed to open fork git tree")
forkPatch, err := baseTree.PatchContext(context.Background(), forkTree)
must(err, "failed to compute patch between base and fork")
baseFiles := map[string]struct{}{}
forkFiles := map[string]struct{}{}
patchByName := make(map[string]diff.FilePatch, len(forkPatch.FilePatches()))
for _, fp := range forkPatch.FilePatches() {
from, to := fp.Files()
if to != nil {
patchByName[to.Path()] = fp
} else if from != nil {
patchByName[from.Path()] = fp
} else {
continue
}
if to != nil {
forkFiles[to.Path()] = struct{}{}
}
if from != nil {
baseFiles[from.Path()] = struct{}{}
}
}
// remove the patches that are ignored
ignored := make(map[string]diff.FilePatch)
for k := range patchByName {
for _, globPattern := range pageDefinition.Ignore {
ok, err := filepath.Match(globPattern, k)
must(err, "failed to check %q against ignore glob pattern %q", k, globPattern)
if ok {
ignored[k] = patchByName[k]
delete(patchByName, k)
}
}
}
remaining := make(map[string]struct{})
for k := range patchByName {
remaining[k] = struct{}{}
}
must(pageDefinition.Def.hydrate(patchByName, remaining, 1), "failed to hydrate patch stats")
if len(remaining) > 0 {
remainingDef := &ForkDefinition{
Title: "other changes",
Level: 2,
}
remainingPaths := make([]string, 0, len(remaining))
for k := range remaining {
remainingPaths = append(remainingPaths, k)
}
sort.Strings(remainingPaths)
for _, k := range remainingPaths {
remainingDef.hydratePatch(k, patchByName[k])
}
pageDefinition.Def.Sub = append(pageDefinition.Def.Sub, remainingDef)
pageDefinition.Def.LinesAdded += remainingDef.LinesAdded
pageDefinition.Def.LinesDeleted += remainingDef.LinesDeleted
}
if len(ignored) > 0 {
ignoredPaths := make([]string, 0, len(ignored))
for k := range ignored {
ignoredPaths = append(ignoredPaths, k)
}
sort.Strings(ignoredPaths)
ignoredDef := &ForkDefinition{
Title: "ignored changes",
Level: 4,
}
for _, k := range ignoredPaths {
ignoredDef.hydratePatch(k, ignored[k])
}
pageDefinition.Ignored = ignoredDef
}
templ := template.New("main")
templ.Funcs(template.FuncMap{
"renderMarkdown": func(md string) string {
markdownRenderer := html.NewRenderer(html.RendererOptions{
Flags: html.Smartypants | html.SmartypantsFractions | html.SmartypantsDashes | html.SmartypantsLatexDashes,
Generator: "forkdiff",
})
markdownParser := parser.NewWithExtensions(parser.CommonExtensions | parser.OrderedListStart)
return string(markdown.ToHTML([]byte(md), markdownParser, markdownRenderer))
},
"page": func() *Page {
return pageDefinition
},
"existsInBase": func(path string) bool {
_, ok := baseFiles[path]
return ok
},
"existsInFork": func(path string) bool {
_, ok := forkFiles[path]
return ok
},
"baseFileURL": func(path string) string {
return fmt.Sprintf("%s/blob/%s/%s", pageDefinition.Base.URL, baseCommit.Hash, path)
},
"forkFileURL": func(path string) string {
return fmt.Sprintf("%s/blob/%s/%s", pageDefinition.Fork.URL, forkCommit.Hash, path)
},
"baseCommitHash": func() string {
return baseCommit.Hash.String()
},
"forkCommitHash": func() string {
return forkCommit.Hash.String()
},
"renderPatch": func(fps *FilePatchStats) (string, error) {
var out bytes.Buffer
enc := diff.NewUnifiedEncoder(&out, 3)
enc.SetSrcPrefix(pageDefinition.Base.Name + "/")
enc.SetDstPrefix(pageDefinition.Fork.Name + "/")
enc.SetColor(diff.NewColorConfig())
err := enc.Encode(FilePatch{filePatch: fps.Patch})
if err != nil {
return "", fmt.Errorf("")
}
return string(t2html.Render(out.Bytes())), nil
},
"randomID": func() (string, error) {
var out [12]byte
if _, err := rand.Read(out[:]); err != nil {
return "", err
}
return "id-" + hex.EncodeToString(out[:]), nil
},
})
templ, err = templ.ParseFS(page, "*.gohtml")
must(err, "failed to parse page template")
f, err := os.OpenFile(*outStr, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0o755)
must(err, "failed to open output file")
defer f.Close()
must(templ.ExecuteTemplate(f, "main", pageDefinition), "failed to build page")
}
func readPageYaml(path string) (*Page, error) {
f, err := os.OpenFile(path, os.O_RDONLY, 0)
if err != nil {
return nil, fmt.Errorf("failed to read page YAML file: %w", err)
}
defer f.Close()
dec := yaml.NewDecoder(f)
dec.KnownFields(true)
var page Page
if err := dec.Decode(&page); err != nil {
return nil, fmt.Errorf("failed to decode page YAML file: %w", err)
}
return &page, nil
}
func countOperations(chunks []diff.Chunk, op diff.Operation) (out int) {
for _, ch := range chunks {
if ch.Type() == op {
out += strings.Count(ch.Content(), "\n")
}
}
return
}
type FilePatch struct {
filePatch diff.FilePatch
}
var _ diff.Patch = FilePatch{}
func (p FilePatch) FilePatches() []diff.FilePatch {
return []diff.FilePatch{p.filePatch}
}
func (p FilePatch) Message() string {
return ""
}
type RefRepo struct {
Name string `yaml:"name"`
Ref string `yaml:"ref,omitempty"`
Hash string `yaml:"hash,omitempty"`
URL string `yaml:"url"`
}
type Page struct {
Title string `yaml:"title"`
Footer string `yaml:"footer"`
Base RefRepo `yaml:"base"`
Fork RefRepo `yaml:"fork"`
Def *ForkDefinition `yaml:"def"`
Ignore []string `yaml:"ignore"`
Ignored *ForkDefinition `yaml:"-"`
}
type FilePatchStats struct {
Path string
LinesAdded int
LinesDeleted int
Binary bool
Patch diff.FilePatch
}
type ForkDefinition struct {
Title string `yaml:"title,omitempty"`
Description string `yaml:"description,omitempty"`
Globs []string `yaml:"globs,omitempty"`
Sub []*ForkDefinition `yaml:"sub,omitempty"`
Files []FilePatchStats `yaml:"-"`
LinesAdded int `yaml:"-"`
LinesDeleted int `yaml:"-"`
Level int `yaml:"-"`
}
func (fd *ForkDefinition) hydrate(patchByName map[string]diff.FilePatch, remaining map[string]struct{}, level int) error {
fd.Level = level
for i, sub := range fd.Sub {
if err := sub.hydrate(patchByName, remaining, level+1); err != nil {
return fmt.Errorf("sub definition %d failed to hydrate: %w", i, err)
}
fd.LinesAdded += sub.LinesAdded
fd.LinesDeleted += sub.LinesDeleted
}
for i, globPattern := range fd.Globs {
for name, p := range patchByName {
if ok, err := filepath.Match(globPattern, name); err != nil {
return fmt.Errorf("failed to glob match entry %q against pattern %q", name, globPattern)
} else if ok {
if _, ok := remaining[name]; !ok {
return fmt.Errorf("file %q was matched by glob %d (%q) but is not remaining", name, i, globPattern)
}
delete(remaining, name)
fd.hydratePatch(name, p)
}
}
}
return nil
}
func (fd *ForkDefinition) hydratePatch(name string, p diff.FilePatch) {
stat := FilePatchStats{
Path: name,
LinesAdded: countOperations(p.Chunks(), diff.Add),
LinesDeleted: countOperations(p.Chunks(), diff.Delete),
Binary: p.IsBinary(),
Patch: p,
}
fd.Files = append(fd.Files, stat)
fd.LinesAdded += stat.LinesAdded
fd.LinesDeleted += stat.LinesDeleted
}