Compare commits

...

26 Commits

Author SHA1 Message Date
Jonathan Clem
048309c447 Bump to v1 2020-05-18 14:32:21 -04:00
Jonathan Clem
a8704b62a3 Add note about checkout to separate file docs 2020-05-18 12:59:15 -04:00
Jonathan Clem
e16145c72e Merge pull request #50 from actions/readme-update
Add step results section to readme
2020-05-18 12:55:07 -04:00
Jonathan Clem
dd16c14e71 Move another section in the wrong place 2020-05-18 12:54:07 -04:00
Jonathan Clem
5d33ffc89d Fix step ID in output example 2020-05-18 12:53:18 -04:00
Jonathan Clem
adb3d5168d Fix section not moved 2020-05-18 12:52:37 -04:00
Jonathan Clem
181dcc219c Add step results section to readme 2020-05-18 12:51:39 -04:00
Jonathan Clem
6f0504cb03 Merge pull request #45 from tevoinea/patch-1
Add example on how to get the step result
2020-05-18 12:48:21 -04:00
Jonathan Clem
d89db5b6f4 s/script/module 2020-05-18 12:41:53 -04:00
Jonathan Clem
52110c52e9 Add a separate file example 2020-05-18 12:38:49 -04:00
Jonathan Clem
f498913621 Merge pull request #48 from actions/code-quality
Code quality improvements
2020-05-18 11:34:07 -04:00
Jonathan Clem
58f0ff84d6 Add style:check to ci workflow 2020-05-18 11:33:04 -04:00
Jonathan Clem
3037861304 Add ESLint and Prettier 2020-05-18 11:28:54 -04:00
Jonathan Clem
b945d091bf Check in .vscode 2020-05-18 11:27:26 -04:00
Jonathan Clem
ca14121875 Merge pull request #47 from actions/users/paquirk/ghesfixes
Bumping actions/core and actions/github dependencies for GHES
2020-05-14 18:08:58 -04:00
PJ Quirk
ca6d0aaa59 Fixing exports in generated file 2020-05-14 18:05:57 -04:00
PJ Quirk
5d879b69aa Revert changes to tsc/ncc 2020-05-14 17:16:50 -04:00
Jonathan Clem
1bc9cbef6c Merge pull request #46 from nschonni/patch-1
fix: Example YAML schema to match Actions Docs
2020-05-14 16:22:01 -04:00
PJ Quirk
9a58186a54 Combine build/pack 2020-05-12 15:54:30 -04:00
PJ Quirk
8934ce0ffe Fix pack step and re-run 2020-05-12 15:20:35 -04:00
PJ Quirk
05997a2463 Fix build steps 2020-05-12 15:09:19 -04:00
PJ Quirk
1bc2687309 Bump package versions 2020-05-12 15:08:00 -04:00
Nick Schonning
97fd3f1973 fix: Example YAML schema to match Actions Docs
Both ways should be valid, but the regular nested YAML keys seems to be the format of the regular GitHub Actions docs
2020-05-09 13:09:30 -04:00
Teo Voinea
f8e6050e29 Add example on how to get the step result 2020-05-07 18:19:02 -07:00
Jonathan Clem
648bc46b8a Merge pull request #37 from localheinz/fix/three
Fix: README.md
2020-04-20 12:25:29 -04:00
Andreas Möller
1268370776 Fix: README.md 2020-03-27 12:38:18 +01:00
13 changed files with 1387 additions and 279 deletions

13
.eslintrc.yml Normal file
View File

@@ -0,0 +1,13 @@
root: true
parser: '@typescript-eslint/parser'
plugins: ['@typescript-eslint']
extends:
- eslint:recommended
- plugin:@typescript-eslint/eslint-recommended
- plugin:@typescript-eslint/recommended
- prettier/@typescript-eslint
rules:
# '@typescript-eslint/explicit-function-return-type': 0
'@typescript-eslint/no-use-before-define':
- 2
- functions: false

View File

@@ -15,4 +15,5 @@ jobs:
key: ${{runner.os}}-npm-${{hashFiles('**/package-lock.json')}} key: ${{runner.os}}-npm-${{hashFiles('**/package-lock.json')}}
restore-keys: ${{runner.os}}-npm- restore-keys: ${{runner.os}}-npm-
- run: npm ci - run: npm ci
- run: npm run style:check
- run: npm test - run: npm test

3
.gitignore vendored
View File

@@ -1 +1,2 @@
node_modules /node_modules/
!/.vscode/

5
.prettierrc.yml Normal file
View File

@@ -0,0 +1,5 @@
arrowParens: avoid
bracketSpacing: false
semi: false
singleQuote: true
trailingComma: none

10
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,10 @@
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
},
"files.exclude": {
"**/dist": true,
"**/node_modules": true
}
}

View File

