Skip to content

Commit

Permalink
refactor retrieving workspace dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
Cammisuli committed Jan 17, 2022
1 parent 4fe4e35 commit 06babd0
Show file tree
Hide file tree
Showing 23 changed files with 292 additions and 190 deletions.
4 changes: 3 additions & 1 deletion apps/vscode/src/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@
],
"dependencies": {
"jsonc-parser": "^3.0.0",
"@monodon/typescript-nx-imports-plugin": "0.2.0"
"@monodon/typescript-nx-imports-plugin": "0.2.0",
"@yarnpkg/fslib": "2.6.1-rc.5",
"@yarnpkg/libzip": "2.2.3-rc.5"
},
"contributes": {
"typescriptServerPlugins": [
Expand Down
18 changes: 18 additions & 0 deletions libs/npm/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": ["../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}
7 changes: 7 additions & 0 deletions libs/npm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# npm

This library was generated with [Nx](https://nx.dev).

## Running unit tests

Run `nx test npm` to execute the unit tests via [Jest](https://jestjs.io).
15 changes: 15 additions & 0 deletions libs/npm/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module.exports = {
displayName: 'npm',
preset: '../../jest.preset.js',
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
},
},
testEnvironment: 'node',
transform: {
'^.+\\.[tj]sx?$': 'ts-jest',
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
coverageDirectory: '../../coverage/libs/npm',
};
4 changes: 4 additions & 0 deletions libs/npm/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"name": "@nx-console/npm",
"version": "0.0.1"
}
34 changes: 34 additions & 0 deletions libs/npm/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"root": "libs/npm",
"sourceRoot": "libs/npm/src",
"projectType": "library",
"targets": {
"lint": {
"executor": "@nrwl/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": ["libs/npm/**/*.ts"]
}
},
"test": {
"executor": "@nrwl/jest:jest",
"outputs": ["coverage/libs/npm"],
"options": {
"jestConfig": "libs/npm/jest.config.js",
"passWithNoTests": true
}
},
"build": {
"executor": "@nrwl/node:package",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/libs/npm",
"tsConfig": "libs/npm/tsconfig.lib.json",
"packageJson": "libs/npm/package.json",
"main": "libs/npm/src/index.ts",
"assets": ["libs/npm/*.md"]
}
}
},
"tags": []
}
1 change: 1 addition & 0 deletions libs/npm/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './lib/workspace-dependencies';
34 changes: 34 additions & 0 deletions libs/npm/src/lib/npm-dependencies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { stat, readdir } from 'fs/promises';
import { join } from 'path';

