git-bug/bridge/gitlab/import.go

373 lines
8.3 KiB
Go
Raw Normal View History

2019-07-09 23:56:38 +03:00
package gitlab
import (
"context"
2019-07-17 01:06:42 +03:00
"fmt"
"strconv"
2019-07-09 23:56:38 +03:00
"time"
2019-07-17 01:06:42 +03:00
"github.com/xanzy/go-gitlab"
2019-07-09 23:56:38 +03:00
"github.com/MichaelMure/git-bug/bridge/core"
"github.com/MichaelMure/git-bug/bridge/core/auth"
2019-07-09 23:56:38 +03:00
"github.com/MichaelMure/git-bug/cache"
"github.com/MichaelMure/git-bug/entities/bug"
"github.com/MichaelMure/git-bug/entity"
2019-07-17 01:06:42 +03:00
"github.com/MichaelMure/git-bug/util/text"
2019-07-09 23:56:38 +03:00
)
// gitlabImporter implement the Importer interface
2019-07-09 23:56:38 +03:00
type gitlabImporter struct {
conf core.Configuration
// default client
client *gitlab.Client
// send only channel
out chan<- core.ImportResult
2019-07-09 23:56:38 +03:00
}
func (gi *gitlabImporter) Init(_ context.Context, repo *cache.RepoCache, conf core.Configuration) error {
2019-07-17 01:06:42 +03:00
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
}
2019-07-17 01:06:42 +03:00
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
}
2019-07-17 01:06:42 +03:00
2021-12-05 13:05:38 +03:00
issueEvents := SortedEvents(
Notes(ctx, gi.client, issue),
LabelEvents(ctx, gi.client, issue),
StateEvents(ctx, gi.client, issue),
)
2019-07-17 01:06:42 +03:00
2021-12-05 13:05:38 +03:00
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()))
}
2019-07-17 01:06:42 +03:00
}
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
2019-07-17 01:06:42 +03:00
}
}
}()
return out, nil
2019-07-09 23:56:38 +03:00
}
2019-07-17 01:06:42 +03:00
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.ResolveBugMatcher(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
}
2022-11-19 13:33:12 +03:00
if !entity.IsErrNotFound(err) {
return nil, err
}
2019-07-17 01:06:42 +03:00
// if bug was never imported, create bug
b, _, err = repo.NewBugRaw(
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],
},
)
2019-07-17 01:06:42 +03:00
if err != nil {
return nil, err
2019-07-17 01:06:42 +03:00
}
// importing a new bug
gi.out <- core.NewImportBug(b.Id())
return b, nil
2019-07-17 01:06:42 +03:00
}
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
}
2019-07-17 01:06:42 +03:00
// ensure issue author
author, err := gi.ensurePerson(repo, event.UserID())
2019-07-17 01:06:42 +03:00
if err != nil {
return err
}
switch event.Kind() {
case EventClosed:
if errResolve == nil {
return nil
}
op, err := b.CloseRaw(
2019-07-17 01:06:42 +03:00
author,
event.CreatedAt().Unix(),
2019-07-17 01:06:42 +03:00
map[string]string{
metaKeyGitlabId: event.ID(),
2019-07-17 01:06:42 +03:00
},
)
if err != nil {
return err
}
gi.out <- core.NewImportStatusChange(b.Id(), op.Id())
2019-07-17 01:06:42 +03:00
case EventReopened:
if errResolve == nil {
return nil
}
op, err := b.OpenRaw(
2019-07-17 01:06:42 +03:00
author,
event.CreatedAt().Unix(),
2019-07-17 01:06:42 +03:00
map[string]string{
metaKeyGitlabId: event.ID(),
2019-07-17 01:06:42 +03:00
},
)
if err != nil {
return err
}
gi.out <- core.NewImportStatusChange(b.Id(), op.Id())
2019-07-17 01:06:42 +03:00
case EventDescriptionChanged:
firstComment := b.Snapshot().Comments[0]
2019-07-17 01:06:42 +03:00
// 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 {
2019-07-17 01:06:42 +03:00
// comment edition
op, err := b.EditCommentRaw(
2019-07-17 01:06:42 +03:00
author,
event.(NoteEvent).UpdatedAt.Unix(),
firstComment.CombinedId(),
cleanedDesc,
2019-07-17 01:06:42 +03:00
map[string]string{
metaKeyGitlabId: event.ID(),
2019-07-17 01:06:42 +03:00
},
)
if err != nil {
return err
}
2019-07-17 01:06:42 +03:00
gi.out <- core.NewImportTitleEdition(b.Id(), op.Id())
2019-07-17 01:06:42 +03:00
}
case EventComment:
cleanText := text.Cleanup(event.(NoteEvent).Body)
2019-07-17 01:06:42 +03:00
// if we didn't import the comment
if errResolve == cache.ErrNoMatchingOp {
2019-07-17 01:06:42 +03:00
// add comment operation
commentId, _, err := b.AddCommentRaw(
2019-07-17 01:06:42 +03:00
author,
event.CreatedAt().Unix(),
2019-07-17 01:06:42 +03:00
cleanText,
nil,
map[string]string{
metaKeyGitlabId: event.ID(),
2019-07-17 01:06:42 +03:00
},
)
if err != nil {
return err
}
gi.out <- core.NewImportComment(b.Id(), commentId)
return nil
2019-07-17 01:06:42 +03:00
}
// if comment was already exported
// search for last comment update
comment, err := b.Snapshot().SearchCommentByOpId(id)
2019-07-17 01:06:42 +03:00
if err != nil {
return err
}
// compare local bug comment with the new event body
if comment.Message != cleanText {
2019-07-17 01:06:42 +03:00
// comment edition
_, err := b.EditCommentRaw(
2019-07-17 01:06:42 +03:00
author,
event.(NoteEvent).UpdatedAt.Unix(),
comment.CombinedId(),
2019-07-17 01:06:42 +03:00
cleanText,
nil,
2019-07-17 01:06:42 +03:00
)
if err != nil {
return err
}
gi.out <- core.NewImportCommentEdition(b.Id(), comment.CombinedId())
2019-07-17 01:06:42 +03:00
}
return nil
case EventTitleChanged:
// title change events are given new notes
if errResolve == nil {
return nil
}
op, err := b.SetTitleRaw(
2019-07-17 01:06:42 +03:00
author,
event.CreatedAt().Unix(),
event.(NoteEvent).Title(),
2019-07-17 01:06:42 +03:00
map[string]string{
metaKeyGitlabId: event.ID(),
2019-07-17 01:06:42 +03:00
},
)
if err != nil {
return err
}
2019-07-17 01:06:42 +03:00
gi.out <- core.NewImportTitleEdition(b.Id(), op.Id())
2019-07-17 01:06:42 +03:00
case EventAddLabel:
2019-07-17 01:06:42 +03:00
_, err = b.ForceChangeLabelsRaw(
author,
event.CreatedAt().Unix(),
[]string{event.(LabelEvent).Label.Name},
2019-07-17 01:06:42 +03:00
nil,
map[string]string{
metaKeyGitlabId: event.ID(),
2019-07-17 01:06:42 +03:00
},
)
return err
2019-07-17 01:06:42 +03:00
case EventRemoveLabel:
2019-07-17 01:06:42 +03:00
_, err = b.ForceChangeLabelsRaw(
author,
event.CreatedAt().Unix(),
2019-07-17 01:06:42 +03:00
nil,
[]string{event.(LabelEvent).Label.Name},
2019-07-17 01:06:42 +03:00
map[string]string{
metaKeyGitlabId: event.ID(),
2019-07-17 01:06:42 +03:00
},
)
return err
case EventAssigned,
EventUnassigned,
EventChangedMilestone,
EventRemovedMilestone,
EventChangedDuedate,
EventRemovedDuedate,
EventLocked,
EventUnlocked,
EventMentionedInIssue,
EventMentionedInMergeRequest:
return nil
2019-07-17 01:06:42 +03:00
default:
return fmt.Errorf("unexpected event")
2019-07-17 01:06:42 +03:00
}
return nil
2019-07-17 01:06:42 +03:00
}
func (gi *gitlabImporter) ensurePerson(repo *cache.RepoCache, id int) (*cache.IdentityCache, error) {
// Look first in the cache
i, err := repo.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{})
2019-07-17 01:06:42 +03:00
if err != nil {
return nil, err
}
i, err = repo.NewIdentityRaw(
2019-07-17 01:06:42 +03:00
user.Name,
user.PublicEmail,
user.Username,
2019-07-17 01:06:42 +03:00
user.AvatarURL,
2020-11-08 21:18:44 +03:00
nil,
2019-07-17 01:06:42 +03:00
map[string]string{
2019-07-23 20:16:52 +03:00
// because Gitlab
metaKeyGitlabId: strconv.Itoa(id),
metaKeyGitlabLogin: user.Username,
2019-07-17 01:06:42 +03:00
},
)
if err != nil {
return nil, err
}
gi.out <- core.NewImportIdentity(i.Id())
return i, nil
2019-07-17 01:06:42 +03:00
}