Skip to content

Commit

Permalink
refactor(nx): simplify the cli script
Browse files Browse the repository at this point in the history
  • Loading branch information
vsavkin committed Jul 19, 2019
1 parent d0bdb75 commit 297eca0
Showing 1 changed file with 41 additions and 26 deletions.
67 changes: 41 additions & 26 deletions packages/cli/bin/nx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,48 +2,63 @@
import { statSync } from 'fs';
import * as path from 'path';

function isLocalProject(dir: string): boolean {
if (path.dirname(dir) === dir) return false;
const configPath = path.join(dir, 'angular.json');
if (fileExists(configPath)) {
return true;
} else {
return isLocalProject(path.dirname(dir));
}
}

function findLocalNx(dir: string): string {
function findWorkspaceRoot(dir: string) {
if (path.dirname(dir) === dir) return null;
const nxPath = path.join(dir, 'node_modules', '.bin', 'nx');
if (fileExists(nxPath)) {
return nxPath;
if (exists(path.join(dir, 'angular.json'))) {
return { type: 'angular', dir };
} else if (exists(path.join(dir, 'workspace.json'))) {
return { type: 'nx', dir };
} else {
return findLocalNx(path.dirname(dir));
return findWorkspaceRoot(path.dirname(dir));
}
}

function fileExists(filePath: string): boolean {
function exists(filePath: string): boolean {
try {
return statSync(filePath).isFile();
return statSync(filePath).isFile() || statSync(filePath).isDirectory();
} catch (err) {
return false;
}
}

const inLocal = isLocalProject(__dirname);
if (inLocal) {
/**
* The commandsObject is a Yargs object declared in `nx-commands.ts`,
* It is exposed and bootstrapped here to provide CLI features.
*/
const workspace = findWorkspaceRoot(__dirname);

// we are running a local nx
if (workspace) {
// The commandsObject is a Yargs object declared in `nx-commands.ts`,
// It is exposed and bootstrapped here to provide CLI features.
const w = require('@nrwl/workspace');
if (w.supportedNxCommands.includes(process.argv[2])) {
// The commandsObject is a Yargs object declared in `nx-commands.ts`,
// It is exposed and bootstrapped here to provide CLI features.
w.commandsObject.argv;
} else {
require(w.closestCli(__dirname));
} else if (workspace.type === 'nx') {
require(path.join(
workspace.dir,
'node_modules',
'@nrwl',
'tao',
'index.js'
));
} else if (workspace.type === 'angular') {
require(path.join(
workspace.dir,
'node_modules',
'@angular',
'cli',
'lib',
'init.js'
));
}
} else {
require(findLocalNx(process.cwd()));
// we are running global nx
const w = findWorkspaceRoot(process.cwd());
if (w) {
require(path.join(w.dir, 'node_modules', '@nrwl', 'cli', 'bin', 'nx.js'));
} else {
console.error(
`Error: The current directory isn't part of an Nx workspace.`
);
process.exit(1);
}
}

0 comments on commit 297eca0

Please sign in to comment.