aboutsummaryrefslogtreecommitdiffstats
path: root/bridge/gitlab/iterator/issue.go
blob: a6bcebf189bc73c7b8bc42d6e006d72726d36b4f (plain) (blame)
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
package iterator

import (
	"context"

	"github.com/xanzy/go-gitlab"
)

type issueIterator struct {
	page  int
	index int
	cache []*gitlab.Issue
}

func newIssueIterator() *issueIterator {
	ii := &issueIterator{}
	ii.Reset()
	return ii
}

func (ii *issueIterator) Next(ctx context.Context, conf config) (bool, error) {
	// first query
	if ii.cache == nil {
		return ii.getNext(ctx, conf)
	}

	// move cursor index
	if ii.index < len(ii.cache)-1 {
		ii.index++
		return true, nil
	}

	return ii.getNext(ctx, conf)
}

func (ii *issueIterator) Value() *gitlab.Issue {
	return ii.cache[ii.index]
}

func (ii *issueIterator) getNext(ctx context.Context, conf config) (bool, error) {
	ctx, cancel := context.WithTimeout(ctx, conf.timeout)
	defer cancel()

	issues, _, err := conf.gc.Issues.ListProjectIssues(
		conf.project,
		&gitlab.ListProjectIssuesOptions{
			ListOptions: gitlab.ListOptions{
				Page:    ii.page,
				PerPage: conf.capacity,
			},
			Scope:        gitlab.String("all"),
			UpdatedAfter: &conf.since,
			Sort:         gitlab.String("asc"),
		},
		gitlab.WithContext(ctx),
	)

	if err != nil {
		ii.Reset()
		return false, err
	}

	// if repository doesn't have any issues
	if len(issues) == 0 {
		return false, nil
	}

	ii.cache = issues
	ii.index = 0
	ii.page++

	return true, nil
}

func (ii *issueIterator) Reset() {
	ii.index = -1
	ii.page = -1
	ii.cache = nil
}