Merge pull request #393 from davelosert/write-summary-to-pr

Add Feature: Write Summary as comment to the pull request
This commit is contained in:
Federico Builes
2023-02-16 14:44:03 +01:00
committed by GitHub
9 changed files with 349 additions and 251 deletions

View File

@@ -66,25 +66,25 @@ jobs:
Configure this action by either inlining these options in your workflow file, or by using an external configuration file. All configuration options are optional.
| Option | Usage | Possible values | Default value |
|-----------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------|---------------|
| `fail-on-severity` | Defines the threshold for the level of severity. The action will fail on any pull requests that introduce vulnerabilities of the specified severity level or higher. | `low`, `moderate`, `high`, `critical` | `low` |
| `allow-licenses`* | Contains a list of allowed licenses. The action will fail on pull requests that introduce dependencies with licenses that do not match the list. | Any [SPDX-compliant identifier(s)](https://spdx.org/licenses/) | none |
| `deny-licenses`* | Contains a list of prohibited licenses. The action will fail on pull requests that introduce dependencies with licenses that match the list. | Any [SPDX-compliant identifier(s)](https://spdx.org/licenses/) | none |
| `fail-on-scopes`† | Contains a list of strings of the build environments you want to support. The action will fail on pull requests that introduce vulnerabilities in the scopes that match the list. |`runtime`, `development`, `unknown` | `runtime` |
| `allow-ghsas` | Contains a list of GitHub Advisory Database IDs that can be skipped during detection. | Any GHSAs from the [GitHub Advisory Database](https://github.com/advisories) | none |
| `license-check` | Enable or disable the license check performed by the action. | `true`, `false` | `true` |
| `vulnerability-check` | Enable or disable the vulnerability check performed by the action. | `true`, `false` | `true` |
| `base-ref`/`head-ref` | Provide custom git references for the git base/head when performing the comparison check. This is only used for event types other than `pull_request` and `pull_request_target`. | Any valid git ref(s) in your project | none |
| Option | Usage | Possible values | Default value |
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ------------- |
| `fail-on-severity` | Defines the threshold for the level of severity. The action will fail on any pull requests that introduce vulnerabilities of the specified severity level or higher. | `low`, `moderate`, `high`, `critical` | `low` |
| `allow-licenses`* | Contains a list of allowed licenses. The action will fail on pull requests that introduce dependencies with licenses that do not match the list. | Any [SPDX-compliant identifier(s)](https://spdx.org/licenses/) | none |
| `deny-licenses`* | Contains a list of prohibited licenses. The action will fail on pull requests that introduce dependencies with licenses that match the list. | Any [SPDX-compliant identifier(s)](https://spdx.org/licenses/) | none |
| `fail-on-scopes` | Contains a list of strings of the build environments you want to support. The action will fail on pull requests that introduce vulnerabilities in the scopes that match the list. | `runtime`, `development`, `unknown` | `runtime` |
| `allow-ghsas` | Contains a list of GitHub Advisory Database IDs that can be skipped during detection. | Any GHSAs from the [GitHub Advisory Database](https://github.com/advisories) | none |
| `license-check` | Enable or disable the license check performed by the action. | `true`, `false` | `true` |
| `vulnerability-check` | Enable or disable the vulnerability check performed by the action. | `true`, `false` | `true` |
| `base-ref`/`head-ref` | Provide custom git references for the git base/head when performing the comparison check. This is only used for event types other than `pull_request` and `pull_request_target`. | Any valid git ref(s) in your project | none |
| `comment-summary-in-pr` | Enable or disable reporting the review summary as a comment in the pull request. If enabled, you must give the workflow or job permission `pull-requests: write`. | `true`, `false` | `false` |
*not supported for use with GitHub Enterprise Server
†will be supported with GitHub Enterprise Server 3.8
†will be supported with GitHub Enterprise Server 3.8
### Inline Configuration
You can pass options to the Dependency Review GitHub Action using your workflow file.
You can pass options to the Dependency Review GitHub Action using your workflow file.
#### Example
@@ -112,10 +112,10 @@ jobs:
You can use an external configuration file to specify the settings for this action. It can be a local file or a file in an external repository. Refer to the following options for the specification.
| Option | Usage | Possible values |
|-----------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------|
| `config-file` | A path to a file in the current repository or an external repository. Use this syntax for external files: `OWNER/REPOSITORY/FILENAME@BRANCH` | **Local file**: `./.github/dependency-review-config.yml` <br> **External repo**: `github/octorepo/dependency-review-config.yml@main` |
| `external-repo-token` | Specifies a token for fetching the configuration file. It is required if the file resides in a private external repository and for all GitHub Enterprise Server repositories. Create a token in [developer settings](https://github.com/settings/tokens). | Any token with `read` permissions to the repository hosting the config file. |
| Option | Usage | Possible values |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `config-file` | A path to a file in the current repository or an external repository. Use this syntax for external files: `OWNER/REPOSITORY/FILENAME@BRANCH` | **Local file**: `./.github/dependency-review-config.yml` <br> **External repo**: `github/octorepo/dependency-review-config.yml@main` |
| `external-repo-token` | Specifies a token for fetching the configuration file. It is required if the file resides in a private external repository and for all GitHub Enterprise Server repositories. Create a token in [developer settings](https://github.com/settings/tokens). | Any token with `read` permissions to the repository hosting the config file. |
#### Example
@@ -128,7 +128,7 @@ Start by specifying that you will be using an external configuration file:
config-file: './.github/dependency-review-config.yml'
```
And then create the file in the path you just specified:
And then create the file in the path you just specified:
```yaml
fail-on-severity: 'critical'

View File

@@ -22,7 +22,8 @@ function clearInputs() {
'VULNERABILITY-CHECK',
'CONFIG-FILE',
'BASE-REF',
'HEAD-REF'
'HEAD-REF',
'COMMENT-SUMMARY-IN-PR'
]
allowedOptions.forEach(option => {

View File

@@ -41,6 +41,9 @@ inputs:
vulnerability-check:
description: A boolean to determine if vulnerability checks should be performed
required: false
comment-summary-in-pr:
description: A boolean to determine if the report should be posted as a comment in the PR itself. Setting this to true requires you to give the workflow the write permissions for pull-requests
required: false
runs:
using: 'node16'
main: 'dist/index.js'

461
dist/index.js generated vendored
View File

@@ -1,6 +1,142 @@
require('./sourcemap-register.js');/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 5842:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.commentPr = void 0;
const github = __importStar(__nccwpck_require__(5438));
const core = __importStar(__nccwpck_require__(2186));
const githubUtils = __importStar(__nccwpck_require__(3030));
const retry = __importStar(__nccwpck_require__(6298));
const request_error_1 = __nccwpck_require__(537);
const retryingOctokit = githubUtils.GitHub.plugin(retry.retry);
const octo = new retryingOctokit(githubUtils.getOctokitOptions(core.getInput('repo-token', { required: true })));
// Comment Marker to identify an existing comment to update, so we don't spam the PR with comments
const COMMENT_MARKER = '<!-- dependency-review-pr-comment-marker -->';
function commentPr(summary) {
return __awaiter(this, void 0, void 0, function* () {
if (!github.context.payload.pull_request) {
core.warning('Not in the context of a pull request. Skipping comment creation.');
return;
}
const commentBody = `${summary.stringify()}\n\n${COMMENT_MARKER}`;
try {
const existingCommentId = yield findCommentByMarker(COMMENT_MARKER);
if (existingCommentId) {
yield octo.rest.issues.updateComment({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
comment_id: existingCommentId,
body: commentBody
});
}
else {
yield octo.rest.issues.createComment({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: github.context.payload.pull_request.number,
body: commentBody
});
}
}
catch (error) {
if (error instanceof request_error_1.RequestError && error.status === 403) {
core.warning(`Unable to write summary to pull-request. Make sure you are giving this workflow the permission 'pull-requests: write'.`);
}
else {
if (error instanceof Error) {
core.warning(`Unable to comment summary to pull-request, received error: ${error.message}`);
}
else {
core.warning('Unable to comment summary to pull-request: Unexpected fatal error');
}
}
}
});
}
exports.commentPr = commentPr;
function findCommentByMarker(commentBodyIncludes) {
var _a, e_1, _b, _c;
return __awaiter(this, void 0, void 0, function* () {
const commentsIterator = octo.paginate.iterator(octo.rest.issues.listComments, {
owner: github.context.repo.owner,
repo: github.context.repo.repo,
// We are already checking if we are in the context of a pull request in the caller
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
issue_number: github.context.payload.pull_request.number
});
try {
for (var _d = true, commentsIterator_1 = __asyncValues(commentsIterator), commentsIterator_1_1; commentsIterator_1_1 = yield commentsIterator_1.next(), _a = commentsIterator_1_1.done, !_a;) {
_c = commentsIterator_1_1.value;
_d = false;
try {
const { data: comments } = _c;
const existingComment = comments.find(comment => { var _a; return (_a = comment.body) === null || _a === void 0 ? void 0 : _a.includes(commentBodyIncludes); });
if (existingComment)
return existingComment.id;
}
finally {
_d = true;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_d && !_a && (_b = commentsIterator_1.return)) yield _b.call(commentsIterator_1);
}
finally { if (e_1) throw e_1.error; }
}
return undefined;
});
}
/***/ }),
/***/ 4966:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
@@ -322,6 +458,7 @@ const licenses_1 = __nccwpck_require__(3247);
const summary = __importStar(__nccwpck_require__(8608));
const git_refs_1 = __nccwpck_require__(1086);
const utils_1 = __nccwpck_require__(918);
const comment_pr_1 = __nccwpck_require__(5842);
function run() {
return __awaiter(this, void 0, void 0, function* () {
try {
@@ -354,6 +491,9 @@ function run() {
}
summary.addScannedDependencies(changes);
printScannedDependencies(changes);
if (config.comment_summary_in_pr) {
yield (0, comment_pr_1.commentPr)(core.summary);
}
}
catch (error) {
if (error instanceof request_error_1.RequestError && error.status === 404) {
@@ -539,7 +679,8 @@ exports.ConfigurationOptionsSchema = z
vulnerability_check: z.boolean().default(true),
config_file: z.string().optional(),
base_ref: z.string().optional(),
head_ref: z.string().optional()
head_ref: z.string().optional(),
comment_summary_in_pr: z.boolean().default(false)
})
.superRefine((config, context) => {
if (config.allow_licenses && config.deny_licenses) {
@@ -41013,7 +41154,7 @@ const isDirty = (x) => x.status === "dirty";
exports.isDirty = isDirty;
const isValid = (x) => x.status === "valid";
exports.isValid = isValid;
const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
const isAsync = (x) => typeof Promise !== undefined && x instanceof Promise;
exports.isAsync = isAsync;
@@ -41566,29 +41707,28 @@ class ZodType {
return this._refinement(refinement);
}
optional() {
return ZodOptional.create(this, this._def);
return ZodOptional.create(this);
}
nullable() {
return ZodNullable.create(this, this._def);
return ZodNullable.create(this);
}
nullish() {
return this.nullable().optional();
return this.optional().nullable();
}
array() {
return ZodArray.create(this, this._def);
return ZodArray.create(this);
}
promise() {
return ZodPromise.create(this, this._def);
return ZodPromise.create(this);
}
or(option) {
return ZodUnion.create([this, option], this._def);
return ZodUnion.create([this, option]);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
return ZodIntersection.create(this, incoming);
}
transform(transform) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform },
@@ -41597,7 +41737,6 @@ class ZodType {
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodDefault({
...processCreateParams(this._def),
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodDefault,
@@ -41607,15 +41746,14 @@ class ZodType {
return new ZodBranded({
typeName: ZodFirstPartyTypeKind.ZodBranded,
type: this,
...processCreateParams(this._def),
...processCreateParams(undefined),
});
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch,
});
}
@@ -41640,15 +41778,12 @@ exports.ZodType = ZodType;
exports.Schema = ZodType;
exports.ZodSchema = ZodType;
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[a-z][a-z0-9]*$/;
const uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
// from https://stackoverflow.com/a/46181/1550155
// old version: too slow, didn't support unicode
// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
//old email regex
// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
// eslint-disable-next-line
const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|([^-]([a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}))$/;
const emailRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
// interface IsDateStringOptions extends StringDateOptions {
/**
* Match any configuration
@@ -41659,7 +41794,7 @@ const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\
const datetimeRegex = (args) => {
if (args.precision) {
if (args.offset) {
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}:\\d{2})|Z)$`);
}
else {
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
@@ -41667,7 +41802,7 @@ const datetimeRegex = (args) => {
}
else if (args.precision === 0) {
if (args.offset) {
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}:\\d{2})|Z)$`);
}
else {
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
@@ -41675,7 +41810,7 @@ const datetimeRegex = (args) => {
}
else {
if (args.offset) {
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$`);
}
else {
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
@@ -41808,17 +41943,6 @@ class ZodString extends ZodType {
status.dirty();
}
}
else if (check.kind === "cuid2") {
if (!cuid2Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
(0, parseUtil_1.addIssueToContext)(ctx, {
validation: "cuid2",
code: ZodError_1.ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
}
else if (check.kind === "url") {
try {
new URL(input.data);
@@ -41907,9 +42031,6 @@ class ZodString extends ZodType {
cuid(message) {
return this._addCheck({ kind: "cuid", ...errorUtil_1.errorUtil.errToObj(message) });
}
cuid2(message) {
return this._addCheck({ kind: "cuid2", ...errorUtil_1.errorUtil.errToObj(message) });
}
datetime(options) {
var _a;
if (typeof options === "string") {
@@ -41984,9 +42105,6 @@ class ZodString extends ZodType {
get isCUID() {
return !!this._def.checks.find((ch) => ch.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
}
get minLength() {
let min = null;
for (const ch of this._def.checks) {
@@ -42228,27 +42346,7 @@ class ZodNumber extends ZodType {
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" ||
(ch.kind === "multipleOf" && util_1.util.isInteger(ch.value)));
}
get isFinite() {
let max = null, min = null;
for (const ch of this._def.checks) {
if (ch.kind === "finite" ||
ch.kind === "int" ||
ch.kind === "multipleOf") {
return true;
}
else if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
else if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return Number.isFinite(min) && Number.isFinite(max);
return !!this._def.checks.find((ch) => ch.kind === "int");
}
}
exports.ZodNumber = ZodNumber;
@@ -42620,13 +42718,13 @@ class ZodArray extends ZodType {
}
}
if (ctx.common.async) {
return Promise.all([...ctx.data].map((item, i) => {
return Promise.all(ctx.data.map((item, i) => {
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
})).then((result) => {
return parseUtil_1.ParseStatus.mergeArray(status, result);
});
}
const result = [...ctx.data].map((item, i) => {
const result = ctx.data.map((item, i) => {
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
});
return parseUtil_1.ParseStatus.mergeArray(status, result);
@@ -42683,6 +42781,15 @@ var objectUtil;
};
};
})(objectUtil = exports.objectUtil || (exports.objectUtil = {}));
const AugmentFactory = (def) => (augmentation) => {
return new ZodObject({
...def,
shape: () => ({
...def.shape(),
...augmentation,
}),
});
};
function deepPartialify(schema) {
if (schema instanceof ZodObject) {
const newShape = {};
@@ -42720,43 +42827,8 @@ class ZodObject extends ZodType {
* If you want to pass through unknown properties, use `.passthrough()` instead.
*/
this.nonstrict = this.passthrough;
// extend<
// Augmentation extends ZodRawShape,
// NewOutput extends util.flatten<{
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
// ? Augmentation[k]["_output"]
// : k extends keyof Output
// ? Output[k]
// : never;
// }>,
// NewInput extends util.flatten<{
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
// ? Augmentation[k]["_input"]
// : k extends keyof Input
// ? Input[k]
// : never;
// }>
// >(
// augmentation: Augmentation
// ): ZodObject<
// extendShape<T, Augmentation>,
// UnknownKeys,
// Catchall,
// NewOutput,
// NewInput
// > {
// return new ZodObject({
// ...this._def,
// shape: () => ({
// ...this._def.shape(),
// ...augmentation,
// }),
// }) as any;
// }
/**
* @deprecated Use `.extend` instead
* */
this.augment = this.extend;
this.augment = AugmentFactory(this._def);
this.extend = AugmentFactory(this._def);
}
_getCached() {
if (this._cached !== null)
@@ -42894,31 +42966,8 @@ class ZodObject extends ZodType {
unknownKeys: "passthrough",
});
}
// const AugmentFactory =
// <Def extends ZodObjectDef>(def: Def) =>
// <Augmentation extends ZodRawShape>(
// augmentation: Augmentation
// ): ZodObject<
// extendShape<ReturnType<Def["shape"]>, Augmentation>,
// Def["unknownKeys"],
// Def["catchall"]
// > => {
// return new ZodObject({
// ...def,
// shape: () => ({
// ...def.shape(),
// ...augmentation,
// }),
// }) as any;
// };
extend(augmentation) {
return new ZodObject({
...this._def,
shape: () => ({
...this._def.shape(),
...augmentation,
}),
});
setKey(key, schema) {
return this.augment({ [key]: schema });
}
/**
* Prior to zod@1.0.12 there was a bug in the
@@ -42926,6 +42975,10 @@ class ZodObject extends ZodType {
* upgrade if you are experiencing issues.
*/
merge(merging) {
// const mergedShape = objectUtil.mergeShapes(
// this._def.shape(),
// merging._def.shape()
// );
const merged = new ZodObject({
unknownKeys: merging._def.unknownKeys,
catchall: merging._def.catchall,
@@ -42934,65 +42987,6 @@ class ZodObject extends ZodType {
});
return merged;
}
// merge<
// Incoming extends AnyZodObject,
// Augmentation extends Incoming["shape"],
// NewOutput extends {
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
// ? Augmentation[k]["_output"]
// : k extends keyof Output
// ? Output[k]
// : never;
// },
// NewInput extends {
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
// ? Augmentation[k]["_input"]
// : k extends keyof Input
// ? Input[k]
// : never;
// }
// >(
// merging: Incoming
// ): ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"],
// NewOutput,
// NewInput
// > {
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
setKey(key, schema) {
return this.augment({ [key]: schema });
}
// merge<Incoming extends AnyZodObject>(
// merging: Incoming
// ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
// ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"]
// > {
// // const mergedShape = objectUtil.mergeShapes(
// // this._def.shape(),
// // merging._def.shape()
// // );
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
catchall(index) {
return new ZodObject({
...this._def,
@@ -43001,10 +42995,10 @@ class ZodObject extends ZodType {
}
pick(mask) {
const shape = {};
util_1.util.objectKeys(mask).forEach((key) => {
if (mask[key] && this.shape[key]) {
util_1.util.objectKeys(mask).map((key) => {
// only add to shape if key corresponds to an element of the current shape
if (this.shape[key])
shape[key] = this.shape[key];
}
});
return new ZodObject({
...this._def,
@@ -43013,8 +43007,8 @@ class ZodObject extends ZodType {
}
omit(mask) {
const shape = {};
util_1.util.objectKeys(this.shape).forEach((key) => {
if (!mask[key]) {
util_1.util.objectKeys(this.shape).map((key) => {
if (util_1.util.objectKeys(mask).indexOf(key) === -1) {
shape[key] = this.shape[key];
}
});
@@ -43028,15 +43022,26 @@ class ZodObject extends ZodType {
}
partial(mask) {
const newShape = {};
util_1.util.objectKeys(this.shape).forEach((key) => {
const fieldSchema = this.shape[key];
if (mask && !mask[key]) {
newShape[key] = fieldSchema;
}
else {
if (mask) {
util_1.util.objectKeys(this.shape).map((key) => {
if (util_1.util.objectKeys(mask).indexOf(key) === -1) {
newShape[key] = this.shape[key];
}
else {
newShape[key] = this.shape[key].optional();
}
});
return new ZodObject({
...this._def,
shape: () => newShape,
});
}
else {
for (const key in this.shape) {
const fieldSchema = this.shape[key];
newShape[key] = fieldSchema.optional();
}
});
}
return new ZodObject({
...this._def,
shape: () => newShape,
@@ -43044,11 +43049,23 @@ class ZodObject extends ZodType {
}
required(mask) {
const newShape = {};
util_1.util.objectKeys(this.shape).forEach((key) => {
if (mask && !mask[key]) {
newShape[key] = this.shape[key];
}
else {
if (mask) {
util_1.util.objectKeys(this.shape).map((key) => {
if (util_1.util.objectKeys(mask).indexOf(key) === -1) {
newShape[key] = this.shape[key];
}
else {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = newField._def.innerType;
}
newShape[key] = newField;
}
});
}
else {
for (const key in this.shape) {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
@@ -43056,7 +43073,7 @@ class ZodObject extends ZodType {
}
newShape[key] = newField;
}
});
}
return new ZodObject({
...this._def,
shape: () => newShape,
@@ -43441,7 +43458,7 @@ class ZodTuple extends ZodType {
});
status.dirty();
}
const items = [...ctx.data]
const items = ctx.data
.map((item, itemIndex) => {
const schema = this._def.items[itemIndex] || this._def.rest;
if (!schema)
@@ -43827,7 +43844,6 @@ class ZodLiteral extends ZodType {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
(0, parseUtil_1.addIssueToContext)(ctx, {
received: ctx.data,
code: ZodError_1.ZodIssueCode.invalid_literal,
expected: this._def.value,
});
@@ -43902,12 +43918,6 @@ class ZodEnum extends ZodType {
}
return enumValues;
}
extract(values) {
return ZodEnum.create(values);
}
exclude(values) {
return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
}
}
exports.ZodEnum = ZodEnum;
ZodEnum.create = createZodEnum;
@@ -43949,9 +43959,6 @@ ZodNativeEnum.create = (values, params) => {
});
};
class ZodPromise extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== util_1.ZodParsedType.promise &&
@@ -44197,30 +44204,24 @@ class ZodCatch extends ZodType {
const result = this._def.innerType._parse({
data: ctx.data,
path: ctx.path,
parent: {
...ctx,
common: {
...ctx.common,
issues: [], // don't collect issues from inner type
},
},
parent: ctx,
});
if ((0, parseUtil_1.isAsync)(result)) {
return result.then((result) => {
return {
status: "valid",
value: result.status === "valid" ? result.value : this._def.catchValue(),
value: result.status === "valid" ? result.value : this._def.defaultValue(),
};
});
}
else {
return {
status: "valid",
value: result.status === "valid" ? result.value : this._def.catchValue(),
value: result.status === "valid" ? result.value : this._def.defaultValue(),
};
}
}
removeCatch() {
removeDefault() {
return this._def.innerType;
}
}
@@ -44229,7 +44230,9 @@ ZodCatch.create = (type, params) => {
return new ZodCatch({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodCatch,
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
defaultValue: typeof params.default === "function"
? params.default
: () => params.default,
...processCreateParams(params),
});
};
@@ -44472,10 +44475,7 @@ exports.oboolean = oboolean;
exports.coerce = {
string: ((arg) => ZodString.create({ ...arg, coerce: true })),
number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
boolean: ((arg) => ZodBoolean.create({
...arg,
coerce: true,
})),
boolean: ((arg) => ZodBoolean.create({ ...arg, coerce: true })),
bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
date: ((arg) => ZodDate.create({ ...arg, coerce: true })),
};
@@ -44555,6 +44555,7 @@ function readInlineConfig() {
const vulnerability_check = getOptionalBoolean('vulnerability-check');
const base_ref = getOptionalInput('base-ref');
const head_ref = getOptionalInput('head-ref');
const comment_summary_in_pr = getOptionalBoolean('comment-summary-in-pr');
validateLicenses('allow-licenses', allow_licenses);
validateLicenses('deny-licenses', deny_licenses);
const keys = {
@@ -44566,7 +44567,8 @@ function readInlineConfig() {
license_check,
vulnerability_check,
base_ref,
head_ref
head_ref,
comment_summary_in_pr
};
return Object.fromEntries(Object.entries(keys).filter(([_, value]) => value !== undefined));
}
@@ -44831,7 +44833,8 @@ exports.ConfigurationOptionsSchema = z
vulnerability_check: z.boolean().default(true),
config_file: z.string().optional(),
base_ref: z.string().optional(),
head_ref: z.string().optional()
head_ref: z.string().optional(),
comment_summary_in_pr: z.boolean().default(false)
})
.superRefine((config, context) => {
if (config.allow_licenses && config.deny_licenses) {

2
dist/index.js.map generated vendored

File diff suppressed because one or more lines are too long

84
src/comment-pr.ts Normal file
View File

@@ -0,0 +1,84 @@
import * as github from '@actions/github'
import * as core from '@actions/core'
import * as githubUtils from '@actions/github/lib/utils'
import * as retry from '@octokit/plugin-retry'
import {RequestError} from '@octokit/request-error'
const retryingOctokit = githubUtils.GitHub.plugin(retry.retry)
const octo = new retryingOctokit(
githubUtils.getOctokitOptions(core.getInput('repo-token', {required: true}))
)
// Comment Marker to identify an existing comment to update, so we don't spam the PR with comments
const COMMENT_MARKER = '<!-- dependency-review-pr-comment-marker -->'
export async function commentPr(summary: typeof core.summary): Promise<void> {
if (!github.context.payload.pull_request) {
core.warning(
'Not in the context of a pull request. Skipping comment creation.'
)
return
}
const commentBody = `${summary.stringify()}\n\n${COMMENT_MARKER}`
try {
const existingCommentId = await findCommentByMarker(COMMENT_MARKER)
if (existingCommentId) {
await octo.rest.issues.updateComment({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
comment_id: existingCommentId,
body: commentBody
})
} else {
await octo.rest.issues.createComment({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: github.context.payload.pull_request.number,
body: commentBody
})
}
} catch (error) {
if (error instanceof RequestError && error.status === 403) {
core.warning(
`Unable to write summary to pull-request. Make sure you are giving this workflow the permission 'pull-requests: write'.`
)
} else {
if (error instanceof Error) {
core.warning(
`Unable to comment summary to pull-request, received error: ${error.message}`
)
} else {
core.warning(
'Unable to comment summary to pull-request: Unexpected fatal error'
)
}
}
}
}
async function findCommentByMarker(
commentBodyIncludes: string
): Promise<number | undefined> {
const commentsIterator = octo.paginate.iterator(
octo.rest.issues.listComments,
{
owner: github.context.repo.owner,
repo: github.context.repo.repo,
// We are already checking if we are in the context of a pull request in the caller
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
issue_number: github.context.payload.pull_request!.number
}
)
for await (const {data: comments} of commentsIterator) {
const existingComment = comments.find(comment =>
comment.body?.includes(commentBodyIncludes)
)
if (existingComment) return existingComment.id
}
return undefined
}

View File

@@ -34,6 +34,7 @@ function readInlineConfig(): ConfigurationOptionsPartial {
const vulnerability_check = getOptionalBoolean('vulnerability-check')
const base_ref = getOptionalInput('base-ref')
const head_ref = getOptionalInput('head-ref')
const comment_summary_in_pr = getOptionalBoolean('comment-summary-in-pr')
validateLicenses('allow-licenses', allow_licenses)
validateLicenses('deny-licenses', deny_licenses)
@@ -47,7 +48,8 @@ function readInlineConfig(): ConfigurationOptionsPartial {
license_check,
vulnerability_check,
base_ref,
head_ref
head_ref,
comment_summary_in_pr
}
return Object.fromEntries(

View File

@@ -15,6 +15,7 @@ import * as summary from './summary'
import {getRefs} from './git-refs'
import {groupDependenciesByManifest} from './utils'
import {commentPr} from './comment-pr'
async function run(): Promise<void> {
try {
@@ -69,6 +70,9 @@ async function run(): Promise<void> {
summary.addScannedDependencies(changes)
printScannedDependencies(changes)
if (config.comment_summary_in_pr) {
await commentPr(core.summary)
}
} catch (error) {
if (error instanceof RequestError && error.status === 404) {
core.setFailed(

View File

@@ -45,7 +45,8 @@ export const ConfigurationOptionsSchema = z
vulnerability_check: z.boolean().default(true),
config_file: z.string().optional(),
base_ref: z.string().optional(),
head_ref: z.string().optional()
head_ref: z.string().optional(),
comment_summary_in_pr: z.boolean().default(false)
})
.superRefine((config, context) => {
if (config.allow_licenses && config.deny_licenses) {