This repository has been archived by the owner on Sep 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
repositories.go
306 lines (249 loc) · 6.85 KB
/
repositories.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
package core
import (
"bytes"
"github.com/codemicro/abigit/abigit/config"
"github.com/codemicro/abigit/abigit/util"
"github.com/codemicro/htmlRenderer"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/gofiber/fiber/v2"
"github.com/gosimple/slug"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"io"
"os"
"os/exec"
"path/filepath"
)
type RepoOnDisk struct {
Slug string
Description string
Path string
}
func (r *RepoOnDisk) Size() (int64, error) {
size, err := util.DirSize(r.Path)
if err != nil {
return 0, errors.WithStack(err)
}
return size, nil
}
// ListRepositories returns the list of repositories in a given directory.
//
// It assumes that any directory is a repository.
func ListRepositories() ([]*RepoOnDisk, error) {
dirEntries, err := os.ReadDir(config.Git.RepositoriesPath)
if err != nil {
return nil, errors.WithStack(err)
}
var o []*RepoOnDisk
for _, entry := range dirEntries {
if !entry.IsDir() {
continue
}
o = append(o, &RepoOnDisk{
Slug: entry.Name(),
Description: "Lorem ipsum dolor sit amet.",
Path: filepath.Join(config.Git.RepositoriesPath, entry.Name()),
})
}
return o, nil
}
func doesRepositoryExist(slug string) (bool, error) {
dirEntries, err := os.ReadDir(config.Git.RepositoriesPath)
if err != nil {
return false, errors.WithStack(err)
}
for _, entry := range dirEntries {
if entry.Name() == slug {
return true, nil
}
}
return false, nil
}
func GetRepository(slug string) (*RepoOnDisk, error) {
if found, err := doesRepositoryExist(slug); err != nil {
return nil, errors.WithStack(err)
} else if !found {
return nil, util.NewRichErrorFromFiberError(fiber.ErrNotFound, nil)
}
fp := filepath.Join(config.Git.RepositoriesPath, slug)
// TODO: populate with meaningful information
return &RepoOnDisk{
Slug: slug,
Description: "Lorem ipsum dolor sit amet.",
Path: fp,
}, nil
}
func ValidateRepositoryName(repoNameSlug string) error {
if repoNameSlug == "" {
return util.NewRichError(fiber.StatusBadRequest, "Repository name cannot be empty", nil)
} else if len(repoNameSlug) >= 128 {
return util.NewRichError(fiber.StatusBadRequest, "Repository name too long (max: 128 chars)", nil)
}
repoExists, err := doesRepositoryExist(repoNameSlug)
if err != nil {
return errors.WithStack(err)
}
if repoExists {
return util.NewRichError(fiber.StatusBadRequest, "Name already in use", nil)
}
return nil
}
const postUpdateHookContents = `#!/bin/sh
exec git update-server-info
`
func CreateRepository(name string) (*RepoOnDisk, error) {
rod := &RepoOnDisk{
Slug: slug.Make(name),
}
if err := ValidateRepositoryName(rod.Slug); err != nil {
return nil, err
}
rod.Path = filepath.Join(config.Git.RepositoriesPath, rod.Slug)
_, err := git.PlainInit(rod.Path, true)
if err != nil {
return nil, errors.WithStack(err)
}
// Create `post-update` hook
if err := os.MkdirAll(filepath.Join(rod.Path, "hooks"), 0755); err != nil {
return nil, errors.WithStack(err)
}
if err := os.WriteFile(
filepath.Join(rod.Path, "hooks", "post-update"),
[]byte(postUpdateHookContents),
0770,
); err != nil {
return nil, errors.WithStack(err)
}
// We need to execute it so it can be cloned
cmd := exec.Command(filepath.Join("hooks", "post-update"))
cmd.Dir = rod.Path
if err := cmd.Run(); err != nil {
return nil, errors.WithStack(err)
}
return rod, nil
}
func AutoselectDefaultBranch(repo *git.Repository) error {
// Get HEAD to first branch
bi, err := repo.Branches()
if err != nil {
return errors.WithStack(err)
}
branch, err := bi.Next()
if err != nil {
return errors.Wrap(err, "no branches")
}
log.Debug().Msgf("autoselecting new default branch as %s", branch.Name())
return errors.WithStack(
repo.Storer.SetReference(plumbing.NewSymbolicReference("HEAD", branch.Name())),
)
}
func GetHEAD(repo *git.Repository) (*plumbing.Reference, error) {
ref, err := repo.Reference("HEAD", true)
if err != nil {
if errors.Is(err, plumbing.ErrReferenceNotFound) {
goto attemptHeadSwitch
}
return nil, errors.WithStack(err)
}
return ref, nil
attemptHeadSwitch:
{
if err := AutoselectDefaultBranch(repo); err != nil {
return nil, errors.Wrap(err, "could not autoselect new default branch")
}
ref, err = repo.Reference("HEAD", true)
if err != nil {
return nil, errors.WithStack(err)
}
return ref, nil
}
}
func GetDefaultBranch(repo *git.Repository) (plumbing.ReferenceName, error) {
ref, err := repo.Reference("HEAD", false)
if err != nil {
return "", errors.WithStack(err)
}
return ref.Target(), nil
}
func SetDefaultBranch(repo *git.Repository, ref plumbing.ReferenceName) error {
return errors.WithStack(
repo.Storer.SetReference(plumbing.NewSymbolicReference("HEAD", ref)),
)
}
func IsRepositoryEmpty(repo *git.Repository) (bool, error) {
branches, err := repo.Branches()
if err != nil {
return false, errors.WithStack(err)
}
_, err = branches.Next()
if err == nil {
return false, nil
}
if err.Error() == "EOF" {
return true, nil
}
return false, err
}
var ErrNoReadme = errors.New("no README.md file found")
// GetReadmeContent returns the raw Markdown of a README.md file
func GetReadmeContent(repo *git.Repository) ([]byte, error) {
if isEmpty, err := IsRepositoryEmpty(repo); err != nil {
return nil, errors.WithStack(err)
} else if isEmpty {
return nil, ErrNoReadme
}
headref, err := GetHEAD(repo)
if err != nil {
return nil, errors.Wrap(err, "cannot get HEAD")
}
commit, err := repo.CommitObject(headref.Hash())
if err != nil {
return nil, errors.Wrap(err, "cannot get HEAD commit")
}
tree, err := commit.Tree()
if err != nil {
return nil, errors.Wrap(err, "cannot get HEAD commit tree")
}
fi, err := tree.File("README.md")
if err != nil {
if errors.Is(err, object.ErrFileNotFound) {
fi, err = tree.File("readme.md")
if err != nil {
if errors.Is(err, object.ErrFileNotFound) {
return nil, ErrNoReadme
}
}
goto ok
}
return nil, errors.Wrap(err, "could not read file")
}
ok:
if fi.Type() != plumbing.BlobObject {
// make sure it's file and not another tree or something stupid like that
return nil, ErrNoReadme
}
reader, err := fi.Blob.Reader()
if err != nil {
return nil, errors.Wrap(err, "could not obtain reader for readme file")
}
defer reader.Close()
content, err := io.ReadAll(reader)
if err != nil {
return nil, errors.Wrap(err, "could not read readme file content")
}
return content, nil
}
func GetRenderedReadmeContent(repo *git.Repository) (string, error) {
readmeContent, err := GetReadmeContent(repo)
if err != nil {
return "", err
}
buf := new(bytes.Buffer)
markdownProcessor := htmlRenderer.NewProcessor(htmlRenderer.WithHeaderLinks())
if err := markdownProcessor.Convert(readmeContent, buf); err != nil {
return "", errors.WithStack(err)
}
return buf.String(), nil
}