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