2.2.1 • Published 3 years ago

template-kit v2.2.1

Weekly downloads
16
License
Apache-2.0
Repository
github
Last release
3 years ago

template-kit

NPM Version NPM Downloads Deps Dev Deps

Library for creating projects from templates.

Features

  • Project generation using local template as a directory, archive file, or globally installed npm package
  • Download templates from git, npm, or a URL to a archive file
  • Support for .zip, .gz, .bz2, .tar, tar.gz, tar.bz2, .tgz, and .tbz2 archives
  • Run text files through ejs during file copy
  • JavaScript lifecycle hooks
  • User-defined copy file inclusion/exclusion filters
  • Data-driven destination directory and filenames
  • npm dependency installation
  • git repository initialization

Installation

npm install template-kit --save

Example

import TemplateEngine from 'template-kit';

(async () => {
    const engine = new TemplateEngine();

    engine.on('create', async (state, next) => {
        console.log('Creating the project from the template');
        await next();
        console.log('Project created!');
    });

    await engine.run({
        src: 'git@github.com:appcelerator/template-kit-test.git',
        dest: '/path/to/new/project'
    });

    console.log('Project created successfully!');
})();

Template Specification

Structure

A template can be an empty directory or a massive collection of files and subdirectories. All of the files in the template can be compressed in a single archive file (.zip, .tgz, etc) for distribution.

Templates do not need to be npm packages and they do not need to have a package.json. If they do, template-kit will happily call npm install after generation.

Any file that is not binary will be treated as an ejs template regardless of extension. ejs templates have access to any variable or function in the data object including the opts.data passed into the TemplateEngine constructor, the data export from the meta.js, or any data that has be injected via a hook.

Directories and filenames may contain a {{variable}} sequence which will be replaced with the corresponding value in the data object.

By default, template-kit will treat the root of the template directory as the actual template. However, the template may contain several project templates or place all of the template files in a single subdirectory. The relative project template path is defined by setting the template property in the meta.js file. If there are multiple project templates, then you can present them by using the prompts mechanism.

Metadata

template-kit will load the template's metadata from a meta.js file or the package's "main" file. The metadata can be an object or an async function that returns an object. The object contains the following properties:

PropertyTypeDescription
completeFunctionA function to call after the project generation is complete. Useful for displaying post create steps.
dataObjectArbitrary data to mix in with the run() data and pass into ejs when copying a text file.
filtersArray.<String>An array of file patterns to copy. The patterns follow the gitignore rules.
promptsObjectAn array of prompt descriptors that is used to select the template and template data.
templateStringRelative path to the template files. Defaults to '.'

API

TemplateEngine

Resolves a template source, installs the template, and manages the install lifecycle.

Constructor

new TemplateEngine(opts)

Initializes the template engine.

ParamTypeDescription
optsObjectVarious options.
opts.requestOptionsObjectgot HTTP client options and proxy/security settings below.
opts.requestOptions.caFileStringA path to a PEM-formatted certificate authority bundle.
opts.requestOptions.certFileStringA path to a client cert file used for authentication.
opts.requestOptions.keyFileStringA path to a private key file used for authentication.
opts.requestOptions.proxyStringA proxy server URL. Can be http or https.
opts.requestOptions.strictSSLBooleanWhen falsey, disables TLS/SSL certificate validation for both https requests and https proxy servers.

Methods

.run(opts)Promise

Builds a project based on the specified template and options.

ParamTypeDescription
optsObjectVarious options
opts.dataObjectA data object that is passed into ejs when copying template files.
opts.destStringThe destination directory to create the project in.
opts.filtersSet | Array.<String>A list of file patterns to pass into micromatch when copying files.
opts.forceBooleanWhen true, overrides the destination if it already exists.
opts.git=trueBooleanWhen true and git executable is found, after the the project is generated, initialize a git repo in the project directory.
opts.npmArgsArray.<String>An array of additional parameters to pass into npm. Useful if you need to add extra arguments for things such as skipping shrinkwrap or production only.
opts.srcStringThe path to a directory, archive file, globally installed npm package, archive URL, npm package name, or git repo.
opts.template='.'StringRelative path to the directory containing the template files. This value overrides the default template from the meta.js, but not the template value returned from prompting.
Run State

