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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
|
package gitlab
import (
"context"
"fmt"
"strconv"
"time"
"github.com/xanzy/go-gitlab"
"github.com/MichaelMure/git-bug/bridge/core"
"github.com/MichaelMure/git-bug/bridge/core/auth"
"github.com/MichaelMure/git-bug/cache"
"github.com/MichaelMure/git-bug/entity"
"github.com/MichaelMure/git-bug/util/text"
)
// gitlabImporter implement the Importer interface
type gitlabImporter struct {
conf core.Configuration
// default client
client *gitlab.Client
// send only channel
out chan<- core.ImportResult
}
func (gi *gitlabImporter) Init(_ context.Context, repo *cache.RepoCache, conf core.Configuration) error {
gi.conf = conf
creds, err := auth.List(repo,
auth.WithTarget(target),
auth.WithKind(auth.KindToken),
auth.WithMeta(auth.MetaKeyBaseURL, conf[confKeyGitlabBaseUrl]),
auth.WithMeta(auth.MetaKeyLogin, conf[confKeyDefaultLogin]),
)
if err != nil {
return err
}
if len(creds) == 0 {
return ErrMissingIdentityToken
}
gi.client, err = buildClient(conf[confKeyGitlabBaseUrl], creds[0].(*auth.Token))
if err != nil {
return err
}
return nil
}
// ImportAll iterate over all the configured repository issues (notes) and ensure the creation
// of the missing issues / comments / label events / title changes ...
func (gi *gitlabImporter) ImportAll(ctx context.Context, repo *cache.RepoCache, since time.Time) (<-chan core.ImportResult, error) {
out := make(chan core.ImportResult)
gi.out = out
go func() {
defer close(out)
for issue := range Issues(ctx, gi.client, gi.conf[confKeyProjectID], since) {
b, err := gi.ensureIssue(repo, issue)
if err != nil {
err := fmt.Errorf("issue creation: %v", err)
out <- core.NewImportError(err, "")
return
}
issueEvents := SortedEvents(
Notes(ctx, gi.client, issue),
LabelEvents(ctx, gi.client, issue),
StateEvents(ctx, gi.client, issue),
)
for e := range issueEvents {
if e, ok := e.(ErrorEvent); ok {
out <- core.NewImportError(e.Err, "")
continue
}
if err := gi.ensureIssueEvent(repo, b, issue, e); err != nil {
err := fmt.Errorf("issue event creation: %v", err)
out <- core.NewImportError(err, entity.Id(e.ID()))
}
}
if !b.NeedCommit() {
out <- core.NewImportNothing(b.Id(), "no imported operation")
} else if err := b.Commit(); err != nil {
// commit bug state
err := fmt.Errorf("bug commit: %v", err)
out <- core.NewImportError(err, "")
return
}
}
}()
return out, nil
}
func (gi *gitlabImporter) ensureIssue(repo *cache.RepoCache, issue *gitlab.Issue) (*cache.BugCache, error) {
// ensure issue author
author, err := gi.ensurePerson(repo, issue.Author.ID)
if err != nil {
return nil, err
}
// resolve bug
b, err := repo.Bugs().ResolveMatcher(func(excerpt *cache.BugExcerpt) bool {
return excerpt.CreateMetadata[core.MetaKeyOrigin] == target &&
excerpt.CreateMetadata[metaKeyGitlabId] == fmt.Sprintf("%d", issue.IID) &&
excerpt.CreateMetadata[metaKeyGitlabBaseUrl] == gi.conf[confKeyGitlabBaseUrl] &&
excerpt.CreateMetadata[metaKeyGitlabProject] == gi.conf[confKeyProjectID]
})
if err == nil {
return b, nil
}
if !entity.IsErrNotFound(err) {
return nil, err
}
// if bug was never imported, create bug
b, _, err = repo.Bugs().NewRaw(
author,
issue.CreatedAt.Unix(),
text.CleanupOneLine(issue.Title),
text.Cleanup(issue.Description),
nil,
map[string]string{
core.MetaKeyOrigin: target,
metaKeyGitlabId: fmt.Sprintf("%d", issue.IID),
metaKeyGitlabUrl: issue.WebURL,
metaKeyGitlabProject: gi.conf[confKeyProjectID],
metaKeyGitlabBaseUrl: gi.conf[confKeyGitlabBaseUrl],
},
)
if err != nil {
return nil, err
}
// importing a new bug
gi.out <- core.NewImportBug(b.Id())
return b, nil
}
func (gi *gitlabImporter) ensureIssueEvent(repo *cache.RepoCache, b *cache.BugCache, issue *gitlab.Issue, event Event) error {
id, errResolve := b.ResolveOperationWithMetadata(metaKeyGitlabId, event.ID())
if errResolve != nil && errResolve != cache.ErrNoMatchingOp {
return errResolve
}
// ensure issue author
author, err := gi.ensurePerson(repo, event.UserID())
if err != nil {
return err
}
switch event.Kind() {
case EventClosed:
if errResolve == nil {
return nil
}
op, err := b.CloseRaw(
author,
event.CreatedAt().Unix(),
map[string]string{
metaKeyGitlabId: event.ID(),
},
)
if err != nil {
return err
}
gi.out <- core.NewImportStatusChange(b.Id(), op.Id())
case EventReopened:
if errResolve == nil {
return nil
}
op, err := b.OpenRaw(
author,
event.CreatedAt().Unix(),
map[string]string{
metaKeyGitlabId: event.ID(),
},
)
if err != nil {
return err
}
gi.out <- core.NewImportStatusChange(b.Id(), op.Id())
case EventDescriptionChanged:
firstComment := b.Snapshot().Comments[0]
// since gitlab doesn't provide the issue history
// we should check for "changed the description" notes and compare issue texts
// TODO: Check only one time and ignore next 'description change' within one issue
cleanedDesc := text.Cleanup(issue.Description)
if errResolve == cache.ErrNoMatchingOp && cleanedDesc != firstComment.Message {
// comment edition
op, err := b.EditCommentRaw(
author,
event.(NoteEvent).UpdatedAt.Unix(),
firstComment.CombinedId(),
cleanedDesc,
map[string]string{
metaKeyGitlabId: event.ID(),
},
)
if err != nil {
return err
}
gi.out <- core.NewImportTitleEdition(b.Id(), op.Id())
}
case EventComment:
cleanText := text.Cleanup(event.(NoteEvent).Body)
// if we didn't import the comment
if errResolve == cache.ErrNoMatchingOp {
// add comment operation
commentId, _, err := b.AddCommentRaw(
author,
event.CreatedAt().Unix(),
cleanText,
nil,
map[string]string{
metaKeyGitlabId: event.ID(),
},
)
if err != nil {
return err
}
gi.out <- core.NewImportComment(b.Id(), commentId)
return nil
}
// if comment was already exported
// search for last comment update
comment, err := b.Snapshot().SearchCommentByOpId(id)
if err != nil {
return err
}
// compare local bug comment with the new event body
if comment.Message != cleanText {
// comment edition
_, err := b.EditCommentRaw(
author,
event.(NoteEvent).UpdatedAt.Unix(),
comment.CombinedId(),
cleanText,
nil,
)
if err != nil {
return err
}
gi.out <- core.NewImportCommentEdition(b.Id(), comment.CombinedId())
}
return nil
case EventTitleChanged:
// title change events are given new notes
if errResolve == nil {
return nil
}
op, err := b.SetTitleRaw(
author,
event.CreatedAt().Unix(),
event.(NoteEvent).Title(),
map[string]string{
metaKeyGitlabId: event.ID(),
},
)
if err != nil {
return err
}
gi.out <- core.NewImportTitleEdition(b.Id(), op.Id())
case EventAddLabel:
_, err = b.ForceChangeLabelsRaw(
author,
event.CreatedAt().Unix(),
[]string{event.(LabelEvent).Label.Name},
nil,
map[string]string{
metaKeyGitlabId: event.ID(),
},
)
return err
case EventRemoveLabel:
_, err = b.ForceChangeLabelsRaw(
author,
event.CreatedAt().Unix(),
nil,
[]string{event.(LabelEvent).Label.Name},
map[string]string{
metaKeyGitlabId: event.ID(),
},
)
return err
case EventAssigned,
EventUnassigned,
EventChangedMilestone,
EventRemovedMilestone,
EventChangedDuedate,
EventRemovedDuedate,
EventLocked,
EventUnlocked,
EventMentionedInIssue,
EventMentionedInMergeRequest:
return nil
default:
return fmt.Errorf("unexpected event")
}
return nil
}
func (gi *gitlabImporter) ensurePerson(repo *cache.RepoCache, id int) (*cache.IdentityCache, error) {
// Look first in the cache
i, err := repo.Identities().ResolveIdentityImmutableMetadata(metaKeyGitlabId, strconv.Itoa(id))
if err == nil {
return i, nil
}
if entity.IsErrMultipleMatch(err) {
return nil, err
}
user, _, err := gi.client.Users.GetUser(id, gitlab.GetUsersOptions{})
if err != nil {
return nil, err
}
i, err = repo.Identities().NewRaw(
user.Name,
user.PublicEmail,
user.Username,
user.AvatarURL,
nil,
map[string]string{
// because Gitlab
metaKeyGitlabId: strconv.Itoa(id),
metaKeyGitlabLogin: user.Username,
},
)
if err != nil {
return nil, err
}
gi.out <- core.NewImportIdentity(i.Id())
return i, nil
}
|