workspace.ts
1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import fs from "node:fs";
import path from "node:path";
/**
* 依赖分析结果接口
*/
export interface DependencyAnalysis {
/** 是否包含 catalog: 类型的依赖 */
hasCatalogDeps: boolean;
/** 是否包含常规版本类型的依赖(如 ^1.0.0、workspace:* 等) */
hasRegularDeps: boolean;
}
/**
* 从指定目录向上递归查找 workspace 根目录
* @param startPath 起始目录
* @returns workspace 根目录路径,如果未找到返回 null
*/
export function findWorkspaceRoot(startPath: string): null | string {
let currentPath = path.resolve(startPath);
while (currentPath !== path.parse(currentPath).root) {
const workspaceFile = path.join(currentPath, "pnpm-workspace.yaml");
if (fs.existsSync(workspaceFile)) {
return currentPath;
}
currentPath = path.dirname(currentPath);
}
return null;
}
/**
* 检查指定目录是否在 pnpm workspace 中
* @param dir 目录路径
* @returns 如果在 workspace 中返回 true
*/
export function isInWorkspace(dir: string): boolean {
return findWorkspaceRoot(dir) !== null;
}
/**
* 分析项目的依赖类型
* @param packageJsonPath package.json 文件路径
* @returns 依赖分析结果
*/
export function analyzeProjectDependencies(packageJsonPath: string): DependencyAnalysis {
try {
if (!fs.existsSync(packageJsonPath)) {
return { hasCatalogDeps: false, hasRegularDeps: false };
}
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
const allDeps = {
...packageJson.dependencies,
...packageJson.devDependencies,
...packageJson.peerDependencies,
...packageJson.optionalDependencies,
};
const deps = Object.values(allDeps);
const hasCatalogDeps = deps.some((dep) => dep === "catalog:");
const hasRegularDeps = deps.some((dep) => typeof dep === "string" && dep !== "catalog:");
return { hasCatalogDeps, hasRegularDeps };
} catch {
// 如果解析失败,返回默认值,避免中断流程
return { hasCatalogDeps: false, hasRegularDeps: false };
}
}