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