Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use nx utils to read all configuration files #1184

Merged
merged 3 commits into from
Dec 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 27 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 Down Expand Up @@ -168,14 +169,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 +182,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 +225,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 +240,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 +257,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
45 changes: 15 additions & 30 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 All @@ -21,6 +24,7 @@ import {
} from 'jsonc-parser';
import { readdir } from 'fs/promises';
import { getOutputChannel } from './output-channel';
import { toNewFormat } from '@nrwl/tao/src/shared/workspace';

export interface GeneratorDefaults {
[name: string]: string;
Expand Down Expand Up @@ -119,9 +123,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 @@ -342,35 +346,16 @@ export function getPrimitiveValue(value: any): string | undefined {
}
}

function renameProperty(obj: any, from: string, to: string) {
obj[to] = obj[from];
delete obj[from];
}

export function toWorkspaceFormat(w: any): WorkspaceJsonConfiguration {
Object.values(w.projects || {}).forEach((project: any) => {
if (project.architect) {
renameProperty(project, 'architect', 'targets');
}
if (project.schematics) {
renameProperty(project, 'schematics', 'generators');
}
Object.values(project.targets || {}).forEach((target: any) => {
if (target.builder) {
renameProperty(target, 'builder', 'executor');
}
});
});

const sortedProjects = Object.entries(w.projects || {}).sort(
export function toWorkspaceFormat(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function could reuse toNewFormat from @nrwl/tao

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These linked lines are probably not needed anymore since we use the NX helpers to read config

https://github.com/Cammisuli/nx-console/blob/use-nx-utils-for-configs/libs/server/src/lib/utils/utils.ts#L380-L382

w: any
): WorkspaceJsonConfiguration & NxJsonConfiguration {
const newFormat = toNewFormat(w) as WorkspaceJsonConfiguration &
NxJsonConfiguration;
const sortedProjects = Object.entries(newFormat.projects || {}).sort(
(projectA, projectB) => projectA[0].localeCompare(projectB[0])
);
w.projects = Object.fromEntries(sortedProjects);

if (w.schematics) {
renameProperty(w, 'schematics', 'generators');
}
return w;
newFormat.projects = Object.fromEntries(sortedProjects);
return newFormat;
}

function schemaToOptions(schema: Schema): CliOption[] {
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
Loading