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