From 0b1ad74db7359903196dab54d79622c73682e436 Mon Sep 17 00:00:00 2001 From: Stephen Hoekstra Date: Wed, 18 Dec 2019 11:11:57 +0100 Subject: [PATCH] Add github_repository_file resource Signed-off-by: Stephen Hoekstra --- README.md | 4 + github/provider.go | 1 + github/resource_github_repository_file.go | 350 ++++++++++++++ .../resource_github_repository_file_test.go | 442 ++++++++++++++++++ github/util.go | 5 + website/docs/r/repository_file.html.markdown | 64 +++ 6 files changed, 866 insertions(+) create mode 100644 github/resource_github_repository_file.go create mode 100644 github/resource_github_repository_file_test.go create mode 100644 website/docs/r/repository_file.html.markdown diff --git a/README.md b/README.md index 3f2228bd60..022468e647 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,7 @@ In the organization you are using above, create the following test repositories: * The website url should be `http://www.example.com` * Create two topics within the repo named `test-topic` and `second-test-topic` * In the repo settings, make sure all features and merge button options are enabled. + * Create a `test-branch` branch * `test-repo-template` * Configure the repository to be a [Template repository](https://help.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-template-repository) @@ -103,3 +104,6 @@ Export your github username (the one you used to create the personal access toke different github username as `GITHUB_TEST_COLLABORATOR`. Please note that these usernames cannot be the same as each other, and both of them must be real github usernames. The collaborator user does not need to be added as a collaborator to your test repo or organization, but as the acceptance tests do real things (and will trigger some notifications for this user), you should probably make sure the person you specify knows that you're doing this just to be nice. + +Additionally the user exported as `GITHUB_TEST_USER` should have a public email address configured in their profile; this should be exported +as `GITHUB_TEST_USER_EMAIL` and the Github name exported as `GITHUB_TEST_USER_NAME` (this could be different to your GitHub login). diff --git a/github/provider.go b/github/provider.go index 4e317af53b..1bcd2a8c8d 100644 --- a/github/provider.go +++ b/github/provider.go @@ -55,6 +55,7 @@ func Provider() terraform.ResourceProvider { "github_project_column": resourceGithubProjectColumn(), "github_repository_collaborator": resourceGithubRepositoryCollaborator(), "github_repository_deploy_key": resourceGithubRepositoryDeployKey(), + "github_repository_file": resourceGithubRepositoryFile(), "github_repository_project": resourceGithubRepositoryProject(), "github_repository_webhook": resourceGithubRepositoryWebhook(), "github_repository": resourceGithubRepository(), diff --git a/github/resource_github_repository_file.go b/github/resource_github_repository_file.go new file mode 100644 index 0000000000..4d6c4a3884 --- /dev/null +++ b/github/resource_github_repository_file.go @@ -0,0 +1,350 @@ +package github + +import ( + "context" + "log" + "net/http" + "strings" + + "fmt" + + "github.com/google/go-github/v28/github" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceGithubRepositoryFile() *schema.Resource { + return &schema.Resource{ + Create: resourceGithubRepositoryFileCreate, + Read: resourceGithubRepositoryFileRead, + Update: resourceGithubRepositoryFileUpdate, + Delete: resourceGithubRepositoryFileDelete, + Importer: &schema.ResourceImporter{ + State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + parts := strings.Split(d.Id(), ":") + branch := "master" + + if len(parts) > 2 { + return nil, fmt.Errorf("Invalid ID specified. Supplied ID must be written as / (when branch is \"master\") or /:") + } + + if len(parts) == 2 { + branch = parts[1] + } + + client := meta.(*Organization).client + org := meta.(*Organization).name + repo, file := splitRepoFilePath(parts[0]) + 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) + + return []*schema.ResourceData{d}, nil + }, + }, + + Schema: map[string]*schema.Schema{ + "repository": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "The repository name", + }, + "file": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "The file path to manage", + }, + "content": { + Type: schema.TypeString, + Required: true, + Description: "The file's content", + }, + "branch": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: "The branch name, defaults to \"master\"", + Default: "master", + }, + "commit_message": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "The commit message when creating or updating the file", + }, + "commit_author": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "The commit author name, defaults to the authenticated user's name", + }, + "commit_email": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "The commit author email address, defaults to the authenticated user's email address", + }, + "sha": { + Type: schema.TypeString, + Computed: true, + Description: "The blob SHA of the file", + }, + }, + } +} + +func resourceGithubRepositoryFileOptions(d *schema.ResourceData) (*github.RepositoryContentFileOptions, error) { + opts := &github.RepositoryContentFileOptions{ + Content: []byte(*github.String(d.Get("content").(string))), + Branch: github.String(d.Get("branch").(string)), + } + + if commitMessage, hasCommitMessage := d.GetOk("commit_message"); hasCommitMessage { + opts.Message = new(string) + *opts.Message = commitMessage.(string) + } + + if SHA, hasSHA := d.GetOk("sha"); hasSHA { + opts.SHA = new(string) + *opts.SHA = SHA.(string) + } + + commitAuthor, hasCommitAuthor := d.GetOk("commit_author") + commitEmail, hasCommitEmail := d.GetOk("commit_email") + + if hasCommitAuthor && !hasCommitEmail { + return nil, fmt.Errorf("Cannot set commit_author without setting commit_email") + } + + if hasCommitEmail && !hasCommitAuthor { + return nil, fmt.Errorf("Cannot set commit_email without setting commit_author") + } + + if hasCommitAuthor && hasCommitEmail { + name := commitAuthor.(string) + mail := commitEmail.(string) + opts.Author = &github.CommitAuthor{Name: &name, Email: &mail} + opts.Committer = &github.CommitAuthor{Name: &name, Email: &mail} + } + + return opts, nil +} + +func resourceGithubRepositoryFileCreate(d *schema.ResourceData, meta interface{}) error { + if err := checkOrganization(meta); err != nil { + return err + } + + client := meta.(*Organization).client + 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, org, repo, branch); err != nil { + return err + } + + opts, err := resourceGithubRepositoryFileOptions(d) + if err != nil { + return err + } + + if opts.Message == nil { + m := fmt.Sprintf("Add %s", file) + opts.Message = &m + } + + 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.SetId(fmt.Sprintf("%s/%s", repo, file)) + + return resourceGithubRepositoryFileRead(d, meta) +} + +func resourceGithubRepositoryFileRead(d *schema.ResourceData, meta interface{}) error { + err := checkOrganization(meta) + if err != nil { + return err + } + + client := meta.(*Organization).client + 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, org, repo, branch); err != nil { + return err + } + + 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, 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", + org, repo, file) + d.SetId("") + return nil + } + + content, err := fc.GetContent() + if err != nil { + return err + } + + d.Set("content", content) + d.Set("repository", repo) + d.Set("file", file) + d.Set("sha", fc.SHA) + + 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.Commit.Committer.GetName()) + d.Set("commit_email", commit.Commit.Committer.GetEmail()) + d.Set("commit_message", commit.Commit.GetMessage()) + + return nil +} + +func resourceGithubRepositoryFileUpdate(d *schema.ResourceData, meta interface{}) error { + if err := checkOrganization(meta); err != nil { + return err + } + + client := meta.(*Organization).client + 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, org, repo, branch); err != nil { + return err + } + + opts, err := resourceGithubRepositoryFileOptions(d) + if err != nil { + return err + } + + if *opts.Message == fmt.Sprintf("Add %s", file) { + m := fmt.Sprintf("Update %s", file) + 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) + if err != nil { + return err + } + + return resourceGithubRepositoryFileRead(d, meta) +} + +func resourceGithubRepositoryFileDelete(d *schema.ResourceData, meta interface{}) error { + if err := checkOrganization(meta); err != nil { + return err + } + + client := meta.(*Organization).client + org := meta.(*Organization).name + ctx := context.Background() + + repo := d.Get("repository").(string) + file := d.Get("file").(string) + branch := d.Get("branch").(string) + + message := fmt.Sprintf("Delete %s", file) + sha := d.Get("sha").(string) + opts := &github.RepositoryContentFileOptions{ + Message: &message, + SHA: &sha, + Branch: &branch, + } + + 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 + } + + return nil +} + +// checkRepositoryBranchExists tests if a branch exists in a repository. +func checkRepositoryBranchExists(client *github.Client, org, repo, branch string) error { + ctx := context.WithValue(context.Background(), ctxId, buildTwoPartID(&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 { + return fmt.Errorf("Branch %s not found in repository or repository is not readable", branch) + } + } + return err + } + + return nil +} + +// checkRepositoryFileExists tests if a file exists in a repository. +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, 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, 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)) + commits, _, err := client.Repositories.ListCommits(ctx, org, repo, &github.CommitsListOptions{SHA: branch}) + if err != nil { + return nil, err + } + + for _, c := range commits { + 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 new file mode 100644 index 0000000000..afab092271 --- /dev/null +++ b/github/resource_github_repository_file_test.go @@ -0,0 +1,442 @@ +package github + +import ( + "context" + "log" + "os" + "strings" + + "encoding/base64" + "fmt" + "testing" + + "github.com/google/go-github/v28/github" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +// 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 + } + + if err := testSweepDeleteRepositoryFiles(meta, "master"); err != nil { + return err + } + + if err := testSweepDeleteRepositoryFiles(meta, "test-branch"); err != nil { + return err + } + + return nil +} + +func testSweepDeleteRepositoryFiles(meta interface{}, branch string) error { + client := meta.(*Organization).client + 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 strings.HasPrefix(*f.Name, "tf-acc-") { + log.Printf("Deleting repository file: %s, repo: %s/test-repo, branch: %s", *f.Name, org, branch) + opts := &github.RepositoryContentFileOptions{Branch: github.String(branch)} + if _, _, err := client.Repositories.DeleteFile(context.TODO(), org, "test-repo", *f.Name, opts); err != nil { + return err + } + } + } + + 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 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) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No repository file path set") + } + + conn := testAccProvider.Meta().(*Organization).client + org := testAccProvider.Meta().(*Organization).name + + opts := &github.RepositoryContentGetOptions{Ref: branch} + gotContent, _, _, err := conn.Repositories.GetContents(context.TODO(), org, "test-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 commit.Commit.Committer.GetName() != want.CommitAuthor { + return fmt.Errorf("got committer author name %q; want %q", commit.Commit.Committer.GetName(), want.CommitAuthor) + } + + if commit.Commit.Committer.GetEmail() != want.CommitEmail { + return fmt.Errorf("got committer author email %q; want %q", commit.Commit.Committer.GetEmail(), want.CommitEmail) + } + + if commit.Commit.GetMessage() != want.CommitMessage { + return fmt.Errorf("got commit message %q; want %q", commit.Commit.GetMessage(), 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 file.GetFilename() != want.Filename { + return fmt.Errorf("got filename %q; want %q", file.GetFilename(), want.Filename) + } + + return nil + } +} + +func testAccCheckGithubRepositoryFileDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*Organization).client + 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) + } + } + 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) +} diff --git a/github/util.go b/github/util.go index 1a17d3e528..c9f711778d 100644 --- a/github/util.go +++ b/github/util.go @@ -105,3 +105,8 @@ func validateTeamIDFunc(v interface{}, keyName string) (we []string, errors []er return } + +func splitRepoFilePath(path string) (string, string) { + parts := strings.Split(path, "/") + return parts[0], strings.Join(parts[1:], "/") +} diff --git a/website/docs/r/repository_file.html.markdown b/website/docs/r/repository_file.html.markdown new file mode 100644 index 0000000000..bd24a97101 --- /dev/null +++ b/website/docs/r/repository_file.html.markdown @@ -0,0 +1,64 @@ +--- +layout: "github" +page_title: "GitHub: github_repository_file" +description: |- + Creates and manages files within a GitHub repository +--- + +# github_repository_file + +This resource allows you to create and manage files within a +GitHub repository. + + +## Example Usage + +```hcl +resource "github_repository_file" "gitignore" { + repository = "example" + file = ".gitignore" + content = "**/*.tfstate" +} +``` + + +## Argument Reference + +The following arguments are supported: + +* `repo` - (Required) The repository to create the file in. + +* `file` - (Required) The path of the file to manage. + +* `content` - (Required) The file content. + +* `branch` - (Optional) Git branch (defaults to `master`). + The branch must already exist, it willl not be created if it does not already exist. + +* `commit_author` - (Optional) Committer author name to use. + +* `commit_email` - (Optional) Committer email address to use. + +* `commit_message` - (Optional) Commit message when adding or updating the managed file. + + +## Attributes Reference + +The following additional attributes are exported: + +* `sha` - The SHA blob of the file. + + +## Import + +Repository files can be imported using a combination of the `repo` and `file`, e.g. + +``` +$ terraform import github_repository.gitignore example/.gitignore +``` + +To import a file from a branch other than master, append `:` and the branch name, e.g. + +``` +$ terraform import github_repository.gitignore example/.gitignore:dev +```