Skip to content

Commit

Permalink
cleanup(repo): refactored fileutils (#10503)
Browse files Browse the repository at this point in the history
  • Loading branch information
Phillip9587 authored Jun 8, 2022
1 parent a4d95c1 commit b9e623d
Show file tree
Hide file tree
Showing 13 changed files with 69 additions and 212 deletions.
13 changes: 3 additions & 10 deletions packages/add-nx-to-monorepo/src/add-nx-to-monorepo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import * as enquirer from 'enquirer';
import * as yargsParser from 'yargs-parser';
import { output, readJsonFile, writeJsonFile } from '@nrwl/devkit';
import ignore from 'ignore';
import { directoryExists } from 'nx/src/utils/fileutils';

const parsedArgs = yargsParser(process.argv, {
boolean: ['nxCloud'],
Expand Down Expand Up @@ -212,23 +213,15 @@ function createNxJsonFile(repoRoot: string, projects: ProjectDesc[]) {
}

function deduceWorkspaceLayout(repoRoot: string) {
if (exists(path.join(repoRoot, 'packages'))) {
if (directoryExists(path.join(repoRoot, 'packages'))) {
return undefined;
} else if (exists(path.join(repoRoot, 'projects'))) {
} else if (directoryExists(path.join(repoRoot, 'projects'))) {
return { libsDir: 'projects', appsDir: 'projects' };
} else {
return undefined;
}
}

function exists(folder: string) {
try {
return fs.statSync(folder).isDirectory();
} catch {
return false;
}
}

function deduceDefaultBase() {
try {
execSync(`git rev-parse --verify main`, {
Expand Down
27 changes: 3 additions & 24 deletions packages/nx-plugin/src/utils/testing-utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import { dirname, isAbsolute } from 'path';
import { tmpProjPath } from './paths';
import { parseJson } from '@nrwl/devkit';
import type { JsonParseOptions } from '@nrwl/devkit';
import { directoryExists, fileExists } from 'nx/src/utils/fileutils';

export { directoryExists, fileExists };

/**
* Copies module folders from the working directory to the e2e directory
Expand Down Expand Up @@ -139,30 +142,6 @@ export function getCwd(): string {
return process.cwd();
}

/**
* Check if a directory exists
* @param directoryPath Path to directory
*/
export function directoryExists(directoryPath: string): boolean {
try {
return statSync(directoryPath).isDirectory();
} catch {
return false;
}
}

/**
* Check if a file exists.
* @param filePath Path to file
*/
export function fileExists(filePath: string): boolean {
try {
return statSync(filePath).isFile();
} catch {
return false;
}
}

/**
* Check if a file or directory exists.
* @param path Path to file or directory
Expand Down
3 changes: 1 addition & 2 deletions packages/nx/src/command-line/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import { execSync } from 'child_process';
import { join } from 'path';
import { output } from '../utils/output';
import { getPackageManagerCommand } from '../utils/package-manager';
import { fileExists } from '../utils/workspace-root';
import { readJsonFile, writeJsonFile } from '../utils/fileutils';
import { readJsonFile, writeJsonFile, fileExists } from '../utils/fileutils';

export function initHandler() {
const nxIsInstalled = !!execSync(getPackageManagerCommand().list)
Expand Down
30 changes: 4 additions & 26 deletions packages/nx/src/utils/fileutils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,10 @@
import { fs, vol } from 'memfs';
import { stripIndents } from '@angular-devkit/core/src/utils/literals';
import { fs } from 'memfs';
import { createDirectory, isRelativePath } from './fileutils';

jest.mock('fs', () => require('memfs').fs);
jest.mock('fs', () => fs);

describe('fileutils', () => {
beforeEach(() => {
vol.fromJSON(
{
'./README.md': 'hello',
'./.nxignore': stripIndents`
apps/demo/tmp.txt
tmp/
`,
'./.gitignore': stripIndents`
*.js
node_modules/
`,
'./apps/demo/src/index.ts': 'console.log("hello");',
'./apps/demo/tmp.txt': '...',
'./apps/demo/tmp.js': 'console.log("tmp")',
'./workspace.json': '{}',
},
'/root'
);
});

describe('createDirectory', () => {
describe(createDirectory.name, () => {
it('should recursively create the directory', () => {
createDirectory('/root/b/c');
expect(fs.statSync('/root').isDirectory()).toBe(true);
Expand All @@ -35,7 +13,7 @@ describe('fileutils', () => {
});
});

describe('isRelativePath()', () => {
describe(isRelativePath.name, () => {
it('should return true for deeper imports', () => {
expect(isRelativePath('.')).toEqual(true);
expect(isRelativePath('./file')).toEqual(true);
Expand Down
40 changes: 21 additions & 19 deletions packages/nx/src/utils/fileutils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import type { JsonParseOptions, JsonSerializeOptions } from './json';
import {
createReadStream,
createWriteStream,
PathLike,
readFileSync,
writeFileSync,
mkdirSync,
statSync,
} from 'fs';
import { dirname } from 'path';
import { ensureDirSync } from 'fs-extra';
import { mkdirSync, statSync } from 'fs';
import { resolve as pathResolve } from 'path';
import * as tar from 'tar-stream';
import { createGunzip } from 'zlib';

Expand Down Expand Up @@ -64,38 +64,40 @@ export function writeJsonFile<T extends object = object>(
data: T,
options?: JsonWriteOptions
): void {
ensureDirSync(dirname(path));
mkdirSync(dirname(path), { recursive: true });
const serializedJson = serializeJson(data, options);
const content = options?.appendNewLine
? `${serializedJson}\n`
: serializedJson;
writeFileSync(path, content, { encoding: 'utf-8' });
}

export function directoryExists(name) {
/**
* Check if a directory exists
* @param path Path to directory
*/
export function directoryExists(path: PathLike): boolean {
try {
return statSync(name).isDirectory();
} catch (e) {
return statSync(path).isDirectory();
} catch {
return false;
}
}

export function fileExists(filePath: string): boolean {
/**
* Check if a file exists.
* @param path Path to file
*/
export function fileExists(path: PathLike): boolean {
try {
return statSync(filePath).isFile();
} catch (err) {
return statSync(path).isFile();
} catch {
return false;
}
}

export function createDirectory(directoryPath: string) {
const parentPath = pathResolve(directoryPath, '..');
if (!directoryExists(parentPath)) {
createDirectory(parentPath);
}
if (!directoryExists(directoryPath)) {
mkdirSync(directoryPath);
}
export function createDirectory(path: PathLike) {
mkdirSync(path, { recursive: true });
}

export function isRelativePath(path: string): boolean {
Expand All @@ -120,7 +122,7 @@ export async function extractFileFromTarball(
destinationFilePath: string
) {
return new Promise<string>((resolve, reject) => {
ensureDirSync(dirname(destinationFilePath));
mkdirSync(dirname(destinationFilePath), { recursive: true });
var tarExtractStream = tar.extract();
const destinationFileStream = createWriteStream(destinationFilePath);

Expand Down
6 changes: 2 additions & 4 deletions packages/nx/src/utils/target-project-locator.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { getRootTsConfigFileName, resolveModuleByImport } from './typescript';
import { isRelativePath } from './fileutils';
import { isRelativePath, readJsonFile } from './fileutils';
import { dirname, join, posix } from 'path';
import { workspaceRoot } from './workspace-root';
import { readFileSync } from 'fs';
import {
ProjectGraphExternalNode,
ProjectGraphProjectNode,
} from '../config/project-graph';
import { parseJson } from './json';

export class TargetProjectLocator {
private projectRootMappings = createProjectRootMappings(this.nodes);
Expand Down Expand Up @@ -173,7 +171,7 @@ export class TargetProjectLocator {
return {
absolutePath,
path,
config: parseJson(readFileSync(absolutePath, 'utf8')),
config: readJsonFile(absolutePath),
};
}

Expand Down
10 changes: 1 addition & 9 deletions packages/nx/src/utils/workspace-root.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as path from 'path';
import { statSync } from 'fs';
import { fileExists } from './fileutils';

/**
* The root of the workspace
Expand Down Expand Up @@ -28,11 +28,3 @@ export function workspaceRootInner(
return workspaceRootInner(path.dirname(dir), candidateRoot);
}
}

export function fileExists(filePath: string): boolean {
try {
return statSync(filePath).isFile();
} catch (err) {
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import { updatePackageJson } from './update-package-json';
import * as utils from 'nx/src/utils/fileutils';
import { PackageJson } from 'nx/src/utils/package-json';

jest.mock('nx/src/utils/fileutils', () => ({
writeJsonFile: () => {},
}));
jest.mock('fs', () => require('memfs').fs);

describe('updatePackageJson', () => {
const commonOptions = {
Expand Down
13 changes: 3 additions & 10 deletions packages/web/src/utils/fs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as path from 'path';
import { existsSync, removeSync, statSync } from 'fs-extra';
import { existsSync, removeSync } from 'fs-extra';
import { directoryExists } from 'nx/src/utils/fileutils';

export function findUp(
names: string | string[],
Expand Down Expand Up @@ -39,7 +40,7 @@ export function findAllNodeModules(from: string, root?: string) {
let current = from;
while (current && current !== root) {
const potential = path.join(current, 'node_modules');
if (existsSync(potential) && isDirectory(potential)) {
if (directoryExists(potential)) {
nodeModules.push(potential);
}

Expand All @@ -64,11 +65,3 @@ export function deleteOutputDir(root: string, outputPath: string) {

removeSync(resolvedOutputPath);
}

export function isDirectory(path: string) {
try {
return statSync(path).isDirectory();
} catch (_) {
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import type {
NxJsonConfiguration,
ProjectGraphExternalNode,
} from '@nrwl/devkit';
import { workspaceRoot } from '@nrwl/devkit';
import {
workspaceRoot,
readNxJson,
readCachedProjectGraph,
} from '@nrwl/devkit';
import {
DepConstraint,
findConstraintsFor,
Expand All @@ -32,7 +36,6 @@ import {
findFilesInCircularPath,
} from '../utils/graph-utils';
import { isRelativePath } from '../utilities/fileutils';
import { readNxJson, readCachedProjectGraph } from '@nrwl/devkit';

export class Rule extends Lint.Rules.AbstractRule {
constructor(
Expand Down
30 changes: 4 additions & 26 deletions packages/workspace/src/utilities/fileutils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,10 @@
import { fs, vol } from 'memfs';
import { stripIndents } from '@angular-devkit/core/src/utils/literals';
import { fs } from 'memfs';
import { createDirectory, isRelativePath } from './fileutils';

jest.mock('fs', () => require('memfs').fs);
jest.mock('fs', () => fs);

describe('fileutils', () => {
beforeEach(() => {
vol.fromJSON(
{
'./README.md': 'hello',
'./.nxignore': stripIndents`
apps/demo/tmp.txt
tmp/
`,
'./.gitignore': stripIndents`
*.js
node_modules/
`,
'./apps/demo/src/index.ts': 'console.log("hello");',
'./apps/demo/tmp.txt': '...',
'./apps/demo/tmp.js': 'console.log("tmp")',
'./workspace.json': '{}',
},
'/root'
);
});

describe('createDirectory', () => {
describe(createDirectory.name, () => {
it('should recursively create the directory', () => {
createDirectory('/root/b/c');
expect(fs.statSync('/root').isDirectory()).toBe(true);
Expand All @@ -35,7 +13,7 @@ describe('fileutils', () => {
});
});

describe('isRelativePath()', () => {
describe(isRelativePath.name, () => {
it('should return true for deeper imports', () => {
expect(isRelativePath('.')).toEqual(true);
expect(isRelativePath('./file')).toEqual(true);
Expand Down
Loading

0 comments on commit b9e623d

Please sign in to comment.