Update action to hybrid multi platform

This commit is contained in:
Peter Evans 2019-11-09 17:24:47 +09:00
parent d99b58f9d5
commit 55e7b1ec28
13 changed files with 5087 additions and 23 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
node_modules
.DS_Store

View File

@ -1,20 +0,0 @@
FROM alpine:3.10.3
LABEL maintainer="Peter Evans <mail@peterevans.dev>"
LABEL repository="https://github.com/peter-evans/create-pull-request"
LABEL homepage="https://github.com/peter-evans/create-pull-request"
LABEL com.github.actions.name="Create Pull Request"
LABEL com.github.actions.description="Creates a pull request for changes to your repository in the actions workspace"
LABEL com.github.actions.icon="git-pull-request"
LABEL com.github.actions.color="gray-dark"
COPY LICENSE README.md /
RUN apk add python3-dev git git-lfs
COPY requirements.txt /tmp/
RUN pip3 install --requirement /tmp/requirements.txt
COPY create-pull-request.py /create-pull-request.py
ENTRYPOINT [ "/create-pull-request.py" ]

View File

@ -1,9 +1,38 @@
name: 'Create Pull Request'
author: 'Peter Evans'
description: 'Creates a pull request for changes to your repository in the actions workspace'
inputs:
token:
description: 'The GitHub authentication token'
required: true
commit-message:
description: 'The message to use when committing changes.'
author-email:
description: 'The email address of the commit author.'
author-name:
description: 'The name of the commit author.'
title:
description: 'The title of the pull request.'
body:
description: 'The body of the pull request.'
labels:
description: 'A comma separated list of labels.'
assignees:
description: 'A comma separated list of assignees (GitHub usernames).'
reviewers:
description: 'A comma separated list of reviewers (GitHub usernames) to request a review from.'
team-reviewers:
description: 'A comma separated list of GitHub teams to request a review from.'
milestone:
description: 'The number of the milestone to associate this pull request with.'
branch:
description: 'The pull request branch name.'
base:
description: 'Overrides the base branch.'
branch-suffix:
description: 'The branch suffix type.'
runs:
using: 'docker'
image: 'docker://peterevans/create-pull-request:1.6.1'
using: 'node12'
main: 'dist/index.js'
branding:
icon: 'git-pull-request'
color: 'gray-dark'

4524
dist/index.js vendored Normal file

File diff suppressed because it is too large Load Diff

52
dist/src/setup-python.js vendored Normal file
View File

@ -0,0 +1,52 @@
const core = require("@actions/core");
const tc = require("@actions/tool-cache");
const path = require("path");
const semver = require("semver");
/**
* Setup for Python from the GitHub Actions tool cache
* Converted from https://github.com/actions/setup-python
*
* @param {string} versionSpec version of Python
* @param {string} arch architecture (x64|x32)
*/
let setupPython = function(versionSpec, arch) {
return new Promise((resolve, reject) => {
const IS_WINDOWS = process.platform === "win32";
// Find the version of Python we want in the tool cache
const installDir = tc.find("Python", versionSpec, arch);
core.debug(`installDir: ${installDir}`);
// Set paths
core.exportVariable("pythonLocation", installDir);
core.addPath(installDir);
if (IS_WINDOWS) {
core.addPath(path.join(installDir, "Scripts"));
} else {
core.addPath(path.join(installDir, "bin"));
}
if (IS_WINDOWS) {
// Add --user directory
// `installDir` from tool cache should look like $AGENT_TOOLSDIRECTORY/Python/<semantic version>/x64/
// So if `findLocalTool` succeeded above, we must have a conformant `installDir`
const version = path.basename(path.dirname(installDir));
const major = semver.major(version);
const minor = semver.minor(version);
const userScriptsDir = path.join(
process.env["APPDATA"] || "",
"Python",
`Python${major}${minor}`,
"Scripts"
);
core.addPath(userScriptsDir);
}
// On Linux and macOS, pip will create the --user directory and add it to PATH as needed.
resolve();
});
};
module.exports = setupPython;

66
index.js Normal file
View File

