-
Notifications
You must be signed in to change notification settings - Fork 772
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add repository file resource #318
Merged
jcudit
merged 1 commit into
integrations:master
from
shoekstra:add_repository_file_resource
Feb 11, 2020
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 <repository>/<file path> (when branch is \"master\") or <repository>/<file path>:<branch>") | ||
} | ||
|
||
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) { | ||
shoekstra marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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 = &git.luolix.topmitAuthor{Name: &name, Email: &mail} | ||
opts.Committer = &git.luolix.topmitAuthor{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, &git.luolix.topmitsListOptions{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) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
parseTwoPartID
function can be used for this.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I considered
parseTwoPartID
until I saw that the error returned is quite specific and doesn't apply to what I'm parsing. AsparseTwoPartID
is used in a couple of other funcs I decided if I was going to refactor the returned error it probably needs it's own PR/discussion.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've got a PR at #313 to address that problem too, so if you switch to it now when that is merged your code will have to be updated to provide the proper labels for the left/right halves of the ID.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good - what's the delay with merging #313? Feels a bit odd to amend the commit to include broken code, maybe better to wait until #313 is merged and then rebase this PR?