export.go

  1package github
  2
  3import (
  4	"bytes"
  5	"context"
  6	"encoding/json"
  7	"fmt"
  8	"io/ioutil"
  9	"net/http"
 10	"os"
 11	"strings"
 12	"time"
 13
 14	"github.com/pkg/errors"
 15	"github.com/shurcooL/githubv4"
 16	"golang.org/x/sync/errgroup"
 17
 18	"github.com/MichaelMure/git-bug/bridge/core"
 19	"github.com/MichaelMure/git-bug/bridge/core/auth"
 20	"github.com/MichaelMure/git-bug/bug"
 21	"github.com/MichaelMure/git-bug/cache"
 22	"github.com/MichaelMure/git-bug/entity"
 23	"github.com/MichaelMure/git-bug/identity"
 24)
 25
 26var (
 27	ErrMissingIdentityToken = errors.New("missing identity token")
 28)
 29
 30// githubExporter implement the Exporter interface
 31type githubExporter struct {
 32	conf core.Configuration
 33
 34	// cache identities clients
 35	identityClient map[entity.Id]*githubv4.Client
 36
 37	// the client to use for non user-specific queries
 38	// should be the client of the default user
 39	defaultClient *githubv4.Client
 40
 41	// the token of the default user
 42	defaultToken *auth.Token
 43
 44	// github repository ID
 45	repositoryID string
 46
 47	// cache identifiers used to speed up exporting operations
 48	// cleared for each bug
 49	cachedOperationIDs map[entity.Id]string
 50
 51	// cache labels used to speed up exporting labels events
 52	cachedLabels map[string]string
 53}
 54
 55// Init .
 56func (ge *githubExporter) Init(repo *cache.RepoCache, conf core.Configuration) error {
 57	ge.conf = conf
 58	ge.identityClient = make(map[entity.Id]*githubv4.Client)
 59	ge.cachedOperationIDs = make(map[entity.Id]string)
 60	ge.cachedLabels = make(map[string]string)
 61
 62	user, err := repo.GetUserIdentity()
 63	if err != nil {
 64		return err
 65	}
 66
 67	// preload all clients
 68	err = ge.cacheAllClient(repo)
 69	if err != nil {
 70		return err
 71	}
 72
 73	ge.defaultClient, err = ge.getClientForIdentity(user.Id())
 74	if err != nil {
 75		return err
 76	}
 77
 78	login := user.ImmutableMetadata()[metaKeyGithubLogin]
 79	creds, err := auth.List(repo, auth.WithMeta(metaKeyGithubLogin, login), auth.WithTarget(target), auth.WithKind(auth.KindToken))
 80	if err != nil {
 81		return err
 82	}
 83
 84	if len(creds) == 0 {
 85		return ErrMissingIdentityToken
 86	}
 87
 88	ge.defaultToken = creds[0].(*auth.Token)
 89
 90	return nil
 91}
 92
 93func (ge *githubExporter) cacheAllClient(repo *cache.RepoCache) error {
 94	creds, err := auth.List(repo, auth.WithTarget(target), auth.WithKind(auth.KindToken))
 95	if err != nil {
 96		return err
 97	}
 98
 99	for _, cred := range creds {
100		login, ok := cred.GetMetadata(auth.MetaKeyLogin)
101		if !ok {
102			_, _ = fmt.Fprintf(os.Stderr, "credential %s is not tagged with a Github login\n", cred.ID().Human())
103			continue
104		}
105
106		user, err := repo.ResolveIdentityImmutableMetadata(metaKeyGithubLogin, login)
107		if err == identity.ErrIdentityNotExist {
108			continue
109		}
110		if err != nil {
111			return nil
112		}
113
114		if _, ok := ge.identityClient[user.Id()]; !ok {
115			client := buildClient(creds[0].(*auth.Token))
116			ge.identityClient[user.Id()] = client
117		}
118	}
119
120	return nil
121}
122
123// getClientForIdentity return a githubv4 API client configured with the access token of the given identity.
124func (ge *githubExporter) getClientForIdentity(userId entity.Id) (*githubv4.Client, error) {
125	client, ok := ge.identityClient[userId]
126	if ok {
127		return client, nil
128	}
129
130	return nil, ErrMissingIdentityToken
131}
132
133// ExportAll export all event made by the current user to Github
134func (ge *githubExporter) ExportAll(ctx context.Context, repo *cache.RepoCache, since time.Time) (<-chan core.ExportResult, error) {
135	out := make(chan core.ExportResult)
136
137	var err error
138	// get repository node id
139	ge.repositoryID, err = getRepositoryNodeID(
140		ctx,
141		ge.defaultToken,
142		ge.conf[keyOwner],
143		ge.conf[keyProject],
144	)
145	if err != nil {
146		return nil, err
147	}
148
149	// query all labels
150	err = ge.cacheGithubLabels(ctx, ge.defaultClient)
151	if err != nil {
152		return nil, err
153	}
154
155	go func() {
156		defer close(out)
157
158		allIdentitiesIds := make([]entity.Id, 0, len(ge.identityClient))
159		for id := range ge.identityClient {
160			allIdentitiesIds = append(allIdentitiesIds, id)
161		}
162
163		allBugsIds := repo.AllBugsIds()
164
165		for _, id := range allBugsIds {
166			b, err := repo.ResolveBug(id)
167			if err != nil {
168				out <- core.NewExportError(errors.Wrap(err, "can't load bug"), id)
169				return
170			}
171
172			select {
173
174			case <-ctx.Done():
175				// stop iterating if context cancel function is called
176				return
177
178			default:
179				snapshot := b.Snapshot()
180
181				// ignore issues created before since date
182				// TODO: compare the Lamport time instead of using the unix time
183				if snapshot.CreatedAt.Before(since) {
184					out <- core.NewExportNothing(b.Id(), "bug created before the since date")
185					continue
186				}
187
188				if snapshot.HasAnyActor(allIdentitiesIds...) {
189					// try to export the bug and it associated events
190					ge.exportBug(ctx, b, since, out)
191				}
192			}
193		}
194	}()
195
196	return out, nil
197}
198
199// exportBug publish bugs and related events
200func (ge *githubExporter) exportBug(ctx context.Context, b *cache.BugCache, since time.Time, out chan<- core.ExportResult) {
201	snapshot := b.Snapshot()
202	var bugUpdated bool
203
204	var bugGithubID string
205	var bugGithubURL string
206
207	// Special case:
208	// if a user try to export a bug that is not already exported to Github (or imported
209	// from Github) and we do not have the token of the bug author, there is nothing we can do.
210
211	// first operation is always createOp
212	createOp := snapshot.Operations[0].(*bug.CreateOperation)
213	author := snapshot.Author
214
215	// skip bug if origin is not allowed
216	origin, ok := snapshot.GetCreateMetadata(core.MetaKeyOrigin)
217	if ok && origin != target {
218		out <- core.NewExportNothing(b.Id(), fmt.Sprintf("issue tagged with origin: %s", origin))
219		return
220	}
221
222	// get github bug ID
223	githubID, ok := snapshot.GetCreateMetadata(metaKeyGithubId)
224	if ok {
225		githubURL, ok := snapshot.GetCreateMetadata(metaKeyGithubUrl)
226		if !ok {
227			// if we find github ID, github URL must be found too
228			err := fmt.Errorf("incomplete Github metadata: expected to find issue URL")
229			out <- core.NewExportError(err, b.Id())
230		}
231
232		// extract owner and project
233		owner, project, err := splitURL(githubURL)
234		if err != nil {
235			err := fmt.Errorf("bad project url: %v", err)
236			out <- core.NewExportError(err, b.Id())
237			return
238		}
239
240		// ignore issue coming from other repositories
241		if owner != ge.conf[keyOwner] && project != ge.conf[keyProject] {
242			out <- core.NewExportNothing(b.Id(), fmt.Sprintf("skipping issue from url:%s", githubURL))
243			return
244		}
245
246		// will be used to mark operation related to a bug as exported
247		bugGithubID = githubID
248		bugGithubURL = githubURL
249
250	} else {
251		// check that we have a token for operation author
252		client, err := ge.getClientForIdentity(author.Id())
253		if err != nil {
254			// if bug is still not exported and we do not have the author stop the execution
255			out <- core.NewExportNothing(b.Id(), fmt.Sprintf("missing author token"))
256			return
257		}
258
259		// create bug
260		id, url, err := createGithubIssue(ctx, client, ge.repositoryID, createOp.Title, createOp.Message)
261		if err != nil {
262			err := errors.Wrap(err, "exporting github issue")
263			out <- core.NewExportError(err, b.Id())
264			return
265		}
266
267		out <- core.NewExportBug(b.Id())
268
269		// mark bug creation operation as exported
270		if err := markOperationAsExported(b, createOp.Id(), id, url); err != nil {
271			err := errors.Wrap(err, "marking operation as exported")
272			out <- core.NewExportError(err, b.Id())
273			return
274		}
275
276		// commit operation to avoid creating multiple issues with multiple pushes
277		if err := b.CommitAsNeeded(); err != nil {
278			err := errors.Wrap(err, "bug commit")
279			out <- core.NewExportError(err, b.Id())
280			return
281		}
282
283		// cache bug github ID and URL
284		bugGithubID = id
285		bugGithubURL = url
286	}
287
288	// cache operation github id
289	ge.cachedOperationIDs[createOp.Id()] = bugGithubID
290
291	for _, op := range snapshot.Operations[1:] {
292		// ignore SetMetadata operations
293		if _, ok := op.(*bug.SetMetadataOperation); ok {
294			continue
295		}
296
297		// ignore operations already existing in github (due to import or export)
298		// cache the ID of already exported or imported issues and events from Github
299		if id, ok := op.GetMetadata(metaKeyGithubId); ok {
300			ge.cachedOperationIDs[op.Id()] = id
301			continue
302		}
303
304		opAuthor := op.GetAuthor()
305		client, err := ge.getClientForIdentity(opAuthor.Id())
306		if err != nil {
307			continue
308		}
309
310		var id, url string
311		switch op := op.(type) {
312		case *bug.AddCommentOperation:
313			// send operation to github
314			id, url, err = addCommentGithubIssue(ctx, client, bugGithubID, op.Message)
315			if err != nil {
316				err := errors.Wrap(err, "adding comment")
317				out <- core.NewExportError(err, b.Id())
318				return
319			}
320
321			out <- core.NewExportComment(op.Id())
322
323			// cache comment id
324			ge.cachedOperationIDs[op.Id()] = id
325
326		case *bug.EditCommentOperation:
327			// Since github doesn't consider the issue body as a comment
328			if op.Target == createOp.Id() {
329
330				// case bug creation operation: we need to edit the Github issue
331				if err := updateGithubIssueBody(ctx, client, bugGithubID, op.Message); err != nil {
332					err := errors.Wrap(err, "editing issue")
333					out <- core.NewExportError(err, b.Id())
334					return
335				}
336
337				out <- core.NewExportCommentEdition(op.Id())
338
339				id = bugGithubID
340				url = bugGithubURL
341
342			} else {
343
344				// case comment edition operation: we need to edit the Github comment
345				commentID, ok := ge.cachedOperationIDs[op.Target]
346				if !ok {
347					panic("unexpected error: comment id not found")
348				}
349
350				eid, eurl, err := editCommentGithubIssue(ctx, client, commentID, op.Message)
351				if err != nil {
352					err := errors.Wrap(err, "editing comment")
353					out <- core.NewExportError(err, b.Id())
354					return
355				}
356
357				out <- core.NewExportCommentEdition(op.Id())
358
359				// use comment id/url instead of issue id/url
360				id = eid
361				url = eurl
362			}
363
364		case *bug.SetStatusOperation:
365			if err := updateGithubIssueStatus(ctx, client, bugGithubID, op.Status); err != nil {
366				err := errors.Wrap(err, "editing status")
367				out <- core.NewExportError(err, b.Id())
368				return
369			}
370
371			out <- core.NewExportStatusChange(op.Id())
372
373			id = bugGithubID
374			url = bugGithubURL
375
376		case *bug.SetTitleOperation:
377			if err := updateGithubIssueTitle(ctx, client, bugGithubID, op.Title); err != nil {
378				err := errors.Wrap(err, "editing title")
379				out <- core.NewExportError(err, b.Id())
380				return
381			}
382
383			out <- core.NewExportTitleEdition(op.Id())
384
385			id = bugGithubID
386			url = bugGithubURL
387
388		case *bug.LabelChangeOperation:
389			if err := ge.updateGithubIssueLabels(ctx, client, bugGithubID, op.Added, op.Removed); err != nil {
390				err := errors.Wrap(err, "updating labels")
391				out <- core.NewExportError(err, b.Id())
392				return
393			}
394
395			out <- core.NewExportLabelChange(op.Id())
396
397			id = bugGithubID
398			url = bugGithubURL
399
400		default:
401			panic("unhandled operation type case")
402		}
403
404		// mark operation as exported
405		if err := markOperationAsExported(b, op.Id(), id, url); err != nil {
406			err := errors.Wrap(err, "marking operation as exported")
407			out <- core.NewExportError(err, b.Id())
408			return
409		}
410
411		// commit at each operation export to avoid exporting same events multiple times
412		if err := b.CommitAsNeeded(); err != nil {
413			err := errors.Wrap(err, "bug commit")
414			out <- core.NewExportError(err, b.Id())
415			return
416		}
417
418		bugUpdated = true
419	}
420
421	if !bugUpdated {
422		out <- core.NewExportNothing(b.Id(), "nothing has been exported")
423	}
424}
425
426// getRepositoryNodeID request github api v3 to get repository node id
427func getRepositoryNodeID(ctx context.Context, token *auth.Token, owner, project string) (string, error) {
428	url := fmt.Sprintf("%s/repos/%s/%s", githubV3Url, owner, project)
429	client := &http.Client{}
430
431	req, err := http.NewRequest("GET", url, nil)
432	if err != nil {
433		return "", err
434	}
435
436	// need the token for private repositories
437	req.Header.Set("Authorization", fmt.Sprintf("token %s", token.Value))
438
439	ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
440	defer cancel()
441	req = req.WithContext(ctx)
442
443	resp, err := client.Do(req)
444	if err != nil {
445		return "", err
446	}
447
448	if resp.StatusCode != http.StatusOK {
449		return "", fmt.Errorf("HTTP error %v retrieving repository node id", resp.StatusCode)
450	}
451
452	aux := struct {
453		NodeID string `json:"node_id"`
454	}{}
455
456	data, _ := ioutil.ReadAll(resp.Body)
457	err = resp.Body.Close()
458	if err != nil {
459		return "", err
460	}
461
462	err = json.Unmarshal(data, &aux)
463	if err != nil {
464		return "", err
465	}
466
467	return aux.NodeID, nil
468}
469
470func markOperationAsExported(b *cache.BugCache, target entity.Id, githubID, githubURL string) error {
471	_, err := b.SetMetadata(
472		target,
473		map[string]string{
474			metaKeyGithubId:  githubID,
475			metaKeyGithubUrl: githubURL,
476		},
477	)
478
479	return err
480}
481
482func (ge *githubExporter) cacheGithubLabels(ctx context.Context, gc *githubv4.Client) error {
483	variables := map[string]interface{}{
484		"owner": githubv4.String(ge.conf[keyOwner]),
485		"name":  githubv4.String(ge.conf[keyProject]),
486		"first": githubv4.Int(10),
487		"after": (*githubv4.String)(nil),
488	}
489
490	q := labelsQuery{}
491
492	hasNextPage := true
493	for hasNextPage {
494		// create a new timeout context at each iteration
495		ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
496
497		if err := gc.Query(ctx, &q, variables); err != nil {
498			cancel()
499			return err
500		}
501		cancel()
502
503		for _, label := range q.Repository.Labels.Nodes {
504			ge.cachedLabels[label.Name] = label.ID
505		}
506
507		hasNextPage = q.Repository.Labels.PageInfo.HasNextPage
508		variables["after"] = q.Repository.Labels.PageInfo.EndCursor
509	}
510
511	return nil
512}
513
514func (ge *githubExporter) getLabelID(gc *githubv4.Client, label string) (string, error) {
515	label = strings.ToLower(label)
516	for cachedLabel, ID := range ge.cachedLabels {
517		if label == strings.ToLower(cachedLabel) {
518			return ID, nil
519		}
520	}
521
522	return "", fmt.Errorf("didn't find label id in cache")
523}
524
525// create a new label and return it github id
526// NOTE: since createLabel mutation is still in preview mode we use github api v3 to create labels
527// see https://developer.github.com/v4/mutation/createlabel/ and https://developer.github.com/v4/previews/#labels-preview
528func (ge *githubExporter) createGithubLabel(ctx context.Context, label, color string) (string, error) {
529	url := fmt.Sprintf("%s/repos/%s/%s/labels", githubV3Url, ge.conf[keyOwner], ge.conf[keyProject])
530	client := &http.Client{}
531
532	params := struct {
533		Name        string `json:"name"`
534		Color       string `json:"color"`
535		Description string `json:"description"`
536	}{
537		Name:  label,
538		Color: color,
539	}
540
541	data, err := json.Marshal(params)
542	if err != nil {
543		return "", err
544	}
545
546	req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
547	if err != nil {
548		return "", err
549	}
550
551	ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
552	defer cancel()
553	req = req.WithContext(ctx)
554
555	// need the token for private repositories
556	req.Header.Set("Authorization", fmt.Sprintf("token %s", ge.defaultToken.Value))
557
558	resp, err := client.Do(req)
559	if err != nil {
560		return "", err
561	}
562
563	if resp.StatusCode != http.StatusCreated {
564		return "", fmt.Errorf("error creating label: response status %v", resp.StatusCode)
565	}
566
567	aux := struct {
568		ID     int    `json:"id"`
569		NodeID string `json:"node_id"`
570		Color  string `json:"color"`
571	}{}
572
573	data, _ = ioutil.ReadAll(resp.Body)
574	defer resp.Body.Close()
575
576	err = json.Unmarshal(data, &aux)
577	if err != nil {
578		return "", err
579	}
580
581	return aux.NodeID, nil
582}
583
584/**
585// create github label using api v4
586func (ge *githubExporter) createGithubLabelV4(gc *githubv4.Client, label, labelColor string) (string, error) {
587	m := createLabelMutation{}
588	input := createLabelInput{
589		RepositoryID: ge.repositoryID,
590		Name:         githubv4.String(label),
591		Color:        githubv4.String(labelColor),
592	}
593
594	parentCtx := context.Background()
595	ctx, cancel := context.WithTimeout(parentCtx, defaultTimeout)
596	defer cancel()
597
598	if err := gc.Mutate(ctx, &m, input, nil); err != nil {
599		return "", err
600	}
601
602	return m.CreateLabel.Label.ID, nil
603}
604*/
605
606func (ge *githubExporter) getOrCreateGithubLabelID(ctx context.Context, gc *githubv4.Client, repositoryID string, label bug.Label) (string, error) {
607	// try to get label id from cache
608	labelID, err := ge.getLabelID(gc, string(label))
609	if err == nil {
610		return labelID, nil
611	}
612
613	// RGBA to hex color
614	rgba := label.Color().RGBA()
615	hexColor := fmt.Sprintf("%.2x%.2x%.2x", rgba.R, rgba.G, rgba.B)
616
617	ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
618	defer cancel()
619
620	labelID, err = ge.createGithubLabel(ctx, string(label), hexColor)
621	if err != nil {
622		return "", err
623	}
624
625	return labelID, nil
626}
627
628func (ge *githubExporter) getLabelsIDs(ctx context.Context, gc *githubv4.Client, repositoryID string, labels []bug.Label) ([]githubv4.ID, error) {
629	ids := make([]githubv4.ID, 0, len(labels))
630	var err error
631
632	// check labels ids
633	for _, label := range labels {
634		id, ok := ge.cachedLabels[string(label)]
635		if !ok {
636			// try to query label id
637			id, err = ge.getOrCreateGithubLabelID(ctx, gc, repositoryID, label)
638			if err != nil {
639				return nil, errors.Wrap(err, "get or create github label")
640			}
641
642			// cache label id
643			ge.cachedLabels[string(label)] = id
644		}
645
646		ids = append(ids, githubv4.ID(id))
647	}
648
649	return ids, nil
650}
651
652// create a github issue and return it ID
653func createGithubIssue(ctx context.Context, gc *githubv4.Client, repositoryID, title, body string) (string, string, error) {
654	m := &createIssueMutation{}
655	input := githubv4.CreateIssueInput{
656		RepositoryID: repositoryID,
657		Title:        githubv4.String(title),
658		Body:         (*githubv4.String)(&body),
659	}
660
661	ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
662	defer cancel()
663
664	if err := gc.Mutate(ctx, m, input, nil); err != nil {
665		return "", "", err
666	}
667
668	issue := m.CreateIssue.Issue
669	return issue.ID, issue.URL, nil
670}
671
672// add a comment to an issue and return it ID
673func addCommentGithubIssue(ctx context.Context, gc *githubv4.Client, subjectID string, body string) (string, string, error) {
674	m := &addCommentToIssueMutation{}
675	input := githubv4.AddCommentInput{
676		SubjectID: subjectID,
677		Body:      githubv4.String(body),
678	}
679
680	ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
681	defer cancel()
682
683	if err := gc.Mutate(ctx, m, input, nil); err != nil {
684		return "", "", err
685	}
686
687	node := m.AddComment.CommentEdge.Node
688	return node.ID, node.URL, nil
689}
690
691func editCommentGithubIssue(ctx context.Context, gc *githubv4.Client, commentID, body string) (string, string, error) {
692	m := &updateIssueCommentMutation{}
693	input := githubv4.UpdateIssueCommentInput{
694		ID:   commentID,
695		Body: githubv4.String(body),
696	}
697
698	ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
699	defer cancel()
700
701	if err := gc.Mutate(ctx, m, input, nil); err != nil {
702		return "", "", err
703	}
704
705	return commentID, m.UpdateIssueComment.IssueComment.URL, nil
706}
707
708func updateGithubIssueStatus(ctx context.Context, gc *githubv4.Client, id string, status bug.Status) error {
709	m := &updateIssueMutation{}
710
711	// set state
712	var state githubv4.IssueState
713
714	switch status {
715	case bug.OpenStatus:
716		state = githubv4.IssueStateOpen
717	case bug.ClosedStatus:
718		state = githubv4.IssueStateClosed
719	default:
720		panic("unknown bug state")
721	}
722
723	input := githubv4.UpdateIssueInput{
724		ID:    id,
725		State: &state,
726	}
727
728	ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
729	defer cancel()
730
731	if err := gc.Mutate(ctx, m, input, nil); err != nil {
732		return err
733	}
734
735	return nil
736}
737
738func updateGithubIssueBody(ctx context.Context, gc *githubv4.Client, id string, body string) error {
739	m := &updateIssueMutation{}
740	input := githubv4.UpdateIssueInput{
741		ID:   id,
742		Body: (*githubv4.String)(&body),
743	}
744
745	ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
746	defer cancel()
747
748	if err := gc.Mutate(ctx, m, input, nil); err != nil {
749		return err
750	}
751
752	return nil
753}
754
755func updateGithubIssueTitle(ctx context.Context, gc *githubv4.Client, id, title string) error {
756	m := &updateIssueMutation{}
757	input := githubv4.UpdateIssueInput{
758		ID:    id,
759		Title: (*githubv4.String)(&title),
760	}
761
762	ctx, cancel := context.WithTimeout(ctx, defaultTimeout)
763	defer cancel()
764
765	if err := gc.Mutate(ctx, m, input, nil); err != nil {
766		return err
767	}
768
769	return nil
770}
771
772// update github issue labels
773func (ge *githubExporter) updateGithubIssueLabels(ctx context.Context, gc *githubv4.Client, labelableID string, added, removed []bug.Label) error {
774	reqCtx, cancel := context.WithTimeout(ctx, defaultTimeout)
775	defer cancel()
776
777	wg, ctx := errgroup.WithContext(ctx)
778	if len(added) > 0 {
779		wg.Go(func() error {
780			addedIDs, err := ge.getLabelsIDs(ctx, gc, labelableID, added)
781			if err != nil {
782				return err
783			}
784
785			m := &addLabelsToLabelableMutation{}
786			inputAdd := githubv4.AddLabelsToLabelableInput{
787				LabelableID: labelableID,
788				LabelIDs:    addedIDs,
789			}
790
791			// add labels
792			if err := gc.Mutate(reqCtx, m, inputAdd, nil); err != nil {
793				return err
794			}
795			return nil
796		})
797	}
798
799	if len(removed) > 0 {
800		wg.Go(func() error {
801			removedIDs, err := ge.getLabelsIDs(ctx, gc, labelableID, removed)
802			if err != nil {
803				return err
804			}
805
806			m2 := &removeLabelsFromLabelableMutation{}
807			inputRemove := githubv4.RemoveLabelsFromLabelableInput{
808				LabelableID: labelableID,
809				LabelIDs:    removedIDs,
810			}
811
812			// remove label labels
813			if err := gc.Mutate(reqCtx, m2, inputRemove, nil); err != nil {
814				return err
815			}
816			return nil
817		})
818	}
819
820	return wg.Wait()
821}