aboutsummaryrefslogtreecommitdiffstats
path: root/bridge/github/export.go
blob: 8fcbd9e85f352ca9754bf66b93515f16588f9716 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
package github

import (
	"context"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"time"

	"github.com/MichaelMure/git-bug/bridge/core"
	"github.com/MichaelMure/git-bug/bug"
	"github.com/MichaelMure/git-bug/cache"
	"github.com/shurcooL/githubv4"
)

const (
	keyGithubIdExport  = "github-id"
	keyGithubUrlExport = "github-url"
)

// githubImporter implement the Importer interface
type githubExporter struct {
	gc           *githubv4.Client
	conf         core.Configuration
	cachedLabels map[string]githubv4.ID
}

// Init .
func (ge *githubExporter) Init(conf core.Configuration) error {
	ge.gc = buildClient(conf["token"])
	ge.conf = conf
	ge.cachedLabels = make(map[string]githubv4.ID)
	return nil
}

// ExportAll export all event made by the current user to Github
func (ge *githubExporter) ExportAll(repo *cache.RepoCache, since time.Time) error {
	identity, err := repo.GetUserIdentity()
	if err != nil {
		return err
	}

	allBugsIds := repo.AllBugsIds()

	// collect bugs
	bugs := make([]*cache.BugCache, 0)
	for _, id := range allBugsIds {
		b, err := repo.ResolveBug(id)
		if err != nil {
			return err
		}

		snapshot := b.Snapshot()

		// ignore issues edited before since date
		if snapshot.LastEditTime().Before(since) {
			continue
		}

		// if identity participated in a bug
		for _, p := range snapshot.Participants {
			if p.Id() == identity.Id() {
				bugs = append(bugs, b)
			}
		}
	}

	// get repository node id
	repositoryID, err := getRepositoryNodeID(
		ge.conf[keyOwner],
		ge.conf[keyProject],
		ge.conf[keyToken],
	)
	if err != nil {
		return err
	}

	for _, b := range bugs {
		snapshot := b.Snapshot()
		bugGithubID := ""

		for _, op := range snapshot.Operations {
			// treat only operations after since date
			if op.Time().Before(since) {
				continue
			}

			// ignore SetMetadata operations
			if _, ok := op.(*bug.SetMetadataOperation); ok {
				continue
			}

			// ignore imported issues and operations from github
			if _, ok := op.GetMetadata(keyGithubId); ok {
				continue
			}

			// get operation hash
			hash, err := op.Hash()
			if err != nil {
				return fmt.Errorf("reading operation hash: %v", err)
			}

			// ignore already exported issues and operations
			if _, err := b.ResolveOperationWithMetadata("github-exported-op", hash.String()); err != nil {
				continue
			}

			switch op.(type) {
			case *bug.CreateOperation:
				opr := op.(*bug.CreateOperation)
				//TODO export files
				bugGithubID, err = ge.createGithubIssue(repositoryID, opr.Title, opr.Message)
				if err != nil {
					return fmt.Errorf("exporting bug %v: %v", b.HumanId(), err)
				}

			case *bug.AddCommentOperation:
				opr := op.(*bug.AddCommentOperation)
				bugGithubID, err = ge.addCommentGithubIssue(bugGithubID, opr.Message)
				if err != nil {
					return fmt.Errorf("adding comment %v: %v", "", err)
				}

			case *bug.EditCommentOperation:
				opr := op.(*bug.EditCommentOperation)
				if err := ge.editCommentGithubIssue(bugGithubID, opr.Message); err != nil {
					return fmt.Errorf("editing comment %v: %v", "", err)
				}

			case *bug.SetStatusOperation:
				opr := op.(*bug.SetStatusOperation)
				if err := ge.updateGithubIssueStatus(bugGithubID, opr.Status); err != nil {
					return fmt.Errorf("updating status %v: %v", bugGithubID, err)
				}

			case *bug.SetTitleOperation:
				opr := op.(*bug.SetTitleOperation)
				if err := ge.updateGithubIssueTitle(bugGithubID, opr.Title); err != nil {
					return fmt.Errorf("editing comment %v: %v", bugGithubID, err)
				}

			case *bug.LabelChangeOperation:
				opr := op.(*bug.LabelChangeOperation)
				if err := ge.updateGithubIssueLabels(bugGithubID, opr.Added, opr.Removed); err != nil {
					return fmt.Errorf("updating labels %v: %v", bugGithubID, err)
				}

			default:
				// ignore other type of operations
			}

		}

		if err := b.CommitAsNeeded(); err != nil {
			return fmt.Errorf("bug commit: %v", err)
		}

		fmt.Printf("debug: %v", bugGithubID)
	}

	return nil
}

