Skip to content

Optimize yarn workspace discovery #1430

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

Open
wants to merge 6 commits into
base: master
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
Original file line number Diff line number Diff line change
Expand Up @@ -38,42 +38,61 @@ public NullSafePackageJson read(File packageJsonFile) throws IOException {

@NotNull
public Collection<YarnWorkspace> readWorkspacePackageJsonFiles(File workspaceDir) throws IOException {
String forwardSlashedWorkspaceDirPath = deriveForwardSlashedPath(workspaceDir);
File packageJsonFile = new File(workspaceDir, YarnLockDetectable.YARN_PACKAGE_JSON);
List<String> workspaceDirPatterns = extractWorkspaceDirPatterns(packageJsonFile);

if (workspaceDirPatterns.isEmpty()) {
logger.debug("No workspace patterns found in {}", packageJsonFile.getAbsolutePath());
return new LinkedList<>();
}

List<PathMatcher> matchers = convertWorkspaceDirPatternsToPathMatchers(workspaceDirPatterns, workspaceDir);

Collection<YarnWorkspace> workspaces = new LinkedList<>();
for (String workspaceSubdirPattern : workspaceDirPatterns) {
logger.trace("workspaceSubdirPattern: {}", workspaceSubdirPattern);
String globString = String.format("glob:%s/%s/package.json", forwardSlashedWorkspaceDirPath, workspaceSubdirPattern);
logger.trace("workspace subdir globString: {}", globString);
PathMatcher matcher = FileSystems.getDefault().getPathMatcher(globString);
Files.walkFileTree(workspaceDir.toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (matcher.matches(file)) {
logger.trace("\tFound a match: {}", file);
NullSafePackageJson packageJson = read(file.toFile());
Path rel = workspaceDir.toPath().relativize(file.getParent());
WorkspacePackageJson workspacePackageJson = new WorkspacePackageJson(file.toFile(), packageJson, rel.toString());
YarnWorkspace workspace = new YarnWorkspace(workspacePackageJson);
workspaces.add(workspace);

Files.walkFileTree(workspaceDir.toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.getFileName().toString().equals(YarnLockDetectable.YARN_PACKAGE_JSON)) { // no need to try matching if not package.json
for (PathMatcher matcher : matchers) {
if (matcher.matches(file)) {
logger.trace("\tFound a match: {}", file);
NullSafePackageJson packageJson = read(file.toFile());
Path rel = workspaceDir.toPath().relativize(file.getParent());
WorkspacePackageJson workspacePackageJson = new WorkspacePackageJson(file.toFile(), packageJson, rel.toString());
YarnWorkspace workspace = new YarnWorkspace(workspacePackageJson);
workspaces.add(workspace);
break; // no need to match the same file multiple times
}
}
return FileVisitResult.CONTINUE;
}
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
return FileVisitResult.CONTINUE;
}
});

@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
return FileVisitResult.CONTINUE;
}
});
}
if (!workspaceDirPatterns.isEmpty()) {
logger.debug("Found {} matching workspace package.json files for workspaces listed in {}", workspaces.size(), packageJsonFile.getAbsolutePath());
}
return workspaces;
}

private List<PathMatcher> convertWorkspaceDirPatternsToPathMatchers(List<String> workspaceDirPatterns, File workspaceDir) {
List<PathMatcher> matchers = new LinkedList<>();
String forwardSlashedWorkspaceDirPath = deriveForwardSlashedPath(workspaceDir);
for (String workspaceDirPattern : workspaceDirPatterns) {
String globString = String.format("glob:%s/%s/package.json", forwardSlashedWorkspaceDirPath, workspaceDirPattern);
logger.trace("workspace subdir globString: {}", globString);
PathMatcher matcher = FileSystems.getDefault().getPathMatcher(globString);
matchers.add(matcher);
}
return matchers;
}

