-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
executable file
·1135 lines (980 loc) · 24.5 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"embed"
_ "embed"
"flag"
"fmt"
"html/template"
"log/slog"
"math"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/alecthomas/chroma/v2"
formatterHtml "github.com/alecthomas/chroma/v2/formatters/html"
"github.com/alecthomas/chroma/v2/lexers"
"github.com/alecthomas/chroma/v2/styles"
"github.com/dustin/go-humanize"
git "github.com/gogs/git-module"
)
//go:embed html/*.tmpl static/*
var efs embed.FS
type Config struct {
// required params
Outdir string
// abs path to git repo
RepoPath string
// optional params
// generate logs anad tree based on the git revisions provided
Revs []string
// description of repo used in the header of site
Desc string
// maximum number of commits that we will process in descending order
MaxCommits int
// name of the readme file
Readme string
// In order to get the latest commit per file we do a `git rev-list {ref} {file}`
// which is n+1 where n is a file in the tree.
// We offer a way to disable showing the latest commit in the output
// for those who want a faster build time
HideTreeLastCommit bool
// user-defined urls
HomeURL template.URL
CloneURL template.URL
// https://developer.mozilla.org/en-US/docs/Web/API/URL_API/Resolving_relative_references#root_relative
RootRelative string
// computed
// cache for skipping commits, trees, etc.
Cache map[string]bool
// mutex for Cache
Mutex sync.RWMutex
// pretty name for the repo
RepoName string
// logger
Logger *slog.Logger
// chroma style
Theme *chroma.Style
Formatter *formatterHtml.Formatter
}
type RevInfo interface {
ID() string
Name() string
}
// revision data
type RevData struct {
id string
name string
Config *Config
}
func (r *RevData) ID() string {
return r.id
}
func (r *RevData) Name() string {
return r.name
}
func (r *RevData) TreeURL() template.URL {
return r.Config.getTreeURL(r)
}
func (r *RevData) LogURL() template.URL {
return r.Config.getLogsURL(r)
}
type TagData struct {
Name string
URL template.URL
}
type CommitData struct {
SummaryStr string
URL template.URL
WhenStr string
AuthorStr string
ShortID string
ParentID string
Refs []*RefInfo
*git.Commit
}
type TreeItem struct {
IsTextFile bool
IsDir bool
Size string
NumLines int
Name string
Icon string
Path string
URL template.URL
CommitID string
CommitURL template.URL
Summary string
When string
Author *git.Signature
Entry *git.TreeEntry
Crumbs []*Breadcrumb
}
type DiffRender struct {
NumFiles int
TotalAdditions int
TotalDeletions int
Files []*DiffRenderFile
}
type DiffRenderFile struct {
FileType string
OldMode git.EntryMode
OldName string
Mode git.EntryMode
Name string
Content template.HTML
NumAdditions int
NumDeletions int
}
type RefInfo struct {
ID string
Refspec string
URL template.URL
}
type BranchOutput struct {
Readme string
LastCommit *git.Commit
}
type SiteURLs struct {
HomeURL template.URL
CloneURL template.URL
SummaryURL template.URL
RefsURL template.URL
}
type PageData struct {
Repo *Config
SiteURLs *SiteURLs
RevData *RevData
}
type SummaryPageData struct {
*PageData
Readme template.HTML
}
type TreePageData struct {
*PageData
Tree *TreeRoot
}
type LogPageData struct {
*PageData
NumCommits int
Logs []*CommitData
}
type FilePageData struct {
*PageData
Contents template.HTML
Item *TreeItem
}
type CommitPageData struct {
*PageData
CommitMsg template.HTML
CommitID string
Commit *CommitData
Diff *DiffRender
Parent string
ParentURL template.URL
CommitURL template.URL
}
type RefPageData struct {
*PageData
Refs []*RefInfo
}
type WriteData struct {
Template string
Filename string
Subdir string
Data interface{}
}
func bail(err error) {
if err != nil {
panic(err)
}
}
func diffFileType(_type git.DiffFileType) string {
if _type == git.DiffFileAdd {
return "A"
} else if _type == git.DiffFileChange {
return "M"
} else if _type == git.DiffFileDelete {
return "D"
} else if _type == git.DiffFileRename {
return "R"
}
return ""
}
// converts contents of files in git tree to pretty formatted code
func (c *Config) parseText(filename string, text string) (string, error) {
lexer := lexers.Match(filename)
if lexer == nil {
lexer = lexers.Analyse(text)
}
if lexer == nil {
lexer = lexers.Get("plaintext")
}
iterator, err := lexer.Tokenise(nil, text)
if err != nil {
return text, err
}
var buf bytes.Buffer
err = c.Formatter.Format(&buf, c.Theme, iterator)
if err != nil {
return text, err
}
return buf.String(), nil
}
// isText reports whether a significant prefix of s looks like correct UTF-8;
// that is, if it is likely that s is human-readable text.
func isText(s string) bool {
const max = 1024 // at least utf8.UTFMax
if len(s) > max {
s = s[0:max]
}
for i, c := range s {
if i+utf8.UTFMax > len(s) {
// last char may be incomplete - ignore
break
}
if c == 0xFFFD || c < ' ' && c != '\n' && c != '\t' && c != '\f' && c != '\r' {
// decoding error or control character - not a text file
return false
}
}
return true
}
// isTextFile reports whether the file has a known extension indicating
// a text file, or if a significant chunk of the specified file looks like
// correct UTF-8; that is, if it is likely that the file contains human-
// readable text.
func isTextFile(text string) bool {
num := math.Min(float64(len(text)), 1024)
return isText(text[0:int(num)])
}
func toPretty(b int64) string {
return humanize.Bytes(uint64(b))
}
func repoName(root string) string {
_, file := filepath.Split(root)
return file
}
func readmeFile(repo *Config) string {
if repo.Readme == "" {
return "readme.md"
}
return strings.ToLower(repo.Readme)
}
func (c *Config) writeHtml(writeData *WriteData) {
ts, err := template.ParseFS(
efs,
writeData.Template,
"html/header.partial.tmpl",
"html/footer.partial.tmpl",
"html/base.layout.tmpl",
)
bail(err)
dir := filepath.Join(c.Outdir, writeData.Subdir)
err = os.MkdirAll(dir, os.ModePerm)
bail(err)
fp := filepath.Join(dir, writeData.Filename)
c.Logger.Info("writing", "filepath", fp)
w, err := os.OpenFile(fp, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
bail(err)
err = ts.Execute(w, writeData.Data)
bail(err)
}
func (c *Config) copyStatic(dir string) error {
entries, err := efs.ReadDir(dir)
bail(err)
for _, e := range entries {
infp := filepath.Join(dir, e.Name())
if e.IsDir() {
continue
}
w, err := efs.ReadFile(infp)
bail(err)
fp := filepath.Join(c.Outdir, e.Name())
c.Logger.Info("writing", "filepath", fp)
os.WriteFile(fp, w, 0644)
}
return nil
}
func (c *Config) writeRootSummary(data *PageData, readme template.HTML) {
c.Logger.Info("writing root html", "repoPath", c.RepoPath)
c.writeHtml(&WriteData{
Filename: "index.html",
Template: "html/summary.page.tmpl",
Data: &SummaryPageData{
PageData: data,
Readme: readme,
},
})
}
func (c *Config) writeTree(data *PageData, tree *TreeRoot) {
c.Logger.Info("writing tree", "treePath", tree.Path)
c.writeHtml(&WriteData{
Filename: "index.html",
Subdir: tree.Path,
Template: "html/tree.page.tmpl",
Data: &TreePageData{
PageData: data,
Tree: tree,
},
})
}
func (c *Config) writeLog(data *PageData, logs []*CommitData) {
c.Logger.Info("writing log file", "revision", data.RevData.Name())
c.writeHtml(&WriteData{
Filename: "index.html",
Subdir: getLogBaseDir(data.RevData),
Template: "html/log.page.tmpl",
Data: &LogPageData{
PageData: data,
NumCommits: len(logs),
Logs: logs,
},
})
}
func (c *Config) writeRefs(data *PageData, refs []*RefInfo) {
c.Logger.Info("writing refs", "repoPath", c.RepoPath)
c.writeHtml(&WriteData{
Filename: "refs.html",
Template: "html/refs.page.tmpl",
Data: &RefPageData{
PageData: data,
Refs: refs,
},
})
}
func (c *Config) writeHTMLTreeFile(pageData *PageData, treeItem *TreeItem) string {
readme := ""
b, err := treeItem.Entry.Blob().Bytes()
bail(err)
str := string(b)
treeItem.IsTextFile = isTextFile(str)
contents := "binary file, cannot display"
if treeItem.IsTextFile {
treeItem.NumLines = len(strings.Split(str, "\n"))
contents, err = c.parseText(treeItem.Entry.Name(), string(b))
bail(err)
}
d := filepath.Dir(treeItem.Path)
nameLower := strings.ToLower(treeItem.Entry.Name())
summary := readmeFile(pageData.Repo)
if nameLower == summary {
readme = contents
}
c.writeHtml(&WriteData{
Filename: fmt.Sprintf("%s.html", treeItem.Entry.Name()),
Template: "html/file.page.tmpl",
Data: &FilePageData{
PageData: pageData,
Contents: template.HTML(contents),
Item: treeItem,
},
Subdir: getFileDir(pageData.RevData, d),
})
return readme
}
func (c *Config) writeLogDiff(repo *git.Repository, pageData *PageData, commit *CommitData) {
commitID := commit.ID.String()
c.Mutex.RLock()
hasCommit := c.Cache[commitID]
c.Mutex.RUnlock()
if hasCommit {
c.Logger.Info("commit file already generated, skipping", "commitID", getShortID(commitID))
return
} else {
c.Mutex.Lock()
c.Cache[commitID] = true
c.Mutex.Unlock()
}
diff, err := repo.Diff(
commitID,
0,
0,
0,
git.DiffOptions{},
)
bail(err)
rnd := &DiffRender{
NumFiles: diff.NumFiles(),
TotalAdditions: diff.TotalAdditions(),
TotalDeletions: diff.TotalDeletions(),
}
fls := []*DiffRenderFile{}
for _, file := range diff.Files {
fl := &DiffRenderFile{
FileType: diffFileType(file.Type),
OldMode: file.OldMode(),
OldName: file.OldName(),
Mode: file.Mode(),
Name: file.Name,
NumAdditions: file.NumAdditions(),
NumDeletions: file.NumDeletions(),
}
content := ""
for _, section := range file.Sections {
for _, line := range section.Lines {
content += fmt.Sprintf("%s\n", line.Content)
}
}
// set filename to something our `ParseText` recognizes (e.g. `.diff`)
finContent, err := c.parseText("commit.diff", content)
bail(err)
fl.Content = template.HTML(finContent)
fls = append(fls, fl)
}
rnd.Files = fls
commitData := &CommitPageData{
PageData: pageData,
Commit: commit,
CommitID: getShortID(commitID),
Diff: rnd,
Parent: getShortID(commit.ParentID),
CommitURL: c.getCommitURL(commitID),
ParentURL: c.getCommitURL(commit.ParentID),
}
c.writeHtml(&WriteData{
Filename: fmt.Sprintf("%s.html", commitID),
Template: "html/commit.page.tmpl",
Subdir: "commits",
Data: commitData,
})
}
func (c *Config) getSummaryURL() template.URL {
url := c.RootRelative + "index.html"
return template.URL(url)
}
func (c *Config) getRefsURL() template.URL {
url := c.RootRelative + "refs.html"
return template.URL(url)
}
// controls the url for trees and logs
// /logs/getRevIDForURL()/index.html
// /tree/getRevIDForURL()/item/file.x.html
func getRevIDForURL(info RevInfo) string {
return info.Name()
}
func getTreeBaseDir(info RevInfo) string {
subdir := getRevIDForURL(info)
return filepath.Join("/", "tree", subdir)
}
func getLogBaseDir(info RevInfo) string {
subdir := getRevIDForURL(info)
return filepath.Join("/", "logs", subdir)
}
func getFileBaseDir(info RevInfo) string {
return filepath.Join(getTreeBaseDir(info), "item")
}
func getFileDir(info RevInfo, fname string) string {
return filepath.Join(getFileBaseDir(info), fname)
}
func (c *Config) getFileURL(info RevInfo, fname string) template.URL {
return c.compileURL(getFileBaseDir(info), fname)
}
func (c *Config) compileURL(dir, fname string) template.URL {
purl := c.RootRelative + strings.TrimPrefix(dir, "/")
url := filepath.Join(purl, fname)
return template.URL(url)
}
func (c *Config) getTreeURL(info RevInfo) template.URL {
dir := getTreeBaseDir(info)
return c.compileURL(dir, "index.html")
}
func (c *Config) getLogsURL(info RevInfo) template.URL {
dir := getLogBaseDir(info)
return c.compileURL(dir, "index.html")
}
func (c *Config) getCommitURL(commitID string) template.URL {
url := fmt.Sprintf("%scommits/%s.html", c.RootRelative, commitID)
return template.URL(url)
}
func (c *Config) getURLs() *SiteURLs {
return &SiteURLs{
HomeURL: c.HomeURL,
CloneURL: c.CloneURL,
RefsURL: c.getRefsURL(),
SummaryURL: c.getSummaryURL(),
}
}
func getShortID(id string) string {
return id[:7]
}
func (c *Config) writeRepo() *BranchOutput {
c.Logger.Info("writing repo", "repoPath", c.RepoPath)
repo, err := git.Open(c.RepoPath)
bail(err)
refs, err := repo.ShowRef(git.ShowRefOptions{Heads: true, Tags: true})
bail(err)
var first *RevData
revs := []*RevData{}
for _, revStr := range c.Revs {
fullRevID, err := repo.RevParse(revStr)
bail(err)
revID := getShortID(fullRevID)
revName := revID
// if it's a reference then label it as such
for _, ref := range refs {
if revStr == git.RefShortName(ref.Refspec) || revStr == ref.Refspec {
revName = revStr
break
}
}
data := &RevData{
id: fullRevID,
name: revName,
Config: c,
}
if first == nil {
first = data
}
revs = append(revs, data)
}
if first == nil {
bail(fmt.Errorf("could find find a git reference that matches criteria"))
}
refInfoMap := map[string]*RefInfo{}
mainOutput := &BranchOutput{}
claimed := false
for _, revData := range revs {
refInfoMap[revData.Name()] = &RefInfo{
ID: revData.ID(),
Refspec: revData.Name(),
URL: revData.TreeURL(),
}
}
// loop through ALL refs that don't have URLs
// and add them to the map
for _, ref := range refs {
refspec := git.RefShortName(ref.Refspec)
if refInfoMap[refspec] != nil {
continue
}
refInfoMap[refspec] = &RefInfo{
ID: ref.ID,
Refspec: refspec,
}
}
// gather lists of refs to display on refs.html page
refInfoList := []*RefInfo{}
for _, val := range refInfoMap {
refInfoList = append(refInfoList, val)
}
sort.Slice(refInfoList, func(i, j int) bool {
urlI := refInfoList[i].URL
urlJ := refInfoList[j].URL
refI := refInfoList[i].Refspec
refJ := refInfoList[j].Refspec
if urlI == urlJ {
return refI < refJ
}
return urlI > urlJ
})
for _, revData := range revs {
c.Logger.Info("writing revision", "revision", revData.Name())
data := &PageData{
Repo: c,
RevData: revData,
SiteURLs: c.getURLs(),
}
if claimed {
go func() {
c.writeRevision(repo, data, refInfoList)
}()
} else {
branchOutput := c.writeRevision(repo, data, refInfoList)
mainOutput = branchOutput
claimed = true
}
}
// use the first revision in our list to generate
// the root summary, logs, and tree the user can click
revData := &RevData{
id: first.ID(),
name: first.Name(),
Config: c,
}
data := &PageData{
RevData: revData,
Repo: c,
SiteURLs: c.getURLs(),
}
c.writeRefs(data, refInfoList)
c.writeRootSummary(data, template.HTML(mainOutput.Readme))
return mainOutput
}
type TreeRoot struct {
Path string
Items []*TreeItem
Crumbs []*Breadcrumb
}
type TreeWalker struct {
treeItem chan *TreeItem
tree chan *TreeRoot
HideTreeLastCommit bool
PageData *PageData
Repo *git.Repository
Config *Config
}
type Breadcrumb struct {
Text string
URL template.URL
IsLast bool
}
func (tw *TreeWalker) calcBreadcrumbs(curpath string) []*Breadcrumb {
if curpath == "" {
return []*Breadcrumb{}
}
parts := strings.Split(curpath, string(os.PathSeparator))
rootURL := tw.Config.compileURL(
getTreeBaseDir(tw.PageData.RevData),
"index.html",
)
crumbs := make([]*Breadcrumb, len(parts)+1)
crumbs[0] = &Breadcrumb{
URL: rootURL,
Text: tw.PageData.Repo.RepoName,
}
cur := ""
for idx, d := range parts {
crumb := filepath.Join(getFileBaseDir(tw.PageData.RevData), cur, d)
crumbUrl := tw.Config.compileURL(crumb, "index.html")
crumbs[idx+1] = &Breadcrumb{
Text: d,
URL: crumbUrl,
}
if idx == len(parts)-1 {
crumbs[idx+1].IsLast = true
}
cur = filepath.Join(cur, d)
}
return crumbs
}
func FilenameToDevIcon(filename string) string {
ext := filepath.Ext(filename)
extMappr := map[string]string{
".html": "html5",
".go": "go",
".py": "python",
".css": "css3",
".js": "javascript",
".md": "markdown",
".ts": "typescript",
".tsx": "react",
".jsx": "react",
}
nameMappr := map[string]string{
"Makefile": "cmake",
"Dockerfile": "docker",
}
icon := extMappr[ext]
if icon == "" {
icon = nameMappr[filename]
}
return fmt.Sprintf("devicon-%s-original", icon)
}
func (tw *TreeWalker) NewTreeItem(entry *git.TreeEntry, curpath string, crumbs []*Breadcrumb) *TreeItem {
typ := entry.Type()
fname := filepath.Join(curpath, entry.Name())
item := &TreeItem{
Size: toPretty(entry.Size()),
Name: entry.Name(),
Path: fname,
Entry: entry,
URL: tw.Config.getFileURL(tw.PageData.RevData, fname),
Crumbs: crumbs,
}
// `git rev-list` is pretty expensive here, so we have a flag to disable
if tw.HideTreeLastCommit {
// c.Logger.Info("skipping the process of finding the last commit for each file")
} else {
id := tw.PageData.RevData.ID()
lastCommits, err := tw.Repo.RevList([]string{id}, git.RevListOptions{
Path: item.Path,
CommandOptions: git.CommandOptions{Args: []string{"-1"}},
})
bail(err)
var lc *git.Commit
if len(lastCommits) > 0 {
lc = lastCommits[0]
}
item.CommitURL = tw.Config.getCommitURL(lc.ID.String())
item.CommitID = getShortID(lc.ID.String())
item.Summary = lc.Summary()
item.When = lc.Author.When.Format(time.DateOnly)
item.Author = lc.Author
}
fpath := tw.Config.getFileURL(tw.PageData.RevData, fmt.Sprintf("%s.html", fname))
if typ == git.ObjectTree {
item.IsDir = true
fpath = tw.Config.compileURL(
filepath.Join(
getFileBaseDir(tw.PageData.RevData),
curpath,
entry.Name(),
),
"index.html",
)
} else if typ == git.ObjectBlob {
item.Icon = FilenameToDevIcon(item.Name)
}
item.URL = fpath
return item
}
func (tw *TreeWalker) walk(tree *git.Tree, curpath string) {
entries, err := tree.Entries()
bail(err)
crumbs := tw.calcBreadcrumbs(curpath)
treeEntries := []*TreeItem{}
for _, entry := range entries {
typ := entry.Type()
item := tw.NewTreeItem(entry, curpath, crumbs)
if typ == git.ObjectTree {
item.IsDir = true
re, _ := tree.Subtree(entry.Name())
tw.walk(re, item.Path)
treeEntries = append(treeEntries, item)
tw.treeItem <- item
} else if typ == git.ObjectBlob {
treeEntries = append(treeEntries, item)
tw.treeItem <- item
}
}
sort.Slice(treeEntries, func(i, j int) bool {
nameI := treeEntries[i].Name
nameJ := treeEntries[j].Name
if treeEntries[i].IsDir && treeEntries[j].IsDir {
return nameI < nameJ
}
if treeEntries[i].IsDir && !treeEntries[j].IsDir {
return true
}
if !treeEntries[i].IsDir && treeEntries[j].IsDir {
return false
}
return nameI < nameJ
})
fpath := filepath.Join(
getFileBaseDir(tw.PageData.RevData),
curpath,
)
// root gets a special spot outside of `item` subdir
if curpath == "" {
fpath = getTreeBaseDir(tw.PageData.RevData)
}
tw.tree <- &TreeRoot{
Path: fpath,
Items: treeEntries,
Crumbs: crumbs,
}
if curpath == "" {
close(tw.tree)
close(tw.treeItem)
}
}
func (c *Config) writeRevision(repo *git.Repository, pageData *PageData, refs []*RefInfo) *BranchOutput {
c.Logger.Info(
"compiling revision",
"repoName", c.RepoName,
"revision", pageData.RevData.Name(),
)
output := &BranchOutput{}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
pageSize := pageData.Repo.MaxCommits
if pageSize == 0 {
pageSize = 5000
}
commits, err := repo.CommitsByPage(pageData.RevData.ID(), 0, pageSize)
bail(err)
logs := []*CommitData{}
for i, commit := range commits {
if i == 0 {
output.LastCommit = commit
}
tags := []*RefInfo{}
for _, ref := range refs {
if commit.ID.String() == ref.ID {
tags = append(tags, ref)
}
}
parentSha, _ := commit.ParentID(0)
parentID := ""
if parentSha == nil {
parentID = commit.ID.String()
} else {
parentID = parentSha.String()
}
logs = append(logs, &CommitData{
ParentID: parentID,
URL: c.getCommitURL(commit.ID.String()),
ShortID: getShortID(commit.ID.String()),
SummaryStr: commit.Summary(),
AuthorStr: commit.Author.Name,
WhenStr: commit.Author.When.Format(time.DateOnly),
Commit: commit,
Refs: tags,
})
}
c.writeLog(pageData, logs)
for _, cm := range logs {
wg.Add(1)
go func(commit *CommitData) {
defer wg.Done()
c.writeLogDiff(repo, pageData, commit)
}(cm)
}
}()
tree, err := repo.LsTree(pageData.RevData.ID())
bail(err)
readme := ""
entries := make(chan *TreeItem)
subtrees := make(chan *TreeRoot)
tw := &TreeWalker{
Config: c,
PageData: pageData,
Repo: repo,
treeItem: entries,
tree: subtrees,
}
wg.Add(1)
go func() {
defer wg.Done()
tw.walk(tree, "")
}()
wg.Add(1)
go func() {
defer wg.Done()
for e := range entries {
wg.Add(1)
go func(entry *TreeItem) {
defer wg.Done()
if entry.IsDir {
return
}
readmeStr := c.writeHTMLTreeFile(pageData, entry)
if readmeStr != "" {
readme = readmeStr
}
}(e)
}