Skip to content

Commit

Permalink
Merge pull request #22920 from jhipster/skip_ci-sonar
Browse files Browse the repository at this point in the history
rework sonar-project.properties
  • Loading branch information
DanielFran authored Jul 20, 2023
2 parents 0d09160 + b622d33 commit e5a9eca
Show file tree
Hide file tree
Showing 9 changed files with 121 additions and 76 deletions.
4 changes: 2 additions & 2 deletions generators/base/priorities.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -118,14 +118,14 @@ export const CUSTOM_PRIORITIES = [
{
priorityName: POST_WRITING,
queueName: POST_WRITING_QUEUE,
before: TRANSFORM,
before: PRE_CONFLICTS,
args: generator => generator.getArgsForPriority(POST_WRITING),
},
{
priorityName: PRE_CONFLICTS,
queueName: PRE_CONFLICTS_QUEUE,
args: generator => generator.getArgsForPriority(PRE_CONFLICTS),
before: CONFLICTS,
before: TRANSFORM,
},
{
priorityName: INSTALL,
Expand Down
14 changes: 8 additions & 6 deletions generators/bootstrap/generator.mts
Original file line number Diff line number Diff line change
Expand Up @@ -144,10 +144,7 @@ export default class BootstrapGenerator extends BaseGenerator {
*/
async commitSharedFs(stream = this.env.sharedFs.stream({ filter: isFilePending })) {
const { skipYoResolve } = this.options;
const { ignoreErrors } = this.options;

const prettierOptions = { packageJson: true, java: !this.jhipsterConfig.skipServer };
const prettierTransformOptions = { ignoreErrors: ignoreErrors || this.upgradeCommand, extensions: PRETTIER_EXTENSIONS };
const ignoreErrors = this.options.ignoreErrors || this.upgradeCommand;

const transformStreams = [
...(skipYoResolve ? [] : [createYoResolveTransform()]),
Expand All @@ -157,8 +154,13 @@ export default class BootstrapGenerator extends BaseGenerator {
...(this.skipPrettier
? []
: [
createESLintTransform.call(this, { ignoreErrors: ignoreErrors || this.upgradeCommand, extensions: 'ts,js' }),
createPrettierTransform(prettierOptions, this, prettierTransformOptions),
createESLintTransform.call(this, { ignoreErrors, extensions: 'ts,js' }),
createPrettierTransform.call(this, {
ignoreErrors,
prettierPackageJson: true,
prettierJava: !this.jhipsterConfig.skipServer,
extensions: PRETTIER_EXTENSIONS,
}),
]),
...(this.jhipsterConfig.autoCrlf ? [autoCrlfTransform(this.createGit())] : []),
createConflicterTransform(this.env.adapter, { ...(this.env as any).conflicterOptions, memFs: this.env.sharedFs }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,31 @@ import { passthrough } from 'p-transform';
import { isFileStateDeleted } from 'mem-fs-editor/state';
import prettier from 'prettier';
import prettierPluginJava from 'prettier-plugin-java';
import prettierPluginProperties from 'prettier-plugin-properties';
import prettierPluginPackagejson from 'prettier-plugin-packagejson';
import { Minimatch } from 'minimatch';
import type { MemFsEditorFile, VinylMemFsEditorFile } from 'mem-fs-editor';
import type CoreGenerator from '../../base-core/index.mjs';

const minimatch = new Minimatch('**/{.prettierrc**,.prettierignore}');
export const isPrettierConfigFile = file => minimatch.match(file.path);
export const isPrettierConfigFile = (file: MemFsEditorFile) => minimatch.match(file.path);

export const createPrettierTransform = function (options, generator, transformOptions = {}) {
if (typeof transformOptions === 'boolean') {
transformOptions = { ignoreErrors: transformOptions };
}
const { ignoreErrors = false, extensions } = transformOptions;
const minimatch = new Minimatch(`**/*.{${extensions}}`, { dot: true });
export const createPrettierTransform = function (
this: CoreGenerator,
options: {
ignoreErrors?: boolean;
extensions?: string;
prettierPackageJson?: boolean;
prettierJava?: boolean;
prettierProperties?: boolean;
prettierOptions?: prettier.Options;
} = {},
) {
const { ignoreErrors = false, extensions = '*', prettierPackageJson, prettierJava, prettierProperties, prettierOptions } = options;
const globExpression = extensions.includes(',') ? `**/*.{${extensions}}` : `**/*.${extensions}`;
const minimatch = new Minimatch(globExpression, { dot: true });

return passthrough(async file => {
return passthrough(async (file: VinylMemFsEditorFile) => {
if (!minimatch.match(file.path) || isFileStateDeleted(file)) {
return;
}
Expand All @@ -44,21 +55,25 @@ export const createPrettierTransform = function (options, generator, transformOp
let fileContent;
try {
const resolvedDestinationFileOptions = await prettier.resolveConfig(file.relative);
const prettierOptions = {
const fileOptions: prettier.Options = {
// Config from disk
...resolvedDestinationFileOptions,
plugins: [],
// for better errors
filepath: file.relative,
...prettierOptions,
};
if (options.packageJson) {
prettierOptions.plugins.push(prettierPluginPackagejson);
if (prettierPackageJson && file.path.endsWith('package.json')) {
fileOptions.plugins!.push(prettierPluginPackagejson);
}
if (options.java) {
prettierOptions.plugins.push(prettierPluginJava);
if (prettierJava && file.path.endsWith('.java')) {
fileOptions.plugins!.push(prettierPluginJava);
}
if (prettierProperties) {
fileOptions.plugins!.push(prettierPluginProperties);
}
fileContent = file.contents.toString('utf8');
const data = await prettier.format(fileContent, prettierOptions);
const data = await prettier.format(fileContent, fileOptions);
file.contents = Buffer.from(data);
} catch (error) {
let errorMessage;
Expand All @@ -73,7 +88,7 @@ At: ${fileContent
errorMessage = `Unknown prettier error: ${error}`;
}
if (ignoreErrors) {
generator.log.warn(errorMessage);
this?.log?.warn?.(errorMessage);
return;
}
throw new Error(errorMessage);
Expand Down
73 changes: 41 additions & 32 deletions generators/common/__snapshots__/generator.spec.mjs.snap
Original file line number Diff line number Diff line change
Expand Up @@ -276,40 +276,49 @@ To configure CI for your project, run the ci-cd sub-generator (\`jhipster ci-cd\
"stateCleared": "modified",
},
"sonar-project.properties": {
"contents": "sonar.projectKey=jhipster
sonar.projectName=jhipster generated by jhipster
# Typescript tests files must be inside sources and tests, othewise \`INFO: Test execution data ignored for 80 unknown files, including:\` is shown.
sonar.sources=src
sonar.tests=src
sonar.host.url=http://localhost:9001
sonar.test.inclusions=src/test/**/*.*, src/main/webapp/app/**/*.spec.ts
sonar.coverage.jacoco.xmlReportPaths=target/site/**/jacoco*.xml
sonar.java.codeCoveragePlugin=jacoco
sonar.junit.reportPaths=target/surefire-reports,target/failsafe-reports
sonar.testExecutionReportPaths=target/test-results/jest/TESTS-results-sonar.xml
sonar.javascript.lcov.reportPaths=target/test-results/lcov.info
sonar.sourceEncoding=UTF-8
sonar.exclusions=src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.js, target/classes/static/**/*.*
sonar.issue.ignore.multicriteria=S3437,S4502,S4684,S5145,UndocumentedApi
# Rule https://rules.sonarsource.com/java/RSPEC-3437 is ignored, as a JPA-managed field cannot be transient
sonar.issue.ignore.multicriteria.S3437.resourceKey=src/main/java/**/*
sonar.issue.ignore.multicriteria.S3437.ruleKey=squid:S3437
# Rule https://rules.sonarsource.com/java/RSPEC-4502 is ignored, as for JWT tokens we are not subject to CSRF attack
sonar.issue.ignore.multicriteria.S4502.resourceKey=src/main/java/**/*
sonar.issue.ignore.multicriteria.S4502.ruleKey=java:S4502
"contents": "sonar.projectKey = jhipster
sonar.projectName = jhipster generated by jhipster
# Typescript tests files must be inside sources and tests, othewise \`INFO: Test
# execution data ignored for 80 unknown files, including:\` is shown.
sonar.sources = src
sonar.tests = src
sonar.host.url = http://localhost:9001
sonar.test.inclusions = src/test/**/*.*, src/main/webapp/app/**/*.spec.ts
sonar.coverage.jacoco.xmlReportPaths = target/site/**/jacoco*.xml
sonar.java.codeCoveragePlugin = jacoco
sonar.junit.reportPaths = target/surefire-reports,target/failsafe-reports
sonar.testExecutionReportPaths = target/test-results/jest/TESTS-results-sonar.\\
xml
sonar.javascript.lcov.reportPaths = target/test-results/lcov.info
sonar.sourceEncoding = UTF-8
sonar.exclusions = src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.js, \\
target/classes/static/**/*.*
sonar.issue.ignore.multicriteria = S3437,S4502,S4684,S5145,UndocumentedApi
# Rule https://rules.sonarsource.com/java/RSPEC-3437 is ignored, as a
# JPA-managed field cannot be transient
sonar.issue.ignore.multicriteria.S3437.resourceKey = src/main/java/**/*
sonar.issue.ignore.multicriteria.S3437.ruleKey = squid:S3437
# Rule https://rules.sonarsource.com/java/RSPEC-4502 is ignored, as for JWT
# tokens we are not subject to CSRF attack
sonar.issue.ignore.multicriteria.S4502.resourceKey = src/main/java/**/*
sonar.issue.ignore.multicriteria.S4502.ruleKey = java:S4502
# Rule https://rules.sonarsource.com/java/RSPEC-4684
sonar.issue.ignore.multicriteria.S4684.resourceKey=src/main/java/**/*
sonar.issue.ignore.multicriteria.S4684.ruleKey=java:S4684
sonar.issue.ignore.multicriteria.S4684.resourceKey = src/main/java/**/*
sonar.issue.ignore.multicriteria.S4684.ruleKey = java:S4684
# Rule https://rules.sonarsource.com/java/RSPEC-5145 log filter is applied
sonar.issue.ignore.multicriteria.S5145.resourceKey=src/main/java/**/*
sonar.issue.ignore.multicriteria.S5145.ruleKey=javasecurity:S5145
# Rule https://rules.sonarsource.com/java/RSPEC-1176 is ignored, as we want to follow "clean code" guidelines and classes, methods and arguments names should be self-explanatory
sonar.issue.ignore.multicriteria.UndocumentedApi.resourceKey=src/main/java/**/*
sonar.issue.ignore.multicriteria.UndocumentedApi.ruleKey=squid:UndocumentedApi
sonar.issue.ignore.multicriteria.S5145.resourceKey = src/main/java/**/*
sonar.issue.ignore.multicriteria.S5145.ruleKey = javasecurity:S5145
# Rule https://rules.sonarsource.com/java/RSPEC-1176 is ignored, as we want to
# follow "clean code" guidelines and classes, methods and arguments names
# should be self-explanatory
sonar.issue.ignore.multicriteria.UndocumentedApi.resourceKey = \\
src/main/java/**/*
sonar.issue.ignore.multicriteria.UndocumentedApi.ruleKey = squid:UndocumentedApi
",
"stateCleared": "modified",
},
Expand Down
18 changes: 11 additions & 7 deletions generators/common/generator.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* limitations under the License.
*/
/* eslint-disable consistent-return */

import { isFilePending } from 'mem-fs-editor/state';
import BaseApplicationGenerator from '../base-application/index.mjs';

import { writeFiles, prettierConfigFiles } from './files.mjs';
Expand All @@ -31,12 +31,10 @@ import {
import { clientFrameworkTypes } from '../../jdl/jhipster/index.mjs';
import { GENERATOR_COMMON, GENERATOR_BOOTSTRAP_APPLICATION, GENERATOR_GIT } from '../generator-list.mjs';
import command from './command.mjs';
import { createPrettierTransform } from '../bootstrap/support/prettier-support.mjs';

const { REACT, ANGULAR } = clientFrameworkTypes;
/**
* @class
* @extends {BaseApplicationGenerator<import('../bootstrap-application-base/types.js').CommonClientServerApplication>}
*/

export default class CommonGenerator extends BaseApplicationGenerator {
async beforeQueue() {
this.loadStoredAppOptions();
Expand Down Expand Up @@ -158,7 +156,13 @@ export default class CommonGenerator extends BaseApplicationGenerator {
}

get postWriting() {
return {
return this.asPostWritingTaskGroup({
formatSonarProperties() {
this.queueTransformStream(createPrettierTransform.call(this, { extensions: 'properties', prettierProperties: true }), {
name: 'prettifying sonar-project.properties',
streamOptions: { filter: file => isFilePending(file) && file.path.endsWith('sonar-project.properties') },
});
},
addCommitHookDependencies({ application }) {
if (application.skipCommitHook) return;
this.packageJson.merge({
Expand All @@ -171,7 +175,7 @@ export default class CommonGenerator extends BaseApplicationGenerator {
},
});
},
};
});
}

get [BaseApplicationGenerator.POST_WRITING]() {
Expand Down
11 changes: 4 additions & 7 deletions generators/common/generator.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import lodash from 'lodash';
import { basename, dirname, join } from 'path';
import { fileURLToPath } from 'url';

import { defaultHelpers as helpers, basicHelpers } from '../../test/support/helpers.mjs';
import { defaultHelpers as helpers, basicHelpers, runResult } from '../../test/support/helpers.mjs';
import { shouldSupportFeatures, testBlueprintSupport } from '../../test/support/tests.mjs';
import Generator from './index.mjs';
import { checkEnforcements } from '../../test/support/index.mjs';
Expand All @@ -47,20 +47,17 @@ describe(`generator - ${generator}`, () => {

describe('with', () => {
describe('default config', () => {
let runResult;
before(async () => {
runResult = await helpers.run(generatorFile).withJHipsterConfig().withMockedGenerators(mockedGenerators);
await helpers.run(generatorFile).withJHipsterConfig().withMockedGenerators(mockedGenerators);
});

it('should succeed', () => {
expect(runResult.getSnapshot()).toMatchSnapshot();
});
});
describe('Custom prettier', () => {
let runResult;

before(async () => {
runResult = await basicHelpers
await basicHelpers
.run(generatorFile)
.withJHipsterConfig({
prettierTabWidth: 10,
Expand All @@ -72,7 +69,7 @@ describe(`generator - ${generator}`, () => {
runResult.assertFileContent('.prettierrc', /tabWidth: 10/);
});

it('uses custom prettier formatting to java file', () => {
it('uses custom prettier formatting to js file', () => {
runResult.assertFileContent('.lintstagedrc.js', / {10}'{/);
});
});
Expand Down
22 changes: 15 additions & 7 deletions generators/common/templates/sonar-project.properties.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,23 @@ sonar.javascript.lcov.reportPaths=<%_ if (buildToolMaven) { _%>target<%_ } else
sonar.sourceEncoding=UTF-8
sonar.exclusions=<%= clientSrcDir %>content/**/*.*, <%= clientSrcDir %>i18n/*.js, <%= clientDistDir %>**/*.*
sonar.issue.ignore.multicriteria=<%_ if (!skipServer) { _%>S3437,<% if (authenticationTypeJwt) { %>S4502,<% } %>S4684,S5145,UndocumentedApi<%_ } _%>
<%_ if (!skipServer) { _%>
sonar.issue.ignore.multicriteria=\
<%_ if (gatlingTests) { _%>
S2187,\
<%_ } _%>
S3437,\
<%_ if (authenticationTypeJwt) { _%>
S4502,\
<%_ } _%>
S4684,S5145,UndocumentedApi
<%_ if (gatlingTests) { _%>
# Rule https://rules.sonarsource.com/java/RSPEC-2187 is ignored, gatling tests are not supported by sonar
sonar.issue.ignore.multicriteria.S2187.resourceKey=<%= TEST_DIR %>java/gatling/**/*
sonar.issue.ignore.multicriteria.S2187.ruleKey=java:S2187
<%_ } _%>
# Rule https://rules.sonarsource.com/java/RSPEC-3437 is ignored, as a JPA-managed field cannot be transient
sonar.issue.ignore.multicriteria.S3437.resourceKey=<%= MAIN_DIR %>java/**/*
sonar.issue.ignore.multicriteria.S3437.ruleKey=squid:S3437
Expand All @@ -58,9 +71,4 @@ sonar.issue.ignore.multicriteria.S5145.ruleKey=javasecurity:S5145
# Rule https://rules.sonarsource.com/java/RSPEC-1176 is ignored, as we want to follow "clean code" guidelines and classes, methods and arguments names should be self-explanatory
sonar.issue.ignore.multicriteria.UndocumentedApi.resourceKey=<%= MAIN_DIR %>java/**/*
sonar.issue.ignore.multicriteria.UndocumentedApi.ruleKey=squid:UndocumentedApi
<%_ if (gatlingTests) { _%>
# Rule https://rules.sonarsource.com/java/RSPEC-2187 is ignored, gatling tests are not supported by sonar
sonar.issue.ignore.multicriteria.S2187.resourceKey=<%= TEST_DIR %>java/gatling/**/*
sonar.issue.ignore.multicriteria.S2187.ruleKey=java:S2187
<%_ } _%>
<%_ } _%>
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@
"prettier": "3.0.0",
"prettier-plugin-java": "2.2.0",
"prettier-plugin-packagejson": "2.4.5",
"prettier-plugin-properties": "0.2.0",
"progress": "2.0.3",
"randexp": "0.5.3",
"run-async": "3.0.0",
Expand Down

0 comments on commit e5a9eca

Please sign in to comment.