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

Improve workspace support by checking for workspace entries. #1

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
41 changes: 35 additions & 6 deletions src/search-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,20 +67,49 @@ export async function searchForNodeModules(cwd: string, rootPath?: string): Prom
return traverseAncestorDirectories(cwd, pathGenerator, rootPath, undefined, true);
}

function* splitPath(cwd:string) {
for(let part = path.parse(path.resolve(cwd)); part.base !== ""; part = path.parse(part.dir)) {
yield path.join(part.dir, part.base);
}
}

type NodeModuleEntry = {
path: string;
manifest: string;
hasLockfile: boolean;
};

async function* getNodeModulePaths(cwd:string) : AsyncGenerator<NodeModuleEntry> {
for (const part of splitPath(cwd)) {
const manifest = path.join(part, "package.json");
if (await fs.pathExists(manifest)) {
yield {
path:part,
manifest: manifest,
hasLockfile: await fs.pathExists(path.join(part, "package-lock.json")) || await fs.pathExists(path.join(part, "yarn.lock"))
};
}
}
}

/**
* Determine the root directory of a given project, by looking for a directory with an
* NPM or yarn lockfile.
*
* @param cwd the initial directory to traverse
*/
export async function getProjectRootPath(cwd: string): Promise<string> {
for (const lockFilename of ['yarn.lock', 'package-lock.json']) {
const pathGenerator: PathGeneratorFunction = (traversedPath) => path.join(traversedPath, lockFilename);
const lockPaths = await traverseAncestorDirectories(cwd, pathGenerator, undefined, 1)
if (lockPaths.length > 0) {
return path.dirname(lockPaths[0]);
let candidate = path.resolve(cwd);

for await (const root of getNodeModulePaths(cwd)) {
if (root.hasLockfile) {
candidate = root.path;
const manifest = JSON.parse(await fs.readFile(root.manifest, {encoding: "utf-8"}));
if ("workspaces" in manifest) {
break;
}
}
}

return cwd;
return candidate;
}
6 changes: 6 additions & 0 deletions test/fixture/multi-level-workspace/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"private": true,
"workspaces": [
"packages/*"
]
}