-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathworkspace-patterns.ts
More file actions
273 lines (237 loc) · 6.83 KB
/
Copy pathworkspace-patterns.ts
File metadata and controls
273 lines (237 loc) · 6.83 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import { existsSync, readFileSync, readdirSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { parse as parseYaml } from 'yaml'
import { findSkillFiles } from './utils.js'
function normalizeWorkspacePattern(pattern: string): string {
return pattern.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '')
}
function normalizeWorkspacePatterns(patterns: Array<string>): Array<string> {
return [
...new Set(patterns.map(normalizeWorkspacePattern).filter(Boolean)),
].sort((a, b) => a.localeCompare(b))
}
function parseWorkspacePatterns(value: unknown): Array<string> | null {
if (!Array.isArray(value)) {
return null
}
return normalizeWorkspacePatterns(
value.filter((pattern): pattern is string => typeof pattern === 'string'),
)
}
function hasPackageJson(dir: string): boolean {
return existsSync(join(dir, 'package.json'))
}
function stripJsonCommentsAndTrailingCommas(source: string): string {
let result = ''
let inString = false
let escaped = false
for (let index = 0; index < source.length; index += 1) {
const char = source[index]!
const next = source[index + 1]
if (inString) {
result += char
if (escaped) {
escaped = false
} else if (char === '\\') {
escaped = true
} else if (char === '"') {
inString = false
}
continue
}
if (char === '"') {
inString = true
result += char
continue
}
if (char === '/' && next === '/') {
while (index < source.length && source[index] !== '\n') {
index += 1
}
if (index < source.length) {
result += source[index]!
}
continue
}
if (char === '/' && next === '*') {
index += 2
while (
index < source.length &&
!(source[index] === '*' && source[index + 1] === '/')
) {
index += 1
}
index += 1
continue
}
if (char === ',') {
let lookahead = index + 1
while (lookahead < source.length && /\s/.test(source[lookahead]!)) {
lookahead += 1
}
if (source[lookahead] === '}' || source[lookahead] === ']') {
continue
}
}
result += char
}
return result
}
function readJsonFile(path: string, jsonc = false): unknown {
const source = readFileSync(path, 'utf8')
return JSON.parse(jsonc ? stripJsonCommentsAndTrailingCommas(source) : source)
}
export function readWorkspacePatterns(root: string): Array<string> | null {
const pnpmWs = join(root, 'pnpm-workspace.yaml')
if (existsSync(pnpmWs)) {
try {
const config = parseYaml(readFileSync(pnpmWs, 'utf8')) as Record<
string,
unknown
>
const patterns = parseWorkspacePatterns(config.packages)
if (patterns) {
return patterns
}
} catch (err: unknown) {
console.error(
`Warning: failed to parse ${pnpmWs}: ${err instanceof Error ? err.message : err}`,
)
}
}
const pkgPath = join(root, 'package.json')
if (existsSync(pkgPath)) {
try {
const pkg = readJsonFile(pkgPath) as {
workspaces?: unknown | { packages?: unknown }
}
const patterns =
parseWorkspacePatterns(pkg.workspaces) ??
parseWorkspacePatterns(
typeof pkg.workspaces === 'object' && pkg.workspaces !== null
? (pkg.workspaces as Record<string, unknown>).packages
: undefined,
)
if (patterns) {
return patterns
}
} catch (err: unknown) {
console.error(
`Warning: failed to parse ${pkgPath}: ${err instanceof Error ? err.message : err}`,
)
}
}
for (const denoConfigName of ['deno.json', 'deno.jsonc']) {
const denoConfigPath = join(root, denoConfigName)
if (!existsSync(denoConfigPath)) {
continue
}
try {
const denoConfig = readJsonFile(
denoConfigPath,
denoConfigName.endsWith('.jsonc'),
) as {
workspace?: unknown
}
const patterns = parseWorkspacePatterns(denoConfig.workspace)
if (patterns) {
return patterns
}
} catch (err: unknown) {
console.error(
`Warning: failed to parse ${denoConfigPath}: ${err instanceof Error ? err.message : err}`,
)
}
}
return null
}
export function resolveWorkspacePackages(
root: string,
patterns: Array<string>,
): Array<string> {
const includedDirs = new Set<string>()
const excludedDirs = new Set<string>()
for (const pattern of normalizeWorkspacePatterns(patterns)) {
if (pattern.startsWith('!')) {
resolveWorkspacePatternSegments(
root,
pattern.slice(1).split('/'),
excludedDirs,
)
continue
}
resolveWorkspacePatternSegments(root, pattern.split('/'), includedDirs)
}
return [...includedDirs]
.filter((dir) => !excludedDirs.has(dir))
.sort((a, b) => a.localeCompare(b))
}
/** Recursively matches path segments: `*` matches one level, `**` matches zero or more levels. */
function resolveWorkspacePatternSegments(
dir: string,
segments: Array<string>,
result: Set<string>,
): void {
if (segments.length === 0) {
if (hasPackageJson(dir)) {
result.add(dir)
}
return
}
const segment = segments[0]!
const remainingSegments = segments.slice(1)
if (segment === '**') {
resolveWorkspacePatternSegments(dir, remainingSegments, result)
for (const childDir of readChildDirectories(dir)) {
resolveWorkspacePatternSegments(childDir, segments, result)
}
return
}
if (segment === '*') {
for (const childDir of readChildDirectories(dir)) {
resolveWorkspacePatternSegments(childDir, remainingSegments, result)
}
return
}
const nextDir = join(dir, segment)
if (!existsSync(nextDir)) {
return
}
resolveWorkspacePatternSegments(nextDir, remainingSegments, result)
}
function readChildDirectories(dir: string): Array<string> {
try {
return readdirSync(dir, { withFileTypes: true })
.filter(
(entry) =>
entry.isDirectory() &&
entry.name !== 'node_modules' &&
!entry.name.startsWith('.'),
)
.map((entry) => join(dir, entry.name))
} catch (err: unknown) {
console.error(
`Warning: could not read directory ${dir}: ${err instanceof Error ? err.message : err}`,
)
return []
}
}
export function findWorkspaceRoot(start: string): string | null {
let dir = start
while (true) {
if (readWorkspacePatterns(dir)) {
return dir
}
const next = dirname(dir)
if (next === dir) return null
dir = next
}
}
export function findPackagesWithSkills(root: string): Array<string> {
const patterns = readWorkspacePatterns(root)
if (!patterns) return []
return resolveWorkspacePackages(root, patterns).filter((dir) => {
const skillsDir = join(dir, 'skills')
return existsSync(skillsDir) && findSkillFiles(skillsDir).length > 0
})
}