/
fork.go
61 lines (57 loc) · 1.72 KB
/
fork.go
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
package github
import (
"context"
"fmt"
"github.com/cenkalti/backoff/v4"
"github.com/google/go-github/v49/github"
"github.com/suzuki-shunsuke/ghcp/pkg/git"
"github.com/shurcooL/githubv4"
)
// CreateFork creates a fork of the repository.
// This returns ID of the fork.
func (c *GitHub) CreateFork(ctx context.Context, id git.RepositoryID) (*git.RepositoryID, error) {
fork, _, err := c.Client.CreateFork(ctx, id.Owner, id.Name, nil)
if err != nil {
if _, ok := err.(*github.AcceptedError); !ok {
return nil, fmt.Errorf("GitHub API error: %w", err)
}
c.Logger.Debugf("Fork in progress: %+v", err)
}
forkRepository := git.RepositoryID{
Owner: fork.GetOwner().GetLogin(),
Name: fork.GetName(),
}
if err := c.waitUntilGitDataIsAvailable(ctx, forkRepository); err != nil {
return nil, fmt.Errorf("git data is not available on %s: %w", forkRepository, err)
}
return &forkRepository, nil
}
func (c *GitHub) waitUntilGitDataIsAvailable(ctx context.Context, id git.RepositoryID) error {
operation := func() error {
var q struct {
Repository struct {
DefaultBranchRef struct {
Target struct {
Commit struct {
Oid string
} `graphql:"... on Commit"`
}
}
} `graphql:"repository(owner: $owner, name: $repo)"`
}
v := map[string]interface{}{
"owner": githubv4.String(id.Owner),
"repo": githubv4.String(id.Name),
}
c.Logger.Debugf("Querying the repository with %+v", v)
if err := c.Client.Query(ctx, &q, v); err != nil {
return fmt.Errorf("GitHub API error: %w", err)
}
c.Logger.Debugf("Got the result: %+v", q)
return nil
}
if err := backoff.Retry(operation, backoff.NewExponentialBackOff()); err != nil {
return fmt.Errorf("retry over: %w", err)
}
return nil
}