summaryrefslogtreecommitdiffstats
path: root/modules/migrations/gitea.go
blob: 08244e5ab29a4f8ce4eb19b7833de204c885599b (plain)
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// Copyright 2019 The Gitea Authors. All rights reserved.
// Copyright 2018 Jonas Franz. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package migrations

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/git"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/migrations/base"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/util"

	gouuid "github.com/satori/go.uuid"
)

var (
	_ base.Uploader = &GiteaLocalUploader{}
)

// GiteaLocalUploader implements an Uploader to gitea sites
type GiteaLocalUploader struct {
	doer        *models.User
	repoOwner   string
	repoName    string
	repo        *models.Repository
	labels      sync.Map
	milestones  sync.Map
	issues      sync.Map
	gitRepo     *git.Repository
	prHeadCache map[string]struct{}
}

// NewGiteaLocalUploader creates an gitea Uploader via gitea API v1
func NewGiteaLocalUploader(doer *models.User, repoOwner, repoName string) *GiteaLocalUploader {
	return &GiteaLocalUploader{
		doer:        doer,
		repoOwner:   repoOwner,
		repoName:    repoName,
		prHeadCache: make(map[string]struct{}),
	}
}

// MaxBatchInsertSize returns the table's max batch insert size
func (g *GiteaLocalUploader) MaxBatchInsertSize(tp string) int {
	switch tp {
	case "issue":
		return models.MaxBatchInsertSize(new(models.Issue))
	case "comment":
		return models.MaxBatchInsertSize(new(models.Comment))
	case "milestone":
		return models.MaxBatchInsertSize(new(models.Milestone))
	case "label":
		return models.MaxBatchInsertSize(new(models.Label))
	case "release":
		return models.MaxBatchInsertSize(new(models.Release))
	case "pullrequest":
		return models.MaxBatchInsertSize(new(models.PullRequest))
	}
	return 10
}

// CreateRepo creates a repository
func (g *GiteaLocalUploader) CreateRepo(repo *base.Repository, opts base.MigrateOptions) error {
	owner, err := models.GetUserByName(g.repoOwner)
	if err != nil {
		return err
	}

	r, err := models.MigrateRepository(g.doer, owner, models.MigrateRepoOptions{
		Name:                 g.repoName,
		Description:          repo.Description,
		OriginalURL:          repo.OriginalURL,
		IsMirror:             repo.IsMirror,
		RemoteAddr:           repo.CloneURL,
		IsPrivate:            repo.IsPrivate,
		Wiki:                 opts.Wiki,
		SyncReleasesWithTags: !opts.Releases, // if didn't get releases, then sync them from tags
	})
	g.repo = r
	if err != nil {
		return err
	}
	g.gitRepo, err = git.OpenRepository(r.RepoPath())
	return err
}

// CreateTopics creates topics
func (g *GiteaLocalUploader) CreateTopics(topics ...string) error {
	return models.SaveTopics(g.repo.ID, topics...)
}

// CreateMilestones creates milestones
func (g *GiteaLocalUploader) CreateMilestones(milestones ...*base.Milestone) error {
	var mss = make([]*models.Milestone, 0, len(milestones))
	for _, milestone := range milestones {
		var deadline util.TimeStamp
		if milestone.Deadline != nil {
			deadline = util.TimeStamp(milestone.Deadline.Unix())
		}
		if deadline == 0 {
			deadline = util.TimeStamp(time.Date(9999, 1, 1, 0, 0, 0, 0, setting.UILocation).Unix())
		}
		var ms = models.Milestone{
			RepoID:       g.repo.ID,
			Name:         milestone.Title,
			Content:      milestone.Description,
			IsClosed:     milestone.State == "closed",
			DeadlineUnix: deadline,
		}
		if ms.IsClosed && milestone.Closed != nil {
			ms.ClosedDateUnix = util.TimeStamp(milestone.Closed.Unix())
		}
		mss = append(mss, &ms)
	}

	err := models.InsertMilestones(mss...)
	if err != nil {
		return err
	}

	for _, ms := range mss {
		g.milestones.Store(ms.Name, ms.ID)
	}
	return nil
}

// CreateLabels creates labels
func (g *GiteaLocalUploader) CreateLabels(labels ...*base.Label) error {
	var lbs = make([]*models.Label, 0, len(labels))
	for _, label := range labels {
		lbs = append(lbs, &models.Label{
			RepoID:      g.repo.ID,
			Name:        label.Name,
			Description: label.Description,
			Color:       fmt.Sprintf("#%s", label.Color),
		})
	}

	err := models.NewLabels(lbs...)
	if err != nil {
		return err
	}
	for _, lb := range lbs {
		g.labels.Store(lb.Name, lb)
	}
	return nil
}

