Skip to content

Commit 0dc46e2

Browse files
authored
String.raw should be used to avoid escaping (#32052)
1 parent 2e690a0 commit 0dc46e2

File tree

29 files changed

+70
-67
lines changed

29 files changed

+70
-67
lines changed

generators/angular/generator.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ export default class AngularGenerator extends AngularApplicationGenerator {
284284
fieldDefaultValue = defaultValue;
285285
}
286286

287-
fieldDefaultValue = String(fieldDefaultValue).replace(/'/g, "\\'");
287+
fieldDefaultValue = String(fieldDefaultValue).replace(/'/g, String.raw`\'`);
288288

289289
if (fieldTypeCharSequence) {
290290
returnValue = `'${fieldDefaultValue}'`;

generators/angular/support/needles.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ export const addIconImport = ({ icon }: { icon: string }) => {
123123
const iconImport = `fa${upperFirstCamelCase(icon)}`;
124124
return createNeedleCallback({
125125
needle: 'jhipster-needle-add-icon-import',
126-
contentToCheck: new RegExp(`\\b${iconImport}\\b`),
126+
contentToCheck: new RegExp(String.raw`\b${iconImport}\b`),
127127
contentToAdd: (content, { indentPrefix }) =>
128128
content.replace(
129129
/(\r?\n)(\s*)\/\/ jhipster-needle-add-icon-import/g,

generators/angular/support/translate-angular.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ function replaceJSTranslation(getWebappTranslation: GetWebappTranslationCallback
8585
return replaceTranslationKeysWithText(
8686
getWebappTranslation,
8787
content,
88-
`${jsKey}\\s?:\\s?['|"]([a-zA-Z0-9.\\-_]+\\.[a-zA-Z0-9.\\-_]+)['|"]`,
88+
String.raw`${jsKey}\s?:\s?['|"]([a-zA-Z0-9.\-_]+\.[a-zA-Z0-9.\-_]+)['|"]`,
8989
{
9090
escape: (translation, match) => translation.replaceAll(match[0].slice(-1), `\\${match[0].slice(-1)}`),
9191
},
@@ -301,7 +301,7 @@ export const createTranslationReplacer = (getWebappTranslation: GetWebappTransla
301301
});
302302
return replacer(getWebappTranslation, opts, optsReplacer);
303303
},
304-
{ prefixPattern: '>\\s*', suffixPattern: '\\s*<' },
304+
{ prefixPattern: String.raw`>\s*`, suffixPattern: String.raw`\s*<` },
305305
);
306306
}
307307
return function replaceAngularTranslations(content: string, filePath: string) {

generators/base-application/support/prepare-field.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -230,9 +230,9 @@ function generateFakeDataForField(
230230
if (data !== undefined) {
231231
// eslint-disable-next-line no-template-curly-in-string
232232
if (type === 'ts' && ![BOOLEAN, INTEGER, LONG, FLOAT, '${floatType}', DOUBLE, BIG_DECIMAL].includes(field.fieldType)) {
233-
data = `'${typeof data === 'string' ? data.replace(/\\/g, '\\\\').replace(/'/g, "\\'") : data}'`;
233+
data = `'${typeof data === 'string' ? data.replace(/\\/g, '\\\\').replace(/'/g, String.raw`\'`) : data}'`;
234234
} else if (type === 'csv' && field.fieldValidate && field.fieldValidateRules?.includes(PATTERN)) {
235-
data = `"${typeof data === 'string' ? data.replace(/"/g, '\\"') : data}"`;
235+
data = `"${typeof data === 'string' ? data.replace(/"/g, String.raw`\"`) : data}"`;
236236
}
237237
}
238238

generators/base-core/support/needles.spec.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,19 +32,19 @@ import {
3232
describe('needles - support', () => {
3333
describe('convertToPrettierExpressions', () => {
3434
it('should add whitespaces pattern to spaces', () => {
35-
expect(convertToPrettierExpressions('1 2 3')).toBe('1[\\s\\n]*2[\\s\\n]*3');
35+
expect(convertToPrettierExpressions('1 2 3')).toBe(String.raw`1[\s\n]*2[\s\n]*3`);
3636
});
3737
it('should add whitespaces pattern to before >', () => {
38-
expect(convertToPrettierExpressions('>')).toBe(',?\\n?[\\s]*>');
38+
expect(convertToPrettierExpressions('>')).toBe(String.raw`,?\n?[\s]*>`);
3939
});
4040
it('should add whitespaces pattern to after <', () => {
41-
expect(convertToPrettierExpressions('<')).toBe('<\\n?[\\s]*');
41+
expect(convertToPrettierExpressions('<')).toBe(String.raw`<\n?[\s]*`);
4242
});
4343
it('should add whitespaces pattern to before )', () => {
44-
expect(convertToPrettierExpressions('\\)')).toBe(',?\\n?[\\s]*\\)');
44+
expect(convertToPrettierExpressions(String.raw`\)`)).toBe(String.raw`,?\n?[\s]*\)`);
4545
});
4646
it('should add whitespaces pattern to after (', () => {
47-
expect(convertToPrettierExpressions('\\(')).toBe('\\(\\n?[\\s]*');
47+
expect(convertToPrettierExpressions(String.raw`\(`)).toBe(String.raw`\(\n?[\s]*`);
4848
});
4949
});
5050
describe('checkContentIn', () => {

generators/base-core/support/needles.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -96,22 +96,23 @@ type NeedleContentInsertion = Pick<NeedleInsertion, 'needle' | 'autoIndent'> & {
9696
*/
9797
export const convertToPrettierExpressions = (str: string): string =>
9898
str
99-
.replace(/(<|\\\()(?! )/g, '$1\\n?[\\s]*')
100-
.replace(/(?! )(>|\\\))/g, ',?\\n?[\\s]*$1')
101-
.replace(/\s+/g, '[\\s\\n]*');
99+
.replace(/(<|\\\()(?! )/g, String.raw`$1\n?[\s]*`)
100+
.replace(/(?! )(>|\\\))/g, String.raw`,?\n?[\s]*$1`)
101+
.replace(/\s+/g, String.raw`[\s\n]*`);
102102

103103
const isArrayOfContentToAdd = (value: unknown): value is ContentToAdd[] => {
104104
return Array.isArray(value) && value.every(item => typeof item === 'object' && 'content' in item);
105105
};
106106

107-
export const createNeedleRegexp = (needle: string): RegExp => new RegExp(`(?://|<!--|\\{?/\\*|#) ${needle}(?: [^$\\n]*)?(?:$|\\n)`, 'g');
107+
export const createNeedleRegexp = (needle: string): RegExp =>
108+
new RegExp(String.raw`(?://|<!--|\{?/\*|#) ${needle}(?: [^$\n]*)?(?:$|\n)`, 'g');
108109

109110
type NeedleLinePosition = {
110111
start: number;
111112
end: number;
112113
};
113114

114-
export const getNeedlesPositions = (content: string, needle = 'jhipster-needle-(?:[-\\w]*)'): NeedleLinePosition[] => {
115+
export const getNeedlesPositions = (content: string, needle = String.raw`jhipster-needle-(?:[-\w]*)`): NeedleLinePosition[] => {
115116
const regexp = createNeedleRegexp(needle);
116117
const positions: NeedleLinePosition[] = [];
117118
let match: RegExpExecArray | null;
@@ -142,7 +143,7 @@ export const checkContentIn = (contentToCheck: string | RegExp, content: string,
142143
? convertToPrettierExpressions(escapeRegExp(contentToCheck))
143144
: contentToCheck
144145
.split('\n')
145-
.map(line => `\\s*${escapeRegExp(line)}`)
146+
.map(line => String.raw`\s*${escapeRegExp(line)}`)
146147
.join('\n');
147148
re = new RegExp(pattern);
148149
} else {

generators/cypress/generator.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -295,12 +295,12 @@ export default class CypressGenerator extends BaseApplicationGenerator<CypressEn
295295
{},
296296
);
297297
(source as ClientSource).addWebpackConfig?.({
298-
config: `targetOptions.configuration === 'instrumenter'
298+
config: String.raw`targetOptions.configuration === 'instrumenter'
299299
? {
300300
module: {
301301
rules: [
302302
{
303-
test: /\\.(js|ts)$/,
303+
test: /\.(js|ts)$/,
304304
use: [
305305
{
306306
loader: 'babel-loader',
@@ -311,7 +311,7 @@ export default class CypressGenerator extends BaseApplicationGenerator<CypressEn
311311
],
312312
enforce: 'post',
313313
include: path.resolve(__dirname, '../${CLIENT_MAIN_SRC_DIR}'),
314-
exclude: [/\\.(e2e|spec)\\.ts$/, /node_modules/, /(ngfactory|ngstyle)\\.js/],
314+
exclude: [/\.(e2e|spec)\.ts$/, /node_modules/, /(ngfactory|ngstyle)\.js/],
315315
},
316316
],
317317
},

generators/java/support/add-java-annotation.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ const addJavaAnnotationToContent = (content: string, annotationDef: JavaAnnotati
120120
if (packageName) {
121121
content = addJavaImport(content, `${packageName}.${annotation}`);
122122
}
123-
const annotationWithParametersMatches = content.match(new RegExp(`@${annotation}\\((?<oldParameters>[^)]*)\\)`));
123+
const annotationWithParametersMatches = content.match(new RegExp(String.raw`@${annotation}\((?<oldParameters>[^)]*)\)`));
124124
let annotationToAdd: string | undefined;
125125
if (parameters) {
126126
const oldParameters = annotationWithParametersMatches?.groups?.oldParameters?.trim?.();
@@ -160,7 +160,7 @@ const addJavaAnnotationToContent = (content: string, annotationDef: JavaAnnotati
160160
annotationToAdd = annotation;
161161
}
162162
if (annotationWithParametersMatches) {
163-
content = content.replace(new RegExp(`@${annotation}\\((?<oldParameters>[^)]*)\\)`), `@${annotationToAdd}`);
163+
content = content.replace(new RegExp(String.raw`@${annotation}\((?<oldParameters>[^)]*)\)`), `@${annotationToAdd}`);
164164
} else if (!new RegExp(escapeRegExp(`\n@${annotationToAdd}\n`)).test(content)) {
165165
// add the annotation before class or interface
166166
content = content.replace(/\n([a-w ]*(class|@?interface|enum) )/, `\n@${annotationToAdd}\n$1`);

generators/java/support/doc.spec.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ describe('generator - server - support - doc', () => {
2828
});
2929
describe('when passing a comment with newlines', () => {
3030
it('formats the comment correctly with line breaks', () => {
31-
const comment = 'This is the first line.\\nAnd this is the second.';
31+
const comment = String.raw`This is the first line.\nAnd this is the second.`;
3232
expect(formatDocAsJavaDoc(comment, 1)).toBe(' /**\n * This is the first line.\n * And this is the second.\n */');
3333
});
3434
});
@@ -63,7 +63,7 @@ describe('generator - server - support - doc', () => {
6363
});
6464
describe('when having quotes', () => {
6565
it('formats the text to make the string valid', () => {
66-
expect(formatDocAsApiDescription('JHipster is "the" best')).toEqual('JHipster is \\"the\\" best');
66+
expect(formatDocAsApiDescription('JHipster is "the" best')).toEqual(String.raw`JHipster is \"the\" best`);
6767
});
6868
});
6969
});

generators/java/support/doc.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import { formatDocAsSingleLine } from '../../base-application/support/doc.ts';
2020

2121
const escapeDoubleQuotes = (text: string): string => {
2222
if (text.includes('"')) {
23-
return text.replace(/"/g, '\\"');
23+
return text.replace(/"/g, String.raw`\"`);
2424
}
2525
return text;
2626
};
@@ -41,7 +41,7 @@ export const formatDocAsJavaDoc = (text: string, indentSize = 0): string => {
4141
}
4242
text = escapeDoubleQuotes(text);
4343
const indent = ' '.repeat(indentSize);
44-
const rows = ['/**', ...text.split('\\n').map(row => ` * ${row}`), ' */'].map(row => `${indent}${row}`);
44+
const rows = ['/**', ...text.split(String.raw`\n`).map(row => ` * ${row}`), ' */'].map(row => `${indent}${row}`);
4545
return rows.join('\n');
4646
};
4747

0 commit comments

Comments
 (0)