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
|
// Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package db
import (
"context"
"fmt"
"strings"
"time"
api "github.com/gogs/go-gogs-client"
"github.com/pkg/errors"
"gorm.io/gorm"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/repoutil"
)
// ReposStore is the persistent interface for repositories.
type ReposStore interface {
// Create creates a new repository record in the database. It returns
// ErrNameNotAllowed when the repository name is not allowed, or
// ErrRepoAlreadyExist when a repository with same name already exists for the
// owner.
Create(ctx context.Context, ownerID int64, opts CreateRepoOptions) (*Repository, error)
// GetByCollaboratorID returns a list of repositories that the given
// collaborator has access to. Results are limited to the given limit and sorted
// by the given order (e.g. "updated_unix DESC"). Repositories that are owned
// directly by the given collaborator are not included.
GetByCollaboratorID(ctx context.Context, collaboratorID int64, limit int, orderBy string) ([]*Repository, error)
// GetByCollaboratorIDWithAccessMode returns a list of repositories and
// corresponding access mode that the given collaborator has access to.
// Repositories that are owned directly by the given collaborator are not
// included.
GetByCollaboratorIDWithAccessMode(ctx context.Context, collaboratorID int64) (map[*Repository]AccessMode, error)
// GetByID returns the repository with given ID. It returns ErrRepoNotExist when
// not found.
GetByID(ctx context.Context, id int64) (*Repository, error)
// GetByName returns the repository with given owner and name. It returns
// ErrRepoNotExist when not found.
GetByName(ctx context.Context, ownerID int64, name string) (*Repository, error)
// Star marks the user to star the repository.
Star(ctx context.Context, userID, repoID int64) error
// Touch updates the updated time to the current time and removes the bare state
// of the given repository.
Touch(ctx context.Context, id int64) error
// ListWatches returns all watches of the given repository.
ListWatches(ctx context.Context, repoID int64) ([]*Watch, error)
// Watch marks the user to watch the repository.
Watch(ctx context.Context, userID, repoID int64) error
// HasForkedBy returns true if the given repository has forked by the given user.
HasForkedBy(ctx context.Context, repoID, userID int64) bool
}
var Repos ReposStore
// BeforeCreate implements the GORM create hook.
func (r *Repository) BeforeCreate(tx *gorm.DB) error {
if r.CreatedUnix == 0 {
r.CreatedUnix = tx.NowFunc().Unix()
}
return nil
}
// BeforeUpdate implements the GORM update hook.
func (r *Repository) BeforeUpdate(tx *gorm.DB) error {
r.UpdatedUnix = tx.NowFunc().Unix()
return nil
}
// AfterFind implements the GORM query hook.
func (r *Repository) AfterFind(_ *gorm.DB) error {
r.Created = time.Unix(r.CreatedUnix, 0).Local()
r.Updated = time.Unix(r.UpdatedUnix, 0).Local()
return nil
}
type RepositoryAPIFormatOptions struct {
Permission *api.Permission
Parent *api.Repository
}
// APIFormat returns the API format of a repository.
func (r *Repository) APIFormat(owner *User, opts ...RepositoryAPIFormatOptions) *api.Repository {
var opt RepositoryAPIFormatOptions
if len(opts) > 0 {
opt = opts[0]
}
cloneLink := repoutil.NewCloneLink(owner.Name, r.Name, false)
return &api.Repository{
ID: r.ID,
Owner: owner.APIFormat(),
Name: r.Name,
FullName: owner.Name + "/" + r.Name,
Description: r.Description,
Private: r.IsPrivate,
Fork: r.IsFork,
Parent: opt.Parent,
Empty: r.IsBare,
Mirror: r.IsMirror,
Size: r.Size,
HTMLURL: repoutil.HTMLURL(owner.Name, r.Name),
SSHURL: cloneLink.SSH,
CloneURL: cloneLink.HTTPS,
Website: r.Website,
Stars: r.NumStars,
Forks: r.NumForks,
Watchers: r.NumWatches,
OpenIssues: r.NumOpenIssues,
DefaultBranch: r.DefaultBranch,
Created: r.Created,
Updated: r.Updated,
Permissions: opt.Permission,
}
}
var _ ReposStore = (*repos)(nil)
type repos struct {
*gorm.DB
}
// NewReposStore returns a persistent interface for repositories with given
// database connection.
func NewReposStore(db *gorm.DB) ReposStore {
return &repos{DB: db}
}
type ErrRepoAlreadyExist struct {
args errutil.Args
}
func IsErrRepoAlreadyExist(err error) bool {
_, ok := err.(ErrRepoAlreadyExist)
return ok
}
func (err ErrRepoAlreadyExist) Error() string {
return fmt.Sprintf("repository already exists: %v", err.args)
}
type CreateRepoOptions struct {
Name string
Description string
DefaultBranch string
Private bool
Mirror bool
EnableWiki bool
EnableIssues bool
EnablePulls bool
Fork bool
ForkID int64
}
func (db *repos) Create(ctx context.Context, ownerID int64, opts CreateRepoOptions) (*Repository, error) {
err := isRepoNameAllowed(opts.Name)
if err != nil {
return nil, err
}
_, err = db.GetByName(ctx, ownerID, opts.Name)
if err == nil {
return nil, ErrRepoAlreadyExist{
args: errutil.Args{
"ownerID": ownerID,
"name": opts.Name,
},
}
} else if !IsErrRepoNotExist(err) {
return nil, err
}
repo := &Repository{
OwnerID: ownerID,
LowerName: strings.ToLower(opts.Name),
Name: opts.Name,
Description: opts.Description,
DefaultBranch: opts.DefaultBranch,
IsPrivate: opts.Private,
IsMirror: opts.Mirror,
EnableWiki: opts.EnableWiki,
EnableIssues: opts.EnableIssues,
EnablePulls: opts.EnablePulls,
IsFork: opts.Fork,
ForkID: opts.ForkID,
}
return repo, db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
err = tx.Create(repo).Error
if err != nil {
return errors.Wrap(err, "create")
}
err = NewReposStore(tx).Watch(ctx, ownerID, repo.ID)
if err != nil {
return errors.Wrap(err, "watch")
}
return nil
})
}
func (db *repos) GetByCollaboratorID(ctx context.Context, collaboratorID int64, limit int, orderBy string) ([]*Repository, error) {
/*
Equivalent SQL for PostgreSQL:
SELECT * FROM repository
JOIN access ON access.repo_id = repository.id AND access.user_id = @collaboratorID
WHERE access.mode >= @accessModeRead
ORDER BY @orderBy
LIMIT @limit
*/
var repos []*Repository
return repos, db.WithContext(ctx).
Joins("JOIN access ON access.repo_id = repository.id AND access.user_id = ?", collaboratorID).
Where("access.mode >= ?", AccessModeRead).
Order(orderBy).
Limit(limit).
Find(&repos).
Error
}
func (db *repos) GetByCollaboratorIDWithAccessMode(ctx context.Context, collaboratorID int64) (map[*Repository]AccessMode, error) {
/*
Equivalent SQL for PostgreSQL:
SELECT
repository.*,
access.mode
FROM repository
JOIN access ON access.repo_id = repository.id AND access.user_id = @collaboratorID
WHERE access.mode >= @accessModeRead
*/
var reposWithAccessMode []*struct {
*Repository
Mode AccessMode
}
err := db.WithContext(ctx).
Select("repository.*", "access.mode").
Table("repository").
Joins("JOIN access ON access.repo_id = repository.id AND access.user_id = ?", collaboratorID).
Where("access.mode >= ?", AccessModeRead).
Find(&reposWithAccessMode).
Error
if err != nil {
return nil, err
}
repos := make(map[*Repository]AccessMode, len(reposWithAccessMode))
for _, repoWithAccessMode := range reposWithAccessMode {
repos[repoWithAccessMode.Repository] = repoWithAccessMode.Mode
}
return repos, nil
}
var _ errutil.NotFound = (*ErrRepoNotExist)(nil)
type ErrRepoNotExist struct {
args errutil.Args
}
func IsErrRepoNotExist(err error) bool {
_, ok := err.(ErrRepoNotExist)
return ok
}
func (err ErrRepoNotExist) Error() string {
return fmt.Sprintf("repository does not exist: %v", err.args)
}
func (ErrRepoNotExist) NotFound() bool {
return true
}
func (db *repos) GetByID(ctx context.Context, id int64) (*Repository, error) {
repo := new(Repository)
err := db.WithContext(ctx).Where("id = ?", id).First(repo).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, ErrRepoNotExist{errutil.Args{"repoID": id}}
}
return nil, err
}
return repo, nil
}
func (db *repos) GetByName(ctx context.Context, ownerID int64, name string) (*Repository, error) {
repo := new(Repository)
err := db.WithContext(ctx).
Where("owner_id = ? AND lower_name = ?", ownerID, strings.ToLower(name)).
First(repo).
Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, ErrRepoNotExist{
args: errutil.Args{
"ownerID": ownerID,
"name": name,
},
}
}
return nil, err
}
return repo, nil
}
func (db *repos) recountStars(tx *gorm.DB, userID, repoID int64) error {
/*
Equivalent SQL for PostgreSQL:
UPDATE repository
SET num_stars = (
SELECT COUNT(*) FROM star WHERE repo_id = @repoID
)
WHERE id = @repoID
*/
err := tx.Model(&Repository{}).
Where("id = ?", repoID).
Update(
"num_stars",
tx.Model(&Star{}).Select("COUNT(*)").Where("repo_id = ?", repoID),
).
Error
if err != nil {
return errors.Wrap(err, `update "repository.num_stars"`)
}
/*
Equivalent SQL for PostgreSQL:
UPDATE "user"
SET num_stars = (
SELECT COUNT(*) FROM star WHERE uid = @userID
)
WHERE id = @userID
*/
err = tx.Model(&User{}).
Where("id = ?", userID).
Update(
"num_stars",
tx.Model(&Star{}).Select("COUNT(*)").Where("uid = ?", userID),
).
Error
if err != nil {
return errors.Wrap(err, `update "user.num_stars"`)
}
return nil
}
func (db *repos) Star(ctx context.Context, userID, repoID int64) error {
return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
s := &Star{
UserID: userID,
RepoID: repoID,
}
result := tx.FirstOrCreate(s, s)
if result.Error != nil {
return errors.Wrap(result.Error, "upsert")
} else if result.RowsAffected <= 0 {
return nil // Relation already exists
}
return db.recountStars(tx, userID, repoID)
})
}
func (db *repos) Touch(ctx context.Context, id int64) error {
return db.WithContext(ctx).
Model(new(Repository)).
Where("id = ?", id).
Updates(map[string]any{
"is_bare": false,
"updated_unix": db.NowFunc().Unix(),
}).
Error
}
func (db *repos) ListWatches(ctx context.Context, repoID int64) ([]*Watch, error) {
var watches []*Watch
return watches, db.WithContext(ctx).Where("repo_id = ?", repoID).Find(&watches).Error
}
func (db *repos) recountWatches(tx *gorm.DB, repoID int64) error {
/*
Equivalent SQL for PostgreSQL:
UPDATE repository
SET num_watches = (
SELECT COUNT(*) FROM watch WHERE repo_id = @repoID
)
WHERE id = @repoID
*/
return tx.Model(&Repository{}).
Where("id = ?", repoID).
Update(
"num_watches",
tx.Model(&Watch{}).Select("COUNT(*)").Where("repo_id = ?", repoID),
).
Error
}
func (db *repos) Watch(ctx context.Context, userID, repoID int64) error {
return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
w := &Watch{
UserID: userID,
RepoID: repoID,
}
result := tx.FirstOrCreate(w, w)
if result.Error != nil {
return errors.Wrap(result.Error, "upsert")
} else if result.RowsAffected <= 0 {
return nil // Relation already exists
}
return db.recountWatches(tx, repoID)
})
}
func (db *repos) HasForkedBy(ctx context.Context, repoID, userID int64) bool {
var count int64
db.WithContext(ctx).Model(new(Repository)).Where("owner_id = ? AND fork_id = ?", userID, repoID).Count(&count)
return count > 0
}
|