/
default_branch.go
55 lines (50 loc) · 1.71 KB
/
default_branch.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
package github
import (
"context"
"errors"
"fmt"
"github.com/suzuki-shunsuke/ghcp/pkg/git"
"github.com/shurcooL/githubv4"
)
type QueryDefaultBranchInput struct {
BaseRepository git.RepositoryID
HeadRepository git.RepositoryID
}
type QueryDefaultBranchOutput struct {
BaseDefaultBranchName git.BranchName
HeadDefaultBranchName git.BranchName
}
// QueryDefaultBranch returns the default branch names.
// You can set both repositories or either repository.
func (c *GitHub) QueryDefaultBranch(ctx context.Context, in QueryDefaultBranchInput) (*QueryDefaultBranchOutput, error) {
if !in.BaseRepository.IsValid() || !in.HeadRepository.IsValid() {
return nil, errors.New("you need to set both BaseRepository and HeadRepository")
}
var q struct {
BaseRepository struct {
DefaultBranchRef struct {
Name string
}
} `graphql:"baseRepository: repository(owner: $baseOwner, name: $baseRepo)"`
HeadRepository struct {
DefaultBranchRef struct {
Name string
}
} `graphql:"headRepository: repository(owner: $headOwner, name: $headRepo)"`
}
v := map[string]interface{}{
"baseOwner": githubv4.String(in.BaseRepository.Owner),
"baseRepo": githubv4.String(in.BaseRepository.Name),
"headOwner": githubv4.String(in.HeadRepository.Owner),
"headRepo": githubv4.String(in.HeadRepository.Name),
}
c.Logger.Debugf("Querying the default branch name with %+v", v)
if err := c.Client.Query(ctx, &q, v); err != nil {
return nil, fmt.Errorf("GitHub API error: %w", err)
}
c.Logger.Debugf("Got the result: %+v", q)
return &QueryDefaultBranchOutput{
BaseDefaultBranchName: git.BranchName(q.BaseRepository.DefaultBranchRef.Name),
HeadDefaultBranchName: git.BranchName(q.HeadRepository.DefaultBranchRef.Name),
}, nil
}