• Stars
    star
    840
  • Rank 54,265 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 11 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Launch your command line tool with ease.

liftoff

NPM version Downloads Build Status Coveralls Status

Launch your command line tool with ease.

What is it?

See this blog post, check out this proof of concept, or read on.

Say you're writing a CLI tool. Let's call it hacker. You want to configure it using a Hackerfile. This is node, so you install hacker locally for each project you use it in. But, in order to get the hacker command in your PATH, you also install it globally.

Now, when you run hacker, you want to configure what it does using the Hackerfile in your current directory, and you want it to execute using the local installation of your tool. Also, it'd be nice if the hacker command was smart enough to traverse up your folders until it finds a Hackerfileโ€”for those times when you're not in the root directory of your project. Heck, you might even want to launch hacker from a folder outside of your project by manually specifying a working directory. Liftoff manages this for you.

So, everything is working great. Now you can find your local hacker and Hackerfile with ease. Unfortunately, it turns out you've authored your Hackerfile in coffee-script, or some other JS variant. In order to support that, you have to load the compiler for it, and then register the extension for it with node. Good news, Liftoff can do that, and a whole lot more, too.

Usage

const Liftoff = require('liftoff');

const Hacker = new Liftoff({
  name: 'hacker',
  processTitle: 'hacker',
  moduleName: 'hacker',
  configName: 'hackerfile',
  extensions: {
    '.js': null,
    '.json': null,
    '.coffee': 'coffee-script/register',
  },
  v8flags: ['--harmony'], // or v8flags: require('v8flags')
});

Hacker.prepare({}, function (env) {
  Hacker.execute(env, function (env) {
    // Do post-execute things
  });
});

API

constructor(opts)

Create an instance of Liftoff to invoke your application.

opts.name

Sugar for setting processTitle, moduleName, configName automatically.

Type: String

Default: null

These are equivalent:

const Hacker = Liftoff({
  processTitle: 'hacker',
  moduleName: 'hacker',
  configName: 'hackerfile',
});
const Hacker = Liftoff({ name: 'hacker' });

Type: String

Default: null

opts.configName

Sets the name of the configuration file Liftoff will attempt to find. Case-insensitive.

Type: String

Default: null

opts.extensions

Set extensions to include when searching for a configuration file. If an external module is needed to load a given extension (e.g. .coffee), the module name should be specified as the value for the key.

Type: Object

Default: {".js":null,".json":null}

Examples:

In this example Liftoff will look for myappfile{.js,.json,.coffee}. If a config with the extension .coffee is found, Liftoff will try to require coffee-script/require from the current working directory.

const MyApp = new Liftoff({
  name: 'myapp',
  extensions: {
    '.js': null,
    '.json': null,
    '.coffee': 'coffee-script/register',
  },
});

In this example, Liftoff will look for .myapp{rc}.

const MyApp = new Liftoff({
  name: 'myapp',
  configName: '.myapp',
  extensions: {
    rc: null,
  },
});

In this example, Liftoff will automatically attempt to load the correct module for any javascript variant supported by interpret (as long as it does not require a register method).

const MyApp = new Liftoff({
  name: 'myapp',
  extensions: require('interpret').jsVariants,
});

opts.v8flags

Any flag specified here will be applied to node, not your program. Useful for supporting invocations like myapp --harmony command, where --harmony should be passed to node, not your program. This functionality is implemented using flagged-respawn. To support all v8flags, see v8flags.

Type: Array or Function

Default: null

If this method is a function, it should take a node-style callback that yields an array of flags.

opts.processTitle

Sets what the process title will be.

Type: String

Default: null

opts.completions(type)

A method to handle bash/zsh/whatever completions.

Type: Function

Default: null

opts.configFiles

An object of configuration files to find. Each property is keyed by the default basename of the file being found, and the value is an array of path arguments of which the order indicates priority to find.