export async function npmDependencies(workspacePath: string) {
const nodeModulesDir = join(workspacePath, 'node_modules');
const res: string[] = [];
const stats = await stat(nodeModulesDir);
if (!stats.isDirectory()) {
return res;
}

const dirContents = await readdir(nodeModulesDir);

for (const npmPackageOrScope of dirContents) {
if (npmPackageOrScope.startsWith('.')) {
continue;
}

const packageStats = await stat(join(nodeModulesDir, npmPackageOrScope));
if (!packageStats.isDirectory()) {
continue;
}

if (npmPackageOrScope.startsWith('@')) {
(await readdir(join(nodeModulesDir, npmPackageOrScope))).forEach((p) => {
res.push(`${nodeModulesDir}/${npmPackageOrScope}/${p}`);
});
} else {
res.push(`${nodeModulesDir}/${npmPackageOrScope}`);
}
}

return res;
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,40 @@ import { getLibzipSync as libzip } from '@yarnpkg/libzip';

declare function __non_webpack_require__(importPath: string): any;

const PNP_FILE_NAME = '.pnp.cjs';
export async function isWorkspaceInPnp(workspacePath: string) {
try {
const pnpFile = join(workspacePath, PNP_FILE_NAME);
await workspace.fs.stat(Uri.file(pnpFile));
return true;
} catch {
return false;
async function getPnpFile(workspacePath: string) {
const extensions = ['.cjs', '.js'];
for (const ext of extensions) {
try {
const fileName = `.pnp${ext}`;
const pnpFile = join(workspacePath, fileName);
await workspace.fs.stat(Uri.file(pnpFile));
return pnpFile;
} catch {
return;
}
}
}

export function pnpApi(workspacePath: string) {
const pnpFile = join(workspacePath, PNP_FILE_NAME);
async function pnpApi(workspacePath: string) {
const pnpFile = await getPnpFile(workspacePath);
if (!pnpFile) {
return;
}

return __non_webpack_require__(pnpFile);
}

export async function pnpWorkspaceDependencies(workspacePath: string) {
const pnp = pnpApi(workspacePath);
export async function isWorkspaceInPnp(workspacePath: string) {
try {
const file = await getPnpFile(workspacePath);
return !!file;
} catch {
return false;
}
}

export async function pnpDependencies(workspacePath: string) {
const pnp = await pnpApi(workspacePath);

const dependencies = [];
for (const locator of pnp.getDependencyTreeRoots()) {
Expand All @@ -33,27 +48,18 @@ export async function pnpWorkspaceDependencies(workspacePath: string) {
if (reference === null) continue;
if (reference.startsWith('workspace:')) continue;

const depPkg = pnp.getPackageInformation({ name, reference });

try {
let path: string = pnp.resolveToUnqualified(name, workspacePath + '/');
if (path.includes('__virtual__')) {
path = pnp.resolveVirtual(path);
}

dependencies.push({
name,
path,
packageJson: await crossFs.readJsonPromise(path + '/package.json'),
});
dependencies.push(path);
// packageJson: await crossFs.readJsonPromise(path + '/package.json'),
} catch {
continue;
}
}
}
debugger;
return dependencies;
}

const zipOpenFs = new ZipOpenFS({ libzip });
export const crossFs = new PosixFS(zipOpenFs);
20 changes: 20 additions & 0 deletions libs/npm/src/lib/workspace-dependencies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { npmDependencies } from './npm-dependencies';
import { isWorkspaceInPnp, pnpDependencies } from './pnp-dependencies';

/**
* Get a flat list of all node_modules folders in the workspace.
* This is needed to continue to support Angular CLI projects.
*
* @param nodeModulesDir
* @returns
*/

export async function workspaceDependencies(
workspacePath: string
): Promise<string[]> {
if (await isWorkspaceInPnp(workspacePath)) {
return pnpDependencies(workspacePath);
}

return npmDependencies(workspacePath);
}
13 changes: 13 additions & 0 deletions libs/npm/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
},
{
"path": "./tsconfig.spec.json"
}
]
}
11 changes: 11 additions & 0 deletions libs/npm/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"outDir": "../../dist/out-tsc",
"declaration": true,
"types": ["node"]
},
"exclude": ["**/*.spec.ts", "**/*.test.ts"],
"include": ["**/*.ts"]
}
19 changes: 19 additions & 0 deletions libs/npm/tsconfig.spec.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"include": [
"**/*.test.ts",
"**/*.spec.ts",
"**/*.test.tsx",
"**/*.spec.tsx",
"**/*.test.js",
"**/*.spec.js",
"**/*.test.jsx",
"**/*.spec.jsx",
"**/*.d.ts"
]
}
1 change: 0 additions & 1 deletion libs/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,3 @@ export {
export { watchFile } from './lib/utils/watch-file';
export { buildProjectPath } from './lib/utils/build-project-path';
export { findConfig } from './lib/utils/find-config';
export * from './lib/utils/pnp';
8 changes: 4 additions & 4 deletions libs/server/src/lib/utils/get-executors.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { CollectionInfo } from '@nx-console/schema';
import { readCollectionsFromNodeModules } from './read-collections';
import { readCollections } from './read-collections';

export async function getExecutors(
workspacePath: string,
clearPackageJsonCache: boolean
): Promise<CollectionInfo[]> {
return (
await readCollectionsFromNodeModules(workspacePath, clearPackageJsonCache)
).filter((collection) => collection.type === 'executor');
return (await readCollections(workspacePath, clearPackageJsonCache)).filter(
(collection) => collection.type === 'executor'
);
}
14 changes: 3 additions & 11 deletions libs/server/src/lib/utils/get-generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,13 @@ import {
normalizeSchema,
readAndCacheJsonFile,
} from './utils';
import {
getCollectionInfo,
readCollectionsFromNodeModules,
} from './read-collections';
import { getCollectionInfo, readCollections } from './read-collections';

export async function getGenerators(
workspacePath: string
): Promise<CollectionInfo[]> {
const basedir = workspacePath;
const collections = await readCollectionsFromNodeModules(
workspacePath,
false
);
const collections = await readCollections(workspacePath, false);
let generatorCollections = collections.filter(
(collection) => collection.type === 'generator'
);
Expand Down Expand Up @@ -63,14 +57,12 @@ async function readWorkspaceGeneratorsCollection(
const collectionPath = join(collectionDir, 'collection.json');
if (await fileExists(collectionPath)) {
const collection = await readAndCacheJsonFile(
'collection.json',
collectionDir
`${collectionDir}/collection.json`
);

return getCollectionInfo(
collectionName,
collectionPath,
collectionDir,
{
path: collectionPath,
json: {},
Expand Down
Loading

0 comments on commit 06babd0

Please sign in to comment.