summaryrefslogtreecommitdiffstats
path: root/services/migrations/onedev.go
blob: 1159026892db7ca3cccd6b37db5e48a0ebeb48cd (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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
// 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 migrations

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"

	"code.gitea.io/gitea/modules/json"
	"code.gitea.io/gitea/modules/log"
	base "code.gitea.io/gitea/modules/migration"
	"code.gitea.io/gitea/modules/structs"
)

var (
	_ base.Downloader        = &OneDevDownloader{}
	_ base.DownloaderFactory = &OneDevDownloaderFactory{}
)

func init() {
	RegisterDownloaderFactory(&OneDevDownloaderFactory{})
}

// OneDevDownloaderFactory defines a downloader factory
type OneDevDownloaderFactory struct {
}

// New returns a downloader related to this factory according MigrateOptions
func (f *OneDevDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) {
	u, err := url.Parse(opts.CloneAddr)
	if err != nil {
		return nil, err
	}

	repoName := ""

	fields := strings.Split(strings.Trim(u.Path, "/"), "/")
	if len(fields) == 2 && fields[0] == "projects" {
		repoName = fields[1]
	} else if len(fields) == 1 {
		repoName = fields[0]
	} else {
		return nil, fmt.Errorf("invalid path: %s", u.Path)
	}

	u.Path = ""
	u.Fragment = ""

	log.Trace("Create onedev downloader. BaseURL: %v RepoName: %s", u, repoName)

	return NewOneDevDownloader(ctx, u, opts.AuthUsername, opts.AuthPassword, repoName), nil
}

// GitServiceType returns the type of git service
func (f *OneDevDownloaderFactory) GitServiceType() structs.GitServiceType {
	return structs.OneDevService
}

