From af4220990aab71f34342e16a6543798099b715ff Mon Sep 17 00:00:00 2001 From: TIOBE <123092508+it-tiobe@users.noreply.github.com> Date: Thu, 13 Apr 2023 15:14:27 +0000 Subject: [PATCH] Build dist after push to main --- dist/index.js | 2571 +++++++++++++++++++++-------------------- dist/setup-sandbox.js | 25 +- 2 files changed, 1309 insertions(+), 1287 deletions(-) diff --git a/dist/index.js b/dist/index.js index 6bee8118..65199f1d 100644 --- a/dist/index.js +++ b/dist/index.js @@ -5,69 +5,69 @@ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.viewerUrl = exports.baseUrl = exports.requestInit = exports.octokit = exports.ticsConfig = exports.githubConfig = void 0; -const core_1 = __nccwpck_require__(2186); -const github_1 = __nccwpck_require__(5438); -const proxy_agent_1 = __importDefault(__nccwpck_require__(7367)); -const fs_1 = __nccwpck_require__(7147); -const api_helper_1 = __nccwpck_require__(3823); -const os_1 = __nccwpck_require__(2037); -const payload = process.env.GITHUB_EVENT_PATH ? JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, 'utf8')) : ''; -const pullRequestNumber = payload.pull_request ? payload.pull_request.number : ''; -exports.githubConfig = { - repo: process.env.GITHUB_REPOSITORY ? process.env.GITHUB_REPOSITORY : '', - owner: process.env.GITHUB_REPOSITORY ? process.env.GITHUB_REPOSITORY.split('/')[0] : '', - reponame: process.env.GITHUB_REPOSITORY ? process.env.GITHUB_REPOSITORY.split('/')[1] : '', - branchname: process.env.GITHUB_HEAD_REF ? process.env.GITHUB_HEAD_REF : '', - basebranchname: process.env.GITHUB_BASE_REF ? process.env.GITHUB_BASE_REF : '', - branchdir: process.env.GITHUB_WORKSPACE ? process.env.GITHUB_WORKSPACE : '', - eventName: process.env.GITHUB_EVENT_NAME ? process.env.GITHUB_EVENT_NAME : '', - runnerOS: process.env.RUNNER_OS ? process.env.RUNNER_OS : '', - pullRequestNumber: process.env.PULL_REQUEST_NUMBER ? process.env.PULL_REQUEST_NUMBER : pullRequestNumber, - debugger: (0, core_1.isDebug)() -}; -function getSecretsFilter(secretsFilter) { - const defaults = ['TICSAUTHTOKEN', 'GITHUB_TOKEN', 'Authentication token']; - const keys = secretsFilter ? secretsFilter.split(',').filter(s => s !== '') : []; - const combinedFilters = defaults.concat(keys); - if (exports.githubConfig.debugger) - process.stdout.write(`::debug::SecretsFilter: ${JSON.stringify(combinedFilters) + os_1.EOL}`); - return combinedFilters; -} -exports.ticsConfig = { - githubToken: (0, core_1.getInput)('githubToken', { required: true }), - projectName: (0, core_1.getInput)('projectName', { required: true }), - ticsConfiguration: (0, core_1.getInput)('ticsConfiguration', { required: true }), - additionalFlags: (0, core_1.getInput)('additionalFlags'), - branchDir: (0, core_1.getInput)('branchDir'), - branchName: (0, core_1.getInput)('branchName'), - clientData: (0, core_1.getInput)('clientData'), - codetype: (0, core_1.getInput)('codetype'), - calc: (0, core_1.getInput)('calc'), - excludeMovedFiles: (0, core_1.getBooleanInput)('excludeMovedFiles'), - hostnameVerification: (0, core_1.getInput)('hostnameVerification'), - installTics: (0, core_1.getBooleanInput)('installTics'), - mode: (0, core_1.getInput)('mode'), - nocalc: (0, core_1.getInput)('nocalc'), - norecalc: (0, core_1.getInput)('norecalc'), - postAnnotations: (0, core_1.getBooleanInput)('postAnnotations'), - pullRequestApproval: (0, core_1.getBooleanInput)('pullRequestApproval'), - recalc: (0, core_1.getInput)('recalc'), - ticsAuthToken: (0, core_1.getInput)('ticsAuthToken'), - tmpDir: (0, core_1.getInput)('tmpDir'), - trustStrategy: (0, core_1.getInput)('trustStrategy'), - secretsFilter: getSecretsFilter((0, core_1.getInput)('secretsFilter')), - viewerUrl: (0, core_1.getInput)('viewerUrl') -}; -exports.octokit = (0, github_1.getOctokit)(exports.ticsConfig.githubToken); -exports.requestInit = { agent: new proxy_agent_1.default(), headers: {} }; -exports.baseUrl = (0, api_helper_1.getTicsWebBaseUrlFromUrl)(exports.ticsConfig.ticsConfiguration); -exports.viewerUrl = exports.ticsConfig.viewerUrl ? exports.ticsConfig.viewerUrl.replace(/\/+$/, '') : exports.baseUrl; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.viewerUrl = exports.baseUrl = exports.requestInit = exports.octokit = exports.ticsConfig = exports.githubConfig = void 0; +const core_1 = __nccwpck_require__(2186); +const github_1 = __nccwpck_require__(5438); +const proxy_agent_1 = __importDefault(__nccwpck_require__(7367)); +const fs_1 = __nccwpck_require__(7147); +const api_helper_1 = __nccwpck_require__(3823); +const os_1 = __nccwpck_require__(2037); +const payload = process.env.GITHUB_EVENT_PATH ? JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, 'utf8')) : ''; +const pullRequestNumber = payload.pull_request ? payload.pull_request.number : ''; +exports.githubConfig = { + repo: process.env.GITHUB_REPOSITORY ? process.env.GITHUB_REPOSITORY : '', + owner: process.env.GITHUB_REPOSITORY ? process.env.GITHUB_REPOSITORY.split('/')[0] : '', + reponame: process.env.GITHUB_REPOSITORY ? process.env.GITHUB_REPOSITORY.split('/')[1] : '', + branchname: process.env.GITHUB_HEAD_REF ? process.env.GITHUB_HEAD_REF : '', + basebranchname: process.env.GITHUB_BASE_REF ? process.env.GITHUB_BASE_REF : '', + branchdir: process.env.GITHUB_WORKSPACE ? process.env.GITHUB_WORKSPACE : '', + eventName: process.env.GITHUB_EVENT_NAME ? process.env.GITHUB_EVENT_NAME : '', + runnerOS: process.env.RUNNER_OS ? process.env.RUNNER_OS : '', + pullRequestNumber: process.env.PULL_REQUEST_NUMBER ? process.env.PULL_REQUEST_NUMBER : pullRequestNumber, + debugger: (0, core_1.isDebug)() +}; +function getSecretsFilter(secretsFilter) { + const defaults = ['TICSAUTHTOKEN', 'GITHUB_TOKEN', 'Authentication token']; + const keys = secretsFilter ? secretsFilter.split(',').filter(s => s !== '') : []; + const combinedFilters = defaults.concat(keys); + if (exports.githubConfig.debugger) + process.stdout.write(`::debug::SecretsFilter: ${JSON.stringify(combinedFilters) + os_1.EOL}`); + return combinedFilters; +} +exports.ticsConfig = { + githubToken: (0, core_1.getInput)('githubToken', { required: true }), + projectName: (0, core_1.getInput)('projectName', { required: true }), + ticsConfiguration: (0, core_1.getInput)('ticsConfiguration', { required: true }), + additionalFlags: (0, core_1.getInput)('additionalFlags'), + branchDir: (0, core_1.getInput)('branchDir'), + branchName: (0, core_1.getInput)('branchName'), + clientData: (0, core_1.getInput)('clientData'), + codetype: (0, core_1.getInput)('codetype'), + calc: (0, core_1.getInput)('calc'), + excludeMovedFiles: (0, core_1.getBooleanInput)('excludeMovedFiles'), + hostnameVerification: (0, core_1.getInput)('hostnameVerification'), + installTics: (0, core_1.getBooleanInput)('installTics'), + mode: (0, core_1.getInput)('mode'), + nocalc: (0, core_1.getInput)('nocalc'), + norecalc: (0, core_1.getInput)('norecalc'), + postAnnotations: (0, core_1.getBooleanInput)('postAnnotations'), + pullRequestApproval: (0, core_1.getBooleanInput)('pullRequestApproval'), + recalc: (0, core_1.getInput)('recalc'), + ticsAuthToken: (0, core_1.getInput)('ticsAuthToken'), + tmpDir: (0, core_1.getInput)('tmpDir'), + trustStrategy: (0, core_1.getInput)('trustStrategy'), + secretsFilter: getSecretsFilter((0, core_1.getInput)('secretsFilter')), + viewerUrl: (0, core_1.getInput)('viewerUrl') +}; +exports.octokit = (0, github_1.getOctokit)(exports.ticsConfig.githubToken); +exports.requestInit = { agent: new proxy_agent_1.default(), headers: {} }; +exports.baseUrl = (0, api_helper_1.getTicsWebBaseUrlFromUrl)(exports.ticsConfig.ticsConfiguration); +exports.viewerUrl = exports.ticsConfig.viewerUrl ? exports.ticsConfig.viewerUrl.replace(/\/+$/, '') : exports.baseUrl; /***/ }), @@ -76,33 +76,33 @@ exports.viewerUrl = exports.ticsConfig.viewerUrl ? exports.ticsConfig.viewerUrl. /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getPostedReviewComments = void 0; -const logger_1 = __importDefault(__nccwpck_require__(6440)); -const configuration_1 = __nccwpck_require__(5527); -/** - * Gets a list of all reviews posted on the pull request. - * @returns List of reviews posted on the pull request. - */ -async function getPostedReviewComments() { - try { - logger_1.default.Instance.info('Retrieving posted review comments.'); - const params = { - owner: configuration_1.githubConfig.owner, - repo: configuration_1.githubConfig.reponame, - pull_number: configuration_1.githubConfig.pullRequestNumber - }; - return await configuration_1.octokit.paginate(configuration_1.octokit.rest.pulls.listReviewComments, params); - } - catch (error) { - logger_1.default.Instance.error(`Could not retrieve the review comments: ${error.message}`); - } -} -exports.getPostedReviewComments = getPostedReviewComments; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getPostedReviewComments = void 0; +const logger_1 = __importDefault(__nccwpck_require__(6440)); +const configuration_1 = __nccwpck_require__(5527); +/** + * Gets a list of all reviews posted on the pull request. + * @returns List of reviews posted on the pull request. + */ +async function getPostedReviewComments() { + try { + logger_1.default.Instance.info('Retrieving posted review comments.'); + const params = { + owner: configuration_1.githubConfig.owner, + repo: configuration_1.githubConfig.reponame, + pull_number: configuration_1.githubConfig.pullRequestNumber + }; + return await configuration_1.octokit.paginate(configuration_1.octokit.rest.pulls.listReviewComments, params); + } + catch (error) { + logger_1.default.Instance.error(`Could not retrieve the review comments: ${error.message}`); + } +} +exports.getPostedReviewComments = getPostedReviewComments; /***/ }), @@ -111,71 +111,71 @@ exports.getPostedReviewComments = getPostedReviewComments; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.changedFilesToFile = exports.getChangedFiles = void 0; -const fs_1 = __nccwpck_require__(7147); -const canonical_path_1 = __nccwpck_require__(5806); -const logger_1 = __importDefault(__nccwpck_require__(6440)); -const configuration_1 = __nccwpck_require__(5527); -/** - * Sends a request to retrieve the changed files for a given pull request to the GitHub API. - * @returns List of changed files within the GitHub Pull request. - */ -async function getChangedFiles() { - const params = { - owner: configuration_1.githubConfig.owner, - repo: configuration_1.githubConfig.reponame, - pull_number: configuration_1.githubConfig.pullRequestNumber - }; - try { - logger_1.default.Instance.header('Retrieving changed files.'); - const response = await configuration_1.octokit.paginate(configuration_1.octokit.rest.pulls.listFiles, params, response => { - return response.data - .filter(item => { - if (item.status === 'renamed') { - // If a files has been moved without changes or if moved files are excluded, exclude them. - if (configuration_1.ticsConfig.excludeMovedFiles || item.changes === 0) { - return false; - } - } - return true; - }) - .map(item => { - // If a file is moved or renamed the status is 'renamed'. - item.filename = (0, canonical_path_1.normalize)(item.filename); - logger_1.default.Instance.debug(item.filename); - return item; - }); - }); - logger_1.default.Instance.info('Retrieved changed files.'); - return response; - } - catch (error) { - logger_1.default.Instance.exit(`Could not retrieve the changed files: ${error}`); - } -} -exports.getChangedFiles = getChangedFiles; -/** - * Creates a file containing all the changed files based on the given changedFiles. - * @param changedFiles List of changed files. - * @returns Location of the written file. - */ -function changedFilesToFile(changedFiles) { - logger_1.default.Instance.header('Writing changedFiles to file'); - let contents = ''; - changedFiles.forEach(item => { - contents += item.filename + '\n'; - }); - const fileListPath = (0, canonical_path_1.resolve)('changedFiles.txt'); - (0, fs_1.writeFileSync)(fileListPath, contents); - logger_1.default.Instance.info(`Content written to: ${fileListPath}`); - return fileListPath; -} -exports.changedFilesToFile = changedFilesToFile; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.changedFilesToFile = exports.getChangedFiles = void 0; +const fs_1 = __nccwpck_require__(7147); +const canonical_path_1 = __nccwpck_require__(5806); +const logger_1 = __importDefault(__nccwpck_require__(6440)); +const configuration_1 = __nccwpck_require__(5527); +/** + * Sends a request to retrieve the changed files for a given pull request to the GitHub API. + * @returns List of changed files within the GitHub Pull request. + */ +async function getChangedFiles() { + const params = { + owner: configuration_1.githubConfig.owner, + repo: configuration_1.githubConfig.reponame, + pull_number: configuration_1.githubConfig.pullRequestNumber + }; + try { + logger_1.default.Instance.header('Retrieving changed files.'); + const response = await configuration_1.octokit.paginate(configuration_1.octokit.rest.pulls.listFiles, params, response => { + return response.data + .filter(item => { + if (item.status === 'renamed') { + // If a files has been moved without changes or if moved files are excluded, exclude them. + if (configuration_1.ticsConfig.excludeMovedFiles || item.changes === 0) { + return false; + } + } + return true; + }) + .map(item => { + // If a file is moved or renamed the status is 'renamed'. + item.filename = (0, canonical_path_1.normalize)(item.filename); + logger_1.default.Instance.debug(item.filename); + return item; + }); + }); + logger_1.default.Instance.info('Retrieved changed files.'); + return response; + } + catch (error) { + logger_1.default.Instance.exit(`Could not retrieve the changed files: ${error}`); + } +} +exports.getChangedFiles = getChangedFiles; +/** + * Creates a file containing all the changed files based on the given changedFiles. + * @param changedFiles List of changed files. + * @returns Location of the written file. + */ +function changedFilesToFile(changedFiles) { + logger_1.default.Instance.header('Writing changedFiles to file'); + let contents = ''; + changedFiles.forEach(item => { + contents += item.filename + '\n'; + }); + const fileListPath = (0, canonical_path_1.resolve)('changedFiles.txt'); + (0, fs_1.writeFileSync)(fileListPath, contents); + logger_1.default.Instance.info(`Content written to: ${fileListPath}`); + return fileListPath; +} +exports.changedFilesToFile = changedFilesToFile; /***/ }), @@ -184,38 +184,38 @@ exports.changedFilesToFile = changedFilesToFile; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.deletePreviousReviewComments = void 0; -const logger_1 = __importDefault(__nccwpck_require__(6440)); -const configuration_1 = __nccwpck_require__(5527); -/** - * Deletes the review comments of previous runs. - * @param postedReviewComments Previously posted review comments. - */ -async function deletePreviousReviewComments(postedReviewComments) { - logger_1.default.Instance.header('Deleting review comments of previous runs.'); - postedReviewComments.map(async (reviewComment) => { - if (reviewComment.body.substring(0, 17) === ':warning: **TiCS:') { - try { - const params = { - owner: configuration_1.githubConfig.owner, - repo: configuration_1.githubConfig.reponame, - comment_id: reviewComment.id - }; - await configuration_1.octokit.rest.pulls.deleteReviewComment(params); - } - catch (error) { - logger_1.default.Instance.error(`Could not delete review comment: ${error.message}`); - } - } - }); - logger_1.default.Instance.info('Deleted review comments of previous runs.'); -} -exports.deletePreviousReviewComments = deletePreviousReviewComments; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.deletePreviousReviewComments = void 0; +const logger_1 = __importDefault(__nccwpck_require__(6440)); +const configuration_1 = __nccwpck_require__(5527); +/** + * Deletes the review comments of previous runs. + * @param postedReviewComments Previously posted review comments. + */ +async function deletePreviousReviewComments(postedReviewComments) { + logger_1.default.Instance.header('Deleting review comments of previous runs.'); + postedReviewComments.map(async (reviewComment) => { + if (reviewComment.body.substring(0, 17) === ':warning: **TiCS:') { + try { + const params = { + owner: configuration_1.githubConfig.owner, + repo: configuration_1.githubConfig.reponame, + comment_id: reviewComment.id + }; + await configuration_1.octokit.rest.pulls.deleteReviewComment(params); + } + catch (error) { + logger_1.default.Instance.error(`Could not delete review comment: ${error.message}`); + } + } + }); + logger_1.default.Instance.info('Deleted review comments of previous runs.'); +} +exports.deletePreviousReviewComments = deletePreviousReviewComments; /***/ }), @@ -224,36 +224,36 @@ exports.deletePreviousReviewComments = deletePreviousReviewComments; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.postErrorComment = void 0; -const configuration_1 = __nccwpck_require__(5527); -const logger_1 = __importDefault(__nccwpck_require__(6440)); -const summary_1 = __nccwpck_require__(1502); -/** - * Create error comment on the pull request from the analysis given. - * @param analysis Analysis object returned from TiCS analysis. - */ -async function postErrorComment(analysis) { - try { - const params = { - owner: configuration_1.githubConfig.owner, - repo: configuration_1.githubConfig.reponame, - issue_number: configuration_1.githubConfig.pullRequestNumber, - body: (0, summary_1.createErrorSummary)(analysis.errorList, analysis.warningList) - }; - logger_1.default.Instance.header('Posting error summary in pull request.'); - await configuration_1.octokit.rest.issues.createComment(params); - logger_1.default.Instance.info('Posted the error summary in pull request.'); - } - catch (error) { - logger_1.default.Instance.error(`Posting the comment failed: ${error.message}`); - } -} -exports.postErrorComment = postErrorComment; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.postErrorComment = void 0; +const configuration_1 = __nccwpck_require__(5527); +const logger_1 = __importDefault(__nccwpck_require__(6440)); +const summary_1 = __nccwpck_require__(1502); +/** + * Create error comment on the pull request from the analysis given. + * @param analysis Analysis object returned from TiCS analysis. + */ +async function postErrorComment(analysis) { + try { + const params = { + owner: configuration_1.githubConfig.owner, + repo: configuration_1.githubConfig.reponame, + issue_number: configuration_1.githubConfig.pullRequestNumber, + body: (0, summary_1.createErrorSummary)(analysis.errorList, analysis.warningList) + }; + logger_1.default.Instance.header('Posting error summary in pull request.'); + await configuration_1.octokit.rest.issues.createComment(params); + logger_1.default.Instance.info('Posted the error summary in pull request.'); + } + catch (error) { + logger_1.default.Instance.error(`Posting the comment failed: ${error.message}`); + } +} +exports.postErrorComment = postErrorComment; /***/ }), @@ -262,71 +262,71 @@ exports.postErrorComment = postErrorComment; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.postNothingAnalyzedReview = exports.postReview = void 0; -const logger_1 = __importDefault(__nccwpck_require__(6440)); -const configuration_1 = __nccwpck_require__(5527); -const summary_1 = __nccwpck_require__(1502); -const enums_1 = __nccwpck_require__(1655); -const markdown_1 = __nccwpck_require__(5300); -/** - * Create review on the pull request from the analysis given. - * @param analysis Analysis object returned from TiCS analysis. - * @param filesAnalyzed List of all files analyzed by TiCS. - * @param qualityGate Quality gate returned by TiCS. - * @param reviewComments TiCS annotations in the form of review comments. - */ -async function postReview(analysis, filesAnalyzed, qualityGate, reviewComments) { - let body = (0, summary_1.createQualityGateSummary)(qualityGate); - body += analysis.explorerUrl ? (0, summary_1.createLinkSummary)(analysis.explorerUrl) : ''; - body += reviewComments && reviewComments.unpostable.length > 0 ? (0, summary_1.createUnpostableReviewCommentsSummary)(reviewComments.unpostable) : ''; - body += (0, summary_1.createFilesSummary)(filesAnalyzed); - const params = { - owner: configuration_1.githubConfig.owner, - repo: configuration_1.githubConfig.reponame, - pull_number: configuration_1.githubConfig.pullRequestNumber, - event: configuration_1.ticsConfig.pullRequestApproval ? (qualityGate.passed ? enums_1.Events.APPROVE : enums_1.Events.REQUEST_CHANGES) : enums_1.Events.COMMENT, - body: body, - comments: reviewComments ? reviewComments.postable : undefined - }; - try { - logger_1.default.Instance.header('Posting a review for this pull request.'); - await configuration_1.octokit.rest.pulls.createReview(params); - logger_1.default.Instance.info('Posted review for this pull request.'); - } - catch (error) { - logger_1.default.Instance.error(`Posting the review failed: ${error.message}`); - } -} -exports.postReview = postReview; -/** - * Create review on the pull request with a body and approval0. - * @param message Message to display in the body of the review. - * @param event Approve or request changes in the review. - */ -async function postNothingAnalyzedReview(message, event) { - const body = `## TiCS Analysis\n\n### ${(0, markdown_1.generateStatusMarkdown)(enums_1.Status[event === enums_1.Events.APPROVE ? 1 : 0], true)}\n\n${message}`; - const params = { - owner: configuration_1.githubConfig.owner, - repo: configuration_1.githubConfig.reponame, - pull_number: configuration_1.githubConfig.pullRequestNumber, - event: configuration_1.ticsConfig.pullRequestApproval ? event : enums_1.Events.COMMENT, - body: body - }; - try { - logger_1.default.Instance.header('Posting a review for this pull request.'); - await configuration_1.octokit.rest.pulls.createReview(params); - logger_1.default.Instance.info('Posted review for this pull request.'); - } - catch (error) { - logger_1.default.Instance.error(`Posting the review failed: ${error.message}`); - } -} -exports.postNothingAnalyzedReview = postNothingAnalyzedReview; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.postNothingAnalyzedReview = exports.postReview = void 0; +const logger_1 = __importDefault(__nccwpck_require__(6440)); +const configuration_1 = __nccwpck_require__(5527); +const summary_1 = __nccwpck_require__(1502); +const enums_1 = __nccwpck_require__(1655); +const markdown_1 = __nccwpck_require__(5300); +/** + * Create review on the pull request from the analysis given. + * @param analysis Analysis object returned from TiCS analysis. + * @param filesAnalyzed List of all files analyzed by TiCS. + * @param qualityGate Quality gate returned by TiCS. + * @param reviewComments TiCS annotations in the form of review comments. + */ +async function postReview(analysis, filesAnalyzed, qualityGate, reviewComments) { + let body = (0, summary_1.createQualityGateSummary)(qualityGate); + body += analysis.explorerUrl ? (0, summary_1.createLinkSummary)(analysis.explorerUrl) : ''; + body += reviewComments && reviewComments.unpostable.length > 0 ? (0, summary_1.createUnpostableReviewCommentsSummary)(reviewComments.unpostable) : ''; + body += (0, summary_1.createFilesSummary)(filesAnalyzed); + const params = { + owner: configuration_1.githubConfig.owner, + repo: configuration_1.githubConfig.reponame, + pull_number: configuration_1.githubConfig.pullRequestNumber, + event: configuration_1.ticsConfig.pullRequestApproval ? (qualityGate.passed ? enums_1.Events.APPROVE : enums_1.Events.REQUEST_CHANGES) : enums_1.Events.COMMENT, + body: body, + comments: reviewComments ? reviewComments.postable : undefined + }; + try { + logger_1.default.Instance.header('Posting a review for this pull request.'); + await configuration_1.octokit.rest.pulls.createReview(params); + logger_1.default.Instance.info('Posted review for this pull request.'); + } + catch (error) { + logger_1.default.Instance.error(`Posting the review failed: ${error.message}`); + } +} +exports.postReview = postReview; +/** + * Create review on the pull request with a body and approval0. + * @param message Message to display in the body of the review. + * @param event Approve or request changes in the review. + */ +async function postNothingAnalyzedReview(message, event) { + const body = `## TiCS Analysis\n\n### ${(0, markdown_1.generateStatusMarkdown)(enums_1.Status[event === enums_1.Events.APPROVE ? 1 : 0], true)}\n\n${message}`; + const params = { + owner: configuration_1.githubConfig.owner, + repo: configuration_1.githubConfig.reponame, + pull_number: configuration_1.githubConfig.pullRequestNumber, + event: configuration_1.ticsConfig.pullRequestApproval ? event : enums_1.Events.COMMENT, + body: body + }; + try { + logger_1.default.Instance.header('Posting a review for this pull request.'); + await configuration_1.octokit.rest.pulls.createReview(params); + logger_1.default.Instance.info('Posted review for this pull request.'); + } + catch (error) { + logger_1.default.Instance.error(`Posting the review failed: ${error.message}`); + } +} +exports.postNothingAnalyzedReview = postNothingAnalyzedReview; /***/ }), @@ -335,22 +335,22 @@ exports.postNothingAnalyzedReview = postNothingAnalyzedReview; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Events = exports.Status = void 0; -var Status; -(function (Status) { - Status[Status["FAILED"] = 0] = "FAILED"; - Status[Status["PASSED"] = 1] = "PASSED"; - Status[Status["WARNING"] = 2] = "WARNING"; - Status[Status["SKIPPED"] = 3] = "SKIPPED"; -})(Status = exports.Status || (exports.Status = {})); -var Events; -(function (Events) { - Events["APPROVE"] = "APPROVE"; - Events["COMMENT"] = "COMMENT"; - Events["REQUEST_CHANGES"] = "REQUEST_CHANGES"; -})(Events = exports.Events || (exports.Events = {})); + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Events = exports.Status = void 0; +var Status; +(function (Status) { + Status[Status["FAILED"] = 0] = "FAILED"; + Status[Status["PASSED"] = 1] = "PASSED"; + Status[Status["WARNING"] = 2] = "WARNING"; + Status[Status["SKIPPED"] = 3] = "SKIPPED"; +})(Status = exports.Status || (exports.Status = {})); +var Events; +(function (Events) { + Events["APPROVE"] = "APPROVE"; + Events["COMMENT"] = "COMMENT"; + Events["REQUEST_CHANGES"] = "REQUEST_CHANGES"; +})(Events = exports.Events || (exports.Events = {})); /***/ }), @@ -359,150 +359,150 @@ var Events; /***/ (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; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(2186)); -const configuration_1 = __nccwpck_require__(5527); -class Logger { - static _instance; - called = ''; - matched = []; - static get Instance() { - return this._instance || (this._instance = new this()); - } - /** - * Uses core.info to print to the console with a purple color. - * @param string - */ - header(string) { - string = this.maskSecrets(string); - this.addNewline('header'); - core.info(`\u001b[34m${string}`); - this.called = 'header'; - } - /** - * Uses core.info to print to the console. - * - * @param string - */ - info(string) { - string = this.maskSecrets(string); - core.info(string); - this.called = 'info'; - } - /** - * Uses core.debug to print to the console. - * - * @param string - */ - debug(string) { - string = this.maskSecrets(string); - core.debug(string); - this.called = 'debug'; - } - /** - * Uses core.warning to print to the console. - * - * @param string - */ - warning(string) { - string = this.maskSecrets(string); - core.warning(`\u001b[33m${string}`); - this.called = 'warning'; - } - /** - * Uses core.error to print to the console with a red color. - * - * @param error - */ - error(error) { - error = this.maskSecrets(error); - this.addNewline('error'); - core.error(`\u001b[31m${error}`); - this.called = 'error'; - } - /** - * Uses core.setFailed to exit with error. - * - * @param error - */ - setFailed(error) { - error = this.maskSecrets(error); - this.addNewline('error'); - core.setFailed(`\u001b[31m${error}`); - this.called = 'error'; - } - /** - * Uses core.setFailed to exit with error. - * - * @param error - */ - exit(error) { - error = this.maskSecrets(error); - this.addNewline('error'); - core.setFailed(`\u001b[31m${error}`); - process.exit(1); - } - /** - * Add newline above header, error and setFailed if the logger has been called before. - * @param type the type of call to add a newline for. - */ - addNewline(type) { - if (this.called) { - if (type === 'header') { - core.info(''); - } - } - } - /** - * Masks the secrets defined in ticsConfig secretsFilter from the console logging. - * @param data string that is going to be logged to the console. - * @returns the message with the secrets masked. - */ - maskSecrets(data) { - // Find secrets value and add them to this.matched - configuration_1.ticsConfig.secretsFilter.forEach(secret => { - if (data.match(new RegExp(secret, 'gi'))) { - const regex = new RegExp(`\\w*${secret}\\w*(?:[ \\t]*[:=>]*[ \\t]*)(.*)`, 'gi'); - let match = null; - while ((match = regex.exec(data))) { - if (match[1] !== '') { - this.matched.push(match[1]); - } - } - } - }); - // Filter out the values from the output - this.matched.forEach(match => { - data = data.replaceAll(match, '***'); - }); - return data; - } -} -exports["default"] = Logger; + +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; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(2186)); +const configuration_1 = __nccwpck_require__(5527); +class Logger { + static _instance; + called = ''; + matched = []; + static get Instance() { + return this._instance || (this._instance = new this()); + } + /** + * Uses core.info to print to the console with a purple color. + * @param string + */ + header(string) { + string = this.maskSecrets(string); + this.addNewline('header'); + core.info(`\u001b[34m${string}`); + this.called = 'header'; + } + /** + * Uses core.info to print to the console. + * + * @param string + */ + info(string) { + string = this.maskSecrets(string); + core.info(string); + this.called = 'info'; + } + /** + * Uses core.debug to print to the console. + * + * @param string + */ + debug(string) { + string = this.maskSecrets(string); + core.debug(string); + this.called = 'debug'; + } + /** + * Uses core.warning to print to the console. + * + * @param string + */ + warning(string) { + string = this.maskSecrets(string); + core.warning(`\u001b[33m${string}`); + this.called = 'warning'; + } + /** + * Uses core.error to print to the console with a red color. + * + * @param error + */ + error(error) { + error = this.maskSecrets(error); + this.addNewline('error'); + core.error(`\u001b[31m${error}`); + this.called = 'error'; + } + /** + * Uses core.setFailed to exit with error. + * + * @param error + */ + setFailed(error) { + error = this.maskSecrets(error); + this.addNewline('error'); + core.setFailed(`\u001b[31m${error}`); + this.called = 'error'; + } + /** + * Uses core.setFailed to exit with error. + * + * @param error + */ + exit(error) { + error = this.maskSecrets(error); + this.addNewline('error'); + core.setFailed(`\u001b[31m${error}`); + process.exit(1); + } + /** + * Add newline above header, error and setFailed if the logger has been called before. + * @param type the type of call to add a newline for. + */ + addNewline(type) { + if (this.called) { + if (type === 'header') { + core.info(''); + } + } + } + /** + * Masks the secrets defined in ticsConfig secretsFilter from the console logging. + * @param data string that is going to be logged to the console. + * @returns the message with the secrets masked. + */ + maskSecrets(data) { + // Find secrets value and add them to this.matched + configuration_1.ticsConfig.secretsFilter.forEach(secret => { + if (data.match(new RegExp(secret, 'gi'))) { + const regex = new RegExp(`\\w*${secret}\\w*(?:[ \\t]*[:=>]*[ \\t]*)(.*)`, 'gi'); + let match = null; + while ((match = regex.exec(data))) { + if (match[1] !== '') { + this.matched.push(match[1]); + } + } + } + }); + // Filter out the values from the output + this.matched.forEach(match => { + data = data.replaceAll(match, '***'); + }); + return data; + } +} +exports["default"] = Logger; /***/ }), @@ -511,50 +511,50 @@ exports["default"] = Logger; /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.generateExpandableAreaMarkdown = exports.generateStatusMarkdown = exports.generateLinkMarkdown = void 0; -const enums_1 = __nccwpck_require__(1655); -/** - * Generates a link with text in markdown. - * @param text Text for the link. - * @param link The actual link to. - * @returns Annotated link in markdown. - */ -function generateLinkMarkdown(text, link) { - return `[${text}](${link})`; -} -exports.generateLinkMarkdown = generateLinkMarkdown; -/** - * Generates a status symbol with optional suffix. - * @param status The status. (Either 'passed', 'failed', 'skipped' or 'warning'). - * @param hasSuffix if the status needs a suffix for the issue. (Default is false). - * @returns Status symbol in markdown. - */ -function generateStatusMarkdown(status, hasSuffix = false) { - switch (status) { - case enums_1.Status[0]: - return ':x: ' + (hasSuffix ? 'Failed ' : ''); - case enums_1.Status[1]: - return ':heavy_check_mark: ' + (hasSuffix ? 'Passed ' : ''); - case enums_1.Status[2]: - case enums_1.Status[3]: - return ':warning: ' + (hasSuffix ? 'Skipped ' : ''); - default: - return ''; - } -} -exports.generateStatusMarkdown = generateStatusMarkdown; -/** - * Generates a dropdown item in markdown. - * @param header Text to show the dropdown for. - * @param body The body of the dropdown. - * @returns Dropdown item in markdown. - */ -function generateExpandableAreaMarkdown(header, body) { - return `
${header}\n${body}
\n\n`; -} -exports.generateExpandableAreaMarkdown = generateExpandableAreaMarkdown; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.generateExpandableAreaMarkdown = exports.generateStatusMarkdown = exports.generateLinkMarkdown = void 0; +const enums_1 = __nccwpck_require__(1655); +/** + * Generates a link with text in markdown. + * @param text Text for the link. + * @param link The actual link to. + * @returns Annotated link in markdown. + */ +function generateLinkMarkdown(text, link) { + return `[${text}](${link})`; +} +exports.generateLinkMarkdown = generateLinkMarkdown; +/** + * Generates a status symbol with optional suffix. + * @param status The status. (Either 'passed', 'failed', 'skipped' or 'warning'). + * @param hasSuffix if the status needs a suffix for the issue. (Default is false). + * @returns Status symbol in markdown. + */ +function generateStatusMarkdown(status, hasSuffix = false) { + switch (status) { + case enums_1.Status[0]: + return ':x: ' + (hasSuffix ? 'Failed ' : ''); + case enums_1.Status[1]: + return ':heavy_check_mark: ' + (hasSuffix ? 'Passed ' : ''); + case enums_1.Status[2]: + case enums_1.Status[3]: + return ':warning: ' + (hasSuffix ? 'Skipped ' : ''); + default: + return ''; + } +} +exports.generateStatusMarkdown = generateStatusMarkdown; +/** + * Generates a dropdown item in markdown. + * @param header Text to show the dropdown for. + * @param body The body of the dropdown. + * @returns Dropdown item in markdown. + */ +function generateExpandableAreaMarkdown(header, body) { + return `
${header}\n${body}
\n\n`; +} +exports.generateExpandableAreaMarkdown = generateExpandableAreaMarkdown; /***/ }), @@ -563,243 +563,243 @@ exports.generateExpandableAreaMarkdown = generateExpandableAreaMarkdown; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createUnpostableReviewCommentsSummary = exports.createReviewComments = exports.createQualityGateSummary = exports.createFilesSummary = exports.createLinkSummary = exports.createErrorSummary = void 0; -const core_1 = __nccwpck_require__(2186); -const markdown_1 = __nccwpck_require__(5300); -const configuration_1 = __nccwpck_require__(5527); -const enums_1 = __nccwpck_require__(1655); -const underscore_1 = __nccwpck_require__(5067); -const logger_1 = __importDefault(__nccwpck_require__(6440)); -/** - * Creates a summary of all errors (and warnings optionally) to comment in a pull request. - * @param errorList list containing all the errors found in the TiCS run. - * @param warningList list containing all the warnings found in the TiCS run. - * @returns string containing the error summary. - */ -function createErrorSummary(errorList, warningList) { - let summary = '## TiCS Quality Gate\r\n\r\n### :x: Failed'; - if (errorList.length > 0) { - summary += '\r\n\r\n #### The following errors have occurred during analysis:\r\n\r\n'; - errorList.forEach(error => (summary += `> :x: ${error}\r\n`)); - } - if (warningList.length > 0 && configuration_1.githubConfig.debugger) { - summary += '\r\n\r\n #### The following warnings have occurred during analysis:\r\n\r\n'; - warningList.forEach(warning => (summary += `> :warning: ${warning}\r\n`)); - } - return summary; -} -exports.createErrorSummary = createErrorSummary; -/** - * Creates a markdown link summary. - * @param url Url to the TiCS viewer analysis. - * @returns Clickable link to the viewer analysis. - */ -function createLinkSummary(url) { - return `${(0, markdown_1.generateLinkMarkdown)('See the results in the TiCS Viewer', url)}\n\n`; -} -exports.createLinkSummary = createLinkSummary; -/** - * Creates a list of all the files analyzed. - * @param fileList list of files. - * @returns Dropdown with all the files analyzed. - */ -function createFilesSummary(fileList) { - let header = 'The following files have been checked:'; - let body = ''; - return (0, markdown_1.generateExpandableAreaMarkdown)(header, body); -} -exports.createFilesSummary = createFilesSummary; -/** - * Creates a quality gate summary for the TiCS analysis. - * @param qualityGate quality gate retrieved from the TiCS viewer. - * @returns Quality gate summary. - */ -function createQualityGateSummary(qualityGate) { - let failedConditions = []; - qualityGate.gates.forEach(gate => { - failedConditions = failedConditions.concat(gate.conditions.filter(c => !c.passed)); - }); - core_1.summary.clear(); - core_1.summary.addHeading('TiCS Quality Gate'); - core_1.summary.addHeading(`${(0, markdown_1.generateStatusMarkdown)(enums_1.Status[qualityGate.passed ? 1 : 0], true)}`, 3); - core_1.summary.addHeading(`${failedConditions.length} Condition(s) failed`, 2); - failedConditions.forEach(condition => { - if (condition.details && condition.details.items.length > 0) { - core_1.summary.addRaw(`\n
:x: ${condition.message}\n`); - core_1.summary.addBreak(); - core_1.summary.addTable(createConditionTable(condition)); - core_1.summary.addRaw('
', true); - } - else { - core_1.summary.addRaw(`\n   :x: ${condition.message}`, true); - } - }); - core_1.summary.addRaw('', true); - return core_1.summary.stringify(); -} -exports.createQualityGateSummary = createQualityGateSummary; -/** - * Creates a table containing a summary for all conditions. - * @param conditions Conditions of the quality gate - * @returns Table containing a summary for all conditions - */ -function createConditionTable(condition) { - if (!condition.details) - return []; - let rows = [ - [ - { - data: 'File', - header: true - }, - { - data: condition.details.dataKeys.actualValue.title, - header: true - } - ] - ]; - condition.details.items - .filter(item => item.itemType === 'file') - .forEach(item => { - rows.push([`\n\n[${item.name}](${configuration_1.viewerUrl}/${item.link})\n\n`, item.data.actualValue.formattedValue]); - }); - return rows; -} -/** - * Groups the annotations and creates review comments for them. - * @param annotations Annotations retrieved from the viewer. - * @param changedFiles List of files changed in the pull request. - * @returns List of the review comments. - */ -async function createReviewComments(annotations, changedFiles) { - logger_1.default.Instance.info('Creating review comments from annotations.'); - const sortedAnnotations = sortAnnotations(annotations); - const groupedAnnotations = groupAnnotations(sortedAnnotations, changedFiles); - let unpostable = []; - let postable = []; - groupedAnnotations.forEach(annotation => { - const displayCount = annotation.count === 1 ? '' : `(${annotation.count}x) `; - if (annotation.diffLines.includes(annotation.line)) { - logger_1.default.Instance.debug(`Postable: ${JSON.stringify(annotation)}`); - postable.push({ - body: `:warning: **TiCS: ${annotation.type} violation: ${annotation.msg}**\r\n${displayCount}Line: ${annotation.line}, Rule: ${annotation.rule}, Level: ${annotation.level}, Category: ${annotation.category}\r\n`, - path: annotation.path, - line: annotation.line - }); - } - else { - annotation.displayCount = displayCount; - logger_1.default.Instance.debug(`Unpostable: ${JSON.stringify(annotation)}`); - unpostable.push(annotation); - } - }); - logger_1.default.Instance.info('Created review comments from annotations.'); - return { postable: postable, unpostable: unpostable }; -} -exports.createReviewComments = createReviewComments; -/** - * Sorts annotations based on file name and line number. - * @param annotations annotations returned by TiCS analyzer. - * @returns sorted anotations. - */ -function sortAnnotations(annotations) { - return annotations.sort((a, b) => { - if (a.fullPath === b.fullPath) - return a.line - b.line; - return a.fullPath > b.fullPath ? 1 : -1; - }); -} -/** - * Groups annotations by file. Excludes annotations for files that have not been changed. - * @param annotations sorted annotations by file and line. - * @param changedFiles List of files changed in the pull request. - * @returns grouped annotations. - */ -function groupAnnotations(annotations, changedFiles) { - let groupedAnnotations = []; - annotations.forEach(annotation => { - const file = changedFiles.find(c => annotation.fullPath.includes(c.filename)); - const index = findAnnotationInList(groupedAnnotations, annotation); - if (index === -1) { - annotation.diffLines = file ? fetchDiffLines(file) : []; - annotation.path = file ? file.filename : annotation.fullPath.split('/').slice(4).join('/'); - groupedAnnotations.push(annotation); - } - else { - if (groupedAnnotations[index].gateId === annotation.gateId) { - groupedAnnotations[index].count += annotation.count; - } - } - }); - return groupedAnnotations; -} -/** - * Finds all lines that are shown in GitHub diff chunk. - * @param file file to search the lines changed chunk for. - * @returns List of all the lines in the diff chunk. - */ -function fetchDiffLines(file) { - const regex = /\+(\d+),(\d+)+/g; - let diffLines = []; - let match = regex.exec(file.patch); - while (match !== null) { - const startLine = parseInt(match[1]); - const amountOfLines = parseInt(match[2]); - diffLines = diffLines.concat((0, underscore_1.range)(startLine, startLine + amountOfLines)); - match = regex.exec(file.patch); - } - return diffLines; -} -/** - * Finds an annotation in a list and returns the index. - * @param list List to find the annotation in. - * @param annotation Annotation to find. - * @returns The index of the annotation found or -1 - */ -function findAnnotationInList(list, annotation) { - return list.findIndex(a => { - return (a.fullPath === annotation.fullPath && - a.type === annotation.type && - a.line === annotation.line && - a.rule === annotation.rule && - a.level === annotation.level && - a.category === annotation.category && - a.message === annotation.message); - }); -} -/** - * Creates a summary of all the review comments that could not be posted - * @param unpostableReviewComments Review comments that could not be posted. - * @returns Summary of all the review comments that could not be posted. - */ -function createUnpostableReviewCommentsSummary(unpostableReviewComments) { - let header = 'Quality gate failures that cannot be annotated in Files Changed:'; - let body = ''; - let previousPath = ''; - unpostableReviewComments.forEach(reviewComment => { - if (previousPath === '') { - body += ``; - } - else if (previousPath !== reviewComment.path) { - body += `
${reviewComment.path}
`; - } - body += ``; - previousPath = reviewComment.path; - }); - body += '
${reviewComment.path}
:warning:Line: ${reviewComment.line} Level: ${reviewComment.level}
Category: ${reviewComment.category}
${reviewComment.type} violation: ${reviewComment.rule} ${reviewComment.displayCount}
${reviewComment.msg}
'; - return (0, markdown_1.generateExpandableAreaMarkdown)(header, body); -} -exports.createUnpostableReviewCommentsSummary = createUnpostableReviewCommentsSummary; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createUnpostableReviewCommentsSummary = exports.createReviewComments = exports.createQualityGateSummary = exports.createFilesSummary = exports.createLinkSummary = exports.createErrorSummary = void 0; +const core_1 = __nccwpck_require__(2186); +const markdown_1 = __nccwpck_require__(5300); +const configuration_1 = __nccwpck_require__(5527); +const enums_1 = __nccwpck_require__(1655); +const underscore_1 = __nccwpck_require__(5067); +const logger_1 = __importDefault(__nccwpck_require__(6440)); +/** + * Creates a summary of all errors (and warnings optionally) to comment in a pull request. + * @param errorList list containing all the errors found in the TiCS run. + * @param warningList list containing all the warnings found in the TiCS run. + * @returns string containing the error summary. + */ +function createErrorSummary(errorList, warningList) { + let summary = '## TiCS Quality Gate\r\n\r\n### :x: Failed'; + if (errorList.length > 0) { + summary += '\r\n\r\n #### The following errors have occurred during analysis:\r\n\r\n'; + errorList.forEach(error => (summary += `> :x: ${error}\r\n`)); + } + if (warningList.length > 0 && configuration_1.githubConfig.debugger) { + summary += '\r\n\r\n #### The following warnings have occurred during analysis:\r\n\r\n'; + warningList.forEach(warning => (summary += `> :warning: ${warning}\r\n`)); + } + return summary; +} +exports.createErrorSummary = createErrorSummary; +/** + * Creates a markdown link summary. + * @param url Url to the TiCS viewer analysis. + * @returns Clickable link to the viewer analysis. + */ +function createLinkSummary(url) { + return `${(0, markdown_1.generateLinkMarkdown)('See the results in the TiCS Viewer', url)}\n\n`; +} +exports.createLinkSummary = createLinkSummary; +/** + * Creates a list of all the files analyzed. + * @param fileList list of files. + * @returns Dropdown with all the files analyzed. + */ +function createFilesSummary(fileList) { + let header = 'The following files have been checked:'; + let body = ''; + return (0, markdown_1.generateExpandableAreaMarkdown)(header, body); +} +exports.createFilesSummary = createFilesSummary; +/** + * Creates a quality gate summary for the TiCS analysis. + * @param qualityGate quality gate retrieved from the TiCS viewer. + * @returns Quality gate summary. + */ +function createQualityGateSummary(qualityGate) { + let failedConditions = []; + qualityGate.gates.forEach(gate => { + failedConditions = failedConditions.concat(gate.conditions.filter(c => !c.passed)); + }); + core_1.summary.clear(); + core_1.summary.addHeading('TiCS Quality Gate'); + core_1.summary.addHeading(`${(0, markdown_1.generateStatusMarkdown)(enums_1.Status[qualityGate.passed ? 1 : 0], true)}`, 3); + core_1.summary.addHeading(`${failedConditions.length} Condition(s) failed`, 2); + failedConditions.forEach(condition => { + if (condition.details && condition.details.items.length > 0) { + core_1.summary.addRaw(`\n
:x: ${condition.message}\n`); + core_1.summary.addBreak(); + core_1.summary.addTable(createConditionTable(condition)); + core_1.summary.addRaw('
', true); + } + else { + core_1.summary.addRaw(`\n   :x: ${condition.message}`, true); + } + }); + core_1.summary.addRaw('', true); + return core_1.summary.stringify(); +} +exports.createQualityGateSummary = createQualityGateSummary; +/** + * Creates a table containing a summary for all conditions. + * @param conditions Conditions of the quality gate + * @returns Table containing a summary for all conditions + */ +function createConditionTable(condition) { + if (!condition.details) + return []; + let rows = [ + [ + { + data: 'File', + header: true + }, + { + data: condition.details.dataKeys.actualValue.title, + header: true + } + ] + ]; + condition.details.items + .filter(item => item.itemType === 'file') + .forEach(item => { + rows.push([`\n\n[${item.name}](${configuration_1.viewerUrl}/${item.link})\n\n`, item.data.actualValue.formattedValue]); + }); + return rows; +} +/** + * Groups the annotations and creates review comments for them. + * @param annotations Annotations retrieved from the viewer. + * @param changedFiles List of files changed in the pull request. + * @returns List of the review comments. + */ +async function createReviewComments(annotations, changedFiles) { + logger_1.default.Instance.info('Creating review comments from annotations.'); + const sortedAnnotations = sortAnnotations(annotations); + const groupedAnnotations = groupAnnotations(sortedAnnotations, changedFiles); + let unpostable = []; + let postable = []; + groupedAnnotations.forEach(annotation => { + const displayCount = annotation.count === 1 ? '' : `(${annotation.count}x) `; + if (annotation.diffLines.includes(annotation.line)) { + logger_1.default.Instance.debug(`Postable: ${JSON.stringify(annotation)}`); + postable.push({ + body: `:warning: **TiCS: ${annotation.type} violation: ${annotation.msg}**\r\n${displayCount}Line: ${annotation.line}, Rule: ${annotation.rule}, Level: ${annotation.level}, Category: ${annotation.category}\r\n`, + path: annotation.path, + line: annotation.line + }); + } + else { + annotation.displayCount = displayCount; + logger_1.default.Instance.debug(`Unpostable: ${JSON.stringify(annotation)}`); + unpostable.push(annotation); + } + }); + logger_1.default.Instance.info('Created review comments from annotations.'); + return { postable: postable, unpostable: unpostable }; +} +exports.createReviewComments = createReviewComments; +/** + * Sorts annotations based on file name and line number. + * @param annotations annotations returned by TiCS analyzer. + * @returns sorted anotations. + */ +function sortAnnotations(annotations) { + return annotations.sort((a, b) => { + if (a.fullPath === b.fullPath) + return a.line - b.line; + return a.fullPath > b.fullPath ? 1 : -1; + }); +} +/** + * Groups annotations by file. Excludes annotations for files that have not been changed. + * @param annotations sorted annotations by file and line. + * @param changedFiles List of files changed in the pull request. + * @returns grouped annotations. + */ +function groupAnnotations(annotations, changedFiles) { + let groupedAnnotations = []; + annotations.forEach(annotation => { + const file = changedFiles.find(c => annotation.fullPath.includes(c.filename)); + const index = findAnnotationInList(groupedAnnotations, annotation); + if (index === -1) { + annotation.diffLines = file ? fetchDiffLines(file) : []; + annotation.path = file ? file.filename : annotation.fullPath.split('/').slice(4).join('/'); + groupedAnnotations.push(annotation); + } + else { + if (groupedAnnotations[index].gateId === annotation.gateId) { + groupedAnnotations[index].count += annotation.count; + } + } + }); + return groupedAnnotations; +} +/** + * Finds all lines that are shown in GitHub diff chunk. + * @param file file to search the lines changed chunk for. + * @returns List of all the lines in the diff chunk. + */ +function fetchDiffLines(file) { + const regex = /\+(\d+),(\d+)+/g; + let diffLines = []; + let match = regex.exec(file.patch); + while (match !== null) { + const startLine = parseInt(match[1]); + const amountOfLines = parseInt(match[2]); + diffLines = diffLines.concat((0, underscore_1.range)(startLine, startLine + amountOfLines)); + match = regex.exec(file.patch); + } + return diffLines; +} +/** + * Finds an annotation in a list and returns the index. + * @param list List to find the annotation in. + * @param annotation Annotation to find. + * @returns The index of the annotation found or -1 + */ +function findAnnotationInList(list, annotation) { + return list.findIndex(a => { + return (a.fullPath === annotation.fullPath && + a.type === annotation.type && + a.line === annotation.line && + a.rule === annotation.rule && + a.level === annotation.level && + a.category === annotation.category && + a.message === annotation.message); + }); +} +/** + * Creates a summary of all the review comments that could not be posted + * @param unpostableReviewComments Review comments that could not be posted. + * @returns Summary of all the review comments that could not be posted. + */ +function createUnpostableReviewCommentsSummary(unpostableReviewComments) { + let header = 'Quality gate failures that cannot be annotated in Files Changed:'; + let body = ''; + let previousPath = ''; + unpostableReviewComments.forEach(reviewComment => { + if (previousPath === '') { + body += ``; + } + else if (previousPath !== reviewComment.path) { + body += `
${reviewComment.path}
`; + } + body += ``; + previousPath = reviewComment.path; + }); + body += '
${reviewComment.path}
:warning:Line: ${reviewComment.line} Level: ${reviewComment.level}
Category: ${reviewComment.category}
${reviewComment.type} violation: ${reviewComment.rule} ${reviewComment.displayCount}
${reviewComment.msg}
'; + return (0, markdown_1.generateExpandableAreaMarkdown)(header, body); +} +exports.createUnpostableReviewCommentsSummary = createUnpostableReviewCommentsSummary; /***/ }), @@ -808,156 +808,156 @@ exports.createUnpostableReviewCommentsSummary = createUnpostableReviewCommentsSu /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.configure = exports.run = void 0; -const fs_1 = __nccwpck_require__(7147); -const comment_1 = __nccwpck_require__(5436); -const configuration_1 = __nccwpck_require__(5527); -const pulls_1 = __nccwpck_require__(5857); -const logger_1 = __importDefault(__nccwpck_require__(6440)); -const analyzer_1 = __nccwpck_require__(9099); -const api_helper_1 = __nccwpck_require__(3823); -const fetcher_1 = __nccwpck_require__(1559); -const review_1 = __nccwpck_require__(8973); -const summary_1 = __nccwpck_require__(1502); -const annotations_1 = __nccwpck_require__(9757); -const annotations_2 = __nccwpck_require__(7829); -const enums_1 = __nccwpck_require__(1655); -const compare_versions_1 = __nccwpck_require__(4773); -const core_1 = __nccwpck_require__(2186); -run(); -// exported for testing purposes -async function run() { - configure(); - const message = await meetsPrerequisites(); - if (message) - return logger_1.default.Instance.exit(message); - await main(); -} -exports.run = run; -async function main() { - try { - let analysis; - if (configuration_1.ticsConfig.mode === 'diagnostic') { - logger_1.default.Instance.header('Running action in diagnostic mode'); - analysis = await (0, analyzer_1.runTicsAnalyzer)(''); - if (analysis.statusCode !== 0) - logger_1.default.Instance.setFailed('Diagnostic run has failed.'); - } - else { - const changedFiles = await (0, pulls_1.getChangedFiles)(); - if (!changedFiles || changedFiles.length <= 0) - return logger_1.default.Instance.info('No changed files found to analyze.'); - const changedFilesFilePath = (0, pulls_1.changedFilesToFile)(changedFiles); - analysis = await (0, analyzer_1.runTicsAnalyzer)(changedFilesFilePath); - if (!analysis.explorerUrl) { - if (!analysis.completed) { - (0, comment_1.postErrorComment)(analysis); - logger_1.default.Instance.setFailed('Failed to run TiCS Github Action.'); - } - else if (analysis.warningList.find(w => w.includes('[WARNING 5057]'))) { - (0, review_1.postNothingAnalyzedReview)('No changed files applicable for TiCS analysis quality gating.', enums_1.Events.APPROVE); - } - else { - logger_1.default.Instance.setFailed('Failed to run TiCS Github Action.'); - analysis.errorList.push('Explorer URL not returned from TiCS analysis.'); - } - (0, api_helper_1.cliSummary)(analysis); - return; - } - const analyzedFiles = await (0, fetcher_1.getAnalyzedFiles)(analysis.explorerUrl, changedFiles); - const qualityGate = await (0, fetcher_1.getQualityGate)(analysis.explorerUrl); - let reviewComments; - if (configuration_1.ticsConfig.postAnnotations) { - const annotations = await (0, fetcher_1.getAnnotations)(qualityGate.annotationsApiV1Links); - if (annotations && annotations.length > 0) { - reviewComments = await (0, summary_1.createReviewComments)(annotations, changedFiles); - } - const previousReviewComments = await (0, annotations_2.getPostedReviewComments)(); - if (previousReviewComments && previousReviewComments.length > 0) { - await (0, annotations_1.deletePreviousReviewComments)(previousReviewComments); - } - } - await (0, review_1.postReview)(analysis, analyzedFiles, qualityGate, reviewComments); - if (!qualityGate.passed) - logger_1.default.Instance.setFailed(qualityGate.message); - } - (0, api_helper_1.cliSummary)(analysis); - } - catch (error) { - logger_1.default.Instance.error('Failed to run TiCS Github Action'); - logger_1.default.Instance.exit(error.message); - } -} -/** - * Configure the action before running the analysis. - */ -function configure() { - process.removeAllListeners('warning'); - process.on('warning', warning => { - if (configuration_1.githubConfig.debugger) - logger_1.default.Instance.warning(warning.message.toString()); - }); - (0, core_1.exportVariable)('TICSIDE', 'GITHUB'); - // set ticsAuthToken - if (configuration_1.ticsConfig.ticsAuthToken) { - (0, core_1.exportVariable)('TICSAUTHTOKEN', configuration_1.ticsConfig.ticsAuthToken); - } - // set hostnameVerification - if (configuration_1.ticsConfig.hostnameVerification) { - (0, core_1.exportVariable)('TICSHOSTNAMEVERIFICATION', configuration_1.ticsConfig.hostnameVerification); - if (configuration_1.ticsConfig.hostnameVerification === '0' || configuration_1.ticsConfig.hostnameVerification === 'false') { - (0, core_1.exportVariable)('NODE_TLS_REJECT_UNAUTHORIZED', 0); - logger_1.default.Instance.debug('Hostname Verification disabled'); - } - } - // set trustStrategy - if (configuration_1.ticsConfig.trustStrategy) { - (0, core_1.exportVariable)('TICSTRUSTSTRATEGY', configuration_1.ticsConfig.trustStrategy); - if (configuration_1.ticsConfig.trustStrategy === 'self-signed' || configuration_1.ticsConfig.trustStrategy === 'all') { - (0, core_1.exportVariable)('NODE_TLS_REJECT_UNAUTHORIZED', 0); - logger_1.default.Instance.debug(`Trust strategy set to ${configuration_1.ticsConfig.trustStrategy}`); - } - } -} -exports.configure = configure; -/** - * Checks if prerequisites are met to run the Github Plugin. - * If any of these checks fail it returns a message. - * @returns Message containing why it failed the prerequisite. - */ -async function meetsPrerequisites() { - let message; - const viewerVersion = await (0, fetcher_1.getViewerVersion)(); - if (!viewerVersion || !(0, compare_versions_1.satisfies)(viewerVersion.version, '>=2022.4.0')) { - message = `Minimum required TiCS Viewer version is 2022.4. Found version ${viewerVersion?.version}.`; - } - else if (configuration_1.ticsConfig.mode === 'diagnostic') { - // No need for pull_request and checked out repository. - } - else if (configuration_1.githubConfig.eventName !== 'pull_request') { - message = 'This action can only run on pull requests.'; - } - else if (!isCheckedOut()) { - message = 'No checkout found to analyze. Please perform a checkout before running the TiCS Action.'; - } - return message; -} -/** - * Checks if a .git directory exists to see if a checkout has been performed. - * @returns Boolean value if the folder is found or not. - */ -function isCheckedOut() { - if (!(0, fs_1.existsSync)('.git')) { - logger_1.default.Instance.error('No git checkout found'); - return false; - } - return true; -} + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.configure = exports.run = void 0; +const fs_1 = __nccwpck_require__(7147); +const comment_1 = __nccwpck_require__(5436); +const configuration_1 = __nccwpck_require__(5527); +const pulls_1 = __nccwpck_require__(5857); +const logger_1 = __importDefault(__nccwpck_require__(6440)); +const analyzer_1 = __nccwpck_require__(9099); +const api_helper_1 = __nccwpck_require__(3823); +const fetcher_1 = __nccwpck_require__(1559); +const review_1 = __nccwpck_require__(8973); +const summary_1 = __nccwpck_require__(1502); +const annotations_1 = __nccwpck_require__(9757); +const annotations_2 = __nccwpck_require__(7829); +const enums_1 = __nccwpck_require__(1655); +const compare_versions_1 = __nccwpck_require__(4773); +const core_1 = __nccwpck_require__(2186); +run(); +// exported for testing purposes +async function run() { + configure(); + const message = await meetsPrerequisites(); + if (message) + return logger_1.default.Instance.exit(message); + await main(); +} +exports.run = run; +async function main() { + try { + let analysis; + if (configuration_1.ticsConfig.mode === 'diagnostic') { + logger_1.default.Instance.header('Running action in diagnostic mode'); + analysis = await (0, analyzer_1.runTicsAnalyzer)(''); + if (analysis.statusCode !== 0) + logger_1.default.Instance.setFailed('Diagnostic run has failed.'); + } + else { + const changedFiles = await (0, pulls_1.getChangedFiles)(); + if (!changedFiles || changedFiles.length <= 0) + return logger_1.default.Instance.info('No changed files found to analyze.'); + const changedFilesFilePath = (0, pulls_1.changedFilesToFile)(changedFiles); + analysis = await (0, analyzer_1.runTicsAnalyzer)(changedFilesFilePath); + if (!analysis.explorerUrl) { + if (!analysis.completed) { + (0, comment_1.postErrorComment)(analysis); + logger_1.default.Instance.setFailed('Failed to run TiCS Github Action.'); + } + else if (analysis.warningList.find(w => w.includes('[WARNING 5057]'))) { + (0, review_1.postNothingAnalyzedReview)('No changed files applicable for TiCS analysis quality gating.', enums_1.Events.APPROVE); + } + else { + logger_1.default.Instance.setFailed('Failed to run TiCS Github Action.'); + analysis.errorList.push('Explorer URL not returned from TiCS analysis.'); + } + (0, api_helper_1.cliSummary)(analysis); + return; + } + const analyzedFiles = await (0, fetcher_1.getAnalyzedFiles)(analysis.explorerUrl, changedFiles); + const qualityGate = await (0, fetcher_1.getQualityGate)(analysis.explorerUrl); + let reviewComments; + if (configuration_1.ticsConfig.postAnnotations) { + const annotations = await (0, fetcher_1.getAnnotations)(qualityGate.annotationsApiV1Links); + if (annotations && annotations.length > 0) { + reviewComments = await (0, summary_1.createReviewComments)(annotations, changedFiles); + } + const previousReviewComments = await (0, annotations_2.getPostedReviewComments)(); + if (previousReviewComments && previousReviewComments.length > 0) { + await (0, annotations_1.deletePreviousReviewComments)(previousReviewComments); + } + } + await (0, review_1.postReview)(analysis, analyzedFiles, qualityGate, reviewComments); + if (!qualityGate.passed) + logger_1.default.Instance.setFailed(qualityGate.message); + } + (0, api_helper_1.cliSummary)(analysis); + } + catch (error) { + logger_1.default.Instance.error('Failed to run TiCS Github Action'); + logger_1.default.Instance.exit(error.message); + } +} +/** + * Configure the action before running the analysis. + */ +function configure() { + process.removeAllListeners('warning'); + process.on('warning', warning => { + if (configuration_1.githubConfig.debugger) + logger_1.default.Instance.warning(warning.message.toString()); + }); + (0, core_1.exportVariable)('TICSIDE', 'GITHUB'); + // set ticsAuthToken + if (configuration_1.ticsConfig.ticsAuthToken) { + (0, core_1.exportVariable)('TICSAUTHTOKEN', configuration_1.ticsConfig.ticsAuthToken); + } + // set hostnameVerification + if (configuration_1.ticsConfig.hostnameVerification) { + (0, core_1.exportVariable)('TICSHOSTNAMEVERIFICATION', configuration_1.ticsConfig.hostnameVerification); + if (configuration_1.ticsConfig.hostnameVerification === '0' || configuration_1.ticsConfig.hostnameVerification === 'false') { + (0, core_1.exportVariable)('NODE_TLS_REJECT_UNAUTHORIZED', 0); + logger_1.default.Instance.debug('Hostname Verification disabled'); + } + } + // set trustStrategy + if (configuration_1.ticsConfig.trustStrategy) { + (0, core_1.exportVariable)('TICSTRUSTSTRATEGY', configuration_1.ticsConfig.trustStrategy); + if (configuration_1.ticsConfig.trustStrategy === 'self-signed' || configuration_1.ticsConfig.trustStrategy === 'all') { + (0, core_1.exportVariable)('NODE_TLS_REJECT_UNAUTHORIZED', 0); + logger_1.default.Instance.debug(`Trust strategy set to ${configuration_1.ticsConfig.trustStrategy}`); + } + } +} +exports.configure = configure; +/** + * Checks if prerequisites are met to run the Github Plugin. + * If any of these checks fail it returns a message. + * @returns Message containing why it failed the prerequisite. + */ +async function meetsPrerequisites() { + let message; + const viewerVersion = await (0, fetcher_1.getViewerVersion)(); + if (!viewerVersion || !(0, compare_versions_1.satisfies)(viewerVersion.version, '>=2022.4.0')) { + message = `Minimum required TiCS Viewer version is 2022.4. Found version ${viewerVersion?.version}.`; + } + else if (configuration_1.ticsConfig.mode === 'diagnostic') { + // No need for pull_request and checked out repository. + } + else if (configuration_1.githubConfig.eventName !== 'pull_request') { + message = 'This action can only run on pull requests.'; + } + else if (!isCheckedOut()) { + message = 'No checkout found to analyze. Please perform a checkout before running the TiCS Action.'; + } + return message; +} +/** + * Checks if a .git directory exists to see if a checkout has been performed. + * @returns Boolean value if the folder is found or not. + */ +function isCheckedOut() { + if (!(0, fs_1.existsSync)('.git')) { + logger_1.default.Instance.error('No git checkout found'); + return false; + } + return true; +} /***/ }), @@ -966,157 +966,157 @@ function isCheckedOut() { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.runTicsAnalyzer = void 0; -const exec_1 = __nccwpck_require__(1514); -const configuration_1 = __nccwpck_require__(5527); -const logger_1 = __importDefault(__nccwpck_require__(6440)); -const api_helper_1 = __nccwpck_require__(3823); -let errorList = []; -let warningList = []; -let explorerUrl; -let statusCode; -let completed; -/** - * Runs TiCS based on the configuration set in a workflow. - * @param fileListPath Path to changedFiles.txt. - */ -async function runTicsAnalyzer(fileListPath) { - logger_1.default.Instance.header(`Analyzing for project ${configuration_1.ticsConfig.projectName}`); - const command = await buildRunCommand(fileListPath); - logger_1.default.Instance.header('Running TiCS'); - logger_1.default.Instance.debug(`With command: ${command}`); - try { - statusCode = await (0, exec_1.exec)(command, [], { - silent: true, - listeners: { - stdout(data) { - let filtered = data.toString(); - filtered = logger_1.default.Instance.maskSecrets(filtered); - process.stdout.write(filtered); - findInStdOutOrErr(filtered); - }, - stderr(data) { - let filtered = data.toString(); - filtered = logger_1.default.Instance.maskSecrets(filtered); - process.stdout.write(filtered); - findInStdOutOrErr(filtered); - } - } - }); - completed = true; - } - catch (error) { - logger_1.default.Instance.debug(error.message); - completed = false; - statusCode = -1; - } - finally { - return { - completed: completed, - statusCode: statusCode, - explorerUrl: explorerUrl, - errorList: errorList, - warningList: warningList - }; - } -} -exports.runTicsAnalyzer = runTicsAnalyzer; -/** - * Build the command to run (and optionally install) TiCS. - * @param fileListPath Path to changedFiles.txt. - * @returns Command to run. - */ -async function buildRunCommand(fileListPath) { - if (configuration_1.githubConfig.runnerOS === 'Linux') { - return `/bin/bash -c "${await getInstallTics()} ${getTicsCommand(fileListPath)}"`; - } - return `powershell "${await getInstallTics()}; if ($?) {${getTicsCommand(fileListPath)}}"`; -} -/** - * Get the command to install TiCS with. - */ -async function getInstallTics() { - if (!configuration_1.ticsConfig.installTics) - return ''; - const installTicsUrl = await retrieveInstallTics(configuration_1.githubConfig.runnerOS.toLowerCase()); - if (configuration_1.githubConfig.runnerOS === 'Linux') { - let trustStrategy = ''; - if (configuration_1.ticsConfig.trustStrategy === 'self-signed' || configuration_1.ticsConfig.trustStrategy === 'all') { - trustStrategy = '--insecure'; - } - return `source <(curl --silent ${trustStrategy} '${installTicsUrl}') &&`; - } - else { - // runnerOS is assumed to be Windows here - let trustStrategy = ''; - if (configuration_1.ticsConfig.trustStrategy === 'self-signed' || configuration_1.ticsConfig.trustStrategy === 'all') { - trustStrategy = '[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};'; - } - return `Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; ${trustStrategy} iex ((New-Object System.Net.WebClient).DownloadString('${installTicsUrl}'))`; - } -} -/** - * Push warnings or errors to a list to summarize them on exit. - * @param data stdout or stderr - */ -function findInStdOutOrErr(data) { - const error = data.toString().match(/\[ERROR.*/g); - if (error && !errorList.find(e => e === error?.toString())) - errorList.push(error.toString()); - const warning = data.toString().match(/\[WARNING.*/g); - if (warning && !warningList.find(w => w === warning?.toString())) - warningList.push(warning.toString()); - const findExplorerUrl = data.match(/\/Explorer.*/g); - if (!explorerUrl && findExplorerUrl) - explorerUrl = configuration_1.viewerUrl + findExplorerUrl.slice(-1).pop(); -} -/** - * Retrieves the the TiCS install url from the ticsConfiguration. - * @param os the OS the runner runs on. - * @returns the TiCS install url. - */ -async function retrieveInstallTics(os) { - try { - logger_1.default.Instance.info('Trying to retrieve configuration information from TiCS.'); - const ticsInstallApiBaseUrl = (0, api_helper_1.getInstallTicsApiUrl)(configuration_1.baseUrl, os); - const data = await (0, api_helper_1.httpRequest)(ticsInstallApiBaseUrl); - return configuration_1.baseUrl + '/' + data.links.installTics; - } - catch (error) { - logger_1.default.Instance.exit(`An error occurred when trying to retrieve configuration information: ${error.message}`); - } -} -/** - * Builds the TiCS calculate command based on the fileListPath and the ticsConfig set. - * @param fileListPath - * @returns string of the command to run TiCS. - */ -function getTicsCommand(fileListPath) { - let execString = 'TICS -ide github '; - if (configuration_1.ticsConfig.mode === 'diagnostic') { - execString += '-help '; - } - else { - execString += `@${fileListPath} -viewer `; - execString += `-project '${configuration_1.ticsConfig.projectName}' `; - execString += `-calc ${configuration_1.ticsConfig.calc} `; - execString += configuration_1.ticsConfig.nocalc ? `-nocalc ${configuration_1.ticsConfig.nocalc} ` : ''; - execString += configuration_1.ticsConfig.recalc ? `-recalc ${configuration_1.ticsConfig.recalc} ` : ''; - execString += configuration_1.ticsConfig.norecalc ? `-norecalc ${configuration_1.ticsConfig.norecalc} ` : ''; - execString += configuration_1.ticsConfig.codetype ? `-codetype ${configuration_1.ticsConfig.codetype} ` : ''; - execString += configuration_1.ticsConfig.clientData ? `-cdtoken ${configuration_1.ticsConfig.clientData} ` : ''; - execString += configuration_1.ticsConfig.tmpDir ? `-tmpdir '${configuration_1.ticsConfig.tmpDir}' ` : ''; - } - execString += configuration_1.ticsConfig.additionalFlags ? configuration_1.ticsConfig.additionalFlags : ''; - // Add TICS debug flag when in debug mode, if this flag was not already set. - execString += configuration_1.githubConfig.debugger && !execString.includes('-log ') ? ' -log 9' : ''; - return execString; -} + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.runTicsAnalyzer = void 0; +const exec_1 = __nccwpck_require__(1514); +const configuration_1 = __nccwpck_require__(5527); +const logger_1 = __importDefault(__nccwpck_require__(6440)); +const api_helper_1 = __nccwpck_require__(3823); +let errorList = []; +let warningList = []; +let explorerUrl; +let statusCode; +let completed; +/** + * Runs TiCS based on the configuration set in a workflow. + * @param fileListPath Path to changedFiles.txt. + */ +async function runTicsAnalyzer(fileListPath) { + logger_1.default.Instance.header(`Analyzing for project ${configuration_1.ticsConfig.projectName}`); + const command = await buildRunCommand(fileListPath); + logger_1.default.Instance.header('Running TiCS'); + logger_1.default.Instance.debug(`With command: ${command}`); + try { + statusCode = await (0, exec_1.exec)(command, [], { + silent: true, + listeners: { + stdout(data) { + let filtered = data.toString(); + filtered = logger_1.default.Instance.maskSecrets(filtered); + process.stdout.write(filtered); + findInStdOutOrErr(filtered); + }, + stderr(data) { + let filtered = data.toString(); + filtered = logger_1.default.Instance.maskSecrets(filtered); + process.stdout.write(filtered); + findInStdOutOrErr(filtered); + } + } + }); + completed = true; + } + catch (error) { + logger_1.default.Instance.debug(error.message); + completed = false; + statusCode = -1; + } + finally { + return { + completed: completed, + statusCode: statusCode, + explorerUrl: explorerUrl, + errorList: errorList, + warningList: warningList + }; + } +} +exports.runTicsAnalyzer = runTicsAnalyzer; +/** + * Build the command to run (and optionally install) TiCS. + * @param fileListPath Path to changedFiles.txt. + * @returns Command to run. + */ +async function buildRunCommand(fileListPath) { + if (configuration_1.githubConfig.runnerOS === 'Linux') { + return `/bin/bash -c "${await getInstallTics()} ${getTicsCommand(fileListPath)}"`; + } + return `powershell "${await getInstallTics()}; if ($?) {${getTicsCommand(fileListPath)}}"`; +} +/** + * Get the command to install TiCS with. + */ +async function getInstallTics() { + if (!configuration_1.ticsConfig.installTics) + return ''; + const installTicsUrl = await retrieveInstallTics(configuration_1.githubConfig.runnerOS.toLowerCase()); + if (configuration_1.githubConfig.runnerOS === 'Linux') { + let trustStrategy = ''; + if (configuration_1.ticsConfig.trustStrategy === 'self-signed' || configuration_1.ticsConfig.trustStrategy === 'all') { + trustStrategy = '--insecure'; + } + return `source <(curl --silent ${trustStrategy} '${installTicsUrl}') &&`; + } + else { + // runnerOS is assumed to be Windows here + let trustStrategy = ''; + if (configuration_1.ticsConfig.trustStrategy === 'self-signed' || configuration_1.ticsConfig.trustStrategy === 'all') { + trustStrategy = '[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};'; + } + return `Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; ${trustStrategy} iex ((New-Object System.Net.WebClient).DownloadString('${installTicsUrl}'))`; + } +} +/** + * Push warnings or errors to a list to summarize them on exit. + * @param data stdout or stderr + */ +function findInStdOutOrErr(data) { + const error = data.toString().match(/\[ERROR.*/g); + if (error && !errorList.find(e => e === error?.toString())) + errorList.push(error.toString()); + const warning = data.toString().match(/\[WARNING.*/g); + if (warning && !warningList.find(w => w === warning?.toString())) + warningList.push(warning.toString()); + const findExplorerUrl = data.match(/\/Explorer.*/g); + if (!explorerUrl && findExplorerUrl) + explorerUrl = configuration_1.viewerUrl + findExplorerUrl.slice(-1).pop(); +} +/** + * Retrieves the the TiCS install url from the ticsConfiguration. + * @param os the OS the runner runs on. + * @returns the TiCS install url. + */ +async function retrieveInstallTics(os) { + try { + logger_1.default.Instance.info('Trying to retrieve configuration information from TiCS.'); + const ticsInstallApiBaseUrl = (0, api_helper_1.getInstallTicsApiUrl)(configuration_1.baseUrl, os); + const data = await (0, api_helper_1.httpRequest)(ticsInstallApiBaseUrl); + return configuration_1.baseUrl + '/' + data.links.installTics; + } + catch (error) { + logger_1.default.Instance.exit(`An error occurred when trying to retrieve configuration information: ${error.message}`); + } +} +/** + * Builds the TiCS calculate command based on the fileListPath and the ticsConfig set. + * @param fileListPath + * @returns string of the command to run TiCS. + */ +function getTicsCommand(fileListPath) { + let execString = 'TICS -ide github '; + if (configuration_1.ticsConfig.mode === 'diagnostic') { + execString += '-help '; + } + else { + execString += `@${fileListPath} -viewer `; + execString += `-project '${configuration_1.ticsConfig.projectName}' `; + execString += `-calc ${configuration_1.ticsConfig.calc} `; + execString += configuration_1.ticsConfig.nocalc ? `-nocalc ${configuration_1.ticsConfig.nocalc} ` : ''; + execString += configuration_1.ticsConfig.recalc ? `-recalc ${configuration_1.ticsConfig.recalc} ` : ''; + execString += configuration_1.ticsConfig.norecalc ? `-norecalc ${configuration_1.ticsConfig.norecalc} ` : ''; + execString += configuration_1.ticsConfig.codetype ? `-codetype ${configuration_1.ticsConfig.codetype} ` : ''; + execString += configuration_1.ticsConfig.clientData ? `-cdtoken ${configuration_1.ticsConfig.clientData} ` : ''; + execString += configuration_1.ticsConfig.tmpDir ? `-tmpdir '${configuration_1.ticsConfig.tmpDir}' ` : ''; + } + execString += configuration_1.ticsConfig.additionalFlags ? configuration_1.ticsConfig.additionalFlags : ''; + // Add TICS debug flag when in debug mode, if this flag was not already set. + execString += configuration_1.githubConfig.debugger && !execString.includes('-log ') ? ' -log 9' : ''; + return execString; +} /***/ }), @@ -1125,121 +1125,121 @@ function getTicsCommand(fileListPath) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getProjectName = exports.getItemFromUrl = exports.getTicsWebBaseUrlFromUrl = exports.getInstallTicsApiUrl = exports.cliSummary = exports.httpRequest = void 0; -const logger_1 = __importDefault(__nccwpck_require__(6440)); -const configuration_1 = __nccwpck_require__(5527); -const node_fetch_1 = __importDefault(__nccwpck_require__(467)); -/** - * Executes a GET request to the given url. - * @param url api url to perform a GET request for. - * @returns Promise of the data retrieved from the response. - */ -async function httpRequest(url) { - var headers = { - XRequestedWith: 'tics' - }; - if (configuration_1.ticsConfig.ticsAuthToken) { - headers.Authorization = `Basic ${configuration_1.ticsConfig.ticsAuthToken}`; - } - configuration_1.requestInit.headers = headers; - const response = await (0, node_fetch_1.default)(url, configuration_1.requestInit); - switch (response.status) { - case 200: - return response.json(); - case 302: - logger_1.default.Instance.exit(`HTTP request failed with status ${response.status}. Please check if the given ticsConfiguration is correct (possibly http instead of https).`); - break; - case 400: - logger_1.default.Instance.exit(`HTTP request failed with status ${response.status}. ${(await response.json()).alertMessages[0].header}`); - break; - case 401: - logger_1.default.Instance.exit(`HTTP request failed with status ${response.status}. Please provide a valid TICSAUTHTOKEN in your configuration. Check ${configuration_1.viewerUrl}/Administration.html#page=authToken`); - break; - case 403: - logger_1.default.Instance.exit(`HTTP request failed with status ${response.status}. Forbidden call: ${url}`); - break; - case 404: - logger_1.default.Instance.exit(`HTTP request failed with status ${response.status}. Please check if the given ticsConfiguration is correct.`); - break; - default: - logger_1.default.Instance.exit(`HTTP request failed with status ${response.status}. Please check if your configuration is correct.`); - break; - } -} -exports.httpRequest = httpRequest; -/** - * Creates a cli summary of all errors and bugs based on the logLevel. - * @param analysis the output of the TiCS analysis run. - */ -function cliSummary(analysis) { - analysis.errorList.forEach(error => logger_1.default.Instance.error(error)); - if (configuration_1.githubConfig.debugger) { - analysis.warningList.forEach(warning => logger_1.default.Instance.warning(warning)); - } -} -exports.cliSummary = cliSummary; -/** - * Creates the TiCS install data from the TiCS Viewer. - * @param url url given in the ticsConfiguration. - * @param os the OS the runner runs on. - * @returns the TiCS install url. - */ -function getInstallTicsApiUrl(url, os) { - const installTicsApi = new URL(configuration_1.ticsConfig.ticsConfiguration); - installTicsApi.searchParams.append('platform', os); - installTicsApi.searchParams.append('url', url); - return installTicsApi.href; -} -exports.getInstallTicsApiUrl = getInstallTicsApiUrl; -/** - * Returns the TIOBE web base url. - * @param url url given in the ticsConfiguration. - * @returns TIOBE web base url. - */ -function getTicsWebBaseUrlFromUrl(url) { - const cfgMarker = 'cfg?name='; - const apiMarker = '/api/'; - let baseUrl = ''; - if (url.includes(apiMarker + cfgMarker)) { - baseUrl = url.split(apiMarker)[0]; - } - else { - logger_1.default.Instance.exit('Missing configuration api in the TiCS Viewer URL. Please check your workflow configuration.'); - } - return baseUrl; -} -exports.getTicsWebBaseUrlFromUrl = getTicsWebBaseUrlFromUrl; -/** - * Gets query value form a url - * @param url The TiCS Explorer url (e.g. /Explorer.html#axes=Project%28c-demo%29%2CBranch%28main%) - * @param query the query (e.g. Project) - * @returns query value (e.g. c-demo) - **/ -function getItemFromUrl(url, query) { - let regExpr = new RegExp(`${query}\\((.*?)\\)`); - let cleanUrl = url.replace(/\+/g, '%20'); - let itemValue = decodeURIComponent(cleanUrl).match(regExpr); - if (itemValue && itemValue.length >= 2) { - logger_1.default.Instance.debug(`Retrieved ${query} value: ${itemValue[1]}`); - return itemValue[1]; - } - return ''; -} -exports.getItemFromUrl = getItemFromUrl; -/** - * In case of project auto this returns the project name from the explorer url. - * @param url the TiCS explorer url. - * @returns project name. - */ -function getProjectName(url) { - return configuration_1.ticsConfig.projectName === 'auto' ? getItemFromUrl(url, 'Project') : configuration_1.ticsConfig.projectName; -} -exports.getProjectName = getProjectName; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getProjectName = exports.getItemFromUrl = exports.getTicsWebBaseUrlFromUrl = exports.getInstallTicsApiUrl = exports.cliSummary = exports.httpRequest = void 0; +const logger_1 = __importDefault(__nccwpck_require__(6440)); +const configuration_1 = __nccwpck_require__(5527); +const node_fetch_1 = __importDefault(__nccwpck_require__(467)); +/** + * Executes a GET request to the given url. + * @param url api url to perform a GET request for. + * @returns Promise of the data retrieved from the response. + */ +async function httpRequest(url) { + var headers = { + XRequestedWith: 'tics' + }; + if (configuration_1.ticsConfig.ticsAuthToken) { + headers.Authorization = `Basic ${configuration_1.ticsConfig.ticsAuthToken}`; + } + configuration_1.requestInit.headers = headers; + const response = await (0, node_fetch_1.default)(url, configuration_1.requestInit); + switch (response.status) { + case 200: + return response.json(); + case 302: + logger_1.default.Instance.exit(`HTTP request failed with status ${response.status}. Please check if the given ticsConfiguration is correct (possibly http instead of https).`); + break; + case 400: + logger_1.default.Instance.exit(`HTTP request failed with status ${response.status}. ${(await response.json()).alertMessages[0].header}`); + break; + case 401: + logger_1.default.Instance.exit(`HTTP request failed with status ${response.status}. Please provide a valid TICSAUTHTOKEN in your configuration. Check ${configuration_1.viewerUrl}/Administration.html#page=authToken`); + break; + case 403: + logger_1.default.Instance.exit(`HTTP request failed with status ${response.status}. Forbidden call: ${url}`); + break; + case 404: + logger_1.default.Instance.exit(`HTTP request failed with status ${response.status}. Please check if the given ticsConfiguration is correct.`); + break; + default: + logger_1.default.Instance.exit(`HTTP request failed with status ${response.status}. Please check if your configuration is correct.`); + break; + } +} +exports.httpRequest = httpRequest; +/** + * Creates a cli summary of all errors and bugs based on the logLevel. + * @param analysis the output of the TiCS analysis run. + */ +function cliSummary(analysis) { + analysis.errorList.forEach(error => logger_1.default.Instance.error(error)); + if (configuration_1.githubConfig.debugger) { + analysis.warningList.forEach(warning => logger_1.default.Instance.warning(warning)); + } +} +exports.cliSummary = cliSummary; +/** + * Creates the TiCS install data from the TiCS Viewer. + * @param url url given in the ticsConfiguration. + * @param os the OS the runner runs on. + * @returns the TiCS install url. + */ +function getInstallTicsApiUrl(url, os) { + const installTicsApi = new URL(configuration_1.ticsConfig.ticsConfiguration); + installTicsApi.searchParams.append('platform', os); + installTicsApi.searchParams.append('url', url); + return installTicsApi.href; +} +exports.getInstallTicsApiUrl = getInstallTicsApiUrl; +/** + * Returns the TIOBE web base url. + * @param url url given in the ticsConfiguration. + * @returns TIOBE web base url. + */ +function getTicsWebBaseUrlFromUrl(url) { + const cfgMarker = 'cfg?name='; + const apiMarker = '/api/'; + let baseUrl = ''; + if (url.includes(apiMarker + cfgMarker)) { + baseUrl = url.split(apiMarker)[0]; + } + else { + logger_1.default.Instance.exit('Missing configuration api in the TiCS Viewer URL. Please check your workflow configuration.'); + } + return baseUrl; +} +exports.getTicsWebBaseUrlFromUrl = getTicsWebBaseUrlFromUrl; +/** + * Gets query value form a url + * @param url The TiCS Explorer url (e.g. /Explorer.html#axes=Project%28c-demo%29%2CBranch%28main%) + * @param query the query (e.g. Project) + * @returns query value (e.g. c-demo) + **/ +function getItemFromUrl(url, query) { + let regExpr = new RegExp(`${query}\\((.*?)\\)`); + let cleanUrl = url.replace(/\+/g, '%20'); + let itemValue = decodeURIComponent(cleanUrl).match(regExpr); + if (itemValue && itemValue.length >= 2) { + logger_1.default.Instance.debug(`Retrieved ${query} value: ${itemValue[1]}`); + return itemValue[1]; + } + return ''; +} +exports.getItemFromUrl = getItemFromUrl; +/** + * In case of project auto this returns the project name from the explorer url. + * @param url the TiCS explorer url. + * @returns project name. + */ +function getProjectName(url) { + return configuration_1.ticsConfig.projectName === 'auto' ? getItemFromUrl(url, 'Project') : configuration_1.ticsConfig.projectName; +} +exports.getProjectName = getProjectName; /***/ }), @@ -1248,142 +1248,142 @@ exports.getProjectName = getProjectName; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getViewerVersion = exports.getAnnotations = exports.getQualityGate = exports.getAnalyzedFiles = void 0; -const configuration_1 = __nccwpck_require__(5527); -const logger_1 = __importDefault(__nccwpck_require__(6440)); -const api_helper_1 = __nccwpck_require__(3823); -/** - * Retrieves the files TiCS analyzed from the TiCS viewer. - * @param url The TiCS explorer url. - * @returns the analyzed files. - */ -async function getAnalyzedFiles(url, changedFiles) { - logger_1.default.Instance.header('Retrieving analyzed files.'); - const analyzedFilesUrl = getAnalyzedFilesUrl(url); - let analyzedFiles = []; - logger_1.default.Instance.debug(`From: ${analyzedFilesUrl}`); - try { - const response = await (0, api_helper_1.httpRequest)(analyzedFilesUrl); - if (response) { - analyzedFiles = response.data - .filter((file) => { - return changedFiles.find(cf => cf.filename === file.formattedValue) ? true : false; - }) - .map((file) => { - logger_1.default.Instance.debug(file.formattedValue); - return file.formattedValue; - }); - logger_1.default.Instance.info('Retrieved the analyzed files.'); - } - } - catch (error) { - let message = 'unknown error'; - if (error instanceof Error) - message = error.message; - logger_1.default.Instance.exit(`There was an error retrieving the analyzed files: ${message}`); - } - return analyzedFiles; -} -exports.getAnalyzedFiles = getAnalyzedFiles; -/** - * Returns the url to get the analyzed files with from the TiCS. - * @param url The TiCS explorer url. - * @returns url to get the analyzed files from. - */ -function getAnalyzedFilesUrl(url) { - let getAnalyzedFilesUrl = new URL(configuration_1.baseUrl + '/api/public/v1/Measure?metrics=filePath'); - const clientData = (0, api_helper_1.getItemFromUrl)(url, 'ClientData'); - const projectName = (0, api_helper_1.getProjectName)(url); - getAnalyzedFilesUrl.searchParams.append('filters', `ClientData(${clientData}),Project(${projectName}),Window(-1),File()`); - return getAnalyzedFilesUrl.href; -} -/** - * Retrieves the TiCS quality gate from the TiCS viewer. - * @param url The TiCS explorer url. - * @returns the quality gates - */ -async function getQualityGate(url) { - logger_1.default.Instance.header('Retrieving the quality gates.'); - const qualityGateUrl = getQualityGateUrl(url); - logger_1.default.Instance.debug(`From: ${qualityGateUrl}`); - try { - const response = await (0, api_helper_1.httpRequest)(qualityGateUrl); - logger_1.default.Instance.info('Retrieved the quality gates.'); - logger_1.default.Instance.debug(JSON.stringify(response)); - return response; - } - catch (error) { - logger_1.default.Instance.exit(`There was an error retrieving the quality gates: ${error.message}`); - } -} -exports.getQualityGate = getQualityGate; -/** - * Builds the quality gate url from the explorer url. - * @param url The TiCS Explorer url. - * @returns The url to get the quality gate analysis. - */ -function getQualityGateUrl(url) { - let qualityGateUrl = new URL(configuration_1.baseUrl + '/api/public/v1/QualityGateStatus'); - const projectName = (0, api_helper_1.getProjectName)(url); - qualityGateUrl.searchParams.append('project', projectName); - // Branchname is optional, to check if it is set - if (configuration_1.ticsConfig.branchName) { - qualityGateUrl.searchParams.append('branch', configuration_1.ticsConfig.branchName); - } - qualityGateUrl.searchParams.append('fields', 'details,annotationsApiV1Links'); - const clientData = (0, api_helper_1.getItemFromUrl)(url, 'ClientData'); - qualityGateUrl.searchParams.append('cdt', clientData); - return qualityGateUrl.href; -} -/** - * Gets the annotations from the TiCS viewer. - * @param apiLinks annotationsApiLinks url. - * @returns TiCS annotations. - */ -async function getAnnotations(apiLinks) { - logger_1.default.Instance.header('Retrieving annotations.'); - try { - let annotations = []; - await Promise.all(apiLinks.map(async (link, index) => { - const annotationsUrl = `${configuration_1.baseUrl}/${link.url}`; - logger_1.default.Instance.debug(`From: ${annotationsUrl}`); - const response = await (0, api_helper_1.httpRequest)(annotationsUrl); - response.data.forEach((annotation) => { - annotation.gateId = index; - logger_1.default.Instance.debug(JSON.stringify(annotation)); - annotations.push(annotation); - }); - })); - logger_1.default.Instance.info('Retrieved all annotations.'); - return annotations; - } - catch (error) { - logger_1.default.Instance.exit(`An error occured when trying to retrieve annotations: ${error.message}`); - } -} -exports.getAnnotations = getAnnotations; -/** - * Gets the version of the TiCS viewer used. - * @returns Version of the used TiCS viewer. - */ -async function getViewerVersion() { - let getViewerVersionUrl = new URL(configuration_1.baseUrl + '/api/v1/version'); - try { - const response = await (0, api_helper_1.httpRequest)(getViewerVersionUrl.href); - logger_1.default.Instance.info('Retrieved the Viewer Version.'); - logger_1.default.Instance.debug(JSON.stringify(response)); - return response; - } - catch (error) { - logger_1.default.Instance.exit(`There was an error retrieving the Viewer version: ${error.message}`); - } -} -exports.getViewerVersion = getViewerVersion; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getViewerVersion = exports.getAnnotations = exports.getQualityGate = exports.getAnalyzedFiles = void 0; +const configuration_1 = __nccwpck_require__(5527); +const logger_1 = __importDefault(__nccwpck_require__(6440)); +const api_helper_1 = __nccwpck_require__(3823); +/** + * Retrieves the files TiCS analyzed from the TiCS viewer. + * @param url The TiCS explorer url. + * @returns the analyzed files. + */ +async function getAnalyzedFiles(url, changedFiles) { + logger_1.default.Instance.header('Retrieving analyzed files.'); + const analyzedFilesUrl = getAnalyzedFilesUrl(url); + let analyzedFiles = []; + logger_1.default.Instance.debug(`From: ${analyzedFilesUrl}`); + try { + const response = await (0, api_helper_1.httpRequest)(analyzedFilesUrl); + if (response) { + analyzedFiles = response.data + .filter((file) => { + return changedFiles.find(cf => cf.filename === file.formattedValue) ? true : false; + }) + .map((file) => { + logger_1.default.Instance.debug(file.formattedValue); + return file.formattedValue; + }); + logger_1.default.Instance.info('Retrieved the analyzed files.'); + } + } + catch (error) { + let message = 'unknown error'; + if (error instanceof Error) + message = error.message; + logger_1.default.Instance.exit(`There was an error retrieving the analyzed files: ${message}`); + } + return analyzedFiles; +} +exports.getAnalyzedFiles = getAnalyzedFiles; +/** + * Returns the url to get the analyzed files with from the TiCS. + * @param url The TiCS explorer url. + * @returns url to get the analyzed files from. + */ +function getAnalyzedFilesUrl(url) { + let getAnalyzedFilesUrl = new URL(configuration_1.baseUrl + '/api/public/v1/Measure?metrics=filePath'); + const clientData = (0, api_helper_1.getItemFromUrl)(url, 'ClientData'); + const projectName = (0, api_helper_1.getProjectName)(url); + getAnalyzedFilesUrl.searchParams.append('filters', `ClientData(${clientData}),Project(${projectName}),Window(-1),File()`); + return getAnalyzedFilesUrl.href; +} +/** + * Retrieves the TiCS quality gate from the TiCS viewer. + * @param url The TiCS explorer url. + * @returns the quality gates + */ +async function getQualityGate(url) { + logger_1.default.Instance.header('Retrieving the quality gates.'); + const qualityGateUrl = getQualityGateUrl(url); + logger_1.default.Instance.debug(`From: ${qualityGateUrl}`); + try { + const response = await (0, api_helper_1.httpRequest)(qualityGateUrl); + logger_1.default.Instance.info('Retrieved the quality gates.'); + logger_1.default.Instance.debug(JSON.stringify(response)); + return response; + } + catch (error) { + logger_1.default.Instance.exit(`There was an error retrieving the quality gates: ${error.message}`); + } +} +exports.getQualityGate = getQualityGate; +/** + * Builds the quality gate url from the explorer url. + * @param url The TiCS Explorer url. + * @returns The url to get the quality gate analysis. + */ +function getQualityGateUrl(url) { + let qualityGateUrl = new URL(configuration_1.baseUrl + '/api/public/v1/QualityGateStatus'); + const projectName = (0, api_helper_1.getProjectName)(url); + qualityGateUrl.searchParams.append('project', projectName); + // Branchname is optional, to check if it is set + if (configuration_1.ticsConfig.branchName) { + qualityGateUrl.searchParams.append('branch', configuration_1.ticsConfig.branchName); + } + qualityGateUrl.searchParams.append('fields', 'details,annotationsApiV1Links'); + const clientData = (0, api_helper_1.getItemFromUrl)(url, 'ClientData'); + qualityGateUrl.searchParams.append('cdt', clientData); + return qualityGateUrl.href; +} +/** + * Gets the annotations from the TiCS viewer. + * @param apiLinks annotationsApiLinks url. + * @returns TiCS annotations. + */ +async function getAnnotations(apiLinks) { + logger_1.default.Instance.header('Retrieving annotations.'); + try { + let annotations = []; + await Promise.all(apiLinks.map(async (link, index) => { + const annotationsUrl = `${configuration_1.baseUrl}/${link.url}`; + logger_1.default.Instance.debug(`From: ${annotationsUrl}`); + const response = await (0, api_helper_1.httpRequest)(annotationsUrl); + response.data.forEach((annotation) => { + annotation.gateId = index; + logger_1.default.Instance.debug(JSON.stringify(annotation)); + annotations.push(annotation); + }); + })); + logger_1.default.Instance.info('Retrieved all annotations.'); + return annotations; + } + catch (error) { + logger_1.default.Instance.exit(`An error occured when trying to retrieve annotations: ${error.message}`); + } +} +exports.getAnnotations = getAnnotations; +/** + * Gets the version of the TiCS viewer used. + * @returns Version of the used TiCS viewer. + */ +async function getViewerVersion() { + let getViewerVersionUrl = new URL(configuration_1.baseUrl + '/api/v1/version'); + try { + const response = await (0, api_helper_1.httpRequest)(getViewerVersionUrl.href); + logger_1.default.Instance.info('Retrieved the Viewer Version.'); + logger_1.default.Instance.debug(JSON.stringify(response)); + return response; + } + catch (error) { + logger_1.default.Instance.exit(`There was an error retrieving the Viewer version: ${error.message}`); + } +} +exports.getViewerVersion = getViewerVersion; /***/ }), @@ -56771,8 +56771,13 @@ function resolverFromOptions(vm, options, override, compiler) { } const resolved = customResolver(x, path); if (!resolved) return undefined; - if (externals) externals.push(new RegExp('^' + escapeRegExp(resolved))); - return resolver.loadAsFileOrDirecotry(resolved, extList); + if (typeof resolved === 'string') { + if (externals) externals.push(new RegExp('^' + escapeRegExp(resolved))); + return resolver.loadAsFileOrDirectory(resolved, extList); + } + const {module=x, path: resolvedPath} = resolved; + if (externals) externals.push(new RegExp('^' + escapeRegExp(resolvedPath))); + return resolver.loadNodeModules(module, [resolvedPath], extList); }; } @@ -57044,7 +57049,7 @@ class DefaultResolver extends Resolver { // 2. If X begins with '/' if (this.pathIsAbsolute(x)) { // a. set Y to be the filesystem root - f = this.loadAsFileOrDirecotry(x, extList); + f = this.loadAsFileOrDirectory(x, extList); if (f) return f; // c. THROW "not found" @@ -57058,13 +57063,13 @@ class DefaultResolver extends Resolver { for (let i = 0; i < paths.length; i++) { // a. LOAD_AS_FILE(Y + X) // b. LOAD_AS_DIRECTORY(Y + X) - f = this.loadAsFileOrDirecotry(this.pathConcat(paths[i], x), extList); + f = this.loadAsFileOrDirectory(this.pathConcat(paths[i], x), extList); if (f) return f; } } else if (paths === undefined) { // a. LOAD_AS_FILE(Y + X) // b. LOAD_AS_DIRECTORY(Y + X) - f = this.loadAsFileOrDirecotry(this.pathConcat(path, x), extList); + f = this.loadAsFileOrDirectory(this.pathConcat(path, x), extList); if (f) return f; } else { throw new VMError('Invalid options.paths option.'); @@ -57072,7 +57077,7 @@ class DefaultResolver extends Resolver { } else { // a. LOAD_AS_FILE(Y + X) // b. LOAD_AS_DIRECTORY(Y + X) - f = this.loadAsFileOrDirecotry(this.pathConcat(path, x), extList); + f = this.loadAsFileOrDirectory(this.pathConcat(path, x), extList); if (f) return f; } @@ -57117,7 +57122,7 @@ class DefaultResolver extends Resolver { return super.resolveFull(mod, x, options, ext, direct); } - loadAsFileOrDirecotry(x, extList) { + loadAsFileOrDirectory(x, extList) { // a. LOAD_AS_FILE(X) const f = this.loadAsFile(x, extList); if (f) return f; @@ -57357,7 +57362,7 @@ class DefaultResolver extends Resolver { } else { // a. LOAD_AS_FILE(RESOLVED_PATH) // b. LOAD_AS_DIRECTORY(RESOLVED_PATH) - f = this.loadAsFileOrDirecotry(resolvedPath, extList); + f = this.loadAsFileOrDirectory(resolvedPath, extList); } if (f) return f; // 5. THROW "not found" diff --git a/dist/setup-sandbox.js b/dist/setup-sandbox.js index f6cbb8ea..539ce045 100644 --- a/dist/setup-sandbox.js +++ b/dist/setup-sandbox.js @@ -276,13 +276,30 @@ if (typeof OriginalCallSite === 'function') { return; } const newWrapped = (error, sst) => { + const sandboxSst = ensureThis(sst); if (localArrayIsArray(sst)) { - for (let i=0; i < sst.length; i++) { - const cs = sst[i]; - if (typeof cs === 'object' && localReflectGetPrototypeOf(cs) === OriginalCallSite.prototype) { - sst[i] = new CallSite(cs); + if (sst === sandboxSst) { + for (let i=0; i < sst.length; i++) { + const cs = sst[i]; + if (typeof cs === 'object' && localReflectGetPrototypeOf(cs) === OriginalCallSite.prototype) { + sst[i] = new CallSite(cs); + } + } + } else { + sst = []; + for (let i=0; i < sandboxSst.length; i++) { + const cs = sandboxSst[i]; + localReflectDefineProperty(sst, i, { + __proto__: null, + value: new CallSite(cs), + enumerable: true, + configurable: true, + writable: true + }); } } + } else { + sst = sandboxSst; } return value(error, sst); };