@ -0,0 +1,66 @@
const { inspect } = require("util");
const core = require("@actions/core");
const exec = require("@actions/exec");
const setupPython = require("./src/setup-python");
async function run() {
try {
// Allows ncc to find assets to be included in the distribution
const src = __dirname + "/src";
core.debug(`src: ${src}`);
// Setup Python from the tool cache
setupPython("3.8.0", "x64");
// Install requirements
await exec.exec("pip", [
"install",
"--requirement",
`${src}/requirements.txt`
]);
// Fetch action inputs
const inputs = {
token: core.getInput("token"),
commitMessage: core.getInput("commit-message"),
commitAuthorEmail: core.getInput("author-email"),
commitAuthorName: core.getInput("author-name"),
title: core.getInput("title"),
body: core.getInput("body"),
labels: core.getInput("labels"),
assignees: core.getInput("assignees"),
reviewers: core.getInput("reviewers"),
teamReviewers: core.getInput("team-reviewers"),
milestone: core.getInput("milestone"),
branch: core.getInput("branch"),
base: core.getInput("base"),
branchSuffix: core.getInput("branch-suffix"),
debugEvent: core.getInput("debug-event")
};
core.debug(`Inputs: ${inspect(inputs)}`);
// Set environment variables from inputs.
if (inputs.token) process.env.GITHUB_TOKEN = inputs.token;
if (inputs.commitMessage) process.env.COMMIT_MESSAGE = inputs.commitMessage;
if (inputs.commitAuthorEmail) process.env.COMMIT_AUTHOR_EMAIL = inputs.commitAuthorEmail;
if (inputs.commitAuthorName) process.env.COMMIT_AUTHOR_NAME = inputs.commitAuthorName;
if (inputs.title) process.env.PULL_REQUEST_TITLE = inputs.title;
if (inputs.body) process.env.PULL_REQUEST_BODY = inputs.body;
if (inputs.labels) process.env.PULL_REQUEST_LABELS = inputs.labels;
if (inputs.assignees) process.env.PULL_REQUEST_ASSIGNEES = inputs.assignees;
if (inputs.reviewers) process.env.PULL_REQUEST_REVIEWERS = inputs.reviewers;
if (inputs.teamReviewers) process.env.PULL_REQUEST_TEAM_REVIEWERS = inputs.teamReviewers;
if (inputs.milestone) process.env.PULL_REQUEST_MILESTONE = inputs.milestone;
if (inputs.branch) process.env.PULL_REQUEST_BRANCH = inputs.branch;
if (inputs.base) process.env.PULL_REQUEST_BASE = inputs.base;
if (inputs.branchSuffix) process.env.BRANCH_SUFFIX = inputs.branchSuffix;
if (inputs.debugEvent) process.env.DEBUG_EVENT = inputs.debugEvent;
// Execute python script
await exec.exec("python", [`${src}/create-pull-request.py`]);
} catch (error) {
core.setFailed(error.message);
}
}
run();

71
package-lock.json generated Normal file
View File

