Skip to content

Commit

Permalink
feat: add checkAfterItems in builders
Browse files Browse the repository at this point in the history
  • Loading branch information
guillaumerochelle committed Nov 26, 2024
1 parent 2c094a7 commit 3db3b68
Show file tree
Hide file tree
Showing 17 changed files with 91 additions and 74 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@
"jest-preset-angular": "~14.2.0",
"js-yaml": "^4.1.0",
"jsonc-eslint-parser": "~2.4.0",
"jsonpath-plus": "~10.0.0",
"jsonpath-plus": "~10.0.7",
"lighthouse": "~12.2.0",
"lint-staged": "^15.0.0",
"minimist": "^1.2.6",
Expand Down
5 changes: 5 additions & 0 deletions packages/@o3r/components/builders/metadata-check/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@
"type": "string",
"description": "Path of the config metadata file.",
"default": "./component.config.metadata.json"
},
"checkAfterItems": {
"type": "boolean",
"description": "Whether after items should be checked.",
"default": true
}
},
"additionalProperties": false,
Expand Down
2 changes: 1 addition & 1 deletion packages/@o3r/components/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@
"jest-junit": "~16.0.0",
"jest-preset-angular": "~14.2.0",
"jsonc-eslint-parser": "~2.4.0",
"jsonpath-plus": "~10.0.0",
"jsonpath-plus": "~10.0.7",
"memfs": "~4.12.0",
"nx": "~19.5.0",
"pid-from-port": "^1.1.3",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,7 @@ export interface MigrationMetadataCheckBuilderOptions extends JsonObject {

/** Entry to check for previous metadata in the `package.json` file under `cmsMetadata`. */
packageJsonEntry: keyof Omit<CmsMetadataData, 'libraryName'>;

/** Whether to check the items set in "after" property in the migration file. */
checkAfterItems: boolean;
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ function checkMetadataFile<MetadataItem, MigrationMetadataItem, MetadataFile>(
newMetadataFile: MetadataFile,
migrationData: MigrationData<MigrationMetadataItem>[],
isBreakingChangeAllowed: boolean,
checkAfterItems: boolean,
comparator: MetadataComparator<MetadataItem, MigrationMetadataItem, MetadataFile>
): Error[] {
const errors: Error[] = [];
Expand All @@ -40,7 +41,7 @@ function checkMetadataFile<MetadataItem, MigrationMetadataItem, MetadataFile>(
continue;
}

if (migrationMetadataValue.after) {
if (checkAfterItems && migrationMetadataValue.after) {
const isNewValueInNewMetadata = newMetadataArray.some((newValue) => comparator.isMigrationDataMatch(newValue, migrationMetadataValue.after!, migrationMetadataValue.contentType));
if (!isNewValueInNewMetadata) {
errors.push(new Error(`Property ${comparator.getIdentifier(lastValue)} has been modified but the new property is not present in the new metadata`));
Expand Down Expand Up @@ -161,7 +162,7 @@ Detection of package manager runner will fallback on the one used to execute the
const newFile = getLocalMetadataFile<MetadataFile>(metadataPathInWorkspace);


const errors = checkMetadataFile<MetadataItem, MigrationMetadataItem, MetadataFile>(metadata, newFile, migrationData.changes, options.allowBreakingChanges, comparator);
const errors = checkMetadataFile<MetadataItem, MigrationMetadataItem, MetadataFile>(metadata, newFile, migrationData.changes, options.allowBreakingChanges, options.checkAfterItems, comparator);

if (errors.length) {
return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@
"type": "string",
"description": "Path of the localization metadata file.",
"default": "./localisation.metadata.json"
},
"checkAfterItems": {
"type": "boolean",
"description": "Whether after items should be checked.",
"default": true
}
},
"additionalProperties": false,
Expand Down
2 changes: 1 addition & 1 deletion packages/@o3r/rules-engine/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@
"jest-junit": "~16.0.0",
"jest-preset-angular": "~14.2.0",
"jsonc-eslint-parser": "~2.4.0",
"jsonpath-plus": "~10.0.0",
"jsonpath-plus": "~10.0.7",
"memfs": "~4.12.0",
"nx": "~19.5.0",
"pid-from-port": "^1.1.3",
Expand Down
5 changes: 5 additions & 0 deletions packages/@o3r/styling/builders/metadata-check/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@
"type": "string",
"description": "Path of the styling metadata file.",
"default": "./style.metadata.json"
},
"checkAfterItems": {
"type": "boolean",
"description": "Whether after items should be checked.",
"default": true
}
},
"additionalProperties": false,
Expand Down
47 changes: 21 additions & 26 deletions tools/github-actions/audit/packaged-action/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26205,7 +26205,7 @@ const colors = ['', 'green', 'yellow', 'orange', 'red'];
*/
function computeYarn4Report(response, severityThreshold) {
core.info('Computing Report for Yarn 4');
const reports = response.split('\n').filter((a) => !!a);
const reports = response.split('\n').filter(a => !!a);
const severityThresholdIndex = severities.indexOf(severityThreshold);
return reports.reduce((currentReport, currentVulnerability) => {
const vulnerabilityReport = JSON.parse(currentVulnerability);
Expand All @@ -26225,9 +26225,8 @@ function computeYarn4Report(response, severityThreshold) {
overview: `This issue affects versions ${vulnerabilityReport.children['Vulnerable Versions']}. ${vulnerabilityReport.children.Issue}`
});
}
currentReport.highestSeverityFound = severities.indexOf(currentReport.highestSeverityFound || 'info') <= severities.indexOf(vulnerabilitySeverity)
? vulnerabilitySeverity
: currentReport.highestSeverityFound;
currentReport.highestSeverityFound = severities.indexOf(currentReport.highestSeverityFound || 'info') <= severities.indexOf(vulnerabilitySeverity) ?
vulnerabilitySeverity : currentReport.highestSeverityFound;
currentReport.nbVulnerabilities += 1;
return currentReport;
}, { nbVulnerabilities: 0, errors: [], warnings: [] });
Expand Down Expand Up @@ -26276,13 +26275,13 @@ async function run() {
core.warning(err);
core.setOutput('reportJSON', report);
const reportData = version >= 4 ? computeYarn4Report(report, severityConfig) : computeYarn3Report(report, severityConfig);
if (reportData.highestSeverityFound) {
core.info(`Highest severity found: ${reportData.highestSeverityFound}`);
}
else {
if (!reportData.highestSeverityFound) {
core.info('No vulnerability detected.');
return;
}
else {
core.info(`Highest severity found: ${reportData.highestSeverityFound}`);
}
const isFailed = reportData.errors.length > 0;
const getBadge = (sev) => `![${sev}](https://img.shields.io/static/v1?label=&logo=npm&message=${sev}&color=${colors[severities.indexOf(sev)]})`;
const formatVulnerability = (vulnerability) => `
Expand All @@ -26295,40 +26294,36 @@ ${vulnerability.overview.replaceAll('### ', '#### ')}
</details>

`;
const isVulnerabilityWithKnownSeverity = (advisory) => severities.includes(advisory.severity);
const isVulnerabilityWithKnownSeverity = (advisory) => severities.indexOf(advisory.severity) >= 0;
const sortVulnerabilityBySeverity = (advisory1, advisory2) => severities.indexOf(advisory2.severity) - severities.indexOf(advisory1.severity);
const body = `# Audit report ${isFailed ? ':x:' : ':white_check_mark:'}

${reportData.nbVulnerabilities} vulnerabilities found.

${reportData.errors.length > 0
? `## Vulnerabilities to be fixed
${reportData.errors.length ? `## Vulnerabilities to be fixed

${reportData.errors
.filter(isVulnerabilityWithKnownSeverity)
.sort(sortVulnerabilityBySeverity)
.map(formatVulnerability)
.join(os.EOL)}
`
: ''}
${reportData.warnings.length > 0
? `___
.filter(isVulnerabilityWithKnownSeverity)
.sort(sortVulnerabilityBySeverity)
.map(formatVulnerability)
.join(os.EOL)}
` : ''}
${reportData.warnings.length ? `___

<details>
<summary>
Vulnerabilities below the threshold: ${severityConfig}
</summary>

${reportData.warnings
.filter(isVulnerabilityWithKnownSeverity)
.sort(sortVulnerabilityBySeverity)
.map(formatVulnerability)
.join(os.EOL)
.replaceAll('${', '&#36;{')}
.filter(isVulnerabilityWithKnownSeverity)
.sort(sortVulnerabilityBySeverity)
.map(formatVulnerability)
.join(os.EOL)
.replaceAll('${', '&#36;{')}

</details>
`
: ''}
` : ''}
`;
core.setOutput('reportMarkdown', body);
if (isFailed) {
Expand Down
2 changes: 1 addition & 1 deletion tools/github-actions/audit/packaged-action/index.js.map

Large diffs are not rendered by default.

39 changes: 20 additions & 19 deletions tools/github-actions/cascading/packaged-action/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29302,7 +29302,7 @@ class Cascading {
}
catch (e) {
// Compute the packages for which to ignore the conflict if any
if (this.options.conflictsIgnoredPackages.length > 0) {
if (this.options.conflictsIgnoredPackages.length) {
this.options.logger.info('Checking if ignored packages are the only conflicts of the cascading');
this.options.logger.info(`Packages to ignore: ${JSON.stringify(this.options.conflictsIgnoredPackages)}`);
const cascadingError = e.stdout;
Expand All @@ -29314,14 +29314,14 @@ class Cascading {
.map((line) => line.split(conflictingFileStartOfLine)[1]);
const onlyPackagesInConflict = filesInConflict.every((fileName) => fileName.endsWith('package.json') || fileName.endsWith('yarn.lock'));
// We won't handle the use case where only the yarn lock is in conflict
const packageJsonInConflict = filesInConflict.some((filename) => filename.endsWith('package.json'));
const packageJsonInConflict = filesInConflict.some(filename => filename.endsWith('package.json'));
this.options.logger.info(`Files in conflict: ${JSON.stringify(filesInConflict)}`);
if (onlyPackagesInConflict && packageJsonInConflict) {
this.options.logger.info('Conflict is only about packages, checking if we can ignore it');
const gitDiffResultOutput = (await (0, helpers_1.handlePromisifiedExecLog)(promisifiedExec('git diff'), this.options.logger)).stdout;
const changes = (0, helpers_1.extractPackageChanges)(gitDiffResultOutput, this.options.logger);
const notIgnorablePackageChanges = (0, helpers_1.notIgnorablePackages)(changes.packageChanges, this.options.conflictsIgnoredPackages);
if (notIgnorablePackageChanges.length > 0) {
if (notIgnorablePackageChanges.length) {
this.options.logger.info('Conflicts in package.json cannot be ignored');
notIgnorablePackageChanges.forEach((fileChange) => {
this.options.logger.info(JSON.stringify(fileChange, null, 2));
Expand All @@ -29345,7 +29345,7 @@ class Cascading {
await (0, helpers_1.handlePromisifiedExecLog)(promisifiedExec('git status'), this.options.logger);
this.options.logger.info('Should create a branch with completion done inside');
const authenticatedGitUrl = this.githubContext.payload.repository.html_url.replace(/https:\/\/[\w-]+@/, `https://${this.ownerName}:${this.options.token}@`);
const newCascadingBranchName = `automation/automatic-cascading-resolution-${Date.now()}`;
const newCascadingBranchName = `automation/automatic-cascading-resolution-${new Date().getTime()}`;
await (0, helpers_1.handlePromisifiedExecLog)(promisifiedExec(`git push ${authenticatedGitUrl} ${branchToCascade}:${newCascadingBranchName}`), this.options.logger);
this.options.logger.info('Creating a Pull Request with package conflict resolutions');
await this.createFallbackPullRequest(branchToCascade, `Cascading merge failure ${this.options.baseBranch} -> ${branchToCascade} with automatic package conflict resolution`, `refs/heads/${newCascadingBranchName}`, `refs/heads/${branchToCascade}`);
Expand Down Expand Up @@ -29409,7 +29409,7 @@ class Cascading {
this.options.logger.info('Process to assign the responsible of the failure');
const firstMergeCommit = await this.getFirstMergeCommit(pullRequestCreationResponse.data.number);
this.options.logger.debug(JSON.stringify(firstMergeCommit, null, 2));
if (firstMergeCommit?.author) {
if (firstMergeCommit.author) {
this.options.logger.info(`Responsible of the failure is ${JSON.stringify(firstMergeCommit.author.login)}`);
await this.assignPullRequest(pullRequestCreationResponse.data.number, firstMergeCommit.author.login);
}
Expand All @@ -29430,7 +29430,7 @@ class Cascading {
});
this.options.logger.debug(JSON.stringify(commitsResponse, null, 2));
// Responsible for the merge conflict is the first person who merged his PR
return commitsResponse.data.reverse().find(((commitObject) => commitObject.commit.message.startsWith('Merged'))) || commitsResponse.data.at(-1);
return commitsResponse.data.reverse().find((commitObject => commitObject.commit.message.startsWith('Merged'))) || commitsResponse.data[commitsResponse.data.length - 1];
}
/**
* Assign a pull request a user
Expand Down Expand Up @@ -29473,14 +29473,14 @@ exports.notIgnorablePackages = notIgnorablePackages;
* @param branches
*/
function sortBranches(branches) {
return branches.map((branch) => {
return branches.map(branch => {
const extract = branch.match(/release\/([0-9]+)\.([0-9]+)/);
if (!extract) {
throw new Error(`Format of branch does not match the release pattern ${branches.join(',')}`);
}
return {
maj: Number.parseInt(extract[1], 10),
min: Number.parseInt(extract[2], 10),
maj: parseInt(extract[1], 10),
min: parseInt(extract[2], 10),
branch
};
}).sort((branchObjectA, branchObjectB) => {
Expand All @@ -29491,7 +29491,7 @@ function sortBranches(branches) {
return -1;
}
return branchObjectA.min - branchObjectB.min;
}).map((branchObject) => branchObject.branch);
}).map(branchObject => branchObject.branch);
}
/**
* Extract just the branches matching the release/min.maj[.0-next|prerelease|rc] format
Expand All @@ -29510,7 +29510,7 @@ function extractBranchesFromGitOutput(gitOutput) {
*/
function extractPackageLine(diffOutput) {
const results = diffOutput.matchAll(/"([^"]+)":\s+/g);
return [...results].map((result) => result[1]);
return [...results].map(result => result[1]);
}
/**
* Extract the list of old and new packages from a multi-line string coming from a git diff
Expand Down Expand Up @@ -29573,22 +29573,22 @@ function extractPackageChanges(gitDiffResult, logger) {
*/
function notIgnorablePackages(packageChanges, conflictsIgnoredPackages) {
return packageChanges.reduce((remaining, fileWithPackages) => {
if (fileWithPackages.oldPackages.length > 0 || fileWithPackages.newPackages.length > 0) {
if (fileWithPackages.oldPackages.length || fileWithPackages.newPackages.length) {
const removedPackages = [];
const commonPackages = [];
fileWithPackages.oldPackages.forEach((oldPackage) => {
if (fileWithPackages.newPackages.includes(oldPackage)) {
if (!fileWithPackages.newPackages.includes(oldPackage)) {
removedPackages.push(oldPackage);
}
else {
if (!conflictsIgnoredPackages.includes(oldPackage)) {
// We keep it only if it is not ignored
commonPackages.push(oldPackage);
}
}
else {
removedPackages.push(oldPackage);
}
});
const addedPackages = fileWithPackages.newPackages.filter((newPackage) => !fileWithPackages.oldPackages.includes(newPackage));
if (addedPackages.length > 0 || commonPackages.length > 0 || removedPackages.length > 0) {
if (addedPackages.length || commonPackages.length || removedPackages.length) {
remaining.push({
file: fileWithPackages.file,
addedPackages,
Expand Down Expand Up @@ -29686,7 +29686,7 @@ async function run() {
}
catch (error) {
core.error('Caught an error during the plug-in execution');
const errorMessage = error instanceof Error ? error.message : (typeof error === 'string' ? error : 'Caught an error during the plug-in execution');
const errorMessage = error instanceof Error ? error.message : typeof error === 'string' ? error : 'Caught an error during the plug-in execution';
if (errorMessage.includes('pull request already exists')) {
core.warning(errorMessage);
}
Expand All @@ -29696,7 +29696,8 @@ async function run() {
}
}
catch (err) {
const errorMessage = err instanceof Error ? err.message : (typeof err === 'string' ? err : 'Caught an error during input parsing');
// eslint-disable-next-line no-console
const errorMessage = err instanceof Error ? err.message : typeof err === 'string' ? err : 'Caught an error during input parsing';
core.error(errorMessage);
core.setFailed(errorMessage);
}
Expand Down

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions tools/github-actions/get-npm-tag/packaged-action/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31804,7 +31804,7 @@ async function run() {
.pop();
const isLatest = latestVersion ? (0, semver_1.compare)(latestVersion, version) <= 0 : true;
const preRelease = (0, semver_1.prerelease)(version);
if (!preRelease || preRelease.length === 0) {
if (!preRelease || !preRelease.length) {
if (isPreRelease) {
core.setFailed(`No pre-release found for version ${version}`);
}
Expand All @@ -31819,7 +31819,7 @@ async function run() {
core.setOutput('tag', preRelease[0]);
}
catch (err) {
const errorMessage = err instanceof Error ? err.message : (typeof err === 'string' ? err : 'Caught an error during NPM tag calculation');
const errorMessage = err instanceof Error ? err.message : typeof err === 'string' ? err : 'Caught an error during NPM tag calculation';
core.setFailed(errorMessage);
}
}
Expand Down

Large diffs are not rendered by default.

Loading

0 comments on commit 3db3b68

Please sign in to comment.