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