Note: This option is useful if, for example, you want to support an .apprc file in addition to an appfile.js. If you only need a single configuration file, you probably don't need this. In addition to letting you find multiple files, this option allows more fine-grained control over how configuration files are located.

Type: Object

Default: null

Path arguments

The fined module accepts a string representing the path to search or an object with the following keys:

  • path (required)

    The path to search. Using only a string expands to this property.

    Type: String

    Default: null

  • name

    The basename of the file to find. Extensions are appended during lookup.

    Type: String

    Default: Top-level key in configFiles

  • extensions

    The extensions to append to name during lookup. See also: opts.extensions.

    Type: String or Array or Object Default: The value of opts.extensions

  • cwd

    The base directory of path (if relative).

    Type: String

    Default: The value of opts.cwd

  • findUp

    Whether the path should be traversed up to find the file.

    Type: Boolean

    Default: false

Examples:

In this example Liftoff will look for the .hacker.js file relative to the cwd as declared in configFiles.

const MyApp = new Liftoff({
  name: 'hacker',
  configFiles: {
    '.hacker': [{ path: '.' }],
  },
});

In this example, Liftoff will look for .hackerrc in the home directory.

const MyApp = new Liftoff({
  name: 'hacker',
  configFiles: {
    '.hacker': [
      {
        path: '~',
        extensions: {
          rc: null,
        },
      },
    ],
  },
});

In this example, Liftoff will look in the cwd and then lookup the tree for the .hacker.js file.

const MyApp = new Liftoff({
  name: 'hacker',
  configFiles: {
    '.hacker': [
      {
        path: '.',
        findUp: true,
      },
    ],
  },
});

In this example, the name is overridden and the key is ignored so Liftoff looks for .override.js.

const MyApp = new Liftoff({
  name: 'hacker',
  configFiles: {
    hacker: [
      {
        path: '.',
        name: '.override',
      },
    ],
  },
});

In this example, Liftoff will use the home directory as the cwd and looks for ~/.hacker.js.

