Skip to content

Commit

Permalink
feat: use nx utils to read all configuration files
Browse files Browse the repository at this point in the history
  • Loading branch information
Cammisuli committed Dec 10, 2021
1 parent dfff467 commit 13d5687
Show file tree
Hide file tree
Showing 29 changed files with 267 additions and 310 deletions.
82 changes: 28 additions & 54 deletions apps/vscode/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
getGenerators,
teardownTelemetry,
watchFile,
directoryExists,
} from '@nx-console/server';
import {
GlobalConfigurationStore,
Expand Down Expand Up @@ -85,13 +86,13 @@ export async function activate(c: ExtensionContext) {
const revealWebViewPanelCommand = commands.registerCommand(
'nxConsole.revealWebViewPanel',
async (runTargetTreeItem: RunTargetTreeItem, contextMenuUri?: Uri) => {
if (
!existsSync(
join(runTargetTreeItem.workspaceJsonPath, '..', 'node_modules')
)
) {
const { validNodeModules: hasNodeModules } = verifyNodeModules(
join(runTargetTreeItem.workspaceJsonPath, '..')
const workspacePath = WorkspaceConfigurationStore.instance.get(
'nxWorkspacePath',
''
);
if (!(await directoryExists(join(workspacePath, 'node_modules')))) {
const { validNodeModules: hasNodeModules } = await verifyNodeModules(
workspacePath
);
if (!hasNodeModules) {
return;
Expand All @@ -116,6 +117,7 @@ export async function activate(c: ExtensionContext) {
const vscodeWorkspacePath =
workspace.workspaceFolders && workspace.workspaceFolders[0].uri.fsPath;

debugger;
if (vscodeWorkspacePath) {
scanForWorkspace(vscodeWorkspacePath);
}
Expand Down Expand Up @@ -168,14 +170,7 @@ function manuallySelectWorkspaceDefinition() {
.then((value) => {
if (value && value[0]) {
const selectedDirectory = value[0].fsPath;
return setWorkspace(
join(
selectedDirectory,
existsSync(join(selectedDirectory, 'angular.json'))
? 'angular.json'
: 'workspace.json'
)
);
return setWorkspace(selectedDirectory);
}
});
} else {
Expand All @@ -188,32 +183,20 @@ function manuallySelectWorkspaceDefinition() {
function scanForWorkspace(vscodeWorkspacePath: string) {
let currentDirectory = vscodeWorkspacePath;

const { root } = parse(vscodeWorkspacePath);

const workspaceJsonPath = WorkspaceConfigurationStore.instance.get(
'nxWorkspaceJsonPath',
const workspacePath = WorkspaceConfigurationStore.instance.get(
'nxWorkspacePath',
''
);
if (workspaceJsonPath) {
currentDirectory = dirname(workspaceJsonPath);
}

while (currentDirectory !== root) {
if (existsSync(join(currentDirectory, 'angular.json'))) {
setWorkspace(join(currentDirectory, 'angular.json'));
}
if (existsSync(join(currentDirectory, 'workspace.json'))) {
setWorkspace(join(currentDirectory, 'workspace.json'));
}
currentDirectory = dirname(currentDirectory);
if (workspacePath) {
currentDirectory = workspacePath;
}

setWorkspace(currentDirectory);
}

async function setWorkspace(workspaceJsonPath: string) {
WorkspaceConfigurationStore.instance.set(
'nxWorkspaceJsonPath',
workspaceJsonPath
);
async function setWorkspace(workspacePath: string) {
WorkspaceConfigurationStore.instance.set('nxWorkspacePath', workspacePath);
const { verifyWorkspace } = await import('@nx-console/vscode/nx-workspace');

const { validWorkspaceJson } = await verifyWorkspace();
Expand Down Expand Up @@ -243,16 +226,13 @@ async function setWorkspace(workspaceJsonPath: string) {

context.subscriptions.push(nxCommandsTreeView, nxProjectTreeView);
} else {
WorkspaceConfigurationStore.instance.set(
'nxWorkspaceJsonPath',
workspaceJsonPath
);
WorkspaceConfigurationStore.instance.set('nxWorkspacePath', workspacePath);
}

await setApplicationAndLibraryContext(workspaceJsonPath);
await setApplicationAndLibraryContext(workspacePath);

const isNxWorkspace = existsSync(join(workspaceJsonPath, '..', 'nx.json'));
const isAngularWorkspace = workspaceJsonPath.endsWith('angular.json');
const isNxWorkspace = existsSync(join(workspacePath, 'nx.json'));
const isAngularWorkspace = existsSync(join(workspacePath, 'angular.json'));

commands.executeCommand(
'setContext',
Expand All @@ -261,7 +241,7 @@ async function setWorkspace(workspaceJsonPath: string) {
);
commands.executeCommand('setContext', 'isNxWorkspace', isNxWorkspace);

registerWorkspaceFileWatcher(context, workspaceJsonPath);
registerWorkspaceFileWatcher(context, workspacePath);

currentRunTargetTreeProvider.refresh();
nxProjectsTreeProvider.refresh();
Expand All @@ -278,30 +258,24 @@ async function setWorkspace(workspaceJsonPath: string) {
getTelemetry().record('WorkspaceType', { workspaceType });
}

async function setApplicationAndLibraryContext(workspaceJsonPath: string) {
async function setApplicationAndLibraryContext(workspacePath: string) {
const { getNxConfig } = await import('@nx-console/vscode/nx-workspace');

let nxConfig: Awaited<ReturnType<typeof getNxConfig>>;
try {
nxConfig = await getNxConfig(dirname(workspaceJsonPath));
nxConfig = await getNxConfig(workspacePath);
} catch {
return;
}

commands.executeCommand('setContext', 'nxAppsDir', [
join(
dirname(workspaceJsonPath),
nxConfig.workspaceLayout?.appsDir ?? 'apps'
),
join(workspacePath, nxConfig.workspaceLayout?.appsDir ?? 'apps'),
]);
commands.executeCommand('setContext', 'nxLibsDir', [
join(
dirname(workspaceJsonPath),
nxConfig.workspaceLayout?.libsDir ?? 'libs'
),
join(workspacePath, nxConfig.workspaceLayout?.libsDir ?? 'libs'),
]);

const generatorCollections = await getGenerators(workspaceJsonPath);
const generatorCollections = await getGenerators(workspacePath);

let hasApplicationGenerators = false;
let hasLibraryGenerators = false;
Expand Down
3 changes: 2 additions & 1 deletion libs/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ export * from './lib/utils/get-generators';
export * from './lib/utils/get-executors';
export * from './lib/utils/read-collections';
export {
fileExistsSync,
fileExists,
directoryExists,
readAndParseJson,
readAndCacheJsonFile,
normalizeSchema,
Expand Down
11 changes: 5 additions & 6 deletions libs/server/src/lib/utils/build-project-path.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { dirname, join } from 'path';
import { join } from 'path';

/**
* Builds the project path from the given project name.
* @param workspaceJsonPath The full path to the workspace.json file
* @param projectPath The path to the project relative to the workspace.json file
* @param workspacePath The full path to the configured workspace
* @param projectPath The path to the project relative to the workspace
* @returns The full path to the project.json file
*/
export function buildProjectPath(
workspaceJsonPath: string,
workspacePath: string,
projectPath: string
): string {
const workspaceRootDir = dirname(workspaceJsonPath);
return join(workspaceRootDir, projectPath, 'project.json');
return join(workspacePath, projectPath, 'project.json');
}
7 changes: 2 additions & 5 deletions libs/server/src/lib/utils/get-executors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@ import { CollectionInfo } from '@nx-console/schema';
import { readCollectionsFromNodeModules } from './read-collections';

export async function getExecutors(
workspaceJsonPath: string,
workspacePath: string,
clearPackageJsonCache: boolean
): Promise<CollectionInfo[]> {
return (
await readCollectionsFromNodeModules(
workspaceJsonPath,
clearPackageJsonCache
)
await readCollectionsFromNodeModules(workspacePath, clearPackageJsonCache)
).filter((collection) => collection.type === 'executor');
}
10 changes: 5 additions & 5 deletions libs/server/src/lib/utils/get-generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { basename, join } from 'path';

import {
directoryExists,
fileExistsSync,
fileExists,
listFiles,
normalizeSchema,
readAndCacheJsonFile,
Expand All @@ -14,11 +14,11 @@ import {
} from './read-collections';

export async function getGenerators(
workspaceJsonPath: string
workspacePath: string
): Promise<CollectionInfo[]> {
const basedir = join(workspaceJsonPath, '..');
const basedir = workspacePath;
const collections = await readCollectionsFromNodeModules(
workspaceJsonPath,
workspacePath,
false
);
let generatorCollections = collections.filter(
Expand Down Expand Up @@ -62,7 +62,7 @@ async function readWorkspaceGeneratorsCollection(
const collectionDir = join(basedir, workspaceGeneratorsPath);
const collectionName = 'workspace-generator';
const collectionPath = join(collectionDir, 'collection.json');
if (fileExistsSync(collectionPath)) {
if (await fileExists(collectionPath)) {
const collection = await readAndCacheJsonFile(
'collection.json',
collectionDir
Expand Down
7 changes: 3 additions & 4 deletions libs/server/src/lib/utils/read-collections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,13 @@ import {
} from './utils';

export async function readCollectionsFromNodeModules(
workspaceJsonPath: string,
workspacePath: string,
clearPackageJsonCache: boolean
): Promise<CollectionInfo[]> {
const basedir = dirname(workspaceJsonPath);
const nodeModulesDir = join(basedir, 'node_modules');
const nodeModulesDir = join(workspacePath, 'node_modules');

if (clearPackageJsonCache) {
clearJsonCache('package.json', basedir);
clearJsonCache('package.json', workspacePath);
}

const packages = await listOfUnnestedNpmPackages(nodeModulesDir);
Expand Down
13 changes: 9 additions & 4 deletions libs/server/src/lib/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Schema } from '@nrwl/tao/src/shared/params';
import * as path from 'path';
import type { WorkspaceJsonConfiguration } from '@nrwl/devkit';
import type {
WorkspaceJsonConfiguration,
NxJsonConfiguration,
} from '@nrwl/devkit';

import {
ItemsWithEnum,
Expand Down Expand Up @@ -119,9 +122,9 @@ export async function directoryExists(filePath: string): Promise<boolean> {
}
}

export function fileExistsSync(filePath: string): boolean {
export async function fileExists(filePath: string): Promise<boolean> {
try {
return statSync(filePath).isFile();
return (await stat(filePath)).isFile();
} catch {
return false;
}
Expand Down Expand Up @@ -347,7 +350,9 @@ function renameProperty(obj: any, from: string, to: string) {
delete obj[from];
}

export function toWorkspaceFormat(w: any): WorkspaceJsonConfiguration {
export function toWorkspaceFormat(
w: any
): WorkspaceJsonConfiguration & NxJsonConfiguration {
Object.values(w.projects || {}).forEach((project: any) => {
if (project.architect) {
renameProperty(project, 'architect', 'targets');
Expand Down
5 changes: 3 additions & 2 deletions libs/typescript-plugin/src/lib/typescript-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ export async function enableTypeScriptPlugin(context: vscode.ExtensionContext) {
return;
}

const workspaceRoot = dirname(
WorkspaceConfigurationStore.instance.get('nxWorkspaceJsonPath', '')
const workspaceRoot = WorkspaceConfigurationStore.instance.get(
'nxWorkspacePath',
''
);

vscode.workspace.onDidOpenTextDocument(
Expand Down
2 changes: 1 addition & 1 deletion libs/vscode/configuration/src/lib/configuration-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const GLOBAL_CONFIG_KEYS = [
*/
export type GlobalConfigKeys = typeof GLOBAL_CONFIG_KEYS[number];

export const WORKSPACE_CONFIG_KEYS = ['nxWorkspaceJsonPath'] as const;
export const WORKSPACE_CONFIG_KEYS = ['nxWorkspacePath'] as const;
/**
* configuration Keys used for NxConsole on a vscode workspace level
*/
Expand Down
13 changes: 5 additions & 8 deletions libs/vscode/json-schema/src/lib/project-json-schema.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { CollectionInfo } from '@nx-console/schema';
import { getExecutors, watchFile } from '@nx-console/server';
import { WorkspaceConfigurationStore } from '@nx-console/vscode/configuration';
import { dirname, join } from 'path';
import { join } from 'path';
import * as vscode from 'vscode';

let FILE_WATCHER: vscode.FileSystemWatcher;

export class ProjectJsonSchema {
constructor(context: vscode.ExtensionContext) {
const workspacePath = WorkspaceConfigurationStore.instance.get(
'nxWorkspaceJsonPath',
'nxWorkspacePath',
''
);

Expand All @@ -21,12 +21,9 @@ export class ProjectJsonSchema {
* Whenever a new package is added to the package.json, we recreate the schema.
* This allows newly added plugins to be added
*/
FILE_WATCHER = watchFile(
join(dirname(workspacePath), 'package.json'),
() => {
this.setupSchema(workspacePath, context.extensionUri, true);
}
);
FILE_WATCHER = watchFile(join(workspacePath, 'package.json'), () => {
this.setupSchema(workspacePath, context.extensionUri, true);
});
context.subscriptions.push(FILE_WATCHER);

this.setupSchema(workspacePath, context.extensionUri);
Expand Down
11 changes: 4 additions & 7 deletions libs/vscode/json-schema/src/lib/workspace-json-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ let FILE_WATCHER: vscode.FileSystemWatcher;
export class WorkspaceJsonSchema {
constructor(context: vscode.ExtensionContext) {
const workspacePath = WorkspaceConfigurationStore.instance.get(
'nxWorkspaceJsonPath',
'nxWorkspacePath',
''
);

Expand All @@ -21,12 +21,9 @@ export class WorkspaceJsonSchema {
* Whenever a new package is added to the package.json, we recreate the schema.
* This allows newly added plugins to be added
*/
FILE_WATCHER = watchFile(
join(dirname(workspacePath), 'package.json'),
() => {
this.setupSchema(workspacePath, context.extensionUri, true);
}
);
FILE_WATCHER = watchFile(join(workspacePath, 'package.json'), () => {
this.setupSchema(workspacePath, context.extensionUri, true);
});
context.subscriptions.push(FILE_WATCHER);

this.setupSchema(workspacePath, context.extensionUri);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export class NxProjectTreeItem extends TreeItem {

export interface NxProject {
project: string;
root: string;
target?: {
name: string;
configuration?: string;
Expand Down
Loading

0 comments on commit 13d5687

Please sign in to comment.