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) isUnlisted(name string) bool {
34 for _, i := range d.c.Repo.Unlisted {
35 if name == i {
36 return true
37 }
38 }
39
40 return false
41}
42
43func (d *deps) isIgnored(name string) bool {
44 for _, i := range d.c.Repo.Ignore {
45 if name == i {
46 return true
47 }
48 }
49
50 return false
51}
52
53type repoInfo struct {
54 Git *git.GitRepo
55 Path string
56 Category string
57}
58
59func (d *deps) getAllRepos() ([]repoInfo, error) {
60 repos := []repoInfo{}
61 max := strings.Count(d.c.Repo.ScanPath, string(os.PathSeparator)) + 2
62
63 err := filepath.WalkDir(d.c.Repo.ScanPath, func(path string, de fs.DirEntry, err error) error {
64 if err != nil {
65 return err
66 }
67
68 if de.IsDir() {
69 // Check if we've exceeded our recursion depth
70 if strings.Count(path, string(os.PathSeparator)) > max {
71 return fs.SkipDir
72 }
73
74 if d.isIgnored(path) {
75 return fs.SkipDir
76 }
77
78 // A bare repo should always have at least a HEAD file, if it
79 // doesn't we can continue recursing
80 if _, err := os.Lstat(filepath.Join(path, "HEAD")); err == nil {
81 repo, err := git.Open(path, "")
82 if err != nil {
83 log.Println(err)
84 } else {
85 relpath, _ := filepath.Rel(d.c.Repo.ScanPath, path)
86 repos = append(repos, repoInfo{
87 Git: repo,
88 Path: relpath,
89 Category: d.category(path),
90 })
91 // Since we found a Git repo, we don't want to recurse
92 // further
93 return fs.SkipDir
94 }
95 }
96 }
97 return nil
98 })
99
100 return repos, err
101}
102
103func (d *deps) category(path string) string {
104 return strings.TrimPrefix(filepath.Dir(strings.TrimPrefix(path, d.c.Repo.ScanPath)), string(os.PathSeparator))
105}
106
107func setContentDisposition(w http.ResponseWriter, name string) {
108 h := "inline; filename=\"" + name + "\""
109 w.Header().Add("Content-Disposition", h)
110}
111
112func setGZipMIME(w http.ResponseWriter) {
113 setMIME(w, "application/gzip")
114}
115
116func setMIME(w http.ResponseWriter, mime string) {
117 w.Header().Add("Content-Type", mime)
118}