Every time run() is invoked, a new state object is created and passed through the various stages. The contents of the state depends on the Source Type.

PropertyTypeDescription
destStringThe destination directory to create the project in.
destFileStringWhen copying files, this is the destination file path.
disposablesArray.<String>A list of temp directories to cleanup.
extractDestStringThe temporary directory where the archive was extracted to.
filtersSet | Array.<String>A list of file patterns to copy.
forceBooleanWhen true, overrides the destination if it already exists.
gitBooleanWhen true and git executable is found, after the the project is generated, initialize a git repo in the project directory.
gitInfoObjectThe parsed git repo information.
npmArgsArray.<String>An array of additional parameters to pass into npm. Useful if you need to add extra arguments for things such as skipping shrinkwrap.
npmManifestObjectThe npm package information
promptsArray.<Object>A list of prompt descriptors.
srcStringThe path to a directory, archive file, globally installed npm package, archive URL, npm package name, or git repo.
srcFileStringWhen copying files, this is the source file path.
templateStringRelative path to the directory containing the template files. Defaults to '.'

Events

The TemplateEngine emits several events. It uses the hook-emitter package which supports async event listeners.

Some events are only emitted depending on the source type (e.g. the src passed into run()).

Event Flow                   ┌───────┐
                             │ run() │
                             └───┬───┘ ┌───────┐
                                 ├─────┤ #init │
                                 │     └───────┘
      ┌──────────────┬───────────┼────────┬──────────┬──────────┐
     git            URL        Local    Local      Global      npm
      │        ┌─────┴─────┐   File   Directory  npm Package    │
      │        │ #download │     │        │          │          │
      │        └─────┬─────┘     │        │          │          │
┌─────┴──────┐       └─────┬─────┘        │          │  ┌───────┴───────┐
│ #git-clone │   ┌─────────┴─────────┐    │          │  │ #npm-download │
└─────┬──────┘   │ #extract          │    │          │  └───────┬───────┘
      │          │ #extract-file     │    │          │          │
      │          │ #extract-progress │    │          │          │
      │          └─────────┬─────────┘    │          │          │
      └────────────────────┴───────┬──────┴──────────┴──────────┘
                             ┌─────┴──────┐
                             │ #load-meta │
                             └─────┬──────┘ ┌─────────┐
                                   ├────────┤ #prompt │
                              ┌────┴────┐   └─────────┘
                              │ #create │
                              └────┬────┘   ┌───────┐
                                   ├────────┤ #copy │
                                   │        └───┬───┘    ┌────────────┐
                                   │            └────────┤ #copy-file │
                                   │    ┌──────────────┐ └────────────┘
                                   ├────┤ #npm-install │
                                   │    └──────────────┘
                                   │    ┌───────────┐
                                   ├────┤ #git-init │
                                   │    └───────────┘
                              ┌────┴─────┐
                              │ #cleanup │
                              └──────────┘

#init

Initialize the run state with the options passed into run().

Source Type: Local file, local directory, global npm package, npm, git, URL

ParamTypeDescription
optsObjectThe options passed into run().
async next(opts)FunctionContinue to next hook.
engine.on('init', async opts => {
    // before the run state has been initialized
});

or

engine.on('init', async (opts, next) => {
    // before the run state has been initialized
    await next();
    // after initialization
});

#git-clone

Emitted when git clone is called.

Source Type: git

ParamTypeDescription
stateObjectThe run state.
argsArray.<String>The arguments passed into the git command.
optsObjectspawn() options.
async next(opts)FunctionContinue to next hook.
engine.on('git-clone', async (state, args, opts, next) => {
    // before the git clone call
    await next();
    // after the clone
});

#download

Emitted when downloading a file based on a http/https URL.

Source Type: URL