// getRepositoryNodeID request github api v3 to get repository node id
func getRepositoryNodeID(owner, project, token string) (string, error) {
	url := fmt.Sprintf("%s/repos/%s/%s", githubV3Url, owner, project)

	client := &http.Client{
		Timeout: defaultTimeout,
	}

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return "", err
	}

	// need the token for private repositories
	req.Header.Set("Authorization", fmt.Sprintf("token %s", token))

	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}

	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("error retrieving repository node id %v", resp.StatusCode)
	}

	aux := struct {
		NodeID string `json:"node_id"`
	}{}

	data, _ := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()

	err = json.Unmarshal(data, &aux)
	if err != nil {
		return "", err
	}

	return aux.NodeID, nil
}

func (ge *githubExporter) markOperationAsExported(b *cache.BugCache, opHash string) error {
	return nil
}

// get label from github
func (ge *githubExporter) getGithubLabelID(label string) (string, error) {
	url := fmt.Sprintf("%s/repos/%s/%s/labels/%s", githubV3Url, ge.conf[keyOwner], ge.conf[keyProject], label)

	client := &http.Client{
		Timeout: defaultTimeout,
	}

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return "", err
	}

	// need the token for private repositories
	req.Header.Set("Authorization", fmt.Sprintf("token %s", ge.conf[keyToken]))

	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}

	if resp.StatusCode != http.StatusFound {
		return "", fmt.Errorf("error getting label: status code: %v", resp.StatusCode)
	}

	aux := struct {
		ID     string `json:"id"`
		NodeID string `json:"node_id"`
		Color  string `json:"color"`
	}{}

	data, _ := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()

	err = json.Unmarshal(data, &aux)
	if err != nil {
		return "", err
	}

	return aux.NodeID, nil
}

// create github label using api v3
func (ge *githubExporter) createGithubLabel(label, labelColor string) (string, error) {
	url := fmt.Sprintf("%s/repos/%s/%s/labels", githubV3Url, ge.conf[keyOwner], ge.conf[keyProject])

	client := &http.Client{
		Timeout: defaultTimeout,
	}

	req, err := http.NewRequest("POST", url, nil)
	if err != nil {
		return "", err
	}

	// need the token for private repositories
	req.Header.Set("Authorization", fmt.Sprintf("token %s", ge.conf[keyToken]))

	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}

	if resp.StatusCode != http.StatusCreated {
		return "", fmt.Errorf("error creating label: response status %v", resp.StatusCode)
	}

	aux := struct {
		ID     string `json:"id"`
		NodeID string `json:"node_id"`
		Color  string `json:"color"`
	}{}

	data, _ := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()

	err = json.Unmarshal(data, &aux)
	if err != nil {
		return "", err
	}

	return aux.NodeID, nil
}

// randomHexColor return a random hex color code
func randomHexColor() string {
	bytes := make([]byte, 6)
	if _, err := rand.Read(bytes); err != nil {
		return "fffff"
	}

	return hex.EncodeToString(bytes)
}

func (ge *githubExporter) getOrCreateGithubLabelID(repositoryID, label string) (string, error) {
	// try to get label id
	labelID, err := ge.getGithubLabelID(label)
	if err == nil {
		return labelID, nil
	}

	// random color
	color := randomHexColor()

	// create label and return id
	labelID, err = ge.createGithubLabel(label, color)
	if err != nil {
		return "", err
	}

	return labelID, nil
}