@ -0,0 +1,71 @@
{
"name": "create-pull-request",
"version": "1.7.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@actions/core": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.0.tgz",
"integrity": "sha512-ZKdyhlSlyz38S6YFfPnyNgCDZuAF2T0Qv5eHflNWytPS8Qjvz39bZFMry9Bb/dpSnqWcNeav5yM2CTYpJeY+Dw=="
},
"@actions/exec": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@actions/exec/-/exec-1.0.1.tgz",
"integrity": "sha512-nvFkxwiicvpzNiCBF4wFBDfnBvi7xp/as7LE1hBxBxKG2L29+gkIPBiLKMVORL+Hg3JNf07AKRfl0V5djoypjQ=="
},
"@actions/io": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@actions/io/-/io-1.0.1.tgz",
"integrity": "sha512-rhq+tfZukbtaus7xyUtwKfuiCRXd1hWSfmJNEpFgBQJ4woqPEpsBw04awicjwz9tyG2/MVhAEMfVn664Cri5zA=="
},
"@actions/tool-cache": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@actions/tool-cache/-/tool-cache-1.1.2.tgz",
"integrity": "sha512-IJczPaZr02ECa3Lgws/TJEVco9tjOujiQSZbO3dHuXXjhd5vrUtfOgGwhmz3/f97L910OraPZ8SknofUk6RvOQ==",
"requires": {
"@actions/core": "^1.1.0",
"@actions/exec": "^1.0.1",
"@actions/io": "^1.0.1",
"semver": "^6.1.0",
"typed-rest-client": "^1.4.0",
"uuid": "^3.3.2"
}
},
"@zeit/ncc": {
"version": "0.20.5",
"resolved": "https://registry.npmjs.org/@zeit/ncc/-/ncc-0.20.5.tgz",
"integrity": "sha512-XU6uzwvv95DqxciQx+aOLhbyBx/13ky+RK1y88Age9Du3BlA4mMPCy13BGjayOrrumOzlq1XV3SD/BWiZENXlw==",
"dev": true
},
"semver": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
"integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw=="
},
"tunnel": {
"version": "0.0.4",
"resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.4.tgz",
"integrity": "sha1-LTeFoVjBdMmhbcLARuxfxfF0IhM="
},
"typed-rest-client": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/typed-rest-client/-/typed-rest-client-1.5.0.tgz",
"integrity": "sha512-DVZRlmsfnTjp6ZJaatcdyvvwYwbWvR4YDNFDqb+qdTxpvaVP99YCpBkA8rxsLtAPjBVoDe4fNsnMIdZTiPuKWg==",
"requires": {
"tunnel": "0.0.4",
"underscore": "1.8.3"
}
},
"underscore": {
"version": "1.8.3",
"resolved": "https://registry.npmjs.org/underscore/-/underscore-1.8.3.tgz",
"integrity": "sha1-Tz+1OxBuYJf8+ctBCfKl6b36UCI="
},
"uuid": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.3.tgz",
"integrity": "sha512-pW0No1RGHgzlpHJO1nsVrHKpOEIxkGg1xB+v0ZmdNH5OAeAwzAVrCnI2/6Mtx+Uys6iaylxa+D3g4j63IKKjSQ=="
}
}
}

28
package.json Normal file
View File

@ -0,0 +1,28 @@
{
"name": "create-pull-request",
"version": "1.7.0",
"description": "Creates a pull request for changes to your repository in the actions workspace",
"main": "index.js",
"scripts": {
"build": "ncc build index.js -o dist"
},
"repository": {
"type": "git",
"url": "git+https://github.com/peter-evans/create-pull-request.git"
},
"keywords": [],
"author": "Peter Evans",
"license": "MIT",
"bugs": {
"url": "https://github.com/peter-evans/create-pull-request/issues"
},
"homepage": "https://github.com/peter-evans/create-pull-request",
"dependencies": {
"@actions/core": "^1.1.1",
"@actions/exec": "^1.0.1",
"@actions/tool-cache": "^1.1.2"
},
"devDependencies": {
"@zeit/ncc": "^0.20.5"
}
}

259
src/create-pull-request.py Executable file
View File