ParamTypeDescription
stateObjectThe run state.
async next(opts)FunctionContinue to next hook.
engine.on('download', async (state, next) => {
    // before the download begins
    await next();
    // after the clone
});

#extract

Emitted when extracting the downloaded or local archive file.

Source Type: Local directory, URL

ParamTypeDescription
stateObjectThe run state.
async next(opts)FunctionContinue to next hook.
engine.on('extract', async (state, next) => {
    // before the archive is extracted
    await next();
    // after extraction
});

#extract-file

Emits the current file being extracted from the archive.

Source Type: Local directory, URL

ParamTypeDescription
stateObjectThe run state.
fileStringThe name of the file being extracted.
engine.on('extract-file', async (state, file) => {
    console.log(`Extracting ${file}`);
});

#extract-progress

Emits the current progress of the file extraction from 0 to 100.

Source Type: Local directory, URL

ParamTypeDescription
stateObjectThe run state.
percentNumberThe percentage complete.
engine.on('extract-progress', async (state, percent) => {
    console.log(`Extracted ${percent}%`);
});

#npm-download

Emitted when downloading and extracting an npm package.

Source Type: npm

ParamTypeDescription
stateObjectThe run state.
async next(opts)FunctionContinue to next hook.
engine.on('npm-download', async (state, next) => {
    // before downloading and extracting the npm package
    await next();
    // after extraction
});

#create

Emitted when about to populate the destination directory.

Source Type: All sources.

ParamTypeDescription
stateObjectThe run state.
async next(opts)FunctionContinue to next hook.
engine.on('create', async (state, next) => {
    // before the project is generated
    await next();
    // after project is generated
});

#load-meta

Emitted when attempting to load the template's meta.js or "main" file.

Source Type: Any source with a meta script.

ParamTypeDescription
stateObjectThe run state.
async next(opts)FunctionContinue to next hook.
engine.on('load-meta', async (state, next) => {
    // before npm dependencies have been installed
    await next();
    // after installation
});

#prompt

Allows application opportunity to prompt for missing data, then populate state's data property.

Source Type: Any source with a meta script.

ParamTypeDescription
stateObjectThe run state.
engine.on('prompt', async state => {
    // prompt for `state.prompts` and store results in `state.data`
});

#copy

Emitted when copying the template files to the destination.

Source Type: All sources.

ParamTypeDescription
stateObjectThe run state.
async next(opts)FunctionContinue to next hook.
engine.on('copy', async (state, next) => {
    // before copying has begun
    await next();
    // after files have been copied
});

#copy-file

Emitted for each file copied.

Source Type: All sources.

ParamTypeDescription
stateObjectThe run state.
async next(opts)FunctionContinue to next hook.
engine.on('copy-file', async (state, next) => {
    // before a specific file is to be copied
    await next();
    // file has been copied
});

#npm-install

Emitted when installing npm dependencies in the destination directory.

Source Type: Any source with a package.json.

ParamTypeDescription
stateObjectThe run state.
cmdStringThe path to npm command.
argsArray.<String>The npm arguments.
optsObjectspawn() options.
async next(opts)FunctionContinue to next hook.
engine.on('npm-install', async (state, cmd, args, opts, next) => {
    // before npm dependencies have been installed
    await next();
    // after installation
});

#git-init

Emitted when a git repository is being initialized in the project directory.

Source Type: Any source.

ParamTypeDescription
stateObjectThe run state.
argsArray.<String>git arguments.
optsObjectspawn() options.
async next(opts)FunctionContinue to next hook.
engine.on('git-init`', async (state, args, opts, next) => {
    // before the git repo has been initialized
    await next();
    // after initialization
});

#cleanup

Emitted after the project has been created and the temp directories are to be deleted.

Source Type: Any source.

ParamTypeDescription
stateObjectThe run state.
async next(opts)FunctionContinue to next hook.
engine.on('cleanup`', async (state, next) => {
    // before temp directories have been deleted
    await next();
    // after cleanup
});

Legal

This project is open source under the Apache Public License v2 and is developed by Axway, Inc and the community. Please read the LICENSE file included in this distribution for more information.