type onedevUser struct {
	ID    int64  `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
}

// OneDevDownloader implements a Downloader interface to get repository informations
// from OneDev
type OneDevDownloader struct {
	base.NullDownloader
	ctx           context.Context
	client        *http.Client
	baseURL       *url.URL
	repoName      string
	repoID        int64
	maxIssueIndex int64
	userMap       map[int64]*onedevUser
	milestoneMap  map[int64]string
}

// SetContext set context
func (d *OneDevDownloader) SetContext(ctx context.Context) {
	d.ctx = ctx
}

// NewOneDevDownloader creates a new downloader
func NewOneDevDownloader(ctx context.Context, baseURL *url.URL, username, password, repoName string) *OneDevDownloader {
	var downloader = &OneDevDownloader{
		ctx:      ctx,
		baseURL:  baseURL,
		repoName: repoName,
		client: &http.Client{
			Transport: &http.Transport{
				Proxy: func(req *http.Request) (*url.URL, error) {
					if len(username) > 0 && len(password) > 0 {
						req.SetBasicAuth(username, password)
					}
					return nil, nil
				},
			},
		},
		userMap:      make(map[int64]*onedevUser),
		milestoneMap: make(map[int64]string),
	}

	return downloader
}

func (d *OneDevDownloader) callAPI(endpoint string, parameter map[string]string, result interface{}) error {
	u, err := d.baseURL.Parse(endpoint)
	if err != nil {
		return err
	}

	if parameter != nil {
		query := u.Query()
		for k, v := range parameter {
			query.Set(k, v)
		}
		u.RawQuery = query.Encode()
	}

	req, err := http.NewRequestWithContext(d.ctx, "GET", u.String(), nil)
	if err != nil {
		return err
	}

	resp, err := d.client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	decoder := json.NewDecoder(resp.Body)
	return decoder.Decode(&result)
}

// GetRepoInfo returns repository information
func (d *OneDevDownloader) GetRepoInfo() (*base.Repository, error) {
	info := make([]struct {
		ID          int64  `json:"id"`
		Name        string `json:"name"`
		Description string `json:"description"`
	}, 0, 1)

	err := d.callAPI(
		"/api/projects",
		map[string]string{
			"query":  `"Name" is "` + d.repoName + `"`,
			"offset": "0",
			"count":  "1",
		},
		&info,
	)
	if err != nil {
		return nil, err
	}
	if len(info) != 1 {
		return nil, fmt.Errorf("Project %s not found", d.repoName)
	}

	d.repoID = info[0].ID

	cloneURL, err := d.baseURL.Parse(info[0].Name)
	if err != nil {
		return nil, err
	}
	originalURL, err := d.baseURL.Parse("/projects/" + info[0].Name)
	if err != nil {
		return nil, err
	}

	return &base.Repository{
		Name:        info[0].Name,
		Description: info[0].Description,
		CloneURL:    cloneURL.String(),
		OriginalURL: originalURL.String(),
	}, nil
}

// GetMilestones returns milestones
func (d *OneDevDownloader) GetMilestones() ([]*base.Milestone, error) {
	rawMilestones := make([]struct {
		ID          int64      `json:"id"`
		Name        string     `json:"name"`
		Description string     `json:"description"`
		DueDate     *time.Time `json:"dueDate"`
		Closed      bool       `json:"closed"`
	}, 0, 100)

	endpoint := fmt.Sprintf("/api/projects/%d/milestones", d.repoID)

	var milestones = make([]*base.Milestone, 0, 100)
	offset := 0
	for {
		err := d.callAPI(
			endpoint,
			map[string]string{
				"offset": strconv.Itoa(offset),
				"count":  "100",
			},
			&rawMilestones,
		)
		if err != nil {
			return nil, err
		}
		if len(rawMilestones) == 0 {
			break
		}
		offset += 100

		for _, milestone := range rawMilestones {
			d.milestoneMap[milestone.ID] = milestone.Name
			closed := milestone.DueDate
			if !milestone.Closed {
				closed = nil
			}

			milestones = append(milestones, &base.Milestone{
				Title:       milestone.Name,
				Description: milestone.Description,
				Deadline:    milestone.DueDate,
				Closed:      closed,
			})
		}
	}
	return milestones, nil
}

// GetLabels returns labels
func (d *OneDevDownloader) GetLabels() ([]*base.Label, error) {
	return []*base.Label{
		{
			Name:  "Bug",
			Color: "f64e60",
		},
		{
			Name:  "Build Failure",
			Color: "f64e60",
		},
		{
			Name:  "Discussion",
			Color: "8950fc",
		},
		{
			Name:  "Improvement",
			Color: "1bc5bd",
		},
		{
			Name:  "New Feature",
			Color: "1bc5bd",
		},
		{
			Name:  "Support Request",
			Color: "8950fc",
		},
	}, nil
}

type onedevIssueContext struct {
	foreignID     int64
	localID       int64
	IsPullRequest bool
}

func (c onedevIssueContext) LocalID() int64 {
	return c.localID
}

func (c onedevIssueContext) ForeignID() int64 {
	return c.foreignID
}

// GetIssues returns issues
func (d *OneDevDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, error) {
	rawIssues := make([]struct {
		ID          int64     `json:"id"`
		Number      int64     `json:"number"`
		State       string    `json:"state"`
		Title       string    `json:"title"`
		Description string    `json:"description"`
		MilestoneID int64     `json:"milestoneId"`
		SubmitterID int64     `json:"submitterId"`
		SubmitDate  time.Time `json:"submitDate"`
	}, 0, perPage)

	err := d.callAPI(
		"/api/issues",
		map[string]string{
			"query":  `"Project" is "` + d.repoName + `"`,
			"offset": strconv.Itoa((page - 1) * perPage),
			"count":  strconv.Itoa(perPage),
		},
		&rawIssues,
	)
	if err != nil {
		return nil, false, err
	}

	issues := make([]*base.Issue, 0, len(rawIssues))
	for _, issue := range rawIssues {
		fields := make([]struct {
			Name  string `json:"name"`
			Value string `json:"value"`
		}, 0, 10)
		err := d.callAPI(
			fmt.Sprintf("/api/issues/%d/fields", issue.ID),
			nil,
			&fields,
		)
		if err != nil {
			return nil, false, err
		}

		var label *base.Label
		for _, field := range fields {
			if field.Name == "Type" {
				label = &base.Label{Name: field.Value}
				break
			}
		}

		state := strings.ToLower(issue.State)
		if state == "released" {
			state = "closed"
		}
		poster := d.tryGetUser(issue.SubmitterID)
		issues = append(issues, &base.Issue{
			Title:       issue.Title,
			Number:      issue.Number,
			PosterName:  poster.Name,
			PosterEmail: poster.Email,
			Content:     issue.Description,
			Milestone:   d.milestoneMap[issue.MilestoneID],
			State:       state,
			Created:     issue.SubmitDate,
			Updated:     issue.SubmitDate,
			Labels:      []*base.Label{label},
			Context: onedevIssueContext{
				foreignID:     issue.ID,
				localID:       issue.Number,
				IsPullRequest: false,
			},
		})

		if d.maxIssueIndex < issue.Number {
			d.maxIssueIndex = issue.Number
		}
	}

	return issues, len(issues) == 0, nil
}

// GetComments returns comments
func (d *OneDevDownloader) GetComments(opts base.GetCommentOptions) ([]*base.Comment, bool, error) {
	context, ok := opts.Context.(onedevIssueContext)
	if !ok {
		return nil, false, fmt.Errorf("unexpected comment context: %+v", opts.Context)
	}

	rawComments := make([]struct {
		Date    time.Time `json:"date"`
		UserID  int64     `json:"userId"`
		Content string    `json:"content"`
	}, 0, 100)

	var endpoint string
	if context.IsPullRequest {
		endpoint = fmt.Sprintf("/api/pull-requests/%d/comments", context.ForeignID())
	} else {
		endpoint = fmt.Sprintf("/api/issues/%d/comments", context.ForeignID())
	}

	err := d.callAPI(
		endpoint,
		nil,
		&rawComments,
	)
	if err != nil {
		return nil, false, err
	}

	rawChanges := make([]struct {
		Date   time.Time              `json:"date"`
		UserID int64                  `json:"userId"`
		Data   map[string]interface{} `json:"data"`
	}, 0, 100)

	if context.IsPullRequest {
		endpoint = fmt.Sprintf("/api/pull-requests/%d/changes", context.ForeignID())
	} else {
		endpoint = fmt.Sprintf("/api/issues/%d/changes", context.ForeignID())
	}

	err = d.callAPI(
		endpoint,
		nil,
		&rawChanges,
	)
	if err != nil {
		return nil, false, err
	}

	comments := make([]*base.Comment, 0, len(rawComments)+len(rawChanges))
	for _, comment := range rawComments {
		if len(comment.Content) == 0 {
			continue
		}
		poster := d.tryGetUser(comment.UserID)
		comments = append(comments, &base.Comment{
			IssueIndex:  context.LocalID(),
			PosterID:    poster.ID,
			PosterName:  poster.Name,
			PosterEmail: poster.Email,
			Content:     comment.Content,
			Created:     comment.Date,
			Updated:     comment.Date,
		})
	}
	for _, change := range rawChanges {
		contentV, ok := change.Data["content"]
		if !ok {
			contentV, ok = change.Data["comment"]
			if !ok {
				continue
			}
		}
		content, ok := contentV.(string)
		if !ok || len(content) == 0 {
			continue
		}

		poster := d.tryGetUser(change.UserID)
		comments = append(comments, &base.Comment{
			IssueIndex:  context.LocalID(),
			PosterID:    poster.ID,
			PosterName:  poster.Name,
			PosterEmail: poster.Email,
			Content:     content,
			Created:     change.Date,
			Updated:     change.Date,
		})
	}

	return comments, true, nil
}

// GetPullRequests returns pull requests
func (d *OneDevDownloader) GetPullRequests(page, perPage int) ([]*base.PullRequest, bool, error) {
	rawPullRequests := make([]struct {
		ID             int64     `json:"id"`
		Number         int64     `json:"number"`
		Title          string    `json:"title"`
		SubmitterID    int64     `json:"submitterId"`
		SubmitDate     time.Time `json:"submitDate"`
		Description    string    `json:"description"`
		TargetBranch   string    `json:"targetBranch"`
		SourceBranch   string    `json:"sourceBranch"`
		BaseCommitHash string    `json:"baseCommitHash"`
		CloseInfo      *struct {
			Date   *time.Time `json:"date"`
			Status string     `json:"status"`
		}
	}, 0, perPage)

	err := d.callAPI(
		"/api/pull-requests",
		map[string]string{
			"query":  `"Target Project" is "` + d.repoName + `"`,
			"offset": strconv.Itoa((page - 1) * perPage),
			"count":  strconv.Itoa(perPage),
		},
		&rawPullRequests,
	)
	if err != nil {
		return nil, false, err
	}

	pullRequests := make([]*base.PullRequest, 0, len(rawPullRequests))
	for _, pr := range rawPullRequests {
		var mergePreview struct {
			TargetHeadCommitHash string `json:"targetHeadCommitHash"`
			HeadCommitHash       string `json:"headCommitHash"`
			MergeStrategy        string `json:"mergeStrategy"`
			MergeCommitHash      string `json:"mergeCommitHash"`
		}
		err := d.callAPI(
			fmt.Sprintf("/api/pull-requests/%d/merge-preview", pr.ID),
			nil,
			&mergePreview,
		)
		if err != nil {
			return nil, false, err
		}

		state := "open"
		merged := false
		var closeTime *time.Time
		var mergedTime *time.Time
		if pr.CloseInfo != nil {
			state = "closed"
			closeTime = pr.CloseInfo.Date
			if pr.CloseInfo.Status == "MERGED" { // "DISCARDED"
				merged = true
				mergedTime = pr.CloseInfo.Date
			}
		}
		poster := d.tryGetUser(pr.SubmitterID)

		number := pr.Number + d.maxIssueIndex
		pullRequests = append(pullRequests, &base.PullRequest{
			Title:      pr.Title,
			Number:     number,
			PosterName: poster.Name,
			PosterID:   poster.ID,
			Content:    pr.Description,
			State:      state,
			Created:    pr.SubmitDate,
			Updated:    pr.SubmitDate,
			Closed:     closeTime,
			Merged:     merged,
			MergedTime: mergedTime,
			Head: base.PullRequestBranch{
				Ref:      pr.SourceBranch,
				SHA:      mergePreview.HeadCommitHash,
				RepoName: d.repoName,
			},
			Base: base.PullRequestBranch{
				Ref:      pr.TargetBranch,
				SHA:      mergePreview.TargetHeadCommitHash,
				RepoName: d.repoName,
			},
			Context: onedevIssueContext{
				foreignID:     pr.ID,
				localID:       number,
				IsPullRequest: true,
			},
		})
	}

	return pullRequests, len(pullRequests) == 0, nil
}

// GetReviews returns pull requests reviews
func (d *OneDevDownloader) GetReviews(context base.IssueContext) ([]*base.Review, error) {
	rawReviews := make([]struct {
		ID     int64 `json:"id"`
		UserID int64 `json:"userId"`
		Result *struct {
			Commit   string `json:"commit"`
			Approved bool   `json:"approved"`
			Comment  string `json:"comment"`
		}
	}, 0, 100)

	err := d.callAPI(
		fmt.Sprintf("/api/pull-requests/%d/reviews", context.ForeignID()),
		nil,
		&rawReviews,
	)
	if err != nil {
		return nil, err
	}

	var reviews = make([]*base.Review, 0, len(rawReviews))
	for _, review := range rawReviews {
		state := base.ReviewStatePending
		content := ""
		if review.Result != nil {
			if len(review.Result.Comment) > 0 {
				state = base.ReviewStateCommented
				content = review.Result.Comment
			}
			if review.Result.Approved {
				state = base.ReviewStateApproved
			}
		}

		poster := d.tryGetUser(review.UserID)
		reviews = append(reviews, &base.Review{
			IssueIndex:   context.LocalID(),
			ReviewerID:   poster.ID,
			ReviewerName: poster.Name,
			Content:      content,
			State:        state,
		})
	}

	return reviews, nil
}

// GetTopics return repository topics
func (d *OneDevDownloader) GetTopics() ([]string, error) {
	return []string{}, nil
}

func (d *OneDevDownloader) tryGetUser(userID int64) *onedevUser {
	user, ok := d.userMap[userID]
	if !ok {
		err := d.callAPI(
			fmt.Sprintf("/api/users/%d", userID),
			nil,
			&user,
		)
		if err != nil {
			user = &onedevUser{
				Name: fmt.Sprintf("User %d", userID),
			}
		}
		d.userMap[userID] = user
	}

	return user
}