From efa457efde8cebf99f6eeaa1d819f06c82a65d9c Mon Sep 17 00:00:00 2001 From: Eric Cornelisesn Date: Sun, 21 Jun 2020 16:47:26 +0300 Subject: [PATCH 1/7] Refactor to have status available when matching --- dist/index.js | 384 +++++++++++++++++++++++++++++++++----------------- src/main.ts | 28 ++-- 2 files changed, 270 insertions(+), 142 deletions(-) diff --git a/dist/index.js b/dist/index.js index 3840d586e..4ff09075b 100644 --- a/dist/index.js +++ b/dist/index.js @@ -419,13 +419,6 @@ module.exports = new Schema({ }); -/***/ }), - -/***/ 34: -/***/ (function(module) { - -module.exports = require("https"); - /***/ }), /***/ 39: @@ -2285,13 +2278,21 @@ const windowsRelease = release => { 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 // 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)) { - const stdout = execa.sync('wmic', ['os', 'get', 'Caption']).stdout || ''; - const year = (stdout.match(/2008|2012|2016/) || [])[0]; + let stdout; + 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) { return `Server ${year}`; } @@ -3488,7 +3489,7 @@ module.exports = require("child_process"); var net = __webpack_require__(631); var tls = __webpack_require__(16); var http = __webpack_require__(605); -var https = __webpack_require__(34); +var https = __webpack_require__(211); var events = __webpack_require__(614); var assert = __webpack_require__(357); var util = __webpack_require__(669); @@ -4156,10 +4157,13 @@ function getChangedFiles(client, prNumber) { repo: github.context.repo.repo, pull_number: prNumber }); - const changedFiles = listFilesResponse.data.map(f => f.filename); + const changedFiles = listFilesResponse.data.map(f => ({ + filename: f.filename, + status: f.status, + })); core.debug('found changed files:'); for (const file of changedFiles) { - core.debug(' ' + file); + core.debug(' ' + file.filename); } return changedFiles; }); @@ -4224,7 +4228,7 @@ function isMatch(changedFile, matchers) { core.debug(` matching patterns against file ${changedFile}`); for (const matcher of matchers) { core.debug(` - ${printPattern(matcher)}`); - if (!matcher.match(changedFile)) { + if (!matcher.match(changedFile.filename)) { core.debug(` ${printPattern(matcher)} did not match`); return false; } @@ -4287,39 +4291,16 @@ run(); /***/ }), /***/ 211: -/***/ (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 "; - } - - return ""; - } -} - -exports.getUserAgent = getUserAgent; -//# sourceMappingURL=index.js.map +/***/ (function(module) { +module.exports = require("https"); /***/ }), /***/ 215: /***/ (function(module) { -module.exports = {"_args":[["@octokit/rest@16.43.1","/Users/jalaziz/Development/forks/labeler"]],"_from":"@octokit/rest@16.43.1","_id":"@octokit/rest@16.43.1","_inBundle":false,"_integrity":"sha512-gfFKwRT/wFxq5qlNjnW2dh+qh74XgTQ2B179UX5K1HYCluioWj8Ndbgqw2PVqa1NnVJkGHp2ovMpVn/DImlmkw==","_location":"/@octokit/rest","_phantomChildren":{},"_requested":{"type":"version","registry":true,"raw":"@octokit/rest@16.43.1","name":"@octokit/rest","escapedName":"@octokit%2frest","scope":"@octokit","rawSpec":"16.43.1","saveSpec":null,"fetchSpec":"16.43.1"},"_requiredBy":["/@actions/github"],"_resolved":"https://registry.npmjs.org/@octokit/rest/-/rest-16.43.1.tgz","_spec":"16.43.1","_where":"/Users/jalaziz/Development/forks/labeler","author":{"name":"Gregor Martynus","url":"https://github.com/gr2m"},"bugs":{"url":"https://github.com/octokit/rest.js/issues"},"bundlesize":[{"path":"./dist/octokit-rest.min.js.gz","maxSize":"33 kB"}],"contributors":[{"name":"Mike de Boer","email":"info@mikedeboer.nl"},{"name":"Fabian Jakobs","email":"fabian@c9.io"},{"name":"Joe Gallo","email":"joe@brassafrax.com"},{"name":"Gregor Martynus","url":"https://github.com/gr2m"}],"dependencies":{"@octokit/auth-token":"^2.4.0","@octokit/plugin-paginate-rest":"^1.1.1","@octokit/plugin-request-log":"^1.0.0","@octokit/plugin-rest-endpoint-methods":"2.4.0","@octokit/request":"^5.2.0","@octokit/request-error":"^1.0.2","atob-lite":"^2.0.0","before-after-hook":"^2.0.0","btoa-lite":"^1.0.0","deprecation":"^2.0.0","lodash.get":"^4.4.2","lodash.set":"^4.3.2","lodash.uniq":"^4.5.0","octokit-pagination-methods":"^1.1.0","once":"^1.4.0","universal-user-agent":"^4.0.0"},"description":"GitHub REST API client for Node.js","devDependencies":{"@gimenete/type-writer":"^0.1.3","@octokit/auth":"^1.1.1","@octokit/fixtures-server":"^5.0.6","@octokit/graphql":"^4.2.0","@types/node":"^13.1.0","bundlesize":"^0.18.0","chai":"^4.1.2","compression-webpack-plugin":"^3.1.0","cypress":"^3.0.0","glob":"^7.1.2","http-proxy-agent":"^4.0.0","lodash.camelcase":"^4.3.0","lodash.merge":"^4.6.1","lodash.upperfirst":"^4.3.1","lolex":"^5.1.2","mkdirp":"^1.0.0","mocha":"^7.0.1","mustache":"^4.0.0","nock":"^11.3.3","npm-run-all":"^4.1.2","nyc":"^15.0.0","prettier":"^1.14.2","proxy":"^1.0.0","semantic-release":"^17.0.0","sinon":"^8.0.0","sinon-chai":"^3.0.0","sort-keys":"^4.0.0","string-to-arraybuffer":"^1.0.0","string-to-jsdoc-comment":"^1.0.0","typescript":"^3.3.1","webpack":"^4.0.0","webpack-bundle-analyzer":"^3.0.0","webpack-cli":"^3.0.0"},"files":["index.js","index.d.ts","lib","plugins"],"homepage":"https://github.com/octokit/rest.js#readme","keywords":["octokit","github","rest","api-client"],"license":"MIT","name":"@octokit/rest","nyc":{"ignore":["test"]},"publishConfig":{"access":"public"},"release":{"publish":["@semantic-release/npm",{"path":"@semantic-release/github","assets":["dist/*","!dist/*.map.gz"]}]},"repository":{"type":"git","url":"git+https://github.com/octokit/rest.js.git"},"scripts":{"build":"npm-run-all build:*","build:browser":"npm-run-all build:browser:*","build:browser:development":"webpack --mode development --entry . --output-library=Octokit --output=./dist/octokit-rest.js --profile --json > dist/bundle-stats.json","build:browser:production":"webpack --mode production --entry . --plugin=compression-webpack-plugin --output-library=Octokit --output-path=./dist --output-filename=octokit-rest.min.js --devtool source-map","build:ts":"npm run -s update-endpoints:typescript","coverage":"nyc report --reporter=html && open coverage/index.html","generate-bundle-report":"webpack-bundle-analyzer dist/bundle-stats.json --mode=static --no-open --report dist/bundle-report.html","lint":"prettier --check '{lib,plugins,scripts,test}/**/*.{js,json,ts}' 'docs/*.{js,json}' 'docs/src/**/*' index.js README.md package.json","lint:fix":"prettier --write '{lib,plugins,scripts,test}/**/*.{js,json,ts}' 'docs/*.{js,json}' 'docs/src/**/*' index.js README.md package.json","postvalidate:ts":"tsc --noEmit --target es6 test/typescript-validate.ts","prebuild:browser":"mkdirp dist/","pretest":"npm run -s lint","prevalidate:ts":"npm run -s build:ts","start-fixtures-server":"octokit-fixtures-server","test":"nyc mocha test/mocha-node-setup.js \"test/*/**/*-test.js\"","test:browser":"cypress run --browser chrome","update-endpoints":"npm-run-all update-endpoints:*","update-endpoints:fetch-json":"node scripts/update-endpoints/fetch-json","update-endpoints:typescript":"node scripts/update-endpoints/typescript","validate:ts":"tsc --target es6 --noImplicitAny index.d.ts"},"types":"index.d.ts","version":"16.43.1"}; +module.exports = {"_args":[["@octokit/rest@16.43.1","/media/win/workspace/labeler"]],"_from":"@octokit/rest@16.43.1","_id":"@octokit/rest@16.43.1","_inBundle":false,"_integrity":"sha512-gfFKwRT/wFxq5qlNjnW2dh+qh74XgTQ2B179UX5K1HYCluioWj8Ndbgqw2PVqa1NnVJkGHp2ovMpVn/DImlmkw==","_location":"/@octokit/rest","_phantomChildren":{"@octokit/types":"2.14.0","deprecation":"2.3.1","once":"1.4.0","os-name":"3.1.0"},"_requested":{"type":"version","registry":true,"raw":"@octokit/rest@16.43.1","name":"@octokit/rest","escapedName":"@octokit%2frest","scope":"@octokit","rawSpec":"16.43.1","saveSpec":null,"fetchSpec":"16.43.1"},"_requiredBy":["/@actions/github"],"_resolved":"https://registry.npmjs.org/@octokit/rest/-/rest-16.43.1.tgz","_spec":"16.43.1","_where":"/media/win/workspace/labeler","author":{"name":"Gregor Martynus","url":"https://github.com/gr2m"},"bugs":{"url":"https://github.com/octokit/rest.js/issues"},"bundlesize":[{"path":"./dist/octokit-rest.min.js.gz","maxSize":"33 kB"}],"contributors":[{"name":"Mike de Boer","email":"info@mikedeboer.nl"},{"name":"Fabian Jakobs","email":"fabian@c9.io"},{"name":"Joe Gallo","email":"joe@brassafrax.com"},{"name":"Gregor Martynus","url":"https://github.com/gr2m"}],"dependencies":{"@octokit/auth-token":"^2.4.0","@octokit/plugin-paginate-rest":"^1.1.1","@octokit/plugin-request-log":"^1.0.0","@octokit/plugin-rest-endpoint-methods":"2.4.0","@octokit/request":"^5.2.0","@octokit/request-error":"^1.0.2","atob-lite":"^2.0.0","before-after-hook":"^2.0.0","btoa-lite":"^1.0.0","deprecation":"^2.0.0","lodash.get":"^4.4.2","lodash.set":"^4.3.2","lodash.uniq":"^4.5.0","octokit-pagination-methods":"^1.1.0","once":"^1.4.0","universal-user-agent":"^4.0.0"},"description":"GitHub REST API client for Node.js","devDependencies":{"@gimenete/type-writer":"^0.1.3","@octokit/auth":"^1.1.1","@octokit/fixtures-server":"^5.0.6","@octokit/graphql":"^4.2.0","@types/node":"^13.1.0","bundlesize":"^0.18.0","chai":"^4.1.2","compression-webpack-plugin":"^3.1.0","cypress":"^3.0.0","glob":"^7.1.2","http-proxy-agent":"^4.0.0","lodash.camelcase":"^4.3.0","lodash.merge":"^4.6.1","lodash.upperfirst":"^4.3.1","lolex":"^5.1.2","mkdirp":"^1.0.0","mocha":"^7.0.1","mustache":"^4.0.0","nock":"^11.3.3","npm-run-all":"^4.1.2","nyc":"^15.0.0","prettier":"^1.14.2","proxy":"^1.0.0","semantic-release":"^17.0.0","sinon":"^8.0.0","sinon-chai":"^3.0.0","sort-keys":"^4.0.0","string-to-arraybuffer":"^1.0.0","string-to-jsdoc-comment":"^1.0.0","typescript":"^3.3.1","webpack":"^4.0.0","webpack-bundle-analyzer":"^3.0.0","webpack-cli":"^3.0.0"},"files":["index.js","index.d.ts","lib","plugins"],"homepage":"https://github.com/octokit/rest.js#readme","keywords":["octokit","github","rest","api-client"],"license":"MIT","name":"@octokit/rest","nyc":{"ignore":["test"]},"publishConfig":{"access":"public"},"release":{"publish":["@semantic-release/npm",{"path":"@semantic-release/github","assets":["dist/*","!dist/*.map.gz"]}]},"repository":{"type":"git","url":"git+https://github.com/octokit/rest.js.git"},"scripts":{"build":"npm-run-all build:*","build:browser":"npm-run-all build:browser:*","build:browser:development":"webpack --mode development --entry . --output-library=Octokit --output=./dist/octokit-rest.js --profile --json > dist/bundle-stats.json","build:browser:production":"webpack --mode production --entry . --plugin=compression-webpack-plugin --output-library=Octokit --output-path=./dist --output-filename=octokit-rest.min.js --devtool source-map","build:ts":"npm run -s update-endpoints:typescript","coverage":"nyc report --reporter=html && open coverage/index.html","generate-bundle-report":"webpack-bundle-analyzer dist/bundle-stats.json --mode=static --no-open --report dist/bundle-report.html","lint":"prettier --check '{lib,plugins,scripts,test}/**/*.{js,json,ts}' 'docs/*.{js,json}' 'docs/src/**/*' index.js README.md package.json","lint:fix":"prettier --write '{lib,plugins,scripts,test}/**/*.{js,json,ts}' 'docs/*.{js,json}' 'docs/src/**/*' index.js README.md package.json","postvalidate:ts":"tsc --noEmit --target es6 test/typescript-validate.ts","prebuild:browser":"mkdirp dist/","pretest":"npm run -s lint","prevalidate:ts":"npm run -s build:ts","start-fixtures-server":"octokit-fixtures-server","test":"nyc mocha test/mocha-node-setup.js \"test/*/**/*-test.js\"","test:browser":"cypress run --browser chrome","update-endpoints":"npm-run-all update-endpoints:*","update-endpoints:fetch-json":"node scripts/update-endpoints/fetch-json","update-endpoints:typescript":"node scripts/update-endpoints/typescript","validate:ts":"tsc --target es6 --noImplicitAny index.d.ts"},"types":"index.d.ts","version":"16.43.1"}; /***/ }), @@ -4735,7 +4716,7 @@ function range(a, b, str) { module.exports = authenticationRequestError; -const { RequestError } = __webpack_require__(463); +const { RequestError } = __webpack_require__(497); function authenticationRequestError(state, error, options) { if (!error.headers) throw error; @@ -4804,7 +4785,7 @@ function authenticationRequestError(state, error, options) { module.exports = parseOptions; const { Deprecation } = __webpack_require__(692); -const { getUserAgent } = __webpack_require__(796); +const { getUserAgent } = __webpack_require__(619); const once = __webpack_require__(969); const pkg = __webpack_require__(215); @@ -5327,7 +5308,7 @@ function hasLastPage (link) { module.exports = validate; -const { RequestError } = __webpack_require__(463); +const { RequestError } = __webpack_require__(497); const get = __webpack_require__(854); const set = __webpack_require__(883); @@ -5483,7 +5464,7 @@ function validate(octokit, options) { module.exports = authenticationRequestError; -const { RequestError } = __webpack_require__(463); +const { RequestError } = __webpack_require__(497); function authenticationRequestError(state, error, options) { /* istanbul ignore next */ @@ -5687,7 +5668,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var isPlainObject = _interopDefault(__webpack_require__(696)); -var universalUserAgent = __webpack_require__(562); +var universalUserAgent = __webpack_require__(796); function lowercaseKeys(object) { if (!object) { @@ -6037,7 +6018,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. // So we use RequestParameters and add method as additional required property. @@ -6449,14 +6430,28 @@ class Command { 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) { - return (s || '') + return toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { - return (s || '') + return toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') @@ -6569,7 +6564,7 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau var Stream = _interopDefault(__webpack_require__(413)); var http = _interopDefault(__webpack_require__(605)); var Url = _interopDefault(__webpack_require__(835)); -var https = _interopDefault(__webpack_require__(34)); +var https = _interopDefault(__webpack_require__(211)); var zlib = _interopDefault(__webpack_require__(761)); // Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js @@ -9993,13 +9988,15 @@ class GitHub extends rest_1.Octokit { static getOctokitOptions(args) { const token = args[0]; 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 const auth = GitHub.getAuthString(token, options); if (auth) { options.auth = auth; } // Proxy - const agent = GitHub.getProxyAgent(options); + const agent = GitHub.getProxyAgent(options.baseUrl, options); if (agent) { // Shallow clone - don't mutate the object provided by the caller options.request = options.request ? Object.assign({}, options.request) : {}; @@ -10010,6 +10007,7 @@ class GitHub extends rest_1.Octokit { } static getGraphQL(args) { const defaults = {}; + defaults.baseUrl = this.getGraphQLBaseUrl(); const token = args[0]; const options = args[1]; // Authorization @@ -10020,7 +10018,7 @@ class GitHub extends rest_1.Octokit { }; } // Proxy - const agent = GitHub.getProxyAgent(options); + const agent = GitHub.getProxyAgent(defaults.baseUrl, options); if (agent) { defaults.request = { agent }; } @@ -10036,17 +10034,31 @@ class GitHub extends rest_1.Octokit { } return typeof options.auth === 'string' ? options.auth : `token ${token}`; } - static getProxyAgent(options) { + static getProxyAgent(destinationUrl, options) { var _a; if (!((_a = options.request) === null || _a === void 0 ? void 0 : _a.agent)) { - const serverUrl = 'https://api.github.com'; - if (httpClient.getProxyUrl(serverUrl)) { + if (httpClient.getProxyUrl(destinationUrl)) { const hc = new httpClient.HttpClient(); - return hc.getAgent(serverUrl); + return hc.getAgent(destinationUrl); } } 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; //# sourceMappingURL=github.js.map @@ -10098,11 +10110,13 @@ var ExitCode; /** * Sets env variable for this action and future actions in the job * @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) { - process.env[name] = val; - command_1.issueCommand('set-env', { name }, val); + const convertedVal = command_1.toCommandValue(val); + process.env[name] = convertedVal; + command_1.issueCommand('set-env', { name }, convertedVal); } exports.exportVariable = exportVariable; /** @@ -10141,12 +10155,22 @@ exports.getInput = getInput; * Sets the value of an output. * * @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) { command_1.issueCommand('set-output', { name }, value); } 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 //----------------------------------------------------------------------- @@ -10180,18 +10204,18 @@ function debug(message) { exports.debug = debug; /** * 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) { - command_1.issue('error', message); + command_1.issue('error', message instanceof Error ? message.toString() : message); } exports.error = error; /** * 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) { - command_1.issue('warning', message); + command_1.issue('warning', message instanceof Error ? message.toString() : message); } exports.warning = warning; /** @@ -10249,8 +10273,9 @@ exports.group = group; * 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 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) { command_1.issueCommand('save-state', { name }, value); } @@ -10372,6 +10397,69 @@ function resolveCommand(parsed) { 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: @@ -10525,7 +10613,7 @@ function hasFirstPage (link) { Object.defineProperty(exports, "__esModule", { value: true }); const url = __webpack_require__(835); const http = __webpack_require__(605); -const https = __webpack_require__(34); +const https = __webpack_require__(211); const pm = __webpack_require__(950); let tunnel; var HttpCodes; @@ -10551,6 +10639,7 @@ var HttpCodes; HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; @@ -10575,8 +10664,18 @@ function getProxyUrl(serverUrl) { return proxyUrl ? proxyUrl.href : ''; } exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect]; -const HttpResponseRetryCodes = [HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout]; +const HttpRedirectCodes = [ + 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 ExponentialBackoffCeiling = 10; const ExponentialBackoffTimeSlice = 5; @@ -10701,18 +10800,22 @@ class HttpClient { */ async request(verb, requestUrl, data, headers) { 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 info = this._prepareRequest(verb, parsedUrl, headers); // 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 response; while (numTries < maxTries) { response = await this.requestRaw(info, data); // 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; for (let i = 0; i < this.handlers.length; i++) { if (this.handlers[i].canHandleAuthentication(response)) { @@ -10730,21 +10833,32 @@ class HttpClient { } } let redirectsRemaining = this._maxRedirects; - while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 - && this._allowRedirects - && redirectsRemaining > 0) { - const redirectUrl = response.message.headers["location"]; + while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && + this._allowRedirects && + redirectsRemaining > 0) { + const redirectUrl = response.message.headers['location']; if (!redirectUrl) { // if there's no location to redirect to, we won't break; } let parsedRedirectUrl = url.parse(redirectUrl); - if (parsedUrl.protocol == 'https:' && 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."); + if (parsedUrl.protocol == 'https:' && + 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 // which will leak the open socket. 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 info = this._prepareRequest(verb, parsedRedirectUrl, headers); response = await this.requestRaw(info, data); @@ -10795,8 +10909,8 @@ class HttpClient { */ requestRawWithCallback(info, data, onResult) { let socket; - if (typeof (data) === 'string') { - info.options.headers["Content-Length"] = Buffer.byteLength(data, 'utf8'); + if (typeof data === 'string') { + info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } let callbackCalled = false; let handleResult = (err, res) => { @@ -10809,7 +10923,7 @@ class HttpClient { let res = new HttpClientResponse(msg); handleResult(null, res); }); - req.on('socket', (sock) => { + req.on('socket', sock => { socket = sock; }); // If we ever get disconnected, we want the socket to timeout eventually @@ -10824,10 +10938,10 @@ class HttpClient { // res should have headers handleResult(err, null); }); - if (data && typeof (data) === 'string') { + if (data && typeof data === 'string') { req.write(data, 'utf8'); } - if (data && typeof (data) !== 'string') { + if (data && typeof data !== 'string') { data.on('close', function () { req.end(); }); @@ -10854,31 +10968,34 @@ class HttpClient { const defaultPort = usingSsl ? 443 : 80; info.options = {}; info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort; - info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); + info.options.port = info.parsedUrl.port + ? parseInt(info.parsedUrl.port) + : defaultPort; + info.options.path = + (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); info.options.method = method; info.options.headers = this._mergeHeaders(headers); 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); // gives handlers an opportunity to participate if (this.handlers) { - this.handlers.forEach((handler) => { + this.handlers.forEach(handler => { handler.prepareRequest(info.options); }); } return info; } _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) { return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); } return lowercaseKeys(headers || {}); } _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; if (this.requestOptions && this.requestOptions.headers) { clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; @@ -10916,7 +11033,7 @@ class HttpClient { proxyAuth: proxyUrl.auth, host: proxyUrl.hostname, port: proxyUrl.port - }, + } }; let tunnelAgent; const overHttps = proxyUrl.protocol === 'https:'; @@ -10943,7 +11060,9 @@ class HttpClient { // 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 // 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; } @@ -11004,7 +11123,7 @@ class HttpClient { msg = contents; } else { - msg = "Failed request: (" + statusCode + ")"; + msg = 'Failed request: (' + statusCode + ')'; } let err = new Error(msg); // attach statusCode and body obj (if available) to the error object @@ -11104,36 +11223,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 "; - } - - return ""; - } -} - -exports.getUserAgent = getUserAgent; -//# sourceMappingURL=index.js.map - - /***/ }), /***/ 563: @@ -12314,6 +12403,36 @@ module.exports = new Schema({ 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 "; + } + + throw error; + } +} + +exports.getUserAgent = getUserAgent; +//# sourceMappingURL=index.js.map + + /***/ }), /***/ 621: @@ -13742,12 +13861,12 @@ Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var endpoint = __webpack_require__(385); -var universalUserAgent = __webpack_require__(211); +var universalUserAgent = __webpack_require__(796); var isPlainObject = _interopDefault(__webpack_require__(696)); var nodeFetch = _interopDefault(__webpack_require__(454)); var requestError = __webpack_require__(463); -const VERSION = "5.3.2"; +const VERSION = "5.4.2"; function getBufferResponse(response) { return response.arrayBuffer(); @@ -13975,7 +14094,7 @@ function getUserAgent() { return "Windows "; } - throw error; + return ""; } } @@ -29706,7 +29825,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); var request = __webpack_require__(753); var universalUserAgent = __webpack_require__(796); -const VERSION = "4.3.1"; +const VERSION = "4.4.0"; class GraphqlError extends Error { constructor(request, response) { @@ -29725,7 +29844,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) { options = typeof query === "string" ? options = Object.assign({ query @@ -30201,12 +30320,10 @@ function getProxyUrl(reqUrl) { } let proxyVar; if (usingSsl) { - proxyVar = process.env["https_proxy"] || - process.env["HTTPS_PROXY"]; + proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; } else { - proxyVar = process.env["http_proxy"] || - process.env["HTTP_PROXY"]; + proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; } if (proxyVar) { proxyUrl = url.parse(proxyVar); @@ -30218,7 +30335,7 @@ function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } - let noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || ''; + let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; } @@ -30239,7 +30356,10 @@ function checkBypass(reqUrl) { upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } // 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)) { return true; } diff --git a/src/main.ts b/src/main.ts index 3fffa6393..e46ca598f 100644 --- a/src/main.ts +++ b/src/main.ts @@ -8,6 +8,11 @@ interface MatchConfig { any?: string[]; } +interface File { + filename: string; + status: string; +} + type StringOrMatchConfig = string | MatchConfig; async function run() { @@ -24,7 +29,7 @@ async function run() { const client = new github.GitHub(token); core.debug(`fetching changed files for pr #${prNumber}`); - const changedFiles: string[] = await getChangedFiles(client, prNumber); + const changedFiles: File[] = await getChangedFiles(client, prNumber); const labelGlobs: Map = await getLabelGlobs( client, configPath @@ -59,18 +64,21 @@ function getPrNumber(): number | undefined { async function getChangedFiles( client: github.GitHub, prNumber: number -): Promise { +): Promise { const listFilesResponse = await client.pulls.listFiles({ owner: github.context.repo.owner, repo: github.context.repo.repo, pull_number: prNumber }); - const changedFiles = listFilesResponse.data.map(f => f.filename); + const changedFiles = listFilesResponse.data.map(f => ({ + filename: f.filename, + status: f.status, + })); core.debug('found changed files:'); for (const file of changedFiles) { - core.debug(' ' + file); + core.debug(' ' + file.filename); } return changedFiles; @@ -140,7 +148,7 @@ function printPattern(matcher: IMinimatch): string { } function checkGlobs( - changedFiles: string[], + changedFiles: File[], globs: StringOrMatchConfig[] ): boolean { for (const glob of globs) { @@ -153,11 +161,11 @@ function checkGlobs( return false; } -function isMatch(changedFile: string, matchers: IMinimatch[]): boolean { +function isMatch(changedFile: File, matchers: IMinimatch[]): boolean { core.debug(` matching patterns against file ${changedFile}`); for (const matcher of matchers) { core.debug(` - ${printPattern(matcher)}`); - if (!matcher.match(changedFile)) { + if (!matcher.match(changedFile.filename)) { core.debug(` ${printPattern(matcher)} did not match`); return false; } @@ -168,7 +176,7 @@ function isMatch(changedFile: string, matchers: IMinimatch[]): boolean { } // equivalent to "Array.some()" but expanded for debugging and clarity -function checkAny(changedFiles: string[], globs: string[]): boolean { +function checkAny(changedFiles: File[], globs: string[]): boolean { const matchers = globs.map(g => new Minimatch(g)); core.debug(` checking "any" patterns`); for (const changedFile of changedFiles) { @@ -183,7 +191,7 @@ function checkAny(changedFiles: string[], globs: string[]): boolean { } // equivalent to "Array.every()" but expanded for debugging and clarity -function checkAll(changedFiles: string[], globs: string[]): boolean { +function checkAll(changedFiles: File[], globs: string[]): boolean { const matchers = globs.map(g => new Minimatch(g)); core.debug(` checking "all" patterns`); for (const changedFile of changedFiles) { @@ -197,7 +205,7 @@ function checkAll(changedFiles: string[], globs: string[]): boolean { return true; } -function checkMatch(changedFiles: string[], matchConfig: MatchConfig): boolean { +function checkMatch(changedFiles: File[], matchConfig: MatchConfig): boolean { if (matchConfig.all !== undefined) { if (!checkAll(changedFiles, matchConfig.all)) { return false; From 797a6af39c0c935c276552fca96b3954f03598e3 Mon Sep 17 00:00:00 2001 From: Eric Cornelisesn Date: Sun, 21 Jun 2020 17:13:28 +0300 Subject: [PATCH 2/7] Check file status in isMatch() --- dist/index.js | 25 +++++++++++++++++-------- src/main.ts | 41 +++++++++++++++++++++++++++++++++-------- 2 files changed, 50 insertions(+), 16 deletions(-) diff --git a/dist/index.js b/dist/index.js index 4ff09075b..2b7c215dc 100644 --- a/dist/index.js +++ b/dist/index.js @@ -4204,11 +4204,16 @@ function getLabelGlobMapFromObject(configObject) { return labelGlobs; } function toMatchConfig(config) { + const allStatus = ["added", "modified", "removed"]; if (typeof config === "string") { return { - any: [config] + any: [config], + status: allStatus }; } + if (typeof config.status === "string") { + config.status = [config.status]; + } return config; } function printPattern(matcher) { @@ -4224,7 +4229,11 @@ function checkGlobs(changedFiles, globs) { } return false; } -function isMatch(changedFile, matchers) { +function isMatch(changedFile, matchers, statuses) { + core.debug(` matching statuses against file ${changedFile}`); + if (!statuses.includes(changedFile.status)) { + return false; + } core.debug(` matching patterns against file ${changedFile}`); for (const matcher of matchers) { core.debug(` - ${printPattern(matcher)}`); @@ -4237,11 +4246,11 @@ function isMatch(changedFile, matchers) { return true; } // equivalent to "Array.some()" but expanded for debugging and clarity -function checkAny(changedFiles, globs) { +function checkAny(changedFiles, globs, statuses) { const matchers = globs.map(g => new minimatch_1.Minimatch(g)); core.debug(` checking "any" patterns`); for (const changedFile of changedFiles) { - if (isMatch(changedFile, matchers)) { + if (isMatch(changedFile, matchers, statuses)) { core.debug(` "any" patterns matched against ${changedFile}`); return true; } @@ -4250,11 +4259,11 @@ function checkAny(changedFiles, globs) { return false; } // equivalent to "Array.every()" but expanded for debugging and clarity -function checkAll(changedFiles, globs) { +function checkAll(changedFiles, globs, statuses) { const matchers = globs.map(g => new minimatch_1.Minimatch(g)); core.debug(` checking "all" patterns`); for (const changedFile of changedFiles) { - if (!isMatch(changedFile, matchers)) { + if (!isMatch(changedFile, matchers, statuses)) { core.debug(` "all" patterns did not match against ${changedFile}`); return false; } @@ -4264,12 +4273,12 @@ function checkAll(changedFiles, globs) { } function checkMatch(changedFiles, matchConfig) { if (matchConfig.all !== undefined) { - if (!checkAll(changedFiles, matchConfig.all)) { + if (!checkAll(changedFiles, matchConfig.all, matchConfig.status)) { return false; } } if (matchConfig.any !== undefined) { - if (!checkAny(changedFiles, matchConfig.any)) { + if (!checkAny(changedFiles, matchConfig.any, matchConfig.status)) { return false; } } diff --git a/src/main.ts b/src/main.ts index e46ca598f..6e58d9fdd 100644 --- a/src/main.ts +++ b/src/main.ts @@ -6,6 +6,7 @@ import {Minimatch, IMinimatch} from 'minimatch'; interface MatchConfig { all?: string[]; any?: string[]; + status: string[]; } interface File { @@ -134,12 +135,19 @@ function getLabelGlobMapFromObject( } function toMatchConfig(config: StringOrMatchConfig): MatchConfig { + const allStatus = ["added", "modified", "removed"]; + if (typeof config === "string") { return { - any: [config] + any: [config], + status: allStatus }; } + if (typeof config.status === "string") { + config.status = [config.status]; + } + return config; } @@ -161,7 +169,16 @@ function checkGlobs( return false; } -function isMatch(changedFile: File, matchers: IMinimatch[]): boolean { +function isMatch( + changedFile: File, + matchers: IMinimatch[], + statuses: string[] +): boolean { + core.debug(` matching statuses against file ${changedFile}`); + if (!statuses.includes(changedFile.status)) { + return false; + } + core.debug(` matching patterns against file ${changedFile}`); for (const matcher of matchers) { core.debug(` - ${printPattern(matcher)}`); @@ -176,11 +193,15 @@ function isMatch(changedFile: File, matchers: IMinimatch[]): boolean { } // equivalent to "Array.some()" but expanded for debugging and clarity -function checkAny(changedFiles: File[], globs: string[]): boolean { +function checkAny( + changedFiles: File[], + globs: string[], + statuses: string[] +): boolean { const matchers = globs.map(g => new Minimatch(g)); core.debug(` checking "any" patterns`); for (const changedFile of changedFiles) { - if (isMatch(changedFile, matchers)) { + if (isMatch(changedFile, matchers, statuses)) { core.debug(` "any" patterns matched against ${changedFile}`); return true; } @@ -191,11 +212,15 @@ function checkAny(changedFiles: File[], globs: string[]): boolean { } // equivalent to "Array.every()" but expanded for debugging and clarity -function checkAll(changedFiles: File[], globs: string[]): boolean { +function checkAll( + changedFiles: File[], + globs: string[], + statuses: string[] +): boolean { const matchers = globs.map(g => new Minimatch(g)); core.debug(` checking "all" patterns`); for (const changedFile of changedFiles) { - if (!isMatch(changedFile, matchers)) { + if (!isMatch(changedFile, matchers, statuses)) { core.debug(` "all" patterns did not match against ${changedFile}`); return false; } @@ -207,13 +232,13 @@ function checkAll(changedFiles: File[], globs: string[]): boolean { function checkMatch(changedFiles: File[], matchConfig: MatchConfig): boolean { if (matchConfig.all !== undefined) { - if (!checkAll(changedFiles, matchConfig.all)) { + if (!checkAll(changedFiles, matchConfig.all, matchConfig.status)) { return false; } } if (matchConfig.any !== undefined) { - if (!checkAny(changedFiles, matchConfig.any)) { + if (!checkAny(changedFiles, matchConfig.any, matchConfig.status)) { return false; } } From e7f086fd63241add02721c4c748c9b31b0e4b927 Mon Sep 17 00:00:00 2001 From: Eric Cornelisesn Date: Sun, 21 Jun 2020 18:17:21 +0300 Subject: [PATCH 3/7] Account for missing status key --- dist/index.js | 7 +++++-- src/main.ts | 6 ++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/dist/index.js b/dist/index.js index 2b7c215dc..5c08d4124 100644 --- a/dist/index.js +++ b/dist/index.js @@ -4204,16 +4204,19 @@ function getLabelGlobMapFromObject(configObject) { return labelGlobs; } function toMatchConfig(config) { - const allStatus = ["added", "modified", "removed"]; + const allStatuses = ["added", "modified", "removed"]; if (typeof config === "string") { return { any: [config], - status: allStatus + status: allStatuses }; } if (typeof config.status === "string") { config.status = [config.status]; } + else if (!Array.isArray(config.status)) { + config.status = allStatuses; + } return config; } function printPattern(matcher) { diff --git a/src/main.ts b/src/main.ts index 6e58d9fdd..43faa105f 100644 --- a/src/main.ts +++ b/src/main.ts @@ -135,17 +135,19 @@ function getLabelGlobMapFromObject( } function toMatchConfig(config: StringOrMatchConfig): MatchConfig { - const allStatus = ["added", "modified", "removed"]; + const allStatuses = ["added", "modified", "removed"]; if (typeof config === "string") { return { any: [config], - status: allStatus + status: allStatuses }; } if (typeof config.status === "string") { config.status = [config.status]; + } else if (!Array.isArray(config.status)) { + config.status = allStatuses; } return config; From 8e0eacfd2b190c6370521cc683a0494eaba2e0e0 Mon Sep 17 00:00:00 2001 From: Eric Cornelisesn Date: Sun, 21 Jun 2020 18:21:27 +0300 Subject: [PATCH 4/7] Fix [Object object] in debug logs --- dist/index.js | 8 ++++---- src/main.ts | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/dist/index.js b/dist/index.js index 5c08d4124..f01b31113 100644 --- a/dist/index.js +++ b/dist/index.js @@ -4233,11 +4233,11 @@ function checkGlobs(changedFiles, globs) { return false; } function isMatch(changedFile, matchers, statuses) { - core.debug(` matching statuses against file ${changedFile}`); + core.debug(` matching statuses against file ${changedFile.filename}`); if (!statuses.includes(changedFile.status)) { return false; } - core.debug(` matching patterns against file ${changedFile}`); + core.debug(` matching patterns against file ${changedFile.filename}`); for (const matcher of matchers) { core.debug(` - ${printPattern(matcher)}`); if (!matcher.match(changedFile.filename)) { @@ -4254,7 +4254,7 @@ function checkAny(changedFiles, globs, statuses) { core.debug(` checking "any" patterns`); for (const changedFile of changedFiles) { if (isMatch(changedFile, matchers, statuses)) { - core.debug(` "any" patterns matched against ${changedFile}`); + core.debug(` "any" patterns matched against ${changedFile.filename}`); return true; } } @@ -4267,7 +4267,7 @@ function checkAll(changedFiles, globs, statuses) { core.debug(` checking "all" patterns`); for (const changedFile of changedFiles) { if (!isMatch(changedFile, matchers, statuses)) { - core.debug(` "all" patterns did not match against ${changedFile}`); + core.debug(` "all" patterns did not match against ${changedFile.filename}`); return false; } } diff --git a/src/main.ts b/src/main.ts index 43faa105f..ad3473fe8 100644 --- a/src/main.ts +++ b/src/main.ts @@ -176,12 +176,12 @@ function isMatch( matchers: IMinimatch[], statuses: string[] ): boolean { - core.debug(` matching statuses against file ${changedFile}`); + core.debug(` matching statuses against file ${changedFile.filename}`); if (!statuses.includes(changedFile.status)) { return false; } - core.debug(` matching patterns against file ${changedFile}`); + core.debug(` matching patterns against file ${changedFile.filename}`); for (const matcher of matchers) { core.debug(` - ${printPattern(matcher)}`); if (!matcher.match(changedFile.filename)) { @@ -204,7 +204,7 @@ function checkAny( core.debug(` checking "any" patterns`); for (const changedFile of changedFiles) { if (isMatch(changedFile, matchers, statuses)) { - core.debug(` "any" patterns matched against ${changedFile}`); + core.debug(` "any" patterns matched against ${changedFile.filename}`); return true; } } @@ -223,7 +223,7 @@ function checkAll( core.debug(` checking "all" patterns`); for (const changedFile of changedFiles) { if (!isMatch(changedFile, matchers, statuses)) { - core.debug(` "all" patterns did not match against ${changedFile}`); + core.debug(` "all" patterns did not match against ${changedFile.filename}`); return false; } } From a9e40c72a4501c01e094d38be2ac062c059cac7a Mon Sep 17 00:00:00 2001 From: Eric Cornelisesn Date: Sun, 21 Jun 2020 18:50:25 +0300 Subject: [PATCH 5/7] Add debug log if status does not match --- dist/index.js | 1 + src/main.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/dist/index.js b/dist/index.js index f01b31113..a29d2a1b4 100644 --- a/dist/index.js +++ b/dist/index.js @@ -4235,6 +4235,7 @@ function checkGlobs(changedFiles, globs) { function isMatch(changedFile, matchers, statuses) { core.debug(` matching statuses against file ${changedFile.filename}`); if (!statuses.includes(changedFile.status)) { + core.debug(` ${changedFile.status} did not match ${JSON.stringify(statuses)}`); return false; } core.debug(` matching patterns against file ${changedFile.filename}`); diff --git a/src/main.ts b/src/main.ts index ad3473fe8..da3282a23 100644 --- a/src/main.ts +++ b/src/main.ts @@ -178,6 +178,7 @@ function isMatch( ): boolean { core.debug(` matching statuses against file ${changedFile.filename}`); if (!statuses.includes(changedFile.status)) { + core.debug(` ${changedFile.status} did not match ${JSON.stringify(statuses)}`); return false; } From a35c80b1c7739783c7672ce3178c84acfeeb5217 Mon Sep 17 00:00:00 2001 From: Eric Cornelisesn Date: Sun, 21 Jun 2020 19:00:03 +0300 Subject: [PATCH 6/7] Add status example to documentation --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2d430629a..c1e85d7f8 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ label2: example2/* # Add 'repo' label to any root file changes repo: - ./* - + # Add '@domain/core' label to any change within the 'core' package @domain/core: - package/core/* @@ -75,6 +75,12 @@ source: frontend: - any: ['src/**/*.js'] all: ['!src/main.js'] + +# Add 'new-test` only if a new test file has been added +new-test: + - any: [src/**/*.spec.js] + status: 'added' + ``` ### Create Workflow From b4f95e00ae31650580f0291dff2aa228cb1d107f Mon Sep 17 00:00:00 2001 From: Eric Cornelissen Date: Mon, 14 Jun 2021 22:53:43 +0200 Subject: [PATCH 7/7] Update tests & add negative test for status matching --- __tests__/labeler.test.ts | 18 ++++++++++++++---- __tests__/main.test.ts | 2 +- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/__tests__/labeler.test.ts b/__tests__/labeler.test.ts index 082ed672b..6df8e4f20 100644 --- a/__tests__/labeler.test.ts +++ b/__tests__/labeler.test.ts @@ -10,18 +10,28 @@ beforeAll(() => { }); }); -const matchConfig = [{ any: ["*.txt"] }]; +const matchConfig = [{ any: ["*.txt"], status: ["added", "modified"] }]; describe("checkGlobs", () => { - it("returns true when our pattern does match changed files", () => { - const changedFiles = ["foo.txt", "bar.txt"]; + it("returns true when our pattern does match changed files & status", () => { + const changedFiles = [ + { filename: "foo.txt", status: "modified" }, + { filename: "bar.txt", status: "modified" }, + ]; const result = checkGlobs(changedFiles, matchConfig); expect(result).toBeTruthy(); }); it("returns false when our pattern does not match changed files", () => { - const changedFiles = ["foo.docx"]; + const changedFiles = [{ filename: "foo.docx", status: "modified" }]; + const result = checkGlobs(changedFiles, matchConfig); + + expect(result).toBeFalsy(); + }); + + it("returns false when our pattern does not match changed files status", () => { + const changedFiles = [{ filename: "foo.docx", status: "removed" }]; const result = checkGlobs(changedFiles, matchConfig); expect(result).toBeFalsy(); diff --git a/__tests__/main.test.ts b/__tests__/main.test.ts index f4e895d97..2fec9ed78 100644 --- a/__tests__/main.test.ts +++ b/__tests__/main.test.ts @@ -111,6 +111,6 @@ function usingLabelerConfigYaml(fixtureName: keyof typeof yamlFixtures): void { } function mockGitHubResponseChangedFiles(...files: string[]): void { - const returnValue = files.map((f) => ({ filename: f })); + const returnValue = files.map((f) => ({ filename: f, status: "modified" })); paginateMock.mockReturnValue(returnValue); }