@@ -4,8 +4,8 @@ This action makes it easy to quickly write a script in your workflow that
uses the GitHub API and the workflow run context. uses the GitHub API and the workflow run context.
In order to use this action, a `script` input is provided. The value of that In order to use this action, a `script` input is provided. The value of that
input should be the body of an asynchronous function call. Two arguments will input should be the body of an asynchronous function call. The following
be provided: arguments will be provided:
- `github` A pre-authenticated - `github` A pre-authenticated
[octokit/rest.js](https://github.com/octokit/rest.js) client [octokit/rest.js](https://github.com/octokit/rest.js) client
@@ -26,6 +26,39 @@ future versions. 🙂
See [development.md](/docs/development.md). See [development.md](/docs/development.md).
## Reading step results
The return value of the script will be in the step's outputs under the
"result" key.
```yaml
- uses: actions/github-script@v1
id: set-result
with:
script: return "Hello!"
result-encoding: string
- name: Get result
run: echo "${{steps.set-result.outputs.result}}"
```
See ["Result encoding"](#result-encoding) for details on how the encoding of
these outputs can be changed.
## Result encoding
By default, the JSON-encoded return value of the function is set as the "result" in the
output of a github-script step. For some workflows, string encoding is preferred. This option can be set using the
`result-encoding` input:
```yaml
- uses: actions/github-script@v1
id: my-script
with:
github-token: ${{secrets.GITHUB_TOKEN}}
result-encoding: string
script: return "I will be string (not JSON) encoded!"
```
## Examples ## Examples
Note that `github-token` is optional in this action, and the input is there Note that `github-token` is optional in this action, and the input is there
@@ -37,13 +70,14 @@ By default, github-script will use the token provided to your workflow.
```yaml ```yaml
on: on:
issues: {types: opened} issues:
types: [opened]
jobs: jobs:
comment: comment:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/github-script@0.9.0 - uses: actions/github-script@v1
with: with:
github-token: ${{secrets.GITHUB_TOKEN}} github-token: ${{secrets.GITHUB_TOKEN}}
script: | script: |
@@ -59,13 +93,14 @@ jobs:
```yaml ```yaml
on: on:
issues: {types: opened} issues:
types: [opened]
jobs: jobs:
apply-label: apply-label:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/github-script@0.9.0 - uses: actions/github-script@v1
with: with:
github-token: ${{secrets.GITHUB_TOKEN}} github-token: ${{secrets.GITHUB_TOKEN}}
script: | script: |
@@ -86,7 +121,7 @@ jobs:
welcome: welcome:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/github-script@0.9.0 - uses: actions/github-script@v1
with: with:
github-token: ${{secrets.GITHUB_TOKEN}} github-token: ${{secrets.GITHUB_TOKEN}}
script: | script: |
@@ -130,7 +165,7 @@ jobs:
diff: diff:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/github-script@0.9.0 - uses: actions/github-script@v1
with: with:
github-token: ${{secrets.GITHUB_TOKEN}} github-token: ${{secrets.GITHUB_TOKEN}}
script: | script: |
@@ -142,17 +177,42 @@ jobs:
This will print the full diff object in the screen; `result.data` will This will print the full diff object in the screen; `result.data` will
contain the actual diff text. contain the actual diff text.
### Result encoding ### Run a separate file
By default, the JSON-encoded return value of the function is set as the "result" in the If you don't want to inline your entire script that you want to run, you can
output of a github-script step. For some workflows, string encoding is preferred. This option can be set using the use a separate JavaScript module in your repository like so:
`result-encoding` input:
```yaml ```yaml
- uses: actions/github-script@0.9.0 on: push
with:
github-token: ${{secrets.GITHUB_TOKEN}} jobs:
result-encoding: string echo-input:
script: | runs-on: ubuntu-latest
return "I will be string (not JSON) encoded!" steps:
- uses: @actions/checkout@v2
- uses: @actions/github-script@v1
with:
script: |
const path = require('path')
const scriptPath = path.resolve('./path/to/script.js')
console.log(require(scriptPath)({context}))
``` ```
And then export a function from your module:
```javascript
module.exports = ({context}) => {
return context.payload.client_payload.value
}
```
You can also use async functions in this manner, as long as you `await` it in
the inline script.
Note that because you can't `require` things like the GitHub context or
Actions Toolkit libraries, you'll want to pass them as arguments to your
external function.
Additionally, you'll want to use the [checkout
action](https://github.com/actions/checkout) to make sure your script file is
available.

View File

@@ -1,8 +1,10 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {callAsyncFunction} from '../src/async-function' import {callAsyncFunction} from '../src/async-function'
describe('callAsyncFunction', () => { describe('callAsyncFunction', () => {
test('calls the function with its arguments', async () => { test('calls the function with its arguments', async () => {
const result = await callAsyncFunction({foo: 'bar'}, 'return foo') const result = await callAsyncFunction({foo: 'bar'} as any, 'return foo')
expect(result).toEqual('bar') expect(result).toEqual('bar')
}) })
@@ -10,17 +12,17 @@ describe('callAsyncFunction', () => {
expect.assertions(1) expect.assertions(1)
try { try {
await callAsyncFunction({}, 'proces') await callAsyncFunction({} as any, 'proces')
} catch (err) { } catch (err) {
expect(err).toBeInstanceOf(ReferenceError) expect(err).toBeInstanceOf(ReferenceError)
} }
}) })
test('can access process', async () => { test('can access process', async () => {
await callAsyncFunction({}, 'process') await callAsyncFunction({} as any, 'process')
}) })
test('can access console', async () => { test('can access console', async () => {
await callAsyncFunction({}, 'console') await callAsyncFunction({} as any, 'console')
}) })
}) })

385
dist/index.js vendored
View File