func (ge *githubExporter) getLabelsIDs(repositoryID string, labels []bug.Label) ([]githubv4.ID, error) {
	ids := make([]githubv4.ID, 0, len(labels))
	var err error

	// check labels ids
	for _, l := range labels {
		label := string(l)

		id, ok := ge.cachedLabels[label]
		if !ok {
			// try to query label id
			id, err = ge.getOrCreateGithubLabelID(repositoryID, label)
			if err != nil {
				return nil, fmt.Errorf("get or create github label: %v", err)
			}

			// cache label id
			ge.cachedLabels[label] = id
		}

		ids = append(ids, githubv4.ID(id))
	}

	return ids, nil
}

// create a github issue and return it ID
func (ge *githubExporter) createGithubIssue(repositoryID, title, body string) (string, error) {
	m := &createIssueMutation{}
	input := &githubv4.CreateIssueInput{
		RepositoryID: repositoryID,
		Title:        githubv4.String(title),
		Body:         (*githubv4.String)(&body),
	}

	if err := ge.gc.Mutate(context.TODO(), m, input, nil); err != nil {
		return "", err
	}

	return m.CreateIssue.Issue.ID, nil
}

// add a comment to an issue and return it ID
func (ge *githubExporter) addCommentGithubIssue(subjectID string, body string) (string, error) {
	m := &addCommentToIssueMutation{}
	input := &githubv4.AddCommentInput{
		SubjectID: subjectID,
		Body:      githubv4.String(body),
	}

	if err := ge.gc.Mutate(context.TODO(), m, input, nil); err != nil {
		return "", err
	}

	return m.AddComment.CommentEdge.Node.ID, nil
}

func (ge *githubExporter) editCommentGithubIssue(commentID, body string) error {
	m := &updateIssueCommentMutation{}
	input := &githubv4.UpdateIssueCommentInput{
		ID:   commentID,
		Body: githubv4.String(body),
	}

	if err := ge.gc.Mutate(context.TODO(), m, input, nil); err != nil {
		return err
	}

	return nil
}

func (ge *githubExporter) updateGithubIssueStatus(id string, status bug.Status) error {
	m := &updateIssueMutation{}

	// set state
	state := githubv4.IssueStateClosed
	if status == bug.OpenStatus {
		state = githubv4.IssueStateOpen
	}

	input := &githubv4.UpdateIssueInput{
		ID:    id,
		State: &state,
	}

	if err := ge.gc.Mutate(context.TODO(), m, input, nil); err != nil {
		return err
	}

	return nil
}

func (ge *githubExporter) updateGithubIssueBody(id string, body string) error {
	m := &updateIssueMutation{}
	input := &githubv4.UpdateIssueInput{
		ID:   id,
		Body: (*githubv4.String)(&body),
	}

	if err := ge.gc.Mutate(context.TODO(), m, input, nil); err != nil {
		return err
	}

	return nil
}

func (ge *githubExporter) updateGithubIssueTitle(id, title string) error {
	m := &updateIssueMutation{}
	input := &githubv4.UpdateIssueInput{
		ID:    id,
		Title: (*githubv4.String)(&title),
	}

	if err := ge.gc.Mutate(context.TODO(), m, input, nil); err != nil {
		return err
	}

	return nil
}

// update github issue labels
func (ge *githubExporter) updateGithubIssueLabels(labelableID string, added, removed []bug.Label) error {
	addedIDs, err := ge.getLabelsIDs(labelableID, added)
	if err != nil {
		return fmt.Errorf("getting added labels ids: %v", err)
	}

	m := &updateIssueMutation{}
	inputAdd := &githubv4.AddLabelsToLabelableInput{
		LabelableID: labelableID,
		LabelIDs:    addedIDs,
	}

	// add labels
	if err := ge.gc.Mutate(context.TODO(), m, inputAdd, nil); err != nil {
		return err
	}

	removedIDs, err := ge.getLabelsIDs(labelableID, added)
	if err != nil {
		return fmt.Errorf("getting added labels ids: %v", err)
	}

	inputRemove := &githubv4.RemoveLabelsFromLabelableInput{
		LabelableID: labelableID,
		LabelIDs:    removedIDs,
	}

	// remove label labels
	if err := ge.gc.Mutate(context.TODO(), m, inputRemove, nil); err != nil {
		return err
	}

	return nil
}