mugit/internal/handlers/repo.go(view raw)
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 |
package handlers
import (
"bytes"
"errors"
"fmt"
"html/template"
"io"
"log/slog"
"net/http"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"olexsmir.xyz/mugit/internal/git"
"olexsmir.xyz/mugit/internal/markdown"
)
type Meta struct {
Title string
Description string
Host string
IsEmpty bool
GoMod bool
SSHEnabled bool
}
type RepoBase struct {
Ref string
Desc string
}
type PageData[T any] struct {
Meta Meta
RepoName string // empty for non-repo pages, needed for _head.html to compile
P T
}
func (h *handlers) indexHandler(w http.ResponseWriter, r *http.Request) {
repos, err := h.listPublicRepos()
if err != nil {
h.write500(w, err)
return
}
h.templ(w, "index", h.pageData(nil, repos))
}
type RepoIndex struct {
Desc string
IsEmpty bool
Readme template.HTML
Ref string
Commits []*git.Commit
IsMirror bool
MirrorURL string
MirrorLastSync time.Time
}
func (h *handlers) repoIndex(w http.ResponseWriter, r *http.Request) {
repo, err := h.openPublicRepo(r.PathValue("name"), "")
if err != nil {
h.write404(w, err)
return
}
desc, err := repo.Description()
if err != nil {
h.write500(w, err)
return
}
p := RepoIndex{Desc: desc, IsEmpty: repo.IsEmpty()}
if p.IsEmpty {
h.templ(w, "repo_index", h.pageData(repo, p))
return
}
p.Ref, err = repo.FindMasterBranch(h.c.Repo.Masters)
if err != nil {
h.write500(w, err)
return
}
p.Readme, err = h.renderReadme(repo, p.Ref, "")
if err != nil {
h.write500(w, err)
return
}
p.Commits, err = repo.Commits("")
if err != nil {
h.write500(w, err)
return
}
if len(p.Commits) >= 3 {
p.Commits = p.Commits[:3:3]
}
if isMirror, err := repo.IsMirror(); isMirror && err == nil {
p.IsMirror = true
p.MirrorURL, _ = repo.RemoteURL()
p.MirrorLastSync, _ = repo.LastSync()
}
h.templ(w, "repo_index", h.pageData(repo, p))
}
type RepoTree struct {
Desc string
Ref string
Tree []git.NiceTree
ParentPath string
DotDot string
Readme template.HTML
}
func (h *handlers) repoTreeHandler(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
ref := h.parseRef(r.PathValue("ref"))
treePath := r.PathValue("rest")
repo, err := h.openPublicRepo(name, ref)
if err != nil {
h.write404(w, err)
return
}
desc, err := repo.Description()
if err != nil {
h.write500(w, err)
return
}
tree, err := repo.FileTree(treePath)
if err != nil {
h.write500(w, err)
return
}
readme, err := h.renderReadme(repo, ref, treePath)
if err != nil {
h.write500(w, err)
return
}
h.templ(w, "repo_tree", h.pageData(repo, RepoTree{
Desc: desc,
Ref: ref,
Tree: tree,
ParentPath: treePath,
DotDot: filepath.Dir(treePath),
Readme: readme,
}))
}
type RepoFile struct {
Ref string
Desc string
LineCount []int
Path string
IsImage bool
IsBinary bool
Content string
Mime string
Size int64
}
func (h *handlers) fileContentsHandler(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
ref := h.parseRef(r.PathValue("ref"))
treePath := r.PathValue("rest")
var raw bool
if rawParam, err := strconv.ParseBool(r.URL.Query().Get("raw")); err == nil {
raw = rawParam
}
repo, err := h.openPublicRepo(name, ref)
if err != nil {
h.write404(w, err)
return
}
fc, err := repo.FileContent(treePath)
if err != nil {
if errors.Is(err, git.ErrFileNotFound) {
h.write404(w, err)
return
}
h.write500(w, err)
return
}
if raw {
w.Header().Set("Content-Type", fc.Mime)
w.WriteHeader(http.StatusOK)
w.Write(fc.Content)
return
}
p := RepoFile{
Ref: ref,
Path: treePath,
IsImage: fc.IsImage(),
IsBinary: fc.IsBinary,
Mime: fc.Mime,
Size: fc.Size,
}
p.Desc, err = repo.Description()
if err != nil {
h.write500(w, err)
return
}
if !fc.IsImage() && !fc.IsBinary {
contentStr := fc.String()
lc, err := countLines(strings.NewReader(contentStr))
if err != nil {
slog.Error("failed to count line numbers", "err", err)
}
lines := make([]int, lc)
for i := range lines {
lines[i] = i + 1
}
p.Content = contentStr
p.LineCount = lines
}
h.templ(w, "repo_file", h.pageData(repo, p))
}
type RepoLog struct {
Desc string
Commits []*git.Commit
Ref string
NextAfter string
}
func (h *handlers) logHandler(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
ref := h.parseRef(r.PathValue("ref"))
after := r.URL.Query().Get("after")
repo, err := h.openPublicRepo(name, ref)
if err != nil {
h.write404(w, err)
return
}
desc, err := repo.Description()
if err != nil {
h.write500(w, err)
return
}
commits, err := repo.Commits(after)
if err != nil {
h.write500(w, err)
return
}
// if we got full page of commits, we probably have more.
// NOTE: this has edge case, when last page has git.CommitsPage, "load more would be shown"
nextAfter := ""
if len(commits) == git.CommitsPage && len(commits) > 0 {
nextAfter = commits[len(commits)-1].HashShort
}
h.templ(w, "repo_log", h.pageData(repo, RepoLog{
Desc: desc,
Ref: ref,
Commits: commits,
NextAfter: nextAfter,
}))
}
type RepoCommit struct {
Diff *git.NiceDiff
Ref string
Desc string
}
func (h *handlers) commitHandler(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
ref := h.parseRef(r.PathValue("ref"))
repo, err := h.openPublicRepo(name, ref)
if err != nil {
h.write404(w, err)
return
}
diff, err := h.getDiff(repo, ref)
if err != nil {
h.write500(w, err)
return
}
desc, err := repo.Description()
if err != nil {
h.write500(w, err)
return
}
h.templ(w, "repo_commit", h.pageData(repo, RepoCommit{
Desc: desc,
Ref: ref,
Diff: diff,
}))
}
type RepoRefs struct {
Desc string
Ref string
Branches []*git.Branch
Tags []*git.TagReference
}
func (h *handlers) refsHandler(w http.ResponseWriter, r *http.Request) {
repo, err := h.openPublicRepo(r.PathValue("name"), "")
if err != nil {
h.write404(w, err)
return
}
desc, err := repo.Description()
if err != nil {
h.write500(w, err)
return
}
master, err := repo.FindMasterBranch(h.c.Repo.Masters)
if err != nil {
h.write500(w, err)
return
}
branches, err := repo.Branches()
if err != nil {
h.write500(w, err)
return
}
// repo should have at least one branch, tags are *optional*
tags, _ := repo.Tags()
h.templ(w, "repo_refs", h.pageData(repo, RepoRefs{
Desc: desc,
Ref: master,
Tags: tags,
Branches: branches,
}))
}
func countLines(r io.Reader) (int, error) {
buf := make([]byte, 32*1024)
bufLen := 0
count := 0
nl := []byte{'\n'}
for {
c, err := r.Read(buf)
if c > 0 {
bufLen += c
}
count += bytes.Count(buf[:c], nl)
switch {
case err == io.EOF:
// handle last line not having a newline at the end
if bufLen >= 1 && buf[(bufLen-1)%(32*1024)] != '\n' {
count++
}
return count, nil
case err != nil:
return 0, err
}
}
}
type repoList struct {
Name string
Desc string
LastCommit time.Time
}
func (h *handlers) listPublicRepos() ([]repoList, error) {
if v, found := h.repoListCache.Get("repo_list"); found {
return v, nil
}
dirs, err := os.ReadDir(h.c.Repo.Dir)
if err != nil {
return nil, err
}
var repos []repoList
var errs []error
for _, dir := range dirs {
if !dir.IsDir() {
continue
}
name := dir.Name()
repo, err := h.openPublicRepo(name, "")
if err != nil {
// if it's not git repo, just ignore it
continue
}
desc, err := repo.Description()
if err != nil {
errs = append(errs, err)
continue
}
lastCommit, err := repo.LastCommit()
if err != nil {
errs = append(errs, err)
continue
}
repos = append(repos, repoList{
Name: repo.Name(),
Desc: desc,
LastCommit: lastCommit.Committed,
})
}
sort.Slice(repos, func(i, j int) bool {
return repos[j].LastCommit.Before(repos[i].LastCommit)
})
h.repoListCache.Set("repo_list", repos)
return repos, errors.Join(errs...)
}
func (h handlers) getDiff(r *git.Repo, ref string) (*git.NiceDiff, error) {
cacheKey := fmt.Sprintf("%s:%s", r.Name(), ref)
if v, found := h.diffCache.Get(cacheKey); found {
return v, nil
}
diff, err := r.Diff()
if err != nil {
return nil, err
}
h.diffCache.Set(cacheKey, diff)
return diff, nil
}
func (h *handlers) renderReadme(r *git.Repo, ref, treePath string) (template.HTML, error) {
name := r.Name()
cacheKey := fmt.Sprintf("%s:%s:%s", name, ref, treePath)
if v, found := h.readmeCache.Get(cacheKey); found {
return v, nil
}
var readmeContents template.HTML
for _, readme := range h.c.Repo.Readmes {
fullPath := filepath.Join(treePath, readme)
fc, ferr := r.FileContent(fullPath)
if ferr != nil {
continue
}
if fc.IsBinary {
continue
}
ext := filepath.Ext(readme)
content := fc.String()
if len(content) > 0 {
switch ext {
case ".md", ".markdown", ".mkd":
readme, err := markdown.Render(name, ref, fullPath, content)
if err != nil {
return "", err
}
return template.HTML(readme), nil
default:
readmeContents = template.HTML(fmt.Sprintf(`<pre>%s</pre>`, content))
}
break
}
}
h.readmeCache.Set(cacheKey, readmeContents)
return readmeContents, nil
}
func (h handlers) pageData(repo *git.Repo, p any) PageData[any] {
var name string
var gomod, empty bool
if repo != nil {
gomod = repo.IsGoMod()
empty = repo.IsEmpty()
name = repo.Name()
}
return PageData[any]{
P: p,
RepoName: name,
Meta: Meta{
Title: h.c.Meta.Title,
Description: h.c.Meta.Description,
Host: h.c.Meta.Host,
GoMod: gomod,
SSHEnabled: h.c.SSH.Enable,
IsEmpty: empty,
},
}
}
|