( packageFolderOrPubspecPath: string, existsSync: (itemPath: string) => boolean = fs.existsSync, readFileSync: (itemPath: string) => string = (p) => fs.readFileSync(p, "utf8").toString(), )
| 309 | * containing folder). |
| 310 | */ |
| 311 | export function getPubWorkspaceFolderOrPackageFolderPath( |
| 312 | packageFolderOrPubspecPath: string, |
| 313 | existsSync: (itemPath: string) => boolean = fs.existsSync, |
| 314 | readFileSync: (itemPath: string) => string = (p) => fs.readFileSync(p, "utf8").toString(), |
| 315 | ): string { |
| 316 | const pubspecPath = path.basename(packageFolderOrPubspecPath) === "pubspec.yaml" |
| 317 | ? packageFolderOrPubspecPath |
| 318 | : path.join(packageFolderOrPubspecPath, "pubspec.yaml"); |
| 319 | const packageFolderPath = path.dirname(pubspecPath); |
| 320 | |
| 321 | // We shouldn't really have gotten here without a pubspec because that means this isn't |
| 322 | // a package, but in that case just return the containing folder. |
| 323 | if (!existsSync(pubspecPath)) |
| 324 | return packageFolderPath; |
| 325 | |
| 326 | let pubspecContent: string; |
| 327 | try { |
| 328 | pubspecContent = readFileSync(pubspecPath); |
| 329 | } catch { |
| 330 | return packageFolderPath; |
| 331 | } |
| 332 | |
| 333 | // If this is not a Pub Workspace project, just return the package itself. |
| 334 | if (!pubspecIsWorkspaceProjectRegex.test(pubspecContent)) |
| 335 | return packageFolderPath; |
| 336 | |
| 337 | // Walk up the tree to find the workspace root. |
| 338 | let currentFolder = path.dirname(packageFolderPath); |
| 339 | while (true) { |
| 340 | // Check if the current folder is the workspace root |
| 341 | try { |
| 342 | const currentPubspecPath = path.join(currentFolder, "pubspec.yaml"); |
| 343 | const currentPubspecContent = readFileSync(currentPubspecPath); |
| 344 | |
| 345 | // We've found the root. |
| 346 | if (pubspecIsWorkspaceRootRegex.test(currentPubspecContent)) |
| 347 | return currentFolder; |
| 348 | } catch { |
| 349 | // A pubspec may not exist at every level. |
| 350 | } |
| 351 | |
| 352 | // Otherwise, continue up. |
| 353 | const parent = path.dirname(currentFolder); |
| 354 | |
| 355 | // If we get to the root of the filesystem without finding, use the original package. |
| 356 | if (parent === currentFolder) |
| 357 | return packageFolderPath; |
| 358 | |
| 359 | // Otherwise, loop. |
| 360 | currentFolder = parent; |
| 361 | } |
| 362 | } |
no test coverage detected