@@ -388,13 +388,6 @@ module.exports._parse = parse;
module.exports._enoent = enoent; module.exports._enoent = enoent;
/***/ }),
/***/ 34:
/***/ (function(module) {
module.exports = require("https");
/***/ }), /***/ }),
/***/ 39: /***/ 39:
@@ -467,13 +460,21 @@ const windowsRelease = release => {
const ver = (version || [])[0]; const ver = (version || [])[0];
// Server 2008, 2012 and 2016 versions are ambiguous with desktop versions and must be detected at runtime. // Server 2008, 2012, 2016, and 2019 versions are ambiguous with desktop versions and must be detected at runtime.
// If `release` is omitted or we're on a Windows system, and the version number is an ambiguous version // If `release` is omitted or we're on a Windows system, and the version number is an ambiguous version
// then use `wmic` to get the OS caption: https://msdn.microsoft.com/en-us/library/aa394531(v=vs.85).aspx // then use `wmic` to get the OS caption: https://msdn.microsoft.com/en-us/library/aa394531(v=vs.85).aspx
// If the resulting caption contains the year 2008, 2012 or 2016, it is a server version, so return a server OS name. // If `wmic` is obsoloete (later versions of Windows 10), use PowerShell instead.
// If the resulting caption contains the year 2008, 2012, 2016 or 2019, it is a server version, so return a server OS name.
if ((!release || release === os.release()) && ['6.1', '6.2', '6.3', '10.0'].includes(ver)) { if ((!release || release === os.release()) && ['6.1', '6.2', '6.3', '10.0'].includes(ver)) {
const stdout = execa.sync('wmic', ['os', 'get', 'Caption']).stdout || ''; let stdout;
const year = (stdout.match(/2008|2012|2016/) || [])[0]; try {
stdout = execa.sync('powershell', ['(Get-CimInstance -ClassName Win32_OperatingSystem).caption']).stdout || '';
} catch (_) {
stdout = execa.sync('wmic', ['os', 'get', 'Caption']).stdout || '';
}
const year = (stdout.match(/2008|2012|2016|2019/) || [])[0];
if (year) { if (year) {
return `Server ${year}`; return `Server ${year}`;
} }
@@ -1453,7 +1454,7 @@ module.exports = require("child_process");
var net = __webpack_require__(631); var net = __webpack_require__(631);
var tls = __webpack_require__(16); var tls = __webpack_require__(16);
var http = __webpack_require__(605); var http = __webpack_require__(605);
var https = __webpack_require__(34); var https = __webpack_require__(211);
var events = __webpack_require__(614); var events = __webpack_require__(614);
var assert = __webpack_require__(357); var assert = __webpack_require__(357);
var util = __webpack_require__(669); var util = __webpack_require__(669);
@@ -1999,32 +2000,9 @@ function checkMode (stat, options) {
/***/ }), /***/ }),
/***/ 211: /***/ 211:
/***/ (function(__unusedmodule, exports, __webpack_require__) { /***/ (function(module) {
"use strict";
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var osName = _interopDefault(__webpack_require__(2));
function getUserAgent() {
try {
return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`;
} catch (error) {
if (/wmic os get Caption/.test(error.message)) {
return "Windows <version undetectable>";
}
return "<environment undetectable>";
}
}
exports.getUserAgent = getUserAgent;
//# sourceMappingURL=index.js.map
module.exports = require("https");
/***/ }), /***/ }),
@@ -3792,7 +3770,7 @@ function coerce (version) {
module.exports = authenticationRequestError; module.exports = authenticationRequestError;
const { RequestError } = __webpack_require__(463); const { RequestError } = __webpack_require__(497);
function authenticationRequestError(state, error, options) { function authenticationRequestError(state, error, options) {
if (!error.headers) throw error; if (!error.headers) throw error;
@@ -3861,7 +3839,7 @@ function authenticationRequestError(state, error, options) {
module.exports = parseOptions; module.exports = parseOptions;
const { Deprecation } = __webpack_require__(692); const { Deprecation } = __webpack_require__(692);
const { getUserAgent } = __webpack_require__(796); const { getUserAgent } = __webpack_require__(619);
const once = __webpack_require__(969); const once = __webpack_require__(969);
const pkg = __webpack_require__(215); const pkg = __webpack_require__(215);
@@ -4176,7 +4154,7 @@ function hasLastPage (link) {
module.exports = validate; module.exports = validate;
const { RequestError } = __webpack_require__(463); const { RequestError } = __webpack_require__(497);
const get = __webpack_require__(854); const get = __webpack_require__(854);
const set = __webpack_require__(883); const set = __webpack_require__(883);
@@ -4332,7 +4310,7 @@ function validate(octokit, options) {
module.exports = authenticationRequestError; module.exports = authenticationRequestError;
const { RequestError } = __webpack_require__(463); const { RequestError } = __webpack_require__(497);
function authenticationRequestError(state, error, options) { function authenticationRequestError(state, error, options) {
/* istanbul ignore next */ /* istanbul ignore next */
@@ -4471,7 +4449,7 @@ Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var isPlainObject = _interopDefault(__webpack_require__(696)); var isPlainObject = _interopDefault(__webpack_require__(696));
var universalUserAgent = __webpack_require__(562); var universalUserAgent = __webpack_require__(796);
function lowercaseKeys(object) { function lowercaseKeys(object) {
if (!object) { if (!object) {
@@ -4821,7 +4799,7 @@ function withDefaults(oldDefaults, newDefaults) {
}); });
} }
const VERSION = "5.5.3"; const VERSION = "6.0.1";
const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url. const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url.
// So we use RequestParameters and add method as additional required property. // So we use RequestParameters and add method as additional required property.
@@ -5058,14 +5036,28 @@ class Command {
return cmdStr; return cmdStr;
} }
} }
/**
* Sanitizes an input into a string so it can be passed into issueCommand safely
* @param input input to sanitize into a string
*/
function toCommandValue(input) {
if (input === null || input === undefined) {
return '';
}
else if (typeof input === 'string' || input instanceof String) {
return input;
}
return JSON.stringify(input);
}
exports.toCommandValue = toCommandValue;
function escapeData(s) { function escapeData(s) {
return (s || '') return toCommandValue(s)
.replace(/%/g, '%25') .replace(/%/g, '%25')
.replace(/\r/g, '%0D') .replace(/\r/g, '%0D')
.replace(/\n/g, '%0A'); .replace(/\n/g, '%0A');
} }
function escapeProperty(s) { function escapeProperty(s) {
return (s || '') return toCommandValue(s)
.replace(/%/g, '%25') .replace(/%/g, '%25')
.replace(/\r/g, '%0D') .replace(/\r/g, '%0D')
.replace(/\n/g, '%0A') .replace(/\n/g, '%0A')
@@ -5178,7 +5170,7 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau
var Stream = _interopDefault(__webpack_require__(413)); var Stream = _interopDefault(__webpack_require__(413));
var http = _interopDefault(__webpack_require__(605)); var http = _interopDefault(__webpack_require__(605));
var Url = _interopDefault(__webpack_require__(835)); var Url = _interopDefault(__webpack_require__(835));
var https = _interopDefault(__webpack_require__(34)); var https = _interopDefault(__webpack_require__(211));
var zlib = _interopDefault(__webpack_require__(761)); var zlib = _interopDefault(__webpack_require__(761));
// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js // Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
@@ -6969,13 +6961,15 @@ class GitHub extends rest_1.Octokit {
static getOctokitOptions(args) { static getOctokitOptions(args) {
const token = args[0]; const token = args[0];
const options = Object.assign({}, args[1]); // Shallow clone - don't mutate the object provided by the caller const options = Object.assign({}, args[1]); // Shallow clone - don't mutate the object provided by the caller
// Base URL - GHES or Dotcom
options.baseUrl = options.baseUrl || this.getApiBaseUrl();
// Auth // Auth
const auth = GitHub.getAuthString(token, options); const auth = GitHub.getAuthString(token, options);
if (auth) { if (auth) {
options.auth = auth; options.auth = auth;
} }
// Proxy // Proxy
const agent = GitHub.getProxyAgent(options); const agent = GitHub.getProxyAgent(options.baseUrl, options);
if (agent) { if (agent) {
// Shallow clone - don't mutate the object provided by the caller // Shallow clone - don't mutate the object provided by the caller
options.request = options.request ? Object.assign({}, options.request) : {}; options.request = options.request ? Object.assign({}, options.request) : {};
@@ -6986,6 +6980,7 @@ class GitHub extends rest_1.Octokit {
} }
static getGraphQL(args) { static getGraphQL(args) {
const defaults = {}; const defaults = {};
defaults.baseUrl = this.getGraphQLBaseUrl();
const token = args[0]; const token = args[0];
const options = args[1]; const options = args[1];
// Authorization // Authorization
@@ -6996,7 +6991,7 @@ class GitHub extends rest_1.Octokit {
}; };
} }
// Proxy // Proxy
const agent = GitHub.getProxyAgent(options); const agent = GitHub.getProxyAgent(defaults.baseUrl, options);
if (agent) { if (agent) {
defaults.request = { agent }; defaults.request = { agent };
} }
@@ -7012,17 +7007,31 @@ class GitHub extends rest_1.Octokit {
} }
return typeof options.auth === 'string' ? options.auth : `token ${token}`; return typeof options.auth === 'string' ? options.auth : `token ${token}`;
} }
static getProxyAgent(options) { static getProxyAgent(destinationUrl, options) {
var _a; var _a;
if (!((_a = options.request) === null || _a === void 0 ? void 0 : _a.agent)) { if (!((_a = options.request) === null || _a === void 0 ? void 0 : _a.agent)) {
const serverUrl = 'https://api.github.com'; if (httpClient.getProxyUrl(destinationUrl)) {
if (httpClient.getProxyUrl(serverUrl)) {
const hc = new httpClient.HttpClient(); const hc = new httpClient.HttpClient();
return hc.getAgent(serverUrl); return hc.getAgent(destinationUrl);
} }
} }
return undefined; return undefined;
} }
static getApiBaseUrl() {
return process.env['GITHUB_API_URL'] || 'https://api.github.com';
}
static getGraphQLBaseUrl() {
let url = process.env['GITHUB_GRAPHQL_URL'] || 'https://api.github.com/graphql';
// Shouldn't be a trailing slash, but remove if so
if (url.endsWith('/')) {
url = url.substr(0, url.length - 1);
}
// Remove trailing "/graphql"
if (url.toUpperCase().endsWith('/GRAPHQL')) {
url = url.substr(0, url.length - '/graphql'.length);
}
return url;
}
} }
exports.GitHub = GitHub; exports.GitHub = GitHub;
//# sourceMappingURL=github.js.map //# sourceMappingURL=github.js.map
@@ -7074,11 +7083,13 @@ var ExitCode;
/** /**
* Sets env variable for this action and future actions in the job * Sets env variable for this action and future actions in the job
* @param name the name of the variable to set * @param name the name of the variable to set
* @param val the value of the variable * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function exportVariable(name, val) { function exportVariable(name, val) {
process.env[name] = val; const convertedVal = command_1.toCommandValue(val);
command_1.issueCommand('set-env', { name }, val); process.env[name] = convertedVal;
command_1.issueCommand('set-env', { name }, convertedVal);
} }
exports.exportVariable = exportVariable; exports.exportVariable = exportVariable;
/** /**
@@ -7117,12 +7128,22 @@ exports.getInput = getInput;
* Sets the value of an output. * Sets the value of an output.
* *
* @param name name of the output to set * @param name name of the output to set
* @param value value to store * @param value value to store. Non-string values will be converted to a string via JSON.stringify
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function setOutput(name, value) { function setOutput(name, value) {
command_1.issueCommand('set-output', { name }, value); command_1.issueCommand('set-output', { name }, value);
} }
exports.setOutput = setOutput; exports.setOutput = setOutput;
/**
* Enables or disables the echoing of commands into stdout for the rest of the step.
* Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.
*
*/
function setCommandEcho(enabled) {
command_1.issue('echo', enabled ? 'on' : 'off');
}
exports.setCommandEcho = setCommandEcho;
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// Results // Results
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@@ -7156,18 +7177,18 @@ function debug(message) {
exports.debug = debug; exports.debug = debug;
/** /**
* Adds an error issue * Adds an error issue
* @param message error issue message * @param message error issue message. Errors will be converted to string via toString()
*/ */
function error(message) { function error(message) {
command_1.issue('error', message); command_1.issue('error', message instanceof Error ? message.toString() : message);
} }
exports.error = error; exports.error = error;
/** /**
* Adds an warning issue * Adds an warning issue
* @param message warning issue message * @param message warning issue message. Errors will be converted to string via toString()
*/ */
function warning(message) { function warning(message) {
command_1.issue('warning', message); command_1.issue('warning', message instanceof Error ? message.toString() : message);
} }
exports.warning = warning; exports.warning = warning;
/** /**
@@ -7225,8 +7246,9 @@ exports.group = group;
* Saves state for current action, the state can only be retrieved by this action's post job execution. * Saves state for current action, the state can only be retrieved by this action's post job execution.
* *
* @param name name of the state to store * @param name name of the state to store
* @param value value to store * @param value value to store. Non-string values will be converted to a string via JSON.stringify
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function saveState(name, value) { function saveState(name, value) {
command_1.issueCommand('save-state', { name }, value); command_1.issueCommand('save-state', { name }, value);
} }
@@ -7348,6 +7370,69 @@ function resolveCommand(parsed) {
module.exports = resolveCommand; module.exports = resolveCommand;
/***/ }),
/***/ 497:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var deprecation = __webpack_require__(692);
var once = _interopDefault(__webpack_require__(969));
const logOnce = once(deprecation => console.warn(deprecation));
/**
* Error with extra properties to help with debugging
*/
class RequestError extends Error {
constructor(message, statusCode, options) {
super(message); // Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = "HttpError";
this.status = statusCode;
Object.defineProperty(this, "code", {
get() {
logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
return statusCode;
}
});
this.headers = options.headers || {}; // redact request credentials without mutating original request options
const requestCopy = Object.assign({}, options.request);
if (options.request.headers.authorization) {
requestCopy.headers = Object.assign({}, options.request.headers, {
authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]")
});
}
requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit
// see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications
.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended
// see https://developer.github.com/v3/#oauth2-token-sent-in-a-header
.replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
this.request = requestCopy;
}
}
exports.RequestError = RequestError;
//# sourceMappingURL=index.js.map
/***/ }), /***/ }),
/***/ 510: /***/ 510:
@@ -7501,7 +7586,7 @@ function hasFirstPage (link) {
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const url = __webpack_require__(835); const url = __webpack_require__(835);
const http = __webpack_require__(605); const http = __webpack_require__(605);
const https = __webpack_require__(34); const https = __webpack_require__(211);
const pm = __webpack_require__(950); const pm = __webpack_require__(950);
let tunnel; let tunnel;
var HttpCodes; var HttpCodes;
@@ -7527,6 +7612,7 @@ var HttpCodes;
HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";
HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";
HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; HttpCodes[HttpCodes["Gone"] = 410] = "Gone";
HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests";
HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";
HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";
HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
@@ -7551,8 +7637,18 @@ function getProxyUrl(serverUrl) {
return proxyUrl ? proxyUrl.href : ''; return proxyUrl ? proxyUrl.href : '';
} }
exports.getProxyUrl = getProxyUrl; exports.getProxyUrl = getProxyUrl;
const HttpRedirectCodes = [HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect]; const HttpRedirectCodes = [
const HttpResponseRetryCodes = [HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout]; HttpCodes.MovedPermanently,
HttpCodes.ResourceMoved,
HttpCodes.SeeOther,
HttpCodes.TemporaryRedirect,
HttpCodes.PermanentRedirect
];
const HttpResponseRetryCodes = [
HttpCodes.BadGateway,
HttpCodes.ServiceUnavailable,
HttpCodes.GatewayTimeout
];
const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];
const ExponentialBackoffCeiling = 10; const ExponentialBackoffCeiling = 10;
const ExponentialBackoffTimeSlice = 5; const ExponentialBackoffTimeSlice = 5;
@@ -7677,18 +7773,22 @@ class HttpClient {
*/ */
async request(verb, requestUrl, data, headers) { async request(verb, requestUrl, data, headers) {
if (this._disposed) { if (this._disposed) {
throw new Error("Client has already been disposed."); throw new Error('Client has already been disposed.');
} }
let parsedUrl = url.parse(requestUrl); let parsedUrl = url.parse(requestUrl);
let info = this._prepareRequest(verb, parsedUrl, headers); let info = this._prepareRequest(verb, parsedUrl, headers);
// Only perform retries on reads since writes may not be idempotent. // Only perform retries on reads since writes may not be idempotent.
let maxTries = (this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1) ? this._maxRetries + 1 : 1; let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1
? this._maxRetries + 1
: 1;
let numTries = 0; let numTries = 0;
let response; let response;
while (numTries < maxTries) { while (numTries < maxTries) {
response = await this.requestRaw(info, data); response = await this.requestRaw(info, data);
// Check if it's an authentication challenge // Check if it's an authentication challenge
if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { if (response &&
response.message &&
response.message.statusCode === HttpCodes.Unauthorized) {
let authenticationHandler; let authenticationHandler;
for (let i = 0; i < this.handlers.length; i++) { for (let i = 0; i < this.handlers.length; i++) {
if (this.handlers[i].canHandleAuthentication(response)) { if (this.handlers[i].canHandleAuthentication(response)) {
@@ -7706,21 +7806,32 @@ class HttpClient {
} }
} }
let redirectsRemaining = this._maxRedirects; let redirectsRemaining = this._maxRedirects;
while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 &&
&& this._allowRedirects this._allowRedirects &&
&& redirectsRemaining > 0) { redirectsRemaining > 0) {
const redirectUrl = response.message.headers["location"]; const redirectUrl = response.message.headers['location'];
if (!redirectUrl) { if (!redirectUrl) {
// if there's no location to redirect to, we won't // if there's no location to redirect to, we won't
break; break;
} }
let parsedRedirectUrl = url.parse(redirectUrl); let parsedRedirectUrl = url.parse(redirectUrl);
if (parsedUrl.protocol == 'https:' && parsedUrl.protocol != parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { if (parsedUrl.protocol == 'https:' &&
throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true."); parsedUrl.protocol != parsedRedirectUrl.protocol &&
!this._allowRedirectDowngrade) {
throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');
} }
// we need to finish reading the response before reassigning response // we need to finish reading the response before reassigning response
// which will leak the open socket. // which will leak the open socket.
await response.readBody(); await response.readBody();
// strip authorization header if redirected to a different hostname
if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
for (let header in headers) {
// header names are case insensitive
if (header.toLowerCase() === 'authorization') {
delete headers[header];
}
}
}
// let's make the request with the new redirectUrl // let's make the request with the new redirectUrl
info = this._prepareRequest(verb, parsedRedirectUrl, headers); info = this._prepareRequest(verb, parsedRedirectUrl, headers);
response = await this.requestRaw(info, data); response = await this.requestRaw(info, data);
@@ -7771,8 +7882,8 @@ class HttpClient {
*/ */
requestRawWithCallback(info, data, onResult) { requestRawWithCallback(info, data, onResult) {
let socket; let socket;
if (typeof (data) === 'string') { if (typeof data === 'string') {
info.options.headers["Content-Length"] = Buffer.byteLength(data, 'utf8'); info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
} }
let callbackCalled = false; let callbackCalled = false;
let handleResult = (err, res) => { let handleResult = (err, res) => {
@@ -7785,7 +7896,7 @@ class HttpClient {
let res = new HttpClientResponse(msg); let res = new HttpClientResponse(msg);
handleResult(null, res); handleResult(null, res);
}); });
req.on('socket', (sock) => { req.on('socket', sock => {
socket = sock; socket = sock;
}); });
// If we ever get disconnected, we want the socket to timeout eventually // If we ever get disconnected, we want the socket to timeout eventually
@@ -7800,10 +7911,10 @@ class HttpClient {
// res should have headers // res should have headers
handleResult(err, null); handleResult(err, null);
}); });
if (data && typeof (data) === 'string') { if (data && typeof data === 'string') {
req.write(data, 'utf8'); req.write(data, 'utf8');
} }
if (data && typeof (data) !== 'string') { if (data && typeof data !== 'string') {
data.on('close', function () { data.on('close', function () {
req.end(); req.end();
}); });
@@ -7830,31 +7941,34 @@ class HttpClient {
const defaultPort = usingSsl ? 443 : 80; const defaultPort = usingSsl ? 443 : 80;
info.options = {}; info.options = {};
info.options.host = info.parsedUrl.hostname; info.options.host = info.parsedUrl.hostname;
info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort; info.options.port = info.parsedUrl.port
info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); ? parseInt(info.parsedUrl.port)
: defaultPort;
info.options.path =
(info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');
info.options.method = method; info.options.method = method;
info.options.headers = this._mergeHeaders(headers); info.options.headers = this._mergeHeaders(headers);
if (this.userAgent != null) { if (this.userAgent != null) {
info.options.headers["user-agent"] = this.userAgent; info.options.headers['user-agent'] = this.userAgent;
} }
info.options.agent = this._getAgent(info.parsedUrl); info.options.agent = this._getAgent(info.parsedUrl);
// gives handlers an opportunity to participate // gives handlers an opportunity to participate
if (this.handlers) { if (this.handlers) {
this.handlers.forEach((handler) => { this.handlers.forEach(handler => {
handler.prepareRequest(info.options); handler.prepareRequest(info.options);
}); });
} }
return info; return info;
} }
_mergeHeaders(headers) { _mergeHeaders(headers) {
const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
if (this.requestOptions && this.requestOptions.headers) { if (this.requestOptions && this.requestOptions.headers) {
return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers));
} }
return lowercaseKeys(headers || {}); return lowercaseKeys(headers || {});
} }
_getExistingOrDefaultHeader(additionalHeaders, header, _default) { _getExistingOrDefaultHeader(additionalHeaders, header, _default) {
const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {}); const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
let clientHeader; let clientHeader;
if (this.requestOptions && this.requestOptions.headers) { if (this.requestOptions && this.requestOptions.headers) {
clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
@@ -7892,7 +8006,7 @@ class HttpClient {
proxyAuth: proxyUrl.auth, proxyAuth: proxyUrl.auth,
host: proxyUrl.hostname, host: proxyUrl.hostname,
port: proxyUrl.port port: proxyUrl.port
}, }
}; };
let tunnelAgent; let tunnelAgent;
const overHttps = proxyUrl.protocol === 'https:'; const overHttps = proxyUrl.protocol === 'https:';
@@ -7919,7 +8033,9 @@ class HttpClient {
// we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
// http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
// we have to cast it to any and change it directly // we have to cast it to any and change it directly
agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false }); agent.options = Object.assign(agent.options || {}, {
rejectUnauthorized: false
});
} }
return agent; return agent;
} }
@@ -7980,7 +8096,7 @@ class HttpClient {
msg = contents; msg = contents;
} }
else { else {
msg = "Failed request: (" + statusCode + ")"; msg = 'Failed request: (' + statusCode + ')';
} }
let err = new Error(msg); let err = new Error(msg);
// attach statusCode and body obj (if available) to the error object // attach statusCode and body obj (if available) to the error object
@@ -8029,36 +8145,6 @@ function hasPreviousPage (link) {
} }
/***/ }),
/***/ 562:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var osName = _interopDefault(__webpack_require__(2));
function getUserAgent() {
try {
return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`;
} catch (error) {
if (/wmic os get Caption/.test(error.message)) {
return "Windows <version undetectable>";
}
return "<environment undetectable>";
}
}
exports.getUserAgent = getUserAgent;
//# sourceMappingURL=index.js.map
/***/ }), /***/ }),
/***/ 563: /***/ 563:
@@ -8242,6 +8328,36 @@ module.exports = require("http");
module.exports = require("events"); module.exports = require("events");
/***/ }),
/***/ 619:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var osName = _interopDefault(__webpack_require__(2));
function getUserAgent() {
try {
return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`;
} catch (error) {
if (/wmic os get Caption/.test(error.message)) {
return "Windows <version undetectable>";
}
throw error;
}
}
exports.getUserAgent = getUserAgent;
//# sourceMappingURL=index.js.map
/***/ }), /***/ }),
/***/ 621: /***/ 621:
@@ -8644,12 +8760,12 @@ Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var endpoint = __webpack_require__(385); var endpoint = __webpack_require__(385);
var universalUserAgent = __webpack_require__(211); var universalUserAgent = __webpack_require__(796);
var isPlainObject = _interopDefault(__webpack_require__(696)); var isPlainObject = _interopDefault(__webpack_require__(696));
var nodeFetch = _interopDefault(__webpack_require__(454)); var nodeFetch = _interopDefault(__webpack_require__(454));
var requestError = __webpack_require__(463); var requestError = __webpack_require__(463);
const VERSION = "5.3.2"; const VERSION = "5.4.2";
function getBufferResponse(response) { function getBufferResponse(response) {
return response.arrayBuffer(); return response.arrayBuffer();
@@ -8877,7 +8993,7 @@ function getUserAgent() {
return "Windows <version undetectable>"; return "Windows <version undetectable>";
} }
throw error; return "<environment undetectable>";
} }
} }
@@ -9158,7 +9274,7 @@ var core = __webpack_require__(470);
var lib_github = __webpack_require__(469); var lib_github = __webpack_require__(469);
// CONCATENATED MODULE: ./src/async-function.ts // CONCATENATED MODULE: ./src/async-function.ts
const AsyncFunction = Object.getPrototypeOf(async () => { }).constructor; const AsyncFunction = Object.getPrototypeOf(async () => null).constructor;
function callAsyncFunction(args, source) { function callAsyncFunction(args, source) {
const fn = new AsyncFunction(...Object.keys(args), source); const fn = new AsyncFunction(...Object.keys(args), source);
return fn(...Object.values(args)); return fn(...Object.values(args));
@@ -9184,7 +9300,7 @@ async function main() {
opts.previews = previews.split(','); opts.previews = previews.split(',');
const github = new lib_github.GitHub(token, opts); const github = new lib_github.GitHub(token, opts);
const script = Object(core.getInput)('script', { required: true }); const script = Object(core.getInput)('script', { required: true });
// Using property/value shorthand on `require` (e.g. `{require}`) causes compilatin errors. // Using property/value shorthand on `require` (e.g. `{require}`) causes compilation errors.
const result = await callAsyncFunction({ require: __webpack_require__(875), github, context: lib_github.context, core: core }, script); const result = await callAsyncFunction({ require: __webpack_require__(875), github, context: lib_github.context, core: core }, script);
let encoding = Object(core.getInput)('result-encoding'); let encoding = Object(core.getInput)('result-encoding');
encoding = encoding ? encoding : 'json'; encoding = encoding ? encoding : 'json';
@@ -9201,14 +9317,10 @@ async function main() {
} }
Object(core.setOutput)('result', output); Object(core.setOutput)('result', output);
} }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function handleError(err) { function handleError(err) {
console.error(err); console.error(err);
if (err && err.message) { Object(core.setFailed)(`Unhandled error: ${err}`);
Object(core.setFailed)(err.message);
}
else {
Object(core.setFailed)(`Unhandled error: ${err}`);
}
} }
@@ -24587,7 +24699,7 @@ Object.defineProperty(exports, '__esModule', { value: true });
var request = __webpack_require__(753); var request = __webpack_require__(753);
var universalUserAgent = __webpack_require__(796); var universalUserAgent = __webpack_require__(796);
const VERSION = "4.3.1"; const VERSION = "4.4.0";
class GraphqlError extends Error { class GraphqlError extends Error {
constructor(request, response) { constructor(request, response) {
@@ -24606,7 +24718,7 @@ class GraphqlError extends Error {
} }
const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query"]; const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"];
function graphql(request, query, options) { function graphql(request, query, options) {
options = typeof query === "string" ? options = Object.assign({ options = typeof query === "string" ? options = Object.assign({
query query
@@ -24757,12 +24869,10 @@ function getProxyUrl(reqUrl) {
} }
let proxyVar; let proxyVar;
if (usingSsl) { if (usingSsl) {
proxyVar = process.env["https_proxy"] || proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY'];
process.env["HTTPS_PROXY"];
} }
else { else {
proxyVar = process.env["http_proxy"] || proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY'];
process.env["HTTP_PROXY"];
} }
if (proxyVar) { if (proxyVar) {
proxyUrl = url.parse(proxyVar); proxyUrl = url.parse(proxyVar);
@@ -24774,7 +24884,7 @@ function checkBypass(reqUrl) {
if (!reqUrl.hostname) { if (!reqUrl.hostname) {
return false; return false;
} }
let noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ''; let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';
if (!noProxy) { if (!noProxy) {
return false; return false;
} }
@@ -24795,7 +24905,10 @@ function checkBypass(reqUrl) {
upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
} }
// Compare request host against noproxy // Compare request host against noproxy
for (let upperNoProxyItem of noProxy.split(',').map(x => x.trim().toUpperCase()).filter(x => x)) { for (let upperNoProxyItem of noProxy
.split(',')
.map(x => x.trim().toUpperCase())
.filter(x => x)) {
if (upperReqHosts.some(x => x === upperNoProxyItem)) { if (upperReqHosts.some(x => x === upperNoProxyItem)) {
return true; return true;
} }

View File

@@ -15,7 +15,8 @@ bash> npm run build
It also has a pre-commit hook configured via It also has a pre-commit hook configured via
[husky](https://www.npmjs.com/package/husky) that should run the build script [husky](https://www.npmjs.com/package/husky) that should run the build script
before each commit. before each commit. Additionally, this hook formats code and lints it, as
well.
## Releasing ## Releasing

1049
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,23 +1,24 @@
{ {
"name": "github-script", "name": "github-script",
"description": "A GitHub action for executing a simple script", "description": "A GitHub action for executing a simple script",
"version": "0.9.0", "version": "1.0.0",
"author": "GitHub", "author": "GitHub",
"dependencies": { "license": "MIT",
"@actions/core": "^1.2.3", "main": "dist/index.js",
"@actions/github": "^2.1.1" "private": true,
}, "scripts": {
"devDependencies": { "build": "ncc build src/main.ts",
"@types/jest": "^25.1.4", "format:check": "prettier --check src __test__",
"@zeit/ncc": "^0.22.0", "format:write": "prettier --write src __test__",
"husky": "^4.2.3", "lint": "eslint src __test__",
"jest": "^25.1.0", "style:check": "run-p --continue-on-error --aggregate-output format:check lint",
"ts-jest": "^25.2.1", "style:write": "run-p --continue-on-error --aggregate-output format:write lint",
"typescript": "^3.8.3" "pre-commit": "run-s style:write test build",
"test": "jest"
}, },
"husky": { "husky": {
"hooks": { "hooks": {
"pre-commit": "npm run build && git add dist/" "pre-commit": "npm run pre-commit && git add dist/"
} }
}, },
"jest": { "jest": {
@@ -33,11 +34,22 @@
} }
} }
}, },
"license": "MIT", "dependencies": {
"main": "dist/index.js", "@actions/core": "^1.2.4",
"private": true, "@actions/github": "^2.2.0"
"scripts": { },
"build": "ncc build src/main.ts", "devDependencies": {
"test": "jest" "@types/jest": "^25.1.4",
"@typescript-eslint/eslint-plugin": "^2.33.0",
"@typescript-eslint/parser": "^2.33.0",
"@zeit/ncc": "^0.22.0",
"eslint": "^7.0.0",
"eslint-config-prettier": "^6.11.0",
"husky": "^4.2.5",
"jest": "^25.1.0",
"npm-run-all": "^4.1.5",
"prettier": "^2.0.5",
"ts-jest": "^25.2.1",
"typescript": "^3.8.3"
} }
} }

View File

@@ -1,11 +1,20 @@
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor import * as core from '@actions/core'
import {GitHub} from '@actions/github'
import {Context} from '@actions/github/lib/context'
type AsyncFunctionArguments = {[key: string]: any} const AsyncFunction = Object.getPrototypeOf(async () => null).constructor
export function callAsyncFunction( type AsyncFunctionArguments = {
context: Context
core: typeof core
github: GitHub
require: NodeRequire
}
export function callAsyncFunction<T>(
args: AsyncFunctionArguments, args: AsyncFunctionArguments,
source: string source: string
): Promise<any> { ): Promise<T> {
const fn = new AsyncFunction(...Object.keys(args), source) const fn = new AsyncFunction(...Object.keys(args), source)
return fn(...Object.values(args)) return fn(...Object.values(args))
} }

View File

@@ -5,19 +5,27 @@ import {callAsyncFunction} from './async-function'
process.on('unhandledRejection', handleError) process.on('unhandledRejection', handleError)
main().catch(handleError) main().catch(handleError)
async function main() { type Options = {
log?: Console
userAgent?: string
previews?: string[]
}
async function main(): Promise<void> {
const token = core.getInput('github-token', {required: true}) const token = core.getInput('github-token', {required: true})
const debug = core.getInput('debug') const debug = core.getInput('debug')
const userAgent = core.getInput('user-agent') const userAgent = core.getInput('user-agent')
const previews = core.getInput('previews') const previews = core.getInput('previews')
const opts: {[key: string]: any} = {}
const opts: Options = {}
if (debug === 'true') opts.log = console if (debug === 'true') opts.log = console
if (userAgent != null) opts.userAgent = userAgent if (userAgent != null) opts.userAgent = userAgent
if (previews != null) opts.previews = previews.split(',') if (previews != null) opts.previews = previews.split(',')
const github = new GitHub(token, opts) const github = new GitHub(token, opts)
const script = core.getInput('script', {required: true}) const script = core.getInput('script', {required: true})
// Using property/value shorthand on `require` (e.g. `{require}`) causes compilatin errors. // Using property/value shorthand on `require` (e.g. `{require}`) causes compilation errors.
const result = await callAsyncFunction( const result = await callAsyncFunction(
{require: require, github, context, core}, {require: require, github, context, core},
script script
@@ -42,12 +50,8 @@ async function main() {
core.setOutput('result', output) core.setOutput('result', output)
} }
function handleError(err: any) { // eslint-disable-next-line @typescript-eslint/no-explicit-any
function handleError(err: any): void {
console.error(err) console.error(err)
core.setFailed(`Unhandled error: ${err}`)
if (err && err.message) {
core.setFailed(err.message)
} else {
core.setFailed(`Unhandled error: ${err}`)
}
} }