@NotNull
private String deriveForwardSlashedPath(File file) {
String forwardSlashWorkspaceDirPath;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package com.blackduck.integration.detectable.detectables.yarn.packagejson;

import com.blackduck.integration.detectable.detectables.yarn.workspace.YarnWorkspace;
import com.google.gson.Gson;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Collection;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

class PackageJsonFilesTest {

private PackageJsonReader packageJsonReader;
private PackageJsonFiles packageJsonFiles;
private File tempDir;

@BeforeEach
void setUp() throws IOException {
packageJsonReader = new PackageJsonReader(new Gson());
packageJsonFiles = new PackageJsonFiles(packageJsonReader);
tempDir = Files.createTempDirectory("yarnws").toFile();
}

@AfterEach
void tearDown() throws IOException {
FileUtils.deleteDirectory(tempDir);
}

@Test
void returnsEmptyWhenNoWorkspacePatterns() throws IOException {
// Setup a root package.json with no workspaces
File rootPackageJson = new File(tempDir, "package.json");
Files.write(rootPackageJson.toPath(), "{ \"workspaces\": [] }".getBytes(StandardCharsets.UTF_8));

Collection<YarnWorkspace> result = packageJsonFiles.readWorkspacePackageJsonFiles(tempDir);
assertTrue(result.isEmpty());
}

@Test
void findsWorkspacePackageJsonFiles() throws IOException {
// Setup a root package.json with a workspace pattern
File rootPackageJson = new File(tempDir, "package.json");
Files.write(rootPackageJson.toPath(), "{ \"workspaces\": [\"packages/*\"] }".getBytes(StandardCharsets.UTF_8));

// Create a workspace directory and its package.json
File wsDir = new File(tempDir, "packages/a");
wsDir.mkdirs();
File wsPackageJson = new File(wsDir, "package.json");
Files.write(wsPackageJson.toPath(), "{ \"name\": \"a\" }".getBytes(StandardCharsets.UTF_8));

Collection<YarnWorkspace> result = packageJsonFiles.readWorkspacePackageJsonFiles(tempDir);
assertEquals(1, result.size());

YarnWorkspace foundWorkspace = result.iterator().next();
assertEquals("a", foundWorkspace.getName().orElse(null));
assertEquals(wsPackageJson.getAbsolutePath(), foundWorkspace.getWorkspacePackageJson().getFile().getAbsolutePath());
}

@Test
void findsMultipleWorkspacesWithDoubleWildcard() throws IOException {
// Setup a root package.json with a double wildcard workspace pattern
File rootPackageJson = new File(tempDir, "package.json");
Files.write(rootPackageJson.toPath(), "{ \"workspaces\": [\"packages/**\"] }".getBytes(StandardCharsets.UTF_8));

// Create two workspace directories and their package.json files
File wsDir1 = new File(tempDir, "packages/a");
wsDir1.mkdirs();
File wsPackageJson1 = new File(wsDir1, "package.json");
Files.write(wsPackageJson1.toPath(), "{ \"name\": \"a\" }".getBytes(StandardCharsets.UTF_8));

File wsDir2 = new File(tempDir, "packages/b/subdir");
wsDir2.mkdirs();
File wsPackageJson2 = new File(wsDir2, "package.json");
Files.write(wsPackageJson2.toPath(), "{ \"name\": \"b\" }".getBytes(StandardCharsets.UTF_8));

Collection<YarnWorkspace> result = packageJsonFiles.readWorkspacePackageJsonFiles(tempDir);
assertEquals(2, result.size());

// Verify the workspaces
YarnWorkspace workspaceA = result.stream()
.filter(ws -> "a".equals(ws.getName().orElse(null)))
.findFirst()
.orElseThrow(() -> new AssertionError("Workspace 'a' not found"));
assertEquals(wsPackageJson1.getAbsolutePath(), workspaceA.getWorkspacePackageJson().getFile().getAbsolutePath());

YarnWorkspace workspaceB = result.stream()
.filter(ws -> "b".equals(ws.getName().orElse(null)))
.findFirst()
.orElseThrow(() -> new AssertionError("Workspace 'b' not found"));
assertEquals(wsPackageJson2.getAbsolutePath(), workspaceB.getWorkspacePackageJson().getFile().getAbsolutePath());
}
}