feat(core): added encoding param in Tree.read() (#5668)

feat(core): added encoding param in Tree.read()
This commit is contained in:
Phillip Barta 2021-05-18 03:03:04 +02:00 committed by GitHub
parent f111027a8e
commit 52e3083a19
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
58 changed files with 250 additions and 215 deletions

View File

@ -63,7 +63,7 @@ function updateWorkspaceJsonToMatchFormatVersion(host: Tree) {
try { try {
const workspaceJson = JSON.parse( const workspaceJson = JSON.parse(
stripJsonComments(host.read(path).toString()) stripJsonComments(host.read(path, 'utf-8'))
); );
const reformatted = reformattedWorkspaceJsonOrNull(workspaceJson); const reformatted = reformattedWorkspaceJsonOrNull(workspaceJson);
if (reformatted) { if (reformatted) {

View File

@ -18,13 +18,13 @@ describe('generateFiles', () => {
it('should copy files from a directory into a tree', () => { it('should copy files from a directory into a tree', () => {
expect(tree.exists('file.txt')).toBeTruthy(); expect(tree.exists('file.txt')).toBeTruthy();
expect(tree.read('file.txt').toString()).toMatchSnapshot(); expect(tree.read('file.txt', 'utf-8')).toMatchSnapshot();
}); });
it('should copy files from a directory into the tree', () => { it('should copy files from a directory into the tree', () => {
expect(tree.exists('directory/file-in-directory.txt')).toBeTruthy(); expect(tree.exists('directory/file-in-directory.txt')).toBeTruthy();
expect( expect(
tree.read('directory/file-in-directory.txt').toString() tree.read('directory/file-in-directory.txt', 'utf-8')
).toMatchSnapshot(); ).toMatchSnapshot();
}); });
@ -34,7 +34,7 @@ describe('generateFiles', () => {
).not.toBeTruthy(); ).not.toBeTruthy();
expect(tree.exists('file-with-template-suffix.txt')).toBeTruthy(); expect(tree.exists('file-with-template-suffix.txt')).toBeTruthy();
expect( expect(
tree.read('file-with-template-suffix.txt').toString() tree.read('file-with-template-suffix.txt', 'utf-8')
).toMatchSnapshot(); ).toMatchSnapshot();
}); });
@ -42,7 +42,7 @@ describe('generateFiles', () => {
expect(tree.exists('file-with-property-foo-__foo__.txt')).not.toBeTruthy(); expect(tree.exists('file-with-property-foo-__foo__.txt')).not.toBeTruthy();
expect(tree.exists('file-with-property-foo-bar.txt')).toBeTruthy(); expect(tree.exists('file-with-property-foo-bar.txt')).toBeTruthy();
expect( expect(
tree.read('file-with-property-foo-bar.txt').toString() tree.read('file-with-property-foo-bar.txt', 'utf-8')
).toMatchSnapshot(); ).toMatchSnapshot();
}); });
@ -54,7 +54,7 @@ describe('generateFiles', () => {
tree.exists('directory-foo-bar/file-in-directory-foo-bar.txt') tree.exists('directory-foo-bar/file-in-directory-foo-bar.txt')
).toBeTruthy(); ).toBeTruthy();
expect( expect(
tree.read('directory-foo-bar/file-in-directory-foo-bar.txt').toString() tree.read('directory-foo-bar/file-in-directory-foo-bar.txt', 'utf-8')
).toMatchSnapshot(); ).toMatchSnapshot();
}); });

View File

@ -2,7 +2,7 @@ import { Tree } from '@nrwl/tao/src/shared/tree';
import { join } from 'path'; import { join } from 'path';
import ignore from 'ignore'; import ignore, { Ignore } from 'ignore';
/** /**
* Utility to act on all files in a tree that are not ignored by git. * Utility to act on all files in a tree that are not ignored by git.
@ -12,10 +12,10 @@ export function visitNotIgnoredFiles(
dirPath: string = tree.root, dirPath: string = tree.root,
visitor: (path: string) => void visitor: (path: string) => void
) { ) {
let ig; let ig: Ignore;
if (tree.exists('.gitignore')) { if (tree.exists('.gitignore')) {
ig = ignore(); ig = ignore();
ig.add(tree.read('.gitignore').toString()); ig.add(tree.read('.gitignore', 'utf-8'));
} }
if (dirPath !== '' && ig?.ignores(dirPath)) { if (dirPath !== '' && ig?.ignores(dirPath)) {
return; return;

View File

@ -24,9 +24,10 @@ export function installPackagesTask(
cwd: string = '', cwd: string = '',
packageManager?: PackageManager packageManager?: PackageManager
) { ) {
const packageJsonValue = host const packageJsonValue = host.read(
.read(joinPathFragments(cwd, 'package.json')) joinPathFragments(cwd, 'package.json'),
.toString(); 'utf-8'
);
if ( if (
host host
.listChanges() .listChanges()
@ -35,9 +36,10 @@ export function installPackagesTask(
) { ) {
// Don't install again if install was already executed with package.json // Don't install again if install was already executed with package.json
if (storedPackageJsonValue != packageJsonValue || alwaysRun) { if (storedPackageJsonValue != packageJsonValue || alwaysRun) {
storedPackageJsonValue = host storedPackageJsonValue = host.read(
.read(joinPathFragments(cwd, 'package.json')) joinPathFragments(cwd, 'package.json'),
.toString(); 'utf-8'
);
const pm = packageManager || detectPackageManager(cwd); const pm = packageManager || detectPackageManager(cwd);
const pmc = getPackageManagerCommand(pm); const pmc = getPackageManagerCommand(pm);
execSync(pmc.install, { execSync(pmc.install, {

View File

@ -1,6 +1,9 @@
import { join, relative } from 'path'; import { join, relative } from 'path';
import { FileChange } from '@nrwl/tao/src/shared/tree'; import type { FileChange, Tree } from '@nrwl/tao/src/shared/tree';
import { Generator, GeneratorCallback } from '@nrwl/tao/src/shared/workspace'; import type {
Generator,
GeneratorCallback,
} from '@nrwl/tao/src/shared/workspace';
class RunCallbackTask { class RunCallbackTask {
constructor(private callback: GeneratorCallback) {} constructor(private callback: GeneratorCallback) {}
@ -69,7 +72,7 @@ const actionToFileChangeMap = {
d: 'DELETE', d: 'DELETE',
}; };
class DevkitTreeFromAngularDevkitTree { class DevkitTreeFromAngularDevkitTree implements Tree {
constructor(private tree, private _root: string) {} constructor(private tree, private _root: string) {}
get root(): string { get root(): string {
@ -132,10 +135,18 @@ class DevkitTreeFromAngularDevkitTree {
return relative(this.root, join(this.root, path)); return relative(this.root, join(this.root, path));
} }
read(filePath: string): Buffer | null { read(filePath: string): Buffer;
return this.tree.read(filePath); read(filePath: string, encoding: BufferEncoding): string;
read(filePath: string, encoding?: BufferEncoding) {
return encoding
? this.tree.read(filePath).toString(encoding)
: this.tree.read(filePath);
} }
/* read(filePath: string): Buffer | null {
return this.tree.read(filePath);
}*/
rename(from: string, to: string): void { rename(from: string, to: string): void {
this.tree.rename(from, to); this.tree.rename(from, to);
} }

View File

