Skip to content
Jonathan Pidgeon edited this page Sep 18, 2013 · 5 revisions

Base#option

Adds an option to the set of generator expected options, only used to generate generator usage. By default, generators get all the cli option parsed by nopt as a this.options Hash object.

  • name - The name of the argument
  • options - Hash of configuration values where:
    • desc - Description for the argument.
    • type - Type for this argument, either Boolean, String or Number.
    • default - Default value for this argument.
    • banner - String to show on usage notes.
    • hide - If you want to hide this option from the help.

Base#argument

Adds an argument to the class and creates an attribute getter for it.

Arguments are different from options in several aspects. The first one is how they are parsed from the command line, arguments are retrieved from position.

Examples

yo generate NAME
# Instead of:
yo generate --name NAME

Besides, arguments are used inside your code as a property (this.argument), while options are all kept in a hash (this.options).

  • name - The argument String name to use
  • config - The Hash of congiguration values
    • desc - Description for the argument.
    • required - If the argument is required or not.
    • optional - If the argument is optional or not.
    • type - The type of the argument, can be String, Number, Array, Object (in which case considered as an Hash object, key:value).
    • defaults - Default value for this argument. It cannot be required and have default values.
    • banner - String to show on usage notes.

Returns the generator instance

Base#run

Runs the generator, executing top-level methods in the order they were defined.

Special named method like constructor and initialize are skipped (CoffeeScript, Backbone like inheritence), or any method prefixed by a _.

You can also supply the arguments for the method to be invoked, if none is given, the same values used to initialize the invoker are used to initialize the invoked.

  • args - The Array of arguments to invoke the generator with (defaults: this.args)
  • cb - The callback Function to invoke on completion. (defaults: noop)

Returns the generator instance.

Base#runHooks

Goes through all registered hooks, invoking them in series.

  • cb - Function to be called on completion

Returns the generator instance.

Base#hookFor

Registers a hook to invoke when this generator runs.

A generator with a namespace based on the value supplied by the user to the given option named "name".

Example

// with `--test-framework jasmine` from CLI
this.hookFor('test-framework');
// => registers the `jasmine` hook

An option is created when this method is invoked and you can set a hash to customize it.

