1package iterator
2
3import (
4 "context"
5
6 "code.gitea.io/sdk/gitea"
7)
8
9type labelIterator struct {
10 issue int64
11 page int
12 lastPage bool
13 index int
14 cache []*gitea.Label
15}
16
17func newLabelIterator() *labelIterator {
18 li := &labelIterator{}
19 li.Reset(-1)
20 return li
21}
22
23func (li *labelIterator) Next(ctx context.Context, conf config) (bool, error) {
24 // first query
25 if li.cache == nil {
26 return li.getNext(ctx, conf)
27 }
28
29 // move cursor index
30 if li.index < len(li.cache)-1 {
31 li.index++
32 return true, nil
33 }
34
35 return li.getNext(ctx, conf)
36}
37
38func (li *labelIterator) Value() *gitea.Label {
39 return li.cache[li.index]
40}
41
42func (li *labelIterator) getNext(ctx context.Context, conf config) (bool, error) {
43 if li.lastPage {
44 return false, nil
45 }
46
47 ctx, cancel := context.WithTimeout(ctx, conf.timeout)
48 defer cancel()
49 conf.gc.SetContext(ctx)
50
51 labels, _, err := conf.gc.GetIssueLabels(
52 conf.owner,
53 conf.project,
54 li.issue,
55 gitea.ListLabelsOptions{
56 ListOptions: gitea.ListOptions{
57 Page: li.page,
58 PageSize: conf.capacity,
59 },
60 },
61 )
62 if err != nil {
63 li.Reset(-1)
64 return false, err
65 }
66
67 li.lastPage = true
68
69 if len(labels) == 0 {
70 return false, nil
71 }
72
73 li.cache = labels
74 li.index = 0
75 li.page++
76
77 return true, nil
78}
79
80func (li *labelIterator) Reset(issue int64) {
81 li.issue = issue
82 li.index = -1
83 li.page = 1
84 li.lastPage = false
85 li.cache = nil
86}