@ -11,7 +11,7 @@ export function readJson<T = any>(host: Tree, path: string) {
if (!host.exists(path)) { if (!host.exists(path)) {
throw new Error(`Cannot find ${path}`); throw new Error(`Cannot find ${path}`);
} }
const contents = stripJsonComments(host.read(path).toString('utf-8')); const contents = stripJsonComments(host.read(path, 'utf-8'));
try { try {
return JSON.parse(contents) as T; return JSON.parse(contents) as T;
} catch (e) { } catch (e) {

View File

@ -208,7 +208,7 @@ describe('app', () => {
style: 'css', style: 'css',
}); });
expect(tree.read('apps/my-app/jest.config.js').toString('utf-8')).toContain( expect(tree.read('apps/my-app/jest.config.js', 'utf-8')).toContain(
`moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],` `moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],`
); );
}); });
@ -219,7 +219,7 @@ describe('app', () => {
style: 'css', style: 'css',
}); });
expect(tree.read('apps/my-app/jest.config.js').toString('utf-8')).toContain( expect(tree.read('apps/my-app/jest.config.js', 'utf-8')).toContain(
`'^(?!.*\\\\.(js|jsx|ts|tsx|css|json)$)': '@nrwl/react/plugins/jest'` `'^(?!.*\\\\.(js|jsx|ts|tsx|css|json)$)': '@nrwl/react/plugins/jest'`
); );
}); });
@ -281,7 +281,7 @@ describe('app', () => {
it('should generate an index component', async () => { it('should generate an index component', async () => {
await applicationGenerator(tree, { name: 'myApp', style: 'css' }); await applicationGenerator(tree, { name: 'myApp', style: 'css' });
const appContent = tree.read('apps/my-app/src/pages/index.tsx').toString(); const appContent = tree.read('apps/my-app/src/pages/index.tsx', 'utf-8');
expect(appContent).not.toMatch(/extends Component/); expect(appContent).not.toMatch(/extends Component/);
}); });

View File

@ -3,7 +3,7 @@ import { NormalizedSchema } from './normalize-options';
export function addGitIgnoreEntry(host: Tree, options: NormalizedSchema) { export function addGitIgnoreEntry(host: Tree, options: NormalizedSchema) {
if (host.exists('.gitignore')) { if (host.exists('.gitignore')) {
let content = host.read('.gitignore').toString('utf-8'); let content = host.read('.gitignore', 'utf-8');
content = `${content}\n/apps/${options.projectName}/node_modules\n/apps/${options.projectName}/public\n/apps/${options.projectName}/.cache\n`; content = `${content}\n/apps/${options.projectName}/node_modules\n/apps/${options.projectName}/public\n/apps/${options.projectName}/.cache\n`;
host.write('.gitignore', content); host.write('.gitignore', content);
} else { } else {

View File

@ -3,7 +3,7 @@ import { NormalizedSchema } from './normalize-options';
export function addPrettierIgnoreEntry(host: Tree, options: NormalizedSchema) { export function addPrettierIgnoreEntry(host: Tree, options: NormalizedSchema) {
if (host.exists('.prettierignore')) { if (host.exists('.prettierignore')) {
let content = host.read('.prettierignore').toString('utf-8'); let content = host.read('.prettierignore', 'utf-8');
content = `${content}\n/apps/${options.projectName}/node_modules\n/apps/${options.projectName}/public\n/apps/${options.projectName}/.cache\n`; content = `${content}\n/apps/${options.projectName}/node_modules\n/apps/${options.projectName}/public\n/apps/${options.projectName}/.cache\n`;
host.write('.prettierignore', content); host.write('.prettierignore', content);
} else { } else {

View File

@ -8,7 +8,7 @@ export function updateJestConfig(host: Tree, options: NormalizedSchema) {
} }
const configPath = `${options.projectRoot}/jest.config.js`; const configPath = `${options.projectRoot}/jest.config.js`;
const originalContent = host.read(configPath).toString(); const originalContent = host.read(configPath, 'utf-8');
const content = updateJestConfigContent(originalContent); const content = updateJestConfigContent(originalContent);
host.write(configPath, content); host.write(configPath, content);
} }

View File

@ -13,7 +13,7 @@ describe('jest', () => {
jestInitGenerator(tree, {}); jestInitGenerator(tree, {});
expect(tree.exists('jest.config.js')).toBeTruthy(); expect(tree.exists('jest.config.js')).toBeTruthy();
expect(tree.read('jest.config.js').toString()).toMatchInlineSnapshot(` expect(tree.read('jest.config.js', 'utf-8')).toMatchInlineSnapshot(`
"module.exports = { "module.exports = {
projects: [] projects: []
};" };"
@ -23,7 +23,7 @@ describe('jest', () => {
it('should not override existing files', async () => { it('should not override existing files', async () => {
tree.write('jest.config.js', `test`); tree.write('jest.config.js', `test`);
jestInitGenerator(tree, {}); jestInitGenerator(tree, {});
expect(tree.read('jest.config.js').toString()).toEqual('test'); expect(tree.read('jest.config.js', 'utf-8')).toEqual('test');
}); });
it('should add dependencies', async () => { it('should add dependencies', async () => {

View File

@ -80,7 +80,7 @@ describe('jestProject', () => {
...defaultOptions, ...defaultOptions,
project: 'lib1', project: 'lib1',
} as JestProjectSchema); } as JestProjectSchema);
expect(tree.read('libs/lib1/jest.config.js').toString()).toMatchSnapshot(); expect(tree.read('libs/lib1/jest.config.js', 'utf-8')).toMatchSnapshot();
}); });
it('should add a project reference in the root jest.config.js', async () => { it('should add a project reference in the root jest.config.js', async () => {
@ -130,7 +130,7 @@ describe('jestProject', () => {
project: 'lib1', project: 'lib1',
} as JestProjectSchema); } as JestProjectSchema);
expect(tree.exists('src/test-setup.ts')).toBeFalsy(); expect(tree.exists('src/test-setup.ts')).toBeFalsy();
expect(tree.read('libs/lib1/jest.config.js').toString()).not.toContain( expect(tree.read('libs/lib1/jest.config.js', 'utf-8')).not.toContain(
`setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],` `setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],`
); );
}); });
@ -141,7 +141,7 @@ describe('jestProject', () => {
project: 'lib1', project: 'lib1',
setupFile: 'web-components', setupFile: 'web-components',
} as JestProjectSchema); } as JestProjectSchema);
expect(tree.read('libs/lib1/jest.config.js').toString()).toContain( expect(tree.read('libs/lib1/jest.config.js', 'utf-8')).toContain(
`setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],` `setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],`
); );
}); });
@ -153,7 +153,7 @@ describe('jestProject', () => {
setupFile: 'angular', setupFile: 'angular',
} as JestProjectSchema); } as JestProjectSchema);
const jestConfig = tree.read('libs/lib1/jest.config.js').toString(); const jestConfig = tree.read('libs/lib1/jest.config.js', 'utf-8');
expect(jestConfig).toContain( expect(jestConfig).toContain(
`setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],` `setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],`
); );
@ -219,7 +219,7 @@ describe('jestProject', () => {
project: 'lib1', project: 'lib1',
skipSerializers: true, skipSerializers: true,
} as JestProjectSchema); } as JestProjectSchema);
const jestConfig = tree.read('libs/lib1/jest.config.js').toString(); const jestConfig = tree.read('libs/lib1/jest.config.js', 'utf-8');
expect(jestConfig).not.toContain(` expect(jestConfig).not.toContain(`
snapshotSerializers: [ snapshotSerializers: [
'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js, 'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js,
@ -288,9 +288,7 @@ describe('jestProject', () => {
tsConfig: '<rootDir>/tsconfig.spec.json', tsConfig: '<rootDir>/tsconfig.spec.json',
}, },
}); });
expect( expect(tree.read('libs/lib1/jest.config.js', 'utf-8')).toMatchSnapshot();
tree.read('libs/lib1/jest.config.js').toString()
).toMatchSnapshot();
}); });
it('should generate proper jest.transform when babelJest and supportTsx is true', async () => { it('should generate proper jest.transform when babelJest and supportTsx is true', async () => {
@ -300,9 +298,7 @@ describe('jestProject', () => {
babelJest: true, babelJest: true,
supportTsx: true, supportTsx: true,
} as JestProjectSchema); } as JestProjectSchema);
expect( expect(tree.read('libs/lib1/jest.config.js', 'utf-8')).toMatchSnapshot();
tree.read('libs/lib1/jest.config.js').toString()
).toMatchSnapshot();
}); });
}); });
}); });

View File

@ -68,7 +68,7 @@ function updateJestConfig(tree: Tree) {
const { sourceRoot } = readProjectConfiguration(tree, projectName); const { sourceRoot } = readProjectConfiguration(tree, projectName);
const setupTestPath = join(sourceRoot, 'test-setup.ts'); const setupTestPath = join(sourceRoot, 'test-setup.ts');
if (tree.exists(setupTestPath)) { if (tree.exists(setupTestPath)) {
const contents = tree.read(setupTestPath).toString(); const contents = tree.read(setupTestPath, 'utf-8');
tree.write( tree.write(
setupTestPath, setupTestPath,
contents.replace( contents.replace(

View File

@ -53,7 +53,7 @@ export function addOrUpdateProperty(
const propertyName = properties.shift(); const propertyName = properties.shift();
const propertyAssignment = findPropertyAssignment(object, propertyName); const propertyAssignment = findPropertyAssignment(object, propertyName);
const originalContents = tree.read(path).toString(); const originalContents = tree.read(path, 'utf-8');
if (propertyAssignment) { if (propertyAssignment) {
if ( if (
@ -230,6 +230,6 @@ export function jestConfigObject(
host: Tree, host: Tree,
path: string path: string
): Partial<Config.InitialOptions> & { [index: string]: any } { ): Partial<Config.InitialOptions> & { [index: string]: any } {
const jestConfigAst = jestConfigObjectAst(host.read(path).toString('utf-8')); const jestConfigAst = jestConfigObjectAst(host.read(path, 'utf-8'));
return getJsonObject(jestConfigAst.getText()); return getJsonObject(jestConfigAst.getText());
} }

View File

@ -22,7 +22,7 @@ export function addPropertyToJestConfig(
throw new Error(`Cannot find '${path}' in your workspace.`); throw new Error(`Cannot find '${path}' in your workspace.`);
} }
try { try {
const configObject = jestConfigObjectAst(host.read(path).toString('utf-8')); const configObject = jestConfigObjectAst(host.read(path, 'utf-8'));
const properties = propertyName.split('.'); const properties = propertyName.split('.');
addOrUpdateProperty( addOrUpdateProperty(
host, host,
@ -56,14 +56,14 @@ export function removePropertyFromJestConfig(
throw new Error(`Cannot find '${path}' in your workspace.`); throw new Error(`Cannot find '${path}' in your workspace.`);
} }
try { try {
const configObject = jestConfigObjectAst(host.read(path).toString('utf-8')); const configObject = jestConfigObjectAst(host.read(path, 'utf-8'));
const propertyAssignment = removeProperty( const propertyAssignment = removeProperty(
configObject, configObject,
propertyName.split('.') propertyName.split('.')
); );
if (propertyAssignment) { if (propertyAssignment) {
const file = host.read(path).toString('utf-8'); const file = host.read(path, 'utf-8');
const commaNeeded = file[propertyAssignment.end] === ','; const commaNeeded = file[propertyAssignment.end] === ',';
const updatedFile = applyChangesToString(file, [ const updatedFile = applyChangesToString(file, [
{ {

View File

@ -18,7 +18,7 @@ describe('@nrwl/linter:init', () => {
linter: Linter.EsLint, linter: Linter.EsLint,
}); });
expect(tree.read('.eslintrc.json').toString()).toMatchSnapshot(); expect(tree.read('.eslintrc.json', 'utf-8')).toMatchSnapshot();
}); });
}); });
@ -28,7 +28,7 @@ describe('@nrwl/linter:init', () => {
linter: Linter.TsLint, linter: Linter.TsLint,
}); });
expect(tree.read('tslint.json').toString()).toMatchSnapshot(); expect(tree.read('tslint.json', 'utf-8')).toMatchSnapshot();
}); });
}); });
}); });

View File

