forked from integrations/terraform-provider-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_source_github_branch.go
More file actions
85 lines (77 loc) · 1.91 KB
/
data_source_github_branch.go
File metadata and controls
85 lines (77 loc) · 1.91 KB
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"
"errors"
"fmt"
"net/http"
"github.com/google/go-github/v84/github"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func dataSourceGithubBranch() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourceGithubBranchRead,
Schema: map[string]*schema.Schema{
"repository": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"branch": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"etag": {
Type: schema.TypeString,
Computed: true,
},
"ref": {
Type: schema.TypeString,
Computed: true,
},
"sha": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceGithubBranchRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
client := meta.(*Owner).v3client
orgName := meta.(*Owner).name
repoName := d.Get("repository").(string)
branchName := d.Get("branch").(string)
branchRefName := "refs/heads/" + branchName
ref, resp, err := client.Git.GetRef(ctx, orgName, repoName, branchRefName)
if err != nil {
var ghErr *github.ErrorResponse
if errors.As(err, &ghErr) {
if ghErr.Response.StatusCode == http.StatusNotFound {
tflog.Debug(ctx, fmt.Sprintf("Missing GitHub branch %s/%s (%s)", orgName, repoName, branchRefName), map[string]any{
"org": orgName,
"repo": repoName,
"branch": branchRefName,
})
d.SetId("")
return nil
}
}
return diag.FromErr(err)
}
d.SetId(buildTwoPartID(repoName, branchName))
err = d.Set("etag", resp.Header.Get("ETag"))
if err != nil {
return diag.FromErr(err)
}
err = d.Set("ref", *ref.Ref)
if err != nil {
return diag.FromErr(err)
}
err = d.Set("sha", *ref.Object.SHA)
if err != nil {
return diag.FromErr(err)
}
return nil
}