1- import {
2- Generator ,
3- GeneratorResults ,
4- GeneratorOptions
5- } from "code-skeleton/lib/generators/abstract" ;
6- import { dirname } from "node:path" ;
7- import { writeFile , mkdir , readFile } from "node:fs/promises" ;
1+ import { Generator } from "code-skeleton/lib/generators/abstract" ;
2+ import { readFile } from "node:fs/promises" ;
83import Mustache from "mustache" ;
94Mustache . tags = [ "<%" , "%>" ] ;
105
11- interface MustacheGeneratorOptions extends GeneratorOptions {
6+ interface MustacheGeneratorOptions {
127 sourcePath : string ;
8+ variables : unknown ;
139}
1410
15- class MustacheGenerator extends Generator {
11+ class MustacheGenerator extends Generator < MustacheGeneratorOptions > {
1612 declare options : MustacheGeneratorOptions ;
1713
1814 constructor ( options : MustacheGeneratorOptions ) {
@@ -23,47 +19,14 @@ class MustacheGenerator extends Generator {
2319 }
2420 }
2521
26- async apply ( targetPath : string ) : Promise < GeneratorResults > {
27- await mkdir ( dirname ( targetPath ) , { recursive : true } ) ;
28- try {
29- const source = await readFile ( this . options . sourcePath ) ;
30-
31- const rendered = Mustache . render ( source . toString ( ) , this . options ) ;
32- await writeFile ( targetPath , rendered ) ;
33- return this . pass ( ) ;
34- } catch ( err ) {
35- const { code, message } = err as { code ?: string ; message : string } ;
36- // istanbul ignore next - no need to test message fallback
37- return this . fail ( code ?? message ) ;
38- }
39- }
40- async verify ( targetPath : string ) : Promise < GeneratorResults > {
41- let actual ;
42- try {
43- actual = await readFile ( targetPath ) ;
44- } catch ( err ) {
45- const { code, message } = err as { code ?: string ; message : string } ;
46- // istanbul ignore next - no need to test passthrough throws
47- if ( code !== "ENOENT" ) {
48- return this . fail ( code ?? message ) ;
49- }
50-
51- return this . fail ( "file missing" ) ;
52- }
53-
22+ async generate ( ) {
5423 const source = await readFile ( this . options . sourcePath ) ;
55- const expected = Buffer . from ( Mustache . render ( source . toString ( ) , this . options ) ) ;
56- if ( actual . compare ( expected ) === 0 ) {
57- return this . pass ( ) ;
58- }
5924
60- return this . fail ( "contents do not match" ) ;
25+ const rendered = Mustache . render ( source . toString ( ) , this . options . variables ) ;
26+ return rendered ;
6127 }
6228}
6329
64- export function mustache ( sourcePath : string , options : GeneratorOptions = { } ) {
65- return new MustacheGenerator ( {
66- ...options ,
67- sourcePath
68- } ) ;
69- }
30+ export function mustache ( options : MustacheGeneratorOptions ) {
31+ return new MustacheGenerator ( options ) ;
32+ }
0 commit comments