-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgitcode.go
329 lines (284 loc) · 7.11 KB
/
gitcode.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
package main
import (
"embed"
"flag"
"fmt"
"html/template"
"io"
"log"
"mime"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"github.com/gin-gonic/gin"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/object"
yaml "gopkg.in/yaml.v2"
)
type GitcodeConfig struct {
Ignore []string
}
func loadConfig(conf string) (config *GitcodeConfig) {
data, err := os.ReadFile(conf)
if err != nil {
log.Fatal(err)
}
config = &GitcodeConfig{}
err = yaml.Unmarshal(data, config)
if err != nil {
log.Fatal(err)
}
return
}
type Org struct {
Name string
Repos []Repo
}
type Repo struct {
Name string
}
type Entry struct {
Name, Path string
IsDir bool
}
func (entry *Entry) IsParent() bool {
return entry.IsDir && entry.Name == ".."
}
type Dir struct {
Entries []Entry
}
type File struct {
Size int64
RawPath string
Lang string
}
type BreadcrumbItem struct {
Name, Path string
Last bool
}
//go:embed templates/*
var tmplFS embed.FS
func newTemplate() (tmpl *template.Template) {
tmpl = template.Must(template.New("").ParseFS(tmplFS, "templates/*.htm"))
return
}
func homeHandler() func(*gin.Context) {
return func(c *gin.Context) {
entries, err := os.ReadDir(reposDir)
if err != nil {
log.Fatal(err)
}
var orgs []Org
Loop:
for _, v := range entries {
hidden := strings.HasPrefix(v.Name(), ".")
// ignore entries that are hidden or aren't directories.
if hidden || !v.IsDir() {
continue
}
// ignore entries that are ignored
for _, ignore := range config.Ignore {
if v.Name() == ignore {
continue Loop
}
}
subEntries, err := os.ReadDir(filepath.Join(reposDir, v.Name()))
if err != nil {
log.Fatal(err)
}
var repos []Repo
for _, vsub := range subEntries {
if vsub.IsDir() && strings.HasSuffix(vsub.Name(), ".git") {
repos = append(repos, Repo{Name: strings.TrimSuffix(vsub.Name(), ".git")})
}
}
orgs = append(orgs, Org{Name: v.Name(), Repos: repos})
}
c.HTML(http.StatusOK, "index.htm", gin.H{
"Orgs": orgs,
})
}
}
func parseParams(path string) (orgName, repoName, branchName string, Breadcrumb []string) {
tmp := strings.Split(path, "/")
orgName = tmp[1]
repoName = tmp[2]
branchName = tmp[4]
Breadcrumb = tmp[5:]
return
}
func getRepoTree(orgName, repoName, branchName string) *object.Tree {
repo, err := git.PlainOpen(filepath.Join(reposDir, orgName, repoName+".git"))
if err != nil {
log.Fatal(err)
}
// todo
// get branch by `branchName`
head, err := repo.Head()
if err != nil {
log.Fatal(err)
}
commit, err := repo.CommitObject(head.Hash())
if err != nil {
log.Fatal(err)
}
tree, err := commit.Tree()
if err != nil {
log.Fatal(err)
}
return tree
}
func getEntryType(isFile bool) string {
if isFile {
return "blob"
} else {
return "tree"
}
}
func getTreeEntries(tree *object.Tree, orgName, repoName, branchName, entryPath string) ([]Entry, bool) {
var (
entries []Entry
loadReadme bool
)
pathFmt := "/" + filepath.Join(orgName, repoName, "%s", branchName, entryPath, "%s")
dstTree := tree
if len(entryPath) > 0 {
var err error
if dstTree, err = tree.Tree(entryPath); err != nil {
log.Fatal(err)
}
entries = append(entries, Entry{
Name: "..",
Path: fmt.Sprintf(pathFmt, getEntryType(false), ".."),
IsDir: true,
})
}
for _, entry := range dstTree.Entries {
entries = append(entries, Entry{
Name: entry.Name,
Path: fmt.Sprintf(pathFmt, getEntryType(entry.Mode.IsFile()), entry.Name),
IsDir: !entry.Mode.IsFile(),
})
if entry.Mode.IsFile() && entry.Name == "README.md" {
loadReadme = true
}
}
if len(entries) > 0 {
sort.Slice(entries, func(i, j int) bool {
if entries[i].IsDir == entries[j].IsDir {
return entries[i].Name <= entries[j].Name
}
return entries[i].IsDir
})
}
return entries, loadReadme
}
func getBreadcrumb(branchPath string, breadcrumb []string) []BreadcrumbItem {
tmp := make([]BreadcrumbItem, len(breadcrumb))
for i := range breadcrumb {
tmp[i].Name = breadcrumb[i]
tmp[i].Path = filepath.Join(branchPath, strings.Join(breadcrumb[:i+1], "/"))
tmp[i].Last = i == len(breadcrumb)-1
}
return tmp
}
func noRouteHandler() func(*gin.Context) {
return func(c *gin.Context) {
path := strings.TrimSuffix(c.Request.URL.Path, "/")
isTree := strings.Contains(path, "/tree/")
isBlob := strings.Contains(path, "/blob/")
// only handle tree or blob requests
if !(isTree || isBlob) {
c.AbortWithStatus(http.StatusNotFound)
return
}
orgName, repoName, branchName, breadcrumb := parseParams(path)
branchPath := fmt.Sprintf("/%s/%s/tree/%s", orgName, repoName, branchName)
entryPath := strings.Join(breadcrumb, "/")
tree := getRepoTree(orgName, repoName, branchName)
// /:orgName/:repoName/tree/:branchName/...
if isTree {
entries, loadReadme := getTreeEntries(tree, orgName, repoName, branchName, entryPath)
c.HTML(http.StatusOK, "repo.htm", gin.H{
"OrgName": orgName,
"RepoName": repoName,
"BranchName": branchName,
"BranchPath": branchPath,
"Tree": true,
"Root": len(breadcrumb) == 0,
"Breadcrumb": getBreadcrumb(branchPath, breadcrumb),
"Dir": Dir{entries},
"LoadReadme": loadReadme,
"ReadmePath": filepath.Join(fmt.Sprintf("/%s/%s/blob/%s", orgName, repoName, branchName), entryPath, "README.md"),
})
return
}
// /:orgName/:repoName/blob/:branchName/...[?raw=true]
if isBlob {
file, err := tree.File(entryPath)
if err != nil {
log.Fatal(err)
}
isBin, err := file.IsBinary()
if err != nil {
log.Fatal(err)
}
ext := filepath.Ext(path)
raw := c.Query("raw") == "true"
if raw || isBin {
reader, err := file.Reader()
if err != nil {
log.Fatal(err)
}
contentType := mime.TypeByExtension(ext)
if len(contentType) == 0 {
contentType = "text/plain; charset=utf-8"
}
c.Writer.Header().Set("Content-type", contentType)
c.Status(200)
io.Copy(c.Writer, reader)
} else {
lang := "none"
if len(ext) > 0 {
lang = ext[1:]
}
if lang == "md" {
c.HTML(http.StatusOK, "readme.htm", gin.H{
"BasePath": filepath.Dir(path),
"HomePage": filepath.Base(path) + "?raw=true",
})
} else {
c.HTML(http.StatusOK, "repo.htm", gin.H{
"OrgName": orgName,
"RepoName": repoName,
"BranchName": branchName,
"BranchPath": branchPath,
"Blob": true,
"Breadcrumb": getBreadcrumb(branchPath, breadcrumb),
"File": File{file.Size, path + "?raw=true", lang},
})
}
}
}
}
}
var (
port int
host, reposDir string
config *GitcodeConfig
)
func main() {
flag.IntVar(&port, "port", 8000, "the port that server listen on")
flag.StringVar(&host, "host", "127.0.0.1", "the host that server listen on")
flag.StringVar(&reposDir, "repos", "/srv", "the director where repos store")
flag.Parse()
config = loadConfig(filepath.Join(reposDir, "gitcode.yaml"))
router := gin.Default()
router.SetHTMLTemplate(newTemplate())
router.GET("/", homeHandler())
router.NoRoute(noRouteHandler())
router.SetTrustedProxies(nil)
router.Run(fmt.Sprintf("%s:%d", host, port))
}