-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathrunner.ts
More file actions
219 lines (188 loc) · 6.66 KB
/
Copy pathrunner.ts
File metadata and controls
219 lines (188 loc) · 6.66 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
#!/usr/bin/env node
/**
* Shared script runner utility
* Provides common functionality for running scripts in each category
*/
import { type ChildProcess, spawn } from 'node:child_process'
import fs from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
interface ScriptMap {
[key: string]: string
}
export interface CategoryConfig {
categoryName: string
includes?: string[]
excludes?: string[]
}
/**
* Run a script file
* @param scriptPath - Path to the script file
*/
export function runScript(scriptPath: string): Promise<void> {
return new Promise((resolve, reject) => {
const child: ChildProcess = spawn('pnpm', ['exec', 'tsx', scriptPath], {
stdio: 'inherit',
shell: false,
})
child.on('close', code => {
if (code === 0) {
resolve()
} else {
reject(new Error(`Script exited with code ${code}`))
}
})
child.on('error', error => {
reject(error)
})
})
}
/**
* Get the directory path for a category
* @param categoryDir - The category directory (e.g., 'generate', 'validate', 'fetch')
* @returns - Full path to the category directory
*/
export function getCategoryDir(categoryDir: string): string {
return path.join(__dirname, '..', categoryDir)
}
/**
* Discover all scripts in a category directory
* @param categoryDir - The category directory path
* @returns - Map of script names to script files
*
* Script names are generated by:
* 1. Removing .ts extension
* 2. If filename starts with category prefix (e.g., "generate-", "fetch-"), remove it
* 3. Otherwise, use the full filename without extension
*
* Examples:
* - "generate-manifest-indexes.ts" in generate/ -> "manifest-indexes"
* - "sort-manifest-fields.ts" in refactor/ -> "sort-manifest-fields" (no prefix)
* - "refactor-sort-fields.ts" in refactor/ -> "sort-fields" (prefix removed)
*/
async function discoverScripts(categoryDir: string): Promise<ScriptMap> {
const scripts: ScriptMap = {}
try {
const entries = await fs.readdir(categoryDir, { withFileTypes: true })
for (const entry of entries) {
// Skip index.ts and non-.ts files
if (entry.isFile() && entry.name.endsWith('.ts') && entry.name !== 'index.ts') {
// Generate script name from filename (without .ts extension)
const baseName = entry.name.replace(/\.ts$/, '')
// Remove category prefix if present (e.g., "generate-", "fetch-")
// If filename doesn't start with prefix, use full name without extension
const categoryPrefix = `${path.basename(categoryDir)}-`
const scriptName = baseName.startsWith(categoryPrefix)
? baseName.slice(categoryPrefix.length)
: baseName
scripts[scriptName] = entry.name
}
}
} catch (error) {
console.error(`Error discovering scripts in ${categoryDir}:`, (error as Error).message)
}
return scripts
}
/**
* Filter scripts based on includes/excludes
* @param scripts - Map of script names to script files
* @param includes - Script names to include (if specified, only these will run)
* Use script name without .ts extension (e.g., 'sort-manifest-fields', 'manifests')
* @param excludes - Script names to exclude
* Use script name without .ts extension (e.g., 'sort-manifest-fields', 'github-stars')
* @returns - Filtered scripts map
*/
function filterScripts(scripts: ScriptMap, includes?: string[], excludes?: string[]): ScriptMap {
let filtered = { ...scripts }
// Apply includes filter
if (includes && includes.length > 0) {
filtered = {}
for (const name of includes) {
if (scripts[name]) {
filtered[name] = scripts[name]
} else {
console.warn(`⚠️ Script "${name}" specified in includes but not found`)
}
}
}
// Apply excludes filter
if (excludes && excludes.length > 0) {
for (const name of excludes) {
if (filtered[name]) {
delete filtered[name]
}
}
}
return filtered
}
/**
* Main runner function
* @param config - Configuration object
* @param config.categoryName - Category name (e.g., 'generate', 'validate', 'fetch')
* @param config.includes - Script names to include (without .ts suffix, e.g., 'manifests', 'urls')
* @param config.excludes - Script names to exclude (without .ts suffix, e.g., 'github-stars')
*/
export async function runCategoryScripts(config: CategoryConfig): Promise<void> {
const { categoryName, includes, excludes } = config
const categoryDir = getCategoryDir(categoryName)
// Auto-discover scripts in the category directory
const allScripts = await discoverScripts(categoryDir)
if (Object.keys(allScripts).length === 0) {
console.error(`❌ No scripts found in ${categoryName}/ directory`)
process.exit(1)
}
// Filter scripts based on includes/excludes
const scripts = filterScripts(allScripts, includes, excludes)
if (Object.keys(scripts).length === 0) {
console.error(`❌ No scripts to run after filtering`)
process.exit(1)
}
const scriptName = process.argv[2]
if (scriptName) {
// Run specific script (bypasses includes/excludes filter)
const scriptFile = allScripts[scriptName]
if (!scriptFile) {
console.error(`❌ Unknown script: ${scriptName}`)
console.error(`\nAvailable scripts:`)
Object.keys(allScripts)
.sort()
.forEach(name => {
console.error(` - ${name}`)
})
process.exit(1)
}
console.log(`🚀 Running ${scriptName}...\n`)
try {
await runScript(path.join(categoryDir, scriptFile))
console.log(`\n✅ ${scriptName} completed successfully`)
} catch (error) {
console.error(`\n❌ ${scriptName} failed:`, (error as Error).message)
process.exit(1)
}
} else {
// Run all filtered scripts in alphabetical order
console.log(`🚀 Running all ${categoryName} scripts...\n`)
const order = Object.keys(scripts).sort()
for (const name of order) {
const scriptFile = scripts[name]
if (!scriptFile) {
console.error(`\n❌ ${name} has no associated script file`)
process.exit(1)
}
console.log(`\n${'='.repeat(60)}`)
console.log(`Running ${name}...`)
console.log('='.repeat(60))
try {
await runScript(path.join(categoryDir, scriptFile))
} catch (error) {
console.error(`\n❌ ${name} failed:`, (error as Error).message)
process.exit(1)
}
}
console.log(`\n${'='.repeat(60)}`)
console.log(`✅ All ${categoryName} scripts completed successfully!`)
console.log('='.repeat(60))
}
}