Skip to content

Commit

Permalink
fix: Use ETag when reading github_branch_default resources. (#1994)
Browse files Browse the repository at this point in the history
This resource was missing saving and using the underlying resource's
ETag. This was discovered when we were hitting over-quota errors via
this resource.

The etag related implementation was copied from the `github_repository`
implementation.

Aside: There could be some refactoring to have these resources share
some common code. Such a refactoring seemed outside the scope of this
change.

Co-authored-by: Keegan Campbell <[email protected]>
  • Loading branch information
nairb774 and kfcampbell authored Nov 10, 2023
1 parent a8c7ec3 commit 6b7fd8b
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion github/resource_github_branch_default.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package github

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

"github.com/google/go-github/v55/github"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
Expand Down Expand Up @@ -35,6 +37,10 @@ func resourceGithubBranchDefault() *schema.Resource {
Default: false,
Description: "Indicate if it should rename the branch rather than use an existing branch. Defaults to 'false'.",
},
"etag": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
Expand Down Expand Up @@ -79,9 +85,23 @@ func resourceGithubBranchDefaultRead(d *schema.ResourceData, meta interface{}) e
repoName := d.Id()

ctx := context.WithValue(context.Background(), ctxId, d.Id())
if !d.IsNewResource() {
ctx = context.WithValue(ctx, ctxEtag, d.Get("etag").(string))
}

repository, _, err := client.Repositories.Get(ctx, owner, repoName)
repository, resp, err := client.Repositories.Get(ctx, owner, repoName)
if err != nil {
if ghErr, ok := err.(*github.ErrorResponse); ok {
if ghErr.Response.StatusCode == http.StatusNotModified {
return nil
}
if ghErr.Response.StatusCode == http.StatusNotFound {
log.Printf("[INFO] Removing repository %s/%s from state because it no longer exists in GitHub",
owner, repoName)
d.SetId("")
return nil
}
}
return err
}

Expand All @@ -90,6 +110,7 @@ func resourceGithubBranchDefaultRead(d *schema.ResourceData, meta interface{}) e
return nil
}

d.Set("etag", resp.Header.Get("ETag"))
d.Set("branch", *repository.DefaultBranch)
d.Set("repository", *repository.Name)
return nil
Expand Down

0 comments on commit 6b7fd8b

Please sign in to comment.