Skip to content

Commit 02bec13

Browse files
committed
address review: escape newline/carriage return, add unit tests
Also escape \n and \r in the module specifier, since an unescaped newline would produce an unterminated string literal in the generated file. Adds two test cases covering quote/backslash and newline/ carriage-return escaping in insertImport's output.
1 parent cb4a373 commit 02bec13

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

packages/schematics/angular/utility/ast-utils.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,11 @@ export function insertImport(
7777
// if there are no imports or 'use strict' statement, insert import at beginning of file
7878
const insertAtBeginning = allImports.length === 0 && useStrict.length === 0;
7979
const separator = insertAtBeginning ? '' : `;${eol}`;
80-
const escapedFileName = fileName.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
80+
const escapedFileName = fileName
81+
.replace(/\\/g, '\\\\')
82+
.replace(/'/g, "\\'")
83+
.replace(/\n/g, '\\n')
84+
.replace(/\r/g, '\\r');
8185
const toInsert =
8286
`${separator}import ${open}${importExpression}${close}` +
8387
` from '${escapedFileName}'${insertAtBeginning ? `;${eol}` : ''}`;

packages/schematics/angular/utility/ast-utils_spec.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -768,6 +768,24 @@ describe('ast utils', () => {
768768

769769
expect(result).toBe(fileContent);
770770
});
771+
772+
it('should escape single quotes and backslashes in the module specifier', () => {
773+
const fileContent = '';
774+
const source = getTsSource(filePath, fileContent);
775+
const change = insertImport(source, filePath, 'Component', "foo'bar\\baz");
776+
const result = applyChanges(filePath, fileContent, [change]).trim();
777+
778+
expect(result).toBe("import { Component } from 'foo\\'bar\\\\baz';");
779+
});
780+
781+
it('should escape newlines and carriage returns in the module specifier', () => {
782+
const fileContent = '';
783+
const source = getTsSource(filePath, fileContent);
784+
const change = insertImport(source, filePath, 'Component', 'foo\nbar\rbaz');
785+
const result = applyChanges(filePath, fileContent, [change]).trim();
786+
787+
expect(result).toBe(`import { Component } from 'foo\\nbar\\rbaz';`);
788+
});
771789
});
772790

773791
describe('hasTopLevelIdentifier', () => {

0 commit comments

Comments
 (0)