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 2021 The Gitea 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 models
import (
"context"
"fmt"
"os"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/organization"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
)
// RepoTransfer is used to manage repository transfers
type RepoTransfer struct {
ID int64 `xorm:"pk autoincr"`
DoerID int64
Doer *user_model.User `xorm:"-"`
RecipientID int64
Recipient *user_model.User `xorm:"-"`
RepoID int64
TeamIDs []int64
Teams []*organization.Team `xorm:"-"`
CreatedUnix timeutil.TimeStamp `xorm:"INDEX NOT NULL created"`
UpdatedUnix timeutil.TimeStamp `xorm:"INDEX NOT NULL updated"`
}
func init() {
db.RegisterModel(new(RepoTransfer))
}
// LoadAttributes fetches the transfer recipient from the database
func (r *RepoTransfer) LoadAttributes() error {
if r.Recipient == nil {
u, err := user_model.GetUserByID(r.RecipientID)
if err != nil {
return err
}
r.Recipient = u
}
if r.Recipient.IsOrganization() && len(r.TeamIDs) != len(r.Teams) {
for _, v := range r.TeamIDs {
team, err := organization.GetTeamByID(v)
if err != nil {
return err
}
if team.OrgID != r.Recipient.ID {
return fmt.Errorf("team %d belongs not to org %d", v, r.Recipient.ID)
}
r.Teams = append(r.Teams, team)
}
}
if r.Doer == nil {
u, err := user_model.GetUserByID(r.DoerID)
if err != nil {
return err
}
r.Doer = u
}
return nil
}
// CanUserAcceptTransfer checks if the user has the rights to accept/decline a repo transfer.
// For user, it checks if it's himself
// For organizations, it checks if the user is able to create repos
func (r *RepoTransfer) CanUserAcceptTransfer(u *user_model.User) bool {
if err := r.LoadAttributes(); err != nil {
log.Error("LoadAttributes: %v", err)
return false
}
if !r.Recipient.IsOrganization() {
return r.RecipientID == u.ID
}
allowed, err := organization.CanCreateOrgRepo(r.RecipientID, u.ID)
if err != nil {
log.Error("CanCreateOrgRepo: %v", err)
return false
}
return allowed
}
// GetPendingRepositoryTransfer fetches the most recent and ongoing transfer
// process for the repository
func GetPendingRepositoryTransfer(repo *repo_model.Repository) (*RepoTransfer, error) {
transfer := new(RepoTransfer)
has, err := db.GetEngine(db.DefaultContext).Where("repo_id = ? ", repo.ID).Get(transfer)
if err != nil {
return nil, err
}
if !has {
return nil, ErrNoPendingRepoTransfer{RepoID: repo.ID}
}
return transfer, nil
}
func deleteRepositoryTransfer(ctx context.Context, repoID int64) error {
_, err := db.GetEngine(ctx).Where("repo_id = ?", repoID).Delete(&RepoTransfer{})
return err
}
// CancelRepositoryTransfer marks the repository as ready and remove pending transfer entry,
// thus cancel the transfer process.
func CancelRepositoryTransfer(repo *repo_model.Repository) error {
ctx, committer, err := db.TxContext()
if err != nil {
return err
}
defer committer.Close()
repo.Status = repo_model.RepositoryReady
if err := repo_model.UpdateRepositoryColsCtx(ctx, repo, "status"); err != nil {
return err
}
if err := deleteRepositoryTransfer(ctx, repo.ID); err != nil {
return err
}
return committer.Commit()
}
// TestRepositoryReadyForTransfer make sure repo is ready to transfer
func TestRepositoryReadyForTransfer(status repo_model.RepositoryStatus) error {
switch status {
case repo_model.RepositoryBeingMigrated:
return fmt.Errorf("repo is not ready, currently migrating")
case repo_model.RepositoryPendingTransfer:
return ErrRepoTransferInProgress{}
}
return nil
}
// CreatePendingRepositoryTransfer transfer a repo from one owner to a new one.
// it marks the repository transfer as "pending"
func CreatePendingRepositoryTransfer(doer, newOwner *user_model.User, repoID int64, teams []*organization.Team) error {
ctx, committer, err := db.TxContext()
if err != nil {
return err
}
defer committer.Close()
repo, err := repo_model.GetRepositoryByIDCtx(ctx, repoID)
if err != nil {
return err
}
// Make sure repo is ready to transfer
if err := TestRepositoryReadyForTransfer(repo.Status); err != nil {
return err
}
repo.Status = repo_model.RepositoryPendingTransfer
if err := repo_model.UpdateRepositoryColsCtx(ctx, repo, "status"); err != nil {
return err
}
// Check if new owner has repository with same name.
if has, err := repo_model.IsRepositoryExistCtx(ctx, newOwner, repo.Name); err != nil {
return fmt.Errorf("IsRepositoryExist: %v", err)
} else if has {
return repo_model.ErrRepoAlreadyExist{
Uname: newOwner.LowerName,
Name: repo.Name,
}
}
transfer := &RepoTransfer{
RepoID: repo.ID,
RecipientID: newOwner.ID,
CreatedUnix: timeutil.TimeStampNow(),
UpdatedUnix: timeutil.TimeStampNow(),
DoerID: doer.ID,
TeamIDs: make([]int64, 0, len(teams)),
}
for k := range teams {
transfer.TeamIDs = append(transfer.TeamIDs, teams[k].ID)
}
if err := db.Insert(ctx, transfer); err != nil {
return err
}
return committer.Commit()
}
// TransferOwnership transfers all corresponding repository items from old user to new one.
func TransferOwnership(doer *user_model.User, newOwnerName string, repo *repo_model.Repository) (err error) {
repoRenamed := false
wikiRenamed := false
oldOwnerName := doer.Name
defer func() {
if !repoRenamed && !wikiRenamed {
return
}
recoverErr := recover()
if err == nil && recoverErr == nil {
return
}
if repoRenamed {
if err := util.Rename(repo_model.RepoPath(newOwnerName, repo.Name), repo_model.RepoPath(oldOwnerName, repo.Name)); err != nil {
log.Critical("Unable to move repository %s/%s directory from %s back to correct place %s: %v", oldOwnerName, repo.Name,
repo_model.RepoPath(newOwnerName, repo.Name), repo_model.RepoPath(oldOwnerName, repo.Name), err)
}
}
if wikiRenamed {
if err := util.Rename(repo_model.WikiPath(newOwnerName, repo.Name), repo_model.WikiPath(oldOwnerName, repo.Name)); err != nil {
log.Critical("Unable to move wiki for repository %s/%s directory from %s back to correct place %s: %v", oldOwnerName, repo.Name,
repo_model.WikiPath(newOwnerName, repo.Name), repo_model.WikiPath(oldOwnerName, repo.Name), err)
}
}
if recoverErr != nil {
log.Error("Panic within TransferOwnership: %v\n%s", recoverErr, log.Stack(2))
panic(recoverErr)
}
}()
ctx, committer, err := db.TxContext()
if err != nil {
return err
}
defer committer.Close()
sess := db.GetEngine(ctx)
newOwner, err := user_model.GetUserByNameCtx(ctx, newOwnerName)
if err != nil {
return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
}
newOwnerName = newOwner.Name // ensure capitalisation matches
// Check if new owner has repository with same name.
if has, err := repo_model.IsRepositoryExistCtx(ctx, newOwner, repo.Name); err != nil {
return fmt.Errorf("IsRepositoryExist: %v", err)
} else if has {
return repo_model.ErrRepoAlreadyExist{
Uname: newOwnerName,
Name: repo.Name,
}
}
oldOwner := repo.Owner
oldOwnerName = oldOwner.Name
// Note: we have to set value here to make sure recalculate accesses is based on
// new owner.
repo.OwnerID = newOwner.ID
repo.Owner = newOwner
repo.OwnerName = newOwner.Name
// Update repository.
if _, err := sess.ID(repo.ID).Update(repo); err != nil {
return fmt.Errorf("update owner: %v", err)
}
// Remove redundant collaborators.
collaborators, err := getCollaborators(sess, repo.ID, db.ListOptions{})
if err != nil {
return fmt.Errorf("getCollaborators: %v", err)
}
// Dummy object.
collaboration := &Collaboration{RepoID: repo.ID}
for _, c := range collaborators {
if c.IsGhost() {
collaboration.ID = c.Collaboration.ID
if _, err := sess.Delete(collaboration); err != nil {
return fmt.Errorf("remove collaborator '%d': %v", c.ID, err)
}
collaboration.ID = 0
}
if c.ID != newOwner.ID {
isMember, err := organization.IsOrganizationMember(ctx, newOwner.ID, c.ID)
if err != nil {
return fmt.Errorf("IsOrgMember: %v", err)
} else if !isMember {
continue
}
}
collaboration.UserID = c.ID
if _, err := sess.Delete(collaboration); err != nil {
return fmt.Errorf("remove collaborator '%d': %v", c.ID, err)
}
collaboration.UserID = 0
}
// Remove old team-repository relations.
if oldOwner.IsOrganization() {
if err := organization.RemoveOrgRepo(ctx, oldOwner.ID, repo.ID); err != nil {
return fmt.Errorf("removeOrgRepo: %v", err)
}
}
if newOwner.IsOrganization() {
teams, err := organization.FindOrgTeams(ctx, newOwner.ID)
if err != nil {
return fmt.Errorf("LoadTeams: %v", err)
}
for _, t := range teams {
if t.IncludesAllRepositories {
if err := addRepository(ctx, t, repo); err != nil {
return fmt.Errorf("addRepository: %v", err)
}
}
}
} else if err := recalculateAccesses(ctx, repo); err != nil {
// Organization called this in addRepository method.
return fmt.Errorf("recalculateAccesses: %v", err)
}
// Update repository count.
if _, err := sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.ID); err != nil {
return fmt.Errorf("increase new owner repository count: %v", err)
} else if _, err := sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", oldOwner.ID); err != nil {
return fmt.Errorf("decrease old owner repository count: %v", err)
}
if err := repo_model.WatchRepoCtx(ctx, doer.ID, repo.ID, true); err != nil {
return fmt.Errorf("watchRepo: %v", err)
}
// Remove watch for organization.
if oldOwner.IsOrganization() {
if err := repo_model.WatchRepoCtx(ctx, oldOwner.ID, repo.ID, false); err != nil {
return fmt.Errorf("watchRepo [false]: %v", err)
}
}
// Delete labels that belong to the old organization and comments that added these labels
if oldOwner.IsOrganization() {
if _, err := sess.Exec(`DELETE FROM issue_label WHERE issue_label.id IN (
SELECT il_too.id FROM (
SELECT il_too_too.id
FROM issue_label AS il_too_too
INNER JOIN label ON il_too_too.label_id = label.id
INNER JOIN issue on issue.id = il_too_too.issue_id
WHERE
issue.repo_id = ? AND ((label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != ?))
) AS il_too )`, repo.ID, newOwner.ID); err != nil {
return fmt.Errorf("Unable to remove old org labels: %v", err)
}
if _, err := sess.Exec(`DELETE FROM comment WHERE comment.id IN (
SELECT il_too.id FROM (
SELECT com.id
FROM comment AS com
INNER JOIN label ON com.label_id = label.id
INNER JOIN issue ON issue.id = com.issue_id
WHERE
com.type = ? AND issue.repo_id = ? AND ((label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != ?))
) AS il_too)`, CommentTypeLabel, repo.ID, newOwner.ID); err != nil {
return fmt.Errorf("Unable to remove old org label comments: %v", err)
}
}
// Rename remote repository to new path and delete local copy.
dir := user_model.UserPath(newOwner.Name)
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return fmt.Errorf("Failed to create dir %s: %v", dir, err)
}
if err := util.Rename(repo_model.RepoPath(oldOwner.Name, repo.Name), repo_model.RepoPath(newOwner.Name, repo.Name)); err != nil {
return fmt.Errorf("rename repository directory: %v", err)
}
repoRenamed = true
// Rename remote wiki repository to new path and delete local copy.
wikiPath := repo_model.WikiPath(oldOwner.Name, repo.Name)
if isExist, err := util.IsExist(wikiPath); err != nil {
log.Error("Unable to check if %s exists. Error: %v", wikiPath, err)
return err
} else if isExist {
if err := util.Rename(wikiPath, repo_model.WikiPath(newOwner.Name, repo.Name)); err != nil {
return fmt.Errorf("rename repository wiki: %v", err)
}
wikiRenamed = true
}
if err := deleteRepositoryTransfer(ctx, repo.ID); err != nil {
return fmt.Errorf("deleteRepositoryTransfer: %v", err)
}
repo.Status = repo_model.RepositoryReady
if err := repo_model.UpdateRepositoryColsCtx(ctx, repo, "status"); err != nil {
return err
}
// If there was previously a redirect at this location, remove it.
if err := repo_model.DeleteRedirect(ctx, newOwner.ID, repo.Name); err != nil {
return fmt.Errorf("delete repo redirect: %v", err)
}
if err := repo_model.NewRedirect(ctx, oldOwner.ID, repo.ID, repo.Name, repo.Name); err != nil {
return fmt.Errorf("repo_model.NewRedirect: %v", err)
}
return committer.Commit()
}
|