| 1 |
// Copyright 2018 The go-github AUTHORS. All rights reserved. |
| 2 |
// |
| 3 |
// Use of this source code is governed by a BSD-style |
| 4 |
// license that can be found in the LICENSE file. |
| 5 |
|
| 6 |
// The commitpr command utilizes go-github as a CLI tool for |
| 7 |
// pushing files to a branch and creating a pull request from it. |
| 8 |
// It takes an auth token as an environment variable and creates |
| 9 |
// the commit and the PR under the account affiliated with that token. |
| 10 |
// |
| 11 |
// The purpose of this example is to show how to use refs, trees and commits to |
| 12 |
// create commits and pull requests. |
| 13 |
// |
| 14 |
// Note, if you want to push a single file, you probably prefer to use the |
| 15 |
// content API. An example is available here: |
| 16 |
// https://godoc.org/github.com/google/go-github/github#example-RepositoriesService-CreateFile |
| 17 |
// |
| 18 |
// Note, for this to work at least 1 commit is needed, so you if you use this |
| 19 |
// after creating a repository you might want to make sure you set `AutoInit` to |
| 20 |
// `true`. |
| 21 |
package main |
| 22 |
|
| 23 |
import ( |
| 24 |
"bytes" |
| 25 |
"context" |
| 26 |
"errors" |
| 27 |
"flag" |
| 28 |
"fmt" |
| 29 |
"io" |
| 30 |
"log" |
| 31 |
"os" |
| 32 |
"strings" |
| 33 |
"time" |
| 34 |
|
| 35 |
"github.com/ProtonMail/go-crypto/openpgp" |
| 36 |
"github.com/google/go-github/v60/github" |
| 37 |
) |
| 38 |
|
| 39 |
var ( |
| 40 |
sourceOwner = flag.String("source-owner", "", "Name of the owner (user or org) of the repo to create the commit in.") |
| 41 |
sourceRepo = flag.String("source-repo", "", "Name of repo to create the commit in.") |
| 42 |
commitMessage = flag.String("commit-message", "", "Content of the commit message.") |
| 43 |
commitBranch = flag.String("commit-branch", "", "Name of branch to create the commit in. If it does not already exists, it will be created using the `base-branch` parameter") |
| 44 |
repoBranch = flag.String("repo-branch", "", "Name of the repository where the changes in the pull request were made. This field is required for cross-repository pull requests if both repositories are owned by the same organization") |
| 45 |
baseBranch = flag.String("base-branch", "master", "Name of branch to create the `commit-branch` from.") |
| 46 |
prRepoOwner = flag.String("merge-repo-owner", "", "Name of the owner (user or org) of the repo to create the PR against. If not specified, the value of the `-source-owner` flag will be used.") |
| 47 |
prRepo = flag.String("merge-repo", "", "Name of repo to create the PR against. If not specified, the value of the `-source-repo` flag will be used.") |
| 48 |
prBranch = flag.String("merge-branch", "master", "Name of branch to create the PR against (the one you want to merge your branch in via the PR).") |
| 49 |
prSubject = flag.String("pr-title", "", "Title of the pull request. If not specified, no pull request will be created.") |
| 50 |
prDescription = flag.String("pr-text", "", "Text to put in the description of the pull request.") |
| 51 |
sourceFiles = flag.String("files", "", `Comma-separated list of files to commit and their location. |
| 52 |
The local file is separated by its target location by a semi-colon. |
| 53 |
If the file should be in the same location with the same name, you can just put the file name and omit the repetition. |
| 54 |
Example: README.md,main.go:github/examples/commitpr/main.go`) |
| 55 |
authorName = flag.String("author-name", "", "Name of the author of the commit.") |
| 56 |
authorEmail = flag.String("author-email", "", "Email of the author of the commit.") |
| 57 |
privateKey = flag.String("private-key", "", "Path to the private key to use to sign the commit.") |
| 58 |
) |
| 59 |
|
| 60 |
var client *github.Client |
| 61 |
var ctx = context.Background() |
| 62 |
|
| 63 |
// getRef returns the commit branch reference object if it exists or creates it |
| 64 |
// from the base branch before returning it. |
| 65 |
func getRef() (ref *github.Reference, err error) { |
| 66 |
if ref, _, err = client.Git.GetRef(ctx, *sourceOwner, *sourceRepo, "refs/heads/"+*commitBranch); err == nil { |
| 67 |
return ref, nil |
| 68 |
} |
| 69 |
|
| 70 |
// We consider that an error means the branch has not been found and needs to |
| 71 |
// be created. |
| 72 |
if *commitBranch == *baseBranch { |
| 73 |
return nil, errors.New("the commit branch does not exist but `-base-branch` is the same as `-commit-branch`") |
| 74 |
} |
| 75 |
|
| 76 |
if *baseBranch == "" { |
| 77 |
return nil, errors.New("the `-base-branch` should not be set to an empty string when the branch specified by `-commit-branch` does not exists") |
| 78 |
} |
| 79 |
|
| 80 |
var baseRef *github.Reference |
| 81 |
if baseRef, _, err = client.Git.GetRef(ctx, *sourceOwner, *sourceRepo, "refs/heads/"+*baseBranch); err != nil { |
| 82 |
return nil, err |
| 83 |
} |
| 84 |
newRef := &github.Reference{Ref: github.String("refs/heads/" + *commitBranch), Object: &github.GitObject{SHA: baseRef.Object.SHA}} |
| 85 |
ref, _, err = client.Git.CreateRef(ctx, *sourceOwner, *sourceRepo, newRef) |
| 86 |
return ref, err |
| 87 |
} |
| 88 |
|
| 89 |
// getTree generates the tree to commit based on the given files and the commit |
| 90 |
// of the ref you got in getRef. |
| 91 |
func getTree(ref *github.Reference) (tree *github.Tree, err error) { |
| 92 |
// Create a tree with what to commit. |
| 93 |
entries := []*github.TreeEntry{} |
| 94 |
|
| 95 |
// Load each file into the tree. |
| 96 |
for _, fileArg := range strings.Split(*sourceFiles, ",") { |
| 97 |
file, content, err := getFileContent(fileArg) |
| 98 |
if err != nil { |
| 99 |
return nil, err |
| 100 |
} |
| 101 |
entries = append(entries, &github.TreeEntry{Path: github.String(file), Type: github.String("blob"), Content: github.String(string(content)), Mode: github.String("100644")}) |
| 102 |
} |
| 103 |
|
| 104 |
tree, _, err = client.Git.CreateTree(ctx, *sourceOwner, *sourceRepo, *ref.Object.SHA, entries) |
| 105 |
return tree, err |
| 106 |
} |
| 107 |
|
| 108 |
// getFileContent loads the local content of a file and return the target name |
| 109 |
// of the file in the target repository and its contents. |
| 110 |
func getFileContent(fileArg string) (targetName string, b []byte, err error) { |
| 111 |
var localFile string |
| 112 |
files := strings.Split(fileArg, ":") |
| 113 |
switch { |
| 114 |
case len(files) < 1: |
| 115 |
return "", nil, errors.New("empty `-files` parameter") |
| 116 |
case len(files) == 1: |
| 117 |
localFile = files[0] |
| 118 |
targetName = files[0] |
| 119 |
default: |
| 120 |
localFile = files[0] |
| 121 |
targetName = files[1] |
| 122 |
} |
| 123 |
|
| 124 |
b, err = os.ReadFile(localFile) |
| 125 |
return targetName, b, err |
| 126 |
} |
| 127 |
|
| 128 |
// pushCommit creates the commit in the given reference using the given tree. |
| 129 |
func pushCommit(ref *github.Reference, tree *github.Tree) (err error) { |
| 130 |
// Get the parent commit to attach the commit to. |
| 131 |
parent, _, err := client.Repositories.GetCommit(ctx, *sourceOwner, *sourceRepo, *ref.Object.SHA, nil) |
| 132 |
if err != nil { |
| 133 |
return err |
| 134 |
} |
| 135 |
// This is not always populated, but is needed. |
| 136 |
parent.Commit.SHA = parent.SHA |
| 137 |
|
| 138 |
// Create the commit using the tree. |
| 139 |
date := time.Now() |
| 140 |
author := &github.CommitAuthor{Date: &github.Timestamp{Time: date}, Name: authorName, Email: authorEmail} |
| 141 |
commit := &github.Commit{Author: author, Message: commitMessage, Tree: tree, Parents: []*github.Commit{parent.Commit}} |
| 142 |
opts := github.CreateCommitOptions{} |
| 143 |
if *privateKey != "" { |
| 144 |
armoredBlock, e := os.ReadFile(*privateKey) |
| 145 |
if e != nil { |
| 146 |
return e |
| 147 |
} |
| 148 |
keyring, e := openpgp.ReadArmoredKeyRing(bytes.NewReader(armoredBlock)) |
| 149 |
if e != nil { |
| 150 |
return e |
| 151 |
} |
| 152 |
if len(keyring) != 1 { |
| 153 |
return errors.New("expected exactly one key in the keyring") |
| 154 |
} |
| 155 |
key := keyring[0] |
| 156 |
opts.Signer = github.MessageSignerFunc(func(w io.Writer, r io.Reader) error { |
| 157 |
return openpgp.ArmoredDetachSign(w, key, r, nil) |
| 158 |
}) |
| 159 |
} |
| 160 |
newCommit, _, err := client.Git.CreateCommit(ctx, *sourceOwner, *sourceRepo, commit, &opts) |
| 161 |
if err != nil { |
| 162 |
return err |
| 163 |
} |
| 164 |
|
| 165 |
// Attach the commit to the master branch. |
| 166 |
ref.Object.SHA = newCommit.SHA |
| 167 |
_, _, err = client.Git.UpdateRef(ctx, *sourceOwner, *sourceRepo, ref, false) |
| 168 |
return err |
| 169 |
} |
| 170 |
|
| 171 |
// createPR creates a pull request. Based on: https://godoc.org/github.com/google/go-github/github#example-PullRequestsService-Create |
| 172 |
func createPR() (err error) { |
| 173 |
if *prSubject == "" { |
| 174 |
return errors.New("missing `-pr-title` flag; skipping PR creation") |
| 175 |
} |
| 176 |
|
| 177 |
if *prRepoOwner != "" && *prRepoOwner != *sourceOwner { |
| 178 |
*commitBranch = fmt.Sprintf("%s:%s", *sourceOwner, *commitBranch) |
| 179 |
} else { |
| 180 |
prRepoOwner = sourceOwner |
| 181 |
} |
| 182 |
|
| 183 |
if *prRepo == "" { |
| 184 |
prRepo = sourceRepo |
| 185 |
} |
| 186 |
|
| 187 |
newPR := &github.NewPullRequest{ |
| 188 |
Title: prSubject, |
| 189 |
Head: commitBranch, |
| 190 |
HeadRepo: repoBranch, |
| 191 |
Base: prBranch, |
| 192 |
Body: prDescription, |
| 193 |
MaintainerCanModify: github.Bool(true), |
| 194 |
} |
| 195 |
|
| 196 |
pr, _, err := client.PullRequests.Create(ctx, *prRepoOwner, *prRepo, newPR) |
| 197 |
if err != nil { |
| 198 |
return err |
| 199 |
} |
| 200 |
|
| 201 |
fmt.Printf("PR created: %s\n", pr.GetHTMLURL()) |
| 202 |
return nil |
| 203 |
} |
| 204 |
|
| 205 |
func main() { |
| 206 |
flag.Parse() |
| 207 |
token := os.Getenv("GITHUB_AUTH_TOKEN") |
| 208 |
if token == "" { |
| 209 |
log.Fatal("Unauthorized: No token present") |
| 210 |
} |
| 211 |
if *sourceOwner == "" || *sourceRepo == "" || *commitBranch == "" || *sourceFiles == "" || *authorName == "" || *authorEmail == "" { |
| 212 |
log.Fatal("You need to specify a non-empty value for the flags `-source-owner`, `-source-repo`, `-commit-branch`, `-files`, `-author-name` and `-author-email`") |
| 213 |
} |
| 214 |
client = github.NewClient(nil).WithAuthToken(token) |
| 215 |
|
| 216 |
ref, err := getRef() |
| 217 |
if err != nil { |
| 218 |
log.Fatalf("Unable to get/create the commit reference: %s\n", err) |
| 219 |
} |
| 220 |
if ref == nil { |
| 221 |
log.Fatalf("No error where returned but the reference is nil") |
| 222 |
} |
| 223 |
|
| 224 |
tree, err := getTree(ref) |
| 225 |
if err != nil { |
| 226 |
log.Fatalf("Unable to create the tree based on the provided files: %s\n", err) |
| 227 |
} |
| 228 |
|
| 229 |
if err := pushCommit(ref, tree); err != nil { |
| 230 |
log.Fatalf("Unable to create the commit: %s\n", err) |
| 231 |
} |
| 232 |
|
| 233 |
if err := createPR(); err != nil { |
| 234 |
log.Fatalf("Error while creating the pull request: %s", err) |
| 235 |
} |
| 236 |
} |