1package iterator
2
3import (
4 "context"
5
6 "github.com/xanzy/go-gitlab"
7)
8
9type noteIterator struct {
10 issue int
11 page int
12 lastPage bool
13 index int
14 cache []*gitlab.Note
15}
16
17func newNoteIterator() *noteIterator {
18 in := ¬eIterator{}
19 in.Reset(-1)
20 return in
21}
22
23func (in *noteIterator) Next(ctx context.Context, conf config) (bool, error) {
24 // first query
25 if in.cache == nil {
26 return in.getNext(ctx, conf)
27 }
28
29 // move cursor index
30 if in.index < len(in.cache)-1 {
31 in.index++
32 return true, nil
33 }
34
35 return in.getNext(ctx, conf)
36}
37
38func (in *noteIterator) Value() *gitlab.Note {
39 return in.cache[in.index]
40}
41
42func (in *noteIterator) getNext(ctx context.Context, conf config) (bool, error) {
43 if in.lastPage {
44 return false, nil
45 }
46
47 ctx, cancel := context.WithTimeout(ctx, conf.timeout)
48 defer cancel()
49
50 notes, resp, err := conf.gc.Notes.ListIssueNotes(
51 conf.project,
52 in.issue,
53 &gitlab.ListIssueNotesOptions{
54 ListOptions: gitlab.ListOptions{
55 Page: in.page,
56 PerPage: conf.capacity,
57 },
58 Sort: gitlab.String("asc"),
59 OrderBy: gitlab.String("created_at"),
60 },
61 gitlab.WithContext(ctx),
62 )
63
64 if err != nil {
65 in.Reset(-1)
66 return false, err
67 }
68
69 if resp.TotalPages == in.page {
70 in.lastPage = true
71 }
72
73 if len(notes) == 0 {
74 return false, nil
75 }
76
77 in.cache = notes
78 in.index = 0
79 in.page++
80
81 return true, nil
82}
83
84func (in *noteIterator) Reset(issue int) {
85 in.issue = issue
86 in.index = -1
87 in.page = 1
88 in.lastPage = false
89 in.cache = nil
90}