// CreateReleases creates releases
func (g *GiteaLocalUploader) CreateReleases(releases ...*base.Release) error {
	var rels = make([]*models.Release, 0, len(releases))
	for _, release := range releases {
		var rel = models.Release{
			RepoID:       g.repo.ID,
			PublisherID:  g.doer.ID,
			TagName:      release.TagName,
			LowerTagName: strings.ToLower(release.TagName),
			Target:       release.TargetCommitish,
			Title:        release.Name,
			Sha1:         release.TargetCommitish,
			Note:         release.Body,
			IsDraft:      release.Draft,
			IsPrerelease: release.Prerelease,
			IsTag:        false,
			CreatedUnix:  util.TimeStamp(release.Created.Unix()),
		}

		// calc NumCommits
		commit, err := g.gitRepo.GetCommit(rel.TagName)
		if err != nil {
			return fmt.Errorf("GetCommit: %v", err)
		}
		rel.NumCommits, err = commit.CommitsCount()
		if err != nil {
			return fmt.Errorf("CommitsCount: %v", err)
		}

		for _, asset := range release.Assets {
			var attach = models.Attachment{
				UUID:          gouuid.NewV4().String(),
				Name:          asset.Name,
				DownloadCount: int64(*asset.DownloadCount),
				Size:          int64(*asset.Size),
				CreatedUnix:   util.TimeStamp(asset.Created.Unix()),
			}

			// download attachment
			resp, err := http.Get(asset.URL)
			if err != nil {
				return err
			}
			defer resp.Body.Close()

			localPath := attach.LocalPath()
			if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
				return fmt.Errorf("MkdirAll: %v", err)
			}

			fw, err := os.Create(localPath)
			if err != nil {
				return fmt.Errorf("Create: %v", err)
			}
			defer fw.Close()

			if _, err := io.Copy(fw, resp.Body); err != nil {
				return err
			}

			rel.Attachments = append(rel.Attachments, &attach)
		}

		rels = append(rels, &rel)
	}
	if err := models.InsertReleases(rels...); err != nil {
		return err
	}

	// sync tags to releases in database
	return models.SyncReleasesWithTags(g.repo, g.gitRepo)
}

// CreateIssues creates issues
func (g *GiteaLocalUploader) CreateIssues(issues ...*base.Issue) error {
	var iss = make([]*models.Issue, 0, len(issues))
	for _, issue := range issues {
		var labels []*models.Label
		for _, label := range issue.Labels {
			lb, ok := g.labels.Load(label.Name)
			if ok {
				labels = append(labels, lb.(*models.Label))
			}
		}

		var milestoneID int64
		if issue.Milestone != "" {
			milestone, ok := g.milestones.Load(issue.Milestone)
			if ok {
				milestoneID = milestone.(int64)
			}
		}

		var is = models.Issue{
			RepoID:           g.repo.ID,
			Repo:             g.repo,
			Index:            issue.Number,
			PosterID:         g.doer.ID,
			OriginalAuthor:   issue.PosterName,
			OriginalAuthorID: issue.PosterID,
			Title:            issue.Title,
			Content:          issue.Content,
			IsClosed:         issue.State == "closed",
			IsLocked:         issue.IsLocked,
			MilestoneID:      milestoneID,
			Labels:           labels,
			CreatedUnix:      util.TimeStamp(issue.Created.Unix()),
		}
		if issue.Closed != nil {
			is.ClosedUnix = util.TimeStamp(issue.Closed.Unix())
		}
		// TODO: add reactions
		iss = append(iss, &is)
	}

	err := models.InsertIssues(iss...)
	if err != nil {
		return err
	}
	for _, is := range iss {
		g.issues.Store(is.Index, is.ID)
	}
	return nil
}

// CreateComments creates comments of issues
func (g *GiteaLocalUploader) CreateComments(comments ...*base.Comment) error {
	var cms = make([]*models.Comment, 0, len(comments))
	for _, comment := range comments {
		var issueID int64
		if issueIDStr, ok := g.issues.Load(comment.IssueIndex); !ok {
			issue, err := models.GetIssueByIndex(g.repo.ID, comment.IssueIndex)
			if err != nil {
				return err
			}
			issueID = issue.ID
			g.issues.Store(comment.IssueIndex, issueID)
		} else {
			issueID = issueIDStr.(int64)
		}

		cms = append(cms, &models.Comment{
			IssueID:          issueID,
			Type:             models.CommentTypeComment,
			PosterID:         g.doer.ID,
			OriginalAuthor:   comment.PosterName,
			OriginalAuthorID: comment.PosterID,
			Content:          comment.Content,
			CreatedUnix:      util.TimeStamp(comment.Created.Unix()),
		})

		// TODO: Reactions
	}

	return models.InsertIssueComments(cms)
}

// CreatePullRequests creates pull requests
func (g *GiteaLocalUploader) CreatePullRequests(prs ...*base.PullRequest) error {
	var gprs = make([]*models.PullRequest, 0, len(prs))
	for _, pr := range prs {
		gpr, err := g.newPullRequest(pr)
		if err != nil {
			return err
		}
		gprs = append(gprs, gpr)
	}
	if err := models.InsertPullRequests(gprs...); err != nil {
		return err
	}
	for _, pr := range gprs {
		g.issues.Store(pr.Issue.Index, pr.Issue.ID)
	}
	return nil
}

