-
Notifications
You must be signed in to change notification settings - Fork 697
/
data_source_github_repository_branches.go
107 lines (94 loc) · 2.61 KB
/
data_source_github_repository_branches.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package github
import (
"context"
"fmt"
"github.com/google/go-github/v47/github"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func dataSourceGithubRepositoryBranches() *schema.Resource {
return &schema.Resource{
Read: dataSourceGithubRepositoryBranchesRead,
Schema: map[string]*schema.Schema{
"repository": {
Type: schema.TypeString,
Required: true,
},
"only_protected_branches": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ConflictsWith: []string{"only_non_protected_branches"},
},
"only_non_protected_branches": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ConflictsWith: []string{"only_protected_branches"},
},
"branches": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Computed: true,
},
"protected": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
},
}
}
func flattenBranches(branches []*github.Branch) []map[string]interface{} {
results := make([]map[string]interface{}, 0)
if branches == nil {
return results
}
for _, branch := range branches {
branchMap := make(map[string]interface{})
branchMap["name"] = branch.GetName()
branchMap["protected"] = branch.GetProtected()
results = append(results, branchMap)
}
return results
}
func dataSourceGithubRepositoryBranchesRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Owner).v3client
orgName := meta.(*Owner).name
repoName := d.Get("repository").(string)
onlyProtectedBranches := d.Get("only_protected_branches").(bool)
onlyNonProtectedBranches := d.Get("only_non_protected_branches").(bool)
var listBranchOptions *github.BranchListOptions
if onlyProtectedBranches {
listBranchOptions = &github.BranchListOptions{
Protected: &onlyProtectedBranches,
}
} else if onlyNonProtectedBranches {
listBranchOptions = &github.BranchListOptions{
Protected: &onlyProtectedBranches,
}
} else {
listBranchOptions = &github.BranchListOptions{}
}
results := make([]map[string]interface{}, 0)
for {
branches, resp, err := client.Repositories.ListBranches(context.TODO(), orgName, repoName, listBranchOptions)
if err != nil {
return err
}
results = append(results, flattenBranches(branches)...)
if resp.NextPage == 0 {
break
}
listBranchOptions.Page = resp.NextPage
}
d.SetId(fmt.Sprintf("%s/%s", orgName, repoName))
d.Set("repository", repoName)
d.Set("branches", results)
return nil
}