-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathweb.go
1074 lines (960 loc) · 26.1 KB
/
web.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 git
import (
"bytes"
"context"
"embed"
"fmt"
"html/template"
"io"
"io/fs"
"log/slog"
"mime"
"net/http"
"net/url"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
"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/bluekeyes/go-gitdiff/gitdiff"
"github.com/gorilla/feeds"
)
//go:embed tmpl/*
var tmplFS embed.FS
//go:embed static/*
var embedStaticFS embed.FS
type WebCtx struct {
Pr *PrCmd
Backend *Backend
Formatter *formatterHtml.Formatter
Logger *slog.Logger
Theme *chroma.Style
}
type ctxWeb struct{}
func getWebCtx(r *http.Request) (*WebCtx, error) {
data, ok := r.Context().Value(ctxWeb{}).(*WebCtx)
if data == nil || !ok {
return data, fmt.Errorf("webCtx not set on `r.Context()` for connection")
}
return data, nil
}
func setWebCtx(ctx context.Context, web *WebCtx) context.Context {
return context.WithValue(ctx, ctxWeb{}, web)
}
// converts contents of files in git tree to pretty formatted code.
func parseText(formatter *formatterHtml.Formatter, theme *chroma.Style, text string) (string, error) {
lexer := lexers.Get("diff")
iterator, err := lexer.Tokenise(nil, text)
if err != nil {
return text, err
}
var buf bytes.Buffer
err = formatter.Format(&buf, theme, iterator)
if err != nil {
return text, err
}
return buf.String(), nil
}
func ctxMdw(ctx context.Context, handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
handler(w, r.WithContext(ctx))
}
}
func shaFn(sha string) string {
if sha == "" {
return "(none)"
}
return truncateSha(sha)
}
func getTemplate(file string) *template.Template {
tmpl, err := template.New("").Funcs(template.FuncMap{
"sha": shaFn,
}).ParseFS(
tmplFS,
filepath.Join("tmpl", file),
filepath.Join("tmpl", "user-pill.html"),
filepath.Join("tmpl", "patchset.html"),
filepath.Join("tmpl", "range-diff.html"),
filepath.Join("tmpl", "pr-header.html"),
filepath.Join("tmpl", "pr-list-item.html"),
filepath.Join("tmpl", "pr-table.html"),
filepath.Join("tmpl", "pr-status.html"),
filepath.Join("tmpl", "base.html"),
)
if err != nil {
panic(err)
}
return tmpl
}
type LinkData struct {
Url template.URL
Text string
}
type PrTableData struct {
Prs []*PrListData
MetaData
}
type UserDetailData struct {
Prs []*PrListData
UserData UserData
MetaData
}
func createPrDataSorter(sort, sortDir string) func(a, b *PrListData) int {
return func(a *PrListData, b *PrListData) int {
if sort == "status" {
statusA := strings.ToLower(a.Status)
statusB := strings.ToLower(b.Status)
if sortDir == "asc" {
return strings.Compare(statusA, statusB)
} else {
return strings.Compare(statusB, statusA)
}
}
if sort == "title" {
titleA := strings.ToLower(a.Title)
titleB := strings.ToLower(b.Title)
if sortDir == "asc" {
return strings.Compare(titleA, titleB)
} else {
return strings.Compare(titleB, titleA)
}
}
if sort == "repo" {
repoA := strings.ToLower(a.RepoNs)
repoB := strings.ToLower(b.RepoNs)
if sortDir == "asc" {
return strings.Compare(repoA, repoB)
} else {
return strings.Compare(repoB, repoA)
}
}
if sort == "created_at" {
if sortDir == "asc" {
return a.DateOrig.Compare(b.DateOrig)
} else {
return b.DateOrig.Compare(a.DateOrig)
}
}
if sortDir == "desc" {
return int(b.ID) - int(a.ID)
}
return int(a.ID) - int(b.ID)
}
}
func getPrTableData(web *WebCtx, prs []*PatchRequest, query url.Values) ([]*PrListData, error) {
prdata := []*PrListData{}
status := strings.ToLower(query.Get("status"))
if status == "" {
status = "open"
}
username := strings.ToLower(query.Get("user"))
title := strings.ToLower(query.Get("title"))
sort := strings.ToLower(query.Get("sort"))
sortDir := strings.ToLower(query.Get("sort_dir"))
hasFilter := status != "" || username != "" || title != ""
for _, curpr := range prs {
user, err := web.Pr.GetUserByID(curpr.UserID)
if err != nil {
web.Logger.Error("cannot get user from pr", "err", err)
continue
}
pk, err := web.Backend.PubkeyToPublicKey(user.Pubkey)
if err != nil {
web.Logger.Error("cannot get pubkey from user public key", "err", err)
continue
}
repo, err := web.Pr.GetRepoByID(curpr.RepoID)
if err != nil {
web.Logger.Error("cannot get repo", "err", err)
continue
}
repoUser, err := web.Pr.GetUserByID(repo.UserID)
if err != nil {
web.Logger.Error("cannot get repo user", "err", err)
continue
}
if hasFilter {
if status != "" {
if status != curpr.Status {
continue
}
}
if username != "" {
if username != strings.ToLower(user.Name) {
continue
}
}
if title != "" {
if !strings.Contains(strings.ToLower(curpr.Name), title) {
continue
}
}
}
isAdmin := web.Backend.IsAdmin(pk)
repoNs := web.Backend.CreateRepoNs(repoUser.Name, repo.Name)
prls := &PrListData{
RepoNs: repoNs,
ID: curpr.ID,
UserData: UserData{
Name: user.Name,
IsAdmin: isAdmin,
Pubkey: user.Pubkey,
},
RepoLink: LinkData{
Url: template.URL(fmt.Sprintf("/r/%s/%s", repoUser.Name, repo.Name)),
Text: repoNs,
},
PrLink: LinkData{
Url: template.URL(fmt.Sprintf("/prs/%d", curpr.ID)),
Text: curpr.Name,
},
DateOrig: curpr.CreatedAt,
Date: curpr.CreatedAt.Format(web.Backend.Cfg.TimeFormat),
Status: curpr.Status,
}
prdata = append(prdata, prls)
}
if sort != "" {
if sortDir == "" {
sortDir = "asc"
}
slices.SortFunc(prdata, createPrDataSorter(sort, sortDir))
}
return prdata, nil
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
web, err := getWebCtx(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
prs, err := web.Pr.GetPatchRequests()
if err != nil {
web.Logger.Error("could not get prs", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
prdata, err := getPrTableData(web, prs, r.URL.Query())
if err != nil {
web.Logger.Error("could not get pr table data", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("content-type", "text/html")
tmpl := getTemplate("index.html")
err = tmpl.ExecuteTemplate(w, "index.html", PrTableData{
Prs: prdata,
MetaData: MetaData{
URL: web.Backend.Cfg.Url,
},
})
if err != nil {
web.Backend.Logger.Error("cannot execute template", "err", err)
}
}
type UserData struct {
UserID int64
Name string
IsAdmin bool
Pubkey string
CreatedAt string
}
type MetaData struct {
URL string
}
type PrListData struct {
UserData
RepoNs string
RepoLink LinkData
PrLink LinkData
Title string
ID int64
DateOrig time.Time
Date string
Status string
}
func userDetailHandler(w http.ResponseWriter, r *http.Request) {
userName := r.PathValue("user")
web, err := getWebCtx(r)
if err != nil {
web.Logger.Error("fetch web", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
user, err := web.Pr.GetUserByName(userName)
if err != nil {
web.Logger.Error("cannot find user by name", "err", err, "name", userName)
w.WriteHeader(http.StatusNotFound)
return
}
pk, err := web.Backend.PubkeyToPublicKey(user.Pubkey)
if err != nil {
web.Logger.Error("cannot parse pubkey for pr user", "err", err)
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
isAdmin := web.Backend.IsAdmin(pk)
prs, err := web.Pr.GetPatchRequests()
if err != nil {
web.Logger.Error("cannot get prs", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
query := r.URL.Query()
query.Set("user", userName)
prdata, err := getPrTableData(web, prs, query)
if err != nil {
web.Logger.Error("cannot get pr table data", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("content-type", "text/html")
tmpl := getTemplate("user-detail.html")
err = tmpl.ExecuteTemplate(w, "user-detail.html", UserDetailData{
Prs: prdata,
UserData: UserData{
UserID: user.ID,
Name: user.Name,
Pubkey: user.Pubkey,
CreatedAt: user.CreatedAt.Format(time.RFC3339),
IsAdmin: isAdmin,
},
MetaData: MetaData{
URL: web.Backend.Cfg.Url,
},
})
if err != nil {
web.Backend.Logger.Error("cannot execute template", "err", err)
}
}
type RepoDetailData struct {
Name string
UserID int64
Username string
Branch string
Prs []*PrListData
MetaData
}
func repoDetailHandler(w http.ResponseWriter, r *http.Request) {
userName := r.PathValue("user")
repoName := r.PathValue("repo")
web, err := getWebCtx(r)
if err != nil {
web.Logger.Error("fetch web", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
user, err := web.Pr.GetUserByName(userName)
if err != nil {
web.Logger.Error("cannot find user", "user", user, "err", err)
w.WriteHeader(http.StatusNotFound)
return
}
repo, err := web.Pr.GetRepoByName(user, repoName)
if err != nil {
web.Logger.Error("cannot find repo", "user", user, "err", err)
w.WriteHeader(http.StatusNotFound)
return
}
prs, err := web.Pr.GetPatchRequestsByRepoID(repo.ID)
if err != nil {
web.Logger.Error("cannot get prs", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
prdata, err := getPrTableData(web, prs, r.URL.Query())
if err != nil {
web.Logger.Error("cannot get pr table data", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("content-type", "text/html")
tmpl := getTemplate("repo-detail.html")
err = tmpl.ExecuteTemplate(w, "repo-detail.html", RepoDetailData{
Name: repo.Name,
UserID: user.ID,
Username: userName,
Prs: prdata,
MetaData: MetaData{
URL: web.Backend.Cfg.Url,
},
})
if err != nil {
web.Backend.Logger.Error("cannot execute template", "err", err)
}
}
type PrData struct {
UserData
ID int64
Title string
Date string
Status string
}
type PatchFile struct {
*gitdiff.File
Adds int64
Dels int64
DiffText template.HTML
}
type PatchData struct {
*Patch
PatchFiles []*PatchFile
PatchHeader *gitdiff.PatchHeader
Url template.URL
Review bool
FormattedAuthorDate string
}
type EventLogData struct {
*EventLog
UserData
*Patchset
FormattedPatchsetID string
Date string
}
type PatchsetData struct {
*Patchset
UserData
FormattedID string
Date string
RangeDiff []*RangeDiffOutput
}
type PrDetailData struct {
Page string
Repo LinkData
Pr PrData
Patchset *Patchset
PatchsetData *PatchsetData
Patches []PatchData
Branch string
Logs []EventLogData
Patchsets []PatchsetData
IsRangeDiff bool
MetaData
}
func createPrDetail(page string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
prID, err := strconv.Atoi(id)
if err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
web, err := getWebCtx(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
var pr *PatchRequest
var ps *Patchset
if page == "pr" {
pr, err = web.Pr.GetPatchRequestByID(int64(prID))
if err != nil {
web.Pr.Backend.Logger.Error("cannot get prs", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
} else if page == "ps" || page == "rd" {
ps, err = web.Pr.GetPatchsetByID(int64(prID))
if err != nil {
web.Pr.Backend.Logger.Error("cannot get patchset", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
pr, err = web.Pr.GetPatchRequestByID(int64(ps.PatchRequestID))
if err != nil {
web.Pr.Backend.Logger.Error("cannot get pr", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
patchsets, err := web.Pr.GetPatchsetsByPrID(pr.ID)
if err != nil {
web.Logger.Error("cannot get latest patchset", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// get patchsets and diff from previous patchset
patchsetsData := []PatchsetData{}
var selectedPatchsetData *PatchsetData
for idx, patchset := range patchsets {
user, err := web.Pr.GetUserByID(patchset.UserID)
if err != nil {
web.Logger.Error("could not get user for patch", "err", err)
continue
}
var prevPatchset *Patchset
if idx > 0 {
prevPatchset = patchsets[idx-1]
}
var rangeDiff []*RangeDiffOutput
if idx > 0 {
rangeDiff, err = web.Pr.DiffPatchsets(prevPatchset, patchset)
if err != nil {
web.Logger.Error("could not diff patchset", "err", err)
continue
}
}
pk, err := web.Backend.PubkeyToPublicKey(user.Pubkey)
if err != nil {
web.Logger.Error("cannot parse pubkey for pr user", "err", err)
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
// set selected patchset to latest when no ps already set
if ps == nil && idx == len(patchsets)-1 {
ps = patchset
}
data := PatchsetData{
Patchset: patchset,
FormattedID: getFormattedPatchsetID(patchset.ID),
UserData: UserData{
UserID: user.ID,
Name: user.Name,
IsAdmin: web.Backend.IsAdmin(pk),
Pubkey: user.Pubkey,
CreatedAt: user.CreatedAt.Format(time.RFC3339),
},
Date: patchset.CreatedAt.Format(time.RFC3339),
RangeDiff: rangeDiff,
}
patchsetsData = append(patchsetsData, data)
if ps != nil && ps.ID == patchset.ID {
selectedPatchsetData = &data
}
}
patchesData := []PatchData{}
if len(patchsetsData) >= 1 {
psID := ps.ID
patches, err := web.Pr.GetPatchesByPatchsetID(psID)
if err != nil {
web.Logger.Error("cannot get patches", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// TODO: a little hacky
reviewIDs := []int64{}
for _, data := range patchsetsData {
if psID != data.ID {
continue
}
if !data.Patchset.Review {
continue
}
for _, rdiff := range data.RangeDiff {
if rdiff.Type == "add" {
for _, patch := range patches {
commSha := truncateSha(patch.CommitSha)
if strings.Contains(rdiff.Header.String(), commSha) {
reviewIDs = append(reviewIDs, patch.ID)
break
}
}
}
}
break
}
for _, patch := range patches {
diffFiles, preamble, err := ParsePatch(patch.RawText)
if err != nil {
web.Logger.Error("cannot parse patch", "err", err)
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
header, err := gitdiff.ParsePatchHeader(preamble)
if err != nil {
web.Logger.Error("cannot parse patch", "err", err)
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
// highlight review
isReview := false
for _, pID := range reviewIDs {
if pID == patch.ID {
isReview = true
break
}
}
patchFiles := []*PatchFile{}
for _, file := range diffFiles {
var adds int64 = 0
var dels int64 = 0
for _, frag := range file.TextFragments {
adds += frag.LinesAdded
dels += frag.LinesDeleted
}
diffStr, err := parseText(web.Formatter, web.Theme, file.String())
if err != nil {
web.Logger.Error("cannot parse patch", "err", err)
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
patchFiles = append(patchFiles, &PatchFile{
File: file,
Adds: adds,
Dels: dels,
DiffText: template.HTML(diffStr),
})
}
timestamp := patch.AuthorDate.Format(web.Backend.Cfg.TimeFormat)
patchesData = append(patchesData, PatchData{
Patch: patch,
Url: template.URL(fmt.Sprintf("patch-%d", patch.ID)),
Review: isReview,
FormattedAuthorDate: timestamp,
PatchFiles: patchFiles,
PatchHeader: header,
})
}
}
user, err := web.Pr.GetUserByID(pr.UserID)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("content-type", "text/html")
tmpl := getTemplate("pr-detail.html")
pk, err := web.Backend.PubkeyToPublicKey(user.Pubkey)
if err != nil {
web.Logger.Error("cannot parse pubkey for pr user", "err", err)
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
isAdmin := web.Backend.IsAdmin(pk)
logs, err := web.Pr.GetEventLogsByPrID(pr.ID)
if err != nil {
web.Logger.Error("cannot get logs for pr", "err", err)
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
slices.SortFunc(logs, func(a *EventLog, b *EventLog) int {
return a.CreatedAt.Compare(b.CreatedAt)
})
logData := []EventLogData{}
for _, eventlog := range logs {
user, _ := web.Pr.GetUserByID(eventlog.UserID)
pk, err := web.Backend.PubkeyToPublicKey(user.Pubkey)
if err != nil {
web.Logger.Error("cannot parse pubkey for pr user", "err", err)
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
var logps *Patchset
if eventlog.PatchsetID.Int64 > 0 {
logps, err = web.Pr.GetPatchsetByID(eventlog.PatchsetID.Int64)
if err != nil {
web.Logger.Error("cannot get patchset", "err", err, "ps", eventlog.PatchsetID)
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
}
logData = append(logData, EventLogData{
EventLog: eventlog,
FormattedPatchsetID: getFormattedPatchsetID(eventlog.PatchsetID.Int64),
Patchset: logps,
UserData: UserData{
UserID: user.ID,
Name: user.Name,
IsAdmin: web.Backend.IsAdmin(pk),
Pubkey: user.Pubkey,
CreatedAt: user.CreatedAt.Format(time.RFC3339),
},
Date: eventlog.CreatedAt.Format(web.Backend.Cfg.TimeFormat),
})
}
repo, err := web.Pr.GetRepoByID(pr.RepoID)
if err != nil {
web.Logger.Error("cannot get repo for pr", "err", err)
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
repoOwner, err := web.Pr.GetUserByID(repo.UserID)
if err != nil {
web.Logger.Error("cannot get repo for pr", "err", err)
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
repoNs := web.Backend.CreateRepoNs(repoOwner.Name, repo.Name)
url := fmt.Sprintf("/r/%s/%s", repoOwner.Name, repo.Name)
err = tmpl.ExecuteTemplate(w, "pr-detail.html", PrDetailData{
Page: "pr",
Repo: LinkData{
Url: template.URL(url),
Text: repoNs,
},
Branch: "main",
Patchset: ps,
PatchsetData: selectedPatchsetData,
IsRangeDiff: page == "rd",
Patches: patchesData,
Patchsets: patchsetsData,
Logs: logData,
Pr: PrData{
ID: pr.ID,
UserData: UserData{
UserID: user.ID,
Name: user.Name,
IsAdmin: isAdmin,
Pubkey: user.Pubkey,
CreatedAt: user.CreatedAt.Format(time.RFC3339),
},
Title: pr.Name,
Date: pr.CreatedAt.Format(web.Backend.Cfg.TimeFormat),
Status: pr.Status,
},
MetaData: MetaData{
URL: web.Backend.Cfg.Url,
},
})
if err != nil {
web.Backend.Logger.Error("cannot execute template", "err", err)
}
}
}
func rssHandler(w http.ResponseWriter, r *http.Request) {
web, err := getWebCtx(r)
if err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
desc := fmt.Sprintf(
"Events related to git collaboration server %s",
web.Backend.Cfg.Url,
)
feed := &feeds.Feed{
Title: fmt.Sprintf("%s events", web.Backend.Cfg.Url),
Link: &feeds.Link{Href: web.Backend.Cfg.Url},
Description: desc,
Author: &feeds.Author{Name: "git collaboration server"},
Created: time.Now(),
}
var eventLogs []*EventLog
id := r.PathValue("id")
pubkey := r.URL.Query().Get("pubkey")
username := r.PathValue("user")
repoName := r.PathValue("repo")
if id != "" {
var prID int64
prID, err = getPrID(id)
if err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
eventLogs, err = web.Pr.GetEventLogsByPrID(prID)
} else if pubkey != "" {
user, perr := web.Pr.GetUserByPubkey(pubkey)
if perr != nil {
w.WriteHeader(http.StatusNotFound)
return
}
eventLogs, err = web.Pr.GetEventLogsByUserID(user.ID)
} else if username != "" {
user, perr := web.Pr.GetUserByName(username)
if perr != nil {
w.WriteHeader(http.StatusNotFound)
return
}
eventLogs, err = web.Pr.GetEventLogsByUserID(user.ID)
} else if repoName != "" {
user, perr := web.Pr.GetUserByName(username)
if perr != nil {
w.WriteHeader(http.StatusNotFound)
return
}
eventLogs, err = web.Pr.GetEventLogsByRepoName(user, repoName)
} else {
eventLogs, err = web.Pr.GetEventLogs()
}
if err != nil {
web.Logger.Error("rss could not get eventLogs", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
var feedItems []*feeds.Item
for _, eventLog := range eventLogs {
user, err := web.Pr.GetUserByID(eventLog.UserID)
if err != nil {
web.Logger.Error("user not found for event log", "id", eventLog.ID, "err", err)
continue
}
repo := &Repo{Name: "unknown"}
if eventLog.RepoID.Valid {
repo, err = web.Pr.GetRepoByID(eventLog.RepoID.Int64)
if err != nil {
web.Logger.Error("repo not found for event log", "id", eventLog.ID, "err", err)
continue
}
}
realUrl := fmt.Sprintf("%s/prs/%d", web.Backend.Cfg.Url, eventLog.PatchRequestID.Int64)
content := fmt.Sprintf(
"<div><div>RepoID: %s</div><div>PatchRequestID: %d</div><div>Event: %s</div><div>Created: %s</div><div>Data: %s</div></div>",
web.Backend.CreateRepoNs(user.Name, repo.Name),
eventLog.PatchRequestID.Int64,
eventLog.Event,
eventLog.CreatedAt.Format(time.RFC3339Nano),
eventLog.Data,
)
pr, err := web.Pr.GetPatchRequestByID(eventLog.PatchRequestID.Int64)
if err != nil {
continue
}
title := fmt.Sprintf(
`%s in %s for PR "%s" (#%d)`,
eventLog.Event,
web.Backend.CreateRepoNs(user.Name, repo.Name),
pr.Name,
eventLog.PatchRequestID.Int64,
)
item := &feeds.Item{
Id: fmt.Sprintf("%d", eventLog.ID),
Title: title,
Link: &feeds.Link{Href: realUrl},
Content: content,
Created: eventLog.CreatedAt,
Description: title,
Author: &feeds.Author{Name: user.Name},
}
feedItems = append(feedItems, item)
}
feed.Items = feedItems
rss, err := feed.ToAtom()
if err != nil {
web.Logger.Error("could not generate atom rss feed", "err", err)
http.Error(w, "Could not generate atom rss feed", http.StatusInternalServerError)
}
w.Header().Add("Content-Type", "application/atom+xml; charset=utf-8")
_, err = w.Write([]byte(rss))
if err != nil {
web.Logger.Error("write error atom rss feed", "err", err)
}
}
func chromaStyleHandler(w http.ResponseWriter, r *http.Request) {
web, err := getWebCtx(r)
if err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
w.Header().Add("content-type", "text/css")
err = web.Formatter.WriteCSS(w, web.Theme)
if err != nil {
web.Backend.Logger.Error("cannot write css file", "err", err)
}
}
func serveFile(userfs fs.FS, embedfs fs.FS) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
web, err := getWebCtx(r)
if err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
logger := web.Logger
file := r.PathValue("file")
logger.Info("serving file", "file", file)
// merging both embedded fs and whatever user provides
var reader fs.File
if userfs == nil {
reader, err = embedfs.Open(file)
} else {
reader, err = userfs.Open(file)
if err != nil {
// serve embeded static folder
reader, err = embedfs.Open(file)
}
}
if err != nil {
logger.Error(err.Error())
http.Error(w, "file not found", 404)
return
}
contents, err := io.ReadAll(reader)
if err != nil {
logger.Error(err.Error())
http.Error(w, "file not found", 404)
return
}
contentType := mime.TypeByExtension(filepath.Ext(file))
if contentType == "" {
contentType = http.DetectContentType(contents)
}
w.Header().Add("Content-Type", contentType)
_, err = w.Write(contents)
if err != nil {
logger.Error(err.Error())
http.Error(w, "server error", 500)
return
}
}
}
func getUserDefinedFS(datadir, dirName string) fs.FS {
dir := filepath.Join(datadir, dirName)
_, err := os.Stat(dir)