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 {
const workspaceJson = JSON.parse(
stripJsonComments(host.read(path).toString())
stripJsonComments(host.read(path, 'utf-8'))
);
const reformatted = reformattedWorkspaceJsonOrNull(workspaceJson);
if (reformatted) {

View File

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

View File

@ -2,7 +2,7 @@ import { Tree } from '@nrwl/tao/src/shared/tree';
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.
@ -12,10 +12,10 @@ export function visitNotIgnoredFiles(
dirPath: string = tree.root,
visitor: (path: string) => void
) {
let ig;
let ig: Ignore;
if (tree.exists('.gitignore')) {
ig = ignore();
ig.add(tree.read('.gitignore').toString());
ig.add(tree.read('.gitignore', 'utf-8'));
}
if (dirPath !== '' && ig?.ignores(dirPath)) {
return;

View File

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

View File

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

View File

@ -11,7 +11,7 @@ export function readJson<T = any>(host: Tree, path: string) {
if (!host.exists(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 {
return JSON.parse(contents) as T;
} catch (e) {

View File

@ -208,7 +208,7 @@ describe('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'],`
);
});
@ -219,7 +219,7 @@ describe('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'`
);
});
@ -281,7 +281,7 @@ describe('app', () => {
it('should generate an index component', async () => {
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/);
});

View File

@ -3,7 +3,7 @@ import { NormalizedSchema } from './normalize-options';
export function addGitIgnoreEntry(host: Tree, options: NormalizedSchema) {
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`;
host.write('.gitignore', content);
} else {

View File

@ -3,7 +3,7 @@ import { NormalizedSchema } from './normalize-options';
export function addPrettierIgnoreEntry(host: Tree, options: NormalizedSchema) {
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`;
host.write('.prettierignore', content);
} else {

View File

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

View File

@ -13,7 +13,7 @@ describe('jest', () => {
jestInitGenerator(tree, {});
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 = {
projects: []
};"
@ -23,7 +23,7 @@ describe('jest', () => {
it('should not override existing files', async () => {
tree.write('jest.config.js', `test`);
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 () => {

View File

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

View File

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

View File

@ -53,7 +53,7 @@ export function addOrUpdateProperty(
const propertyName = properties.shift();
const propertyAssignment = findPropertyAssignment(object, propertyName);
const originalContents = tree.read(path).toString();
const originalContents = tree.read(path, 'utf-8');
if (propertyAssignment) {
if (
@ -230,6 +230,6 @@ export function jestConfigObject(
host: Tree,
path: string
): 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());
}

View File

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

View File

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

View File

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

View File

@ -215,9 +215,9 @@ export function convertTSLintDisableCommentsForProject(
if (!filePath.endsWith('.ts')) {
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
if (!likelyContainsTSLintComment(fileContent)) {
if (!fileContent || !likelyContainsTSLintComment(fileContent)) {
return;
}
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/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(
`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/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(
`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/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(
`import styles from './index.module.styl'`
);
@ -116,7 +116,7 @@ describe('app', () => {
).toBeFalsy();
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).toContain(`import styled from 'styled-components'`);
});
@ -134,7 +134,7 @@ describe('app', () => {
).toBeFalsy();
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).toContain(`import styled from '@emotion/styled'`);
});
@ -147,7 +147,7 @@ describe('app', () => {
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(
@ -165,7 +165,7 @@ describe('app', () => {
it('should setup jest with tsx support', async () => {
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'],`
);
});
@ -173,7 +173,7 @@ describe('app', () => {
it('should setup jest with SVGR support', async () => {
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'`
);
});
@ -244,7 +244,7 @@ describe('app', () => {
it('should generate functional components by default', async () => {
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/);
});

View File

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

View File

@ -330,7 +330,7 @@ describe('app', () => {
babelJest: true,
} 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(`
"module.exports = {
displayName: 'my-node-app',

View File

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

View File

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

View File

@ -8,7 +8,6 @@ import {
import {
joinPathFragments,
Tree,
StringInsertion,
applyChangesToString,
addDependenciesToPackageJson,
} from '@nrwl/devkit';
@ -22,7 +21,7 @@ export function addRouting(host: Tree, options: NormalizedSchema) {
options.appProjectRoot,
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(
appPath,
appFileContent,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -97,7 +97,7 @@ describe('component', () => {
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/);
});
@ -110,7 +110,7 @@ describe('component', () => {
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/);
});

View File

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

View File

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

View File

@ -363,7 +363,7 @@ function readComponent(
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(
path,

View File

@ -71,7 +71,7 @@ describe('redux', () => {
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('configureStore');
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'
);
const buffer = host.read(indexFilePath);
if (!!buffer) {
const indexSource = buffer.toString('utf-8');
const indexSource = host.read(indexFilePath, 'utf-8');
if (indexSource !== null) {
const indexSourceFile = ts.createSourceFile(
indexFilePath,
indexSource,
@ -93,7 +92,7 @@ function addStoreConfiguration(host: Tree, options: NormalizedSchema) {
return;
}
const mainSource = host.read(options.appMainFilePath).toString();
const mainSource = host.read(options.appMainFilePath, 'utf-8');
if (!mainSource.includes('redux')) {
const mainSourceFile = ts.createSourceFile(
options.appMainFilePath,
@ -114,7 +113,7 @@ function updateReducerConfiguration(host: Tree, options: NormalizedSchema) {
return;
}
const mainSource = host.read(options.appMainFilePath).toString();
const mainSource = host.read(options.appMainFilePath, 'utf-8');
const mainSourceFile = ts.createSourceFile(
options.appMainFilePath,
mainSource,

View File

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

View File

@ -97,7 +97,7 @@ describe('@nrwl/storybook:configuration', () => {
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 () => {

View File

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

View File

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

View File

@ -21,9 +21,17 @@ export interface Tree {
/**
* Read the contents of a file.
* @param filePath A path to a file.
*/
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.
*/
@ -87,14 +95,19 @@ export class FsTree implements Tree {
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);
try {
let content: Buffer;
if (this.recordedChanges[this.rp(filePath)]) {
return this.recordedChanges[this.rp(filePath)].content;
content = this.recordedChanges[this.rp(filePath)].content;
} else {
return this.fsReadFile(filePath);
content = this.fsReadFile(filePath);
}
return encoding ? content.toString(encoding) : content;
} catch (e) {
if (this.isVerbose) {
logger.error(e);

View File

@ -191,10 +191,10 @@ describe('app', () => {
directory: 'myDir',
});
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();
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.');
});
});
@ -214,7 +214,7 @@ describe('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',`
);
});
@ -294,7 +294,7 @@ describe('app', () => {
it('should use the prefix in the index.html', async () => {
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>'
);
});
@ -347,7 +347,7 @@ describe('app', () => {
babelJest: true,
} as Schema);
expect(tree.read(`apps/my-app/jest.config.js`).toString())
expect(tree.read(`apps/my-app/jest.config.js`, 'utf-8'))
.toMatchInlineSnapshot(`
"module.exports = {
displayName: 'my-app',

View File

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

View File

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

View File

@ -66,7 +66,7 @@ export function updateImports(
}
visitNotIgnoredFiles(tree, definition.root, (file) => {
const contents = tree.read(file).toString('utf-8');
const contents = tree.read(file, 'utf-8');
if (!replaceProjectRef.test(contents)) {
return;
}
@ -110,7 +110,7 @@ export function updateImports(
* Changes imports in a file from one import to another
*/
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(
path,
contents,

View File

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

View File

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

View File

@ -38,7 +38,7 @@ describe('updateProjectRootFiles', () => {
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(
`coverageDirectory: '../../../coverage/libs/my-source'`

View File

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

View File

@ -51,7 +51,7 @@ describe('updateStorybookConfig', () => {
updateStorybookConfig(tree, schema, projectConfig);
const storybookMainAfter = tree.read(storybookMainPath).toString();
const storybookMainAfter = tree.read(storybookMainPath, 'utf-8');
expect(storybookMainAfter).toContain(
`const rootMain = require('../../../../.storybook/main');`
);
@ -80,9 +80,10 @@ describe('updateStorybookConfig', () => {
updateStorybookConfig(tree, schema, projectConfig);
const storybookWebpackConfigAfter = tree
.read(storybookWebpackConfigPath)
.toString();
const storybookWebpackConfigAfter = tree.read(
storybookWebpackConfigPath,
'utf-8'
);
expect(storybookWebpackConfigAfter).toContain(
`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
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);
tree.write(join(storybookDir, file), newContent);

View File

@ -30,18 +30,18 @@ describe('updateRootJestConfig', () => {
tree.write(
'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 () => {
const jestConfig = tree.read('jest.config.js').toString();
const jestConfig = tree.read('jest.config.js', 'utf-8');
expect(jestConfig).toMatchSnapshot();
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();
@ -51,7 +51,7 @@ describe('updateRootJestConfig', () => {
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();
});
@ -59,7 +59,7 @@ describe('updateRootJestConfig', () => {
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');
const originalRootJestConfig = tree.read('jest.config.js').toString();
const originalRootJestConfig = tree.read('jest.config.js', 'utf-8');
tree.write(
'jest.config.js',
originalRootJestConfig.replace(`'<rootDir>/libs/my-lib',`, '')
@ -67,7 +67,7 @@ describe('updateRootJestConfig', () => {
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();
});

View File

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

View File

@ -14,7 +14,7 @@ describe('insertImport', () => {
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';"`
);
});
@ -24,7 +24,7 @@ describe('insertImport', () => {
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';"`
);
});
@ -34,7 +34,7 @@ describe('insertImport', () => {
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 { b } from 'b-path';"
`);

View File

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

View File

@ -14,7 +14,7 @@ describe('insertStatement', () => {
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';
const b = 0;"
`);
@ -25,7 +25,7 @@ describe('insertStatement', () => {
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 a = 0;"
`);

View File

@ -9,7 +9,7 @@ import {
* Insert a statement after the last import statement in a file
*/
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);

View File

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