From b956f489772e468eddba9dbc0d8987e8b1aed251 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Thu, 14 May 2020 09:13:44 -0400 Subject: [PATCH 01/21] Add Failing Test --- .../resource_github_repository_file_test.go | 614 +++++++++++++----- 1 file changed, 463 insertions(+), 151 deletions(-) diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index 911e8781e6..a5fa318794 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -1,197 +1,509 @@ package github import ( + "context" + "log" + "os" "strings" + "encoding/base64" "fmt" "testing" + "github.com/google/go-github/v31/github" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/terraform" ) -func TestAccGithubRepositoryFile(t *testing.T) { +// The authenticated user's name used for commits should be exported as GITHUB_TEST_USER_NAME +var userName string = os.Getenv("GITHUB_TEST_USER_NAME") - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) +// The authenticated user's email address used for commits should be exported as GITHUB_TEST_USER_EMAIL +var userEmail string = os.Getenv("GITHUB_TEST_USER_EMAIL") - t.Run("creates and updates file content without error", func(t *testing.T) { +func init() { + resource.AddTestSweepers("github_repository_file", &resource.Sweeper{ + Name: "github_repository_file", + F: testSweepRepositoryFiles, + }) - fileContent := "file_content_value" - updatedFileContent := "updated_file_content_value" +} - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%s" - auto_init = true - } +func testSweepRepositoryFiles(region string) error { + meta, err := sharedConfigForRegion(region) + if err != nil { + return err + } + + if err := testSweepDeleteRepositoryFiles(meta, "master"); err != nil { + return err + } + + if err := testSweepDeleteRepositoryFiles(meta, "test-branch"); err != nil { + return err + } - resource "github_repository_file" "test" { - repository = github_repository.test.id - file = "test" - content = "%s" + return nil +} + +func testSweepDeleteRepositoryFiles(meta interface{}, branch string) error { + client := meta.(*Organization).v3client + org := meta.(*Organization).name + + _, files, _, err := client.Repositories.GetContents( + context.TODO(), org, "test-repo", "", &github.RepositoryContentGetOptions{Ref: branch}) + if err != nil { + return err + } + + for _, f := range files { + if name := f.GetName(); strings.HasPrefix(name, "tf-acc-") { + log.Printf("Deleting repository file: %s, repo: %s/test-repo, branch: %s", name, org, branch) + opts := &github.RepositoryContentFileOptions{Branch: github.String(branch)} + if _, _, err := client.Repositories.DeleteFile(context.TODO(), org, "test-repo", name, opts); err != nil { + return err } - `, randomID, fileContent) + } + } + + return nil +} + +func TestAccGithubRepositoryFile_basic(t *testing.T) { + if userName == "" { + t.Skip("This test requires you to set the test user's name (set it by exporting GITHUB_TEST_USER_NAME)") + } + + if userEmail == "" { + t.Skip("This test requires you to set the test user's email address (set it by exporting GITHUB_TEST_USER_EMAIL)") + } + + var content github.RepositoryContent + var commit github.RepositoryCommit + + rn := "github_repository_file.foo" + randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + path := fmt.Sprintf("tf-acc-test-file-%s", randString) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckGithubRepositoryFileDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubRepositoryFileConfig( + path, "Terraform acceptance test file"), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubRepositoryFileExists(rn, path, "master", &content, &commit), + testAccCheckGithubRepositoryFileAttributes(&content, &testAccGithubRepositoryFileExpectedAttributes{ + Content: base64.StdEncoding.EncodeToString([]byte("Terraform acceptance test file")) + "\n", + }), + testAccCheckGithubRepositoryFileCommitAttributes(&commit, &testAccGithubRepositoryFileExpectedCommitAttributes{ + Branch: "master", + CommitAuthor: userName, + CommitEmail: userEmail, + CommitMessage: fmt.Sprintf("Add %s", path), + Filename: path, + }), + resource.TestCheckResourceAttr(rn, "repository", "test-repo"), + resource.TestCheckResourceAttr(rn, "branch", "master"), + resource.TestCheckResourceAttr(rn, "file", path), + resource.TestCheckResourceAttr(rn, "content", "Terraform acceptance test file"), + resource.TestCheckResourceAttr(rn, "commit_author", userName), + resource.TestCheckResourceAttr(rn, "commit_email", userEmail), + resource.TestCheckResourceAttr(rn, "commit_message", fmt.Sprintf("Add %s", path)), + ), + }, + { + Config: testAccGithubRepositoryFileConfig( + path, "Terraform acceptance test file updated"), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubRepositoryFileExists(rn, path, "master", &content, &commit), + testAccCheckGithubRepositoryFileAttributes(&content, &testAccGithubRepositoryFileExpectedAttributes{ + Content: base64.StdEncoding.EncodeToString([]byte("Terraform acceptance test file updated")) + "\n", + }), + testAccCheckGithubRepositoryFileCommitAttributes(&commit, &testAccGithubRepositoryFileExpectedCommitAttributes{ + Branch: "master", + CommitAuthor: userName, + CommitEmail: userEmail, + CommitMessage: fmt.Sprintf("Update %s", path), + Filename: path, + }), + resource.TestCheckResourceAttr(rn, "repository", "test-repo"), + resource.TestCheckResourceAttr(rn, "branch", "master"), + resource.TestCheckResourceAttr(rn, "file", path), + resource.TestCheckResourceAttr(rn, "content", "Terraform acceptance test file updated"), + resource.TestCheckResourceAttr(rn, "commit_author", userName), + resource.TestCheckResourceAttr(rn, "commit_email", userEmail), + resource.TestCheckResourceAttr(rn, "commit_message", fmt.Sprintf("Update %s", path)), + ), + }, + { + ResourceName: rn, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccGithubRepositoryFile_branch(t *testing.T) { + if userName == "" { + t.Skip("This test requires you to set the test user's name (set it by exporting GITHUB_TEST_USER_NAME)") + } + + if userEmail == "" { + t.Skip("This test requires you to set the test user's email address (set it by exporting GITHUB_TEST_USER_EMAIL)") + } + + var content github.RepositoryContent + var commit github.RepositoryCommit + + rn := "github_repository_file.foo" + randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + path := fmt.Sprintf("tf-acc-test-file-%s", randString) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckGithubRepositoryFileDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubRepositoryFileBranchConfig( + path, "Terraform acceptance test file"), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubRepositoryFileExists(rn, path, "test-branch", &content, &commit), + testAccCheckGithubRepositoryFileAttributes(&content, &testAccGithubRepositoryFileExpectedAttributes{ + Content: base64.StdEncoding.EncodeToString([]byte("Terraform acceptance test file")) + "\n", + }), + testAccCheckGithubRepositoryFileCommitAttributes(&commit, &testAccGithubRepositoryFileExpectedCommitAttributes{ + Branch: "test-branch", + CommitAuthor: userName, + CommitEmail: userEmail, + CommitMessage: fmt.Sprintf("Add %s", path), + Filename: path, + }), + resource.TestCheckResourceAttr(rn, "repository", "test-repo"), + resource.TestCheckResourceAttr(rn, "branch", "test-branch"), + resource.TestCheckResourceAttr(rn, "file", path), + resource.TestCheckResourceAttr(rn, "content", "Terraform acceptance test file"), + resource.TestCheckResourceAttr(rn, "commit_author", userName), + resource.TestCheckResourceAttr(rn, "commit_email", userEmail), + resource.TestCheckResourceAttr(rn, "commit_message", fmt.Sprintf("Add %s", path)), + ), + }, + { + Config: testAccGithubRepositoryFileBranchConfig( + path, "Terraform acceptance test file updated"), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubRepositoryFileExists(rn, path, "test-branch", &content, &commit), + testAccCheckGithubRepositoryFileAttributes(&content, &testAccGithubRepositoryFileExpectedAttributes{ + Content: base64.StdEncoding.EncodeToString([]byte("Terraform acceptance test file updated")) + "\n", + }), + testAccCheckGithubRepositoryFileCommitAttributes(&commit, &testAccGithubRepositoryFileExpectedCommitAttributes{ + Branch: "test-branch", + CommitAuthor: userName, + CommitEmail: userEmail, + CommitMessage: fmt.Sprintf("Update %s", path), + Filename: path, + }), + resource.TestCheckResourceAttr(rn, "repository", "test-repo"), + resource.TestCheckResourceAttr(rn, "branch", "test-branch"), + resource.TestCheckResourceAttr(rn, "file", path), + resource.TestCheckResourceAttr(rn, "content", "Terraform acceptance test file updated"), + resource.TestCheckResourceAttr(rn, "commit_author", userName), + resource.TestCheckResourceAttr(rn, "commit_email", userEmail), + resource.TestCheckResourceAttr(rn, "commit_message", fmt.Sprintf("Update %s", path)), + ), + }, + { + ResourceName: rn, + ImportState: true, + ImportStateId: fmt.Sprintf("test-repo/%s:test-branch", path), + ImportStateVerify: true, + }, + }, + }) +} - checks := map[string]resource.TestCheckFunc{ - "before": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository_file.test", "sha", - "deee258b7c807901aad79d01da020d993739160a", +func TestAccGithubRepositoryFile_committer(t *testing.T) { + var content github.RepositoryContent + var commit github.RepositoryCommit + + rn := "github_repository_file.foo" + randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + path := fmt.Sprintf("tf-acc-test-file-%s", randString) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckGithubRepositoryFileDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubRepositoryFileCommitterConfig( + path, "Terraform acceptance test file"), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubRepositoryFileExists(rn, path, "master", &content, &commit), + testAccCheckGithubRepositoryFileAttributes(&content, &testAccGithubRepositoryFileExpectedAttributes{ + Content: base64.StdEncoding.EncodeToString([]byte("Terraform acceptance test file")) + "\n", + }), + testAccCheckGithubRepositoryFileCommitAttributes(&commit, &testAccGithubRepositoryFileExpectedCommitAttributes{ + Branch: "master", + CommitAuthor: "Terraform User", + CommitEmail: "terraform@example.com", + CommitMessage: "Managed by Terraform", + Filename: path, + }), + resource.TestCheckResourceAttr(rn, "repository", "test-repo"), + resource.TestCheckResourceAttr(rn, "branch", "master"), + resource.TestCheckResourceAttr(rn, "file", path), + resource.TestCheckResourceAttr(rn, "content", "Terraform acceptance test file"), + resource.TestCheckResourceAttr(rn, "commit_author", "Terraform User"), + resource.TestCheckResourceAttr(rn, "commit_email", "terraform@example.com"), + resource.TestCheckResourceAttr(rn, "commit_message", "Managed by Terraform"), ), - ), - "after": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository_file.test", "sha", - "ec9aad0ba478cdd7349faabbeac2a64e5ce72ddb", + }, + { + Config: testAccGithubRepositoryFileCommitterConfig( + path, "Terraform acceptance test file updated"), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubRepositoryFileExists(rn, path, "master", &content, &commit), + testAccCheckGithubRepositoryFileAttributes(&content, &testAccGithubRepositoryFileExpectedAttributes{ + Content: base64.StdEncoding.EncodeToString([]byte("Terraform acceptance test file updated")) + "\n", + }), + testAccCheckGithubRepositoryFileCommitAttributes(&commit, &testAccGithubRepositoryFileExpectedCommitAttributes{ + Branch: "master", + CommitAuthor: "Terraform User", + CommitEmail: "terraform@example.com", + CommitMessage: "Managed by Terraform", + Filename: path, + }), + resource.TestCheckResourceAttr(rn, "repository", "test-repo"), + resource.TestCheckResourceAttr(rn, "branch", "master"), + resource.TestCheckResourceAttr(rn, "file", path), + resource.TestCheckResourceAttr(rn, "content", "Terraform acceptance test file updated"), + resource.TestCheckResourceAttr(rn, "commit_author", "Terraform User"), + resource.TestCheckResourceAttr(rn, "commit_email", "terraform@example.com"), + resource.TestCheckResourceAttr(rn, "commit_message", "Managed by Terraform"), ), - ), + }, + { + ResourceName: rn, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccGithubRepositoryFile_overwrite(t *testing.T) { + var content github.RepositoryContent + var commit github.RepositoryCommit + + rn := "github_repository_file.foo" + randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + path := fmt.Sprintf("tf-acc-test-file-%s", randString) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckGithubRepositoryFileDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubRepositoryFileOverwriteConfig(), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubRepositoryFileExists(rn, path, "master", &content, &commit), + testAccCheckGithubRepositoryFileAttributes(&content, &testAccGithubRepositoryFileExpectedAttributes{ + Content: base64.StdEncoding.EncodeToString([]byte("Terraform acceptance test file")) + "\n", + }), + ), + }, + }, + }) +} + +func testAccCheckGithubRepositoryFileExists(n, path, branch string, content *github.RepositoryContent, commit *github.RepositoryCommit) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not Found: %s", n) } - 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: checks["before"], - }, - { - Config: strings.Replace(config, - fileContent, - updatedFileContent, 1), - Check: checks["after"], - }, - }, - }) + if rs.Primary.ID == "" { + return fmt.Errorf("No repository file path set") } - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) + conn := testAccProvider.Meta().(*Organization).v3client + org := testAccProvider.Meta().(*Organization).name - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) + opts := &github.RepositoryContentGetOptions{Ref: branch} + gotContent, _, _, err := conn.Repositories.GetContents(context.TODO(), org, "test-repo", path, opts) + if err != nil { + return err + } - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) + gotCommit, err := getFileCommit(conn, org, "test-repo", path, branch) + if err != nil { + return err + } - }) + *content = *gotContent + *commit = *gotCommit - t.Run("manages file content for a specified branch", func(t *testing.T) { + return nil + } +} - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%s" - auto_init = true - } +type testAccGithubRepositoryFileExpectedAttributes struct { + Content string +} - resource "github_branch" "test" { - repository = github_repository.test.id - branch = "tf-acc-test-%[1]s" - } +func testAccCheckGithubRepositoryFileAttributes(content *github.RepositoryContent, want *testAccGithubRepositoryFileExpectedAttributes) resource.TestCheckFunc { + return func(s *terraform.State) error { - resource "github_repository_file" "test" { - repository = github_repository.test.id - branch = github_branch.test.branch - file = "test" - content = "test" - } - `, randomID) - - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository_file.test", "sha", - "30d74d258442c7c65512eafab474568dd706c430", - ), - ) - - 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, - }, - }, - }) + if *content.Content != want.Content { + return fmt.Errorf("got content %q; want %q", *content.Content, want.Content) } - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) + return nil + } +} - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) +type testAccGithubRepositoryFileExpectedCommitAttributes struct { + Branch string + CommitAuthor string + CommitEmail string + CommitMessage string + Filename string +} - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) +func testAccCheckGithubRepositoryFileCommitAttributes(commit *github.RepositoryCommit, want *testAccGithubRepositoryFileExpectedCommitAttributes) resource.TestCheckFunc { + return func(s *terraform.State) error { - }) + if name := commit.GetCommit().GetCommitter().GetName(); name != want.CommitAuthor { + return fmt.Errorf("got committer author name %q; want %q", name, want.CommitAuthor) + } - t.Run("commits with custom message, author and e-mail", func(t *testing.T) { + if email := commit.GetCommit().GetCommitter().GetEmail(); email != want.CommitEmail { + return fmt.Errorf("got committer author email %q; want %q", email, want.CommitEmail) + } - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%s" - auto_init = true - } + if message := commit.GetCommit().GetMessage(); message != want.CommitMessage { + return fmt.Errorf("got commit message %q; want %q", message, want.CommitMessage) + } + + if len(commit.Files) != 1 { + return fmt.Errorf("got multiple files in commit (%q); expected 1", len(commit.Files)) + } - resource "github_repository_file" "test" { - repository = github_repository.test.id - file = "test" - content = "test" - commit_message = "Managed by Terraform" - commit_author = "Terraform User" - commit_email = "terraform@example.com" + file := commit.Files[0] + if filename := file.GetFilename(); filename != want.Filename { + return fmt.Errorf("got filename %q; want %q", filename, want.Filename) + } + + return nil + } +} + +func testAccCheckGithubRepositoryFileDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*Organization).v3client + org := testAccProvider.Meta().(*Organization).name + + for _, rs := range s.RootModule().Resources { + if rs.Type != "github_repository_file" { + continue + } + + repo, file := splitRepoFilePath(rs.Primary.ID) + opts := &github.RepositoryContentGetOptions{Ref: rs.Primary.Attributes["branch"]} + + fc, _, resp, err := conn.Repositories.GetContents(context.TODO(), org, repo, file, opts) + if err == nil { + if fc != nil { + return fmt.Errorf("Repository file %s/%s/%s still exists", org, repo, file) } - `, randomID) - - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository_file.test", "commit_message", - "Managed by Terraform", - ), - resource.TestCheckResourceAttr( - "github_repository_file.test", "commit_author", - "Terraform User", - ), - resource.TestCheckResourceAttr( - "github_repository_file.test", "commit_email", - "terraform@example.com", - ), - ) - - 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, - }, - }, - }) } + if resp.StatusCode != 404 { + return err + } + return nil + } + return nil +} - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) +func testAccGithubRepositoryFileConfig(file, content string) string { + return fmt.Sprintf(` +resource "github_repository_file" "foo" { + repository = "test-repo" + file = "%s" + content = "%s" +} +`, file, content) +} - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) +func testAccGithubRepositoryFileBranchConfig(file, content string) string { + return fmt.Sprintf(` +resource "github_repository_file" "foo" { + repository = "test-repo" + branch = "test-branch" + file = "%s" + content = "%s" +} +`, file, content) +} - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) +func testAccGithubRepositoryFileCommitterConfig(file, content string) string { + return fmt.Sprintf(` +resource "github_repository_file" "foo" { + repository = "test-repo" + file = "%s" + content = "%s" + commit_message = "Managed by Terraform" + commit_author = "Terraform User" + commit_email = "terraform@example.com" +} +`, file, content) +} - }) +func testAccGithubRepositoryFileOverwriteConfig() string { + + owner := os.Getenv("GITHUB_ORGANIZATION") + repository := os.Getenv("GITHUB_TEMPLATE_REPOSITORY") + randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + + return fmt.Sprintf(` +resource "github_repository" "foo" { + name = "tf-acc-test-%s" + description = "Terraform acceptance tests %s" + homepage_url = "http://example.com/" + + template { + owner = "%s" + repository = "%s" + } + + # So that acceptance tests can be run in a github organization + # with no billing + private = false + + has_issues = true + has_wiki = true + allow_merge_commit = true + allow_squash_merge = false + allow_rebase_merge = false + has_downloads = true + +} + +resource "github_repository_file" "foo" { + repository = github_repository.foo.name + file = ".gitignore" + content = "**/.terraform/*" + commit_message = "Managed by Terraform" + commit_author = "Terraform User" + commit_email = "terraform@example.com" +} +`, randString, randString, owner, repository) } From ce177d8a4dc569b11f3bf0ac0339ee4abaaa58ba Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Thu, 14 May 2020 17:49:55 -0400 Subject: [PATCH 02/21] Add Overwrite Support --- github/resource_github_repository_file.go | 169 ++++++++++++++---- .../resource_github_repository_file_test.go | 77 ++++++-- website/docs/r/repository_file.html.markdown | 1 + 3 files changed, 193 insertions(+), 54 deletions(-) diff --git a/github/resource_github_repository_file.go b/github/resource_github_repository_file.go index e30af03ceb..79f647a8e1 100644 --- a/github/resource_github_repository_file.go +++ b/github/resource_github_repository_file.go @@ -31,15 +31,16 @@ func resourceGithubRepositoryFile() *schema.Resource { branch = parts[1] } - client := meta.(*Owner).v3client - owner := meta.(*Owner).name + client := meta.(*Organization).v3client + org := meta.(*Organization).name repo, file := splitRepoFilePath(parts[0]) - if err := checkRepositoryFileExists(client, owner, repo, file, branch); err != nil { + if err := checkRepositoryFileExists(client, org, repo, file, branch); err != nil { return nil, err } d.SetId(fmt.Sprintf("%s/%s", repo, file)) d.Set("branch", branch) + d.Set("overwrite", false) return []*schema.ResourceData{d}, nil }, @@ -93,6 +94,12 @@ func resourceGithubRepositoryFile() *schema.Resource { Computed: true, Description: "The blob SHA of the file", }, + "overwrite": { + Type: schema.TypeBool, + Optional: true, + Description: "Enable overwriting existing files, defaults to \"false\"", + Default: false, + }, }, } } @@ -135,15 +142,19 @@ func resourceGithubRepositoryFileOptions(d *schema.ResourceData) (*github.Reposi } func resourceGithubRepositoryFileCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Owner).v3client - owner := meta.(*Owner).name + if err := checkOrganization(meta); err != nil { + return err + } + + client := meta.(*Organization).v3client + org := meta.(*Organization).name ctx := context.Background() repo := d.Get("repository").(string) file := d.Get("file").(string) branch := d.Get("branch").(string) - if err := checkRepositoryBranchExists(client, owner, repo, branch); err != nil { + if err := checkRepositoryBranchExists(client, org, repo, branch); err != nil { return err } @@ -157,38 +168,67 @@ func resourceGithubRepositoryFileCreate(d *schema.ResourceData, meta interface{} opts.Message = &m } - log.Printf("[DEBUG] Creating repository file: %s/%s/%s in branch: %s", owner, repo, file, branch) - resp, _, err := client.Repositories.CreateFile(ctx, owner, repo, file, opts) + log.Printf("[DEBUG] Checking if overwriting a repository file: %s/%s/%s in branch: %s", org, repo, file, branch) + checkOpt := github.RepositoryContentGetOptions{Ref: branch} + fileContent, _, resp, err := client.Repositories.GetContents(ctx, org, repo, file, &checkOpt) + if err != nil { + if resp != nil { + if resp.StatusCode != 404 { + // 404 is a valid response if the file does not exist + return err + } + } else { + // Response should be non-nil + return err + } + } + + if fileContent != nil { + if d.Get("overwrite").(bool) { + // Overwrite existing file if requested by configuring the options for + // `client.Repositories.CreateFile` to match the existing file's SHA + opts.SHA = fileContent.SHA + } else { + // Error if overwriting a file is not requested + return fmt.Errorf("[ERROR] Refusing to overwrite existing file. Configure `overwrite` to `true` to override.") + } + } + + // Create a new or overwritten file + log.Printf("[DEBUG] Creating repository file: %s/%s/%s in branch: %s", org, repo, file, branch) + _, _, err = client.Repositories.CreateFile(ctx, org, repo, file, opts) if err != nil { return err } - d.Set("commit_author", resp.GetCommitter().GetName()) - d.Set("commit_email", resp.GetCommitter().GetEmail()) - d.Set("commit_message", resp.GetMessage()) d.SetId(fmt.Sprintf("%s/%s", repo, file)) return resourceGithubRepositoryFileRead(d, meta) } func resourceGithubRepositoryFileRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Owner).v3client - owner := meta.(*Owner).name + err := checkOrganization(meta) + if err != nil { + return err + } + + client := meta.(*Organization).v3client + org := meta.(*Organization).name ctx := context.WithValue(context.Background(), ctxId, d.Id()) repo, file := splitRepoFilePath(d.Id()) branch := d.Get("branch").(string) - if err := checkRepositoryBranchExists(client, owner, repo, branch); err != nil { + if err := checkRepositoryBranchExists(client, org, repo, branch); err != nil { return err } - log.Printf("[DEBUG] Reading repository file: %s/%s/%s, branch: %s", owner, repo, file, branch) + log.Printf("[DEBUG] Reading repository file: %s/%s/%s, branch: %s", org, repo, file, branch) opts := &github.RepositoryContentGetOptions{Ref: branch} - fc, _, _, _ := client.Repositories.GetContents(ctx, owner, repo, file, opts) + fc, _, _, _ := client.Repositories.GetContents(ctx, org, repo, file, opts) if fc == nil { log.Printf("[WARN] Removing repository path %s/%s/%s from state because it no longer exists in GitHub", - owner, repo, file) + org, repo, file) d.SetId("") return nil } @@ -203,19 +243,33 @@ func resourceGithubRepositoryFileRead(d *schema.ResourceData, meta interface{}) d.Set("file", file) d.Set("sha", fc.GetSHA()) + log.Printf("[DEBUG] Fetching commit info for repository file: %s/%s/%s", org, repo, file) + commit, err := getFileCommit(client, org, repo, file, branch) + if err != nil { + return err + } + + d.Set("commit_author", commit.GetCommit().GetCommitter().GetName()) + d.Set("commit_email", commit.GetCommit().GetCommitter().GetEmail()) + d.Set("commit_message", commit.GetCommit().GetMessage()) + return nil } func resourceGithubRepositoryFileUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Owner).v3client - owner := meta.(*Owner).name + if err := checkOrganization(meta); err != nil { + return err + } + + client := meta.(*Organization).v3client + org := meta.(*Organization).name ctx := context.Background() repo := d.Get("repository").(string) file := d.Get("file").(string) branch := d.Get("branch").(string) - if err := checkRepositoryBranchExists(client, owner, repo, branch); err != nil { + if err := checkRepositoryBranchExists(client, org, repo, branch); err != nil { return err } @@ -229,22 +283,22 @@ func resourceGithubRepositoryFileUpdate(d *schema.ResourceData, meta interface{} opts.Message = &m } - log.Printf("[DEBUG] Updating content in repository file: %s/%s/%s", owner, repo, file) - resp, _, err := client.Repositories.CreateFile(ctx, owner, repo, file, opts) + log.Printf("[DEBUG] Updating content in repository file: %s/%s/%s", org, repo, file) + _, _, err = client.Repositories.CreateFile(ctx, org, repo, file, opts) if err != nil { return err } - d.Set("commit_author", resp.GetCommitter().GetName()) - d.Set("commit_email", resp.GetCommitter().GetEmail()) - d.Set("commit_message", resp.GetMessage()) - return resourceGithubRepositoryFileRead(d, meta) } func resourceGithubRepositoryFileDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Owner).v3client - owner := meta.(*Owner).name + if err := checkOrganization(meta); err != nil { + return err + } + + client := meta.(*Organization).v3client + org := meta.(*Organization).name ctx := context.Background() repo := d.Get("repository").(string) @@ -259,8 +313,8 @@ func resourceGithubRepositoryFileDelete(d *schema.ResourceData, meta interface{} Branch: &branch, } - log.Printf("[DEBUG] Deleting repository file: %s/%s/%s", owner, repo, file) - _, _, err := client.Repositories.DeleteFile(ctx, owner, repo, file, opts) + log.Printf("[DEBUG] Deleting repository file: %s/%s/%s", org, repo, file) + _, _, err := client.Repositories.DeleteFile(ctx, org, repo, file, opts) if err != nil { return nil } @@ -269,9 +323,9 @@ func resourceGithubRepositoryFileDelete(d *schema.ResourceData, meta interface{} } // checkRepositoryBranchExists tests if a branch exists in a repository. -func checkRepositoryBranchExists(client *github.Client, owner, repo, branch string) error { +func checkRepositoryBranchExists(client *github.Client, org, repo, branch string) error { ctx := context.WithValue(context.Background(), ctxId, buildTwoPartID(repo, branch)) - _, _, err := client.Repositories.GetBranch(ctx, owner, repo, branch) + _, _, err := client.Repositories.GetBranch(ctx, org, repo, branch) if err != nil { if ghErr, ok := err.(*github.ErrorResponse); ok { if ghErr.Response.StatusCode == http.StatusNotFound { @@ -285,15 +339,60 @@ func checkRepositoryBranchExists(client *github.Client, owner, repo, branch stri } // checkRepositoryFileExists tests if a file exists in a repository. -func checkRepositoryFileExists(client *github.Client, owner, repo, file, branch string) error { +func checkRepositoryFileExists(client *github.Client, org, 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}) + fc, _, _, err := client.Repositories.GetContents(ctx, org, 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 fmt.Errorf("File %s not a file in in repository %s/%s or repository is not readable", file, org, repo) } return nil } + +func getFileCommit(client *github.Client, org, repo, file, branch string) (*github.RepositoryCommit, error) { + ctx := context.WithValue(context.Background(), ctxId, fmt.Sprintf("%s/%s", repo, file)) + opts := &github.CommitsListOptions{ + SHA: branch, + } + allCommits := []*github.RepositoryCommit{} + for { + commits, resp, err := client.Repositories.ListCommits(ctx, org, 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, org, repo, sha) + if err != nil { + return nil, err + } + + for _, f := range rc.Files { + if f.GetFilename() == file && f.GetStatus() != "removed" { + log.Printf("[DEBUG] Found file: %s in commit: %s", file, sha) + return rc, nil + } + } + } + + return nil, fmt.Errorf("Cannot find file %s in repo %s/%s", file, org, repo) +} diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index a5fa318794..701d1d33bd 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -4,6 +4,7 @@ import ( "context" "log" "os" + "regexp" "strings" "encoding/base64" @@ -302,8 +303,10 @@ func TestAccGithubRepositoryFile_overwrite(t *testing.T) { var commit github.RepositoryCommit rn := "github_repository_file.foo" + path := ".gitignore" + fileContent := "**/.terraform/*" randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) - path := fmt.Sprintf("tf-acc-test-file-%s", randString) + repo := fmt.Sprintf("tf-acc-test-%s", randString) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -311,12 +314,18 @@ func TestAccGithubRepositoryFile_overwrite(t *testing.T) { CheckDestroy: testAccCheckGithubRepositoryFileDestroy, Steps: []resource.TestStep{ { - Config: testAccGithubRepositoryFileOverwriteConfig(), + Config: testAccGithubRepositoryFileOverwriteDisabledConfig(randString), + ExpectError: regexp.MustCompile(`Refusing to overwrite existing file`), + }, + { + Config: testAccGithubRepositoryFileOverwriteEnabledConfig(randString, path, fileContent), Check: resource.ComposeTestCheckFunc( - testAccCheckGithubRepositoryFileExists(rn, path, "master", &content, &commit), - testAccCheckGithubRepositoryFileAttributes(&content, &testAccGithubRepositoryFileExpectedAttributes{ - Content: base64.StdEncoding.EncodeToString([]byte("Terraform acceptance test file")) + "\n", - }), + testAccCheckGithubRepositoryFileExistsWithRepo(rn, path, "master", repo, &content, &commit), + testAccCheckGithubRepositoryFileAttributes( + &content, &testAccGithubRepositoryFileExpectedAttributes{ + Content: base64.StdEncoding.EncodeToString([]byte(fileContent)) + "\n", + }, + ), ), }, }, @@ -324,6 +333,11 @@ func TestAccGithubRepositoryFile_overwrite(t *testing.T) { } func testAccCheckGithubRepositoryFileExists(n, path, branch string, content *github.RepositoryContent, commit *github.RepositoryCommit) resource.TestCheckFunc { + hardCodedRepoName := "test-repo" + return testAccCheckGithubRepositoryFileExistsWithRepo(n, path, branch, hardCodedRepoName, content, commit) +} + +func testAccCheckGithubRepositoryFileExistsWithRepo(n, path, branch, repo string, content *github.RepositoryContent, commit *github.RepositoryCommit) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -339,7 +353,7 @@ func testAccCheckGithubRepositoryFileExists(n, path, branch string, content *git org := testAccProvider.Meta().(*Organization).name opts := &github.RepositoryContentGetOptions{Ref: branch} - gotContent, _, _, err := conn.Repositories.GetContents(context.TODO(), org, "test-repo", path, opts) + gotContent, _, _, err := conn.Repositories.GetContents(context.TODO(), org, repo, path, opts) if err != nil { return err } @@ -467,11 +481,10 @@ resource "github_repository_file" "foo" { `, file, content) } -func testAccGithubRepositoryFileOverwriteConfig() string { +func testAccGithubRepositoryFileOverwriteDisabledConfig(randString string) string { owner := os.Getenv("GITHUB_ORGANIZATION") repository := os.Getenv("GITHUB_TEMPLATE_REPOSITORY") - randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) return fmt.Sprintf(` resource "github_repository" "foo" { @@ -484,16 +497,9 @@ resource "github_repository" "foo" { repository = "%s" } - # So that acceptance tests can be run in a github organization - # with no billing - private = false - - has_issues = true - has_wiki = true - allow_merge_commit = true - allow_squash_merge = false - allow_rebase_merge = false - has_downloads = true + private = false + has_issues = false + has_wiki = false } @@ -507,3 +513,36 @@ resource "github_repository_file" "foo" { } `, randString, randString, owner, repository) } + +func testAccGithubRepositoryFileOverwriteEnabledConfig(randString, path, content string) string { + + owner := os.Getenv("GITHUB_ORGANIZATION") + templateRepository := os.Getenv("GITHUB_TEMPLATE_REPOSITORY") + + return fmt.Sprintf(` +resource "github_repository" "foo" { + name = "tf-acc-test-%s" + description = "Terraform acceptance tests %s" + homepage_url = "http://example.com/" + + template { + owner = "%s" + repository = "%s" + } + + private = false + has_issues = false + has_wiki = false +} + +resource "github_repository_file" "foo" { + repository = github_repository.foo.name + file = "%s" + content = "%s" + commit_message = "Managed by Terraform" + commit_author = "Terraform User" + commit_email = "terraform@example.com" + overwrite = true +} +`, randString, randString, owner, templateRepository, path, content) +} diff --git a/website/docs/r/repository_file.html.markdown b/website/docs/r/repository_file.html.markdown index 8dbbc1bdbb..61bb6da518 100644 --- a/website/docs/r/repository_file.html.markdown +++ b/website/docs/r/repository_file.html.markdown @@ -41,6 +41,7 @@ The following arguments are supported: * `commit_message` - (Optional) Commit message when adding or updating the managed file. +* `overwrite` - (Optional) Enable overwriting existing files ## Attributes Reference From c699d14dfa4c976b968534d860f7f9d169d89d36 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 16 May 2020 11:39:41 -0400 Subject: [PATCH 03/21] fixup! Reuse global variable --- github/resource_github_repository_file_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index 701d1d33bd..d987af0127 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -483,7 +483,7 @@ resource "github_repository_file" "foo" { func testAccGithubRepositoryFileOverwriteDisabledConfig(randString string) string { - owner := os.Getenv("GITHUB_ORGANIZATION") + owner := testOrganization repository := os.Getenv("GITHUB_TEMPLATE_REPOSITORY") return fmt.Sprintf(` @@ -516,7 +516,7 @@ resource "github_repository_file" "foo" { func testAccGithubRepositoryFileOverwriteEnabledConfig(randString, path, content string) string { - owner := os.Getenv("GITHUB_ORGANIZATION") + owner := testOrganization templateRepository := os.Getenv("GITHUB_TEMPLATE_REPOSITORY") return fmt.Sprintf(` From c9f63532136b17598de87e4e911d9ef211657767 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 08:31:26 -0400 Subject: [PATCH 04/21] start with minimal test --- .github/workflows/dotcom-acceptance-tests.yml | 5 +- .../resource_github_repository_file_test.go | 581 ++---------------- website/docs/r/repository_file.html.markdown | 16 + 3 files changed, 74 insertions(+), 528 deletions(-) diff --git a/.github/workflows/dotcom-acceptance-tests.yml b/.github/workflows/dotcom-acceptance-tests.yml index e5ee72cc32..d9e637d375 100644 --- a/.github/workflows/dotcom-acceptance-tests.yml +++ b/.github/workflows/dotcom-acceptance-tests.yml @@ -1,6 +1,7 @@ name: Dotcom Acceptance Tests on: + push: pull_request: types: [opened, synchronize, reopened] @@ -30,7 +31,7 @@ jobs: - name: Acceptance Tests (Individual) uses: terraformtesting/acceptance-tests@v2.0.0 with: - TF_LOG: INFO + TF_LOG: DEBUG GITHUB_OWNER: github-terraform-test-user GITHUB_TEST_USER_TOKEN: ${{ secrets.DOTCOM_TEST_USER_TOKEN }} GITHUB_TEST_ORGANIZATION: terraformtesting @@ -46,7 +47,7 @@ jobs: - name: Acceptance Tests (Organization) uses: terraformtesting/acceptance-tests@v2.0.0 with: - TF_LOG: INFO + TF_LOG: DEBUG GITHUB_ORGANIZATION: terraformtesting GITHUB_TEST_USER_TOKEN: ${{ secrets.DOTCOM_TEST_USER_TOKEN }} GITHUB_TEST_OWNER: github-terraform-test-user diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index d987af0127..1d9d1fe3af 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -1,548 +1,77 @@ package github import ( - "context" - "log" - "os" - "regexp" - "strings" - - "encoding/base64" "fmt" + "regexp" "testing" - "github.com/google/go-github/v31/github" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" ) -// The authenticated user's name used for commits should be exported as GITHUB_TEST_USER_NAME -var userName string = os.Getenv("GITHUB_TEST_USER_NAME") - -// The authenticated user's email address used for commits should be exported as GITHUB_TEST_USER_EMAIL -var userEmail string = os.Getenv("GITHUB_TEST_USER_EMAIL") - -func init() { - resource.AddTestSweepers("github_repository_file", &resource.Sweeper{ - Name: "github_repository_file", - F: testSweepRepositoryFiles, - }) - -} - -func testSweepRepositoryFiles(region string) error { - meta, err := sharedConfigForRegion(region) - if err != nil { - return err - } +func TestAccGithubRepositoryFile(t *testing.T) { - if err := testSweepDeleteRepositoryFiles(meta, "master"); err != nil { - return err - } + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - if err := testSweepDeleteRepositoryFiles(meta, "test-branch"); err != nil { - return err - } - - return nil -} + t.Run("create and manage files", func(t *testing.T) { -func testSweepDeleteRepositoryFiles(meta interface{}, branch string) error { - client := meta.(*Organization).v3client - org := meta.(*Organization).name + config := fmt.Sprintf(` - _, files, _, err := client.Repositories.GetContents( - context.TODO(), org, "test-repo", "", &github.RepositoryContentGetOptions{Ref: branch}) - if err != nil { - return err - } - - for _, f := range files { - if name := f.GetName(); strings.HasPrefix(name, "tf-acc-") { - log.Printf("Deleting repository file: %s, repo: %s/test-repo, branch: %s", name, org, branch) - opts := &github.RepositoryContentFileOptions{Branch: github.String(branch)} - if _, _, err := client.Repositories.DeleteFile(context.TODO(), org, "test-repo", name, opts); err != nil { - return err + resource "github_repository" "foo" { + name = "tf-acc-test-%s" + auto_init = true } - } - } - - return nil -} - -func TestAccGithubRepositoryFile_basic(t *testing.T) { - if userName == "" { - t.Skip("This test requires you to set the test user's name (set it by exporting GITHUB_TEST_USER_NAME)") - } - - if userEmail == "" { - t.Skip("This test requires you to set the test user's email address (set it by exporting GITHUB_TEST_USER_EMAIL)") - } - - var content github.RepositoryContent - var commit github.RepositoryCommit - - rn := "github_repository_file.foo" - randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) - path := fmt.Sprintf("tf-acc-test-file-%s", randString) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckGithubRepositoryFileDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubRepositoryFileConfig( - path, "Terraform acceptance test file"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubRepositoryFileExists(rn, path, "master", &content, &commit), - testAccCheckGithubRepositoryFileAttributes(&content, &testAccGithubRepositoryFileExpectedAttributes{ - Content: base64.StdEncoding.EncodeToString([]byte("Terraform acceptance test file")) + "\n", - }), - testAccCheckGithubRepositoryFileCommitAttributes(&commit, &testAccGithubRepositoryFileExpectedCommitAttributes{ - Branch: "master", - CommitAuthor: userName, - CommitEmail: userEmail, - CommitMessage: fmt.Sprintf("Add %s", path), - Filename: path, - }), - resource.TestCheckResourceAttr(rn, "repository", "test-repo"), - resource.TestCheckResourceAttr(rn, "branch", "master"), - resource.TestCheckResourceAttr(rn, "file", path), - resource.TestCheckResourceAttr(rn, "content", "Terraform acceptance test file"), - resource.TestCheckResourceAttr(rn, "commit_author", userName), - resource.TestCheckResourceAttr(rn, "commit_email", userEmail), - resource.TestCheckResourceAttr(rn, "commit_message", fmt.Sprintf("Add %s", path)), - ), - }, - { - Config: testAccGithubRepositoryFileConfig( - path, "Terraform acceptance test file updated"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubRepositoryFileExists(rn, path, "master", &content, &commit), - testAccCheckGithubRepositoryFileAttributes(&content, &testAccGithubRepositoryFileExpectedAttributes{ - Content: base64.StdEncoding.EncodeToString([]byte("Terraform acceptance test file updated")) + "\n", - }), - testAccCheckGithubRepositoryFileCommitAttributes(&commit, &testAccGithubRepositoryFileExpectedCommitAttributes{ - Branch: "master", - CommitAuthor: userName, - CommitEmail: userEmail, - CommitMessage: fmt.Sprintf("Update %s", path), - Filename: path, - }), - resource.TestCheckResourceAttr(rn, "repository", "test-repo"), - resource.TestCheckResourceAttr(rn, "branch", "master"), - resource.TestCheckResourceAttr(rn, "file", path), - resource.TestCheckResourceAttr(rn, "content", "Terraform acceptance test file updated"), - resource.TestCheckResourceAttr(rn, "commit_author", userName), - resource.TestCheckResourceAttr(rn, "commit_email", userEmail), - resource.TestCheckResourceAttr(rn, "commit_message", fmt.Sprintf("Update %s", path)), - ), - }, - { - ResourceName: rn, - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func TestAccGithubRepositoryFile_branch(t *testing.T) { - if userName == "" { - t.Skip("This test requires you to set the test user's name (set it by exporting GITHUB_TEST_USER_NAME)") - } - - if userEmail == "" { - t.Skip("This test requires you to set the test user's email address (set it by exporting GITHUB_TEST_USER_EMAIL)") - } - - var content github.RepositoryContent - var commit github.RepositoryCommit - - rn := "github_repository_file.foo" - randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) - path := fmt.Sprintf("tf-acc-test-file-%s", randString) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckGithubRepositoryFileDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubRepositoryFileBranchConfig( - path, "Terraform acceptance test file"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubRepositoryFileExists(rn, path, "test-branch", &content, &commit), - testAccCheckGithubRepositoryFileAttributes(&content, &testAccGithubRepositoryFileExpectedAttributes{ - Content: base64.StdEncoding.EncodeToString([]byte("Terraform acceptance test file")) + "\n", - }), - testAccCheckGithubRepositoryFileCommitAttributes(&commit, &testAccGithubRepositoryFileExpectedCommitAttributes{ - Branch: "test-branch", - CommitAuthor: userName, - CommitEmail: userEmail, - CommitMessage: fmt.Sprintf("Add %s", path), - Filename: path, - }), - resource.TestCheckResourceAttr(rn, "repository", "test-repo"), - resource.TestCheckResourceAttr(rn, "branch", "test-branch"), - resource.TestCheckResourceAttr(rn, "file", path), - resource.TestCheckResourceAttr(rn, "content", "Terraform acceptance test file"), - resource.TestCheckResourceAttr(rn, "commit_author", userName), - resource.TestCheckResourceAttr(rn, "commit_email", userEmail), - resource.TestCheckResourceAttr(rn, "commit_message", fmt.Sprintf("Add %s", path)), - ), - }, - { - Config: testAccGithubRepositoryFileBranchConfig( - path, "Terraform acceptance test file updated"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubRepositoryFileExists(rn, path, "test-branch", &content, &commit), - testAccCheckGithubRepositoryFileAttributes(&content, &testAccGithubRepositoryFileExpectedAttributes{ - Content: base64.StdEncoding.EncodeToString([]byte("Terraform acceptance test file updated")) + "\n", - }), - testAccCheckGithubRepositoryFileCommitAttributes(&commit, &testAccGithubRepositoryFileExpectedCommitAttributes{ - Branch: "test-branch", - CommitAuthor: userName, - CommitEmail: userEmail, - CommitMessage: fmt.Sprintf("Update %s", path), - Filename: path, - }), - resource.TestCheckResourceAttr(rn, "repository", "test-repo"), - resource.TestCheckResourceAttr(rn, "branch", "test-branch"), - resource.TestCheckResourceAttr(rn, "file", path), - resource.TestCheckResourceAttr(rn, "content", "Terraform acceptance test file updated"), - resource.TestCheckResourceAttr(rn, "commit_author", userName), - resource.TestCheckResourceAttr(rn, "commit_email", userEmail), - resource.TestCheckResourceAttr(rn, "commit_message", fmt.Sprintf("Update %s", path)), - ), - }, - { - ResourceName: rn, - ImportState: true, - ImportStateId: fmt.Sprintf("test-repo/%s:test-branch", path), - ImportStateVerify: true, - }, - }, - }) -} - -func TestAccGithubRepositoryFile_committer(t *testing.T) { - var content github.RepositoryContent - var commit github.RepositoryCommit - - rn := "github_repository_file.foo" - randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) - path := fmt.Sprintf("tf-acc-test-file-%s", randString) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckGithubRepositoryFileDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubRepositoryFileCommitterConfig( - path, "Terraform acceptance test file"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubRepositoryFileExists(rn, path, "master", &content, &commit), - testAccCheckGithubRepositoryFileAttributes(&content, &testAccGithubRepositoryFileExpectedAttributes{ - Content: base64.StdEncoding.EncodeToString([]byte("Terraform acceptance test file")) + "\n", - }), - testAccCheckGithubRepositoryFileCommitAttributes(&commit, &testAccGithubRepositoryFileExpectedCommitAttributes{ - Branch: "master", - CommitAuthor: "Terraform User", - CommitEmail: "terraform@example.com", - CommitMessage: "Managed by Terraform", - Filename: path, - }), - resource.TestCheckResourceAttr(rn, "repository", "test-repo"), - resource.TestCheckResourceAttr(rn, "branch", "master"), - resource.TestCheckResourceAttr(rn, "file", path), - resource.TestCheckResourceAttr(rn, "content", "Terraform acceptance test file"), - resource.TestCheckResourceAttr(rn, "commit_author", "Terraform User"), - resource.TestCheckResourceAttr(rn, "commit_email", "terraform@example.com"), - resource.TestCheckResourceAttr(rn, "commit_message", "Managed by Terraform"), - ), - }, - { - Config: testAccGithubRepositoryFileCommitterConfig( - path, "Terraform acceptance test file updated"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubRepositoryFileExists(rn, path, "master", &content, &commit), - testAccCheckGithubRepositoryFileAttributes(&content, &testAccGithubRepositoryFileExpectedAttributes{ - Content: base64.StdEncoding.EncodeToString([]byte("Terraform acceptance test file updated")) + "\n", - }), - testAccCheckGithubRepositoryFileCommitAttributes(&commit, &testAccGithubRepositoryFileExpectedCommitAttributes{ - Branch: "master", - CommitAuthor: "Terraform User", - CommitEmail: "terraform@example.com", - CommitMessage: "Managed by Terraform", - Filename: path, - }), - resource.TestCheckResourceAttr(rn, "repository", "test-repo"), - resource.TestCheckResourceAttr(rn, "branch", "master"), - resource.TestCheckResourceAttr(rn, "file", path), - resource.TestCheckResourceAttr(rn, "content", "Terraform acceptance test file updated"), - resource.TestCheckResourceAttr(rn, "commit_author", "Terraform User"), - resource.TestCheckResourceAttr(rn, "commit_email", "terraform@example.com"), - resource.TestCheckResourceAttr(rn, "commit_message", "Managed by Terraform"), - ), - }, - { - ResourceName: rn, - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func TestAccGithubRepositoryFile_overwrite(t *testing.T) { - var content github.RepositoryContent - var commit github.RepositoryCommit - - rn := "github_repository_file.foo" - path := ".gitignore" - fileContent := "**/.terraform/*" - randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) - repo := fmt.Sprintf("tf-acc-test-%s", randString) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckGithubRepositoryFileDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubRepositoryFileOverwriteDisabledConfig(randString), - ExpectError: regexp.MustCompile(`Refusing to overwrite existing file`), - }, - { - Config: testAccGithubRepositoryFileOverwriteEnabledConfig(randString, path, fileContent), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubRepositoryFileExistsWithRepo(rn, path, "master", repo, &content, &commit), - testAccCheckGithubRepositoryFileAttributes( - &content, &testAccGithubRepositoryFileExpectedAttributes{ - Content: base64.StdEncoding.EncodeToString([]byte(fileContent)) + "\n", - }, - ), - ), - }, - }, - }) -} - -func testAccCheckGithubRepositoryFileExists(n, path, branch string, content *github.RepositoryContent, commit *github.RepositoryCommit) resource.TestCheckFunc { - hardCodedRepoName := "test-repo" - return testAccCheckGithubRepositoryFileExistsWithRepo(n, path, branch, hardCodedRepoName, content, commit) -} - -func testAccCheckGithubRepositoryFileExistsWithRepo(n, path, branch, repo string, content *github.RepositoryContent, commit *github.RepositoryCommit) resource.TestCheckFunc { - return func(s *terraform.State) error { - - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not Found: %s", n) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("No repository file path set") - } - - conn := testAccProvider.Meta().(*Organization).v3client - org := testAccProvider.Meta().(*Organization).name - - opts := &github.RepositoryContentGetOptions{Ref: branch} - gotContent, _, _, err := conn.Repositories.GetContents(context.TODO(), org, repo, path, opts) - if err != nil { - return err - } - - gotCommit, err := getFileCommit(conn, org, "test-repo", path, branch) - if err != nil { - return err - } - - *content = *gotContent - *commit = *gotCommit - - return nil - } -} -type testAccGithubRepositoryFileExpectedAttributes struct { - Content string -} - -func testAccCheckGithubRepositoryFileAttributes(content *github.RepositoryContent, want *testAccGithubRepositoryFileExpectedAttributes) resource.TestCheckFunc { - return func(s *terraform.State) error { - - if *content.Content != want.Content { - return fmt.Errorf("got content %q; want %q", *content.Content, want.Content) - } - - return nil - } -} - -type testAccGithubRepositoryFileExpectedCommitAttributes struct { - Branch string - CommitAuthor string - CommitEmail string - CommitMessage string - Filename string -} - -func testAccCheckGithubRepositoryFileCommitAttributes(commit *github.RepositoryCommit, want *testAccGithubRepositoryFileExpectedCommitAttributes) resource.TestCheckFunc { - return func(s *terraform.State) error { - - if name := commit.GetCommit().GetCommitter().GetName(); name != want.CommitAuthor { - return fmt.Errorf("got committer author name %q; want %q", name, want.CommitAuthor) - } - - if email := commit.GetCommit().GetCommitter().GetEmail(); email != want.CommitEmail { - return fmt.Errorf("got committer author email %q; want %q", email, want.CommitEmail) - } - - if message := commit.GetCommit().GetMessage(); message != want.CommitMessage { - return fmt.Errorf("got commit message %q; want %q", message, want.CommitMessage) - } - - if len(commit.Files) != 1 { - return fmt.Errorf("got multiple files in commit (%q); expected 1", len(commit.Files)) - } - - file := commit.Files[0] - if filename := file.GetFilename(); filename != want.Filename { - return fmt.Errorf("got filename %q; want %q", filename, want.Filename) - } - - return nil - } -} - -func testAccCheckGithubRepositoryFileDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*Organization).v3client - org := testAccProvider.Meta().(*Organization).name - - for _, rs := range s.RootModule().Resources { - if rs.Type != "github_repository_file" { - continue - } - - repo, file := splitRepoFilePath(rs.Primary.ID) - opts := &github.RepositoryContentGetOptions{Ref: rs.Primary.Attributes["branch"]} - - fc, _, resp, err := conn.Repositories.GetContents(context.TODO(), org, repo, file, opts) - if err == nil { - if fc != nil { - return fmt.Errorf("Repository file %s/%s/%s still exists", org, repo, file) + resource "github_repository_file" "foo" { + repository = github_repository.foo.name + branch = "master" + file = "%s" + content = "%s" + commit_message = "Managed by Terraform" + commit_author = "Terraform User" + commit_email = "terraform@example.com" + overwrite = true } - } - if resp.StatusCode != 404 { - return err - } - return nil - } - return nil -} - -func testAccGithubRepositoryFileConfig(file, content string) string { - return fmt.Sprintf(` -resource "github_repository_file" "foo" { - repository = "test-repo" - file = "%s" - content = "%s" -} -`, file, content) -} - -func testAccGithubRepositoryFileBranchConfig(file, content string) string { - return fmt.Sprintf(` -resource "github_repository_file" "foo" { - repository = "test-repo" - branch = "test-branch" - file = "%s" - content = "%s" -} -`, file, content) -} - -func testAccGithubRepositoryFileCommitterConfig(file, content string) string { - return fmt.Sprintf(` -resource "github_repository_file" "foo" { - repository = "test-repo" - file = "%s" - content = "%s" - commit_message = "Managed by Terraform" - commit_author = "Terraform User" - commit_email = "terraform@example.com" -} -`, file, content) -} - -func testAccGithubRepositoryFileOverwriteDisabledConfig(randString string) string { - - owner := testOrganization - repository := os.Getenv("GITHUB_TEMPLATE_REPOSITORY") - return fmt.Sprintf(` -resource "github_repository" "foo" { - name = "tf-acc-test-%s" - description = "Terraform acceptance tests %s" - homepage_url = "http://example.com/" - - template { - owner = "%s" - repository = "%s" - } - - private = false - has_issues = false - has_wiki = false - -} - -resource "github_repository_file" "foo" { - repository = github_repository.foo.name - file = ".gitignore" - content = "**/.terraform/*" - commit_message = "Managed by Terraform" - commit_author = "Terraform User" - commit_email = "terraform@example.com" -} -`, randString, randString, owner, repository) -} - -func testAccGithubRepositoryFileOverwriteEnabledConfig(randString, path, content string) string { + resource "github_repository_file" "gitignore" { + repository = "example" + file = ".gitignore" + content = "**/*.tfstate" + } - owner := testOrganization - templateRepository := os.Getenv("GITHUB_TEMPLATE_REPOSITORY") + `, randomID) + + check := resource.ComposeTestCheckFunc( + resource.TestMatchResourceAttr( + "github_repository_file.test", "url", + regexp.MustCompile(randomID+"/projects/1"), + ), + ) + + 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, + }, + }, + }) + } - return fmt.Sprintf(` -resource "github_repository" "foo" { - name = "tf-acc-test-%s" - description = "Terraform acceptance tests %s" - homepage_url = "http://example.com/" + t.Run("with an anonymous account", func(t *testing.T) { + t.Skip("anonymous account not supported for this operation") + }) - template { - owner = "%s" - repository = "%s" - } + t.Run("with an individual account", func(t *testing.T) { + testCase(t, individual) + }) - private = false - has_issues = false - has_wiki = false -} + t.Run("with an organization account", func(t *testing.T) { + testCase(t, organization) + }) -resource "github_repository_file" "foo" { - repository = github_repository.foo.name - file = "%s" - content = "%s" - commit_message = "Managed by Terraform" - commit_author = "Terraform User" - commit_email = "terraform@example.com" - overwrite = true -} -`, randString, randString, owner, templateRepository, path, content) + }) } diff --git a/website/docs/r/repository_file.html.markdown b/website/docs/r/repository_file.html.markdown index 61bb6da518..fad866c180 100644 --- a/website/docs/r/repository_file.html.markdown +++ b/website/docs/r/repository_file.html.markdown @@ -14,6 +14,22 @@ GitHub repository. ## Example Usage ```hcl +resource "github_repository" "foo" { + name = "tf-acc-test-%s" + auto_init = true +} + +resource "github_repository_file" "foo" { + repository = github_repository.foo.name + branch = "master" + file = "%s" + content = "%s" + commit_message = "Managed by Terraform" + commit_author = "Terraform User" + commit_email = "terraform@example.com" + overwrite = true +} + resource "github_repository_file" "gitignore" { repository = "example" file = ".gitignore" From acf649b1b0d0bf508bd634617bf9a5af6cbd2217 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 08:37:32 -0400 Subject: [PATCH 05/21] fix compile errors --- github/resource_github_repository_file.go | 20 +++++++++---------- .../resource_github_repository_file_test.go | 4 ++-- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/github/resource_github_repository_file.go b/github/resource_github_repository_file.go index 79f647a8e1..bf4c6cd72d 100644 --- a/github/resource_github_repository_file.go +++ b/github/resource_github_repository_file.go @@ -31,8 +31,8 @@ func resourceGithubRepositoryFile() *schema.Resource { branch = parts[1] } - client := meta.(*Organization).v3client - org := meta.(*Organization).name + client := meta.(*Owner).v3client + org := meta.(*Owner).name repo, file := splitRepoFilePath(parts[0]) if err := checkRepositoryFileExists(client, org, repo, file, branch); err != nil { return nil, err @@ -146,8 +146,8 @@ func resourceGithubRepositoryFileCreate(d *schema.ResourceData, meta interface{} return err } - client := meta.(*Organization).v3client - org := meta.(*Organization).name + client := meta.(*Owner).v3client + org := meta.(*Owner).name ctx := context.Background() repo := d.Get("repository").(string) @@ -212,8 +212,8 @@ func resourceGithubRepositoryFileRead(d *schema.ResourceData, meta interface{}) return err } - client := meta.(*Organization).v3client - org := meta.(*Organization).name + client := meta.(*Owner).v3client + org := meta.(*Owner).name ctx := context.WithValue(context.Background(), ctxId, d.Id()) repo, file := splitRepoFilePath(d.Id()) @@ -261,8 +261,8 @@ func resourceGithubRepositoryFileUpdate(d *schema.ResourceData, meta interface{} return err } - client := meta.(*Organization).v3client - org := meta.(*Organization).name + client := meta.(*Owner).v3client + org := meta.(*Owner).name ctx := context.Background() repo := d.Get("repository").(string) @@ -297,8 +297,8 @@ func resourceGithubRepositoryFileDelete(d *schema.ResourceData, meta interface{} return err } - client := meta.(*Organization).v3client - org := meta.(*Organization).name + client := meta.(*Owner).v3client + org := meta.(*Owner).name ctx := context.Background() repo := d.Get("repository").(string) diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index 1d9d1fe3af..34aeb80cad 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -5,8 +5,8 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform/helper/acctest" - "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" ) func TestAccGithubRepositoryFile(t *testing.T) { From 0b9cba69342653662664432c29b1b5f27192e487 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 08:38:59 -0400 Subject: [PATCH 06/21] more compile errors --- github/resource_github_repository_file_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index 34aeb80cad..1eb0fca906 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -25,8 +25,8 @@ func TestAccGithubRepositoryFile(t *testing.T) { resource "github_repository_file" "foo" { repository = github_repository.foo.name branch = "master" - file = "%s" - content = "%s" + file = "foo" + content = "bar" commit_message = "Managed by Terraform" commit_author = "Terraform User" commit_email = "terraform@example.com" From 54cde81ed8973a3ec289cab2f1e6370b353dd999 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 08:39:22 -0400 Subject: [PATCH 07/21] no need to run on push with synchronize --- .github/workflows/dotcom-acceptance-tests.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/dotcom-acceptance-tests.yml b/.github/workflows/dotcom-acceptance-tests.yml index d9e637d375..ada23eff26 100644 --- a/.github/workflows/dotcom-acceptance-tests.yml +++ b/.github/workflows/dotcom-acceptance-tests.yml @@ -1,7 +1,6 @@ name: Dotcom Acceptance Tests on: - push: pull_request: types: [opened, synchronize, reopened] From bab96d6caa3bc2e54b136d5a97810d0cd65c8988 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 08:44:29 -0400 Subject: [PATCH 08/21] remove uses of checkOrganization the new test format addresses this explicitly instead --- github/resource_github_repository_file.go | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/github/resource_github_repository_file.go b/github/resource_github_repository_file.go index bf4c6cd72d..82b811e689 100644 --- a/github/resource_github_repository_file.go +++ b/github/resource_github_repository_file.go @@ -142,9 +142,6 @@ func resourceGithubRepositoryFileOptions(d *schema.ResourceData) (*github.Reposi } func resourceGithubRepositoryFileCreate(d *schema.ResourceData, meta interface{}) error { - if err := checkOrganization(meta); err != nil { - return err - } client := meta.(*Owner).v3client org := meta.(*Owner).name @@ -207,10 +204,6 @@ func resourceGithubRepositoryFileCreate(d *schema.ResourceData, meta interface{} } func resourceGithubRepositoryFileRead(d *schema.ResourceData, meta interface{}) error { - err := checkOrganization(meta) - if err != nil { - return err - } client := meta.(*Owner).v3client org := meta.(*Owner).name @@ -257,9 +250,6 @@ func resourceGithubRepositoryFileRead(d *schema.ResourceData, meta interface{}) } func resourceGithubRepositoryFileUpdate(d *schema.ResourceData, meta interface{}) error { - if err := checkOrganization(meta); err != nil { - return err - } client := meta.(*Owner).v3client org := meta.(*Owner).name @@ -293,9 +283,6 @@ func resourceGithubRepositoryFileUpdate(d *schema.ResourceData, meta interface{} } func resourceGithubRepositoryFileDelete(d *schema.ResourceData, meta interface{}) error { - if err := checkOrganization(meta); err != nil { - return err - } client := meta.(*Owner).v3client org := meta.(*Owner).name From cdcdd893b2e9c2569403236fb72322eb2bf77379 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 08:55:06 -0400 Subject: [PATCH 09/21] declare branch explicitly to work around error > Branch master not found in repository or repository is not readable --- .../resource_github_repository_file_test.go | 99 ++++++++++++++++--- 1 file changed, 83 insertions(+), 16 deletions(-) diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index 1eb0fca906..5e3326881e 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -17,28 +17,33 @@ func TestAccGithubRepositoryFile(t *testing.T) { config := fmt.Sprintf(` - resource "github_repository" "foo" { - name = "tf-acc-test-%s" - auto_init = true + + resource "github_repository" "test" { + name = "tf-acc-test-%s" + auto_init = true } - resource "github_repository_file" "foo" { - repository = github_repository.foo.name - branch = "master" - file = "foo" - content = "bar" - commit_message = "Managed by Terraform" - commit_author = "Terraform User" - commit_email = "terraform@example.com" - overwrite = true + resource "github_branch" "test" { + repository = github_repository.test.id + branch = "tf-acc-test-%[1]s" } - resource "github_repository_file" "gitignore" { - repository = "example" - file = ".gitignore" - content = "**/*.tfstate" + resource "github_repository_file" "test" { + repository = github_repository.test.name + branch = github_branch.test.branch + file = "test" + content = "bar" + commit_message = "Managed by Terraform" + commit_author = "Terraform User" + commit_email = "terraform@example.com" + overwrite = true } + resource "github_repository_file" "gitignore" { + repository = github_repository.test.name + file = ".gitignore" + content = "**/*.tfstate" + } `, randomID) check := resource.ComposeTestCheckFunc( @@ -74,4 +79,66 @@ func TestAccGithubRepositoryFile(t *testing.T) { }) }) + + // t.Run("can be configured to overwrite files on create", func(t *testing.T) { + // + // config := fmt.Sprintf(` + // + // resource "github_repository" "foo" { + // name = "tf-acc-test-%s" + // auto_init = true + // } + // + // resource "github_repository_file" "foo" { + // repository = github_repository.foo.name + // branch = "master" + // file = "foo" + // content = "bar" + // commit_message = "Managed by Terraform" + // commit_author = "Terraform User" + // commit_email = "terraform@example.com" + // overwrite = true + // } + // + // resource "github_repository_file" "gitignore" { + // repository = "example" + // file = ".gitignore" + // content = "**/*.tfstate" + // } + // + // `, randomID) + // + // check := resource.ComposeTestCheckFunc( + // resource.TestMatchResourceAttr( + // "github_repository_file.test", "url", + // regexp.MustCompile(randomID+"/projects/1"), + // ), + // ) + // + // 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) + // }) + // + // }) } From d29f1db43e210a30c79e9b47c242fbc24056f8aa Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 09:24:26 -0400 Subject: [PATCH 10/21] simplify resources --- .../resource_github_repository_file_test.go | 21 ++++--------------- 1 file changed, 4 insertions(+), 17 deletions(-) diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index 5e3326881e..c4122353d0 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -2,7 +2,6 @@ package github import ( "fmt" - "regexp" "testing" "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" @@ -17,20 +16,14 @@ func TestAccGithubRepositoryFile(t *testing.T) { config := fmt.Sprintf(` - resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true } - resource "github_branch" "test" { - repository = github_repository.test.id - branch = "tf-acc-test-%[1]s" - } - resource "github_repository_file" "test" { repository = github_repository.test.name - branch = github_branch.test.branch + branch = "main" file = "test" content = "bar" commit_message = "Managed by Terraform" @@ -38,18 +31,12 @@ func TestAccGithubRepositoryFile(t *testing.T) { commit_email = "terraform@example.com" overwrite = true } - - resource "github_repository_file" "gitignore" { - repository = github_repository.test.name - file = ".gitignore" - content = "**/*.tfstate" - } `, randomID) check := resource.ComposeTestCheckFunc( - resource.TestMatchResourceAttr( - "github_repository_file.test", "url", - regexp.MustCompile(randomID+"/projects/1"), + resource.TestCheckResourceAttr( + "github_repository_file.test", "content", + "bar", ), ) From e9f8b3fb5ff3145a60d80ffee890fe0260c01c31 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 09:53:59 -0400 Subject: [PATCH 11/21] test for sha as well --- github/resource_github_repository_file_test.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index c4122353d0..60492789f5 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -12,7 +12,7 @@ func TestAccGithubRepositoryFile(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("create and manage files", func(t *testing.T) { + t.Run("creates and manages files", func(t *testing.T) { config := fmt.Sprintf(` @@ -29,7 +29,6 @@ func TestAccGithubRepositoryFile(t *testing.T) { commit_message = "Managed by Terraform" commit_author = "Terraform User" commit_email = "terraform@example.com" - overwrite = true } `, randomID) @@ -38,6 +37,10 @@ func TestAccGithubRepositoryFile(t *testing.T) { "github_repository_file.test", "content", "bar", ), + resource.TestCheckResourceAttr( + "github_repository_file.test", "sha", + "ba0e162e1c47469e3fe4b393a8bf8c569f302116", + ), ) testCase := func(t *testing.T, mode string) { From e9150c5ec3290137d3ec63acfaece27e8f112fa3 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 09:56:57 -0400 Subject: [PATCH 12/21] can be configured to overwrite files on create --- .../resource_github_repository_file_test.go | 116 +++++++++--------- website/docs/r/repository_file.html.markdown | 12 +- 2 files changed, 58 insertions(+), 70 deletions(-) diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index 60492789f5..bb64543274 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -70,65 +70,59 @@ func TestAccGithubRepositoryFile(t *testing.T) { }) - // t.Run("can be configured to overwrite files on create", func(t *testing.T) { - // - // config := fmt.Sprintf(` - // - // resource "github_repository" "foo" { - // name = "tf-acc-test-%s" - // auto_init = true - // } - // - // resource "github_repository_file" "foo" { - // repository = github_repository.foo.name - // branch = "master" - // file = "foo" - // content = "bar" - // commit_message = "Managed by Terraform" - // commit_author = "Terraform User" - // commit_email = "terraform@example.com" - // overwrite = true - // } - // - // resource "github_repository_file" "gitignore" { - // repository = "example" - // file = ".gitignore" - // content = "**/*.tfstate" - // } - // - // `, randomID) - // - // check := resource.ComposeTestCheckFunc( - // resource.TestMatchResourceAttr( - // "github_repository_file.test", "url", - // regexp.MustCompile(randomID+"/projects/1"), - // ), - // ) - // - // 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) - // }) - // - // }) + t.Run("can be configured to overwrite files on create", func(t *testing.T) { + + config := fmt.Sprintf(` + + resource "github_repository" "foo" { + name = "tf-acc-test-%s" + auto_init = true + } + + resource "github_repository_file" "foo" { + repository = github_repository.foo.name + branch = "main" + file = "foo" + content = "bar" + overwrite = true + } + `, randomID) + + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_file.test", "content", + "bar", + ), + resource.TestCheckResourceAttr( + "github_repository_file.test", "sha", + "ba0e162e1c47469e3fe4b393a8bf8c569f302116", + ), + ) + + 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) + }) + + }) } diff --git a/website/docs/r/repository_file.html.markdown b/website/docs/r/repository_file.html.markdown index fad866c180..340945723e 100644 --- a/website/docs/r/repository_file.html.markdown +++ b/website/docs/r/repository_file.html.markdown @@ -21,20 +21,14 @@ resource "github_repository" "foo" { resource "github_repository_file" "foo" { repository = github_repository.foo.name - branch = "master" - file = "%s" - content = "%s" + branch = "main" + file = ".gitignore" + content = "**/*.tfstate" commit_message = "Managed by Terraform" commit_author = "Terraform User" commit_email = "terraform@example.com" overwrite = true } - -resource "github_repository_file" "gitignore" { - repository = "example" - file = ".gitignore" - content = "**/*.tfstate" -} ``` From 04bb261456178266cb0c310586b0e6e373468828 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 10:01:10 -0400 Subject: [PATCH 13/21] correct resource name in hcl --- github/resource_github_repository_file_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index bb64543274..aec45f3d22 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -74,13 +74,13 @@ func TestAccGithubRepositoryFile(t *testing.T) { config := fmt.Sprintf(` - resource "github_repository" "foo" { + resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true } - resource "github_repository_file" "foo" { - repository = github_repository.foo.name + resource "github_repository_file" "test" { + repository = github_repository.test.name branch = "main" file = "foo" content = "bar" From 07ce4c71c13fbbf95e998886b1487e24d312fc18 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 10:05:31 -0400 Subject: [PATCH 14/21] add before and after checking --- .../resource_github_repository_file_test.go | 40 ++++++++++++++----- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index aec45f3d22..a04c370077 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -2,6 +2,7 @@ package github import ( "fmt" + "strings" "testing" "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" @@ -84,20 +85,33 @@ func TestAccGithubRepositoryFile(t *testing.T) { branch = "main" file = "foo" content = "bar" - overwrite = true + overwrite = false } `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository_file.test", "content", - "bar", + checks := map[string]resource.TestCheckFunc{ + "before": resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_file.test", "content", + "bar", + ), + resource.TestCheckResourceAttr( + "github_repository_file.test", "sha", + "ba0e162e1c47469e3fe4b393a8bf8c569f302116", + ), ), - resource.TestCheckResourceAttr( - "github_repository_file.test", "sha", - "ba0e162e1c47469e3fe4b393a8bf8c569f302116", + + "after": resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_file.test", "content", + "bar", + ), + resource.TestCheckResourceAttr( + "github_repository_file.test", "sha", + "ba0e162e1c47469e3fe4b393a8bf8c569f302116", + ), ), - ) + } testCase := func(t *testing.T, mode string) { resource.Test(t, resource.TestCase{ @@ -106,7 +120,13 @@ func TestAccGithubRepositoryFile(t *testing.T) { Steps: []resource.TestStep{ { Config: config, - Check: check, + Check: checks["before"], + }, + { + Config: strings.Replace(config, + "overwrite = false", + "overwrite = true", 1), + Check: checks["after"], }, }, }) From bf1225e88dfb1b170416b4ad7be2141c318b683b Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 15:27:55 -0400 Subject: [PATCH 15/21] test both overwrite states --- .../resource_github_repository_file_test.go | 41 +++++++------------ 1 file changed, 14 insertions(+), 27 deletions(-) diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index a04c370077..df3f0aedb0 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -2,6 +2,7 @@ package github import ( "fmt" + "regexp" "strings" "testing" @@ -74,7 +75,6 @@ func TestAccGithubRepositoryFile(t *testing.T) { t.Run("can be configured to overwrite files on create", func(t *testing.T) { config := fmt.Sprintf(` - resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true @@ -83,35 +83,22 @@ func TestAccGithubRepositoryFile(t *testing.T) { resource "github_repository_file" "test" { repository = github_repository.test.name branch = "main" - file = "foo" - content = "bar" + file = "README.md" + content = "overwrite" overwrite = false } `, randomID) - checks := map[string]resource.TestCheckFunc{ - "before": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository_file.test", "content", - "bar", - ), - resource.TestCheckResourceAttr( - "github_repository_file.test", "sha", - "ba0e162e1c47469e3fe4b393a8bf8c569f302116", - ), + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_file.test", "content", + "bar", ), - - "after": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository_file.test", "content", - "bar", - ), - resource.TestCheckResourceAttr( - "github_repository_file.test", "sha", - "ba0e162e1c47469e3fe4b393a8bf8c569f302116", - ), + resource.TestCheckResourceAttr( + "github_repository_file.test", "sha", + "ba0e162e1c47469e3fe4b393a8bf8c569f302116", ), - } + ) testCase := func(t *testing.T, mode string) { resource.Test(t, resource.TestCase{ @@ -119,14 +106,14 @@ func TestAccGithubRepositoryFile(t *testing.T) { Providers: testAccProviders, Steps: []resource.TestStep{ { - Config: config, - Check: checks["before"], + Config: config, + ExpectError: regexp.MustCompile(`Not Found`), }, { Config: strings.Replace(config, "overwrite = false", "overwrite = true", 1), - Check: checks["after"], + Check: check, }, }, }) From 1f63c3795730b8a5524625b2a7e3198fb729bcb8 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 15:31:18 -0400 Subject: [PATCH 16/21] add expected error message --- github/resource_github_repository_file_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index df3f0aedb0..9f2bf34a7e 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -107,7 +107,7 @@ func TestAccGithubRepositoryFile(t *testing.T) { Steps: []resource.TestStep{ { Config: config, - ExpectError: regexp.MustCompile(`Not Found`), + ExpectError: regexp.MustCompile(`Refusing to overwrite existing file`), }, { Config: strings.Replace(config, From 4d2862db2ffdec4a131c4c6d20daa5a421060aa4 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 15:39:26 -0400 Subject: [PATCH 17/21] add expected file content --- github/resource_github_repository_file_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index 9f2bf34a7e..c6074ae1df 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -84,7 +84,7 @@ func TestAccGithubRepositoryFile(t *testing.T) { repository = github_repository.test.name branch = "main" file = "README.md" - content = "overwrite" + content = "overwritten" overwrite = false } `, randomID) @@ -92,7 +92,7 @@ func TestAccGithubRepositoryFile(t *testing.T) { check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( "github_repository_file.test", "content", - "bar", + "overwritten", ), resource.TestCheckResourceAttr( "github_repository_file.test", "sha", From abc196f251b35ec83e615224391ac8d5e7be81b9 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 16:20:53 -0400 Subject: [PATCH 18/21] add expected sha --- github/resource_github_repository_file_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index c6074ae1df..d124ddfeca 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -96,7 +96,7 @@ func TestAccGithubRepositoryFile(t *testing.T) { ), resource.TestCheckResourceAttr( "github_repository_file.test", "sha", - "ba0e162e1c47469e3fe4b393a8bf8c569f302116", + "67c1a95c2d9bb138aefeaebb319cca82e531736b", ), ) From 27929d9b3bc2b9c06eb2c4fcbc3d132e52de1e2d Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 16:26:23 -0400 Subject: [PATCH 19/21] rebrand to `overwrite_on_create` --- github/resource_github_repository_file.go | 8 ++++---- .../resource_github_repository_file_test.go | 15 +++++++------- website/docs/r/repository_file.html.markdown | 20 ++++++++++--------- 3 files changed, 23 insertions(+), 20 deletions(-) diff --git a/github/resource_github_repository_file.go b/github/resource_github_repository_file.go index 82b811e689..13a76dc9e5 100644 --- a/github/resource_github_repository_file.go +++ b/github/resource_github_repository_file.go @@ -40,7 +40,7 @@ func resourceGithubRepositoryFile() *schema.Resource { d.SetId(fmt.Sprintf("%s/%s", repo, file)) d.Set("branch", branch) - d.Set("overwrite", false) + d.Set("overwrite_on_create", false) return []*schema.ResourceData{d}, nil }, @@ -94,7 +94,7 @@ func resourceGithubRepositoryFile() *schema.Resource { Computed: true, Description: "The blob SHA of the file", }, - "overwrite": { + "overwrite_on_create": { Type: schema.TypeBool, Optional: true, Description: "Enable overwriting existing files, defaults to \"false\"", @@ -181,13 +181,13 @@ func resourceGithubRepositoryFileCreate(d *schema.ResourceData, meta interface{} } if fileContent != nil { - if d.Get("overwrite").(bool) { + if d.Get("overwrite_on_create").(bool) { // Overwrite existing file if requested by configuring the options for // `client.Repositories.CreateFile` to match the existing file's SHA opts.SHA = fileContent.SHA } else { // Error if overwriting a file is not requested - return fmt.Errorf("[ERROR] Refusing to overwrite existing file. Configure `overwrite` to `true` to override.") + return fmt.Errorf("[ERROR] Refusing to overwrite existing file. Configure `overwrite_on_create` to `true` to override.") } } diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index d124ddfeca..3515d45f55 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -81,12 +81,13 @@ func TestAccGithubRepositoryFile(t *testing.T) { } resource "github_repository_file" "test" { - repository = github_repository.test.name - branch = "main" - file = "README.md" - content = "overwritten" - overwrite = false + repository = github_repository.test.name + branch = "main" + file = "README.md" + content = "overwritten" + overwrite_on_create = false } + `, randomID) check := resource.ComposeTestCheckFunc( @@ -111,8 +112,8 @@ func TestAccGithubRepositoryFile(t *testing.T) { }, { Config: strings.Replace(config, - "overwrite = false", - "overwrite = true", 1), + "overwrite_on_create = false", + "overwrite_on_create = true", 1), Check: check, }, }, diff --git a/website/docs/r/repository_file.html.markdown b/website/docs/r/repository_file.html.markdown index 340945723e..0e0a6f58e9 100644 --- a/website/docs/r/repository_file.html.markdown +++ b/website/docs/r/repository_file.html.markdown @@ -14,21 +14,23 @@ GitHub repository. ## Example Usage ```hcl + resource "github_repository" "foo" { name = "tf-acc-test-%s" auto_init = true } resource "github_repository_file" "foo" { - repository = github_repository.foo.name - branch = "main" - file = ".gitignore" - content = "**/*.tfstate" - commit_message = "Managed by Terraform" - commit_author = "Terraform User" - commit_email = "terraform@example.com" - overwrite = true + repository = github_repository.foo.name + branch = "main" + file = ".gitignore" + content = "**/*.tfstate" + commit_message = "Managed by Terraform" + commit_author = "Terraform User" + commit_email = "terraform@example.com" + overwrite_on_create = true } + ``` @@ -51,7 +53,7 @@ The following arguments are supported: * `commit_message` - (Optional) Commit message when adding or updating the managed file. -* `overwrite` - (Optional) Enable overwriting existing files +* `overwrite_on_create` - (Optional) Enable overwriting existing files ## Attributes Reference From fcae103dee8a8c115873245524320173e5c5ebde Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 17:08:47 -0400 Subject: [PATCH 20/21] revert to info logging --- .github/workflows/dotcom-acceptance-tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/dotcom-acceptance-tests.yml b/.github/workflows/dotcom-acceptance-tests.yml index ada23eff26..e5ee72cc32 100644 --- a/.github/workflows/dotcom-acceptance-tests.yml +++ b/.github/workflows/dotcom-acceptance-tests.yml @@ -30,7 +30,7 @@ jobs: - name: Acceptance Tests (Individual) uses: terraformtesting/acceptance-tests@v2.0.0 with: - TF_LOG: DEBUG + TF_LOG: INFO GITHUB_OWNER: github-terraform-test-user GITHUB_TEST_USER_TOKEN: ${{ secrets.DOTCOM_TEST_USER_TOKEN }} GITHUB_TEST_ORGANIZATION: terraformtesting @@ -46,7 +46,7 @@ jobs: - name: Acceptance Tests (Organization) uses: terraformtesting/acceptance-tests@v2.0.0 with: - TF_LOG: DEBUG + TF_LOG: INFO GITHUB_ORGANIZATION: terraformtesting GITHUB_TEST_USER_TOKEN: ${{ secrets.DOTCOM_TEST_USER_TOKEN }} GITHUB_TEST_OWNER: github-terraform-test-user From 331b6de5b54a3bbee4b51bbbf35cb42ef69429d1 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Sat, 3 Oct 2020 17:11:59 -0400 Subject: [PATCH 21/21] rename org to owner --- github/resource_github_repository_file.go | 62 +++++++++++------------ 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/github/resource_github_repository_file.go b/github/resource_github_repository_file.go index 13a76dc9e5..c6b82661c6 100644 --- a/github/resource_github_repository_file.go +++ b/github/resource_github_repository_file.go @@ -32,9 +32,9 @@ func resourceGithubRepositoryFile() *schema.Resource { } client := meta.(*Owner).v3client - org := meta.(*Owner).name + owner := meta.(*Owner).name repo, file := splitRepoFilePath(parts[0]) - if err := checkRepositoryFileExists(client, org, repo, file, branch); err != nil { + if err := checkRepositoryFileExists(client, owner, repo, file, branch); err != nil { return nil, err } @@ -144,14 +144,14 @@ func resourceGithubRepositoryFileOptions(d *schema.ResourceData) (*github.Reposi func resourceGithubRepositoryFileCreate(d *schema.ResourceData, meta interface{}) error { client := meta.(*Owner).v3client - org := meta.(*Owner).name + owner := meta.(*Owner).name ctx := context.Background() repo := d.Get("repository").(string) file := d.Get("file").(string) branch := d.Get("branch").(string) - if err := checkRepositoryBranchExists(client, org, repo, branch); err != nil { + if err := checkRepositoryBranchExists(client, owner, repo, branch); err != nil { return err } @@ -165,9 +165,9 @@ func resourceGithubRepositoryFileCreate(d *schema.ResourceData, meta interface{} opts.Message = &m } - log.Printf("[DEBUG] Checking if overwriting a repository file: %s/%s/%s in branch: %s", org, repo, file, branch) + log.Printf("[DEBUG] Checking if overwriting a repository file: %s/%s/%s in branch: %s", owner, repo, file, branch) checkOpt := github.RepositoryContentGetOptions{Ref: branch} - fileContent, _, resp, err := client.Repositories.GetContents(ctx, org, repo, file, &checkOpt) + fileContent, _, resp, err := client.Repositories.GetContents(ctx, owner, repo, file, &checkOpt) if err != nil { if resp != nil { if resp.StatusCode != 404 { @@ -192,8 +192,8 @@ func resourceGithubRepositoryFileCreate(d *schema.ResourceData, meta interface{} } // Create a new or overwritten file - log.Printf("[DEBUG] Creating repository file: %s/%s/%s in branch: %s", org, repo, file, branch) - _, _, err = client.Repositories.CreateFile(ctx, org, repo, file, opts) + log.Printf("[DEBUG] Creating repository file: %s/%s/%s in branch: %s", owner, repo, file, branch) + _, _, err = client.Repositories.CreateFile(ctx, owner, repo, file, opts) if err != nil { return err } @@ -206,22 +206,22 @@ func resourceGithubRepositoryFileCreate(d *schema.ResourceData, meta interface{} func resourceGithubRepositoryFileRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*Owner).v3client - org := meta.(*Owner).name + owner := meta.(*Owner).name ctx := context.WithValue(context.Background(), ctxId, d.Id()) repo, file := splitRepoFilePath(d.Id()) branch := d.Get("branch").(string) - if err := checkRepositoryBranchExists(client, org, repo, branch); err != nil { + if err := checkRepositoryBranchExists(client, owner, repo, branch); err != nil { return err } - log.Printf("[DEBUG] Reading repository file: %s/%s/%s, branch: %s", org, repo, file, branch) + log.Printf("[DEBUG] Reading repository file: %s/%s/%s, branch: %s", owner, repo, file, branch) opts := &github.RepositoryContentGetOptions{Ref: branch} - fc, _, _, _ := client.Repositories.GetContents(ctx, org, repo, file, opts) + fc, _, _, _ := client.Repositories.GetContents(ctx, owner, repo, file, opts) if fc == nil { log.Printf("[WARN] Removing repository path %s/%s/%s from state because it no longer exists in GitHub", - org, repo, file) + owner, repo, file) d.SetId("") return nil } @@ -236,8 +236,8 @@ func resourceGithubRepositoryFileRead(d *schema.ResourceData, meta interface{}) d.Set("file", file) d.Set("sha", fc.GetSHA()) - log.Printf("[DEBUG] Fetching commit info for repository file: %s/%s/%s", org, repo, file) - commit, err := getFileCommit(client, org, repo, file, branch) + log.Printf("[DEBUG] Fetching commit info for repository file: %s/%s/%s", owner, repo, file) + commit, err := getFileCommit(client, owner, repo, file, branch) if err != nil { return err } @@ -252,14 +252,14 @@ func resourceGithubRepositoryFileRead(d *schema.ResourceData, meta interface{}) func resourceGithubRepositoryFileUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*Owner).v3client - org := meta.(*Owner).name + owner := meta.(*Owner).name ctx := context.Background() repo := d.Get("repository").(string) file := d.Get("file").(string) branch := d.Get("branch").(string) - if err := checkRepositoryBranchExists(client, org, repo, branch); err != nil { + if err := checkRepositoryBranchExists(client, owner, repo, branch); err != nil { return err } @@ -273,8 +273,8 @@ func resourceGithubRepositoryFileUpdate(d *schema.ResourceData, meta interface{} opts.Message = &m } - log.Printf("[DEBUG] Updating content in repository file: %s/%s/%s", org, repo, file) - _, _, err = client.Repositories.CreateFile(ctx, org, repo, file, opts) + log.Printf("[DEBUG] Updating content in repository file: %s/%s/%s", owner, repo, file) + _, _, err = client.Repositories.CreateFile(ctx, owner, repo, file, opts) if err != nil { return err } @@ -285,7 +285,7 @@ func resourceGithubRepositoryFileUpdate(d *schema.ResourceData, meta interface{} func resourceGithubRepositoryFileDelete(d *schema.ResourceData, meta interface{}) error { client := meta.(*Owner).v3client - org := meta.(*Owner).name + owner := meta.(*Owner).name ctx := context.Background() repo := d.Get("repository").(string) @@ -300,8 +300,8 @@ func resourceGithubRepositoryFileDelete(d *schema.ResourceData, meta interface{} Branch: &branch, } - log.Printf("[DEBUG] Deleting repository file: %s/%s/%s", org, repo, file) - _, _, err := client.Repositories.DeleteFile(ctx, org, repo, file, opts) + log.Printf("[DEBUG] Deleting repository file: %s/%s/%s", owner, repo, file) + _, _, err := client.Repositories.DeleteFile(ctx, owner, repo, file, opts) if err != nil { return nil } @@ -310,9 +310,9 @@ func resourceGithubRepositoryFileDelete(d *schema.ResourceData, meta interface{} } // checkRepositoryBranchExists tests if a branch exists in a repository. -func checkRepositoryBranchExists(client *github.Client, org, repo, branch string) error { +func checkRepositoryBranchExists(client *github.Client, owner, repo, branch string) error { ctx := context.WithValue(context.Background(), ctxId, buildTwoPartID(repo, branch)) - _, _, err := client.Repositories.GetBranch(ctx, org, repo, branch) + _, _, err := client.Repositories.GetBranch(ctx, owner, repo, branch) if err != nil { if ghErr, ok := err.(*github.ErrorResponse); ok { if ghErr.Response.StatusCode == http.StatusNotFound { @@ -326,27 +326,27 @@ func checkRepositoryBranchExists(client *github.Client, org, repo, branch string } // checkRepositoryFileExists tests if a file exists in a repository. -func checkRepositoryFileExists(client *github.Client, org, repo, file, branch string) error { +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, org, repo, file, &github.RepositoryContentGetOptions{Ref: branch}) + 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, org, repo) + 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, org, repo, file, branch string) (*github.RepositoryCommit, error) { +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, } allCommits := []*github.RepositoryCommit{} for { - commits, resp, err := client.Repositories.ListCommits(ctx, org, repo, opts) + commits, resp, err := client.Repositories.ListCommits(ctx, owner, repo, opts) if err != nil { return nil, err } @@ -368,7 +368,7 @@ func getFileCommit(client *github.Client, org, repo, file, branch string) (*gith continue } - rc, _, err := client.Repositories.GetCommit(ctx, org, repo, sha) + rc, _, err := client.Repositories.GetCommit(ctx, owner, repo, sha) if err != nil { return nil, err } @@ -381,5 +381,5 @@ func getFileCommit(client *github.Client, org, repo, file, branch string) (*gith } } - return nil, fmt.Errorf("Cannot find file %s in repo %s/%s", file, org, repo) + return nil, fmt.Errorf("Cannot find file %s in repo %s/%s", file, owner, repo) }