@ -0,0 +1,259 @@
#!/usr/bin/env python3
''' Create Pull Request '''
import json
import os
import random
import string
import sys
import time
from git import Repo
from github import Github
from github import GithubException
def get_github_event(github_event_path):
with open(github_event_path) as f:
github_event = json.load(f)
if bool(os.environ.get('DEBUG_EVENT')):
print(os.environ['GITHUB_EVENT_NAME'])
print(json.dumps(github_event, sort_keys=True, indent=2))
return github_event
def get_head_short_sha1(repo):
return repo.git.rev_parse('--short', 'HEAD')
def get_random_suffix(size=7, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def remote_branch_exists(repo, branch):
for ref in repo.remotes.origin.refs:
if ref.name == ("origin/%s" % branch):
return True
return False
def get_author_default(event_name, event_data):
if event_name == "push":
email = "{head_commit[author][email]}".format(**event_data)
name = "{head_commit[author][name]}".format(**event_data)
else:
email = os.environ['GITHUB_ACTOR'] + '@users.noreply.github.com'
name = os.environ['GITHUB_ACTOR']
return email, name
def set_git_config(git, email, name):
git.config('--global', 'user.email', '"%s"' % email)
git.config('--global', 'user.name', '"%s"' % name)
def set_git_remote_url(git, token, github_repository):
git.remote(
'set-url', 'origin', "https://x-access-token:%s@github.com/%s" %
(token, github_repository))
def checkout_branch(git, remote_exists, branch):
if remote_exists:
git.stash('--include-untracked')
git.checkout(branch)
try:
git.stash('pop')
except BaseException:
git.checkout('--theirs', '.')
git.reset()
else:
git.checkout('HEAD', b=branch)
def push_changes(git, branch, commit_message):
git.add('-A')
git.commit(m=commit_message)
return git.push('-f', '--set-upstream', 'origin', branch)
def cs_string_to_list(str):
# Split the comma separated string into a list
l = [i.strip() for i in str.split(',')]
# Remove empty strings
return list(filter(None, l))
def process_event(github_token, github_repository, repo, branch, base):
# Fetch optional environment variables with default values
commit_message = os.getenv(
'COMMIT_MESSAGE',
"Auto-committed changes by create-pull-request action")
title = os.getenv(
'PULL_REQUEST_TITLE',
"Auto-generated by create-pull-request action")
body = os.getenv(
'PULL_REQUEST_BODY', "Auto-generated pull request by "
"[create-pull-request](https://github.com/peter-evans/create-pull-request) GitHub Action")
# Fetch optional environment variables with no default values
pull_request_labels = os.environ.get('PULL_REQUEST_LABELS')
pull_request_assignees = os.environ.get('PULL_REQUEST_ASSIGNEES')
pull_request_milestone = os.environ.get('PULL_REQUEST_MILESTONE')
pull_request_reviewers = os.environ.get('PULL_REQUEST_REVIEWERS')
pull_request_team_reviewers = os.environ.get('PULL_REQUEST_TEAM_REVIEWERS')
# Push the local changes to the remote branch
print("Pushing changes.")
push_result = push_changes(repo.git, branch, commit_message)
print(push_result)
# Create the pull request
github_repo = Github(github_token).get_repo(github_repository)
try:
pull_request = github_repo.create_pull(
title=title,
body=body,
base=base,
head=branch)
print("Created pull request #%d (%s => %s)" %
(pull_request.number, branch, base))
except GithubException as e:
if e.status == 422:
pull_request = github_repo.get_pulls(
state='open',
base=base,
head=branch)[1]
print("Updated pull request #%d (%s => %s)" %
(pull_request.number, branch, base))
else:
print(str(e))
sys.exit(1)
# Set the output variable
os.system(
'echo ::set-env name=PULL_REQUEST_NUMBER::%d' %
pull_request.number)
# Set labels, assignees and milestone
if pull_request_labels is not None:
print("Applying labels")
pull_request.as_issue().edit(labels=cs_string_to_list(pull_request_labels))
if pull_request_assignees is not None:
print("Applying assignees")
pull_request.as_issue().edit(assignees=cs_string_to_list(pull_request_assignees))
if pull_request_milestone is not None:
print("Applying milestone")
milestone = github_repo.get_milestone(int(pull_request_milestone))
pull_request.as_issue().edit(milestone=milestone)
# Set pull request reviewers
if pull_request_reviewers is not None:
print("Requesting reviewers")
try:
pull_request.create_review_request(
reviewers=cs_string_to_list(pull_request_reviewers))
except GithubException as e:
# Likely caused by "Review cannot be requested from pull request author."
if e.status == 422:
print("Requesting reviewers failed - %s" % e.data["message"])
# Set pull request team reviewers
if pull_request_team_reviewers is not None:
print("Requesting team reviewers")
pull_request.create_review_request(
team_reviewers=cs_string_to_list(pull_request_team_reviewers))
# Fetch environment variables
github_token = os.environ['GITHUB_TOKEN']
github_repository = os.environ['GITHUB_REPOSITORY']
github_ref = os.environ['GITHUB_REF']
event_name = os.environ['GITHUB_EVENT_NAME']
# Get the JSON event data
event_data = get_github_event(os.environ['GITHUB_EVENT_PATH'])
# Set the repo to the working directory
repo = Repo(os.getcwd())
# Get the default for author email and name
author_email, author_name = get_author_default(event_name, event_data)
# Set commit author overrides
author_email = os.getenv('COMMIT_AUTHOR_EMAIL', author_email)
author_name = os.getenv('COMMIT_AUTHOR_NAME', author_name)
# Set git configuration
set_git_config(repo.git, author_email, author_name)
# Update URL for the 'origin' remote
set_git_remote_url(repo.git, github_token, github_repository)
# Fetch/Set the branch name
branch_prefix = os.getenv(
'PULL_REQUEST_BRANCH',
'create-pull-request/patch')
# Fetch an optional base branch override
base_override = os.environ.get('PULL_REQUEST_BASE')
# Set the base branch
if base_override is not None:
base = base_override
checkout_branch(repo.git, True, base)
elif github_ref.startswith('refs/pull/'):
# Switch to the merging branch instead of the merge commit
base = os.environ['GITHUB_HEAD_REF']
repo.git.checkout(base)
else:
base = github_ref[11:]
# Skip if the current branch is a PR branch created by this action.
# This may occur when using a PAT instead of GITHUB_TOKEN.
if base.startswith(branch_prefix):
print("Branch '%s' was created by this action. Skipping." % base)
sys.exit()
# Fetch an optional environment variable to determine the branch suffix
branch_suffix = os.getenv('BRANCH_SUFFIX', 'short-commit-hash')
if branch_suffix == "short-commit-hash":
# Suffix with the short SHA1 hash
branch = "%s-%s" % (branch_prefix, get_head_short_sha1(repo))
elif branch_suffix == "timestamp":
# Suffix with the current timestamp
branch = "%s-%s" % (branch_prefix, int(time.time()))
elif branch_suffix == "random":
# Suffix with the current timestamp
branch = "%s-%s" % (branch_prefix, get_random_suffix())
elif branch_suffix == "none":
# Fixed branch name
branch = branch_prefix
else:
print(
"Branch suffix '%s' is not a valid value." %
branch_suffix)
sys.exit(1)
# Check if the remote branch exists
remote_exists = remote_branch_exists(repo, branch)
if remote_exists:
if branch_suffix == 'short-commit-hash':
# A remote branch already exists for the HEAD commit
print(
"Pull request branch '%s' already exists for this commit. Skipping." %
branch)
sys.exit()
elif branch_suffix in ['timestamp', 'random']:
# Generated branch name clash with an existing branch
print(
"Pull request branch '%s' already exists. Please re-run." %
branch)
sys.exit(1)
# Checkout branch
checkout_branch(repo.git, remote_exists, branch)
# Check if there are changes to pull request
if repo.is_dirty() or len(repo.untracked_files) > 0:
print("Repository has modified or untracked files.")
process_event(
github_token,
github_repository,
repo,
branch,
base)
else:
print("Repository has no modified or untracked files. Skipping.")

2
src/requirements.txt Normal file
View File

@ -0,0 +1,2 @@
GitPython==3.0.4
PyGithub==1.44.1

52
src/setup-python.js Normal file
View File

@ -0,0 +1,52 @@
const core = require("@actions/core");
const tc = require("@actions/tool-cache");
const path = require("path");
const semver = require("semver");
/**
* Setup for Python from the GitHub Actions tool cache
* Converted from https://github.com/actions/setup-python
*
* @param {string} versionSpec version of Python
* @param {string} arch architecture (x64|x32)
*/
let setupPython = function(versionSpec, arch) {
return new Promise((resolve, reject) => {
const IS_WINDOWS = process.platform === "win32";
// Find the version of Python we want in the tool cache
const installDir = tc.find("Python", versionSpec, arch);
core.debug(`installDir: ${installDir}`);
// Set paths
core.exportVariable("pythonLocation", installDir);
core.addPath(installDir);
if (IS_WINDOWS) {
core.addPath(path.join(installDir, "Scripts"));
} else {
core.addPath(path.join(installDir, "bin"));
}
if (IS_WINDOWS) {
// Add --user directory
// `installDir` from tool cache should look like $AGENT_TOOLSDIRECTORY/Python/<semantic version>/x64/
// So if `findLocalTool` succeeded above, we must have a conformant `installDir`
const version = path.basename(path.dirname(installDir));
const major = semver.major(version);
const minor = semver.minor(version);
const userScriptsDir = path.join(
process.env["APPDATA"] || "",
"Python",
`Python${major}${minor}`,
"Scripts"
);
core.addPath(userScriptsDir);
}
// On Linux and macOS, pip will create the --user directory and add it to PATH as needed.
resolve();
});
};
module.exports = setupPython;