Skip to content
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
36 changes: 30 additions & 6 deletions scripts/workspace-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,34 @@ function getWorkspaceGlobs(rootPackage) {
throw new Error("Unsupported workspace configuration in package.json");
}

function escapeRegExp(value) {
return value.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
}

function segmentHasPatternSyntax(segment) {
return segment.includes("*") || /\{[^{}]+,[^{}]*\}/u.test(segment);
}

function segmentPatternToRegExp(segment) {
return new RegExp(
`^${segment.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*")}$`,
);
let pattern = "";
for (let index = 0; index < segment.length; index += 1) {
const char = segment[index];
if (char === "*") {
pattern += "[^/]*";
continue;
}
if (char === "{") {
const end = segment.indexOf("}", index + 1);
const body = end === -1 ? "" : segment.slice(index + 1, end);
if (body.includes(",")) {
pattern += `(?:${body.split(",").map(escapeRegExp).join("|")})`;
index = end;
continue;
}
}
pattern += escapeRegExp(char);
}
return new RegExp(`^${pattern}$`);
}

function listDirectories(path) {
Expand All @@ -120,7 +144,7 @@ function expandWorkspacePattern(rootDir, pattern) {

for (const segment of segments) {
if (segment === "**") {
const descendants = [];
const descendants = [...directories];
const visit = (dir) => {
for (const child of listDirectories(dir)) {
descendants.push(child);
Expand All @@ -130,11 +154,11 @@ function expandWorkspacePattern(rootDir, pattern) {
for (const dir of directories) {
visit(dir);
}
directories = descendants;
directories = Array.from(new Set(descendants));
continue;
}

if (segment.includes("*")) {
if (segmentHasPatternSyntax(segment)) {
const regexp = segmentPatternToRegExp(segment);
directories = directories.flatMap((dir) =>
listDirectories(dir).filter((child) =>
Expand Down
99 changes: 99 additions & 0 deletions test/scripts/workspace-utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { execFileSync } from "node:child_process";
import {
mkdirSync,
readFileSync,
realpathSync,
rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { afterEach, describe, expect, it } from "vitest";

const fixtures: string[] = [];

function makeFixture() {
const root = join(
tmpdir(),
`maestro-workspace-utils-${process.pid}-${Date.now()}-${fixtures.length}`,
);
fixtures.push(root);
return root;
}

function copyScript(root: string, scriptName: string) {
mkdirSync(join(root, "scripts"), { recursive: true });
writeFileSync(
join(root, "scripts", scriptName),
readFileSync(join(process.cwd(), "scripts", scriptName), "utf8"),
);
}

function writePackage(root: string, relativePath: string) {
const packageDir = join(root, relativePath);
mkdirSync(packageDir, { recursive: true });
writeFileSync(
join(packageDir, "package.json"),
JSON.stringify({ name: relativePath.replaceAll("/", "-") }),
);
}

function readWorkspacePaths(root: string) {
const output = execFileSync(process.execPath, ["--input-type=module"], {
cwd: root,
encoding: "utf8",
input: [
'import { getWorkspacePackagePaths, loadRootPackage } from "./scripts/workspace-utils.js";',
"console.log(JSON.stringify(await getWorkspacePackagePaths(loadRootPackage())));",
].join("\n"),
});
return JSON.parse(output).sort();
}

describe("getWorkspacePackagePaths", () => {
afterEach(() => {
for (const fixture of fixtures.splice(0)) {
rmSync(fixture, { recursive: true, force: true });
}
});

it("treats ** as zero or more path segments without glob installed", () => {
const root = makeFixture();
copyScript(root, "workspace-utils.js");
writeFileSync(
join(root, "package.json"),
JSON.stringify({
name: "fixture",
type: "module",
workspaces: ["packages/**/pkg-*"],
}),
);
writePackage(root, "packages/pkg-a");
writePackage(root, "packages/nested/pkg-b");

expect(readWorkspacePaths(root)).toEqual([
realpathSync(resolve(root, "packages/nested/pkg-b/package.json")),
realpathSync(resolve(root, "packages/pkg-a/package.json")),
]);
});

it("treats brace segments as alternatives without glob installed", () => {
const root = makeFixture();
copyScript(root, "workspace-utils.js");
writeFileSync(
join(root, "package.json"),
JSON.stringify({
name: "fixture",
type: "module",
workspaces: ["{packages,apps}/*"],
}),
);
writePackage(root, "apps/app-a");
writePackage(root, "packages/pkg-a");

expect(readWorkspacePaths(root)).toEqual([
realpathSync(resolve(root, "apps/app-a/package.json")),
realpathSync(resolve(root, "packages/pkg-a/package.json")),
]);
});
});
Loading