cli/directives/TemplateDirective.js

/**
 * @module flitter-cli/directives/TemplateDirective
 */

const Directive = require('../Directive')
const fs = require('fs').promises
const path = require('path')

/**
 * Directive to create new files from registered templates by name.
 * 
 * @extends module:flitter-cli/Directive~Directive
 */
class TemplateDirective extends Directive {

    /**
     * Get the name of the directive. Used by ./flitter.
     * @static
     * @returns {string} "new"
     */
    static name(){
        return "new"
    }

    /**
     * Get the usage information for the directive. Used by ./flitter help.
     * @returns {string}
     */
    static help(){
        return "create a new file from a registered template: <template name> <file name>"
    }

    /**
     * Handles an invocation of the directive. Creates a new template with the specified class name.
     * This directive is sub-directory aware and accepts Flitter canonical names.
     * @param {module:libflitter/app/FlitterApp~FlitterApp} app - the Flitter app
     * @param {Array} argv - the CLI arguments passed after the directive
     * @returns {Promise<void>}
     */
    async handle(app, argv){
        const templates = app.d.cli.templates
        let found = false
        let names = "\t"
        
        for ( let template_name in templates ){
            names += template_name+", "
            
            if ( template_name === argv[0] ){
                const template = templates[template_name]
                
                if ( !argv[1] ){
                    found = true
                    console.log("ERROR: Please enter a canonical name for the new "+template_name+".")
                    break
                }
                
                const file_name = argv[1].replace(/:/g, '/')+template.extension
                
                let subdir = ""
                if ( file_name.lastIndexOf("/") > -1 ){
                    subdir = file_name.substr(0, file_name.lastIndexOf("/"))
                }                
                
                // mkdir -p the template destination
                await fs.mkdir(path.resolve(template.directory, subdir), { recursive: true })
                
                // get the full path to the file
                const file_path = path.resolve(template.directory, file_name)
                const class_name = argv[1].split(":").slice(-1)[0]
                
                await fs.writeFile(file_path, template.template(class_name, argv[1]))
                found = true
                break
            }
        }
        
        if ( !found ){
            console.log("ERROR: Please enter a valid template name.\nThe following templates are registered with Flitter:")
            console.log(names.slice(0, -2))
        }
    }
    
}

module.exports = exports = TemplateDirective