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