-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.js
More file actions
361 lines (299 loc) · 11.1 KB
/
build.js
File metadata and controls
361 lines (299 loc) · 11.1 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#!/usr/bin/env node
const crypto = require("crypto");
const fs = require("fs");
const os = require("os");
const path = require("path");
const ejs = require("ejs");
const { pluginTargets } = require("./plugins");
const repoRoot = path.resolve(__dirname, "../..");
const srcRoot = path.join(repoRoot, "src");
const srcSkills = path.join(srcRoot, "skills");
const srcPlugins = path.join(srcRoot, "plugins");
const srcShared = path.join(srcRoot, "shared");
const outPlugins = path.join(repoRoot, "plugins");
const sharedLicense = path.join(repoRoot, "LICENSE");
const pluginVersionsPath = path.join(repoRoot, "plugin-versions.json");
const args = new Set(process.argv.slice(2));
const checkMode = args.has("--check");
const cleanMode = args.has("--clean");
if (![...args].every((arg) => ["--check", "--clean"].includes(arg))) {
fail(`Unknown argument. Supported arguments: --check, --clean`);
}
if (checkMode && cleanMode) {
fail("Use either --check or --clean, not both.");
}
main().catch((error) => {
console.error(error.stack || error.message);
process.exit(1);
});
async function main() {
const mode = cleanMode ? "clean" : checkMode ? "check" : "build";
log(`Starting generated output ${mode}.`);
log(`Targets: ${pluginTargets.map((target) => target.name).join(", ")}.`);
const pluginVersions = await readPluginVersions(pluginTargets.map((target) => target.name));
log(
`Target versions: ${pluginTargets
.map((target) => `${target.name}@${pluginVersions[target.name]}`)
.join(", ")}.`,
);
if (cleanMode) {
log("Cleaning generated outputs.");
for (const target of pluginTargets) {
const removedEntries = await cleanOutputDirectory(path.join(outPlugins, target.name));
log(`Cleaned plugins/${target.name}; removed ${removedEntries} generated entries.`);
}
log("Clean succeeded.");
return;
}
const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "specdd-plugins-"));
const tempPlugins = path.join(tempDir, "plugins");
log(`Rendering expected output trees in ${tempDir}.`);
try {
await renderPluginTrees(pluginTargets, pluginVersions, tempPlugins);
if (checkMode) {
log("Comparing expected output trees with generated outputs.");
const differences = [];
for (const target of pluginTargets) {
const targetDifferences = await compareTrees(
path.join(tempPlugins, target.name),
path.join(outPlugins, target.name),
`plugins/${target.name}`,
);
differences.push(...targetDifferences);
log(
targetDifferences.length === 0
? `Checked plugins/${target.name}; output is current.`
: `Checked plugins/${target.name}; found ${targetDifferences.length} differences.`,
);
}
if (differences.length > 0) {
differences.forEach((difference) => console.error(difference));
throw new Error("Generated outputs are stale. Run `make build`.");
}
log("Check succeeded. Generated outputs are current.");
return;
}
log("Replacing generated outputs.");
for (const target of pluginTargets) {
const outputDir = path.join(outPlugins, target.name);
const removedEntries = await cleanOutputDirectory(outputDir);
log(`Cleaned plugins/${target.name}; removed ${removedEntries} generated entries.`);
const copiedEntries = await copyTree(path.join(tempPlugins, target.name), outputDir);
log(`Copied plugins/${target.name}; wrote ${copiedEntries} generated files.`);
}
log("Build succeeded. Generated outputs were rebuilt.");
} finally {
await fs.promises.rm(tempDir, { recursive: true, force: true });
log("Removed temporary build directory.");
}
}
async function readPluginVersions(pluginNames) {
const versions = JSON.parse(await fs.promises.readFile(pluginVersionsPath, "utf8"));
for (const pluginName of pluginNames) {
const version = versions[pluginName];
if (!version) {
fail(`Missing version for ${pluginName} in plugin-versions.json.`);
}
if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) {
fail(`Invalid semver version for ${pluginName} in plugin-versions.json: ${version}`);
}
}
return versions;
}
async function renderPluginTrees(targets, pluginVersions, targetRoot) {
for (const target of targets) {
const targetDir = path.join(targetRoot, target.name);
log(`Rendering ${target.name} output.`);
const templateData = createTemplateData(target);
const sharedFiles = await copyIncludedFiles(
srcShared,
targetDir,
target.includes.shared,
templateData,
);
log(`Copied ${target.name} shared includes: ${sharedFiles} files.`);
if (fs.existsSync(sharedLicense)) {
await fs.promises.mkdir(targetDir, { recursive: true });
await fs.promises.copyFile(sharedLicense, path.join(targetDir, "LICENSE"));
log(`Copied ${target.name} shared license.`);
}
const packageFiles = await copyIncludedFiles(
path.join(srcPlugins, target.name),
targetDir,
target.includes.plugin,
templateData,
);
log(`Copied ${target.name} package includes: ${packageFiles} files.`);
if (target.manifest) {
await setManifestVersion(targetDir, target.manifest, pluginVersions[target.name]);
log(`Set ${target.name} manifest version to ${pluginVersions[target.name]}.`);
} else {
log(`Skipped ${target.name} manifest version; target has no manifest.`);
}
const targetSkillsDir = path.join(targetDir, target.skillsOutputDir || "skills");
const renderedSkills = await renderSkills(target, targetSkillsDir, templateData);
log(`Rendered ${target.name} skills: ${renderedSkills} skills.`);
log(`Rendered ${target.name} output successfully.`);
}
}
function createTemplateData(target) {
return {
repoRoot,
srcRoot,
target,
agentName: target.agentName,
};
}
async function setManifestVersion(targetDir, manifestRelativePath, version) {
const manifestPath = path.join(targetDir, manifestRelativePath);
const manifest = JSON.parse(await fs.promises.readFile(manifestPath, "utf8"));
manifest.version = version;
await writeText(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
}
async function renderSkills(target, targetSkillsDir, templateData) {
const skillEntries = await fs.promises.readdir(srcSkills, { withFileTypes: true });
skillEntries.sort((left, right) => left.name.localeCompare(right.name));
let renderedSkills = 0;
for (const entry of skillEntries) {
if (!entry.isDirectory()) {
continue;
}
await copyIncludedFiles(
path.join(srcSkills, entry.name),
path.join(targetSkillsDir, entry.name),
target.includes.skills,
templateData,
);
renderedSkills += 1;
}
return renderedSkills;
}
async function copyIncludedFiles(sourceDir, targetDir, includes, templateData) {
let copiedFiles = 0;
for (const includePath of includes) {
const sourcePath = path.join(sourceDir, includePath);
const targetName = includePath.endsWith(".ejs") ? includePath.slice(0, -4) : includePath;
const targetPath = path.join(targetDir, targetName);
await copyOrRenderFile(sourcePath, targetPath, templateData);
copiedFiles += 1;
}
return copiedFiles;
}
async function copyOrRenderFile(sourcePath, targetPath, templateData) {
await fs.promises.mkdir(path.dirname(targetPath), { recursive: true });
if (sourcePath.endsWith(".ejs")) {
const rendered = await ejs.renderFile(
sourcePath,
templateData,
{
root: srcRoot,
views: [srcRoot],
filename: sourcePath,
},
);
await writeText(targetPath, ensureTrailingNewline(rendered));
return;
}
await fs.promises.copyFile(sourcePath, targetPath);
}
async function copyTree(sourceDir, targetDir) {
const entries = await fs.promises.readdir(sourceDir, { withFileTypes: true });
entries.sort((left, right) => left.name.localeCompare(right.name));
await fs.promises.mkdir(targetDir, { recursive: true });
let copiedFiles = 0;
for (const entry of entries) {
const sourcePath = path.join(sourceDir, entry.name);
const targetPath = path.join(targetDir, entry.name);
if (entry.isDirectory()) {
copiedFiles += await copyTree(sourcePath, targetPath);
} else if (entry.isFile() && !entry.name.endsWith(".sdd")) {
await fs.promises.mkdir(path.dirname(targetPath), { recursive: true });
await fs.promises.copyFile(sourcePath, targetPath);
copiedFiles += 1;
}
}
return copiedFiles;
}
async function cleanOutputDirectory(outputDir) {
await fs.promises.mkdir(outputDir, { recursive: true });
const entries = await fs.promises.readdir(outputDir, { withFileTypes: true });
let removedEntries = 0;
for (const entry of entries) {
if (entry.name === ".git") {
continue;
}
await fs.promises.rm(path.join(outputDir, entry.name), {
recursive: true,
force: true,
});
removedEntries += 1;
}
return removedEntries;
}
async function compareTrees(expectedDir, actualDir, label) {
const expectedFiles = await listFiles(expectedDir);
const actualFiles = await listFiles(actualDir);
const differences = [];
const allFiles = Array.from(new Set([...expectedFiles.keys(), ...actualFiles.keys()])).sort();
for (const relativePath of allFiles) {
const expectedPath = expectedFiles.get(relativePath);
const actualPath = actualFiles.get(relativePath);
if (!expectedPath) {
differences.push(`Unexpected generated file: ${label}/${relativePath}`);
continue;
}
if (!actualPath) {
differences.push(`Missing generated file: ${label}/${relativePath}`);
continue;
}
const [expectedHash, actualHash] = await Promise.all([
hashFile(expectedPath),
hashFile(actualPath),
]);
if (expectedHash !== actualHash) {
differences.push(`Changed generated file: ${label}/${relativePath}`);
}
}
return differences;
}
async function listFiles(rootDir) {
const files = new Map();
if (!fs.existsSync(rootDir)) {
return files;
}
await walk(rootDir);
return files;
async function walk(currentDir) {
const entries = await fs.promises.readdir(currentDir, { withFileTypes: true });
entries.sort((left, right) => left.name.localeCompare(right.name));
for (const entry of entries) {
if (entry.name === ".git") {
continue;
}
const entryPath = path.join(currentDir, entry.name);
if (entry.isDirectory()) {
await walk(entryPath);
} else if (entry.isFile()) {
files.set(path.relative(rootDir, entryPath), entryPath);
}
}
}
}
async function hashFile(filePath) {
const content = await fs.promises.readFile(filePath);
return crypto.createHash("sha256").update(content).digest("hex");
}
async function writeText(filePath, content) {
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
await fs.promises.writeFile(filePath, content, "utf8");
}
function ensureTrailingNewline(content) {
return content.endsWith("\n") ? content : `${content}\n`;
}
function log(message) {
console.log(`[build] ${message}`);
}
function fail(message) {
console.error(message);
process.exit(1);
}