routes/util.go (view raw)
1package routes
2
3import (
4 "io/fs"
5 "log"
6 "net/http"
7 "os"
8 "path/filepath"
9 "strings"
10
11 "git.icyphox.sh/legit/git"
12)
13
14func isGoModule(gr *git.GitRepo) bool {
15 _, err := gr.FileContent("go.mod")
16 return err == nil
17}
18
19func getDisplayName(name string) string {
20 return strings.TrimSuffix(name, ".git")
21}
22
23func getDescription(path string) (desc string) {
24 db, err := os.ReadFile(filepath.Join(path, "description"))
25 if err == nil {
26 desc = string(db)
27 } else {
28 desc = ""
29 }
30 return
31}
32
33func (d *deps) isIgnored(name string) bool {
34 for _, i := range d.c.Repo.Ignore {
35 if name == i {
36 return true
37 }
38 }
39
40 return false
41}
42
43type repoInfo struct {
44 Git *git.GitRepo
45 Path string
46 Category string
47}
48
49func (d *deps) getAllRepos() ([]repoInfo, error) {
50 repos := []repoInfo{}
51 max := strings.Count(d.c.Repo.ScanPath, string(os.PathSeparator)) + 2
52
53 err := filepath.WalkDir(d.c.Repo.ScanPath, func(path string, de fs.DirEntry, err error) error {
54 if err != nil {
55 return err
56 }
57
58 if de.IsDir() {
59 // Check if we've exceeded our recursion depth
60 if strings.Count(path, string(os.PathSeparator)) > max {
61 return fs.SkipDir
62 }
63
64 if d.isIgnored(path) {
65 return fs.SkipDir
66 }
67
68 // A bare repo should always have at least a HEAD file, if it
69 // doesn't we can continue recursing
70 if _, err := os.Lstat(filepath.Join(path, "HEAD")); err == nil {
71 repo, err := git.Open(path, "")
72 if err != nil {
73 log.Println(err)
74 } else {
75 relpath, _ := filepath.Rel(d.c.Repo.ScanPath, path)
76 repos = append(repos, repoInfo{
77 Git: repo,
78 Path: relpath,
79 Category: d.category(path),
80 })
81 // Since we found a Git repo, we don't want to recurse
82 // further
83 return fs.SkipDir
84 }
85 }
86 }
87 return nil
88 })
89
90 return repos, err
91}
92
93func (d *deps) category(path string) string {
94 return strings.TrimPrefix(filepath.Dir(strings.TrimPrefix(path, d.c.Repo.ScanPath)), string(os.PathSeparator))
95}
96
97func setContentDisposition(w http.ResponseWriter, name string) {
98 h := "inline; filename=\"" + name + "\""
99 w.Header().Add("Content-Disposition", h)
100}
101
102func setGZipMIME(w http.ResponseWriter) {
103 setMIME(w, "application/gzip")
104}
105
106func setMIME(w http.ResponseWriter, mime string) {
107 w.Header().Add("Content-Type", mime)
108}