@@ -3,31 +3,36 @@ import fs from 'fs-extra';
33import Mustache from 'mustache' ;
44
55import { EXT , ROOT } from '../constants' ;
6+ import { Logger } from './Logger' ;
67
78export class TemplateService {
89 constructor ( variables ) {
910 this . variables = variables ;
10- this . parse = this . parse . bind ( this ) ;
1111 }
1212
13- parse ( template ) {
14- return Mustache . render ( template , this . variables ) ;
13+ static getExt ( format ) {
14+ switch ( format ) {
15+ case 'script' :
16+ case 'test' :
17+ return EXT . component === 'js' ? 'jsx' : EXT . component ;
18+ case 'style' :
19+ return 'css' ;
20+ default :
21+ Logger . error ( `Unhandled format ${ format } ` ) ;
22+ return process . exit ( 1 ) ;
23+ }
1524 }
1625
17- getScriptTemplate ( ) {
18- const ext = EXT . component === 'js' ? 'jsx' : EXT . component ;
19- const filePath = path . resolve ( ROOT , `templates/component-${ ext } .template` ) ;
20- return fs . readFile ( filePath , 'utf8' ) . then ( this . parse ) ;
21- }
22-
23- getStyleTemplate ( ) {
24- const filePath = path . resolve ( ROOT , `templates/style-css.template` ) ;
25- return fs . readFile ( filePath , 'utf8' ) . then ( this . parse ) ;
26- }
26+ getTemplate ( format = 'script' ) {
27+ const ext = TemplateService . getExt ( format ) ;
28+ const { type } = this . variables ;
2729
28- getTestTemplate ( ) {
29- const ext = EXT . component === 'js' ? 'jsx' : EXT . component ;
30- const filePath = path . resolve ( ROOT , `templates/test-${ ext } .template` ) ;
31- return fs . readFile ( filePath , 'utf8' ) . then ( this . parse ) ;
30+ const filePath = path . resolve ( ROOT , `templates/${ type } /${ type } -${ format } -${ ext } .template` ) ;
31+ if ( fs . pathExistsSync ( filePath ) ) {
32+ const template = fs . readFileSync ( filePath , 'utf8' ) ;
33+ return Mustache . render ( template , this . variables ) ;
34+ }
35+ Logger . warn ( chalk => `Couldn't find "${ format } " template at ${ chalk . white ( filePath ) } ` ) ;
36+ return '// Template not found' ;
3237 }
3338}
0 commit comments