forked from integrations/terraform-provider-github
-
Notifications
You must be signed in to change notification settings - Fork 0
/
repository_utils.go
85 lines (70 loc) · 2.27 KB
/
repository_utils.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package github
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/google/go-github/v46/github"
)
// checkRepositoryBranchExists tests if a branch exists in a repository.
func checkRepositoryBranchExists(client *github.Client, owner, repo, branch string) error {
ctx := context.WithValue(context.Background(), ctxId, buildTwoPartID(repo, branch))
_, _, err := client.Repositories.GetBranch(ctx, owner, repo, branch, true)
if err != nil {
if ghErr, ok := err.(*github.ErrorResponse); ok {
if ghErr.Response.StatusCode == http.StatusNotFound {
return fmt.Errorf("branch %s not found in repository %s/%s or repository is not readable", branch, owner, repo)
}
}
return err
}
return nil
}
// checkRepositoryFileExists tests if a file exists in a repository.
func checkRepositoryFileExists(client *github.Client, owner, repo, file, branch string) error {
ctx := context.WithValue(context.Background(), ctxId, fmt.Sprintf("%s/%s", repo, file))
fc, _, _, err := client.Repositories.GetContents(ctx, owner, repo, file, &github.RepositoryContentGetOptions{Ref: branch})
if err != nil {
return nil
}
if fc == nil {
return fmt.Errorf("file %s not a file in in repository %s/%s or repository is not readable", file, owner, repo)
}
return nil
}
func getFileCommit(client *github.Client, owner, repo, file, branch string) (*github.RepositoryCommit, error) {
ctx := context.WithValue(context.Background(), ctxId, fmt.Sprintf("%s/%s", repo, file))
opts := &github.CommitsListOptions{
SHA: branch,
Path: file,
}
allCommits := []*github.RepositoryCommit{}
for {
commits, resp, err := client.Repositories.ListCommits(ctx, owner, repo, opts)
if err != nil {
return nil, err
}
allCommits = append(allCommits, commits...)
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
}
for _, c := range allCommits {
sha := c.GetSHA()
// Skip merge commits
if strings.Contains(c.Commit.GetMessage(), "Merge branch") {
continue
}
rc, _, err := client.Repositories.GetCommit(ctx, owner, repo, sha, nil)
if err != nil {
return nil, err
}
for _, f := range rc.Files {
if f.GetFilename() == file && f.GetStatus() != "removed" {
return rc, nil
}
}
}
return nil, fmt.Errorf("cannot find file %s in repo %s/%s", file, owner, repo)
}