Skip to content

Commit

Permalink
Return nil instead of 404 error if branch does not exist (#806)
Browse files Browse the repository at this point in the history
  • Loading branch information
threeseed authored and Jeremy Udit committed Jun 15, 2021
1 parent 7d5d47d commit 6e88301
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 7 deletions.
19 changes: 12 additions & 7 deletions github/data_source_github_branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package github

import (
"context"
"fmt"
"log"
"net/http"

"github.com/google/go-github/v35/github"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)

Expand Down Expand Up @@ -46,13 +47,17 @@ func dataSourceGithubBranchRead(d *schema.ResourceData, meta interface{}) error
branchName := d.Get("branch").(string)
branchRefName := "refs/heads/" + branchName

log.Printf("[DEBUG] Reading GitHub branch reference %s/%s (%s)",
orgName, repoName, branchRefName)
ref, resp, err := client.Git.GetRef(
context.TODO(), orgName, repoName, branchRefName)
log.Printf("[DEBUG] Reading GitHub branch reference %s/%s (%s)", orgName, repoName, branchRefName)
ref, resp, err := client.Git.GetRef(context.TODO(), orgName, repoName, branchRefName)
if err != nil {
return fmt.Errorf("Error reading GitHub branch reference %s/%s (%s): %s",
orgName, repoName, branchRefName, err)
if err, ok := err.(*github.ErrorResponse); ok {
if err.Response.StatusCode == http.StatusNotFound {
log.Printf("Error reading GitHub branch reference %s/%s (%s): %s", orgName, repoName, branchRefName, err)
d.SetId("")
return nil
}
}
return err
}

d.SetId(buildTwoPartID(repoName, branchName))
Expand Down
47 changes: 47 additions & 0 deletions github/data_source_github_branch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,51 @@ func TestAccGithubBranchDataSource(t *testing.T) {
})

})

t.Run("queries an invalid branch without error", func(t *testing.T) {

config := fmt.Sprintf(`
resource "github_repository" "test" {
name = "tf-acc-test-%[1]s"
auto_init = true
}
data "github_branch" "test" {
repository = github_repository.test.id
branch = "xxxxxx"
}
`, randomID)

check := resource.ComposeTestCheckFunc(
resource.TestCheckNoResourceAttr(
"data.github_branch.test", "id",
),
)

testCase := func(t *testing.T, mode string) {
resource.Test(t, resource.TestCase{
PreCheck: func() { skipUnlessMode(t, mode) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: config,
Check: check,
},
},
})
}

t.Run("with an anonymous account", func(t *testing.T) {
t.Skip("anonymous account not supported for this operation")
})

t.Run("with an individual account", func(t *testing.T) {
testCase(t, individual)
})

t.Run("with an organization account", func(t *testing.T) {
testCase(t, organization)
})

})
}

0 comments on commit 6e88301

Please sign in to comment.