@canonical/summon-core 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +459 -0
- package/package.json +59 -0
- package/src/cli-types.ts +59 -0
- package/src/discovery/discoverGeneratorTree.ts +449 -0
- package/src/discovery/generatorCache.ts +16 -0
- package/src/discovery/index.ts +3 -0
- package/src/discovery/types.ts +18 -0
- package/src/index.ts +66 -0
- package/src/stamp.ts +165 -0
- package/src/template.test.ts +666 -0
- package/src/template.ts +543 -0
- package/src/types.ts +97 -0
package/src/template.ts
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Template Engine
|
|
3
|
+
*
|
|
4
|
+
* This module provides template rendering utilities for generators.
|
|
5
|
+
* Templates are a key part of code generation, allowing dynamic file creation.
|
|
6
|
+
*
|
|
7
|
+
* By default uses EJS, but supports custom templating engines via the
|
|
8
|
+
* TemplatingEngine interface.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import * as path from "node:path";
|
|
12
|
+
import {
|
|
13
|
+
glob,
|
|
14
|
+
mkdir,
|
|
15
|
+
readFile,
|
|
16
|
+
sequence_,
|
|
17
|
+
type Task,
|
|
18
|
+
task,
|
|
19
|
+
writeFile,
|
|
20
|
+
} from "@canonical/task";
|
|
21
|
+
import ejs from "ejs";
|
|
22
|
+
|
|
23
|
+
// =============================================================================
|
|
24
|
+
// Templating Engine Interface
|
|
25
|
+
// =============================================================================
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Abstract interface for templating engines.
|
|
29
|
+
*
|
|
30
|
+
* Implement this interface to use alternative template engines
|
|
31
|
+
* (e.g., Handlebars, Mustache, Nunjucks) with the summon generator.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```ts
|
|
35
|
+
* const handlebarsEngine: TemplatingEngine = {
|
|
36
|
+
* render: (tpl, vars) => Handlebars.compile(tpl)(vars),
|
|
37
|
+
* renderAsync: async (tpl, vars) => Handlebars.compile(tpl)(vars),
|
|
38
|
+
* renderFile: async (path, vars) => {
|
|
39
|
+
* const tpl = await fs.readFile(path, "utf-8");
|
|
40
|
+
* return Handlebars.compile(tpl)(vars);
|
|
41
|
+
* },
|
|
42
|
+
* };
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
export interface TemplatingEngine {
|
|
46
|
+
/**
|
|
47
|
+
* Render a template string with variables (synchronous).
|
|
48
|
+
* Used for quick inline rendering like destination paths.
|
|
49
|
+
*/
|
|
50
|
+
render(template: string, vars: Record<string, unknown>): string;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Render a template string with variables (asynchronous).
|
|
54
|
+
* Useful when templates may include async operations.
|
|
55
|
+
*/
|
|
56
|
+
renderAsync(template: string, vars: Record<string, unknown>): Promise<string>;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Render a template file with variables (asynchronous).
|
|
60
|
+
* Implementations may leverage caching or streaming.
|
|
61
|
+
*/
|
|
62
|
+
renderFile(
|
|
63
|
+
templatePath: string,
|
|
64
|
+
vars: Record<string, unknown>,
|
|
65
|
+
): Promise<string>;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// =============================================================================
|
|
69
|
+
// EJS Engine Implementation
|
|
70
|
+
// =============================================================================
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Default EJS templating engine implementation.
|
|
74
|
+
*/
|
|
75
|
+
export const ejsEngine: TemplatingEngine = {
|
|
76
|
+
render(template, vars) {
|
|
77
|
+
return ejs.render(template, vars, { async: false });
|
|
78
|
+
},
|
|
79
|
+
|
|
80
|
+
async renderAsync(template, vars) {
|
|
81
|
+
return ejs.render(template, vars, { async: true }) as Promise<string>;
|
|
82
|
+
},
|
|
83
|
+
|
|
84
|
+
async renderFile(templatePath, vars) {
|
|
85
|
+
return ejs.renderFile(templatePath, vars, { async: true });
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
// =============================================================================
|
|
90
|
+
// Stamp Options
|
|
91
|
+
// =============================================================================
|
|
92
|
+
|
|
93
|
+
export interface StampOptions {
|
|
94
|
+
/** Generator name (e.g., "@canonical/summon-package") */
|
|
95
|
+
generator: string;
|
|
96
|
+
/** Generator version (e.g., "0.1.0") */
|
|
97
|
+
version: string;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// =============================================================================
|
|
101
|
+
// Template Options
|
|
102
|
+
// =============================================================================
|
|
103
|
+
|
|
104
|
+
export interface TemplateOptions {
|
|
105
|
+
/** Path to the template file */
|
|
106
|
+
source: string;
|
|
107
|
+
/** Destination path (can contain template variables) */
|
|
108
|
+
dest: string;
|
|
109
|
+
/** Variables to pass to the template */
|
|
110
|
+
vars: Record<string, unknown>;
|
|
111
|
+
/** Templating engine to use (defaults to EJS) */
|
|
112
|
+
engine?: TemplatingEngine;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface TemplateDirOptions {
|
|
116
|
+
/** Source directory containing templates */
|
|
117
|
+
source: string;
|
|
118
|
+
/** Destination directory */
|
|
119
|
+
dest: string;
|
|
120
|
+
/** Variables to pass to all templates */
|
|
121
|
+
vars: Record<string, unknown>;
|
|
122
|
+
/** File rename mappings (original -> new name, supports template vars) */
|
|
123
|
+
rename?: Record<string, string>;
|
|
124
|
+
/** Glob patterns to ignore */
|
|
125
|
+
ignore?: string[];
|
|
126
|
+
/** Content transformers by file extension or name */
|
|
127
|
+
transform?: Record<string, (content: string) => string>;
|
|
128
|
+
/** Templating engine to use (defaults to EJS) */
|
|
129
|
+
engine?: TemplatingEngine;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// =============================================================================
|
|
133
|
+
// String Rendering
|
|
134
|
+
// =============================================================================
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Render a template string with variables.
|
|
138
|
+
* @param engine - Templating engine to use (defaults to EJS)
|
|
139
|
+
*/
|
|
140
|
+
export const renderString = (
|
|
141
|
+
template: string,
|
|
142
|
+
vars: Record<string, unknown>,
|
|
143
|
+
engine: TemplatingEngine = ejsEngine,
|
|
144
|
+
): string => {
|
|
145
|
+
return engine.render(template, vars);
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Render a template string asynchronously.
|
|
150
|
+
* @param engine - Templating engine to use (defaults to EJS)
|
|
151
|
+
*/
|
|
152
|
+
export const renderStringAsync = async (
|
|
153
|
+
template: string,
|
|
154
|
+
vars: Record<string, unknown>,
|
|
155
|
+
engine: TemplatingEngine = ejsEngine,
|
|
156
|
+
): Promise<string> => {
|
|
157
|
+
return engine.renderAsync(template, vars);
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
// =============================================================================
|
|
161
|
+
// File Rendering
|
|
162
|
+
// =============================================================================
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Render a template file with variables.
|
|
166
|
+
* @param engine - Templating engine to use (defaults to EJS)
|
|
167
|
+
*/
|
|
168
|
+
export const renderFile = async (
|
|
169
|
+
templatePath: string,
|
|
170
|
+
vars: Record<string, unknown>,
|
|
171
|
+
engine: TemplatingEngine = ejsEngine,
|
|
172
|
+
): Promise<string> => {
|
|
173
|
+
return engine.renderFile(templatePath, vars);
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// =============================================================================
|
|
177
|
+
// Template Tasks
|
|
178
|
+
// =============================================================================
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Render a single template file to a destination.
|
|
182
|
+
*/
|
|
183
|
+
export const template = (options: TemplateOptions): Task<void> => {
|
|
184
|
+
const engine = options.engine ?? ejsEngine;
|
|
185
|
+
|
|
186
|
+
// Render destination path with variables
|
|
187
|
+
const destPath = renderString(options.dest, options.vars, engine);
|
|
188
|
+
const destDir = path.dirname(destPath);
|
|
189
|
+
|
|
190
|
+
return task(mkdir(destDir))
|
|
191
|
+
.chain(() => task(readFile(options.source)))
|
|
192
|
+
.map((content) => renderString(content, options.vars, engine))
|
|
193
|
+
.chain((rendered) => task(writeFile(destPath, rendered)))
|
|
194
|
+
.unwrap();
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Render a directory of templates to a destination.
|
|
199
|
+
*/
|
|
200
|
+
export const templateDir = (options: TemplateDirOptions): Task<void> => {
|
|
201
|
+
const engine = options.engine ?? ejsEngine;
|
|
202
|
+
|
|
203
|
+
return task(glob("**/*", options.source))
|
|
204
|
+
.chain((files) => {
|
|
205
|
+
const tasks = files
|
|
206
|
+
.filter((file) => {
|
|
207
|
+
// Filter out ignored patterns
|
|
208
|
+
if (options.ignore) {
|
|
209
|
+
return !options.ignore.some((pattern) => minimatch(file, pattern));
|
|
210
|
+
}
|
|
211
|
+
return true;
|
|
212
|
+
})
|
|
213
|
+
.map((file) => {
|
|
214
|
+
const sourcePath = path.join(options.source, file);
|
|
215
|
+
|
|
216
|
+
// Remove .ejs extension if present
|
|
217
|
+
let destFile = file.replace(/\.ejs$/, "");
|
|
218
|
+
|
|
219
|
+
// Apply renames
|
|
220
|
+
const renamed = options.rename?.[destFile];
|
|
221
|
+
if (renamed) {
|
|
222
|
+
destFile = renamed;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Render destination path with variables
|
|
226
|
+
destFile = renderString(destFile, options.vars, engine);
|
|
227
|
+
const destPath = path.join(options.dest, destFile);
|
|
228
|
+
|
|
229
|
+
return template({
|
|
230
|
+
source: sourcePath,
|
|
231
|
+
dest: destPath,
|
|
232
|
+
vars: options.vars,
|
|
233
|
+
engine,
|
|
234
|
+
});
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
return task(sequence_(tasks));
|
|
238
|
+
})
|
|
239
|
+
.unwrap();
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Simple minimatch implementation for common patterns.
|
|
244
|
+
*/
|
|
245
|
+
const minimatch = (filepath: string, pattern: string): boolean => {
|
|
246
|
+
// Convert glob pattern to regex
|
|
247
|
+
const regex = pattern
|
|
248
|
+
.replace(/\./g, "\\.")
|
|
249
|
+
.replace(/\*\*/g, "<<GLOBSTAR>>")
|
|
250
|
+
.replace(/\*/g, "[^/]*")
|
|
251
|
+
.replace(/<<GLOBSTAR>>/g, ".*");
|
|
252
|
+
|
|
253
|
+
return new RegExp(`^${regex}$`).test(filepath);
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
// =============================================================================
|
|
257
|
+
// Template Helpers
|
|
258
|
+
// =============================================================================
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Common template helpers that can be passed to templates.
|
|
262
|
+
*/
|
|
263
|
+
export const templateHelpers = {
|
|
264
|
+
/**
|
|
265
|
+
* Convert a string to camelCase.
|
|
266
|
+
*/
|
|
267
|
+
camelCase: (str: string): string => {
|
|
268
|
+
return str
|
|
269
|
+
.replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ""))
|
|
270
|
+
.replace(/^[A-Z]/, (c) => c.toLowerCase());
|
|
271
|
+
},
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Convert a string to PascalCase.
|
|
275
|
+
*/
|
|
276
|
+
pascalCase: (str: string): string => {
|
|
277
|
+
const camel = templateHelpers.camelCase(str);
|
|
278
|
+
return camel.charAt(0).toUpperCase() + camel.slice(1);
|
|
279
|
+
},
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Convert a string to kebab-case.
|
|
283
|
+
*/
|
|
284
|
+
kebabCase: (str: string): string => {
|
|
285
|
+
return str
|
|
286
|
+
.replace(/([a-z])([A-Z])/g, "$1-$2")
|
|
287
|
+
.replace(/[\s_]+/g, "-")
|
|
288
|
+
.toLowerCase();
|
|
289
|
+
},
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Convert a string to snake_case.
|
|
293
|
+
*/
|
|
294
|
+
snakeCase: (str: string): string => {
|
|
295
|
+
return str
|
|
296
|
+
.replace(/([a-z])([A-Z])/g, "$1_$2")
|
|
297
|
+
.replace(/[\s-]+/g, "_")
|
|
298
|
+
.toLowerCase();
|
|
299
|
+
},
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Convert a string to CONSTANT_CASE.
|
|
303
|
+
*/
|
|
304
|
+
constantCase: (str: string): string => {
|
|
305
|
+
return templateHelpers.snakeCase(str).toUpperCase();
|
|
306
|
+
},
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Capitalize the first letter of a string.
|
|
310
|
+
*/
|
|
311
|
+
capitalize: (str: string): string => {
|
|
312
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
313
|
+
},
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Get the current date in ISO format.
|
|
317
|
+
*/
|
|
318
|
+
isoDate: (): string => new Date().toISOString(),
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Get the current year.
|
|
322
|
+
*/
|
|
323
|
+
year: (): number => new Date().getFullYear(),
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Indent a multi-line string.
|
|
327
|
+
*/
|
|
328
|
+
indent: (str: string, spaces: number): string => {
|
|
329
|
+
const pad = " ".repeat(spaces);
|
|
330
|
+
return str
|
|
331
|
+
.split("\n")
|
|
332
|
+
.map((line) => pad + line)
|
|
333
|
+
.join("\n");
|
|
334
|
+
},
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Join array items with a separator.
|
|
338
|
+
*/
|
|
339
|
+
join: (arr: unknown[], separator = ", "): string => {
|
|
340
|
+
return arr.map(String).join(separator);
|
|
341
|
+
},
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Pluralize a word based on count.
|
|
345
|
+
*/
|
|
346
|
+
pluralize: (word: string, count: number): string => {
|
|
347
|
+
return count === 1 ? word : `${word}s`;
|
|
348
|
+
},
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Create a vars object with helpers included.
|
|
353
|
+
*/
|
|
354
|
+
export const withHelpers = (
|
|
355
|
+
vars: Record<string, unknown>,
|
|
356
|
+
): Record<string, unknown> => ({
|
|
357
|
+
...templateHelpers,
|
|
358
|
+
...vars,
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
// =============================================================================
|
|
362
|
+
// Generator Metadata Comment
|
|
363
|
+
// =============================================================================
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Generate a metadata comment for generated files.
|
|
367
|
+
*/
|
|
368
|
+
export const generatorComment = (
|
|
369
|
+
generatorName: string,
|
|
370
|
+
options?: {
|
|
371
|
+
version?: string;
|
|
372
|
+
timestamp?: boolean;
|
|
373
|
+
},
|
|
374
|
+
): string => {
|
|
375
|
+
const parts = [`Generated by ${generatorName}`];
|
|
376
|
+
|
|
377
|
+
if (options?.version) {
|
|
378
|
+
parts.push(`v${options.version}`);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
if (options?.timestamp) {
|
|
382
|
+
parts.push(`on ${new Date().toISOString()}`);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
return `// ${parts.join(" ")}`;
|
|
386
|
+
};
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Generate a metadata comment as an HTML comment.
|
|
390
|
+
*/
|
|
391
|
+
export const generatorHtmlComment = (
|
|
392
|
+
generatorName: string,
|
|
393
|
+
options?: {
|
|
394
|
+
version?: string;
|
|
395
|
+
timestamp?: boolean;
|
|
396
|
+
},
|
|
397
|
+
): string => {
|
|
398
|
+
const parts = [`Generated by ${generatorName}`];
|
|
399
|
+
|
|
400
|
+
if (options?.version) {
|
|
401
|
+
parts.push(`v${options.version}`);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
if (options?.timestamp) {
|
|
405
|
+
parts.push(`on ${new Date().toISOString()}`);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
return `<!-- ${parts.join(" ")} -->`;
|
|
409
|
+
};
|
|
410
|
+
|
|
411
|
+
// =============================================================================
|
|
412
|
+
// Generated File Stamp
|
|
413
|
+
// =============================================================================
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Comment style configuration for different file types.
|
|
417
|
+
*/
|
|
418
|
+
interface CommentStyle {
|
|
419
|
+
/** Single line comment prefix (e.g., "//") */
|
|
420
|
+
single?: string;
|
|
421
|
+
/** Block comment start (e.g., slash-star) */
|
|
422
|
+
blockStart?: string;
|
|
423
|
+
/** Block comment end (e.g., star-slash) */
|
|
424
|
+
blockEnd?: string;
|
|
425
|
+
/** Use block style even for single line (e.g., for CSS) */
|
|
426
|
+
preferBlock?: boolean;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Map of file extensions to comment styles.
|
|
431
|
+
*/
|
|
432
|
+
const COMMENT_STYLES: Record<string, CommentStyle> = {
|
|
433
|
+
// JavaScript/TypeScript family
|
|
434
|
+
".ts": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
435
|
+
".tsx": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
436
|
+
".js": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
437
|
+
".jsx": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
438
|
+
".mjs": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
439
|
+
".cjs": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
440
|
+
|
|
441
|
+
// CSS family (prefer block comments)
|
|
442
|
+
".css": { blockStart: "/*", blockEnd: "*/", preferBlock: true },
|
|
443
|
+
".scss": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
444
|
+
".sass": { single: "//" },
|
|
445
|
+
".less": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
446
|
+
|
|
447
|
+
// HTML/XML family
|
|
448
|
+
".html": { blockStart: "<!--", blockEnd: "-->" },
|
|
449
|
+
".htm": { blockStart: "<!--", blockEnd: "-->" },
|
|
450
|
+
".xml": { blockStart: "<!--", blockEnd: "-->" },
|
|
451
|
+
".svg": { blockStart: "<!--", blockEnd: "-->" },
|
|
452
|
+
".vue": { blockStart: "<!--", blockEnd: "-->" },
|
|
453
|
+
".svelte": { blockStart: "<!--", blockEnd: "-->" },
|
|
454
|
+
|
|
455
|
+
// Config files
|
|
456
|
+
".json": {}, // JSON doesn't support comments - skip stamp
|
|
457
|
+
".yaml": { single: "#" },
|
|
458
|
+
".yml": { single: "#" },
|
|
459
|
+
".toml": { single: "#" },
|
|
460
|
+
|
|
461
|
+
// Shell/scripting
|
|
462
|
+
".sh": { single: "#" },
|
|
463
|
+
".bash": { single: "#" },
|
|
464
|
+
".zsh": { single: "#" },
|
|
465
|
+
".fish": { single: "#" },
|
|
466
|
+
".py": { single: "#" },
|
|
467
|
+
".rb": { single: "#" },
|
|
468
|
+
".pl": { single: "#" },
|
|
469
|
+
|
|
470
|
+
// Other languages
|
|
471
|
+
".go": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
472
|
+
".rs": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
473
|
+
".java": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
474
|
+
".kt": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
475
|
+
".swift": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
476
|
+
".c": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
477
|
+
".cpp": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
478
|
+
".h": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
479
|
+
".hpp": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
480
|
+
".php": { single: "//", blockStart: "/*", blockEnd: "*/" },
|
|
481
|
+
|
|
482
|
+
// Documentation
|
|
483
|
+
".md": { blockStart: "<!--", blockEnd: "-->" },
|
|
484
|
+
".mdx": { blockStart: "{/*", blockEnd: "*/}" },
|
|
485
|
+
|
|
486
|
+
// SQL
|
|
487
|
+
".sql": { single: "--", blockStart: "/*", blockEnd: "*/" },
|
|
488
|
+
};
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Get the comment style for a given file path.
|
|
492
|
+
*/
|
|
493
|
+
export const getCommentStyle = (filePath: string): CommentStyle | null => {
|
|
494
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
495
|
+
return COMMENT_STYLES[ext] ?? null;
|
|
496
|
+
};
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* Generate a stamp comment for a generated file.
|
|
500
|
+
* Returns null if the file type doesn't support comments.
|
|
501
|
+
*/
|
|
502
|
+
export const generateStamp = (
|
|
503
|
+
filePath: string,
|
|
504
|
+
options: StampOptions,
|
|
505
|
+
): string | null => {
|
|
506
|
+
const style = getCommentStyle(filePath);
|
|
507
|
+
if (!style) return null;
|
|
508
|
+
|
|
509
|
+
// Skip if no comment syntax available
|
|
510
|
+
if (!style.single && !style.blockStart) return null;
|
|
511
|
+
|
|
512
|
+
const stampText = `Generated by ${options.generator} v${options.version}`;
|
|
513
|
+
|
|
514
|
+
// Use block style if preferred or single not available
|
|
515
|
+
if (style.preferBlock || (!style.single && style.blockStart)) {
|
|
516
|
+
return `${style.blockStart} ${stampText} ${style.blockEnd}`;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// Use single line style
|
|
520
|
+
if (style.single) {
|
|
521
|
+
return `${style.single} ${stampText}`;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
return null;
|
|
525
|
+
};
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Prepend a stamp to file content.
|
|
529
|
+
* Handles shebang lines (#!/...) by placing stamp after them.
|
|
530
|
+
*/
|
|
531
|
+
export const prependStamp = (content: string, stamp: string): string => {
|
|
532
|
+
// Check for shebang
|
|
533
|
+
if (content.startsWith("#!")) {
|
|
534
|
+
const firstNewline = content.indexOf("\n");
|
|
535
|
+
if (firstNewline !== -1) {
|
|
536
|
+
const shebang = content.slice(0, firstNewline + 1);
|
|
537
|
+
const rest = content.slice(firstNewline + 1);
|
|
538
|
+
return `${shebang}${stamp}\n${rest}`;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
return `${stamp}\n${content}`;
|
|
543
|
+
};
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generator type definitions for the Summon code generator framework.
|
|
3
|
+
*
|
|
4
|
+
* Effect framework types (Task, Effect, TaskError, etc.) are in @canonical/task.
|
|
5
|
+
*
|
|
6
|
+
* @packageDocumentation
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { Task } from "@canonical/task";
|
|
10
|
+
|
|
11
|
+
// =============================================================================
|
|
12
|
+
// Generator Definition Types
|
|
13
|
+
// =============================================================================
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Metadata for a generator, displayed in CLI help and discovery.
|
|
17
|
+
*/
|
|
18
|
+
export interface GeneratorMeta {
|
|
19
|
+
/** Generator name, used in CLI path (e.g., "component/react") */
|
|
20
|
+
name: string;
|
|
21
|
+
/**
|
|
22
|
+
* Name used in generated file stamp comments.
|
|
23
|
+
* Use this when the stamp should differ from the CLI command path
|
|
24
|
+
* (e.g., "@canonical/summon-component:react" vs "component/react").
|
|
25
|
+
*/
|
|
26
|
+
displayName: string;
|
|
27
|
+
/** One-line description shown in generator listings */
|
|
28
|
+
description: string;
|
|
29
|
+
/** Semantic version of the generator */
|
|
30
|
+
version: string;
|
|
31
|
+
/** Author name or email */
|
|
32
|
+
author?: string;
|
|
33
|
+
/**
|
|
34
|
+
* Extended help text shown when calling `summon <topic>` (without subgenerator)
|
|
35
|
+
* and in --help. Use this for detailed explanation and examples.
|
|
36
|
+
* Supports markdown-like formatting.
|
|
37
|
+
*/
|
|
38
|
+
help?: string;
|
|
39
|
+
/**
|
|
40
|
+
* Usage examples shown in help. Each example should show a common invocation.
|
|
41
|
+
*/
|
|
42
|
+
examples?: string[];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Definition of a prompt in a generator.
|
|
47
|
+
*
|
|
48
|
+
* Each prompt becomes a CLI flag. The prompt name is converted to kebab-case
|
|
49
|
+
* for the flag (e.g., `componentPath` → `--component-path`).
|
|
50
|
+
*/
|
|
51
|
+
export interface PromptDefinition {
|
|
52
|
+
/** Unique identifier, used as answer key and CLI flag name */
|
|
53
|
+
name: string;
|
|
54
|
+
/** Question text displayed to the user */
|
|
55
|
+
message: string;
|
|
56
|
+
/** Type of input */
|
|
57
|
+
type: "text" | "confirm" | "select" | "multiselect";
|
|
58
|
+
/** Default value if user provides no input */
|
|
59
|
+
default?: unknown;
|
|
60
|
+
/** Choices for select/multiselect prompts */
|
|
61
|
+
choices?: Array<{ label: string; value: string }>;
|
|
62
|
+
/** Conditional function - prompt is skipped if this returns false */
|
|
63
|
+
when?: (answers: Record<string, unknown>) => boolean;
|
|
64
|
+
/** Validation function, returns true or error message */
|
|
65
|
+
validate?: (value: unknown) => boolean | string;
|
|
66
|
+
/**
|
|
67
|
+
* Group name for organizing options in --help output.
|
|
68
|
+
* Options without a group appear under "Options".
|
|
69
|
+
*/
|
|
70
|
+
group?: string;
|
|
71
|
+
/**
|
|
72
|
+
* If true, this prompt can be provided as a positional argument.
|
|
73
|
+
* Only one prompt per generator should be positional.
|
|
74
|
+
* Only text prompts can be positional.
|
|
75
|
+
*/
|
|
76
|
+
positional?: boolean;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The complete definition of a generator.
|
|
81
|
+
*
|
|
82
|
+
* @typeParam TAnswers - Type of the answers object passed to generate
|
|
83
|
+
*/
|
|
84
|
+
export interface GeneratorDefinition<TAnswers = Record<string, unknown>> {
|
|
85
|
+
/** Generator metadata for CLI display */
|
|
86
|
+
meta: GeneratorMeta;
|
|
87
|
+
/** Prompts to collect answers from user */
|
|
88
|
+
prompts: PromptDefinition[];
|
|
89
|
+
/** Pure function that returns a Task describing the generation */
|
|
90
|
+
generate: (answers: TAnswers) => Task<void>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* A generator definition without type parameters, used in barrels/collections.
|
|
95
|
+
*/
|
|
96
|
+
// biome-ignore lint/suspicious/noExplicitAny: Required for contravariant generator collections
|
|
97
|
+
export type AnyGenerator = GeneratorDefinition<any>;
|