Must be called prior to the generator run (shouldn't be called within a generator "step" - top-level methods)

  • name - The hook value to look for
  • config - The Hash of configuration options
    • as - The context value to use when runing the hooked generator (defaults: the invoker generator name)
    • args - The array of positional arguments to init and run the generator with.
    • options - The hash of options to use to init and run the generator with.

Returns the generator instance.

Base#defaultFor

Return the default value for the option name.

Also performs a lookup in CLI options and the this.fallbacks property.

  • name - The String name to look for.

Returns the resolved value.

Base#bannerFor

Generate the default banner for help output, adjusting output to argument type.

  • config - A hash of options with the following properties:
    • name - The String value to display, uppercased (only relevant with String type)
    • type - The argument type. This is the constructor Function (eg. String, Number, Object or Array) used to init the argument.

Returns the banner.

Base#help

Tries to get the description from a USAGE file one folder above the source root otherwise uses a default description.

Returns the usage output.

Base#usage

Output usage information for this given generator, depending on its arguments / options / hooks.

Returns the usge output.

Base#desc

Simple setter for custom description to append on help output.

Returns the generator instance.

Base#optionsHelp

Returns the list of options in formatted table.

Mixins

invoke#invoke

Receives a namespace, and an Hash of options to invoke a given generator. The usual list of arguments can be set with options.args (ex. nopt's argv.remain array)

It's used to hookFor another generator from within your generators.

  • namespace - The namespace value to look for.
  • options - The Hash of options to invoke the generator with. See Environment#create for the list of possible values.

Returns the generator instance.

optsToArgs

Convert an object to an array of CLI arguments

bower#install

Receives a list of paths, and an Hash of options to install through bower

  • paths - A String or an Array of package name to install. Empty string for bower install
  • options - [optional] The Hash of options to invoke bower.commands.install with. See bower help install.
  • callback - [optional]

Returns the generator instance.

The log API is a bit different, and accesible through the property. Intead of the usual mixin

formatter

borrowed to https://github.com/mikeal/logref/blob/master/main.js#L6-15

log

this.log is a logref compatible logger, with a bit of enhanced API.

It also have EventEmitter like ability, so you can call on / emit on it, namely used to increase or decrease the padding.

All logs are done against STDERR, letting you stdout for meaningfull value and redirection, should you need to generate output this way.

Log functions take two arguments, a message and a context. For any other kind of paramters, console.error is used, so all of the console format string goodies you're used to work fine.

  • msg - The message to show up
  • context - The optional context to escape the message against

Retunrns the logger

log#write

A simple write method, with formatted message. If msg is ommitted, then a single \n is written.

Returns the logger

log#writeln

Same as log.write() but automatically appends a \n at the end of the message.

log#ok

Convenience helper to write sucess status, this simply prepends the message with a gren .

log#status

Each predefined status has its logging method utility, handling status color and padding before the usual .write()

Example

this.log
  .write()
  .info('Doing something')
  .force('Forcing filepath %s, 'some path')
  .conflict('on %s' 'model.js')
  .write()
  .ok('This is ok');

The list of status and mapping colors

skip       yellow
force      yellow
create     green
invoke     bold
conflict   red
identical  cyan
info       grey

Returns the logger

log#table

A basic wrapper around cli-table package, resetting any single char to empty strings, this is used for aligning options and arguments without too much Math on our side.

  • opts - A list of rows or an Hash of options to pass through cli table.

Returns the table reprensetation

actions#sourceRoot

Stores and return the source root for this class. The source root is used to prefix filepath with .read() or .template().

  • root - A string to resolve sourceRoot against.

Returns the source root value.

actions#destinationRoot

Sets the destination root for this class, the working directory.

Relatives path are added to the directory where the script was invoked and expanded.

This automatically creates the working directory if it doensn't exists and cd into it.

  • root - A string to resolve destinationRoot against.

Returns the destinatio root value.

actions#copy

Make some of the file API aware of our source / destination root paths. copy, template (only when could be applied/required by legacy code), write and alike consider:

  • source - the source path to be relative to generator's templates/ directory.
  • destination - the destination path to be relative to application Gruntfile's directory (most likely cwd)

actions#read

A simple method to read the content of the a file.

The encoding is utf8 by default, to read binary files, pass the proper encoding or null.

Non absolute path are prefixed by the source root.

  • source - A filepath String to read from
  • encoding - An optional encoding value to use (default: utf8)

Returns the file content

actions#write

Writes a chunk of data to a given filepath, checking for collision prior to the file write.

  • filepath - Path to write to
  • conent - File content to write

Returns the generator instance

actions#checkForCollision

File collision checked. Takes a filepath (the file about to be written) and the actual content. A basic check is done to see if the file exists, it it does:

  1. read its content from FS
  2. compare it with content provided
  3. if identical, mark it as is and skip the check
  4. if diverged, prepare and show up the file collision menu

The menu has the following options:

  • Y - yes, overwrite
  • n - no, do not overwrite
  • a - all, overwrite this and all others
  • q - quit, abort
  • d - diff, show the differences between the old and the new
  • h - help, show this help

actions#template

Use configured engine to render the provided source template at the given destination. data is an optional hash to pass to the template, if undefined, executes the template in the generator instance context.

actions#engine

The engine method is the function used whenever a template needs to be rendered.

It uses the configured engine (default: underscore) to render the body template with the provided data.

  • body - Template content
  • data - Data to render the template with

Returns the rendered string

actions#directory

Copies recursively the files from source directory to root directory.

  • source - Filepath of the directory to read from (relative to sourceRoot)
  • destination - Filepath to copy to (relative to destinationRoot) Returns the generator instance

actions#remote

Remotely fetch a package on github, store this into a _cache folder, and provide a "remote" object as a facade API to ourself (part of genrator API, copy, template, directory)

Example:

this.remote('user', 'repo', function(err, remote) {
  remote.copy('.', 'vendors/user-repo');
});

Returns the generator instance

remote#copy

Simple proxy to .copy(source, destination)

remote#template

same as .template(source, destination, data)

remote#directory

same as .template(source, destination)

actions#installDependencies

Runs npm and bower in the generated directory concurrently and prints a message to let the user know.

Options:

  • npm: bool, whether to run npm install, default: true
  • bower: bool, whether to run bower install, default: true
  • skipInstall: bool, whether to skip automatic installation and just print a message to the user how to do it, default: false

Example:

this.installDependencies({ bower: true, npm: true, skipInstall: false });

Returns the generator instance.

file#expand

Performs a glob search with the provided pattern and optional Hash of options. Options can be any option supported by glob

  • pattern - Glob String pattern to look for
  • options - Hash of options matching glob's option.

Returns an Array of filenames matching the pattern

file#expandFiles

Performs a glob search with the provided pattern and optional Hash of options, filtering results to only return files (not directories). Options can be any option supported by glob

  • pattern - Glob String pattern to look for
  • options - Hash of options matching glob's option.

Returns an Array of filenames matching the pattern

file#isPathAbsolute

Checks a given file path being absolute or not. Borrowed to grunt's file API.

file#mkdir

simple facade to mkdirp.sync

prompt#prompt

Prompt for user input based on the given Array of prompts to perform in series, and call done callback on completion. prompts can be a single Hash of options in which case a single prompt is performed.

Options can be any read's option: https://github.com/isaacs/read#options

  • prompts - A single or an Array of Hash options.
  • done - Callback to call on error or on completion.

Returns the generator instance.

fetch#fetch

Download a single file at the given destination.

fetch#tarball

heavily based on npm's util/untar.js file

fetch#request

re-expose the request with proxy defaults, so that we can reuse this instance of request.

module#_

and expose that

wiring#domUpdate

Update a file containing HTML markup with new content, either appending, prepending or replacing content matching a particular selector

  • html - a string containing HTML markup
  • tagName - a valid CSS selector
  • content - the inline content to update your selector with
  • mode - a(ppend), p(repend), r(eplace), d(elete)

wiring#append

Insert specific content as the last child of each element matched by the tagName selector. Returns a string.

wiring#prepend

Insert specific content as the first child of each element matched by the tagName selector. Returns a string.

wiring#appendToFile

Insert specific content as the last child of each element matched by the tagName selector. Writes to file.

wiring#prependToFile

Insert specific content as the first child of each element matched by the tagName selector. Writes to file.

wiring#generateBlock

Generate a usemin-handler block.

  • blockType - js, css
  • optimizedPath - the final file to build
  • filesBlock - a string containing populated script/style tags ready to be injected into a usemin block.
  • searchPath - an alternate search path to look in for files

Returns the new block.

wiring#appendFiles

Append files, specifying the optimized path and generating the necessary usemin blocks to be used for the build process.

  • htmlOrOptions - string to append the files to or an object of this and the remaining options
  • fileType - js (appends to the end of 'body'), css (appends to the end of 'head')
  • optimizedPath - the final file to build
  • sourceFileList - the list of files to be appended. We check against the fileType to ensure the correct tags are wrapped around them and the right usemin blocks generated.
  • attrs - A Hash of html attributes to generate along the generated script / link tags
  • searchPath - an alternate path to look in for files

Returns updated content.

wiring#attributes

Computes a given Hash object of attributes into its HTML representation

  • attrs - Hash object of attributes to generate

Returns the generated string of attributes.

wiring#appendScripts

Scripts alias to appendFiles

wiring#removeScript

Simple script removal

wiring#appendScriptsDir

Append a directory of scripts

wiring#appendStylesDir

Append a directory of stylesheets

Clone this wiki locally