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 index int
13 cache []*gitlab.Note
14}
15
16func newNoteIterator() *noteIterator {
17 in := ¬eIterator{}
18 in.Reset(-1)
19 return in
20}
21
22func (in *noteIterator) Next(ctx context.Context, conf config) (bool, error) {
23 // first query
24 if in.cache == nil {
25 return in.getNext(ctx, conf)
26 }
27
28 // move cursor index
29 if in.index < len(in.cache)-1 {
30 in.index++
31 return true, nil
32 }
33
34 return in.getNext(ctx, conf)
35}
36
37func (in *noteIterator) Value() *gitlab.Note {
38 return in.cache[in.index]
39}
40
41func (in *noteIterator) getNext(ctx context.Context, conf config) (bool, error) {
42 ctx, cancel := context.WithTimeout(ctx, conf.timeout)
43 defer cancel()
44
45 notes, _, err := conf.gc.Notes.ListIssueNotes(
46 conf.project,
47 in.issue,
48 &gitlab.ListIssueNotesOptions{
49 ListOptions: gitlab.ListOptions{
50 Page: in.page,
51 PerPage: conf.capacity,
52 },
53 Sort: gitlab.String("asc"),
54 OrderBy: gitlab.String("created_at"),
55 },
56 gitlab.WithContext(ctx),
57 )
58
59 if err != nil {
60 in.Reset(-1)
61 return false, err
62 }
63
64 if len(notes) == 0 {
65 return false, nil
66 }
67
68 in.cache = notes
69 in.index = 0
70 in.page++
71
72 return true, nil
73}
74
75func (in *noteIterator) Reset(issue int) {
76 in.issue = issue
77 in.index = -1
78 in.page = -1
79 in.cache = nil
80}