import.go

  1package jira
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"fmt"
  7	"net/http"
  8	"sort"
  9	"strings"
 10	"time"
 11
 12	"github.com/MichaelMure/git-bug/bridge/core"
 13	"github.com/MichaelMure/git-bug/bridge/core/auth"
 14	"github.com/MichaelMure/git-bug/cache"
 15	"github.com/MichaelMure/git-bug/entities/bug"
 16	"github.com/MichaelMure/git-bug/entities/common"
 17	"github.com/MichaelMure/git-bug/entity"
 18	"github.com/MichaelMure/git-bug/entity/dag"
 19	"github.com/MichaelMure/git-bug/util/text"
 20)
 21
 22const (
 23	defaultPageSize = 10
 24)
 25
 26// jiraImporter implement the Importer interface
 27type jiraImporter struct {
 28	conf core.Configuration
 29
 30	client *Client
 31
 32	// send only channel
 33	out chan<- core.ImportResult
 34}
 35
 36// Init .
 37func (ji *jiraImporter) Init(ctx context.Context, repo *cache.RepoCache, conf core.Configuration) error {
 38	ji.conf = conf
 39
 40	var cred auth.Credential
 41
 42	// Prioritize LoginPassword credentials to avoid a prompt
 43	creds, err := auth.List(repo,
 44		auth.WithTarget(target),
 45		auth.WithKind(auth.KindLoginPassword),
 46		auth.WithMeta(auth.MetaKeyBaseURL, conf[confKeyBaseUrl]),
 47		auth.WithMeta(auth.MetaKeyLogin, conf[confKeyDefaultLogin]),
 48	)
 49	if err != nil {
 50		return err
 51	}
 52	if len(creds) > 0 {
 53		cred = creds[0]
 54		goto end
 55	}
 56
 57	creds, err = auth.List(repo,
 58		auth.WithTarget(target),
 59		auth.WithKind(auth.KindLogin),
 60		auth.WithMeta(auth.MetaKeyBaseURL, conf[confKeyBaseUrl]),
 61		auth.WithMeta(auth.MetaKeyLogin, conf[confKeyDefaultLogin]),
 62	)
 63	if err != nil {
 64		return err
 65	}
 66	if len(creds) > 0 {
 67		cred = creds[0]
 68	}
 69
 70end:
 71	if cred == nil {
 72		return fmt.Errorf("no credential for this bridge")
 73	}
 74
 75	// TODO(josh)[da52062]: Validate token and if it is expired then prompt for
 76	// credentials and generate a new one
 77	ji.client, err = buildClient(ctx, conf[confKeyBaseUrl], conf[confKeyCredentialType], cred)
 78	return err
 79}
 80
 81// ImportAll iterate over all the configured repository issues and ensure the
 82// creation of the missing issues / timeline items / edits / label events ...
 83func (ji *jiraImporter) ImportAll(ctx context.Context, repo *cache.RepoCache, since time.Time) (<-chan core.ImportResult, error) {
 84	sinceStr := since.Format("2006-01-02 15:04")
 85	project := ji.conf[confKeyProject]
 86
 87	out := make(chan core.ImportResult)
 88	ji.out = out
 89
 90	go func() {
 91		defer close(ji.out)
 92
 93		message, err := ji.client.Search(
 94			fmt.Sprintf("project=%s AND updatedDate>\"%s\"", project, sinceStr), 0, 0)
 95		if err != nil {
 96			out <- core.NewImportError(err, "")
 97			return
 98		}
 99
100		fmt.Printf("So far so good. Have %d issues to import\n", message.Total)
101
102		jql := fmt.Sprintf("project=%s AND updatedDate>\"%s\"", project, sinceStr)
103		var searchIter *SearchIterator
104		for searchIter =
105			ji.client.IterSearch(jql, defaultPageSize); searchIter.HasNext(); {
106			issue := searchIter.Next()
107			b, err := ji.ensureIssue(repo, *issue)
108			if err != nil {
109				err := fmt.Errorf("issue creation: %v", err)
110				out <- core.NewImportError(err, "")
111				return
112			}
113
114			var commentIter *CommentIterator
115			for commentIter =
116				ji.client.IterComments(issue.ID, defaultPageSize); commentIter.HasNext(); {
117				comment := commentIter.Next()
118				err := ji.ensureComment(repo, b, *comment)
119				if err != nil {
120					out <- core.NewImportError(err, "")
121				}
122			}
123			if commentIter.HasError() {
124				out <- core.NewImportError(commentIter.Err, "")
125			}
126
127			snapshot := b.Compile()
128			opIdx := 0
129
130			var changelogIter *ChangeLogIterator
131			for changelogIter =
132				ji.client.IterChangeLog(issue.ID, defaultPageSize); changelogIter.HasNext(); {
133				changelogEntry := changelogIter.Next()
134
135				// Advance the operation iterator up to the first operation which has
136				// an export date not before the changelog entry date. If the changelog
137				// entry was created in response to an exported operation, then this
138				// will be that operation.
139				var exportTime time.Time
140				for ; opIdx < len(snapshot.Operations); opIdx++ {
141					exportTimeStr, hasTime := snapshot.Operations[opIdx].GetMetadata(
142						metaKeyJiraExportTime)
143					if !hasTime {
144						continue
145					}
146					exportTime, err = http.ParseTime(exportTimeStr)
147					if err != nil {
148						continue
149					}
150					if !exportTime.Before(changelogEntry.Created.Time) {
151						break
152					}
153				}
154				if opIdx < len(snapshot.Operations) {
155					err = ji.ensureChange(repo, b, *changelogEntry, snapshot.Operations[opIdx])
156				} else {
157					err = ji.ensureChange(repo, b, *changelogEntry, nil)
158				}
159				if err != nil {
160					out <- core.NewImportError(err, "")
161				}
162
163			}
164			if changelogIter.HasError() {
165				out <- core.NewImportError(changelogIter.Err, "")
166			}
167
168			if !b.NeedCommit() {
169				out <- core.NewImportNothing(b.Id(), "no imported operation")
170			} else if err := b.Commit(); err != nil {
171				err = fmt.Errorf("bug commit: %v", err)
172				out <- core.NewImportError(err, "")
173				return
174			}
175		}
176		if searchIter.HasError() {
177			out <- core.NewImportError(searchIter.Err, "")
178		}
179	}()
180
181	return out, nil
182}
183
184// Create a bug.Person from a JIRA user
185func (ji *jiraImporter) ensurePerson(repo *cache.RepoCache, user User) (*cache.IdentityCache, error) {
186	// Look first in the cache
187	i, err := repo.Identities().ResolveIdentityImmutableMetadata(
188		metaKeyJiraUser, string(user.Key))
189	if err == nil {
190		return i, nil
191	}
192	if _, ok := err.(entity.ErrMultipleMatch); ok {
193		return nil, err
194	}
195
196	i, err = repo.Identities().NewRaw(
197		user.DisplayName,
198		user.EmailAddress,
199		user.Key,
200		"",
201		nil,
202		map[string]string{
203			metaKeyJiraUser: user.Key,
204		},
205	)
206
207	if err != nil {
208		return nil, err
209	}
210
211	ji.out <- core.NewImportIdentity(i.Id())
212	return i, nil
213}
214
215// Create a bug.Bug based from a JIRA issue
216func (ji *jiraImporter) ensureIssue(repo *cache.RepoCache, issue Issue) (*cache.BugCache, error) {
217	author, err := ji.ensurePerson(repo, issue.Fields.Creator)
218	if err != nil {
219		return nil, err
220	}
221
222	b, err := repo.Bugs().ResolveMatcher(func(excerpt *cache.BugExcerpt) bool {
223		if _, ok := excerpt.CreateMetadata[metaKeyJiraBaseUrl]; ok &&
224			excerpt.CreateMetadata[metaKeyJiraBaseUrl] != ji.conf[confKeyBaseUrl] {
225			return false
226		}
227
228		return excerpt.CreateMetadata[core.MetaKeyOrigin] == target &&
229			excerpt.CreateMetadata[metaKeyJiraId] == issue.ID &&
230			excerpt.CreateMetadata[metaKeyJiraProject] == ji.conf[confKeyProject]
231	})
232	if err != nil && !entity.IsErrNotFound(err) {
233		return nil, err
234	}
235
236	if entity.IsErrNotFound(err) {
237		b, _, err = repo.Bugs().NewRaw(
238			author,
239			issue.Fields.Created.Unix(),
240			text.CleanupOneLine(issue.Fields.Summary),
241			text.Cleanup(issue.Fields.Description),
242			nil,
243			map[string]string{
244				core.MetaKeyOrigin: target,
245				metaKeyJiraId:      issue.ID,
246				metaKeyJiraKey:     issue.Key,
247				metaKeyJiraProject: ji.conf[confKeyProject],
248				metaKeyJiraBaseUrl: ji.conf[confKeyBaseUrl],
249			})
250		if err != nil {
251			return nil, err
252		}
253
254		ji.out <- core.NewImportBug(b.Id())
255	}
256
257	return b, nil
258}
259
260// Return a unique string derived from a unique jira id and a timestamp
261func getTimeDerivedID(jiraID string, timestamp Time) string {
262	return fmt.Sprintf("%s-%d", jiraID, timestamp.Unix())
263}
264
265// Create a bug.Comment from a JIRA comment
266func (ji *jiraImporter) ensureComment(repo *cache.RepoCache, b *cache.BugCache, item Comment) error {
267	// ensure person
268	author, err := ji.ensurePerson(repo, item.Author)
269	if err != nil {
270		return err
271	}
272
273	targetOpID, err := b.ResolveOperationWithMetadata(metaKeyJiraId, item.ID)
274	if err != nil && err != cache.ErrNoMatchingOp {
275		return err
276	}
277
278	// If the comment is a new comment then create it
279	if targetOpID == "" && err == cache.ErrNoMatchingOp {
280		var cleanText string
281		if item.Updated != item.Created {
282			// We don't know the original text... we only have the updated text.
283			cleanText = ""
284		} else {
285			cleanText = text.Cleanup(item.Body)
286		}
287
288		// add comment operation
289		commentId, op, err := b.AddCommentRaw(
290			author,
291			item.Created.Unix(),
292			cleanText,
293			nil,
294			map[string]string{
295				metaKeyJiraId: item.ID,
296			},
297		)
298		if err != nil {
299			return err
300		}
301
302		ji.out <- core.NewImportComment(b.Id(), commentId)
303		targetOpID = op.Id()
304	}
305
306	// If there are no updates to this comment, then we are done
307	if item.Updated == item.Created {
308		return nil
309	}
310
311	// If there has been an update to this comment, we try to find it in the
312	// database. We need a unique id so we'll concat the issue id with the update
313	// timestamp. Note that this must be consistent with the exporter during
314	// export of an EditCommentOperation
315	derivedID := getTimeDerivedID(item.ID, item.Updated)
316	_, err = b.ResolveOperationWithMetadata(metaKeyJiraId, derivedID)
317	if err == nil {
318		// Already imported this edition
319		return nil
320	}
321
322	if err != cache.ErrNoMatchingOp {
323		return err
324	}
325
326	// ensure editor identity
327	editor, err := ji.ensurePerson(repo, item.UpdateAuthor)
328	if err != nil {
329		return err
330	}
331
332	commentId := entity.CombineIds(b.Id(), targetOpID)
333
334	// comment edition
335	_, err = b.EditCommentRaw(
336		editor,
337		item.Updated.Unix(),
338		commentId,
339		text.Cleanup(item.Body),
340		map[string]string{
341			metaKeyJiraId: derivedID,
342		},
343	)
344
345	if err != nil {
346		return err
347	}
348
349	ji.out <- core.NewImportCommentEdition(b.Id(), commentId)
350
351	return nil
352}
353
354// Return a unique string derived from a unique jira id and an index into the
355// data referred to by that jira id.
356func getIndexDerivedID(jiraID string, idx int) string {
357	return fmt.Sprintf("%s-%d", jiraID, idx)
358}
359
360func labelSetsMatch(jiraSet []string, gitbugSet []bug.Label) bool {
361	if len(jiraSet) != len(gitbugSet) {
362		return false
363	}
364
365	sort.Strings(jiraSet)
366	gitbugStrSet := make([]string, len(gitbugSet))
367	for idx, label := range gitbugSet {
368		gitbugStrSet[idx] = label.String()
369	}
370	sort.Strings(gitbugStrSet)
371
372	for idx, value := range jiraSet {
373		if value != gitbugStrSet[idx] {
374			return false
375		}
376	}
377
378	return true
379}
380
381// Create a bug.Operation (or a series of operations) from a JIRA changelog
382// entry
383func (ji *jiraImporter) ensureChange(repo *cache.RepoCache, b *cache.BugCache, entry ChangeLogEntry, potentialOp dag.Operation) error {
384
385	// If we have an operation which is already mapped to the entire changelog
386	// entry then that means this changelog entry was induced by an export
387	// operation and we've already done the match, so we skip this one
388	_, err := b.ResolveOperationWithMetadata(metaKeyJiraDerivedId, entry.ID)
389	if err == nil {
390		return nil
391	} else if err != cache.ErrNoMatchingOp {
392		return err
393	}
394
395	// In general, multiple fields may be changed in changelog entry  on
396	// JIRA. For example, when an issue is closed both its "status" and its
397	// "resolution" are updated within a single changelog entry.
398	// I don't thing git-bug has a single operation to modify an arbitrary
399	// number of fields in one go, so we break up the single JIRA changelog
400	// entry into individual field updates.
401	author, err := ji.ensurePerson(repo, entry.Author)
402	if err != nil {
403		return err
404	}
405
406	if len(entry.Items) < 1 {
407		return fmt.Errorf("Received changelog entry with no item! (%s)", entry.ID)
408	}
409
410	statusMap, err := getStatusMapReverse(ji.conf)
411	if err != nil {
412		return err
413	}
414
415	// NOTE(josh): first do an initial scan and see if any of the changed items
416	// matches the current potential operation. If it does, then we know that this
417	// entire changelog entry was created in response to that git-bug operation.
418	// So we associate the operation with the entire changelog, and not a specific
419	// entry.
420	for _, item := range entry.Items {
421		switch item.Field {
422		case "labels":
423			fromLabels := removeEmpty(strings.Split(item.FromString, " "))
424			toLabels := removeEmpty(strings.Split(item.ToString, " "))
425			removedLabels, addedLabels, _ := setSymmetricDifference(fromLabels, toLabels)
426
427			opr, isRightType := potentialOp.(*bug.LabelChangeOperation)
428			if isRightType && labelSetsMatch(addedLabels, opr.Added) && labelSetsMatch(removedLabels, opr.Removed) {
429				_, err := b.SetMetadata(opr.Id(), map[string]string{
430					metaKeyJiraDerivedId: entry.ID,
431				})
432				if err != nil {
433					return err
434				}
435				return nil
436			}
437
438		case "status":
439			opr, isRightType := potentialOp.(*bug.SetStatusOperation)
440			if isRightType && statusMap[opr.Status.String()] == item.To {
441				_, err := b.SetMetadata(opr.Id(), map[string]string{
442					metaKeyJiraDerivedId: entry.ID,
443				})
444				if err != nil {
445					return err
446				}
447				return nil
448			}
449
450		case "summary":
451			// NOTE(josh): JIRA calls it "summary", which sounds more like the body
452			// text, but it's the title
453			opr, isRightType := potentialOp.(*bug.SetTitleOperation)
454			if isRightType && opr.Title == item.To {
455				_, err := b.SetMetadata(opr.Id(), map[string]string{
456					metaKeyJiraDerivedId: entry.ID,
457				})
458				if err != nil {
459					return err
460				}
461				return nil
462			}
463
464		case "description":
465			// NOTE(josh): JIRA calls it "description", which sounds more like the
466			// title but it's actually the body
467			opr, isRightType := potentialOp.(*bug.EditCommentOperation)
468			if isRightType &&
469				opr.Target == b.Compile().Operations[0].Id() &&
470				opr.Message == item.ToString {
471				_, err := b.SetMetadata(opr.Id(), map[string]string{
472					metaKeyJiraDerivedId: entry.ID,
473				})
474				if err != nil {
475					return err
476				}
477				return nil
478			}
479		}
480	}
481
482	// Since we didn't match the changelog entry to a known export operation,
483	// then this is a changelog entry that we should import. We import each
484	// changelog entry item as a separate git-bug operation.
485	for idx, item := range entry.Items {
486		derivedID := getIndexDerivedID(entry.ID, idx)
487		_, err := b.ResolveOperationWithMetadata(metaKeyJiraDerivedId, derivedID)
488		if err == nil {
489			continue
490		}
491		if err != cache.ErrNoMatchingOp {
492			return err
493		}
494
495		switch item.Field {
496		case "labels":
497			fromLabels := removeEmpty(strings.Split(item.FromString, " "))
498			toLabels := removeEmpty(strings.Split(item.ToString, " "))
499			removedLabels, addedLabels, _ := setSymmetricDifference(fromLabels, toLabels)
500
501			op, err := b.ForceChangeLabelsRaw(
502				author,
503				entry.Created.Unix(),
504				text.CleanupOneLineArray(addedLabels),
505				text.CleanupOneLineArray(removedLabels),
506				map[string]string{
507					metaKeyJiraId:        entry.ID,
508					metaKeyJiraDerivedId: derivedID,
509				},
510			)
511			if err != nil {
512				return err
513			}
514
515			ji.out <- core.NewImportLabelChange(b.Id(), op.Id())
516
517		case "status":
518			statusStr, hasMap := statusMap[item.To]
519			if hasMap {
520				switch statusStr {
521				case common.OpenStatus.String():
522					op, err := b.OpenRaw(
523						author,
524						entry.Created.Unix(),
525						map[string]string{
526							metaKeyJiraId:        entry.ID,
527							metaKeyJiraDerivedId: derivedID,
528						},
529					)
530					if err != nil {
531						return err
532					}
533					ji.out <- core.NewImportStatusChange(b.Id(), op.Id())
534
535				case common.ClosedStatus.String():
536					op, err := b.CloseRaw(
537						author,
538						entry.Created.Unix(),
539						map[string]string{
540							metaKeyJiraId:        entry.ID,
541							metaKeyJiraDerivedId: derivedID,
542						},
543					)
544					if err != nil {
545						return err
546					}
547					ji.out <- core.NewImportStatusChange(b.Id(), op.Id())
548				}
549			} else {
550				ji.out <- core.NewImportError(
551					fmt.Errorf(
552						"No git-bug status mapped for jira status %s (%s)",
553						item.ToString, item.To), "")
554			}
555
556		case "summary":
557			// NOTE(josh): JIRA calls it "summary", which sounds more like the body
558			// text, but it's the title
559			op, err := b.SetTitleRaw(
560				author,
561				entry.Created.Unix(),
562				text.CleanupOneLine(item.ToString),
563				map[string]string{
564					metaKeyJiraId:        entry.ID,
565					metaKeyJiraDerivedId: derivedID,
566				},
567			)
568			if err != nil {
569				return err
570			}
571
572			ji.out <- core.NewImportTitleEdition(b.Id(), op.Id())
573
574		case "description":
575			// NOTE(josh): JIRA calls it "description", which sounds more like the
576			// title but it's actually the body
577			commentId, _, err := b.EditCreateCommentRaw(
578				author,
579				entry.Created.Unix(),
580				text.Cleanup(item.ToString),
581				map[string]string{
582					metaKeyJiraId:        entry.ID,
583					metaKeyJiraDerivedId: derivedID,
584				},
585			)
586			if err != nil {
587				return err
588			}
589
590			ji.out <- core.NewImportCommentEdition(b.Id(), commentId)
591
592		default:
593			ji.out <- core.NewImportWarning(
594				fmt.Errorf(
595					"Unhandled changelog event %s", item.Field), "")
596		}
597
598		// Other Examples:
599		// "assignee" (jira)
600		// "Attachment" (jira)
601		// "Epic Link" (custom)
602		// "Rank" (custom)
603		// "resolution" (jira)
604		// "Sprint" (custom)
605	}
606	return nil
607}
608
609func getStatusMap(conf core.Configuration) (map[string]string, error) {
610	mapStr, hasConf := conf[confKeyIDMap]
611	if !hasConf {
612		return map[string]string{
613			common.OpenStatus.String():   "1",
614			common.ClosedStatus.String(): "6",
615		}, nil
616	}
617
618	statusMap := make(map[string]string)
619	err := json.Unmarshal([]byte(mapStr), &statusMap)
620	return statusMap, err
621}
622
623func getStatusMapReverse(conf core.Configuration) (map[string]string, error) {
624	fwdMap, err := getStatusMap(conf)
625	if err != nil {
626		return fwdMap, err
627	}
628
629	outMap := map[string]string{}
630	for key, val := range fwdMap {
631		outMap[val] = key
632	}
633
634	mapStr, hasConf := conf[confKeyIDRevMap]
635	if !hasConf {
636		return outMap, nil
637	}
638
639	revMap := make(map[string]string)
640	err = json.Unmarshal([]byte(mapStr), &revMap)
641	for key, val := range revMap {
642		outMap[key] = val
643	}
644
645	return outMap, err
646}
647
648func removeEmpty(values []string) []string {
649	output := make([]string, 0, len(values))
650	for _, value := range values {
651		value = strings.TrimSpace(value)
652		if value != "" {
653			output = append(output, value)
654		}
655	}
656	return output
657}