@ -34,7 +34,7 @@ describe('@nrwl/linter:lint-project', () => {
}); });
expect( expect(
tree.read('libs/test-lib/.eslintrc.json').toString() tree.read('libs/test-lib/.eslintrc.json', 'utf-8')
).toMatchSnapshot(); ).toMatchSnapshot();
}); });
@ -70,7 +70,7 @@ describe('@nrwl/linter:lint-project', () => {
}); });
expect( expect(
tree.read('libs/test-lib/tslint.json').toString() tree.read('libs/test-lib/tslint.json', 'utf-8')
).toMatchSnapshot(); ).toMatchSnapshot();
}); });

View File

@ -154,13 +154,13 @@ describe('convertTSLintDisableCommentsForProject', () => {
convertTSLintDisableCommentsForProject(tree, projectName); convertTSLintDisableCommentsForProject(tree, projectName);
expect( expect(
tree.read(join(projectRoot, 'top-level-file.ts')).toString() tree.read(join(projectRoot, 'top-level-file.ts'), 'utf-8')
).toMatchSnapshot(); ).toMatchSnapshot();
expect( expect(
tree.read(join(projectRoot, 'single-level-nested/file.ts')).toString() tree.read(join(projectRoot, 'single-level-nested/file.ts'), 'utf-8')
).toMatchSnapshot(); ).toMatchSnapshot();
expect( expect(
tree.read(join(projectRoot, 'multi-level/nested/file.ts')).toString() tree.read(join(projectRoot, 'multi-level/nested/file.ts'), 'utf-8')
).toMatchSnapshot(); ).toMatchSnapshot();
}); });
}); });

View File