const MyApp = new Liftoff({
  name: 'hacker',
  configFiles: {
    '.hacker': [
      {
        path: '.',
        cwd: '~',
      },
    [,
  },
});

prepare(opts, callback(env))

Prepares the environment for your application with provided options, and invokes your callback with the calculated environment as the first argument. The environment can be modified before using it as the first argument to execute.

Example Configuration w/ Options Parsing:

const Liftoff = require('liftoff');
const MyApp = new Liftoff({ name: 'myapp' });
const argv = require('minimist')(process.argv.slice(2));
const onExecute = function (env, argv) {
  // Do post-execute things
};
const onPrepare = function (env) {
  console.log('my environment is:', env);
  console.log('my liftoff config is:', this);
  MyApp.execute(env, onExecute);
};
MyApp.prepare(
  {
    cwd: argv.cwd,
    configPath: argv.myappfile,
    preload: argv.preload,
    completion: argv.completion,
  },
  onPrepare
);

Example w/ modified environment

const Liftoff = require('liftoff');
const Hacker = new Liftoff({
  name: 'hacker',
  configFiles: {
    '.hacker': [{ path: '.', cwd: '~' }],
  },
});
const onExecute = function (env, argv) {
  // Do post-execute things
};
const onPrepare = function (env) {
  const config = env.config['.hacker'];
  if (config.hackerfile) {
    env.configPath = path.resolve(config.hackerfile);
    env.configBase = path.dirname(env.configPath);
  }
  Hacker.execute(env, onExecute);
};
Hacker.prepare({}, onPrepare);

opts.cwd

Change the current working directory for this execution. Relative paths are calculated against process.cwd().

Type: String

Default: process.cwd()

Example Configuration:

const argv = require('minimist')(process.argv.slice(2));
MyApp.prepare(
  {
    cwd: argv.cwd,
  },
  function (env) {
    MyApp.execute(env, invoke);
  }
);

Matching CLI Invocation:

myapp --cwd ../

opts.configPath

Don't search for a config, use the one provided. Note: Liftoff will assume the current working directory is the directory containing the config file unless an alternate location is explicitly specified using cwd.

Type: String

Default: null

Example Configuration:

var argv = require('minimist')(process.argv.slice(2));
MyApp.prepare(
  {
    configPath: argv.myappfile,
  },
  function (env) {
    MyApp.execute(env, invoke);
  }
);

Matching CLI Invocation:

myapp --myappfile /var/www/project/Myappfile.js

Examples using cwd and configPath together:

These are functionally identical:

myapp --myappfile /var/www/project/Myappfile.js
myapp --cwd /var/www/project

These can run myapp from a shared directory as though it were located in another project:

myapp --myappfile /Users/name/Myappfile.js --cwd /var/www/project1
myapp --myappfile /Users/name/Myappfile.js --cwd /var/www/project2

opts.preload

A string or array of modules to attempt requiring from the local working directory before invoking the execute callback.

Type: String|Array Default: null

Example Configuration:

var argv = require('minimist')(process.argv.slice(2));
MyApp.prepare(
  {
    preload: argv.preload,
  },
  function (env) {
    MyApp.execute(env, invoke);
  }
);

Matching CLI Invocation:

myapp --preload coffee-script/register

callback(env)

A function called after your environment is prepared. A good place to modify the environment before calling execute. When invoked, this will be your instance of Liftoff. The env param will contain the following keys:

  • cwd: the current working directory
  • preload: an array of modules that liftoff tried to pre-load
  • configNameSearch: the config files searched for
  • configPath: the full path to your configuration file (if found)
  • configBase: the base directory of your configuration file (if found)
  • modulePath: the full path to the local module your project relies on (if found)
  • modulePackage: the contents of the local module's package.json (if found)
  • configFiles: an object of filepaths for each found config file (filepath values will be null if not found)

execute(env, [forcedFlags], callback(env, argv))

A function to start your application, based on the env given. Optionally takes an array of forcedFlags, which will force a respawn with those node or V8 flags during startup. Invokes your callback with the environment and command-line arguments (minus node & v8 flags) after the application has been executed.

Example:

const Liftoff = require('liftoff');
const MyApp = new Liftoff({ name: 'myapp' });
const onExecute = function (env, argv) {
  // Do post-execute things
  console.log('my environment is:', env);
  console.log('my cli options are:', argv);
  console.log('my liftoff config is:', this);
};
const onPrepare = function (env) {
  var forcedFlags = ['--trace-deprecation'];
  MyApp.execute(env, forcedFlags, onExecute);
};
MyApp.prepare({}, onPrepare);

callback(env, argv)

A function called after your application is executed. When invoked, this will be your instance of Liftoff, argv will be all command-line arguments (minus node & v8 flags), and env will contain the following keys:

  • cwd: the current working directory
  • preload: an array of modules that liftoff tried to pre-load
  • configNameSearch: the config files searched for
  • configPath: the full path to your configuration file (if found)
  • configBase: the base directory of your configuration file (if found)
  • modulePath: the full path to the local module your project relies on (if found)
  • modulePackage: the contents of the local module's package.json (if found)
  • configFiles: an object of filepaths for each found config file (filepath values will be null if not found)

events

on('preload:before', function(name) {})

Emitted before a module is pre-load. (But for only a module which is specified by opts.preload.)

var Hacker = new Liftoff({ name: 'hacker', preload: 'coffee-script' });
Hacker.on('preload:before', function (name) {
  console.log('Requiring external module: ' + name + '...');
});

on('preload:success', function(name, module) {})

Emitted when a module has been pre-loaded.

var Hacker = new Liftoff({ name: 'hacker' });
Hacker.on('preload:success', function (name, module) {
  console.log('Required external module: ' + name + '...');
  // automatically register coffee-script extensions
  if (name === 'coffee-script') {
    module.register();
  }
});

on('preload:failure', function(name, err) {})

Emitted when a requested module cannot be preloaded.

var Hacker = new Liftoff({ name: 'hacker' });
Hacker.on('preload:failure', function (name, err) {
  console.log('Unable to load:', name, err);
});

on('loader:success, function(name, module) {})

Emitted when a loader that matches an extension has been loaded.

var Hacker = new Liftoff({
  name: 'hacker',
  extensions: {
    '.ts': 'ts-node/register',
  },
});
Hacker.on('loader:success', function (name, module) {
  console.log('Required external module: ' + name + '...');
});

on('loader:failure', function(name, err) {})

Emitted when no loader for an extension can be loaded. Emits an error for each failed loader.

var Hacker = new Liftoff({
  name: 'hacker',
  extensions: {
    '.ts': 'ts-node/register',
  },
});
Hacker.on('loader:failure', function (name, err) {
  console.log('Unable to load:', name, err);
});

on('respawn', function(flags, child) {})

Emitted when Liftoff re-spawns your process (when a v8flags is detected).

var Hacker = new Liftoff({
  name: 'hacker',
  v8flags: ['--harmony'],
});
Hacker.on('respawn', function (flags, child) {
  console.log('Detected node flags:', flags);
  console.log('Respawned to PID:', child.pid);
});

Event will be triggered for this command: hacker --harmony commmand

Examples

Check out how gulp uses Liftoff.

For a bare-bones example, try the hacker project.

To try the example, do the following:

  1. Install the sample project hacker with npm install -g hacker.
  2. Make a Hackerfile.js with some arbitrary javascript it.
  3. Install hacker next to it with npm install hacker.
  4. Run hacker while in the same parent folder.

License

MIT

More Repositories

1

gulp

A toolkit to automate & enhance your workflow
JavaScript
32,962
star
2

vinyl

Virtual file format.
JavaScript
1,272
star
3

vinyl-fs

Vinyl adapter for the file system.
JavaScript
966
star
4

gulp-util

[deprecated] - See https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5
JavaScript
829
star
5

gulp-cli

Command Line Interface for gulp.
JavaScript
397
star
6

plugins

[Unused] Very old plugin search website
JavaScript
280
star
7

interpret

A dictionary of file extensions and associated module loaders.
JavaScript
259
star
8

undertaker

Task registry that allows composition through series/parallel methods.
JavaScript
198
star
9

glob-stream

Readable streamx interface over anymatch.
JavaScript
178
star
10

bach

Compose your async functions with elegance.
JavaScript
133
star
11

fancy-log

Log things, prefixed with a timestamp.
JavaScript
120
star
12

findup-sync

Find the first file matching a given pattern in the current directory or the nearest ancestor directory.
JavaScript
98
star
13

glob-watcher

Watch globs and execute a function upon change, with intelligent defaults for debouncing and queueing.
JavaScript
80
star
14

glob-parent

Extract the non-magic parent path from a glob string.
JavaScript
79
star
15

async-done

Allows libraries to handle various caller provided asynchronous functions uniformly. Maps promises, observables, child processes and streams, and callbacks to callback style.
JavaScript
69
star
16

gulplog

Logger for gulp and gulp plugins.
JavaScript
56
star
17

v8flags

Get available v8 and Node.js flags.
JavaScript
56
star
18

rechoir

Prepare a node environment to require files with different extensions.
JavaScript
48
star
19

replace-ext

Replaces a file extension with another one.
JavaScript
46
star
20

gulpjs.github.io

The gulp website
JavaScript
45
star
21

ordered-read-streams

Combines array of streams into one Readable stream in strict order.
JavaScript
28
star
22

now-and-later

Map over an array or object of values in parallel or series, passing each through the async iterator, with optional lifecycle hooks.
JavaScript
24
star
23

hacker

Hack on your project easily. A liftoff proof-of-concept.
JavaScript
24
star
24

flagged-respawn

A tool for respawning node binaries when special flags are present.
JavaScript
21
star
25

artwork

Artwork for the gulp project
21
star
26

empty-dir

Check if a directory is empty.
JavaScript
20
star
27

sparkles

Namespaced global event emitter.
JavaScript
20
star
28

acceptance

Acceptance test suite for plugins
19
star
29

undertaker-forward-reference

Undertaker custom registry supporting forward referenced tasks.
JavaScript
19
star
30

plugin-error

Error handling for vinyl plugins. Just an abstraction of what's in gulp-util with minor reformatting.
JavaScript
19
star
31

glogg

Global logging utility.
JavaScript
18
star
32

lead

Sink your streams.
JavaScript
17
star
33

undertaker-registry

Default registry in gulp 4.
JavaScript
17
star
34

vinyl-sourcemap

Add/write sourcemaps to/from Vinyl files.
JavaScript
15
star
35

last-run

Capture and retrieve the last time a function was run
JavaScript
14
star
36

path-dirname

Node.js path.dirname() ponyfill
JavaScript
13
star
37

fined

Find a file given a declaration of locations.
JavaScript
12
star
38

async-settle

Settle an async function. It will always complete successfully with an object of the resulting state.
JavaScript
11
star
39

value-or-function

Normalize a value or function, applying extra args to the function
JavaScript
11
star
40

copy-props

Copy properties deeply between two objects
JavaScript
10
star
41

to-through

Wrap a Readable stream in a Transform stream.
JavaScript
10
star
42

semver-greatest-satisfied-range

Find the greatest satisfied semver range from an array of ranges.
JavaScript
9
star
43

mute-stdout

Mute and unmute stdout
JavaScript
9
star
44

resolve-options

Resolve an options object based on configuration.
JavaScript
9
star
45

has-gulplog

Check if gulplog is available before attempting to use it
JavaScript
9
star
46

clone-buffer

Easier Buffer cloning in node.
JavaScript
9
star
47

eslint-config-gulp

Sharable eslint config for gulp projects
JavaScript
8
star
48

async-once

Guarantee a node-style async function is only executed once.
JavaScript
8
star
49

fs-mkdirp-stream

Ensure directories exist before writing to them.
JavaScript
8
star
50

undertaker-common-tasks

Proof-of-concept custom registry that pre-defines tasks.
JavaScript
7
star
51

remove-bom-stream

Remove a UTF8 BOM at the start of the stream.
JavaScript
7
star
52

registry

[Unused] NPM on ElasticSearch
JavaScript
5
star
53

better-stats

A replacement for node's fs.Stats with more utility
JavaScript
5
star
54

theming-log

Creates a logger with theme for text decoration.
JavaScript
4
star
55

undertaker-task-metadata

Proof-of-concept custom registry that attaches metadata to each task.
JavaScript
4
star
56

replace-homedir

Replace user home in a string with another string. Useful for tildifying a path.
JavaScript
4
star
57

evented-require

Require modules and receive events.
JavaScript
3
star
58

each-props

Process object properties deeply.
JavaScript
3
star
59

vinyl-contents

Utility to read the contents of a vinyl file.
JavaScript
3
star
60

.boilerplate

The boilerplate template for gulp packages.
3
star
61

update-template

Updates a gulpjs repository to match our current scaffold.
JavaScript
3
star
62

vinyl-prepare

[deprecated] This module's API was never satisfactory and isn't used in gulp - please don't use.
JavaScript
3
star
63

parse-node-version

Turn node's process.version into something useful.
JavaScript
2
star
64

default-resolution

Get the default resolution time based on the current node version, optionally overridable
JavaScript
2
star
65

.github

GitHub template files for the gulpjs organization.
2
star
66

jscs-preset-gulp

Sharable jscs config for gulp projects
2
star
67

conventional-changelog-gulp

conventional-changelog gulp preset
JavaScript
1
star
68

emit-mapper

Re-emit events while mapping them to new names.
JavaScript
1
star