func (g *GiteaLocalUploader) newPullRequest(pr *base.PullRequest) (*models.PullRequest, error) {
	var labels []*models.Label
	for _, label := range pr.Labels {
		lb, ok := g.labels.Load(label.Name)
		if ok {
			labels = append(labels, lb.(*models.Label))
		}
	}

	var milestoneID int64
	if pr.Milestone != "" {
		milestone, ok := g.milestones.Load(pr.Milestone)
		if ok {
			milestoneID = milestone.(int64)
		}
	}

	// download patch file
	resp, err := http.Get(pr.PatchURL)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	pullDir := filepath.Join(g.repo.RepoPath(), "pulls")
	if err = os.MkdirAll(pullDir, os.ModePerm); err != nil {
		return nil, err
	}
	f, err := os.Create(filepath.Join(pullDir, fmt.Sprintf("%d.patch", pr.Number)))
	if err != nil {
		return nil, err
	}
	defer f.Close()
	_, err = io.Copy(f, resp.Body)
	if err != nil {
		return nil, err
	}

	// set head information
	pullHead := filepath.Join(g.repo.RepoPath(), "refs", "pull", fmt.Sprintf("%d", pr.Number))
	if err := os.MkdirAll(pullHead, os.ModePerm); err != nil {
		return nil, err
	}
	p, err := os.Create(filepath.Join(pullHead, "head"))
	if err != nil {
		return nil, err
	}
	defer p.Close()
	_, err = p.WriteString(pr.Head.SHA)
	if err != nil {
		return nil, err
	}

	var head = "unknown repository"
	if pr.IsForkPullRequest() && pr.State != "closed" {
		if pr.Head.OwnerName != "" {
			remote := pr.Head.OwnerName
			_, ok := g.prHeadCache[remote]
			if !ok {
				// git remote add
				err := g.gitRepo.AddRemote(remote, pr.Head.CloneURL, true)
				if err != nil {
					log.Error("AddRemote failed: %s", err)
				} else {
					g.prHeadCache[remote] = struct{}{}
					ok = true
				}
			}

			if ok {
				_, err = git.NewCommand("fetch", remote, pr.Head.Ref).RunInDir(g.repo.RepoPath())
				if err != nil {
					log.Error("Fetch branch from %s failed: %v", pr.Head.CloneURL, err)
				} else {
					headBranch := filepath.Join(g.repo.RepoPath(), "refs", "heads", pr.Head.OwnerName, pr.Head.Ref)
					if err := os.MkdirAll(filepath.Dir(headBranch), os.ModePerm); err != nil {
						return nil, err
					}
					b, err := os.Create(headBranch)
					if err != nil {
						return nil, err
					}
					defer b.Close()
					_, err = b.WriteString(pr.Head.SHA)
					if err != nil {
						return nil, err
					}
					head = pr.Head.OwnerName + "/" + pr.Head.Ref
				}
			}
		}
	} else {
		head = pr.Head.Ref
	}

	var pullRequest = models.PullRequest{
		HeadRepoID:   g.repo.ID,
		HeadBranch:   head,
		HeadUserName: g.repoOwner,
		BaseRepoID:   g.repo.ID,
		BaseBranch:   pr.Base.Ref,
		MergeBase:    pr.Base.SHA,
		Index:        pr.Number,
		HasMerged:    pr.Merged,

		Issue: &models.Issue{
			RepoID:           g.repo.ID,
			Repo:             g.repo,
			Title:            pr.Title,
			Index:            pr.Number,
			PosterID:         g.doer.ID,
			OriginalAuthor:   pr.PosterName,
			OriginalAuthorID: pr.PosterID,
			Content:          pr.Content,
			MilestoneID:      milestoneID,
			IsPull:           true,
			IsClosed:         pr.State == "closed",
			IsLocked:         pr.IsLocked,
			Labels:           labels,
			CreatedUnix:      util.TimeStamp(pr.Created.Unix()),
		},
	}

	if pullRequest.Issue.IsClosed && pr.Closed != nil {
		pullRequest.Issue.ClosedUnix = util.TimeStamp(pr.Closed.Unix())
	}
	if pullRequest.HasMerged && pr.MergedTime != nil {
		pullRequest.MergedUnix = util.TimeStamp(pr.MergedTime.Unix())
		pullRequest.MergedCommitID = pr.MergeCommitSHA
		pullRequest.MergerID = g.doer.ID
	}

	// TODO: reactions
	// TODO: assignees

	return &pullRequest, nil
}

// Rollback when migrating failed, this will rollback all the changes.
func (g *GiteaLocalUploader) Rollback() error {
	if g.repo != nil && g.repo.ID > 0 {
		if err := models.DeleteRepository(g.doer, g.repo.OwnerID, g.repo.ID); err != nil {
			return err
		}
	}
	return nil
}