@ -215,9 +215,9 @@ export function convertTSLintDisableCommentsForProject(
if (!filePath.endsWith('.ts')) { if (!filePath.endsWith('.ts')) {
return; return;
} }
const fileContent = tree.read(filePath)!.toString('utf-8'); const fileContent = tree.read(filePath, 'utf-8');
// Avoid updating files if we don't have to // Avoid updating files if we don't have to
if (!likelyContainsTSLintComment(fileContent)) { if (!fileContent || !likelyContainsTSLintComment(fileContent)) {
return; return;
} }
const updatedFileContent = convertFileComments({ fileContent, filePath }); const updatedFileContent = convertFileComments({ fileContent, filePath });

View File

@ -63,7 +63,7 @@ describe('app', () => {
expect(tree.exists('apps/my-app/pages/index.module.scss')).toBeTruthy(); expect(tree.exists('apps/my-app/pages/index.module.scss')).toBeTruthy();
expect(tree.exists('apps/my-app/pages/styles.css')).toBeTruthy(); expect(tree.exists('apps/my-app/pages/styles.css')).toBeTruthy();
const indexContent = tree.read('apps/my-app/pages/index.tsx').toString(); const indexContent = tree.read('apps/my-app/pages/index.tsx', 'utf-8');
expect(indexContent).toContain( expect(indexContent).toContain(
`import styles from './index.module.scss'` `import styles from './index.module.scss'`
); );
@ -80,7 +80,7 @@ describe('app', () => {
expect(tree.exists('apps/my-app/pages/index.module.less')).toBeTruthy(); expect(tree.exists('apps/my-app/pages/index.module.less')).toBeTruthy();
expect(tree.exists('apps/my-app/pages/styles.less')).toBeTruthy(); expect(tree.exists('apps/my-app/pages/styles.less')).toBeTruthy();
const indexContent = tree.read('apps/my-app/pages/index.tsx').toString(); const indexContent = tree.read('apps/my-app/pages/index.tsx', 'utf-8');
expect(indexContent).toContain( expect(indexContent).toContain(
`import styles from './index.module.less'` `import styles from './index.module.less'`
); );
@ -97,7 +97,7 @@ describe('app', () => {
expect(tree.exists('apps/my-app/pages/index.module.styl')).toBeTruthy(); expect(tree.exists('apps/my-app/pages/index.module.styl')).toBeTruthy();
expect(tree.exists('apps/my-app/pages/styles.styl')).toBeTruthy(); expect(tree.exists('apps/my-app/pages/styles.styl')).toBeTruthy();
const indexContent = tree.read('apps/my-app/pages/index.tsx').toString(); const indexContent = tree.read('apps/my-app/pages/index.tsx', 'utf-8');
expect(indexContent).toContain( expect(indexContent).toContain(
`import styles from './index.module.styl'` `import styles from './index.module.styl'`
); );
@ -116,7 +116,7 @@ describe('app', () => {
).toBeFalsy(); ).toBeFalsy();
expect(tree.exists('apps/my-app/pages/styles.css')).toBeTruthy(); expect(tree.exists('apps/my-app/pages/styles.css')).toBeTruthy();
const indexContent = tree.read('apps/my-app/pages/index.tsx').toString(); const indexContent = tree.read('apps/my-app/pages/index.tsx', 'utf-8');
expect(indexContent).not.toContain(`import styles from './index.module`); expect(indexContent).not.toContain(`import styles from './index.module`);
expect(indexContent).toContain(`import styled from 'styled-components'`); expect(indexContent).toContain(`import styled from 'styled-components'`);
}); });
@ -134,7 +134,7 @@ describe('app', () => {
).toBeFalsy(); ).toBeFalsy();
expect(tree.exists('apps/my-app/pages/styles.css')).toBeTruthy(); expect(tree.exists('apps/my-app/pages/styles.css')).toBeTruthy();
const indexContent = tree.read('apps/my-app/pages/index.tsx').toString(); const indexContent = tree.read('apps/my-app/pages/index.tsx', 'utf-8');
expect(indexContent).not.toContain(`import styles from './index.module`); expect(indexContent).not.toContain(`import styles from './index.module`);
expect(indexContent).toContain(`import styled from '@emotion/styled'`); expect(indexContent).toContain(`import styled from '@emotion/styled'`);
}); });
@ -147,7 +147,7 @@ describe('app', () => {
style: 'styled-jsx', style: 'styled-jsx',
}); });
const indexContent = tree.read('apps/my-app/pages/index.tsx').toString(); const indexContent = tree.read('apps/my-app/pages/index.tsx', 'utf-8');
expect(indexContent).toMatch(/<style jsx>{`.page {}`}<\/style>/); expect(indexContent).toMatch(/<style jsx>{`.page {}`}<\/style>/);
expect( expect(
@ -165,7 +165,7 @@ describe('app', () => {
it('should setup jest with tsx support', async () => { it('should setup jest with tsx support', async () => {
await applicationGenerator(tree, { name: 'my-app', style: 'css' }); await applicationGenerator(tree, { name: 'my-app', style: 'css' });
expect(tree.read('apps/my-app/jest.config.js').toString('utf-8')).toContain( expect(tree.read('apps/my-app/jest.config.js', 'utf-8')).toContain(
`moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],` `moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],`
); );
}); });
@ -173,7 +173,7 @@ describe('app', () => {
it('should setup jest with SVGR support', async () => { it('should setup jest with SVGR support', async () => {
await applicationGenerator(tree, { name: 'my-app', style: 'css' }); await applicationGenerator(tree, { name: 'my-app', style: 'css' });
expect(tree.read('apps/my-app/jest.config.js').toString('utf-8')).toContain( expect(tree.read('apps/my-app/jest.config.js', 'utf-8')).toContain(
`'^(?!.*\\\\.(js|jsx|ts|tsx|css|json)$)': '@nrwl/react/plugins/jest'` `'^(?!.*\\\\.(js|jsx|ts|tsx|css|json)$)': '@nrwl/react/plugins/jest'`
); );
}); });
@ -244,7 +244,7 @@ describe('app', () => {
it('should generate functional components by default', async () => { it('should generate functional components by default', async () => {
await applicationGenerator(tree, { name: 'myApp', style: 'css' }); await applicationGenerator(tree, { name: 'myApp', style: 'css' });
const appContent = tree.read('apps/my-app/pages/index.tsx').toString(); const appContent = tree.read('apps/my-app/pages/index.tsx', 'utf-8');
expect(appContent).not.toMatch(/extends Component/); expect(appContent).not.toMatch(/extends Component/);
}); });

View File

@ -7,7 +7,7 @@ export function updateJestConfig(host: Tree, options: NormalizedSchema) {
} }
const configPath = `${options.appProjectRoot}/jest.config.js`; const configPath = `${options.appProjectRoot}/jest.config.js`;
const originalContent = host.read(configPath).toString(); const originalContent = host.read(configPath, 'utf-8');
const content = originalContent.replace( const content = originalContent.replace(
'transform: {', 'transform: {',
"transform: {\n '^(?!.*\\\\.(js|jsx|ts|tsx|css|json)$)': '@nrwl/react/plugins/jest'," "transform: {\n '^(?!.*\\\\.(js|jsx|ts|tsx|css|json)$)': '@nrwl/react/plugins/jest',"

View File

@ -330,7 +330,7 @@ describe('app', () => {
babelJest: true, babelJest: true,
} as Schema); } as Schema);
expect(tree.read(`apps/my-node-app/jest.config.js`).toString()) expect(tree.read(`apps/my-node-app/jest.config.js`, 'utf-8'))
.toMatchInlineSnapshot(` .toMatchInlineSnapshot(`
"module.exports = { "module.exports = {
displayName: 'my-node-app', displayName: 'my-node-app',

View File

@ -387,7 +387,7 @@ describe('lib', () => {
babelJest: true, babelJest: true,
} as Schema); } as Schema);
expect(tree.read(`libs/my-lib/jest.config.js`).toString()) expect(tree.read(`libs/my-lib/jest.config.js`, 'utf-8'))
.toMatchInlineSnapshot(` .toMatchInlineSnapshot(`
"module.exports = { "module.exports = {
displayName: 'my-lib', displayName: 'my-lib',

View File

@ -1,4 +1,3 @@
import * as stripJsonComments from 'strip-json-comments';
import { import {
getProjects, getProjects,
readJson, readJson,
@ -85,27 +84,20 @@ describe('app', () => {
tsconfig.compilerOptions.noFallthroughCasesInSwitch tsconfig.compilerOptions.noFallthroughCasesInSwitch
).not.toBeDefined(); ).not.toBeDefined();
const tsconfigApp = JSON.parse( const tsconfigApp = readJson(appTree, 'apps/my-app/tsconfig.app.json');
stripJsonComments(
appTree.read('apps/my-app/tsconfig.app.json').toString()
)
);
expect(tsconfigApp.compilerOptions.outDir).toEqual('../../dist/out-tsc'); expect(tsconfigApp.compilerOptions.outDir).toEqual('../../dist/out-tsc');
expect(tsconfigApp.extends).toEqual('./tsconfig.json'); expect(tsconfigApp.extends).toEqual('./tsconfig.json');
const eslintJson = JSON.parse( const eslintJson = readJson(appTree, 'apps/my-app/.eslintrc.json');
stripJsonComments(appTree.read('apps/my-app/.eslintrc.json').toString())
);
expect(eslintJson.extends).toEqual([ expect(eslintJson.extends).toEqual([
'plugin:@nrwl/nx/react', 'plugin:@nrwl/nx/react',
'../../.eslintrc.json', '../../.eslintrc.json',
]); ]);
expect(appTree.exists('apps/my-app-e2e/cypress.json')).toBeTruthy(); expect(appTree.exists('apps/my-app-e2e/cypress.json')).toBeTruthy();
const tsconfigE2E = JSON.parse( const tsconfigE2E = readJson(
stripJsonComments( appTree,
appTree.read('apps/my-app-e2e/tsconfig.e2e.json').toString() 'apps/my-app-e2e/tsconfig.e2e.json'
)
); );
expect(tsconfigE2E.compilerOptions.outDir).toEqual('../../dist/out-tsc'); expect(tsconfigE2E.compilerOptions.outDir).toEqual('../../dist/out-tsc');
expect(tsconfigE2E.extends).toEqual('./tsconfig.json'); expect(tsconfigE2E.extends).toEqual('./tsconfig.json');
@ -147,8 +139,7 @@ describe('app', () => {
it('should generate files', async () => { it('should generate files', async () => {
const hasJsonValue = ({ path, expectedValue, lookupFn }) => { const hasJsonValue = ({ path, expectedValue, lookupFn }) => {
const content = appTree.read(path).toString(); const config = readJson(appTree, path);
const config = JSON.parse(stripJsonComments(content));
expect(lookupFn(config)).toEqual(expectedValue); expect(lookupFn(config)).toEqual(expectedValue);
}; };
@ -207,7 +198,7 @@ describe('app', () => {
}); });
expect(() => { expect(() => {
JSON.parse(appTree.read(`apps/my-app/.babelrc`).toString()); readJson(appTree, `apps/my-app/.babelrc`);
}).not.toThrow(); }).not.toThrow();
} }
); );

View File

@ -8,7 +8,6 @@ import {
import { import {
joinPathFragments, joinPathFragments,
Tree, Tree,
StringInsertion,
applyChangesToString, applyChangesToString,
addDependenciesToPackageJson, addDependenciesToPackageJson,
} from '@nrwl/devkit'; } from '@nrwl/devkit';
@ -22,7 +21,7 @@ export function addRouting(host: Tree, options: NormalizedSchema) {
options.appProjectRoot, options.appProjectRoot,
maybeJs(options, `src/app/${options.fileName}.tsx`) maybeJs(options, `src/app/${options.fileName}.tsx`)
); );
const appFileContent = host.read(appPath).toString('utf-8'); const appFileContent = host.read(appPath, 'utf-8');
const appSource = ts.createSourceFile( const appSource = ts.createSourceFile(
appPath, appPath,
appFileContent, appFileContent,

View File

@ -22,7 +22,7 @@ export function updateJestConfig(host: Tree, options: NormalizedSchema) {
}); });
const configPath = `${options.appProjectRoot}/jest.config.js`; const configPath = `${options.appProjectRoot}/jest.config.js`;
const originalContent = host.read(configPath).toString(); const originalContent = host.read(configPath, 'utf-8');
const content = updateJestConfigContent(originalContent); const content = updateJestConfigContent(originalContent);
host.write(configPath, content); host.write(configPath, content);
} }

View File

@ -102,7 +102,7 @@ describe('react:component-cypress-spec', () => {
it('should properly set up the spec', () => { it('should properly set up the spec', () => {
expect( expect(
formatFile`${appTree.read(cypressStorySpecFilePath).toString()}` formatFile`${appTree.read(cypressStorySpecFilePath, 'utf-8')}`
) )
.toContain(formatFile`describe('test-ui-lib: Test component', () => { .toContain(formatFile`describe('test-ui-lib: Test component', () => {
beforeEach(() => cy.visit('/iframe.html?id=test--primary&knob-name=&knob-displayAge=false')); beforeEach(() => cy.visit('/iframe.html?id=test--primary&knob-name=&knob-displayAge=false'));
@ -130,9 +130,8 @@ describe('react:component-cypress-spec', () => {
}); });
it('should properly set up the spec', () => { it('should properly set up the spec', () => {
expect( expect(formatFile`${appTree.read(cypressStorySpecFilePath, 'utf-8')}`)
formatFile`${appTree.read(cypressStorySpecFilePath).toString()}` .toContain(formatFile`describe('test-ui-lib: Test component', () => {
).toContain(formatFile`describe('test-ui-lib: Test component', () => {
beforeEach(() => cy.visit('/iframe.html?id=test--primary')); beforeEach(() => cy.visit('/iframe.html?id=test--primary'));
it('should render the component', () => { it('should render the component', () => {

View File

@ -60,14 +60,14 @@ export function createComponentSpecFile(
.replace('.jsx', '') .replace('.jsx', '')
.replace('.js', ''); .replace('.js', '');
const contents = tree.read(componentFilePath); const contents = tree.read(componentFilePath, 'utf-8');
if (!contents) { if (contents === null) {
throw new Error(`Failed to read ${componentFilePath}`); throw new Error(`Failed to read ${componentFilePath}`);
} }
const sourceFile = ts.createSourceFile( const sourceFile = ts.createSourceFile(
componentFilePath, componentFilePath,
contents.toString(), contents,
ts.ScriptTarget.Latest, ts.ScriptTarget.Latest,
true true
); );

View File

@ -50,7 +50,7 @@ describe('react:component-story', () => {
}); });
it('should properly set up the story', () => { it('should properly set up the story', () => {
expect(formatFile`${appTree.read(storyFilePath).toString()}`) expect(formatFile`${appTree.read(storyFilePath, 'utf-8')}`)
.toContain(formatFile` .toContain(formatFile`
import React from 'react'; import React from 'react';
import { TestUiLib, TestUiLibProps } from './test-ui-lib'; import { TestUiLib, TestUiLibProps } from './test-ui-lib';
@ -104,7 +104,7 @@ describe('react:component-story', () => {
}); });
it('should properly set up the story', () => { it('should properly set up the story', () => {
expect(formatFile`${appTree.read(storyFilePathPlain).toString()}`) expect(formatFile`${appTree.read(storyFilePathPlain, 'utf-8')}`)
.toContain(formatFile` .toContain(formatFile`
import React from 'react'; import React from 'react';
import { Test } from './test-ui-libplain'; import { Test } from './test-ui-libplain';
@ -151,7 +151,7 @@ describe('react:component-story', () => {
}); });
it('should create a story without knobs', () => { it('should create a story without knobs', () => {
expect(formatFile`${appTree.read(storyFilePath).toString()}`) expect(formatFile`${appTree.read(storyFilePath, 'utf-8')}`)
.toContain(formatFile` .toContain(formatFile`
import React from 'react'; import React from 'react';
import { Test } from './test-ui-lib'; import { Test } from './test-ui-lib';
@ -200,7 +200,7 @@ describe('react:component-story', () => {
}); });
it('should setup knobs based on the component props', () => { it('should setup knobs based on the component props', () => {
expect(formatFile`${appTree.read(storyFilePath).toString()}`) expect(formatFile`${appTree.read(storyFilePath, 'utf-8')}`)
.toContain(formatFile` .toContain(formatFile`
import { text, boolean } from '@storybook/addon-knobs'; import { text, boolean } from '@storybook/addon-knobs';
import React from 'react'; import React from 'react';
@ -357,7 +357,7 @@ describe('react:component-story', () => {
}); });
it('should properly setup the knobs based on the component props', () => { it('should properly setup the knobs based on the component props', () => {
expect(formatFile`${appTree.read(storyFilePath).toString()}`) expect(formatFile`${appTree.read(storyFilePath, 'utf-8')}`)
.toContain(formatFile` .toContain(formatFile`
import { text, boolean } from '@storybook/addon-knobs'; import { text, boolean } from '@storybook/addon-knobs';
import React from 'react'; import React from 'react';
@ -392,7 +392,7 @@ describe('react:component-story', () => {
}); });
it('should properly set up the story', () => { it('should properly set up the story', () => {
expect(formatFile`${appTree.read(storyFilePath).toString()}`) expect(formatFile`${appTree.read(storyFilePath, 'utf-8')}`)
.toContain(formatFile` .toContain(formatFile`
import React from 'react'; import React from 'react';
import { TestUiLib, TestUiLibProps } from './test-ui-lib'; import { TestUiLib, TestUiLibProps } from './test-ui-lib';

View File

@ -72,14 +72,14 @@ export function createComponentStoriesFile(
const name = componentFileName; const name = componentFileName;
const contents = host.read(componentFilePath); const contents = host.read(componentFilePath, 'utf-8');
if (!contents) { if (contents === null) {
throw new Error(`Failed to read ${componentFilePath}`); throw new Error(`Failed to read ${componentFilePath}`);
} }
const sourceFile = ts.createSourceFile( const sourceFile = ts.createSourceFile(
componentFilePath, componentFilePath,
contents.toString(), contents,
ts.ScriptTarget.Latest, ts.ScriptTarget.Latest,
true true
); );

View File

@ -97,7 +97,7 @@ describe('component', () => {
export: true, export: true,
}); });
const indexContent = appTree.read('libs/my-lib/src/index.ts').toString(); const indexContent = appTree.read('libs/my-lib/src/index.ts', 'utf-8');
expect(indexContent).toMatch(/lib\/hello/); expect(indexContent).toMatch(/lib\/hello/);
}); });
@ -110,7 +110,7 @@ describe('component', () => {
export: true, export: true,
}); });
const indexContent = appTree.read('libs/my-lib/src/index.ts').toString(); const indexContent = appTree.read('libs/my-lib/src/index.ts', 'utf-8');
expect(indexContent).not.toMatch(/lib\/hello/); expect(indexContent).not.toMatch(/lib\/hello/);
}); });

View File

@ -111,9 +111,8 @@ function addExportsToBarrel(host: Tree, options: NormalizedSchema) {
options.projectSourceRoot, options.projectSourceRoot,
options.js ? 'index.js' : 'index.ts' options.js ? 'index.js' : 'index.ts'
); );
const buffer = host.read(indexFilePath); const indexSource = host.read(indexFilePath, 'utf-8');
if (!!buffer) { if (indexSource !== null) {
const indexSource = buffer.toString('utf-8');
const indexSourceFile = ts.createSourceFile( const indexSourceFile = ts.createSourceFile(
indexFilePath, indexFilePath,
indexSource, indexSource,

View File

@ -294,7 +294,7 @@ describe('lib', () => {
appTree.exists('libs/my-lib/src/lib/my-lib.module.styl') appTree.exists('libs/my-lib/src/lib/my-lib.module.styl')
).toBeFalsy(); ).toBeFalsy();
const content = appTree.read('libs/my-lib/src/lib/my-lib.tsx').toString(); const content = appTree.read('libs/my-lib/src/lib/my-lib.tsx', 'utf-8');
expect(content).not.toContain('styled-components'); expect(content).not.toContain('styled-components');
expect(content).not.toContain('<StyledApp>'); expect(content).not.toContain('<StyledApp>');
expect(content).not.toContain('@emotion/styled'); expect(content).not.toContain('@emotion/styled');
@ -361,8 +361,8 @@ describe('lib', () => {
appProject: 'my-app', appProject: 'my-app',
}); });
const appSource = appTree.read('apps/my-app/src/app/app.tsx').toString(); const appSource = appTree.read('apps/my-app/src/app/app.tsx', 'utf-8');
const mainSource = appTree.read('apps/my-app/src/main.tsx').toString(); const mainSource = appTree.read('apps/my-app/src/main.tsx', 'utf-8');
expect(mainSource).toContain('react-router-dom'); expect(mainSource).toContain('react-router-dom');
expect(mainSource).toContain('<BrowserRouter>'); expect(mainSource).toContain('<BrowserRouter>');
@ -387,8 +387,8 @@ describe('lib', () => {
appProject: 'my-app', appProject: 'my-app',
}); });
const appSource = appTree.read('apps/my-app/src/app/app.tsx').toString(); const appSource = appTree.read('apps/my-app/src/app/app.tsx', 'utf-8');
const mainSource = appTree.read('apps/my-app/src/main.tsx').toString(); const mainSource = appTree.read('apps/my-app/src/main.tsx', 'utf-8');
expect(mainSource).toContain('react-router-dom'); expect(mainSource).toContain('react-router-dom');
expect(mainSource).toContain('<BrowserRouter>'); expect(mainSource).toContain('<BrowserRouter>');
@ -621,7 +621,7 @@ describe('lib', () => {
}); });
expect(() => { expect(() => {
JSON.parse(appTree.read(`libs/my-lib/.babelrc`).toString()); readJson(appTree, `libs/my-lib/.babelrc`);
}).not.toThrow(); }).not.toThrow();
} }
); );

View File

@ -363,7 +363,7 @@ function readComponent(
throw new Error(`Cannot find ${path}`); throw new Error(`Cannot find ${path}`);
} }
const content = host.read(path).toString('utf-8'); const content = host.read(path, 'utf-8');
const source = ts.createSourceFile( const source = ts.createSourceFile(
path, path,

View File

@ -71,7 +71,7 @@ describe('redux', () => {
appProject: 'my-app', appProject: 'my-app',
}); });
const main = appTree.read('/apps/my-app/src/main.tsx').toString(); const main = appTree.read('/apps/my-app/src/main.tsx', 'utf-8');
expect(main).toContain('@reduxjs/toolkit'); expect(main).toContain('@reduxjs/toolkit');
expect(main).toContain('configureStore'); expect(main).toContain('configureStore');
expect(main).toContain('[THIRD_SLICE_FEATURE_KEY]: thirdSliceReducer,'); expect(main).toContain('[THIRD_SLICE_FEATURE_KEY]: thirdSliceReducer,');

View File

@ -67,9 +67,8 @@ function addExportsToBarrel(host: Tree, options: NormalizedSchema) {
options.js ? 'index.js' : 'index.ts' options.js ? 'index.js' : 'index.ts'
); );
const buffer = host.read(indexFilePath); const indexSource = host.read(indexFilePath, 'utf-8');
if (!!buffer) { if (indexSource !== null) {
const indexSource = buffer.toString('utf-8');
const indexSourceFile = ts.createSourceFile( const indexSourceFile = ts.createSourceFile(
indexFilePath, indexFilePath,
indexSource, indexSource,
@ -93,7 +92,7 @@ function addStoreConfiguration(host: Tree, options: NormalizedSchema) {
return; return;
} }
const mainSource = host.read(options.appMainFilePath).toString(); const mainSource = host.read(options.appMainFilePath, 'utf-8');
if (!mainSource.includes('redux')) { if (!mainSource.includes('redux')) {
const mainSourceFile = ts.createSourceFile( const mainSourceFile = ts.createSourceFile(
options.appMainFilePath, options.appMainFilePath,
@ -114,7 +113,7 @@ function updateReducerConfiguration(host: Tree, options: NormalizedSchema) {
return; return;
} }
const mainSource = host.read(options.appMainFilePath).toString(); const mainSource = host.read(options.appMainFilePath, 'utf-8');
const mainSourceFile = ts.createSourceFile( const mainSourceFile = ts.createSourceFile(
options.appMainFilePath, options.appMainFilePath,
mainSource, mainSource,

View File

@ -40,14 +40,14 @@ function containsComponentDeclaration(
tree: Tree, tree: Tree,
componentPath: string componentPath: string
): boolean { ): boolean {
const contents = tree.read(componentPath); const contents = tree.read(componentPath, 'utf-8');
if (!contents) { if (contents === null) {
throw new Error(`Failed to read ${componentPath}`); throw new Error(`Failed to read ${componentPath}`);
} }
const sourceFile = ts.createSourceFile( const sourceFile = ts.createSourceFile(
componentPath, componentPath,
contents.toString(), contents,
ts.ScriptTarget.Latest, ts.ScriptTarget.Latest,
true true
); );

View File

@ -97,7 +97,7 @@ describe('@nrwl/storybook:configuration', () => {
uiFramework: '@storybook/angular', uiFramework: '@storybook/angular',
}); });
expect(tree.read('.storybook/main.js').toString()).toEqual(newContents); expect(tree.read('.storybook/main.js', 'utf-8')).toEqual(newContents);
}); });
it('should update workspace file', async () => { it('should update workspace file', async () => {

View File

@ -629,7 +629,7 @@ function convertEventTypeToHandleMultipleConfigNames(
let isNewFormat = true; let isNewFormat = true;
try { try {
isNewFormat = isNewFormat =
JSON.parse(host.read(actualConfigName).toString()).version === 2; JSON.parse(host.read(actualConfigName, 'utf-8')).version === 2;
} catch (e) {} } catch (e) {}
if (content && isNewFormat) { if (content && isNewFormat) {

View File

@ -6,7 +6,7 @@ import { FileChange, FsTree, flushChanges } from './tree';
describe('tree', () => { describe('tree', () => {
describe('FsTree', () => { describe('FsTree', () => {
let dir; let dir: string;
let tree: FsTree; let tree: FsTree;
beforeEach(() => { beforeEach(() => {
dir = dirSync().name; dir = dirSync().name;
@ -32,14 +32,40 @@ describe('tree', () => {
expect(tree.listChanges()).toEqual([]); expect(tree.listChanges()).toEqual([]);
}); });
it('should be able to read and write files', () => { it('should be able to read and write files with Buffers', () => {
expect(tree.read('parent/parent-file.txt').toString()).toEqual( expect(tree.read('parent/parent-file.txt')).toEqual(
Buffer.from('parent content')
);
tree.write('parent/parent-file.txt', Buffer.from('new content'));
expect(tree.read('parent/parent-file.txt')).toEqual(
Buffer.from('new content')
);
expect(s(tree.listChanges())).toEqual([
{
path: 'parent/parent-file.txt',
type: 'UPDATE',
content: 'new content',
},
]);
flushChanges(dir, tree.listChanges());
expect(
readFileSync(path.join(dir, 'parent/parent-file.txt'), 'utf-8')
).toEqual('new content');
});
it('should be able to read and write files with encodings and strings', () => {
expect(tree.read('parent/parent-file.txt', 'utf-8')).toEqual(
'parent content' 'parent content'
); );
tree.write('parent/parent-file.txt', 'new content'); tree.write('parent/parent-file.txt', 'new content');
expect(tree.read('parent/parent-file.txt').toString()).toEqual( expect(tree.read('parent/parent-file.txt', 'utf-8')).toEqual(
'new content' 'new content'
); );
@ -54,7 +80,7 @@ describe('tree', () => {
flushChanges(dir, tree.listChanges()); flushChanges(dir, tree.listChanges());
expect( expect(
readFileSync(path.join(dir, 'parent/parent-file.txt')).toString() readFileSync(path.join(dir, 'parent/parent-file.txt'), 'utf-8')
).toEqual('new content'); ).toEqual('new content');
}); });
@ -75,12 +101,12 @@ describe('tree', () => {
tree.write('parent/new-parent-file.txt', 'new parent content'); tree.write('parent/new-parent-file.txt', 'new parent content');
tree.write('parent/new-child/new-child-file.txt', 'new child content'); tree.write('parent/new-child/new-child-file.txt', 'new child content');
expect(tree.read('parent/new-parent-file.txt').toString()).toEqual( expect(tree.read('parent/new-parent-file.txt', 'utf-8')).toEqual(
'new parent content' 'new parent content'
); );
expect( expect(tree.read('parent/new-child/new-child-file.txt', 'utf-8')).toEqual(
tree.read('parent/new-child/new-child-file.txt').toString() 'new child content'
).toEqual('new child content'); );
expect(s(tree.listChanges())).toEqual([ expect(s(tree.listChanges())).toEqual([
{ {
@ -98,12 +124,13 @@ describe('tree', () => {
flushChanges(dir, tree.listChanges()); flushChanges(dir, tree.listChanges());
expect( expect(
readFileSync(path.join(dir, 'parent/new-parent-file.txt')).toString() readFileSync(path.join(dir, 'parent/new-parent-file.txt'), 'utf-8')
).toEqual('new parent content'); ).toEqual('new parent content');
expect( expect(
readFileSync( readFileSync(
path.join(dir, 'parent/new-child/new-child-file.txt') path.join(dir, 'parent/new-child/new-child-file.txt'),
).toString() 'utf-8'
)
).toEqual('new child content'); ).toEqual('new child content');
}); });
@ -112,35 +139,35 @@ describe('tree', () => {
tree.write('/dir/file2', 'File 2 Contents'); tree.write('/dir/file2', 'File 2 Contents');
tree.write('./dir/file3', 'File 3 Contents'); tree.write('./dir/file3', 'File 3 Contents');
expect(tree.read('dir/file1').toString()).toEqual('File 1 Contents'); expect(tree.read('dir/file1', 'utf-8')).toEqual('File 1 Contents');
expect(tree.read('/dir/file1').toString()).toEqual('File 1 Contents'); expect(tree.read('/dir/file1', 'utf-8')).toEqual('File 1 Contents');
expect(tree.read('./dir/file1').toString()).toEqual('File 1 Contents'); expect(tree.read('./dir/file1', 'utf-8')).toEqual('File 1 Contents');
expect(tree.read('dir/file2').toString()).toEqual('File 2 Contents'); expect(tree.read('dir/file2', 'utf-8')).toEqual('File 2 Contents');
expect(tree.read('/dir/file2').toString()).toEqual('File 2 Contents'); expect(tree.read('/dir/file2', 'utf-8')).toEqual('File 2 Contents');
expect(tree.read('./dir/file2').toString()).toEqual('File 2 Contents'); expect(tree.read('./dir/file2', 'utf-8')).toEqual('File 2 Contents');
expect(tree.read('dir/file3').toString()).toEqual('File 3 Contents'); expect(tree.read('dir/file3', 'utf-8')).toEqual('File 3 Contents');
expect(tree.read('/dir/file3').toString()).toEqual('File 3 Contents'); expect(tree.read('/dir/file3', 'utf-8')).toEqual('File 3 Contents');
expect(tree.read('./dir/file3').toString()).toEqual('File 3 Contents'); expect(tree.read('./dir/file3', 'utf-8')).toEqual('File 3 Contents');
tree.rename('dir/file1', 'dir/file-a'); tree.rename('dir/file1', 'dir/file-a');
expect(tree.read('dir/file-a').toString()).toEqual('File 1 Contents'); expect(tree.read('dir/file-a', 'utf-8')).toEqual('File 1 Contents');
expect(tree.read('/dir/file-a').toString()).toEqual('File 1 Contents'); expect(tree.read('/dir/file-a', 'utf-8')).toEqual('File 1 Contents');
expect(tree.read('./dir/file-a').toString()).toEqual('File 1 Contents'); expect(tree.read('./dir/file-a', 'utf-8')).toEqual('File 1 Contents');
tree.rename('/dir/file2', '/dir/file-b'); tree.rename('/dir/file2', '/dir/file-b');
expect(tree.read('dir/file-b').toString()).toEqual('File 2 Contents'); expect(tree.read('dir/file-b', 'utf-8')).toEqual('File 2 Contents');
expect(tree.read('/dir/file-b').toString()).toEqual('File 2 Contents'); expect(tree.read('/dir/file-b', 'utf-8')).toEqual('File 2 Contents');
expect(tree.read('./dir/file-b').toString()).toEqual('File 2 Contents'); expect(tree.read('./dir/file-b', 'utf-8')).toEqual('File 2 Contents');
tree.rename('./dir/file3', './dir/file-c'); tree.rename('./dir/file3', './dir/file-c');
expect(tree.read('dir/file-c').toString()).toEqual('File 3 Contents'); expect(tree.read('dir/file-c', 'utf-8')).toEqual('File 3 Contents');
expect(tree.read('/dir/file-c').toString()).toEqual('File 3 Contents'); expect(tree.read('/dir/file-c', 'utf-8')).toEqual('File 3 Contents');
expect(tree.read('./dir/file-c').toString()).toEqual('File 3 Contents'); expect(tree.read('./dir/file-c', 'utf-8')).toEqual('File 3 Contents');
}); });
it('should be able to delete files', () => { it('should be able to delete files', () => {
@ -160,7 +187,7 @@ describe('tree', () => {
try { try {
lstatSync(path.join(dir, 'parent/parent-file.txt')).isFile(); lstatSync(path.join(dir, 'parent/parent-file.txt')).isFile();
fail('Should not reach'); fail('Should not reach');
} catch (e) {} } catch {}
}); });
it('should be able to rename files', () => { it('should be able to rename files', () => {
@ -173,10 +200,10 @@ describe('tree', () => {
expect(tree.read('parent/new-child/new-child-file.txt')).toEqual(null); expect(tree.read('parent/new-child/new-child-file.txt')).toEqual(null);
expect(tree.read('root-file.txt')).toEqual(null); expect(tree.read('root-file.txt')).toEqual(null);
expect(tree.read('renamed-new-child-file.txt').toString()).toEqual( expect(tree.read('renamed-new-child-file.txt', 'utf-8')).toEqual(
'new child content' 'new child content'
); );
expect(tree.read('renamed-root-file.txt').toString()).toEqual( expect(tree.read('renamed-root-file.txt', 'utf-8')).toEqual(
'root content' 'root content'
); );
@ -197,10 +224,10 @@ describe('tree', () => {
flushChanges(dir, tree.listChanges()); flushChanges(dir, tree.listChanges());
expect( expect(
readFileSync(path.join(dir, 'renamed-new-child-file.txt')).toString() readFileSync(path.join(dir, 'renamed-new-child-file.txt'), 'utf-8')
).toEqual('new child content'); ).toEqual('new child content');
expect( expect(
readFileSync(path.join(dir, 'renamed-root-file.txt')).toString() readFileSync(path.join(dir, 'renamed-root-file.txt'), 'utf-8')
).toEqual('root content'); ).toEqual('root content');
}); });

View File

@ -21,9 +21,17 @@ export interface Tree {
/** /**
* Read the contents of a file. * Read the contents of a file.
* @param filePath A path to a file.
*/ */
read(filePath: string): Buffer | null; read(filePath: string): Buffer | null;
/**
* Read the contents of a file as string.
* @param filePath A path to a file.
* @param encoding the encoding for the result
*/
read(filePath: string, encoding: BufferEncoding): string | null;
/** /**
* Update the contents of a file or create a new file. * Update the contents of a file or create a new file.
*/ */
@ -87,14 +95,19 @@ export class FsTree implements Tree {
constructor(readonly root: string, private readonly isVerbose: boolean) {} constructor(readonly root: string, private readonly isVerbose: boolean) {}
read(filePath: string): Buffer | null { read(filePath: string): Buffer | null;
read(filePath: string, encoding: BufferEncoding): string | null;
read(filePath: string, encoding?: BufferEncoding): Buffer | string | null {
filePath = this.normalize(filePath); filePath = this.normalize(filePath);
try { try {
let content: Buffer;
if (this.recordedChanges[this.rp(filePath)]) { if (this.recordedChanges[this.rp(filePath)]) {
return this.recordedChanges[this.rp(filePath)].content; content = this.recordedChanges[this.rp(filePath)].content;
} else { } else {
return this.fsReadFile(filePath); content = this.fsReadFile(filePath);
} }
return encoding ? content.toString(encoding) : content;
} catch (e) { } catch (e) {
if (this.isVerbose) { if (this.isVerbose) {
logger.error(e); logger.error(e);

View File

@ -191,10 +191,10 @@ describe('app', () => {
directory: 'myDir', directory: 'myDir',
}); });
expect( expect(
tree.read('apps/my-dir/my-app/src/app/app.element.ts').toString() tree.read('apps/my-dir/my-app/src/app/app.element.ts', 'utf-8')
).toBeTruthy(); ).toBeTruthy();
expect( expect(
tree.read('apps/my-dir/my-app/src/app/app.element.ts').toString() tree.read('apps/my-dir/my-app/src/app/app.element.ts', 'utf-8')
).toContain('Thank you for using and showing some ♥ for Nx.'); ).toContain('Thank you for using and showing some ♥ for Nx.');
}); });
}); });
@ -214,7 +214,7 @@ describe('app', () => {
name: 'my-App', name: 'my-App',
}); });
expect(tree.read('apps/my-app/jest.config.js').toString()).not.toContain( expect(tree.read('apps/my-app/jest.config.js', 'utf-8')).not.toContain(
`'jest-preset-angular/build/AngularSnapshotSerializer.js',` `'jest-preset-angular/build/AngularSnapshotSerializer.js',`
); );
}); });
@ -294,7 +294,7 @@ describe('app', () => {
it('should use the prefix in the index.html', async () => { it('should use the prefix in the index.html', async () => {
await applicationGenerator(tree, { name: 'myApp', prefix: 'prefix' }); await applicationGenerator(tree, { name: 'myApp', prefix: 'prefix' });
expect(tree.read('apps/my-app/src/index.html').toString()).toContain( expect(tree.read('apps/my-app/src/index.html', 'utf-8')).toContain(
'<prefix-root></prefix-root>' '<prefix-root></prefix-root>'
); );
}); });
@ -347,7 +347,7 @@ describe('app', () => {
babelJest: true, babelJest: true,
} as Schema); } as Schema);
expect(tree.read(`apps/my-app/jest.config.js`).toString()) expect(tree.read(`apps/my-app/jest.config.js`, 'utf-8'))
.toMatchInlineSnapshot(` .toMatchInlineSnapshot(`
"module.exports = { "module.exports = {
displayName: 'my-app', displayName: 'my-app',

View File

@ -110,7 +110,7 @@ describe('lib', () => {
}); });
expect(tree.exists(`libs/my-lib/jest.config.js`)).toBeTruthy(); expect(tree.exists(`libs/my-lib/jest.config.js`)).toBeTruthy();
expect(tree.read(`libs/my-lib/jest.config.js`).toString()) expect(tree.read(`libs/my-lib/jest.config.js`, 'utf-8'))
.toMatchInlineSnapshot(` .toMatchInlineSnapshot(`
"module.exports = { "module.exports = {
displayName: 'my-lib', displayName: 'my-lib',
@ -134,7 +134,7 @@ describe('lib', () => {
expect(tree.exists('libs/my-lib/README.md')).toBeTruthy(); expect(tree.exists('libs/my-lib/README.md')).toBeTruthy();
expect(tree.exists('libs/my-lib/package.json')).toBeFalsy(); expect(tree.exists('libs/my-lib/package.json')).toBeFalsy();
const ReadmeContent = tree.read('libs/my-lib/README.md').toString(); const ReadmeContent = tree.read('libs/my-lib/README.md', 'utf-8');
expect(ReadmeContent).toContain('nx test my-lib'); expect(ReadmeContent).toContain('nx test my-lib');
}); });
@ -144,7 +144,7 @@ describe('lib', () => {
name: 'myLib', name: 'myLib',
}); });
expect(tree.read('jest.config.js').toString()).toMatchInlineSnapshot(` expect(tree.read('jest.config.js', 'utf-8')).toMatchInlineSnapshot(`
"module.exports = { "module.exports = {
projects: [\\"<rootDir>/libs/my-lib\\"] projects: [\\"<rootDir>/libs/my-lib\\"]
};" };"
@ -154,7 +154,7 @@ describe('lib', () => {
name: 'myLib2', name: 'myLib2',
}); });
expect(tree.read('jest.config.js').toString()).toMatchInlineSnapshot(` expect(tree.read('jest.config.js', 'utf-8')).toMatchInlineSnapshot(`
"module.exports = { "module.exports = {
projects: [\\"<rootDir>/libs/my-lib\\",\\"<rootDir>/libs/my-lib2\\"] projects: [\\"<rootDir>/libs/my-lib\\",\\"<rootDir>/libs/my-lib2\\"]
};" };"
@ -714,7 +714,7 @@ describe('lib', () => {
babelJest: true, babelJest: true,
} as Schema); } as Schema);
expect(tree.read(`libs/my-lib/jest.config.js`).toString()) expect(tree.read(`libs/my-lib/jest.config.js`, 'utf-8'))
.toMatchInlineSnapshot(` .toMatchInlineSnapshot(`
"module.exports = { "module.exports = {
displayName: 'my-lib', displayName: 'my-lib',

View File

@ -40,7 +40,7 @@ describe('updateImports', () => {
const projectConfig = readProjectConfiguration(tree, 'my-source'); const projectConfig = readProjectConfiguration(tree, 'my-source');
updateImports(tree, schema, projectConfig); updateImports(tree, schema, projectConfig);
expect(tree.read(importerFilePath).toString()).toMatchSnapshot(); expect(tree.read(importerFilePath, 'utf-8')).toMatchSnapshot();
}); });
/** /**
@ -77,15 +77,15 @@ describe('updateImports', () => {
projectConfig projectConfig
); );
expect(tree.read(importerFilePath).toString()).toContain( expect(tree.read(importerFilePath, 'utf-8')).toContain(
`import { Table } from '@proj/table';` `import { Table } from '@proj/table';`
); );
expect(tree.read(importerFilePath).toString()).toContain( expect(tree.read(importerFilePath, 'utf-8')).toContain(
`import { Tab } from '@proj/tabs';` `import { Tab } from '@proj/tabs';`
); );
expect(tree.read(importerFilePath).toString()).toMatchSnapshot(); expect(tree.read(importerFilePath, 'utf-8')).toMatchSnapshot();
}); });
it('should correctly update deep imports', async () => { it('should correctly update deep imports', async () => {
@ -117,15 +117,15 @@ describe('updateImports', () => {
projectConfig projectConfig
); );
expect(tree.read(importerFilePath).toString()).toContain( expect(tree.read(importerFilePath, 'utf-8')).toContain(
`import { Table } from '@proj/table/components';` `import { Table } from '@proj/table/components';`
); );
expect(tree.read(importerFilePath).toString()).toContain( expect(tree.read(importerFilePath, 'utf-8')).toContain(
`import { Tab } from '@proj/tabs/components';` `import { Tab } from '@proj/tabs/components';`
); );
expect(tree.read(importerFilePath).toString()).toMatchSnapshot(); expect(tree.read(importerFilePath, 'utf-8')).toMatchSnapshot();
}); });
it('should update dynamic imports', async () => { it('should update dynamic imports', async () => {
@ -156,23 +156,23 @@ describe('updateImports', () => {
projectConfig projectConfig
); );
expect(tree.read(importerFilePath).toString()).toContain( expect(tree.read(importerFilePath, 'utf-8')).toContain(
`import('@proj/table').then(m => m.Table);` `import('@proj/table').then(m => m.Table);`
); );
expect(tree.read(importerFilePath).toString()).toContain( expect(tree.read(importerFilePath, 'utf-8')).toContain(
`import('@proj/table/components').then(m => m.Table);` `import('@proj/table/components').then(m => m.Table);`
); );
expect(tree.read(importerFilePath).toString()).toContain( expect(tree.read(importerFilePath, 'utf-8')).toContain(
`import('@proj/tabs').then(m => m.Tab);` `import('@proj/tabs').then(m => m.Tab);`
); );
expect(tree.read(importerFilePath).toString()).toContain( expect(tree.read(importerFilePath, 'utf-8')).toContain(
`import('@proj/tabs/components').then(m => m.Tab);` `import('@proj/tabs/components').then(m => m.Tab);`
); );
expect(tree.read(importerFilePath).toString()).toMatchSnapshot(); expect(tree.read(importerFilePath, 'utf-8')).toMatchSnapshot();
}); });
// //
// it('should update require imports', async () => { // it('should update require imports', async () => {

View File

@ -66,7 +66,7 @@ export function updateImports(
} }
visitNotIgnoredFiles(tree, definition.root, (file) => { visitNotIgnoredFiles(tree, definition.root, (file) => {
const contents = tree.read(file).toString('utf-8'); const contents = tree.read(file, 'utf-8');
if (!replaceProjectRef.test(contents)) { if (!replaceProjectRef.test(contents)) {
return; return;
} }
@ -110,7 +110,7 @@ export function updateImports(
* Changes imports in a file from one import to another * Changes imports in a file from one import to another
*/ */
function updateImportPaths(tree: Tree, path: string, from: string, to: string) { function updateImportPaths(tree: Tree, path: string, from: string, to: string) {
const contents = tree.read(path).toString('utf-8'); const contents = tree.read(path, 'utf-8');
const sourceFile = ts.createSourceFile( const sourceFile = ts.createSourceFile(
path, path,
contents, contents,

View File

@ -57,8 +57,8 @@ describe('updateJestConfig', () => {
updateJestConfig(tree, schema, projectConfig); updateJestConfig(tree, schema, projectConfig);
const jestConfigAfter = tree.read(jestConfigPath).toString(); const jestConfigAfter = tree.read(jestConfigPath, 'utf-8');
const rootJestConfigAfter = tree.read(rootJestConfigPath).toString(); const rootJestConfigAfter = tree.read(rootJestConfigPath, 'utf-8');
expect(jestConfigAfter).toContain(`name: 'my-destination'`); expect(jestConfigAfter).toContain(`name: 'my-destination'`);
expect(jestConfigAfter).toContain( expect(jestConfigAfter).toContain(
`coverageDirectory: '../../coverage/libs/my-destination'` `coverageDirectory: '../../coverage/libs/my-destination'`

View File

@ -27,7 +27,7 @@ export function updateJestConfig(
return; return;
} }
const oldContent = tree.read(jestConfigPath).toString('utf-8'); const oldContent = tree.read(jestConfigPath, 'utf-8');
const findName = new RegExp(`'${schema.projectName}'`, 'g'); const findName = new RegExp(`'${schema.projectName}'`, 'g');
const findDir = new RegExp(project.root, 'g'); const findDir = new RegExp(project.root, 'g');
@ -50,9 +50,7 @@ export function updateJestConfig(
'g' 'g'
); );
const oldRootJestConfigContent = tree const oldRootJestConfigContent = tree.read(rootJestConfigPath, 'utf-8');
.read(rootJestConfigPath)
.toString('utf-8');
const newRootJestConfigContent = oldRootJestConfigContent.replace( const newRootJestConfigContent = oldRootJestConfigContent.replace(
findProject, findProject,

View File

@ -38,7 +38,7 @@ describe('updateProjectRootFiles', () => {
updateProjectRootFiles(tree, schema, projectConfig); updateProjectRootFiles(tree, schema, projectConfig);
const testFileAfter = tree.read(testFilePath).toString(); const testFileAfter = tree.read(testFilePath, 'utf-8');
expect(testFileAfter).toContain(`preset: '../../../jest.config.js'`); expect(testFileAfter).toContain(`preset: '../../../jest.config.js'`);
expect(testFileAfter).toContain( expect(testFileAfter).toContain(
`coverageDirectory: '../../../coverage/libs/my-source'` `coverageDirectory: '../../../coverage/libs/my-source'`

View File

@ -43,7 +43,7 @@ export function updateProjectRootFiles(
continue; continue;
} }
const oldContent = tree.read(join(destination, file)).toString(); const oldContent = tree.read(join(destination, file), 'utf-8');
const newContent = oldContent.replace(regex, newRelativeRoot); const newContent = oldContent.replace(regex, newRelativeRoot);
tree.write(join(destination, file), newContent); tree.write(join(destination, file), newContent);
} }

View File

@ -51,7 +51,7 @@ describe('updateStorybookConfig', () => {
updateStorybookConfig(tree, schema, projectConfig); updateStorybookConfig(tree, schema, projectConfig);
const storybookMainAfter = tree.read(storybookMainPath).toString(); const storybookMainAfter = tree.read(storybookMainPath, 'utf-8');
expect(storybookMainAfter).toContain( expect(storybookMainAfter).toContain(
`const rootMain = require('../../../../.storybook/main');` `const rootMain = require('../../../../.storybook/main');`
); );
@ -80,9 +80,10 @@ describe('updateStorybookConfig', () => {
updateStorybookConfig(tree, schema, projectConfig); updateStorybookConfig(tree, schema, projectConfig);
const storybookWebpackConfigAfter = tree const storybookWebpackConfigAfter = tree.read(
.read(storybookWebpackConfigPath) storybookWebpackConfigPath,
.toString(); 'utf-8'
);
expect(storybookWebpackConfigAfter).toContain( expect(storybookWebpackConfigAfter).toContain(
`const rootWebpackConfig = require('../../../../.storybook/webpack.config');` `const rootWebpackConfig = require('../../../../.storybook/webpack.config');`
); );

View File

@ -36,7 +36,7 @@ export function updateStorybookConfig(
// Replace relative import path to root storybook folder for each file under project storybook // Replace relative import path to root storybook folder for each file under project storybook
for (const file of tree.children(storybookDir)) { for (const file of tree.children(storybookDir)) {
const oldContent = tree.read(join(storybookDir, file)).toString('utf-8'); const oldContent = tree.read(join(storybookDir, file), 'utf-8');
const newContent = oldContent.replace(oldRelativeRoot, newRelativeRoot); const newContent = oldContent.replace(oldRelativeRoot, newRelativeRoot);
tree.write(join(storybookDir, file), newContent); tree.write(join(storybookDir, file), newContent);

View File

@ -30,18 +30,18 @@ describe('updateRootJestConfig', () => {
tree.write( tree.write(
'jest.config.js', 'jest.config.js',
readFileSync(join(__dirname, './test-files/jest.config.js')).toString() readFileSync(join(__dirname, './test-files/jest.config.js'), 'utf-8')
); );
}); });
it('should delete lib project ref from root jest config', async () => { it('should delete lib project ref from root jest config', async () => {
const jestConfig = tree.read('jest.config.js').toString(); const jestConfig = tree.read('jest.config.js', 'utf-8');
expect(jestConfig).toMatchSnapshot(); expect(jestConfig).toMatchSnapshot();
updateJestConfig(tree, schema, readProjectConfiguration(tree, 'my-lib')); updateJestConfig(tree, schema, readProjectConfiguration(tree, 'my-lib'));
const updatedJestConfig = tree.read('jest.config.js').toString(); const updatedJestConfig = tree.read('jest.config.js', 'utf-8');
expect(updatedJestConfig).toMatchSnapshot(); expect(updatedJestConfig).toMatchSnapshot();
@ -51,7 +51,7 @@ describe('updateRootJestConfig', () => {
readProjectConfiguration(tree, 'my-other-lib') readProjectConfiguration(tree, 'my-other-lib')
); );
const updatedJestConfig2 = tree.read('jest.config.js').toString(); const updatedJestConfig2 = tree.read('jest.config.js', 'utf-8');
expect(updatedJestConfig2).toMatchSnapshot(); expect(updatedJestConfig2).toMatchSnapshot();
}); });
@ -59,7 +59,7 @@ describe('updateRootJestConfig', () => {
it('should not delete lib project ref from root jest config if there is no project jest config', () => { it('should not delete lib project ref from root jest config if there is no project jest config', () => {
tree.delete('libs/my-lib/jest.config.js'); tree.delete('libs/my-lib/jest.config.js');
const originalRootJestConfig = tree.read('jest.config.js').toString(); const originalRootJestConfig = tree.read('jest.config.js', 'utf-8');
tree.write( tree.write(
'jest.config.js', 'jest.config.js',
originalRootJestConfig.replace(`'<rootDir>/libs/my-lib',`, '') originalRootJestConfig.replace(`'<rootDir>/libs/my-lib',`, '')
@ -67,7 +67,7 @@ describe('updateRootJestConfig', () => {
updateJestConfig(tree, schema, readProjectConfiguration(tree, 'my-lib')); updateJestConfig(tree, schema, readProjectConfiguration(tree, 'my-lib'));
const rootJestConfig = tree.read('jest.config.js').toString(); const rootJestConfig = tree.read('jest.config.js', 'utf-8');
expect(rootJestConfig).toMatchSnapshot(); expect(rootJestConfig).toMatchSnapshot();
}); });

View File

@ -36,7 +36,7 @@ export function updateJestConfig(
return; return;
} }
const contents = tree.read('jest.config.js').toString(); const contents = tree.read('jest.config.js', 'utf-8');
const sourceFile = createSourceFile( const sourceFile = createSourceFile(
'jest.config.js', 'jest.config.js',
contents, contents,

View File

@ -14,7 +14,7 @@ describe('insertImport', () => {
insertImport(tree, 'index.ts', 'b', 'a-path'); insertImport(tree, 'index.ts', 'b', 'a-path');
expect(tree.read('index.ts').toString()).toMatchInlineSnapshot( expect(tree.read('index.ts', 'utf-8')).toMatchInlineSnapshot(
`"import { a ,b} from 'a-path';"` `"import { a ,b} from 'a-path';"`
); );
}); });
@ -24,7 +24,7 @@ describe('insertImport', () => {
insertImport(tree, 'index.ts', 'b', 'a-path'); insertImport(tree, 'index.ts', 'b', 'a-path');
expect(tree.read('index.ts').toString()).toMatchInlineSnapshot( expect(tree.read('index.ts', 'utf-8')).toMatchInlineSnapshot(
`"import { a, b,} from 'a-path';"` `"import { a, b,} from 'a-path';"`
); );
}); });
@ -34,7 +34,7 @@ describe('insertImport', () => {
insertImport(tree, 'index.ts', 'b', 'b-path'); insertImport(tree, 'index.ts', 'b', 'b-path');
expect(tree.read('index.ts').toString()).toMatchInlineSnapshot(` expect(tree.read('index.ts', 'utf-8')).toMatchInlineSnapshot(`
"import { a } from 'a-path'; "import { a } from 'a-path';
import { b } from 'b-path';" import { b } from 'b-path';"
`); `);

View File

@ -15,7 +15,7 @@ export function insertImport(
name: string, name: string,
modulePath: string modulePath: string
) { ) {
const contents = tree.read(path).toString(); const contents = tree.read(path, 'utf-8');
const sourceFile = createSourceFile(path, contents, ScriptTarget.ESNext); const sourceFile = createSourceFile(path, contents, ScriptTarget.ESNext);

View File

@ -14,7 +14,7 @@ describe('insertStatement', () => {
insertStatement(tree, 'index.ts', 'const b = 0;'); insertStatement(tree, 'index.ts', 'const b = 0;');
expect(tree.read('index.ts').toString()).toMatchInlineSnapshot(` expect(tree.read('index.ts', 'utf-8')).toMatchInlineSnapshot(`
"import { a } from 'a'; "import { a } from 'a';
const b = 0;" const b = 0;"
`); `);
@ -25,7 +25,7 @@ describe('insertStatement', () => {
insertStatement(tree, 'index.ts', 'const b = 0;\n'); insertStatement(tree, 'index.ts', 'const b = 0;\n');
expect(tree.read('index.ts').toString()).toMatchInlineSnapshot(` expect(tree.read('index.ts', 'utf-8')).toMatchInlineSnapshot(`
"const b = 0; "const b = 0;
const a = 0;" const a = 0;"
`); `);

View File

@ -9,7 +9,7 @@ import {
* Insert a statement after the last import statement in a file * Insert a statement after the last import statement in a file
*/ */
export function insertStatement(tree: Tree, path: string, statement: string) { export function insertStatement(tree: Tree, path: string, statement: string) {
const contents = tree.read(path).toString(); const contents = tree.read(path, 'utf-8');
const sourceFile = createSourceFile(path, contents, ScriptTarget.ESNext); const sourceFile = createSourceFile(path, contents, ScriptTarget.ESNext);

View File

@ -65,7 +65,7 @@ describe('@nrwl/workspace:workspace', () => {
layout: 'apps-and-libs', layout: 'apps-and-libs',
defaultBase: 'main', defaultBase: 'main',
}); });
expect(tree.read('proj/.prettierrc').toString()).toMatchSnapshot(); expect(tree.read('proj/.prettierrc', 'utf-8')).toMatchSnapshot();
}); });
it('should recommend vscode extensions', async () => { it('should recommend vscode extensions', async () => {