aboutsummaryrefslogtreecommitdiffstats
path: root/bridge/gitlab/iterator/note.go
blob: a1e0544c69b804d1c1320d27594fe6158e9f9965 (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
80
81
82
83
84
85
86
87
88
89
90
package iterator

import (
	"context"

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

type noteIterator struct {
	issue    int
	page     int
	lastPage bool
	index    int
	cache    []*gitlab.Note
}

func newNoteIterator() *noteIterator {
	in := &noteIterator{}
	in.Reset(-1)
	return in
}

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

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

	return in.getNext(ctx, conf)
}

func (in *noteIterator) Value() *gitlab.Note {
	return in.cache[in.index]
}

func (in *noteIterator) getNext(ctx context.Context, conf config) (bool, error) {
	if in.lastPage {
		return false, nil
	}

	ctx, cancel := context.WithTimeout(ctx, conf.timeout)
	defer cancel()

	notes, resp, err := conf.gc.Notes.ListIssueNotes(
		conf.project,
		in.issue,
		&gitlab.ListIssueNotesOptions{
			ListOptions: gitlab.ListOptions{
				Page:    in.page,
				PerPage: conf.capacity,
			},
			Sort:    gitlab.String("asc"),
			OrderBy: gitlab.String("created_at"),
		},
		gitlab.WithContext(ctx),
	)

	if err != nil {
		in.Reset(-1)
		return false, err
	}

	if resp.TotalPages == in.page {
		in.lastPage = true
	}

	if len(notes) == 0 {
		return false, nil
	}

	in.cache = notes
	in.index = 0
	in.page++

	return true, nil
}

func (in *noteIterator) Reset(issue int) {
	in.issue = issue
	in.index = -1
	in.page = 1
	in.lastPage = false
	in.cache = nil
}