forked from G-Node/gin-repo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
repo.go
449 lines (341 loc) · 8.9 KB
/
repo.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
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
package store
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"github.com/G-Node/gin-repo/git"
)
var idChecker *regexp.Regexp
func init() {
idChecker = regexp.MustCompile("^(?:/~/|/)?([[:alnum:]][0-9a-zA-Z._-]{2,})/([[:alnum:]][0-9a-zA-Z._@+-]*?)(?:.git)?(?:/)?$")
}
type RepoId struct {
Owner string
Name string
}
func (id RepoId) String() string {
return path.Join(id.Owner, id.Name)
}
func RepoIdParse(str string) (RepoId, error) {
res := idChecker.FindStringSubmatch(str)
if res == nil || len(res) != 3 {
return RepoId{}, fmt.Errorf("malformed repository id")
}
return RepoId{res[1], res[2]}, nil
}
func RepoIdFromPath(path string) (RepoId, error) {
if !strings.HasSuffix(path, ".git") {
return RepoId{}, fmt.Errorf("Not a valid git path: %q", path)
}
base := filepath.Base(path)
name := base[:len(base)-4]
dir := filepath.Dir(path)
if len(dir) == 1 && (dir[0] == '.' || dir[0] == filepath.Separator) {
return RepoId{}, fmt.Errorf("Malformed git path: %q", path)
}
uid := filepath.Base(dir)
return RepoId{uid, name}, nil
}
type AccessLevel int
const (
NoAccess = 0
PullAccess = 1
PushAccess = 2
AdminAccess = 3
OwnerAccess = 4
)
func (level AccessLevel) String() string {
switch level {
case PullAccess:
return "can-pull"
case PushAccess:
return "can-push"
case AdminAccess:
return "is-admin"
case OwnerAccess:
return "is-owner"
}
return "no-access"
}
func ParseAccessLevel(str string) (AccessLevel, error) {
clean := strings.Trim(str, " \n")
switch clean {
case "no-access":
return NoAccess, nil
case "can-pull":
return PullAccess, nil
case "can-push":
return PushAccess, nil
case "is-admin":
return AdminAccess, nil
case "is-owner":
return OwnerAccess, nil
}
return NoAccess, fmt.Errorf("unknown access level: %q", clean)
}
type RepoStore struct {
Path string
}
func (store *RepoStore) gitPath() string {
return filepath.Join(store.Path, "git")
}
// IdToPath returns the complete path to the root folder of
// the repository referenced by the RepoId. Method does not
// check whether the repository actually exists.
func (store *RepoStore) IdToPath(id RepoId) string {
return filepath.Join(store.gitPath(), id.Owner, id.Name+".git")
}
// RepoExists returns true if the path to a provided RepoId exists, false otherwise.
func (store *RepoStore) RepoExists(id RepoId) (bool, error) {
repoPath := store.IdToPath(id)
_, err := os.Stat(repoPath)
if err != nil && os.IsNotExist(err) {
return false, nil
} else if err != nil {
return false, err
}
return true, nil
}
func (store *RepoStore) CreateRepo(id RepoId) (*git.Repository, error) {
path := store.IdToPath(id)
_, err := os.Stat(path)
if err == nil {
return nil, os.ErrExist
} else if !os.IsNotExist(err) {
return nil, err
}
repo, err := git.InitBareRepository(path)
if err != nil {
return nil, err
}
gin := filepath.Join(path, "gin")
os.Mkdir(gin, 0775) //TODO: what to do about errors?
sharing := filepath.Join(gin, "sharing")
os.Mkdir(sharing, 0775)
return repo, nil
}
func (store *RepoStore) ListRepos() ([]RepoId, error) {
gitpath := store.gitPath()
rdir, err := os.Open(gitpath)
if err != nil {
return nil, err
}
defer rdir.Close()
entries, err := rdir.Readdir(-1)
if err != nil {
return nil, err
}
var repos []RepoId
for _, entry := range entries {
owner := entry.Name()
odir, err := os.Open(filepath.Join(gitpath, owner))
if err != nil {
fmt.Fprintf(os.Stderr, "[W] error opening %q\n", owner)
continue
}
repoInfos, err := store.ListReposForUser(owner)
if err != nil {
fmt.Fprintf(os.Stderr, "[W] %v", err)
} else {
repos = append(repos, repoInfos...)
}
odir.Close()
}
return repos, nil
}
func (store *RepoStore) ListReposForUser(uid string) ([]RepoId, error) {
userpath := filepath.Join(store.gitPath(), uid)
info, err := os.Stat(userpath)
if err != nil {
return nil, err
} else if !info.IsDir() {
return nil, fmt.Errorf("%q is not a directory as expected", userpath)
}
names, _ := filepath.Glob(filepath.Join(userpath, "*.git"))
var repos []RepoId
for _, path := range names {
if !strings.HasSuffix(path, ".git") {
continue
}
base := filepath.Base(path)
name := base[:len(base)-4]
repos = append(repos, RepoId{uid, name})
}
return repos, nil
}
func (store *RepoStore) ListSharedRepos(uid string) ([]RepoId, error) {
gitpath := store.gitPath()
suffix := filepath.Join("gin", "sharing", uid)
pattern := filepath.Join(gitpath, "*", "*.git", suffix)
names, err := filepath.Glob(pattern)
if err != nil {
panic("Bad glob pattern!")
}
repos := make([]RepoId, len(names))
for i, name := range names {
fmt.Fprintf(os.Stderr, "[D] shared: %q\n", name)
rid, err := RepoIdFromPath(name[:len(name)-(len(suffix)+1)])
if err != nil {
fmt.Fprintf(os.Stderr, "[W] could not parse repo id: %v", err)
continue
}
repos[i] = rid
}
return repos, nil
}
func (store *RepoStore) ListPublicRepos() ([]RepoId, error) {
gitpath := store.gitPath()
suffix := filepath.Join("gin", "public")
pattern := filepath.Join(gitpath, "*", "*.git", suffix)
names, err := filepath.Glob(pattern)
if err != nil {
panic("Bad glob pattern!")
}
repos := make([]RepoId, len(names))
for i, name := range names {
fmt.Fprintf(os.Stderr, "[D] public: %q\n", name)
rid, err := RepoIdFromPath(name[:len(name)-(len(suffix)+1)])
if err != nil {
fmt.Fprintf(os.Stderr, "[W] could not parse repo id: %v", err)
continue
}
repos[i] = rid
}
return repos, nil
}
func (store *RepoStore) OpenGitRepo(id RepoId) (*git.Repository, error) {
path := store.IdToPath(id)
return git.OpenRepository(path)
}
func (store *RepoStore) GetRepoVisibility(id RepoId) (bool, error) {
base := store.IdToPath(id)
path := filepath.Join(base, "gin", "public")
_, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
return true, nil
}
func (store *RepoStore) SetRepoVisibility(id RepoId, public bool) error {
cur, err := store.GetRepoVisibility(id)
if err != nil {
return err
}
if cur == public {
return nil
}
path := filepath.Join(store.IdToPath(id), "gin", "public")
if public {
_, err := os.Create(path)
if err != nil {
return err
}
return nil
}
return os.Remove(path)
}
func (store *RepoStore) SetAccessLevel(id RepoId, user string, level AccessLevel) error {
if id.Owner == user {
return fmt.Errorf("cannot set access level for owner")
}
//TODO: check user name
path := filepath.Join(store.IdToPath(id), "gin", "sharing", user)
if level == NoAccess {
err := os.Remove(path)
if os.IsNotExist(err) {
return nil
}
return err
}
err := ioutil.WriteFile(path, []byte(level.String()), 0664)
return err
}
func (store *RepoStore) readAccessLevel(id RepoId, user string) (AccessLevel, error) {
if user == "" {
return NoAccess, nil
}
path := filepath.Join(store.IdToPath(id), "gin", "sharing", user)
data, err := ioutil.ReadFile(path)
if os.IsNotExist(err) {
return NoAccess, nil
} else if err != nil {
return NoAccess, err
}
level, err := ParseAccessLevel(string(data))
if err != nil {
return NoAccess, err
}
return level, nil
}
func (store *RepoStore) GetAccessLevel(id RepoId, user string) (AccessLevel, error) {
if id.Owner == user {
return OwnerAccess, nil
}
level, err := store.readAccessLevel(id, user)
if err != nil {
//what now? besides logging it?
fmt.Fprintf(os.Stderr, "error reading access level: %v", err)
}
// if we got any level other then NoAccess, which is the lowest,
// then we are done. Otherwise, if the repo is public we could
// still get PullAccess, the next higher one, so check for that.
if level != NoAccess {
return level, nil
}
public, err := store.GetRepoVisibility(id)
if err != nil {
return NoAccess, err
} else if public {
return PullAccess, nil
}
return NoAccess, nil
}
func (store *RepoStore) ListSharedAccess(id RepoId) (map[string]AccessLevel, error) {
path := filepath.Join(store.IdToPath(id), "gin", "sharing")
dir, err := os.Open(path)
if os.IsNotExist(err) {
return make(map[string]AccessLevel), nil
} else if err != nil {
return nil, err
}
names, err := dir.Readdirnames(-1)
if err != nil {
return nil, err
}
accessMap := make(map[string]AccessLevel)
for _, name := range names {
level, err := store.GetAccessLevel(id, name)
if err != nil {
fmt.Fprintf(os.Stderr, "[W] could not get level for %s\n", name)
continue
}
accessMap[name] = level
}
return accessMap, nil
}
func NewRepoStore(basePath string) (*RepoStore, error) {
store := RepoStore{Path: filepath.Join(basePath, "repos")}
gitpath := filepath.Join(store.Path, "git")
info, err := os.Stat(gitpath)
if err != nil {
if os.IsNotExist(err) {
err = os.MkdirAll(gitpath, 0777)
if err != nil {
return nil, err
}
} else {
return nil, err
}
}
if !info.IsDir() {
return nil, fmt.Errorf("%q is not a directory as expected", gitpath)
}
return &store, nil
}