# add dist

This commit is contained in:
Mario Romano
2016-04-21 11:56:31 +01:00
parent 5914688467
commit 07807e7bc3
13499 changed files with 1808930 additions and 5 deletions

View File

@@ -0,0 +1,233 @@
# gulp changelog
## 3.9.0
- add babel support
- add transpiler fallback support
- add support for some renamed transpilers (livescript, etc)
- add JSCS
- update dependecies (liftoff, interpret)
- documentation tweaks
## 3.8.11
- fix node 0.12/iojs problems
- add node 0.12 and iojs to travis
- update dependencies (liftoff, v8flags)
- documentation tweaks
## 3.8.10
- add link to spanish docs
- update dependencies (archy, semver, mocha, etc)
- documentation tweaks
## 3.8.9
- fix local version undefined output
- add completion for fish shell
- fix powershell completion line splitting
- add support for arbitrary node flags (oops, should have been a minor bump)
- add v8flags dependency
- update dependencies (liftoff)
- documentation tweaks
## 3.8.8
- update dependencies (minimist, tildify)
- documentation tweaks
## 3.8.7
- handle errors a bit better
- update dependencies (gulp-util, semver, etc)
- documentation tweaks
## 3.8.6
- remove executable flag from LICENSE
- update dependencies (chalk, minimist, liftoff, etc)
- documentation tweaks
## 3.8.5
- simplify --silent and --tasks-simple
- fix bug in autocomplete where errors would come out
## 3.8.4
- CLI will use exit code 1 on exit when any task fails during the lifetime of the process
## 3.8.3
- Tweak error formatting to work better with PluginErrors and strings
## 3.8.2
- add manpage generation
## 3.8.1
- the CLI now adds process.env.INIT_CWD which is the original cwd it was launched from
## 3.8.0
- update vinyl-fs
- gulp.src is now a writable passthrough, this means you can use it to add files to your pipeline at any point
- gulp.dest can now take a function to determine the folder
This is now possible!
```js
gulp.src('lib/*.js')
.pipe(uglify())
.pipe(gulp.src('styles/*.css'))
.pipe(gulp.dest(function(file){
// I don't know, you can do something cool here
return 'build/whatever';
}));
```
## 3.7.0
- update vinyl-fs to remove BOM from UTF8 files
- add --tasks-simple flag for plaintext task listings
- updated autocomplete scripts to be simpler and use new --tasks-simple flag
- added support for transpilers via liftoff 0.11 and interpret
- just npm install your compiler (coffee-script for example) and it will work out of the box
## 3.5.5
- update deps
- gulp.dest now support mode option, uses source file mode by default (file.stat.mode)
- use chalk for colors in bin
- update gulp.env deprecation msg to be more helpful
## 3.5.2
- add -V for version on CLI (unix standard)
- -v is deprecated, use -V
- add -T as an alias for --tasks
- documentation
## 3.5
- added `gulp.watch(globs, tasksArray)` sugar
- remove gulp.taskQueue
- deprecate gulp.run
- deprecate gulp.env
- add engineStrict to prevent people with node < 0.9 from installing
## 3.4
- added `--tasks` that prints out the tree of tasks + deps
- global cli + local install mismatch is no longer fatal
- remove tests for fs stuff
- switch core src, dest, and watch to vinyl-fs
- internal cleaning
## 3.3.4
- `--base` is now `--cwd`
## 3.3.3
- support for `--base` CLI arg to change where the search for gulpfile/`--require`s starts
- support for `--gulpfile` CLI arg to point to a gulpfile specifically
## 3.3.0
- file.contents streams are no longer paused coming out of src
- dest now passes files through before they are empty to fix passing to multiple dests
## 3.2.4
- Bug fix - we didn't have any CLI tests
## 3.2.3
- Update dependencies for bug fixes
- autocomplete stuff in the completion folder
## 3.2
- File object is now [vinyl](https://github.com/wearefractal/vinyl)
- .watch() is now [glob-watcher](https://github.com/wearefractal/glob-watcher)
- Fix CLI -v when no gulpfile found
- gulp-util updated
- Logging moved to CLI bin file
- Will cause double logging if you update global CLI to 3.2 but not local
- Will cause no logging if you update local to 3.1 but not global CLI
- Drop support for < 0.9
## 3.1.3
- Move isStream and isBuffer to gulp-util
## 3.1
- Move file class to gulp-util
## 3.0
- Ability to pass multiple globs and glob negations to glob-stream
- Breaking change to the way glob-stream works
- File object is now a class
- file.shortened changed to file.relative
- file.cwd added
- Break out getStats to avoid nesting
- Major code reorganization
## 2.7
- Breaking change to the way options are passed to glob-stream
- Introduce new File object to ease pain of computing shortened names (now a getter)
## 2.4 - 2.6
- Moved stuff to gulp-util
- Quit exposing createGlobStream (just use the glob-stream module)
- More logging
- Prettier time durations
- Tons of documentation changes
- gulp.trigger(tasks...) as a through stream
## 1.2-2.4 (11/12/13)
- src buffer=false fixed for 0.8 and 0.9 (remember to .resume() on these versions before consuming)
- CLI completely rewritten
- Colorful logging
- Uses local version of gulp to run tasks
- Uses findup to locate gulpfile (so you can run it anywhere in your project)
- chdir to gulpfile directory before loading it
- Correct exit codes on errors
- silent flag added to gulp to disable logging
- Fixes to task orchestration (3rd party)
- Better support for globbed directories (thanks @robrich)
## 1.2 (10/28/13)
- Can specify buffer=false on src streams to make file.content a stream
- Can specify read=false on src streams to disable file.content
## 1.1 (10/21/13)
- Can specify run callback
- Can specify task dependencies
- Tasks can accept callback or return promise
- `gulp.verbose` exposes run-time internals
## 1.0 (9/26/13)
- Specify dependency versions
- Updated docs
## 0.2 (8/6/13)
- Rename .files() to .src() and .folder() to .dest()
## 0.1 (7/18/13)
- Initial Release

View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2013-2016 Fractal <contact@wearefractal.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,103 @@
<p align="center">
<a href="http://gulpjs.com">
<img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png">
</a>
<p align="center">The streaming build system</p>
</p>
[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url]
## What is gulp?
- **Automation** - gulp is a toolkit that helps you automate painful or time-consuming tasks in your development workflow.
- **Platform-agnostic** - Integrations are built into all major IDEs and people are using gulp with PHP, .NET, Node.js, Java, and other platforms.
- **Strong Ecosystem** - Use npm modules to do anything you want + over 2000 curated plugins for streaming file transformations
- **Simple** - By providing only a minimal API surface, gulp is easy to learn and simple to use
## Documentation
For a Getting started guide, API docs, recipes, making a plugin, etc. check out or docs!
- Need something reliable? Check out the [documentation for the current release](/docs/README.md)!
- Want to help us test the latest and greatest? Check out the [documentation for the next release](https://github.com/gulpjs/gulp/tree/4.0)!
## Sample `gulpfile.js`
This file will give you a taste of what gulp does.
```js
var gulp = require('gulp');
var coffee = require('gulp-coffee');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var sourcemaps = require('gulp-sourcemaps');
var del = require('del');
var paths = {
scripts: ['client/js/**/*.coffee', '!client/external/**/*.coffee'],
images: 'client/img/**/*'
};
// Not all tasks need to use streams
// A gulpfile is just another node program and you can use any package available on npm
gulp.task('clean', function() {
// You can use multiple globbing patterns as you would with `gulp.src`
return del(['build']);
});
gulp.task('scripts', ['clean'], function() {
// Minify and copy all JavaScript (except vendor scripts)
// with sourcemaps all the way down
return gulp.src(paths.scripts)
.pipe(sourcemaps.init())
.pipe(coffee())
.pipe(uglify())
.pipe(concat('all.min.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest('build/js'));
});
// Copy all static images
gulp.task('images', ['clean'], function() {
return gulp.src(paths.images)
// Pass in options to the task
.pipe(imagemin({optimizationLevel: 5}))
.pipe(gulp.dest('build/img'));
});
// Rerun the task when a file changes
gulp.task('watch', function() {
gulp.watch(paths.scripts, ['scripts']);
gulp.watch(paths.images, ['images']);
});
// The default task (called when you run `gulp` from cli)
gulp.task('default', ['watch', 'scripts', 'images']);
```
## Incremental Builds
We recommend these plugins:
- [gulp-changed](https://github.com/sindresorhus/gulp-changed) - only pass through changed files
- [gulp-cached](https://github.com/contra/gulp-cached) - in-memory file cache, not for operation on sets of files
- [gulp-remember](https://github.com/ahaurw01/gulp-remember) - pairs nicely with gulp-cached
- [gulp-newer](https://github.com/tschaub/gulp-newer) - pass through newer source files only, supports many:1 source:dest
## Want to contribute?
Anyone can help make this project better - check out our [Contributing guide](/CONTRIBUTING.md)!
[downloads-image]: https://img.shields.io/npm/dm/gulp.svg
[npm-url]: https://www.npmjs.com/package/gulp
[npm-image]: https://img.shields.io/npm/v/gulp.svg
[travis-url]: https://travis-ci.org/gulpjs/gulp
[travis-image]: https://img.shields.io/travis/gulpjs/gulp.svg
[coveralls-url]: https://coveralls.io/r/gulpjs/gulp
[coveralls-image]: https://img.shields.io/coveralls/gulpjs/gulp/master.svg
[gitter-url]: https://gitter.im/gulpjs/gulp
[gitter-image]: https://badges.gitter.im/gulpjs/gulp.png

View File

@@ -0,0 +1,212 @@
#!/usr/bin/env node
'use strict';
var gutil = require('gulp-util');
var prettyTime = require('pretty-hrtime');
var chalk = require('chalk');
var semver = require('semver');
var archy = require('archy');
var Liftoff = require('liftoff');
var tildify = require('tildify');
var interpret = require('interpret');
var v8flags = require('v8flags');
var completion = require('../lib/completion');
var argv = require('minimist')(process.argv.slice(2));
var taskTree = require('../lib/taskTree');
// Set env var for ORIGINAL cwd
// before anything touches it
process.env.INIT_CWD = process.cwd();
var cli = new Liftoff({
name: 'gulp',
completions: completion,
extensions: interpret.jsVariants,
v8flags: v8flags,
});
// Exit with 0 or 1
var failed = false;
process.once('exit', function(code) {
if (code === 0 && failed) {
process.exit(1);
}
});
// Parse those args m8
var cliPackage = require('../package');
var versionFlag = argv.v || argv.version;
var tasksFlag = argv.T || argv.tasks;
var tasks = argv._;
var toRun = tasks.length ? tasks : ['default'];
// This is a hold-over until we have a better logging system
// with log levels
var simpleTasksFlag = argv['tasks-simple'];
var shouldLog = !argv.silent && !simpleTasksFlag;
if (!shouldLog) {
gutil.log = function() {};
}
cli.on('require', function(name) {
gutil.log('Requiring external module', chalk.magenta(name));
});
cli.on('requireFail', function(name) {
gutil.log(chalk.red('Failed to load external module'), chalk.magenta(name));
});
cli.on('respawn', function(flags, child) {
var nodeFlags = chalk.magenta(flags.join(', '));
var pid = chalk.magenta(child.pid);
gutil.log('Node flags detected:', nodeFlags);
gutil.log('Respawned to PID:', pid);
});
cli.launch({
cwd: argv.cwd,
configPath: argv.gulpfile,
require: argv.require,
completion: argv.completion,
}, handleArguments);
// The actual logic
function handleArguments(env) {
if (versionFlag && tasks.length === 0) {
gutil.log('CLI version', cliPackage.version);
if (env.modulePackage && typeof env.modulePackage.version !== 'undefined') {
gutil.log('Local version', env.modulePackage.version);
}
process.exit(0);
}
if (!env.modulePath) {
gutil.log(
chalk.red('Local gulp not found in'),
chalk.magenta(tildify(env.cwd))
);
gutil.log(chalk.red('Try running: npm install gulp'));
process.exit(1);
}
if (!env.configPath) {
gutil.log(chalk.red('No gulpfile found'));
process.exit(1);
}
// Check for semver difference between cli and local installation
if (semver.gt(cliPackage.version, env.modulePackage.version)) {
gutil.log(chalk.red('Warning: gulp version mismatch:'));
gutil.log(chalk.red('Global gulp is', cliPackage.version));
gutil.log(chalk.red('Local gulp is', env.modulePackage.version));
}
// Chdir before requiring gulpfile to make sure
// we let them chdir as needed
if (process.cwd() !== env.cwd) {
process.chdir(env.cwd);
gutil.log(
'Working directory changed to',
chalk.magenta(tildify(env.cwd))
);
}
// This is what actually loads up the gulpfile
require(env.configPath);
gutil.log('Using gulpfile', chalk.magenta(tildify(env.configPath)));
var gulpInst = require(env.modulePath);
logEvents(gulpInst);
process.nextTick(function() {
if (simpleTasksFlag) {
return logTasksSimple(env, gulpInst);
}
if (tasksFlag) {
return logTasks(env, gulpInst);
}
gulpInst.start.apply(gulpInst, toRun);
});
}
function logTasks(env, localGulp) {
var tree = taskTree(localGulp.tasks);
tree.label = 'Tasks for ' + chalk.magenta(tildify(env.configPath));
archy(tree)
.split('\n')
.forEach(function(v) {
if (v.trim().length === 0) {
return;
}
gutil.log(v);
});
}
function logTasksSimple(env, localGulp) {
console.log(Object.keys(localGulp.tasks)
.join('\n')
.trim());
}
// Format orchestrator errors
function formatError(e) {
if (!e.err) {
return e.message;
}
// PluginError
if (typeof e.err.showStack === 'boolean') {
return e.err.toString();
}
// Normal error
if (e.err.stack) {
return e.err.stack;
}
// Unknown (string, number, etc.)
return new Error(String(e.err)).stack;
}
// Wire up logging events
function logEvents(gulpInst) {
// Total hack due to poor error management in orchestrator
gulpInst.on('err', function() {
failed = true;
});
gulpInst.on('task_start', function(e) {
// TODO: batch these
// so when 5 tasks start at once it only logs one time with all 5
gutil.log('Starting', '\'' + chalk.cyan(e.task) + '\'...');
});
gulpInst.on('task_stop', function(e) {
var time = prettyTime(e.hrDuration);
gutil.log(
'Finished', '\'' + chalk.cyan(e.task) + '\'',
'after', chalk.magenta(time)
);
});
gulpInst.on('task_err', function(e) {
var msg = formatError(e);
var time = prettyTime(e.hrDuration);
gutil.log(
'\'' + chalk.cyan(e.task) + '\'',
chalk.red('errored after'),
chalk.magenta(time)
);
gutil.log(msg);
});
gulpInst.on('task_not_found', function(err) {
gutil.log(
chalk.red('Task \'' + err.task + '\' is not in your gulpfile')
);
gutil.log('Please check the documentation for proper gulpfile formatting');
process.exit(1);
});
}

View File

@@ -0,0 +1,20 @@
# Completion for gulp
> Thanks to grunt team and Tyler Kellen
To enable tasks auto-completion in shell you should add `eval "$(gulp --completion=shell)"` in your `.shellrc` file.
## Bash
Add `eval "$(gulp --completion=bash)"` to `~/.bashrc`.
## Zsh
Add `eval "$(gulp --completion=zsh)"` to `~/.zshrc`.
## Powershell
Add `Invoke-Expression ((gulp --completion=powershell) -join [System.Environment]::NewLine)` to `$PROFILE`.
## Fish
Add `gulp --completion=fish | source` to `~/.config/fish/config.fish`.

View File

@@ -0,0 +1,27 @@
#!/bin/bash
# Borrowed from grunt-cli
# http://gruntjs.com/
#
# Copyright (c) 2012 Tyler Kellen, contributors
# Licensed under the MIT license.
# https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
# Usage:
#
# To enable bash <tab> completion for gulp, add the following line (minus the
# leading #, which is the bash comment character) to your ~/.bashrc file:
#
# eval "$(gulp --completion=bash)"
# Enable bash autocompletion.
function _gulp_completions() {
# The currently-being-completed word.
local cur="${COMP_WORDS[COMP_CWORD]}"
#Grab tasks
local compls=$(gulp --tasks-simple)
# Tell complete what stuff to show.
COMPREPLY=($(compgen -W "$compls" -- "$cur"))
}
complete -o default -F _gulp_completions gulp

View File

@@ -0,0 +1,10 @@
#!/usr/bin/env fish
# Usage:
#
# To enable fish <tab> completion for gulp, add the following line to
# your ~/.config/fish/config.fish file:
#
# gulp --completion=fish | source
complete -c gulp -a "(gulp --tasks-simple)" -f

View File

@@ -0,0 +1,61 @@
# Copyright (c) 2014 Jason Jarrett
#
# Tab completion for the `gulp`
#
# Usage:
#
# To enable powershell <tab> completion for gulp you need to be running
# at least PowerShell v3 or greater and add the below to your $PROFILE
#
# Invoke-Expression ((gulp --completion=powershell) -join [System.Environment]::NewLine)
#
#
$gulp_completion_Process = {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
# Load up an assembly to read the gulpfile's sha1
if(-not $global:GulpSHA1Managed) {
[Reflection.Assembly]::LoadWithPartialName("System.Security") | out-null
$global:GulpSHA1Managed = new-Object System.Security.Cryptography.SHA1Managed
}
# setup a global (in-memory) cache
if(-not $global:GulpfileShaCache) {
$global:GulpfileShaCache = @{};
}
$cache = $global:GulpfileShaCache;
# Get the gulpfile's sha1
$sha1gulpFile = (resolve-path gulpfile.js -ErrorAction Ignore | %{
$file = [System.IO.File]::Open($_.Path, "open", "read")
[string]::join('', ($global:GulpSHA1Managed.ComputeHash($file) | %{ $_.ToString("x2") }))
$file.Dispose()
})
# lookup the sha1 for previously cached task lists.
if($cache.ContainsKey($sha1gulpFile)){
$tasks = $cache[$sha1gulpFile];
} else {
$tasks = (gulp --tasks-simple).split("`n");
$cache[$sha1gulpFile] = $tasks;
}
$tasks |
where { $_.startswith($commandName) }
Sort-Object |
foreach { New-Object System.Management.Automation.CompletionResult $_, $_, 'ParameterValue', ('{0}' -f $_) }
}
if (-not $global:options) {
$global:options = @{
CustomArgumentCompleters = @{};
NativeArgumentCompleters = @{}
}
}
$global:options['NativeArgumentCompleters']['gulp'] = $gulp_completion_Process
$function:tabexpansion2 = $function:tabexpansion2 -replace 'End\r\n{','End { if ($null -ne $options) { $options += $global:options} else {$options = $global:options}'

View File

@@ -0,0 +1,25 @@
#!/bin/zsh
# Borrowed from grunt-cli
# http://gruntjs.com/
#
# Copyright (c) 2012 Tyler Kellen, contributors
# Licensed under the MIT license.
# https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
# Usage:
#
# To enable zsh <tab> completion for gulp, add the following line (minus the
# leading #, which is the zsh comment character) to your ~/.zshrc file:
#
# eval "$(gulp --completion=zsh)"
# Enable zsh autocompletion.
function _gulp_completion() {
# Grab tasks
compls=$(gulp --tasks-simple)
completions=(${=compls})
compadd -- $completions
}
compdef _gulp_completion gulp

View File

@@ -0,0 +1,40 @@
.TH "GULP" "" "February 2016" "" ""
.SH "NAME"
\fBgulp\fR
.SH gulp CLI docs
.SS Flags
.P
gulp has very few flags to know about\. All other flags are for tasks to use if needed\.
.RS 0
.IP \(bu 2
\fB\-v\fP or \fB\-\-version\fP will display the global and local gulp versions
.IP \(bu 2
\fB\-\-require <module path>\fP will require a module before running the gulpfile\. This is useful for transpilers but also has other applications\. You can use multiple \fB\-\-require\fP flags
.IP \(bu 2
\fB\-\-gulpfile <gulpfile path>\fP will manually set path of gulpfile\. Useful if you have multiple gulpfiles\. This will set the CWD to the gulpfile directory as well
.IP \(bu 2
\fB\-\-cwd <dir path>\fP will manually set the CWD\. The search for the gulpfile, as well as the relativity of all requires will be from here
.IP \(bu 2
\fB\-T\fP or \fB\-\-tasks\fP will display the task dependency tree for the loaded gulpfile
.IP \(bu 2
\fB\-\-tasks\-simple\fP will display a plaintext list of tasks for the loaded gulpfile
.IP \(bu 2
\fB\-\-color\fP will force gulp and gulp plugins to display colors even when no color support is detected
.IP \(bu 2
\fB\-\-no\-color\fP will force gulp and gulp plugins to not display colors even when color support is detected
.IP \(bu 2
\fB\-\-silent\fP will disable all gulp logging
.RE
.P
The CLI adds process\.env\.INIT_CWD which is the original cwd it was launched from\.
.SS Task specific flags
.P
Refer to this StackOverflow \fIhttp://stackoverflow\.com/questions/23023650/is\-it\-possible\-to\-pass\-a\-flag\-to\-gulp\-to\-have\-it\-run\-tasks\-in\-different\-ways\fR link for how to add task specific flags
.SS Tasks
.P
Tasks can be executed by running \fBgulp <task> <othertask>\fP\|\. Just running \fBgulp\fP will execute the task you registered called \fBdefault\fP\|\. If there is no \fBdefault\fP task gulp will error\.
.SS Compilers
.P
You can find a list of supported languages at interpret \fIhttps://github\.com/tkellen/node\-interpret#jsvariants\fR\|\. If you would like to add support for a new language send pull request/open issues there\.

View File

@@ -0,0 +1,63 @@
'use strict';
var util = require('util');
var Orchestrator = require('orchestrator');
var gutil = require('gulp-util');
var deprecated = require('deprecated');
var vfs = require('vinyl-fs');
function Gulp() {
Orchestrator.call(this);
}
util.inherits(Gulp, Orchestrator);
Gulp.prototype.task = Gulp.prototype.add;
Gulp.prototype.run = function() {
// `run()` is deprecated as of 3.5 and will be removed in 4.0
// Use task dependencies instead
// Impose our opinion of "default" tasks onto orchestrator
var tasks = arguments.length ? arguments : ['default'];
this.start.apply(this, tasks);
};
Gulp.prototype.src = vfs.src;
Gulp.prototype.dest = vfs.dest;
Gulp.prototype.watch = function(glob, opt, fn) {
if (typeof opt === 'function' || Array.isArray(opt)) {
fn = opt;
opt = null;
}
// Array of tasks given
if (Array.isArray(fn)) {
return vfs.watch(glob, opt, function() {
this.start.apply(this, fn);
}.bind(this));
}
return vfs.watch(glob, opt, fn);
};
// Let people use this class from our instance
Gulp.prototype.Gulp = Gulp;
// Deprecations
deprecated.field('gulp.env has been deprecated. ' +
'Use your own CLI parser instead. ' +
'We recommend using yargs or minimist.',
console.warn,
Gulp.prototype,
'env',
gutil.env
);
Gulp.prototype.run = deprecated.method('gulp.run() has been deprecated. ' +
'Use task dependencies or gulp.watch task triggering instead.',
console.warn,
Gulp.prototype.run
);
var inst = new Gulp();
module.exports = inst;

View File

@@ -0,0 +1,19 @@
Copyright Node.js contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.

View File

@@ -0,0 +1,3 @@
# core-util-is
The `util.is*` functions introduced in Node v0.12.

View File

@@ -0,0 +1,604 @@
diff --git a/lib/util.js b/lib/util.js
index a03e874..9074e8e 100644
--- a/lib/util.js
+++ b/lib/util.js
@@ -19,430 +19,6 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
-var formatRegExp = /%[sdj%]/g;
-exports.format = function(f) {
- if (!isString(f)) {
- var objects = [];
- for (var i = 0; i < arguments.length; i++) {
- objects.push(inspect(arguments[i]));
- }
- return objects.join(' ');
- }
-
- var i = 1;
- var args = arguments;
- var len = args.length;
- var str = String(f).replace(formatRegExp, function(x) {
- if (x === '%%') return '%';
- if (i >= len) return x;
- switch (x) {
- case '%s': return String(args[i++]);
- case '%d': return Number(args[i++]);
- case '%j':
- try {
- return JSON.stringify(args[i++]);
- } catch (_) {
- return '[Circular]';
- }
- default:
- return x;
- }
- });
- for (var x = args[i]; i < len; x = args[++i]) {
- if (isNull(x) || !isObject(x)) {
- str += ' ' + x;
- } else {
- str += ' ' + inspect(x);
- }
- }
- return str;
-};
-
-
-// Mark that a method should not be used.
-// Returns a modified function which warns once by default.
-// If --no-deprecation is set, then it is a no-op.
-exports.deprecate = function(fn, msg) {
- // Allow for deprecating things in the process of starting up.
- if (isUndefined(global.process)) {
- return function() {
- return exports.deprecate(fn, msg).apply(this, arguments);
- };
- }
-
- if (process.noDeprecation === true) {
- return fn;
- }
-
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (process.throwDeprecation) {
- throw new Error(msg);
- } else if (process.traceDeprecation) {
- console.trace(msg);
- } else {
- console.error(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
- }
-
- return deprecated;
-};
-
-
-var debugs = {};
-var debugEnviron;
-exports.debuglog = function(set) {
- if (isUndefined(debugEnviron))
- debugEnviron = process.env.NODE_DEBUG || '';
- set = set.toUpperCase();
- if (!debugs[set]) {
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
- var pid = process.pid;
- debugs[set] = function() {
- var msg = exports.format.apply(exports, arguments);
- console.error('%s %d: %s', set, pid, msg);
- };
- } else {
- debugs[set] = function() {};
- }
- }
- return debugs[set];
-};
-
-
-/**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
- *
- * @param {Object} obj The object to print out.
- * @param {Object} opts Optional options object that alters the output.
- */
-/* legacy: obj, showHidden, depth, colors*/
-function inspect(obj, opts) {
- // default options
- var ctx = {
- seen: [],
- stylize: stylizeNoColor
- };
- // legacy...
- if (arguments.length >= 3) ctx.depth = arguments[2];
- if (arguments.length >= 4) ctx.colors = arguments[3];
- if (isBoolean(opts)) {
- // legacy...
- ctx.showHidden = opts;
- } else if (opts) {
- // got an "options" object
- exports._extend(ctx, opts);
- }
- // set default options
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
- if (isUndefined(ctx.depth)) ctx.depth = 2;
- if (isUndefined(ctx.colors)) ctx.colors = false;
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
- if (ctx.colors) ctx.stylize = stylizeWithColor;
- return formatValue(ctx, obj, ctx.depth);
-}
-exports.inspect = inspect;
-
-
-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
-inspect.colors = {
- 'bold' : [1, 22],
- 'italic' : [3, 23],
- 'underline' : [4, 24],
- 'inverse' : [7, 27],
- 'white' : [37, 39],
- 'grey' : [90, 39],
- 'black' : [30, 39],
- 'blue' : [34, 39],
- 'cyan' : [36, 39],
- 'green' : [32, 39],
- 'magenta' : [35, 39],
- 'red' : [31, 39],
- 'yellow' : [33, 39]
-};
-
-// Don't use 'blue' not visible on cmd.exe
-inspect.styles = {
- 'special': 'cyan',
- 'number': 'yellow',
- 'boolean': 'yellow',
- 'undefined': 'grey',
- 'null': 'bold',
- 'string': 'green',
- 'date': 'magenta',
- // "name": intentionally not styling
- 'regexp': 'red'
-};
-
-
-function stylizeWithColor(str, styleType) {
- var style = inspect.styles[styleType];
-
- if (style) {
- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
- '\u001b[' + inspect.colors[style][1] + 'm';
- } else {
- return str;
- }
-}
-
-
-function stylizeNoColor(str, styleType) {
- return str;
-}
-
-
-function arrayToHash(array) {
- var hash = {};
-
- array.forEach(function(val, idx) {
- hash[val] = true;
- });
-
- return hash;
-}
-
-
-function formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (ctx.customInspect &&
- value &&
- isFunction(value.inspect) &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== exports.inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- var ret = value.inspect(recurseTimes, ctx);
- if (!isString(ret)) {
- ret = formatValue(ctx, ret, recurseTimes);
- }
- return ret;
- }
-
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
- }
-
- // Look up the keys of the object.
- var keys = Object.keys(value);
- var visibleKeys = arrayToHash(keys);
-
- if (ctx.showHidden) {
- keys = Object.getOwnPropertyNames(value);
- }
-
- // Some type of object without properties can be shortcutted.
- if (keys.length === 0) {
- if (isFunction(value)) {
- var name = value.name ? ': ' + value.name : '';
- return ctx.stylize('[Function' + name + ']', 'special');
- }
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- }
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
- }
- if (isError(value)) {
- return formatError(value);
- }
- }
-
- var base = '', array = false, braces = ['{', '}'];
-
- // Make Array say that they are Array
- if (isArray(value)) {
- array = true;
- braces = ['[', ']'];
- }
-
- // Make functions say that they are functions
- if (isFunction(value)) {
- var n = value.name ? ': ' + value.name : '';
- base = ' [Function' + n + ']';
- }
-
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
- }
-
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
- }
-
- // Make error with message first say the error
- if (isError(value)) {
- base = ' ' + formatError(value);
- }
-
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
- }
-
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- } else {
- return ctx.stylize('[Object]', 'special');
- }
- }
-
- ctx.seen.push(value);
-
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
- }
-
- ctx.seen.pop();
-
- return reduceToSingleString(output, base, braces);
-}
-
-
-function formatPrimitive(ctx, value) {
- if (isUndefined(value))
- return ctx.stylize('undefined', 'undefined');
- if (isString(value)) {
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
- }
- if (isNumber(value)) {
- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
- if (value === 0 && 1 / value < 0)
- return ctx.stylize('-0', 'number');
- return ctx.stylize('' + value, 'number');
- }
- if (isBoolean(value))
- return ctx.stylize('' + value, 'boolean');
- // For some reason typeof null is "object", so special case here.
- if (isNull(value))
- return ctx.stylize('null', 'null');
-}
-
-
-function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
-}
-
-
-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (hasOwnProperty(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
- }
- }
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
-}
-
-
-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str, desc;
- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
- if (desc.get) {
- if (desc.set) {
- str = ctx.stylize('[Getter/Setter]', 'special');
- } else {
- str = ctx.stylize('[Getter]', 'special');
- }
- } else {
- if (desc.set) {
- str = ctx.stylize('[Setter]', 'special');
- }
- }
- if (!hasOwnProperty(visibleKeys, key)) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (ctx.seen.indexOf(desc.value) < 0) {
- if (isNull(recurseTimes)) {
- str = formatValue(ctx, desc.value, null);
- } else {
- str = formatValue(ctx, desc.value, recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
- }
- }
- if (isUndefined(name)) {
- if (array && key.match(/^\d+$/)) {
- return str;
- }
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
- }
- }
-
- return name + ': ' + str;
-}
-
-
-function reduceToSingleString(output, base, braces) {
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
- }, 0);
-
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
- }
-
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
-}
-
-
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
@@ -522,166 +98,10 @@ function isPrimitive(arg) {
exports.isPrimitive = isPrimitive;
function isBuffer(arg) {
- return arg instanceof Buffer;
+ return Buffer.isBuffer(arg);
}
exports.isBuffer = isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
-}
-
-
-function pad(n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
-}
-
-
-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
- 'Oct', 'Nov', 'Dec'];
-
-// 26 Feb 16:19:34
-function timestamp() {
- var d = new Date();
- var time = [pad(d.getHours()),
- pad(d.getMinutes()),
- pad(d.getSeconds())].join(':');
- return [d.getDate(), months[d.getMonth()], time].join(' ');
-}
-
-
-// log is just a thin wrapper to console.log that prepends a timestamp
-exports.log = function() {
- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
-};
-
-
-/**
- * Inherit the prototype methods from one constructor into another.
- *
- * The Function.prototype.inherits from lang.js rewritten as a standalone
- * function (not on Function.prototype). NOTE: If this file is to be loaded
- * during bootstrapping this function needs to be rewritten using some native
- * functions as prototype setup using normal JavaScript does not work as
- * expected during bootstrapping (see mirror.js in r114903).
- *
- * @param {function} ctor Constructor function which needs to inherit the
- * prototype.
- * @param {function} superCtor Constructor function to inherit prototype from.
- */
-exports.inherits = function(ctor, superCtor) {
- ctor.super_ = superCtor;
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
-};
-
-exports._extend = function(origin, add) {
- // Don't do anything if add isn't an object
- if (!add || !isObject(add)) return origin;
-
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[i]];
- }
- return origin;
-};
-
-function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
-}
-
-
-// Deprecated old stuff.
-
-exports.p = exports.deprecate(function() {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- console.error(exports.inspect(arguments[i]));
- }
-}, 'util.p: Use console.error() instead');
-
-
-exports.exec = exports.deprecate(function() {
- return require('child_process').exec.apply(this, arguments);
-}, 'util.exec is now called `child_process.exec`.');
-
-
-exports.print = exports.deprecate(function() {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- process.stdout.write(String(arguments[i]));
- }
-}, 'util.print: Use console.log instead');
-
-
-exports.puts = exports.deprecate(function() {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- process.stdout.write(arguments[i] + '\n');
- }
-}, 'util.puts: Use console.log instead');
-
-
-exports.debug = exports.deprecate(function(x) {
- process.stderr.write('DEBUG: ' + x + '\n');
-}, 'util.debug: Use console.error instead');
-
-
-exports.error = exports.deprecate(function(x) {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- process.stderr.write(arguments[i] + '\n');
- }
-}, 'util.error: Use console.error instead');
-
-
-exports.pump = exports.deprecate(function(readStream, writeStream, callback) {
- var callbackCalled = false;
-
- function call(a, b, c) {
- if (callback && !callbackCalled) {
- callback(a, b, c);
- callbackCalled = true;
- }
- }
-
- readStream.addListener('data', function(chunk) {
- if (writeStream.write(chunk) === false) readStream.pause();
- });
-
- writeStream.addListener('drain', function() {
- readStream.resume();
- });
-
- readStream.addListener('end', function() {
- writeStream.end();
- });
-
- readStream.addListener('close', function() {
- call();
- });
-
- readStream.addListener('error', function(err) {
- writeStream.end();
- call(err);
- });
-
- writeStream.addListener('error', function(err) {
- readStream.destroy();
- call(err);
- });
-}, 'util.pump(): Use readableStream.pipe() instead');
-
-
-var uv;
-exports._errnoException = function(err, syscall) {
- if (isUndefined(uv)) uv = process.binding('uv');
- var errname = uv.errname(err);
- var e = new Error(syscall + ' ' + errname);
- e.code = errname;
- e.errno = errname;
- e.syscall = syscall;
- return e;
-};
+}

View File

@@ -0,0 +1,89 @@
{
"_args": [
[
"core-util-is@~1.0.0",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/readdirp/node_modules/readable-stream"
],
[
"core-util-is@~1.0.0",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/readable-stream"
]
],
"_from": "core-util-is@>=1.0.0 <1.1.0",
"_id": "core-util-is@1.0.2",
"_inCache": true,
"_installable": true,
"_location": "/gulp/core-util-is",
"_nodeVersion": "4.0.0",
"_npmUser": {
"email": "i@izs.me",
"name": "isaacs"
},
"_npmVersion": "3.3.2",
"_phantomChildren": {},
"_requested": {
"name": "core-util-is",
"raw": "core-util-is@~1.0.0",
"rawSpec": "~1.0.0",
"scope": null,
"spec": ">=1.0.0 <1.1.0",
"type": "range"
},
"_requiredBy": [
"/gulp/readable-stream",
"/gulp/vinyl-fs/readable-stream"
],
"_shrinkwrap": null,
"_spec": "core-util-is@~1.0.0",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/readable-stream",
"author": {
"email": "i@izs.me",
"name": "Isaac Z. Schlueter",
"url": "http://blog.izs.me/"
},
"bugs": {
"url": "https://github.com/isaacs/core-util-is/issues"
},
"dependencies": {},
"description": "The `util.is*` functions introduced in Node v0.12.",
"devDependencies": {
"tap": "^2.3.0"
},
"directories": {},
"dist": {
"shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7",
"tarball": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz"
},
"gitHead": "a177da234df5638b363ddc15fa324619a38577c8",
"homepage": "https://github.com/isaacs/core-util-is#readme",
"keywords": [
"util",
"isBuffer",
"isArray",
"isNumber",
"isString",
"isRegExp",
"isThis",
"isThat",
"polyfill"
],
"license": "MIT",
"main": "lib/util.js",
"maintainers": [
{
"email": "i@izs.me",
"name": "isaacs"
}
],
"name": "core-util-is",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/isaacs/core-util-is.git"
},
"scripts": {
"test": "tap test.js"
},
"version": "1.0.2"
}

View File

@@ -0,0 +1,68 @@
var assert = require('tap');
var t = require('./lib/util');
assert.equal(t.isArray([]), true);
assert.equal(t.isArray({}), false);
assert.equal(t.isBoolean(null), false);
assert.equal(t.isBoolean(true), true);
assert.equal(t.isBoolean(false), true);
assert.equal(t.isNull(null), true);
assert.equal(t.isNull(undefined), false);
assert.equal(t.isNull(false), false);
assert.equal(t.isNull(), false);
assert.equal(t.isNullOrUndefined(null), true);
assert.equal(t.isNullOrUndefined(undefined), true);
assert.equal(t.isNullOrUndefined(false), false);
assert.equal(t.isNullOrUndefined(), true);
assert.equal(t.isNumber(null), false);
assert.equal(t.isNumber('1'), false);
assert.equal(t.isNumber(1), true);
assert.equal(t.isString(null), false);
assert.equal(t.isString('1'), true);
assert.equal(t.isString(1), false);
assert.equal(t.isSymbol(null), false);
assert.equal(t.isSymbol('1'), false);
assert.equal(t.isSymbol(1), false);
assert.equal(t.isSymbol(Symbol()), true);
assert.equal(t.isUndefined(null), false);
assert.equal(t.isUndefined(undefined), true);
assert.equal(t.isUndefined(false), false);
assert.equal(t.isUndefined(), true);
assert.equal(t.isRegExp(null), false);
assert.equal(t.isRegExp('1'), false);
assert.equal(t.isRegExp(new RegExp()), true);
assert.equal(t.isObject({}), true);
assert.equal(t.isObject([]), true);
assert.equal(t.isObject(new RegExp()), true);
assert.equal(t.isObject(new Date()), true);
assert.equal(t.isDate(null), false);
assert.equal(t.isDate('1'), false);
assert.equal(t.isDate(new Date()), true);
assert.equal(t.isError(null), false);
assert.equal(t.isError({ err: true }), false);
assert.equal(t.isError(new Error()), true);
assert.equal(t.isFunction(null), false);
assert.equal(t.isFunction({ }), false);
assert.equal(t.isFunction(function() {}), true);
assert.equal(t.isPrimitive(null), true);
assert.equal(t.isPrimitive(''), true);
assert.equal(t.isPrimitive(0), true);
assert.equal(t.isPrimitive(new Date()), false);
assert.equal(t.isBuffer(null), false);
assert.equal(t.isBuffer({}), false);
assert.equal(t.isBuffer(new Buffer(0)), true);

View File

@@ -0,0 +1,20 @@
(c) 2007-2009 Steven Levithan <stevenlevithan.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,82 @@
# dateformat
A node.js package for Steven Levithan's excellent [dateFormat()][dateformat] function.
[![Build Status](https://travis-ci.org/felixge/node-dateformat.svg)](https://travis-ci.org/felixge/node-dateformat)
## Modifications
* Removed the `Date.prototype.format` method. Sorry folks, but extending native prototypes is for suckers.
* Added a `module.exports = dateFormat;` statement at the bottom
* Added the placeholder `N` to get the ISO 8601 numeric representation of the day of the week
## Installation
```bash
$ npm install dateformat
$ dateformat --help
```
## Usage
As taken from Steven's post, modified to match the Modifications listed above:
```js
var dateFormat = require('dateformat');
var now = new Date();
// Basic usage
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
// You can use one of several named masks
dateFormat(now, "isoDateTime");
// 2007-06-09T17:46:21
// ...Or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
dateFormat(now, "hammerTime");
// 17:46! Can't touch this!
// When using the standalone dateFormat function,
// you can also provide the date as a string
dateFormat("Jun 9 2007", "fullDate");
// Saturday, June 9, 2007
// Note that if you don't include the mask argument,
// dateFormat.masks.default is used
dateFormat(now);
// Sat Jun 09 2007 17:46:21
// And if you don't include the date argument,
// the current date and time is used
dateFormat();
// Sat Jun 09 2007 17:46:22
// You can also skip the date argument (as long as your mask doesn't
// contain any numbers), in which case the current date/time is used
dateFormat("longTime");
// 5:46:22 PM EST
// And finally, you can convert local time to UTC time. Simply pass in
// true as an additional argument (no argument skipping allowed in this case):
dateFormat(now, "longTime", true);
// 10:46:21 PM UTC
// ...Or add the prefix "UTC:" or "GMT:" to your mask.
dateFormat(now, "UTC:h:MM:ss TT Z");
// 10:46:21 PM UTC
// You can also get the ISO 8601 week of the year:
dateFormat(now, "W");
// 42
// and also get the ISO 8601 numeric representation of the day of the week:
dateFormat(now,"N");
// 6
```
## License
(c) 2007-2009 Steven Levithan [stevenlevithan.com][stevenlevithan], MIT license.
[dateformat]: http://blog.stevenlevithan.com/archives/date-time-format
[stevenlevithan]: http://stevenlevithan.com/

View File

@@ -0,0 +1,75 @@
#!/usr/bin/env node
/**
* dateformat <https://github.com/felixge/node-dateformat>
*
* Copyright (c) 2014 Charlike Mike Reagent (cli), contributors.
* Released under the MIT license.
*/
'use strict';
/**
* Module dependencies.
*/
var dateFormat = require('../lib/dateformat');
var meow = require('meow');
var stdin = require('get-stdin');
var cli = meow({
pkg: '../package.json',
help: [
'Options',
' --help Show this help',
' --version Current version of package',
' -d | --date Date that want to format (Date object as Number or String)',
' -m | --mask Mask that will use to format the date',
' -u | --utc Convert local time to UTC time or use `UTC:` prefix in mask',
' -g | --gmt You can use `GMT:` prefix in mask',
'',
'Usage',
' dateformat [date] [mask]',
' dateformat "Nov 26 2014" "fullDate"',
' dateformat 1416985417095 "dddd, mmmm dS, yyyy, h:MM:ss TT"',
' dateformat 1315361943159 "W"',
' dateformat "UTC:h:MM:ss TT Z"',
' dateformat "longTime" true',
' dateformat "longTime" false true',
' dateformat "Jun 9 2007" "fullDate" true',
' date +%s | dateformat',
''
].join('\n')
})
var date = cli.input[0] || cli.flags.d || cli.flags.date || Date.now();
var mask = cli.input[1] || cli.flags.m || cli.flags.mask || dateFormat.masks.default;
var utc = cli.input[2] || cli.flags.u || cli.flags.utc || false;
var gmt = cli.input[3] || cli.flags.g || cli.flags.gmt || false;
utc = utc === 'true' ? true : false;
gmt = gmt === 'true' ? true : false;
if (!cli.input.length) {
stdin(function(date) {
console.log(dateFormat(date, dateFormat.masks.default, utc, gmt));
});
return;
}
if (cli.input.length === 1 && date) {
mask = date;
date = Date.now();
console.log(dateFormat(date, mask, utc, gmt));
return;
}
if (cli.input.length >= 2 && date && mask) {
if (mask === 'true' || mask === 'false') {
utc = mask === 'true' ? true : false;
gmt = !utc;
mask = date
date = Date.now();
}
console.log(dateFormat(date, mask, utc, gmt));
return;
}

View File

@@ -0,0 +1,100 @@
{
"_args": [
[
"dateformat@^1.0.11",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/gulp-util"
]
],
"_from": "dateformat@>=1.0.11 <2.0.0",
"_id": "dateformat@1.0.12",
"_inCache": true,
"_installable": true,
"_location": "/gulp/dateformat",
"_nodeVersion": "0.12.7",
"_npmUser": {
"email": "felix@debuggable.com",
"name": "felixge"
},
"_npmVersion": "2.11.3",
"_phantomChildren": {},
"_requested": {
"name": "dateformat",
"raw": "dateformat@^1.0.11",
"rawSpec": "^1.0.11",
"scope": null,
"spec": ">=1.0.11 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/gulp/gulp-util"
],
"_resolved": "https://registry.npmjs.org/dateformat/-/dateformat-1.0.12.tgz",
"_shasum": "9f124b67594c937ff706932e4a642cca8dbbfee9",
"_shrinkwrap": null,
"_spec": "dateformat@^1.0.11",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/gulp-util",
"author": {
"name": "Steven Levithan"
},
"bin": {
"dateformat": "bin/cli.js"
},
"bugs": {
"url": "https://github.com/felixge/node-dateformat/issues"
},
"contributors": [
{
"name": "Steven Levithan"
},
{
"email": "felix@debuggable.com",
"name": "Felix Geisendörfer"
},
{
"email": "dev@tavan.de",
"name": "Christoph Tavan"
}
],
"dependencies": {
"get-stdin": "^4.0.1",
"meow": "^3.3.0"
},
"description": "A node.js package for Steven Levithan's excellent dateFormat() function.",
"devDependencies": {
"mocha": "2.0.1",
"underscore": "1.7.0"
},
"directories": {},
"dist": {
"shasum": "9f124b67594c937ff706932e4a642cca8dbbfee9",
"tarball": "https://registry.npmjs.org/dateformat/-/dateformat-1.0.12.tgz"
},
"engines": {
"node": "*"
},
"gitHead": "17364d40e61c06f6de228ab94f3660a27f357f01",
"homepage": "https://github.com/felixge/node-dateformat",
"license": "MIT",
"main": "lib/dateformat",
"maintainers": [
{
"email": "felix@debuggable.com",
"name": "felixge"
},
{
"email": "dev@tavan.de",
"name": "ctavan"
}
],
"name": "dateformat",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/felixge/node-dateformat.git"
},
"scripts": {
"test": "mocha"
},
"version": "1.0.12"
}

View File

@@ -0,0 +1,15 @@
var assert = require('assert');
var dateFormat = require('./../lib/dateformat');
describe('dayOfWeek', function() {
it('should correctly format the timezone part', function(done) {
var start = 10; // the 10 of March 2013 is a Sunday
for(var dow = 1; dow <= 7; dow++){
var date = new Date('2013-03-' + (start + dow));
var N = dateFormat(date, 'N');
assert.strictEqual(N, String(dow));
}
done();
});
});

View File

@@ -0,0 +1,76 @@
var assert = require('assert');
var _ = require('underscore');
var dateFormat = require('../lib/dateformat');
var expects = {
'default': 'Wed Nov 26 2014 13:19:44',
'shortDate': '11/26/14',
'mediumDate': 'Nov 26, 2014',
'longDate': 'November 26, 2014',
'fullDate': 'Wednesday, November 26, 2014',
'shortTime': '1:19 PM',
'mediumTime': '1:19:44 PM',
'longTime': '1:19:44 PM %TZ_PREFIX%%TZ_OFFSET%',
'isoDate': '2014-11-26',
'isoTime': '13:19:44',
'isoDateTime': '2014-11-26T13:19:44%TZ_OFFSET%',
'isoUtcDateTime': '',
'expiresHeaderFormat': 'Wed, 26 Nov 2014 13:19:44 %TZ_PREFIX%%TZ_OFFSET%'
};
function pad(num, size) {
var s = num + '';
while (s.length < size) {
s = '0' + s;
}
return s;
}
function parseOffset(date) {
var offset = date.getTimezoneOffset();
var hours = Math.floor(-1 * offset / 60);
var minutes = (-1 * offset) - (hours * 60);
var sign = offset > 0 ? '-' : '+';
return {
offset: offset,
hours: hours,
minutes: minutes,
sign: sign,
};
}
function timezoneOffset(date) {
var offset = parseOffset(date);
return offset.sign + pad(offset.hours, 2) + pad(offset.minutes, 2);
}
describe('dateformat([now], [mask])', function() {
_.each(dateFormat.masks, function(value, key) {
it('should format `' + key + '` mask', function(done) {
var now = new Date(2014, 10, 26, 13, 19, 44);
var tzOffset = timezoneOffset(now);
var expected = expects[key].replace(/%TZ_PREFIX%/, 'GMT')
.replace(/%TZ_OFFSET%/g, tzOffset)
.replace(/GMT\+0000/g, 'UTC');
if (key === 'isoUtcDateTime') {
var offset = parseOffset(now);
now.setHours(now.getHours() - offset.hours,
now.getMinutes() - offset.minutes);
var expected = now.toISOString().replace(/\.000/g, '');
}
var actual = dateFormat(now, key);
assert.strictEqual(actual, expected);
done();
});
});
it('should use `default` mask, when `mask` is empty', function(done) {
var now = new Date(2014, 10, 26, 13, 19, 44);
var expected = expects['default'];
var actual = dateFormat(now);
assert.strictEqual(actual, expected);
done();
});
});

View File

@@ -0,0 +1,11 @@
var assert = require('assert');
var dateFormat = require('./../lib/dateformat');
describe('isoUtcDateTime', function() {
it('should correctly format the timezone part', function(done) {
var actual = dateFormat('2014-06-02T13:23:21-08:00', 'isoUtcDateTime');
assert.strictEqual(actual, '2014-06-02T21:23:21Z');
done();
});
});

View File

@@ -0,0 +1,4 @@
var dateFormat = require('../lib/dateformat.js');
var val = process.argv[2] || new Date();
console.log(dateFormat(val, 'W'));

View File

@@ -0,0 +1,27 @@
#!/bin/bash
# this just takes php's date() function as a reference to check if week of year
# is calculated correctly in the range from 1970 .. 2038 by brute force...
SEQ="seq"
SYSTEM=`uname`
if [ "$SYSTEM" = "Darwin" ]; then
SEQ="jot"
fi
for YEAR in {1970..2038}; do
for MONTH in {1..12}; do
DAYS=$(cal $MONTH $YEAR | egrep "28|29|30|31" |tail -1 |awk '{print $NF}')
for DAY in $( $SEQ $DAYS ); do
DATE=$YEAR-$MONTH-$DAY
echo -n $DATE ...
NODEVAL=$(node test_weekofyear.js $DATE)
PHPVAL=$(php -r "echo intval(date('W', strtotime('$DATE')));")
if [ "$NODEVAL" -ne "$PHPVAL" ]; then
echo "MISMATCH: node: $NODEVAL vs php: $PHPVAL for date $DATE"
else
echo " OK"
fi
done
done
done

View File

@@ -0,0 +1,61 @@
2.0.1 / 2015-04-25
==================
* Use an inline `isArray` check, for ES3 browsers. (#27)
* Some old browsers fail when an identifier is `toString`
* Test latest `node` and `io.js` versions on `travis-ci`; speed up builds
* Add license info to package.json (#25)
* Update `tape`, `jscs`
* Adding a CHANGELOG
2.0.0 / 2014-10-01
==================
* Increase code coverage to 100%; run code coverage as part of tests
* Add `npm run lint`; Run linter as part of tests
* Remove nodeType and setInterval checks in isPlainObject
* Updating `tape`, `jscs`, `covert`
* General style and README cleanup
1.3.0 / 2014-06-20
==================
* Add component.json for browser support (#18)
* Use SVG for badges in README (#16)
* Updating `tape`, `covert`
* Updating travis-ci to work with multiple node versions
* Fix `deep === false` bug (returning target as {}) (#14)
* Fixing constructor checks in isPlainObject
* Adding additional test coverage
* Adding `npm run coverage`
* Add LICENSE (#13)
* Adding a warning about `false`, per #11
* General style and whitespace cleanup
1.2.1 / 2013-09-14
==================
* Fixing hasOwnProperty bugs that would only have shown up in specific browsers. Fixes #8
* Updating `tape`
1.2.0 / 2013-09-02
==================
* Updating the README: add badges
* Adding a missing variable reference.
* Using `tape` instead of `buster` for tests; add more tests (#7)
* Adding node 0.10 to Travis CI (#6)
* Enabling "npm test" and cleaning up package.json (#5)
* Add Travis CI.
1.1.3 / 2012-12-06
==================
* Added unit tests.
* Ensure extend function is named. (Looks nicer in a stack trace.)
* README cleanup.
1.1.1 / 2012-11-07
==================
* README cleanup.
* Added installation instructions.
* Added a missing semicolon
1.0.0 / 2012-04-08
==================
* Initial commit

View File

@@ -0,0 +1,23 @@
The MIT License (MIT)
Copyright (c) 2014 Stefan Thomas
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,62 @@
[![Build Status][travis-svg]][travis-url]
[![dependency status][deps-svg]][deps-url]
[![dev dependency status][dev-deps-svg]][dev-deps-url]
# extend() for Node.js <sup>[![Version Badge][npm-version-png]][npm-url]</sup>
`node-extend` is a port of the classic extend() method from jQuery. It behaves as you expect. It is simple, tried and true.
## Installation
This package is available on [npm][npm-url] as: `extend`
``` sh
npm install extend
```
## Usage
**Syntax:** extend **(** [`deep`], `target`, `object1`, [`objectN`] **)**
*Extend one object with one or more others, returning the modified object.*
Keep in mind that the target object will be modified, and will be returned from extend().
If a boolean true is specified as the first argument, extend performs a deep copy, recursively copying any objects it finds. Otherwise, the copy will share structure with the original object(s).
Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over.
Warning: passing `false` as the first argument is not supported.
### Arguments
* `deep` *Boolean* (optional)
If set, the merge becomes recursive (i.e. deep copy).
* `target` *Object*
The object to extend.
* `object1` *Object*
The object that will be merged into the first.
* `objectN` *Object* (Optional)
More objects to merge into the first.
## License
`node-extend` is licensed under the [MIT License][mit-license-url].
## Acknowledgements
All credit to the jQuery authors for perfecting this amazing utility.
Ported to Node.js by [Stefan Thomas][github-justmoon] with contributions by [Jonathan Buchanan][github-insin] and [Jordan Harband][github-ljharb].
[travis-svg]: https://travis-ci.org/justmoon/node-extend.svg
[travis-url]: https://travis-ci.org/justmoon/node-extend
[npm-url]: https://npmjs.org/package/extend
[mit-license-url]: http://opensource.org/licenses/MIT
[github-justmoon]: https://github.com/justmoon
[github-insin]: https://github.com/insin
[github-ljharb]: https://github.com/ljharb
[npm-version-png]: http://vb.teelaun.ch/justmoon/node-extend.svg
[deps-svg]: https://david-dm.org/justmoon/node-extend.svg
[deps-url]: https://david-dm.org/justmoon/node-extend
[dev-deps-svg]: https://david-dm.org/justmoon/node-extend/dev-status.svg
[dev-deps-url]: https://david-dm.org/justmoon/node-extend#info=devDependencies

View File

@@ -0,0 +1,32 @@
{
"name": "extend",
"author": "Stefan Thomas <justmoon@members.fsf.org> (http://www.justmoon.net)",
"version": "2.0.1",
"description": "Port of jQuery.extend for node.js and the browser.",
"scripts": [
"index.js"
],
"contributors": [
{
"name": "Jordan Harband",
"url": "https://github.com/ljharb"
}
],
"keywords": [
"extend",
"clone",
"merge"
],
"repository" : {
"type": "git",
"url": "https://github.com/justmoon/node-extend.git"
},
"dependencies": {
},
"devDependencies": {
"tape" : "~3.0.0",
"covert": "~0.4.0",
"jscs": "~1.6.2"
}
}

View File

@@ -0,0 +1,89 @@
var hasOwn = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var undefined;
var isArray = function isArray(arr) {
if (typeof Array.isArray === 'function') {
return Array.isArray(arr);
}
return toStr.call(arr) === '[object Array]';
};
var isPlainObject = function isPlainObject(obj) {
'use strict';
if (!obj || toStr.call(obj) !== '[object Object]') {
return false;
}
var has_own_constructor = hasOwn.call(obj, 'constructor');
var has_is_property_of_method = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
// Not own constructor property must be Object
if (obj.constructor && !has_own_constructor && !has_is_property_of_method) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for (key in obj) {}
return key === undefined || hasOwn.call(obj, key);
};
module.exports = function extend() {
'use strict';
var options, name, src, copy, copyIsArray, clone,
target = arguments[0],
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if (typeof target === 'boolean') {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
} else if ((typeof target !== 'object' && typeof target !== 'function') || target == null) {
target = {};
}
for (; i < length; ++i) {
options = arguments[i];
// Only deal with non-null/undefined values
if (options != null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging plain objects or arrays
if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && isArray(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[name] = extend(deep, clone, copy);
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
// Return the modified object
return target;
};

View File

@@ -0,0 +1,95 @@
{
"_args": [
[
"extend@^2.0.1",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/liftoff"
]
],
"_from": "extend@>=2.0.1 <3.0.0",
"_id": "extend@2.0.1",
"_inCache": true,
"_installable": true,
"_location": "/gulp/extend",
"_nodeVersion": "1.8.1",
"_npmUser": {
"email": "ljharb@gmail.com",
"name": "ljharb"
},
"_npmVersion": "2.8.3",
"_phantomChildren": {},
"_requested": {
"name": "extend",
"raw": "extend@^2.0.1",
"rawSpec": "^2.0.1",
"scope": null,
"spec": ">=2.0.1 <3.0.0",
"type": "range"
},
"_requiredBy": [
"/gulp/liftoff"
],
"_resolved": "https://registry.npmjs.org/extend/-/extend-2.0.1.tgz",
"_shasum": "1ee8010689e7395ff9448241c98652bc759a8260",
"_shrinkwrap": null,
"_spec": "extend@^2.0.1",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/liftoff",
"author": {
"email": "justmoon@members.fsf.org",
"name": "Stefan Thomas",
"url": "http://www.justmoon.net"
},
"bugs": {
"url": "https://github.com/justmoon/node-extend/issues"
},
"contributors": [
{
"name": "Jordan Harband",
"url": "https://github.com/ljharb"
}
],
"dependencies": {},
"description": "Port of jQuery.extend for node.js and the browser",
"devDependencies": {
"covert": "^1.0.1",
"jscs": "^1.11.3",
"tape": "^4.0.0"
},
"directories": {},
"dist": {
"shasum": "1ee8010689e7395ff9448241c98652bc759a8260",
"tarball": "https://registry.npmjs.org/extend/-/extend-2.0.1.tgz"
},
"gitHead": "ce3790222d3d2051f728f74be9565f155ed599c3",
"homepage": "https://github.com/justmoon/node-extend#readme",
"keywords": [
"extend",
"clone",
"merge"
],
"license": "MIT",
"main": "index",
"maintainers": [
{
"email": "justmoon@members.fsf.org",
"name": "justmoon"
},
{
"email": "ljharb@gmail.com",
"name": "ljharb"
}
],
"name": "extend",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/justmoon/node-extend.git"
},
"scripts": {
"coverage": "covert test/index.js",
"coverage-quiet": "covert test/index.js --quiet",
"lint": "jscs *.js */*.js",
"test": "npm run lint && node test/index.js && npm run coverage-quiet"
},
"version": "2.0.1"
}

View File

@@ -0,0 +1,22 @@
Copyright (c) 2013 "Cowboy" Ben Alman
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,48 @@
# findup-sync [![Build Status](https://secure.travis-ci.org/cowboy/node-findup-sync.png?branch=master)](http://travis-ci.org/cowboy/node-findup-sync)
Find the first file matching a given pattern in the current directory or the nearest ancestor directory.
## Getting Started
Install the module with: `npm install findup-sync`
```js
var findup = require('findup-sync');
// Start looking in the CWD.
var filepath1 = findup('{a,b}*.txt');
// Start looking somewhere else, and ignore case (probably a good idea).
var filepath2 = findup('{a,b}*.txt', {cwd: '/some/path', nocase: true});
```
## Usage
```js
findup(patternOrPatterns [, minimatchOptions])
```
### patternOrPatterns
Type: `String` or `Array`
Default: none
One or more wildcard glob patterns. Or just filenames.
### minimatchOptions
Type: `Object`
Default: `{}`
Options to be passed to [minimatch](https://github.com/isaacs/minimatch).
Note that if you want to start in a different directory than the current working directory, specify a `cwd` property here.
## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).
## Release History
2015-09-14 0 v0.3.0 - updated glob to ~5.0.
2014-12-17 - v0.2.1 - updated to glob ~4.3.
2014-12-16 - v0.2.0 - Removed lodash, updated to glob 4.x.
2014-03-14 - v0.1.3 - Updated dependencies.
2013-03-08 - v0.1.2 - Updated dependencies. Fixed a Node 0.9.x bug. Updated unit tests to work cross-platform.
2012-11-15 - v0.1.1 - Now works without an options object.
2012-11-01 - v0.1.0 - Initial release.

View File

@@ -0,0 +1,95 @@
{
"_args": [
[
"findup-sync@^0.3.0",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/liftoff"
]
],
"_from": "findup-sync@>=0.3.0 <0.4.0",
"_id": "findup-sync@0.3.0",
"_inCache": true,
"_installable": true,
"_location": "/gulp/findup-sync",
"_nodeVersion": "4.0.0",
"_npmUser": {
"email": "tyler@sleekcode.net",
"name": "tkellen"
},
"_npmVersion": "2.14.2",
"_phantomChildren": {},
"_requested": {
"name": "findup-sync",
"raw": "findup-sync@^0.3.0",
"rawSpec": "^0.3.0",
"scope": null,
"spec": ">=0.3.0 <0.4.0",
"type": "range"
},
"_requiredBy": [
"/gulp/liftoff"
],
"_resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-0.3.0.tgz",
"_shasum": "37930aa5d816b777c03445e1966cc6790a4c0b16",
"_shrinkwrap": null,
"_spec": "findup-sync@^0.3.0",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/liftoff",
"author": {
"name": "\"Cowboy\" Ben Alman",
"url": "http://benalman.com/"
},
"bugs": {
"url": "https://github.com/cowboy/node-findup-sync/issues"
},
"dependencies": {
"glob": "~5.0.0"
},
"description": "Find the first file matching a given pattern in the current directory or the nearest ancestor directory.",
"devDependencies": {
"grunt": "~0.4.4",
"grunt-contrib-jshint": "~0.9.2",
"grunt-contrib-nodeunit": "~0.3.3"
},
"directories": {},
"dist": {
"shasum": "37930aa5d816b777c03445e1966cc6790a4c0b16",
"tarball": "https://registry.npmjs.org/findup-sync/-/findup-sync-0.3.0.tgz"
},
"engines": {
"node": ">= 0.6.0"
},
"gitHead": "24356dc9bc74bf2389080a29c80845a510eaf3ef",
"homepage": "https://github.com/cowboy/node-findup-sync",
"keywords": [
"find",
"glob",
"file"
],
"licenses": [
{
"type": "MIT",
"url": "https://github.com/cowboy/node-findup-sync/blob/master/LICENSE-MIT"
}
],
"main": "lib/findup-sync",
"maintainers": [
{
"email": "cowboy@rj3.net",
"name": "cowboy"
},
{
"email": "tyler@sleekcode.net",
"name": "tkellen"
}
],
"name": "findup-sync",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/cowboy/node-findup-sync.git"
},
"scripts": {
"test": "grunt nodeunit"
},
"version": "0.3.0"
}

View File

@@ -0,0 +1,22 @@
Copyright (c) 2014 Tyler Kellen
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,58 @@
# flagged-respawn [![Build Status](https://secure.travis-ci.org/js-cli/js-flagged-respawn.svg)](http://travis-ci.org/js-cli/js-flagged-respawn)
> A tool for respawning node binaries when special flags are present.
[![NPM](https://nodei.co/npm/flagged-respawn.png)](https://nodei.co/npm/flagged-respawn/)
## What is it?
Say you wrote a command line tool that runs arbitrary javascript (e.g. task runner, test framework, etc). For the sake of discussion, let's pretend it's a testing harness you've named `testify`.
Everything is going splendidly until one day you decide to test some code that relies on a feature behind a v8 flag in node (`--harmony`, for example). Without much thought, you run `testify --harmony spec tests.js`.
It doesn't work. After digging around for a bit, you realize this produces a [`process.argv`](http://nodejs.org/docs/latest/api/process.html#process_process_argv) of:
`['node', '/usr/local/bin/test', '--harmony', 'spec', 'tests.js']`
Crap. The `--harmony` flag is in the wrong place! It should be applied to the **node** command, not our binary. What we actually wanted was this:
`['node', '--harmony', '/usr/local/bin/test', 'spec', 'tests.js']`
Flagged-respawn fixes this problem and handles all the edge cases respawning creates, such as:
- Providing a method to determine if a respawn is needed.
- Piping stderr/stdout from the child into the parent.
- Making the parent process exit with the same code as the child.
- If the child is killed, making the parent exit with the same signal.
To see it in action, clone this repository and run `npm install` / `npm run respawn` / `npm run nospawn`.
## Sample Usage
```js
#!/usr/bin/env node
const flaggedRespawn = require('flagged-respawn');
// get a list of all possible v8 flags for the running version of node
const v8flags = require('v8flags').fetch();
flaggedRespawn(v8flags, process.argv, function (ready, child) {
if (ready) {
console.log('Running!');
// your cli code here
} else {
console.log('Special flags found, respawning.');
}
if (process.pid !== child.pid) {
console.log('Respawned to PID:', child.pid);
}
});
```
## Release History
* 2016-03-22 - v0.3.2 - fix issue with v8 flags values being dropped
* 2014-09-12 - v0.3.1 - use `{ stdio: 'inherit' }` for spawn to maintain colors
* 2014-09-11 - v0.3.0 - for real this time
* 2014-09-11 - v0.2.0 - cleanup
* 2014-09-04 - v0.1.1 - initial release

View File

@@ -0,0 +1,18 @@
const reorder = require('./lib/reorder');
const respawn = require('./lib/respawn');
module.exports = function (flags, argv, execute) {
if (!flags) {
throw new Error('You must specify flags to respawn with.');
}
if (!argv) {
throw new Error('You must specify an argv array.');
}
var proc = process;
var reordered = reorder(flags, argv);
var ready = JSON.stringify(argv) === JSON.stringify(reordered);
if (!ready) {
proc = respawn(reordered);
}
execute(ready, proc);
};

View File

@@ -0,0 +1,97 @@
{
"_args": [
[
"flagged-respawn@^0.3.2",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/liftoff"
]
],
"_from": "flagged-respawn@>=0.3.2 <0.4.0",
"_id": "flagged-respawn@0.3.2",
"_inCache": true,
"_installable": true,
"_location": "/gulp/flagged-respawn",
"_nodeVersion": "0.12.12",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/flagged-respawn-0.3.2.tgz_1458638775261_0.252670707879588"
},
"_npmUser": {
"email": "b@pk.am",
"name": "tusbar"
},
"_npmVersion": "2.14.9",
"_phantomChildren": {},
"_requested": {
"name": "flagged-respawn",
"raw": "flagged-respawn@^0.3.2",
"rawSpec": "^0.3.2",
"scope": null,
"spec": ">=0.3.2 <0.4.0",
"type": "range"
},
"_requiredBy": [
"/gulp/liftoff"
],
"_resolved": "https://registry.npmjs.org/flagged-respawn/-/flagged-respawn-0.3.2.tgz",
"_shasum": "ff191eddcd7088a675b2610fffc976be9b8074b5",
"_shrinkwrap": null,
"_spec": "flagged-respawn@^0.3.2",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/liftoff",
"author": {
"name": "Tyler Kellen",
"url": "http://goingslowly.com/"
},
"bugs": {
"url": "https://github.com/js-cli/js-flagged-respawn/issues"
},
"dependencies": {},
"description": "A tool for respawning node binaries when special flags are present.",
"devDependencies": {
"chai": "~1.9.1",
"mocha": "~1.21.4",
"v8flags": "~1.0.1"
},
"directories": {},
"dist": {
"shasum": "ff191eddcd7088a675b2610fffc976be9b8074b5",
"tarball": "https://registry.npmjs.org/flagged-respawn/-/flagged-respawn-0.3.2.tgz"
},
"engines": {
"node": ">= 0.8.0"
},
"gitHead": "5467529adb5512292c8dd341691ba75b2293ed7e",
"homepage": "https://github.com/js-cli/js-flagged-respawn",
"keywords": [
"respawn flags"
],
"licenses": [
{
"type": "MIT",
"url": "https://github.com/js-cli/js-flagged-respawn/blob/master/LICENSE"
}
],
"main": "index.js",
"maintainers": [
{
"email": "tyler@sleekcode.net",
"name": "tkellen"
},
{
"email": "b@pk.am",
"name": "tusbar"
}
],
"name": "flagged-respawn",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/js-cli/js-flagged-respawn.git"
},
"scripts": {
"nospawn": "node test/bin/respawner test",
"respawn": "node test/bin/respawner --harmony test",
"test": "mocha -R spec test"
},
"version": "0.3.2"
}

View File

@@ -0,0 +1,13 @@
#!/usr/bin/env node
const flaggedRespawn = require('../../');
flaggedRespawn(['--harmony'], process.argv, function (ready) {
if (ready) {
setTimeout(function () {
process.exit(100);
}, 100);
}
});

View File

@@ -0,0 +1,17 @@
#!/usr/bin/env node
const flaggedRespawn = require('../../');
// get a list of all possible v8 flags for the running version of node
const v8flags = require('v8flags').fetch();
flaggedRespawn(v8flags, process.argv, function (ready, child) {
if (ready) {
console.log('Running!');
} else {
console.log('Special flags found, respawning.');
}
if (child.pid !== process.pid) {
console.log('Respawned to PID:', child.pid);
}
});

View File

@@ -0,0 +1,16 @@
#!/usr/bin/env node
const flaggedRespawn = require('../../');
flaggedRespawn(['--harmony'], process.argv, function (ready, child) {
if (ready) {
setTimeout(function() {
process.exit();
}, 100);
} else {
console.log('got child!');
child.kill('SIGHUP');
}
});

View File

@@ -0,0 +1,99 @@
const expect = require('chai').expect;
const exec = require('child_process').exec;
const reorder = require('../lib/reorder');
const flaggedRespawn = require('../');
describe('flaggedRespawn', function () {
var flags = ['--harmony', '--use_strict', '--stack_size']
describe('reorder', function () {
it('should re-order args, placing special flags first', function () {
var needsRespawn = ['node', 'file.js', '--flag', '--harmony', 'command'];
var noRespawnNeeded = ['node', 'bin/flagged-respawn', 'thing'];
expect(reorder(flags, needsRespawn))
.to.deep.equal(['node', '--harmony', 'file.js', '--flag', 'command']);
expect(reorder(flags, noRespawnNeeded))
.to.deep.equal(noRespawnNeeded);
});
it('should keep flags values when not placed first', function () {
var args = ['node', 'file.js', '--stack_size=2048'];
var expected = ['node', '--stack_size=2048', 'file.js'];
expect(reorder(flags, args)).to.deep.equal(expected);
});
it('should ignore special flags when they are in the correct position', function () {
var args = ['node', '--harmony', 'file.js', '--flag'];
expect(reorder(flags, reorder(flags, args))).to.deep.equal(args);
});
});
describe('execute', function () {
it('should throw if no flags are specified', function () {
expect(function () { flaggedRespawn.execute(); }).to.throw;
});
it('should throw if no argv is specified', function () {
expect(function () { flaggedRespawn.execute(flags); }).to.throw;
});
it('should respawn and pipe stderr/stdout to parent', function (done) {
exec('node ./test/bin/respawner.js --harmony', function (err, stdout, stderr) {
expect(stdout.replace(/[0-9]/g, '')).to.equal('Special flags found, respawning.\nRespawned to PID: \nRunning!\n');
done();
});
});
it('should respawn and pass exit code from child to parent', function (done) {
exec('node ./test/bin/exit_code.js --harmony', function (err, stdout, stderr) {
expect(err.code).to.equal(100);
done();
});
});
it.skip('should respawn; if child is killed, parent should exit with same signal', function (done) {
// TODO: figure out why travis hates this
exec('node ./test/bin/signal.js --harmony', function (err, stdout, stderr) {
console.log('err', err);
console.log('stdout', stdout);
console.log('stderr', stderr);
expect(err.signal).to.equal('SIGHUP');
done();
});
});
it('should call back with ready as true when respawn is not needed', function () {
var argv = ['node', './test/bin/respawner'];
flaggedRespawn(flags, argv, function (ready) {
expect(ready).to.be.true;
});
});
it('should call back with ready as false when respawn is needed', function () {
var argv = ['node', './test/bin/respawner', '--harmony'];
flaggedRespawn(flags, argv, function (ready) {
expect(ready).to.be.false;
});
});
it('should call back with the child process when ready', function () {
var argv = ['node', './test/bin/respawner', '--harmony'];
flaggedRespawn(flags, argv, function (ready, child) {
expect(child.pid).to.not.equal(process.pid);
});
});
it('should call back with own process when respawn not needed', function () {
var argv = ['node', './test/bin/respawner'];
flaggedRespawn(flags, argv, function (ready, child) {
expect(child.pid).to.equal(process.pid);
});
});
});
});

View File

@@ -0,0 +1,15 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,377 @@
[![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Dependency Status](https://david-dm.org/isaacs/node-glob.svg)](https://david-dm.org/isaacs/node-glob) [![devDependency Status](https://david-dm.org/isaacs/node-glob/dev-status.svg)](https://david-dm.org/isaacs/node-glob#info=devDependencies) [![optionalDependency Status](https://david-dm.org/isaacs/node-glob/optional-status.svg)](https://david-dm.org/isaacs/node-glob#info=optionalDependencies)
# Glob
Match files using the patterns the shell uses, like stars and stuff.
This is a glob implementation in JavaScript. It uses the `minimatch`
library to do its matching.
![](oh-my-glob.gif)
## Usage
```javascript
var glob = require("glob")
// options is optional
glob("**/*.js", options, function (er, files) {
// files is an array of filenames.
// If the `nonull` option is set, and nothing
// was found, then files is ["**/*.js"]
// er is an error object or null.
})
```
## Glob Primer
"Globs" are the patterns you type when you do stuff like `ls *.js` on
the command line, or put `build/*` in a `.gitignore` file.
Before parsing the path part patterns, braced sections are expanded
into a set. Braced sections start with `{` and end with `}`, with any
number of comma-delimited sections within. Braced sections may contain
slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`.
The following characters have special magic meaning when used in a
path portion:
* `*` Matches 0 or more characters in a single path portion
* `?` Matches 1 character
* `[...]` Matches a range of characters, similar to a RegExp range.
If the first character of the range is `!` or `^` then it matches
any character not in the range.
* `!(pattern|pattern|pattern)` Matches anything that does not match
any of the patterns provided.
* `?(pattern|pattern|pattern)` Matches zero or one occurrence of the
patterns provided.
* `+(pattern|pattern|pattern)` Matches one or more occurrences of the
patterns provided.
* `*(a|b|c)` Matches zero or more occurrences of the patterns provided
* `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns
provided
* `**` If a "globstar" is alone in a path portion, then it matches
zero or more directories and subdirectories searching for matches.
It does not crawl symlinked directories.
### Dots
If a file or directory path portion has a `.` as the first character,
then it will not match any glob pattern unless that pattern's
corresponding path part also has a `.` as its first character.
For example, the pattern `a/.*/c` would match the file at `a/.b/c`.
However the pattern `a/*/c` would not, because `*` does not start with
a dot character.
You can make glob treat dots as normal characters by setting
`dot:true` in the options.
### Basename Matching
If you set `matchBase:true` in the options, and the pattern has no
slashes in it, then it will seek for any file anywhere in the tree
with a matching basename. For example, `*.js` would match
`test/simple/basic.js`.
### Negation
The intent for negation would be for a pattern starting with `!` to
match everything that *doesn't* match the supplied pattern. However,
the implementation is weird, and for the time being, this should be
avoided. The behavior is deprecated in version 5, and will be removed
entirely in version 6.
### Empty Sets
If no matching files are found, then an empty array is returned. This
differs from the shell, where the pattern itself is returned. For
example:
$ echo a*s*d*f
a*s*d*f
To get the bash-style behavior, set the `nonull:true` in the options.
### See Also:
* `man sh`
* `man bash` (Search for "Pattern Matching")
* `man 3 fnmatch`
* `man 5 gitignore`
* [minimatch documentation](https://github.com/isaacs/minimatch)
## glob.hasMagic(pattern, [options])
Returns `true` if there are any special characters in the pattern, and
`false` otherwise.
Note that the options affect the results. If `noext:true` is set in
the options object, then `+(a|b)` will not be considered a magic
pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}`
then that is considered magical, unless `nobrace:true` is set in the
options.
## glob(pattern, [options], cb)
* `pattern` {String} Pattern to be matched
* `options` {Object}
* `cb` {Function}
* `err` {Error | null}
* `matches` {Array<String>} filenames found matching the pattern
Perform an asynchronous glob search.
## glob.sync(pattern, [options])
* `pattern` {String} Pattern to be matched
* `options` {Object}
* return: {Array<String>} filenames found matching the pattern
Perform a synchronous glob search.
## Class: glob.Glob
Create a Glob object by instantiating the `glob.Glob` class.
```javascript
var Glob = require("glob").Glob
var mg = new Glob(pattern, options, cb)
```
It's an EventEmitter, and starts walking the filesystem to find matches
immediately.
### new glob.Glob(pattern, [options], [cb])
* `pattern` {String} pattern to search for
* `options` {Object}
* `cb` {Function} Called when an error occurs, or matches are found
* `err` {Error | null}
* `matches` {Array<String>} filenames found matching the pattern
Note that if the `sync` flag is set in the options, then matches will
be immediately available on the `g.found` member.
### Properties
* `minimatch` The minimatch object that the glob uses.
* `options` The options object passed in.
* `aborted` Boolean which is set to true when calling `abort()`. There
is no way at this time to continue a glob search after aborting, but
you can re-use the statCache to avoid having to duplicate syscalls.
* `cache` Convenience object. Each field has the following possible
values:
* `false` - Path does not exist
* `true` - Path exists
* `'DIR'` - Path exists, and is not a directory
* `'FILE'` - Path exists, and is a directory
* `[file, entries, ...]` - Path exists, is a directory, and the
array value is the results of `fs.readdir`
* `statCache` Cache of `fs.stat` results, to prevent statting the same
path multiple times.
* `symlinks` A record of which paths are symbolic links, which is
relevant in resolving `**` patterns.
* `realpathCache` An optional object which is passed to `fs.realpath`
to minimize unnecessary syscalls. It is stored on the instantiated
Glob object, and may be re-used.
### Events
* `end` When the matching is finished, this is emitted with all the
matches found. If the `nonull` option is set, and no match was found,
then the `matches` list contains the original pattern. The matches
are sorted, unless the `nosort` flag is set.
* `match` Every time a match is found, this is emitted with the matched.
* `error` Emitted when an unexpected error is encountered, or whenever
any fs error occurs if `options.strict` is set.
* `abort` When `abort()` is called, this event is raised.
### Methods
* `pause` Temporarily stop the search
* `resume` Resume the search
* `abort` Stop the search forever
### Options
All the options that can be passed to Minimatch can also be passed to
Glob to change pattern matching behavior. Also, some have been added,
or have glob-specific ramifications.
All options are false by default, unless otherwise noted.
All options are added to the Glob object, as well.
If you are running many `glob` operations, you can pass a Glob object
as the `options` argument to a subsequent operation to shortcut some
`stat` and `readdir` calls. At the very least, you may pass in shared
`symlinks`, `statCache`, `realpathCache`, and `cache` options, so that
parallel glob operations will be sped up by sharing information about
the filesystem.
* `cwd` The current working directory in which to search. Defaults
to `process.cwd()`.
* `root` The place where patterns starting with `/` will be mounted
onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix
systems, and `C:\` or some such on Windows.)
* `dot` Include `.dot` files in normal matches and `globstar` matches.
Note that an explicit dot in a portion of the pattern will always
match dot files.
* `nomount` By default, a pattern starting with a forward-slash will be
"mounted" onto the root setting, so that a valid filesystem path is
returned. Set this flag to disable that behavior.
* `mark` Add a `/` character to directory matches. Note that this
requires additional stat calls.
* `nosort` Don't sort the results.
* `stat` Set to true to stat *all* results. This reduces performance
somewhat, and is completely unnecessary, unless `readdir` is presumed
to be an untrustworthy indicator of file existence.
* `silent` When an unusual error is encountered when attempting to
read a directory, a warning will be printed to stderr. Set the
`silent` option to true to suppress these warnings.
* `strict` When an unusual error is encountered when attempting to
read a directory, the process will just continue on in search of
other matches. Set the `strict` option to raise an error in these
cases.
* `cache` See `cache` property above. Pass in a previously generated
cache object to save some fs calls.
* `statCache` A cache of results of filesystem information, to prevent
unnecessary stat calls. While it should not normally be necessary
to set this, you may pass the statCache from one glob() call to the
options object of another, if you know that the filesystem will not
change between calls. (See "Race Conditions" below.)
* `symlinks` A cache of known symbolic links. You may pass in a
previously generated `symlinks` object to save `lstat` calls when
resolving `**` matches.
* `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead.
* `nounique` In some cases, brace-expanded patterns can result in the
same file showing up multiple times in the result set. By default,
this implementation prevents duplicates in the result set. Set this
flag to disable that behavior.
* `nonull` Set to never return an empty set, instead returning a set
containing the pattern itself. This is the default in glob(3).
* `debug` Set to enable debug logging in minimatch and glob.
* `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets.
* `noglobstar` Do not match `**` against multiple filenames. (Ie,
treat it as a normal `*` instead.)
* `noext` Do not match `+(a|b)` "extglob" patterns.
* `nocase` Perform a case-insensitive match. Note: on
case-insensitive filesystems, non-magic patterns will match by
default, since `stat` and `readdir` will not raise errors.
* `matchBase` Perform a basename-only match if the pattern does not
contain any slash characters. That is, `*.js` would be treated as
equivalent to `**/*.js`, matching all js files in all directories.
* `nodir` Do not match directories, only files. (Note: to match
*only* directories, simply put a `/` at the end of the pattern.)
* `ignore` Add a pattern or an array of patterns to exclude matches.
* `follow` Follow symlinked directories when expanding `**` patterns.
Note that this can result in a lot of duplicate references in the
presence of cyclic links.
* `realpath` Set to true to call `fs.realpath` on all of the results.
In the case of a symlink that cannot be resolved, the full absolute
path to the matched entry is returned (though it will usually be a
broken symlink)
* `nonegate` Suppress deprecated `negate` behavior. (See below.)
Default=true
* `nocomment` Suppress deprecated `comment` behavior. (See below.)
Default=true
## Comparisons to other fnmatch/glob implementations
While strict compliance with the existing standards is a worthwhile
goal, some discrepancies exist between node-glob and other
implementations, and are intentional.
The double-star character `**` is supported by default, unless the
`noglobstar` flag is set. This is supported in the manner of bsdglob
and bash 4.3, where `**` only has special significance if it is the only
thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
`a/**b` will not.
Note that symlinked directories are not crawled as part of a `**`,
though their contents may match against subsequent portions of the
pattern. This prevents infinite loops and duplicates and the like.
If an escaped pattern has no matches, and the `nonull` flag is set,
then glob returns the pattern as-provided, rather than
interpreting the character escapes. For example,
`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
`"*a?"`. This is akin to setting the `nullglob` option in bash, except
that it does not resolve escaped pattern characters.
If brace expansion is not disabled, then it is performed before any
other interpretation of the glob pattern. Thus, a pattern like
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
checked for validity. Since those two are valid, matching proceeds.
### Comments and Negation
**Note**: In version 5 of this module, negation and comments are
**disabled** by default. You can explicitly set `nonegate:false` or
`nocomment:false` to re-enable them. They are going away entirely in
version 6.
The intent for negation would be for a pattern starting with `!` to
match everything that *doesn't* match the supplied pattern. However,
the implementation is weird. It is better to use the `ignore` option
to set a pattern or set of patterns to exclude from matches. If you
want the "everything except *x*" type of behavior, you can use `**` as
the main pattern, and set an `ignore` for the things to exclude.
The comments feature is added in minimatch, primarily to more easily
support use cases like ignore files, where a `#` at the start of a
line makes the pattern "empty". However, in the context of a
straightforward filesystem globber, "comments" don't make much sense.
## Windows
**Please only use forward-slashes in glob expressions.**
Though windows uses either `/` or `\` as its path separator, only `/`
characters are used by this glob implementation. You must use
forward-slashes **only** in glob expressions. Back-slashes will always
be interpreted as escape characters, not path separators.
Results from absolute patterns such as `/foo/*` are mounted onto the
root setting using `path.join`. On windows, this will by default result
in `/foo/*` matching `C:\foo\bar.txt`.
## Race Conditions
Glob searching, by its very nature, is susceptible to race conditions,
since it relies on directory walking and such.
As a result, it is possible that a file that exists when glob looks for
it may have been deleted or modified by the time it returns the result.
As part of its internal implementation, this program caches all stat
and readdir calls that it makes, in order to cut down on system
overhead. However, this also makes it even more susceptible to races,
especially if the cache or statCache objects are reused between glob
calls.
Users are thus advised not to use a glob result as a guarantee of
filesystem state in the face of rapid changes. For the vast majority
of operations, this is never a problem.
## Contributing
Any change to behavior (including bugfixes) must come with a test.
Patches that fail tests or reduce performance will be rejected.
```
# to run tests
npm test
# to re-generate test fixtures
npm run test-regen
# to benchmark against bash/zsh
npm run bench
# to profile javascript
npm run prof
```

View File

@@ -0,0 +1,245 @@
exports.alphasort = alphasort
exports.alphasorti = alphasorti
exports.setopts = setopts
exports.ownProp = ownProp
exports.makeAbs = makeAbs
exports.finish = finish
exports.mark = mark
exports.isIgnored = isIgnored
exports.childrenIgnored = childrenIgnored
function ownProp (obj, field) {
return Object.prototype.hasOwnProperty.call(obj, field)
}
var path = require("path")
var minimatch = require("minimatch")
var isAbsolute = require("path-is-absolute")
var Minimatch = minimatch.Minimatch
function alphasorti (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase())
}
function alphasort (a, b) {
return a.localeCompare(b)
}
function setupIgnores (self, options) {
self.ignore = options.ignore || []
if (!Array.isArray(self.ignore))
self.ignore = [self.ignore]
if (self.ignore.length) {
self.ignore = self.ignore.map(ignoreMap)
}
}
function ignoreMap (pattern) {
var gmatcher = null
if (pattern.slice(-3) === '/**') {
var gpattern = pattern.replace(/(\/\*\*)+$/, '')
gmatcher = new Minimatch(gpattern)
}
return {
matcher: new Minimatch(pattern),
gmatcher: gmatcher
}
}
function setopts (self, pattern, options) {
if (!options)
options = {}
// base-matching: just use globstar for that.
if (options.matchBase && -1 === pattern.indexOf("/")) {
if (options.noglobstar) {
throw new Error("base matching requires globstar")
}
pattern = "**/" + pattern
}
self.silent = !!options.silent
self.pattern = pattern
self.strict = options.strict !== false
self.realpath = !!options.realpath
self.realpathCache = options.realpathCache || Object.create(null)
self.follow = !!options.follow
self.dot = !!options.dot
self.mark = !!options.mark
self.nodir = !!options.nodir
if (self.nodir)
self.mark = true
self.sync = !!options.sync
self.nounique = !!options.nounique
self.nonull = !!options.nonull
self.nosort = !!options.nosort
self.nocase = !!options.nocase
self.stat = !!options.stat
self.noprocess = !!options.noprocess
self.maxLength = options.maxLength || Infinity
self.cache = options.cache || Object.create(null)
self.statCache = options.statCache || Object.create(null)
self.symlinks = options.symlinks || Object.create(null)
setupIgnores(self, options)
self.changedCwd = false
var cwd = process.cwd()
if (!ownProp(options, "cwd"))
self.cwd = cwd
else {
self.cwd = options.cwd
self.changedCwd = path.resolve(options.cwd) !== cwd
}
self.root = options.root || path.resolve(self.cwd, "/")
self.root = path.resolve(self.root)
if (process.platform === "win32")
self.root = self.root.replace(/\\/g, "/")
self.nomount = !!options.nomount
// disable comments and negation unless the user explicitly
// passes in false as the option.
options.nonegate = options.nonegate === false ? false : true
options.nocomment = options.nocomment === false ? false : true
deprecationWarning(options)
self.minimatch = new Minimatch(pattern, options)
self.options = self.minimatch.options
}
// TODO(isaacs): remove entirely in v6
// exported to reset in tests
exports.deprecationWarned
function deprecationWarning(options) {
if (!options.nonegate || !options.nocomment) {
if (process.noDeprecation !== true && !exports.deprecationWarned) {
var msg = 'glob WARNING: comments and negation will be disabled in v6'
if (process.throwDeprecation)
throw new Error(msg)
else if (process.traceDeprecation)
console.trace(msg)
else
console.error(msg)
exports.deprecationWarned = true
}
}
}
function finish (self) {
var nou = self.nounique
var all = nou ? [] : Object.create(null)
for (var i = 0, l = self.matches.length; i < l; i ++) {
var matches = self.matches[i]
if (!matches || Object.keys(matches).length === 0) {
if (self.nonull) {
// do like the shell, and spit out the literal glob
var literal = self.minimatch.globSet[i]
if (nou)
all.push(literal)
else
all[literal] = true
}
} else {
// had matches
var m = Object.keys(matches)
if (nou)
all.push.apply(all, m)
else
m.forEach(function (m) {
all[m] = true
})
}
}
if (!nou)
all = Object.keys(all)
if (!self.nosort)
all = all.sort(self.nocase ? alphasorti : alphasort)
// at *some* point we statted all of these
if (self.mark) {
for (var i = 0; i < all.length; i++) {
all[i] = self._mark(all[i])
}
if (self.nodir) {
all = all.filter(function (e) {
return !(/\/$/.test(e))
})
}
}
if (self.ignore.length)
all = all.filter(function(m) {
return !isIgnored(self, m)
})
self.found = all
}
function mark (self, p) {
var abs = makeAbs(self, p)
var c = self.cache[abs]
var m = p
if (c) {
var isDir = c === 'DIR' || Array.isArray(c)
var slash = p.slice(-1) === '/'
if (isDir && !slash)
m += '/'
else if (!isDir && slash)
m = m.slice(0, -1)
if (m !== p) {
var mabs = makeAbs(self, m)
self.statCache[mabs] = self.statCache[abs]
self.cache[mabs] = self.cache[abs]
}
}
return m
}
// lotta situps...
function makeAbs (self, f) {
var abs = f
if (f.charAt(0) === '/') {
abs = path.join(self.root, f)
} else if (isAbsolute(f) || f === '') {
abs = f
} else if (self.changedCwd) {
abs = path.resolve(self.cwd, f)
} else {
abs = path.resolve(f)
}
return abs
}
// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
function isIgnored (self, path) {
if (!self.ignore.length)
return false
return self.ignore.some(function(item) {
return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
})
}
function childrenIgnored (self, path) {
if (!self.ignore.length)
return false
return self.ignore.some(function(item) {
return !!(item.gmatcher && item.gmatcher.match(path))
})
}

View File

@@ -0,0 +1,752 @@
// Approach:
//
// 1. Get the minimatch set
// 2. For each pattern in the set, PROCESS(pattern, false)
// 3. Store matches per-set, then uniq them
//
// PROCESS(pattern, inGlobStar)
// Get the first [n] items from pattern that are all strings
// Join these together. This is PREFIX.
// If there is no more remaining, then stat(PREFIX) and
// add to matches if it succeeds. END.
//
// If inGlobStar and PREFIX is symlink and points to dir
// set ENTRIES = []
// else readdir(PREFIX) as ENTRIES
// If fail, END
//
// with ENTRIES
// If pattern[n] is GLOBSTAR
// // handle the case where the globstar match is empty
// // by pruning it out, and testing the resulting pattern
// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
// // handle other cases.
// for ENTRY in ENTRIES (not dotfiles)
// // attach globstar + tail onto the entry
// // Mark that this entry is a globstar match
// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
//
// else // not globstar
// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
// Test ENTRY against pattern[n]
// If fails, continue
// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
//
// Caveat:
// Cache all stats and readdirs results to minimize syscall. Since all
// we ever care about is existence and directory-ness, we can just keep
// `true` for files, and [children,...] for directories, or `false` for
// things that don't exist.
module.exports = glob
var fs = require('fs')
var minimatch = require('minimatch')
var Minimatch = minimatch.Minimatch
var inherits = require('inherits')
var EE = require('events').EventEmitter
var path = require('path')
var assert = require('assert')
var isAbsolute = require('path-is-absolute')
var globSync = require('./sync.js')
var common = require('./common.js')
var alphasort = common.alphasort
var alphasorti = common.alphasorti
var setopts = common.setopts
var ownProp = common.ownProp
var inflight = require('inflight')
var util = require('util')
var childrenIgnored = common.childrenIgnored
var isIgnored = common.isIgnored
var once = require('once')
function glob (pattern, options, cb) {
if (typeof options === 'function') cb = options, options = {}
if (!options) options = {}
if (options.sync) {
if (cb)
throw new TypeError('callback provided to sync glob')
return globSync(pattern, options)
}
return new Glob(pattern, options, cb)
}
glob.sync = globSync
var GlobSync = glob.GlobSync = globSync.GlobSync
// old api surface
glob.glob = glob
glob.hasMagic = function (pattern, options_) {
var options = util._extend({}, options_)
options.noprocess = true
var g = new Glob(pattern, options)
var set = g.minimatch.set
if (set.length > 1)
return true
for (var j = 0; j < set[0].length; j++) {
if (typeof set[0][j] !== 'string')
return true
}
return false
}
glob.Glob = Glob
inherits(Glob, EE)
function Glob (pattern, options, cb) {
if (typeof options === 'function') {
cb = options
options = null
}
if (options && options.sync) {
if (cb)
throw new TypeError('callback provided to sync glob')
return new GlobSync(pattern, options)
}
if (!(this instanceof Glob))
return new Glob(pattern, options, cb)
setopts(this, pattern, options)
this._didRealPath = false
// process each pattern in the minimatch set
var n = this.minimatch.set.length
// The matches are stored as {<filename>: true,...} so that
// duplicates are automagically pruned.
// Later, we do an Object.keys() on these.
// Keep them as a list so we can fill in when nonull is set.
this.matches = new Array(n)
if (typeof cb === 'function') {
cb = once(cb)
this.on('error', cb)
this.on('end', function (matches) {
cb(null, matches)
})
}
var self = this
var n = this.minimatch.set.length
this._processing = 0
this.matches = new Array(n)
this._emitQueue = []
this._processQueue = []
this.paused = false
if (this.noprocess)
return this
if (n === 0)
return done()
for (var i = 0; i < n; i ++) {
this._process(this.minimatch.set[i], i, false, done)
}
function done () {
--self._processing
if (self._processing <= 0)
self._finish()
}
}
Glob.prototype._finish = function () {
assert(this instanceof Glob)
if (this.aborted)
return
if (this.realpath && !this._didRealpath)
return this._realpath()
common.finish(this)
this.emit('end', this.found)
}
Glob.prototype._realpath = function () {
if (this._didRealpath)
return
this._didRealpath = true
var n = this.matches.length
if (n === 0)
return this._finish()
var self = this
for (var i = 0; i < this.matches.length; i++)
this._realpathSet(i, next)
function next () {
if (--n === 0)
self._finish()
}
}
Glob.prototype._realpathSet = function (index, cb) {
var matchset = this.matches[index]
if (!matchset)
return cb()
var found = Object.keys(matchset)
var self = this
var n = found.length
if (n === 0)
return cb()
var set = this.matches[index] = Object.create(null)
found.forEach(function (p, i) {
// If there's a problem with the stat, then it means that
// one or more of the links in the realpath couldn't be
// resolved. just return the abs value in that case.
p = self._makeAbs(p)
fs.realpath(p, self.realpathCache, function (er, real) {
if (!er)
set[real] = true
else if (er.syscall === 'stat')
set[p] = true
else
self.emit('error', er) // srsly wtf right here
if (--n === 0) {
self.matches[index] = set
cb()
}
})
})
}
Glob.prototype._mark = function (p) {
return common.mark(this, p)
}
Glob.prototype._makeAbs = function (f) {
return common.makeAbs(this, f)
}
Glob.prototype.abort = function () {
this.aborted = true
this.emit('abort')
}
Glob.prototype.pause = function () {
if (!this.paused) {
this.paused = true
this.emit('pause')
}
}
Glob.prototype.resume = function () {
if (this.paused) {
this.emit('resume')
this.paused = false
if (this._emitQueue.length) {
var eq = this._emitQueue.slice(0)
this._emitQueue.length = 0
for (var i = 0; i < eq.length; i ++) {
var e = eq[i]
this._emitMatch(e[0], e[1])
}
}
if (this._processQueue.length) {
var pq = this._processQueue.slice(0)
this._processQueue.length = 0
for (var i = 0; i < pq.length; i ++) {
var p = pq[i]
this._processing--
this._process(p[0], p[1], p[2], p[3])
}
}
}
}
Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
assert(this instanceof Glob)
assert(typeof cb === 'function')
if (this.aborted)
return
this._processing++
if (this.paused) {
this._processQueue.push([pattern, index, inGlobStar, cb])
return
}
//console.error('PROCESS %d', this._processing, pattern)
// Get the first [n] parts of pattern that are all strings.
var n = 0
while (typeof pattern[n] === 'string') {
n ++
}
// now n is the index of the first one that is *not* a string.
// see if there's anything else
var prefix
switch (n) {
// if not, then this is rather simple
case pattern.length:
this._processSimple(pattern.join('/'), index, cb)
return
case 0:
// pattern *starts* with some non-trivial item.
// going to readdir(cwd), but not include the prefix in matches.
prefix = null
break
default:
// pattern has some string bits in the front.
// whatever it starts with, whether that's 'absolute' like /foo/bar,
// or 'relative' like '../baz'
prefix = pattern.slice(0, n).join('/')
break
}
var remain = pattern.slice(n)
// get the list of entries.
var read
if (prefix === null)
read = '.'
else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
if (!prefix || !isAbsolute(prefix))
prefix = '/' + prefix
read = prefix
} else
read = prefix
var abs = this._makeAbs(read)
//if ignored, skip _processing
if (childrenIgnored(this, read))
return cb()
var isGlobStar = remain[0] === minimatch.GLOBSTAR
if (isGlobStar)
this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
else
this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
}
Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
var self = this
this._readdir(abs, inGlobStar, function (er, entries) {
return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
})
}
Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
// if the abs isn't a dir, then nothing can match!
if (!entries)
return cb()
// It will only match dot entries if it starts with a dot, or if
// dot is set. Stuff like @(.foo|.bar) isn't allowed.
var pn = remain[0]
var negate = !!this.minimatch.negate
var rawGlob = pn._glob
var dotOk = this.dot || rawGlob.charAt(0) === '.'
var matchedEntries = []
for (var i = 0; i < entries.length; i++) {
var e = entries[i]
if (e.charAt(0) !== '.' || dotOk) {
var m
if (negate && !prefix) {
m = !e.match(pn)
} else {
m = e.match(pn)
}
if (m)
matchedEntries.push(e)
}
}
//console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
var len = matchedEntries.length
// If there are no matched entries, then nothing matches.
if (len === 0)
return cb()
// if this is the last remaining pattern bit, then no need for
// an additional stat *unless* the user has specified mark or
// stat explicitly. We know they exist, since readdir returned
// them.
if (remain.length === 1 && !this.mark && !this.stat) {
if (!this.matches[index])
this.matches[index] = Object.create(null)
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
if (prefix) {
if (prefix !== '/')
e = prefix + '/' + e
else
e = prefix + e
}
if (e.charAt(0) === '/' && !this.nomount) {
e = path.join(this.root, e)
}
this._emitMatch(index, e)
}
// This was the last one, and no stats were needed
return cb()
}
// now test all matched entries as stand-ins for that part
// of the pattern.
remain.shift()
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
var newPattern
if (prefix) {
if (prefix !== '/')
e = prefix + '/' + e
else
e = prefix + e
}
this._process([e].concat(remain), index, inGlobStar, cb)
}
cb()
}
Glob.prototype._emitMatch = function (index, e) {
if (this.aborted)
return
if (this.matches[index][e])
return
if (isIgnored(this, e))
return
if (this.paused) {
this._emitQueue.push([index, e])
return
}
var abs = this._makeAbs(e)
if (this.nodir) {
var c = this.cache[abs]
if (c === 'DIR' || Array.isArray(c))
return
}
if (this.mark)
e = this._mark(e)
this.matches[index][e] = true
var st = this.statCache[abs]
if (st)
this.emit('stat', e, st)
this.emit('match', e)
}
Glob.prototype._readdirInGlobStar = function (abs, cb) {
if (this.aborted)
return
// follow all symlinked directories forever
// just proceed as if this is a non-globstar situation
if (this.follow)
return this._readdir(abs, false, cb)
var lstatkey = 'lstat\0' + abs
var self = this
var lstatcb = inflight(lstatkey, lstatcb_)
if (lstatcb)
fs.lstat(abs, lstatcb)
function lstatcb_ (er, lstat) {
if (er)
return cb()
var isSym = lstat.isSymbolicLink()
self.symlinks[abs] = isSym
// If it's not a symlink or a dir, then it's definitely a regular file.
// don't bother doing a readdir in that case.
if (!isSym && !lstat.isDirectory()) {
self.cache[abs] = 'FILE'
cb()
} else
self._readdir(abs, false, cb)
}
}
Glob.prototype._readdir = function (abs, inGlobStar, cb) {
if (this.aborted)
return
cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
if (!cb)
return
//console.error('RD %j %j', +inGlobStar, abs)
if (inGlobStar && !ownProp(this.symlinks, abs))
return this._readdirInGlobStar(abs, cb)
if (ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (!c || c === 'FILE')
return cb()
if (Array.isArray(c))
return cb(null, c)
}
var self = this
fs.readdir(abs, readdirCb(this, abs, cb))
}
function readdirCb (self, abs, cb) {
return function (er, entries) {
if (er)
self._readdirError(abs, er, cb)
else
self._readdirEntries(abs, entries, cb)
}
}
Glob.prototype._readdirEntries = function (abs, entries, cb) {
if (this.aborted)
return
// if we haven't asked to stat everything, then just
// assume that everything in there exists, so we can avoid
// having to stat it a second time.
if (!this.mark && !this.stat) {
for (var i = 0; i < entries.length; i ++) {
var e = entries[i]
if (abs === '/')
e = abs + e
else
e = abs + '/' + e
this.cache[e] = true
}
}
this.cache[abs] = entries
return cb(null, entries)
}
Glob.prototype._readdirError = function (f, er, cb) {
if (this.aborted)
return
// handle errors, and cache the information
switch (er.code) {
case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
case 'ENOTDIR': // totally normal. means it *does* exist.
this.cache[this._makeAbs(f)] = 'FILE'
break
case 'ENOENT': // not terribly unusual
case 'ELOOP':
case 'ENAMETOOLONG':
case 'UNKNOWN':
this.cache[this._makeAbs(f)] = false
break
default: // some unusual error. Treat as failure.
this.cache[this._makeAbs(f)] = false
if (this.strict) {
this.emit('error', er)
// If the error is handled, then we abort
// if not, we threw out of here
this.abort()
}
if (!this.silent)
console.error('glob error', er)
break
}
return cb()
}
Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
var self = this
this._readdir(abs, inGlobStar, function (er, entries) {
self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
})
}
Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
//console.error('pgs2', prefix, remain[0], entries)
// no entries means not a dir, so it can never have matches
// foo.txt/** doesn't match foo.txt
if (!entries)
return cb()
// test without the globstar, and with every child both below
// and replacing the globstar.
var remainWithoutGlobStar = remain.slice(1)
var gspref = prefix ? [ prefix ] : []
var noGlobStar = gspref.concat(remainWithoutGlobStar)
// the noGlobStar pattern exits the inGlobStar state
this._process(noGlobStar, index, false, cb)
var isSym = this.symlinks[abs]
var len = entries.length
// If it's a symlink, and we're in a globstar, then stop
if (isSym && inGlobStar)
return cb()
for (var i = 0; i < len; i++) {
var e = entries[i]
if (e.charAt(0) === '.' && !this.dot)
continue
// these two cases enter the inGlobStar state
var instead = gspref.concat(entries[i], remainWithoutGlobStar)
this._process(instead, index, true, cb)
var below = gspref.concat(entries[i], remain)
this._process(below, index, true, cb)
}
cb()
}
Glob.prototype._processSimple = function (prefix, index, cb) {
// XXX review this. Shouldn't it be doing the mounting etc
// before doing stat? kinda weird?
var self = this
this._stat(prefix, function (er, exists) {
self._processSimple2(prefix, index, er, exists, cb)
})
}
Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
//console.error('ps2', prefix, exists)
if (!this.matches[index])
this.matches[index] = Object.create(null)
// If it doesn't exist, then just mark the lack of results
if (!exists)
return cb()
if (prefix && isAbsolute(prefix) && !this.nomount) {
var trail = /[\/\\]$/.test(prefix)
if (prefix.charAt(0) === '/') {
prefix = path.join(this.root, prefix)
} else {
prefix = path.resolve(this.root, prefix)
if (trail)
prefix += '/'
}
}
if (process.platform === 'win32')
prefix = prefix.replace(/\\/g, '/')
// Mark this as a match
this._emitMatch(index, prefix)
cb()
}
// Returns either 'DIR', 'FILE', or false
Glob.prototype._stat = function (f, cb) {
var abs = this._makeAbs(f)
var needDir = f.slice(-1) === '/'
if (f.length > this.maxLength)
return cb()
if (!this.stat && ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (Array.isArray(c))
c = 'DIR'
// It exists, but maybe not how we need it
if (!needDir || c === 'DIR')
return cb(null, c)
if (needDir && c === 'FILE')
return cb()
// otherwise we have to stat, because maybe c=true
// if we know it exists, but not what it is.
}
var exists
var stat = this.statCache[abs]
if (stat !== undefined) {
if (stat === false)
return cb(null, stat)
else {
var type = stat.isDirectory() ? 'DIR' : 'FILE'
if (needDir && type === 'FILE')
return cb()
else
return cb(null, type, stat)
}
}
var self = this
var statcb = inflight('stat\0' + abs, lstatcb_)
if (statcb)
fs.lstat(abs, statcb)
function lstatcb_ (er, lstat) {
if (lstat && lstat.isSymbolicLink()) {
// If it's a symlink, then treat it as the target, unless
// the target does not exist, then treat it as a file.
return fs.stat(abs, function (er, stat) {
if (er)
self._stat2(f, abs, null, lstat, cb)
else
self._stat2(f, abs, er, stat, cb)
})
} else {
self._stat2(f, abs, er, lstat, cb)
}
}
}
Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
if (er) {
this.statCache[abs] = false
return cb()
}
var needDir = f.slice(-1) === '/'
this.statCache[abs] = stat
if (abs.slice(-1) === '/' && !stat.isDirectory())
return cb(null, false, stat)
var c = stat.isDirectory() ? 'DIR' : 'FILE'
this.cache[abs] = this.cache[abs] || c
if (needDir && c !== 'DIR')
return cb()
return cb(null, c, stat)
}

View File

@@ -0,0 +1,98 @@
{
"_args": [
[
"glob@~5.0.0",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/findup-sync"
]
],
"_from": "glob@>=5.0.0 <5.1.0",
"_id": "glob@5.0.15",
"_inCache": true,
"_installable": true,
"_location": "/gulp/glob",
"_nodeVersion": "4.0.0",
"_npmUser": {
"email": "isaacs@npmjs.com",
"name": "isaacs"
},
"_npmVersion": "3.3.2",
"_phantomChildren": {},
"_requested": {
"name": "glob",
"raw": "glob@~5.0.0",
"rawSpec": "~5.0.0",
"scope": null,
"spec": ">=5.0.0 <5.1.0",
"type": "range"
},
"_requiredBy": [
"/gulp/findup-sync"
],
"_resolved": "https://registry.npmjs.org/glob/-/glob-5.0.15.tgz",
"_shasum": "1bc936b9e02f4a603fcc222ecf7633d30b8b93b1",
"_shrinkwrap": null,
"_spec": "glob@~5.0.0",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/findup-sync",
"author": {
"email": "i@izs.me",
"name": "Isaac Z. Schlueter",
"url": "http://blog.izs.me/"
},
"bugs": {
"url": "https://github.com/isaacs/node-glob/issues"
},
"dependencies": {
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "2 || 3",
"once": "^1.3.0",
"path-is-absolute": "^1.0.0"
},
"description": "a little globber",
"devDependencies": {
"mkdirp": "0",
"rimraf": "^2.2.8",
"tap": "^1.1.4",
"tick": "0.0.6"
},
"directories": {},
"dist": {
"shasum": "1bc936b9e02f4a603fcc222ecf7633d30b8b93b1",
"tarball": "https://registry.npmjs.org/glob/-/glob-5.0.15.tgz"
},
"engines": {
"node": "*"
},
"files": [
"glob.js",
"sync.js",
"common.js"
],
"gitHead": "3a7e71d453dd80e75b196fd262dd23ed54beeceb",
"homepage": "https://github.com/isaacs/node-glob#readme",
"license": "ISC",
"main": "glob.js",
"maintainers": [
{
"email": "i@izs.me",
"name": "isaacs"
}
],
"name": "glob",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/isaacs/node-glob.git"
},
"scripts": {
"bench": "bash benchmark.sh",
"benchclean": "node benchclean.js",
"prepublish": "npm run benchclean",
"prof": "bash prof.sh && cat profile.txt",
"profclean": "rm -f v8.log profile.txt",
"test": "tap test/*.js --cov",
"test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js"
},
"version": "5.0.15"
}

View File

@@ -0,0 +1,460 @@
module.exports = globSync
globSync.GlobSync = GlobSync
var fs = require('fs')
var minimatch = require('minimatch')
var Minimatch = minimatch.Minimatch
var Glob = require('./glob.js').Glob
var util = require('util')
var path = require('path')
var assert = require('assert')
var isAbsolute = require('path-is-absolute')
var common = require('./common.js')
var alphasort = common.alphasort
var alphasorti = common.alphasorti
var setopts = common.setopts
var ownProp = common.ownProp
var childrenIgnored = common.childrenIgnored
function globSync (pattern, options) {
if (typeof options === 'function' || arguments.length === 3)
throw new TypeError('callback provided to sync glob\n'+
'See: https://github.com/isaacs/node-glob/issues/167')
return new GlobSync(pattern, options).found
}
function GlobSync (pattern, options) {
if (!pattern)
throw new Error('must provide pattern')
if (typeof options === 'function' || arguments.length === 3)
throw new TypeError('callback provided to sync glob\n'+
'See: https://github.com/isaacs/node-glob/issues/167')
if (!(this instanceof GlobSync))
return new GlobSync(pattern, options)
setopts(this, pattern, options)
if (this.noprocess)
return this
var n = this.minimatch.set.length
this.matches = new Array(n)
for (var i = 0; i < n; i ++) {
this._process(this.minimatch.set[i], i, false)
}
this._finish()
}
GlobSync.prototype._finish = function () {
assert(this instanceof GlobSync)
if (this.realpath) {
var self = this
this.matches.forEach(function (matchset, index) {
var set = self.matches[index] = Object.create(null)
for (var p in matchset) {
try {
p = self._makeAbs(p)
var real = fs.realpathSync(p, self.realpathCache)
set[real] = true
} catch (er) {
if (er.syscall === 'stat')
set[self._makeAbs(p)] = true
else
throw er
}
}
})
}
common.finish(this)
}
GlobSync.prototype._process = function (pattern, index, inGlobStar) {
assert(this instanceof GlobSync)
// Get the first [n] parts of pattern that are all strings.
var n = 0
while (typeof pattern[n] === 'string') {
n ++
}
// now n is the index of the first one that is *not* a string.
// See if there's anything else
var prefix
switch (n) {
// if not, then this is rather simple
case pattern.length:
this._processSimple(pattern.join('/'), index)
return
case 0:
// pattern *starts* with some non-trivial item.
// going to readdir(cwd), but not include the prefix in matches.
prefix = null
break
default:
// pattern has some string bits in the front.
// whatever it starts with, whether that's 'absolute' like /foo/bar,
// or 'relative' like '../baz'
prefix = pattern.slice(0, n).join('/')
break
}
var remain = pattern.slice(n)
// get the list of entries.
var read
if (prefix === null)
read = '.'
else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
if (!prefix || !isAbsolute(prefix))
prefix = '/' + prefix
read = prefix
} else
read = prefix
var abs = this._makeAbs(read)
//if ignored, skip processing
if (childrenIgnored(this, read))
return
var isGlobStar = remain[0] === minimatch.GLOBSTAR
if (isGlobStar)
this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)
else
this._processReaddir(prefix, read, abs, remain, index, inGlobStar)
}
GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
var entries = this._readdir(abs, inGlobStar)
// if the abs isn't a dir, then nothing can match!
if (!entries)
return
// It will only match dot entries if it starts with a dot, or if
// dot is set. Stuff like @(.foo|.bar) isn't allowed.
var pn = remain[0]
var negate = !!this.minimatch.negate
var rawGlob = pn._glob
var dotOk = this.dot || rawGlob.charAt(0) === '.'
var matchedEntries = []
for (var i = 0; i < entries.length; i++) {
var e = entries[i]
if (e.charAt(0) !== '.' || dotOk) {
var m
if (negate && !prefix) {
m = !e.match(pn)
} else {
m = e.match(pn)
}
if (m)
matchedEntries.push(e)
}
}
var len = matchedEntries.length
// If there are no matched entries, then nothing matches.
if (len === 0)
return
// if this is the last remaining pattern bit, then no need for
// an additional stat *unless* the user has specified mark or
// stat explicitly. We know they exist, since readdir returned
// them.
if (remain.length === 1 && !this.mark && !this.stat) {
if (!this.matches[index])
this.matches[index] = Object.create(null)
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
if (prefix) {
if (prefix.slice(-1) !== '/')
e = prefix + '/' + e
else
e = prefix + e
}
if (e.charAt(0) === '/' && !this.nomount) {
e = path.join(this.root, e)
}
this.matches[index][e] = true
}
// This was the last one, and no stats were needed
return
}
// now test all matched entries as stand-ins for that part
// of the pattern.
remain.shift()
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
var newPattern
if (prefix)
newPattern = [prefix, e]
else
newPattern = [e]
this._process(newPattern.concat(remain), index, inGlobStar)
}
}
GlobSync.prototype._emitMatch = function (index, e) {
var abs = this._makeAbs(e)
if (this.mark)
e = this._mark(e)
if (this.matches[index][e])
return
if (this.nodir) {
var c = this.cache[this._makeAbs(e)]
if (c === 'DIR' || Array.isArray(c))
return
}
this.matches[index][e] = true
if (this.stat)
this._stat(e)
}
GlobSync.prototype._readdirInGlobStar = function (abs) {
// follow all symlinked directories forever
// just proceed as if this is a non-globstar situation
if (this.follow)
return this._readdir(abs, false)
var entries
var lstat
var stat
try {
lstat = fs.lstatSync(abs)
} catch (er) {
// lstat failed, doesn't exist
return null
}
var isSym = lstat.isSymbolicLink()
this.symlinks[abs] = isSym
// If it's not a symlink or a dir, then it's definitely a regular file.
// don't bother doing a readdir in that case.
if (!isSym && !lstat.isDirectory())
this.cache[abs] = 'FILE'
else
entries = this._readdir(abs, false)
return entries
}
GlobSync.prototype._readdir = function (abs, inGlobStar) {
var entries
if (inGlobStar && !ownProp(this.symlinks, abs))
return this._readdirInGlobStar(abs)
if (ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (!c || c === 'FILE')
return null
if (Array.isArray(c))
return c
}
try {
return this._readdirEntries(abs, fs.readdirSync(abs))
} catch (er) {
this._readdirError(abs, er)
return null
}
}
GlobSync.prototype._readdirEntries = function (abs, entries) {
// if we haven't asked to stat everything, then just
// assume that everything in there exists, so we can avoid
// having to stat it a second time.
if (!this.mark && !this.stat) {
for (var i = 0; i < entries.length; i ++) {
var e = entries[i]
if (abs === '/')
e = abs + e
else
e = abs + '/' + e
this.cache[e] = true
}
}
this.cache[abs] = entries
// mark and cache dir-ness
return entries
}
GlobSync.prototype._readdirError = function (f, er) {
// handle errors, and cache the information
switch (er.code) {
case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
case 'ENOTDIR': // totally normal. means it *does* exist.
this.cache[this._makeAbs(f)] = 'FILE'
break
case 'ENOENT': // not terribly unusual
case 'ELOOP':
case 'ENAMETOOLONG':
case 'UNKNOWN':
this.cache[this._makeAbs(f)] = false
break
default: // some unusual error. Treat as failure.
this.cache[this._makeAbs(f)] = false
if (this.strict)
throw er
if (!this.silent)
console.error('glob error', er)
break
}
}
GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
var entries = this._readdir(abs, inGlobStar)
// no entries means not a dir, so it can never have matches
// foo.txt/** doesn't match foo.txt
if (!entries)
return
// test without the globstar, and with every child both below
// and replacing the globstar.
var remainWithoutGlobStar = remain.slice(1)
var gspref = prefix ? [ prefix ] : []
var noGlobStar = gspref.concat(remainWithoutGlobStar)
// the noGlobStar pattern exits the inGlobStar state
this._process(noGlobStar, index, false)
var len = entries.length
var isSym = this.symlinks[abs]
// If it's a symlink, and we're in a globstar, then stop
if (isSym && inGlobStar)
return
for (var i = 0; i < len; i++) {
var e = entries[i]
if (e.charAt(0) === '.' && !this.dot)
continue
// these two cases enter the inGlobStar state
var instead = gspref.concat(entries[i], remainWithoutGlobStar)
this._process(instead, index, true)
var below = gspref.concat(entries[i], remain)
this._process(below, index, true)
}
}
GlobSync.prototype._processSimple = function (prefix, index) {
// XXX review this. Shouldn't it be doing the mounting etc
// before doing stat? kinda weird?
var exists = this._stat(prefix)
if (!this.matches[index])
this.matches[index] = Object.create(null)
// If it doesn't exist, then just mark the lack of results
if (!exists)
return
if (prefix && isAbsolute(prefix) && !this.nomount) {
var trail = /[\/\\]$/.test(prefix)
if (prefix.charAt(0) === '/') {
prefix = path.join(this.root, prefix)
} else {
prefix = path.resolve(this.root, prefix)
if (trail)
prefix += '/'
}
}
if (process.platform === 'win32')
prefix = prefix.replace(/\\/g, '/')
// Mark this as a match
this.matches[index][prefix] = true
}
// Returns either 'DIR', 'FILE', or false
GlobSync.prototype._stat = function (f) {
var abs = this._makeAbs(f)
var needDir = f.slice(-1) === '/'
if (f.length > this.maxLength)
return false
if (!this.stat && ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (Array.isArray(c))
c = 'DIR'
// It exists, but maybe not how we need it
if (!needDir || c === 'DIR')
return c
if (needDir && c === 'FILE')
return false
// otherwise we have to stat, because maybe c=true
// if we know it exists, but not what it is.
}
var exists
var stat = this.statCache[abs]
if (!stat) {
var lstat
try {
lstat = fs.lstatSync(abs)
} catch (er) {
return false
}
if (lstat.isSymbolicLink()) {
try {
stat = fs.statSync(abs)
} catch (er) {
stat = lstat
}
} else {
stat = lstat
}
}
this.statCache[abs] = stat
var c = stat.isDirectory() ? 'DIR' : 'FILE'
this.cache[abs] = this.cache[abs] || c
if (needDir && c !== 'DIR')
return false
return c
}
GlobSync.prototype._mark = function (p) {
return common.mark(this, p)
}
GlobSync.prototype._makeAbs = function (f) {
return common.makeAbs(this, f)
}

View File

@@ -0,0 +1,15 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,36 @@
# graceful-fs
graceful-fs functions as a drop-in replacement for the fs module,
making various improvements.
The improvements are meant to normalize behavior across different
platforms and environments, and to make filesystem access more
resilient to errors.
## Improvements over [fs module](http://api.nodejs.org/fs.html)
graceful-fs:
* Queues up `open` and `readdir` calls, and retries them once
something closes if there is an EMFILE error from too many file
descriptors.
* fixes `lchmod` for Node versions prior to 0.6.2.
* implements `fs.lutimes` if possible. Otherwise it becomes a noop.
* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or
`lchown` if the user isn't root.
* makes `lchmod` and `lchown` become noops, if not available.
* retries reading a file if `read` results in EAGAIN error.
On Windows, it retries renaming a file for up to one second if `EACCESS`
or `EPERM` error occurs, likely because antivirus software has locked
the directory.
## USAGE
```javascript
// use just like fs
var fs = require('graceful-fs')
// now go and do stuff with it...
fs.readFileSync('some-file-or-whatever')
```

View File

@@ -0,0 +1,11 @@
// eeeeeevvvvviiiiiiillllll
// more evil than monkey-patching the native builtin?
// Not sure.
var mod = require("module")
var pre = '(function (exports, require, module, __filename, __dirname) { '
var post = '});'
var src = pre + process.binding('natives').fs + post
var vm = require('vm')
var fn = vm.runInThisContext(src)
fn(exports, require, module, __filename, __dirname)

View File

@@ -0,0 +1,158 @@
// Monkey-patching the fs module.
// It's ugly, but there is simply no other way to do this.
var fs = module.exports = require('./fs.js')
var assert = require('assert')
// fix up some busted stuff, mostly on windows and old nodes
require('./polyfills.js')
var util = require('util')
function noop () {}
var debug = noop
if (util.debuglog)
debug = util.debuglog('gfs')
else if (/\bgfs\b/i.test(process.env.NODE_DEBUG || ''))
debug = function() {
var m = util.format.apply(util, arguments)
m = 'GFS: ' + m.split(/\n/).join('\nGFS: ')
console.error(m)
}
if (/\bgfs\b/i.test(process.env.NODE_DEBUG || '')) {
process.on('exit', function() {
debug('fds', fds)
debug(queue)
assert.equal(queue.length, 0)
})
}
var originalOpen = fs.open
fs.open = open
function open(path, flags, mode, cb) {
if (typeof mode === "function") cb = mode, mode = null
if (typeof cb !== "function") cb = noop
new OpenReq(path, flags, mode, cb)
}
function OpenReq(path, flags, mode, cb) {
this.path = path
this.flags = flags
this.mode = mode
this.cb = cb
Req.call(this)
}
util.inherits(OpenReq, Req)
OpenReq.prototype.process = function() {
originalOpen.call(fs, this.path, this.flags, this.mode, this.done)
}
var fds = {}
OpenReq.prototype.done = function(er, fd) {
debug('open done', er, fd)
if (fd)
fds['fd' + fd] = this.path
Req.prototype.done.call(this, er, fd)
}
var originalReaddir = fs.readdir
fs.readdir = readdir
function readdir(path, cb) {
if (typeof cb !== "function") cb = noop
new ReaddirReq(path, cb)
}
function ReaddirReq(path, cb) {
this.path = path
this.cb = cb
Req.call(this)
}
util.inherits(ReaddirReq, Req)
ReaddirReq.prototype.process = function() {
originalReaddir.call(fs, this.path, this.done)
}
ReaddirReq.prototype.done = function(er, files) {
if (files && files.sort)
files = files.sort()
Req.prototype.done.call(this, er, files)
onclose()
}
var originalClose = fs.close
fs.close = close
function close (fd, cb) {
debug('close', fd)
if (typeof cb !== "function") cb = noop
delete fds['fd' + fd]
originalClose.call(fs, fd, function(er) {
onclose()
cb(er)
})
}
var originalCloseSync = fs.closeSync
fs.closeSync = closeSync
function closeSync (fd) {
try {
return originalCloseSync(fd)
} finally {
onclose()
}
}
// Req class
function Req () {
// start processing
this.done = this.done.bind(this)
this.failures = 0
this.process()
}
Req.prototype.done = function (er, result) {
var tryAgain = false
if (er) {
var code = er.code
var tryAgain = code === "EMFILE" || code === "ENFILE"
if (process.platform === "win32")
tryAgain = tryAgain || code === "OK"
}
if (tryAgain) {
this.failures ++
enqueue(this)
} else {
var cb = this.cb
cb(er, result)
}
}
var queue = []
function enqueue(req) {
queue.push(req)
debug('enqueue %d %s', queue.length, req.constructor.name, req)
}
function onclose() {
var req = queue.shift()
if (req) {
debug('process', req.constructor.name, req)
req.process()
}
}

View File

@@ -0,0 +1,99 @@
{
"_args": [
[
"graceful-fs@^3.0.0",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/vinyl-fs"
]
],
"_from": "graceful-fs@>=3.0.0 <4.0.0",
"_id": "graceful-fs@3.0.8",
"_inCache": true,
"_installable": true,
"_location": "/gulp/graceful-fs",
"_nodeVersion": "2.0.1",
"_npmUser": {
"email": "isaacs@npmjs.com",
"name": "isaacs"
},
"_npmVersion": "2.10.1",
"_phantomChildren": {},
"_requested": {
"name": "graceful-fs",
"raw": "graceful-fs@^3.0.0",
"rawSpec": "^3.0.0",
"scope": null,
"spec": ">=3.0.0 <4.0.0",
"type": "range"
},
"_requiredBy": [
"/gulp/vinyl-fs"
],
"_resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-3.0.8.tgz",
"_shasum": "ce813e725fa82f7e6147d51c9a5ca68270551c22",
"_shrinkwrap": null,
"_spec": "graceful-fs@^3.0.0",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/vinyl-fs",
"author": {
"email": "i@izs.me",
"name": "Isaac Z. Schlueter",
"url": "http://blog.izs.me"
},
"bugs": {
"url": "https://github.com/isaacs/node-graceful-fs/issues"
},
"dependencies": {},
"deprecated": "graceful-fs version 3 and before will fail on newer node releases. Please update to graceful-fs@^4.0.0 as soon as possible.",
"description": "A drop-in replacement for fs, making various improvements.",
"devDependencies": {
"mkdirp": "^0.5.0",
"rimraf": "^2.2.8",
"tap": "^1.2.0"
},
"directories": {
"test": "test"
},
"dist": {
"shasum": "ce813e725fa82f7e6147d51c9a5ca68270551c22",
"tarball": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-3.0.8.tgz"
},
"engines": {
"node": ">=0.4.0"
},
"gitHead": "45c57aa5e323c35a985a525de6f0c9a6ef59e1f8",
"homepage": "https://github.com/isaacs/node-graceful-fs#readme",
"keywords": [
"fs",
"module",
"reading",
"retry",
"retries",
"queue",
"error",
"errors",
"handling",
"EMFILE",
"EAGAIN",
"EINVAL",
"EPERM",
"EACCESS"
],
"license": "ISC",
"main": "graceful-fs.js",
"maintainers": [
{
"email": "i@izs.me",
"name": "isaacs"
}
],
"name": "graceful-fs",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/isaacs/node-graceful-fs.git"
},
"scripts": {
"test": "tap test/*.js"
},
"version": "3.0.8"
}

View File

@@ -0,0 +1,255 @@
var fs = require('./fs.js')
var constants = require('constants')
var origCwd = process.cwd
var cwd = null
process.cwd = function() {
if (!cwd)
cwd = origCwd.call(process)
return cwd
}
var chdir = process.chdir
process.chdir = function(d) {
cwd = null
chdir.call(process, d)
}
// (re-)implement some things that are known busted or missing.
// lchmod, broken prior to 0.6.2
// back-port the fix here.
if (constants.hasOwnProperty('O_SYMLINK') &&
process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
fs.lchmod = function (path, mode, callback) {
callback = callback || noop
fs.open( path
, constants.O_WRONLY | constants.O_SYMLINK
, mode
, function (err, fd) {
if (err) {
callback(err)
return
}
// prefer to return the chmod error, if one occurs,
// but still try to close, and report closing errors if they occur.
fs.fchmod(fd, mode, function (err) {
fs.close(fd, function(err2) {
callback(err || err2)
})
})
})
}
fs.lchmodSync = function (path, mode) {
var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode)
// prefer to return the chmod error, if one occurs,
// but still try to close, and report closing errors if they occur.
var err, err2
try {
var ret = fs.fchmodSync(fd, mode)
} catch (er) {
err = er
}
try {
fs.closeSync(fd)
} catch (er) {
err2 = er
}
if (err || err2) throw (err || err2)
return ret
}
}
// lutimes implementation, or no-op
if (!fs.lutimes) {
if (constants.hasOwnProperty("O_SYMLINK")) {
fs.lutimes = function (path, at, mt, cb) {
fs.open(path, constants.O_SYMLINK, function (er, fd) {
cb = cb || noop
if (er) return cb(er)
fs.futimes(fd, at, mt, function (er) {
fs.close(fd, function (er2) {
return cb(er || er2)
})
})
})
}
fs.lutimesSync = function (path, at, mt) {
var fd = fs.openSync(path, constants.O_SYMLINK)
, err
, err2
, ret
try {
var ret = fs.futimesSync(fd, at, mt)
} catch (er) {
err = er
}
try {
fs.closeSync(fd)
} catch (er) {
err2 = er
}
if (err || err2) throw (err || err2)
return ret
}
} else if (fs.utimensat && constants.hasOwnProperty("AT_SYMLINK_NOFOLLOW")) {
// maybe utimensat will be bound soonish?
fs.lutimes = function (path, at, mt, cb) {
fs.utimensat(path, at, mt, constants.AT_SYMLINK_NOFOLLOW, cb)
}
fs.lutimesSync = function (path, at, mt) {
return fs.utimensatSync(path, at, mt, constants.AT_SYMLINK_NOFOLLOW)
}
} else {
fs.lutimes = function (_a, _b, _c, cb) { process.nextTick(cb) }
fs.lutimesSync = function () {}
}
}
// https://github.com/isaacs/node-graceful-fs/issues/4
// Chown should not fail on einval or eperm if non-root.
// It should not fail on enosys ever, as this just indicates
// that a fs doesn't support the intended operation.
fs.chown = chownFix(fs.chown)
fs.fchown = chownFix(fs.fchown)
fs.lchown = chownFix(fs.lchown)
fs.chmod = chownFix(fs.chmod)
fs.fchmod = chownFix(fs.fchmod)
fs.lchmod = chownFix(fs.lchmod)
fs.chownSync = chownFixSync(fs.chownSync)
fs.fchownSync = chownFixSync(fs.fchownSync)
fs.lchownSync = chownFixSync(fs.lchownSync)
fs.chmodSync = chownFix(fs.chmodSync)
fs.fchmodSync = chownFix(fs.fchmodSync)
fs.lchmodSync = chownFix(fs.lchmodSync)
function chownFix (orig) {
if (!orig) return orig
return function (target, uid, gid, cb) {
return orig.call(fs, target, uid, gid, function (er, res) {
if (chownErOk(er)) er = null
cb(er, res)
})
}
}
function chownFixSync (orig) {
if (!orig) return orig
return function (target, uid, gid) {
try {
return orig.call(fs, target, uid, gid)
} catch (er) {
if (!chownErOk(er)) throw er
}
}
}
// ENOSYS means that the fs doesn't support the op. Just ignore
// that, because it doesn't matter.
//
// if there's no getuid, or if getuid() is something other
// than 0, and the error is EINVAL or EPERM, then just ignore
// it.
//
// This specific case is a silent failure in cp, install, tar,
// and most other unix tools that manage permissions.
//
// When running as root, or if other types of errors are
// encountered, then it's strict.
function chownErOk (er) {
if (!er)
return true
if (er.code === "ENOSYS")
return true
var nonroot = !process.getuid || process.getuid() !== 0
if (nonroot) {
if (er.code === "EINVAL" || er.code === "EPERM")
return true
}
return false
}
// if lchmod/lchown do not exist, then make them no-ops
if (!fs.lchmod) {
fs.lchmod = function (path, mode, cb) {
process.nextTick(cb)
}
fs.lchmodSync = function () {}
}
if (!fs.lchown) {
fs.lchown = function (path, uid, gid, cb) {
process.nextTick(cb)
}
fs.lchownSync = function () {}
}
// on Windows, A/V software can lock the directory, causing this
// to fail with an EACCES or EPERM if the directory contains newly
// created files. Try again on failure, for up to 1 second.
if (process.platform === "win32") {
var rename_ = fs.rename
fs.rename = function rename (from, to, cb) {
var start = Date.now()
rename_(from, to, function CB (er) {
if (er
&& (er.code === "EACCES" || er.code === "EPERM")
&& Date.now() - start < 1000) {
return rename_(from, to, CB)
}
if(cb) cb(er)
})
}
}
// if read() returns EAGAIN, then just try it again.
var read = fs.read
fs.read = function (fd, buffer, offset, length, position, callback_) {
var callback
if (callback_ && typeof callback_ === 'function') {
var eagCounter = 0
callback = function (er, _, __) {
if (er && er.code === 'EAGAIN' && eagCounter < 10) {
eagCounter ++
return read.call(fs, fd, buffer, offset, length, position, callback)
}
callback_.apply(this, arguments)
}
}
return read.call(fs, fd, buffer, offset, length, position, callback)
}
var readSync = fs.readSync
fs.readSync = function (fd, buffer, offset, length, position) {
var eagCounter = 0
while (true) {
try {
return readSync.call(fs, fd, buffer, offset, length, position)
} catch (er) {
if (er.code === 'EAGAIN' && eagCounter < 10) {
eagCounter ++
continue
}
throw er
}
}
}

View File

@@ -0,0 +1,69 @@
var test = require('tap').test
var fs = require('../')
test('open lots of stuff', function (t) {
// Get around EBADF from libuv by making sure that stderr is opened
// Otherwise Darwin will refuse to give us a FD for stderr!
process.stderr.write('')
// How many parallel open()'s to do
var n = 1024
var opens = 0
var fds = []
var going = true
var closing = false
var doneCalled = 0
for (var i = 0; i < n; i++) {
go()
}
function go() {
opens++
fs.open(__filename, 'r', function (er, fd) {
if (er) throw er
fds.push(fd)
if (going) go()
})
}
// should hit ulimit pretty fast
setTimeout(function () {
going = false
t.equal(opens - fds.length, n)
done()
}, 100)
function done () {
if (closing) return
doneCalled++
if (fds.length === 0) {
console.error('done called %d times', doneCalled)
// First because of the timeout
// Then to close the fd's opened afterwards
// Then this time, to complete.
// Might take multiple passes, depending on CPU speed
// and ulimit, but at least 3 in every case.
t.ok(doneCalled >= 2)
return t.end()
}
closing = true
setTimeout(function () {
// console.error('do closing again')
closing = false
done()
}, 100)
// console.error('closing time')
var closes = fds.slice(0)
fds.length = 0
closes.forEach(function (fd) {
fs.close(fd, function (er) {
if (er) throw er
})
})
}
})

View File

@@ -0,0 +1,39 @@
var test = require('tap').test
var fs = require('../graceful-fs.js')
test('graceful fs is monkeypatched fs', function (t) {
t.equal(fs, require('../fs.js'))
t.end()
})
test('open an existing file works', function (t) {
var fd = fs.openSync(__filename, 'r')
fs.closeSync(fd)
fs.open(__filename, 'r', function (er, fd) {
if (er) throw er
fs.close(fd, function (er) {
if (er) throw er
t.pass('works')
t.end()
})
})
})
test('open a non-existing file throws', function (t) {
var er
try {
var fd = fs.openSync('this file does not exist', 'r')
} catch (x) {
er = x
}
t.ok(er, 'should throw')
t.notOk(fd, 'should not get an fd')
t.equal(er.code, 'ENOENT')
fs.open('neither does this file', 'r', function (er, fd) {
t.ok(er, 'should throw')
t.notOk(fd, 'should not get an fd')
t.equal(er.code, 'ENOENT')
t.end()
})
})

View File

@@ -0,0 +1,20 @@
var test = require("tap").test
var fs = require("../fs.js")
var readdir = fs.readdir
fs.readdir = function(path, cb) {
process.nextTick(function() {
cb(null, ["b", "z", "a"])
})
}
var g = require("../")
test("readdir reorder", function (t) {
g.readdir("whatevers", function (er, files) {
if (er)
throw er
t.same(files, [ "a", "b", "z" ])
t.end()
})
})

View File

@@ -0,0 +1,47 @@
var fs = require('../');
var rimraf = require('rimraf');
var mkdirp = require('mkdirp');
var test = require('tap').test;
var p = require('path').resolve(__dirname, 'files');
process.chdir(__dirname)
// Make sure to reserve the stderr fd
process.stderr.write('');
var num = 4097;
var paths = new Array(num);
test('make files', function (t) {
rimraf.sync(p);
mkdirp.sync(p);
for (var i = 0; i < num; ++i) {
paths[i] = 'files/file-' + i;
fs.writeFileSync(paths[i], 'content');
}
t.end();
})
test('read files', function (t) {
// now read them
var done = 0;
for (var i = 0; i < num; ++i) {
fs.readFile(paths[i], function(err, data) {
if (err)
throw err;
++done;
if (done === num) {
t.pass('success');
t.end()
}
});
}
});
test('cleanup', function (t) {
rimraf.sync(p);
t.end();
});

View File

@@ -0,0 +1,20 @@
Copyright (c) 2014 Fractal <contact@wearefractal.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,146 @@
# gulp-util [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Dependency Status][depstat-image]][depstat-url]
## Information
<table>
<tr>
<td>Package</td><td>gulp-util</td>
</tr>
<tr>
<td>Description</td>
<td>Utility functions for gulp plugins</td>
</tr>
<tr>
<td>Node Version</td>
<td>>= 0.10</td>
</tr>
</table>
## Usage
```javascript
var gutil = require('gulp-util');
gutil.log('stuff happened', 'Really it did', gutil.colors.magenta('123'));
gutil.beep();
gutil.replaceExtension('file.coffee', '.js'); // file.js
var opt = {
name: 'todd',
file: someGulpFile
};
gutil.template('test <%= name %> <%= file.path %>', opt) // test todd /js/hi.js
```
### log(msg...)
Logs stuff. Already prefixed with [gulp] and all that. If you pass in multiple arguments it will join them by a space.
The default gulp coloring using gutil.colors.<color>:
```
values (files, module names, etc.) = cyan
numbers (times, counts, etc) = magenta
```
### colors
Is an instance of [chalk](https://github.com/sindresorhus/chalk).
### replaceExtension(path, newExtension)
Replaces a file extension in a path. Returns the new path.
### isStream(obj)
Returns true or false if an object is a stream.
### isBuffer(obj)
Returns true or false if an object is a Buffer.
### template(string[, data])
This is a lodash.template function wrapper. You must pass in a valid gulp file object so it is available to the user or it will error. You can not configure any of the delimiters. Look at the [lodash docs](http://lodash.com/docs#template) for more info.
## new File(obj)
This is just [vinyl](https://github.com/wearefractal/vinyl)
```javascript
var file = new gutil.File({
base: path.join(__dirname, './fixtures/'),
cwd: __dirname,
path: path.join(__dirname, './fixtures/test.coffee')
});
```
## noop()
Returns a stream that does nothing but pass data straight through.
```javascript
// gulp should be called like this :
// $ gulp --type production
gulp.task('scripts', function() {
gulp.src('src/**/*.js')
.pipe(concat('script.js'))
.pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
.pipe(gulp.dest('dist/'));
});
```
## buffer(cb)
This is similar to es.wait but instead of buffering text into one string it buffers anything into an array (so very useful for file objects).
Returns a stream that can be piped to.
The stream will emit one data event after the stream piped to it has ended. The data will be the same array passed to the callback.
Callback is optional and receives two arguments: error and data
```javascript
gulp.src('stuff/*.js')
.pipe(gutil.buffer(function(err, files) {
}));
```
## new PluginError(pluginName, message[, options])
- pluginName should be the module name of your plugin
- message can be a string or an existing error
- By default the stack will not be shown. Set `options.showStack` to true if you think the stack is important for your error.
- If you pass an error in as the message the stack will be pulled from that, otherwise one will be created.
- Note that if you pass in a custom stack string you need to include the message along with that.
- Error properties will be included in `err.toString()`. Can be omitted by including `{showProperties: false}` in the options.
These are all acceptable forms of instantiation:
```javascript
var err = new gutil.PluginError('test', {
message: 'something broke'
});
var err = new gutil.PluginError({
plugin: 'test',
message: 'something broke'
});
var err = new gutil.PluginError('test', 'something broke');
var err = new gutil.PluginError('test', 'something broke', {showStack: true});
var existingError = new Error('OMG');
var err = new gutil.PluginError('test', existingError, {showStack: true});
```
[npm-url]: https://www.npmjs.com/package/gulp-util
[npm-image]: https://badge.fury.io/js/gulp-util.svg
[travis-url]: https://travis-ci.org/gulpjs/gulp-util
[travis-image]: https://img.shields.io/travis/gulpjs/gulp-util.svg?branch=master
[coveralls-url]: https://coveralls.io/r/gulpjs/gulp-util
[coveralls-image]: https://img.shields.io/coveralls/gulpjs/gulp-util.svg
[depstat-url]: https://david-dm.org/gulpjs/gulp-util
[depstat-image]: https://david-dm.org/gulpjs/gulp-util.svg

View File

@@ -0,0 +1,18 @@
module.exports = {
File: require('vinyl'),
replaceExtension: require('replace-ext'),
colors: require('chalk'),
date: require('dateformat'),
log: require('./lib/log'),
template: require('./lib/template'),
env: require('./lib/env'),
beep: require('beeper'),
noop: require('./lib/noop'),
isStream: require('./lib/isStream'),
isBuffer: require('./lib/isBuffer'),
isNull: require('./lib/isNull'),
linefeed: '\n',
combine: require('./lib/combine'),
buffer: require('./lib/buffer'),
PluginError: require('./lib/PluginError')
};

View File

@@ -0,0 +1,114 @@
{
"_args": [
[
"gulp-util@^3.0.0",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp"
]
],
"_from": "gulp-util@>=3.0.0 <4.0.0",
"_id": "gulp-util@3.0.7",
"_inCache": true,
"_installable": true,
"_location": "/gulp/gulp-util",
"_nodeVersion": "0.10.36",
"_npmUser": {
"email": "blaine@iceddev.com",
"name": "phated"
},
"_npmVersion": "2.14.3",
"_phantomChildren": {},
"_requested": {
"name": "gulp-util",
"raw": "gulp-util@^3.0.0",
"rawSpec": "^3.0.0",
"scope": null,
"spec": ">=3.0.0 <4.0.0",
"type": "range"
},
"_requiredBy": [
"/gulp"
],
"_resolved": "https://registry.npmjs.org/gulp-util/-/gulp-util-3.0.7.tgz",
"_shasum": "78925c4b8f8b49005ac01a011c557e6218941cbb",
"_shrinkwrap": null,
"_spec": "gulp-util@^3.0.0",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp",
"author": {
"email": "contact@wearefractal.com",
"name": "Fractal",
"url": "http://wearefractal.com/"
},
"bugs": {
"url": "https://github.com/gulpjs/gulp-util/issues"
},
"dependencies": {
"array-differ": "^1.0.0",
"array-uniq": "^1.0.2",
"beeper": "^1.0.0",
"chalk": "^1.0.0",
"dateformat": "^1.0.11",
"fancy-log": "^1.1.0",
"gulplog": "^1.0.0",
"has-gulplog": "^0.1.0",
"lodash._reescape": "^3.0.0",
"lodash._reevaluate": "^3.0.0",
"lodash._reinterpolate": "^3.0.0",
"lodash.template": "^3.0.0",
"minimist": "^1.1.0",
"multipipe": "^0.1.2",
"object-assign": "^3.0.0",
"replace-ext": "0.0.1",
"through2": "^2.0.0",
"vinyl": "^0.5.0"
},
"description": "Utility functions for gulp plugins",
"devDependencies": {
"buffer-equal": "^0.0.1",
"coveralls": "^2.11.2",
"event-stream": "^3.1.7",
"istanbul": "^0.3.5",
"istanbul-coveralls": "^1.0.1",
"jshint": "^2.5.11",
"lodash.templatesettings": "^3.0.0",
"mocha": "^2.0.1",
"rimraf": "^2.2.8",
"should": "^7.0.1"
},
"directories": {},
"dist": {
"shasum": "78925c4b8f8b49005ac01a011c557e6218941cbb",
"tarball": "https://registry.npmjs.org/gulp-util/-/gulp-util-3.0.7.tgz"
},
"engines": {
"node": ">=0.10"
},
"files": [
"index.js",
"lib"
],
"gitHead": "b74a5ff121471ed00b84fb1e73a0e75488d33ccd",
"homepage": "https://github.com/gulpjs/gulp-util#readme",
"license": "MIT",
"maintainers": [
{
"email": "contact@wearefractal.com",
"name": "fractal"
},
{
"email": "blaine@iceddev.com",
"name": "phated"
}
],
"name": "gulp-util",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/gulpjs/gulp-util.git"
},
"scripts": {
"coveralls": "istanbul cover _mocha --report lcovonly && istanbul-coveralls",
"test": "jshint *.js lib/*.js test/*.js && mocha"
},
"version": "3.0.7"
}

View File

@@ -0,0 +1,6 @@
test:
@node_modules/.bin/tape test.js
.PHONY: test

View File

@@ -0,0 +1,60 @@
# isarray
`Array#isArray` for older browsers.
[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray)
[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray)
[![browser support](https://ci.testling.com/juliangruber/isarray.png)
](https://ci.testling.com/juliangruber/isarray)
## Usage
```js
var isArray = require('isarray');
console.log(isArray([])); // => true
console.log(isArray({})); // => false
```
## Installation
With [npm](http://npmjs.org) do
```bash
$ npm install isarray
```
Then bundle for the browser with
[browserify](https://github.com/substack/browserify).
With [component](http://component.io) do
```bash
$ component install juliangruber/isarray
```
## License
(MIT)
Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,19 @@
{
"name" : "isarray",
"description" : "Array#isArray for older browsers",
"version" : "0.0.1",
"repository" : "juliangruber/isarray",
"homepage": "https://github.com/juliangruber/isarray",
"main" : "index.js",
"scripts" : [
"index.js"
],
"dependencies" : {},
"keywords": ["browser","isarray","array"],
"author": {
"name": "Julian Gruber",
"email": "mail@juliangruber.com",
"url": "http://juliangruber.com"
},
"license": "MIT"
}

View File

@@ -0,0 +1,5 @@
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};

View File

@@ -0,0 +1,96 @@
{
"_args": [
[
"isarray@~1.0.0",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/readable-stream"
]
],
"_from": "isarray@>=1.0.0 <1.1.0",
"_id": "isarray@1.0.0",
"_inCache": true,
"_installable": true,
"_location": "/gulp/isarray",
"_nodeVersion": "5.1.0",
"_npmUser": {
"email": "julian@juliangruber.com",
"name": "juliangruber"
},
"_npmVersion": "3.3.12",
"_phantomChildren": {},
"_requested": {
"name": "isarray",
"raw": "isarray@~1.0.0",
"rawSpec": "~1.0.0",
"scope": null,
"spec": ">=1.0.0 <1.1.0",
"type": "range"
},
"_requiredBy": [
"/gulp/readable-stream"
],
"_resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"_shasum": "bb935d48582cba168c06834957a54a3e07124f11",
"_shrinkwrap": null,
"_spec": "isarray@~1.0.0",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/readable-stream",
"author": {
"email": "mail@juliangruber.com",
"name": "Julian Gruber",
"url": "http://juliangruber.com"
},
"bugs": {
"url": "https://github.com/juliangruber/isarray/issues"
},
"dependencies": {},
"description": "Array#isArray for older browsers",
"devDependencies": {
"tape": "~2.13.4"
},
"directories": {},
"dist": {
"shasum": "bb935d48582cba168c06834957a54a3e07124f11",
"tarball": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz"
},
"gitHead": "2a23a281f369e9ae06394c0fb4d2381355a6ba33",
"homepage": "https://github.com/juliangruber/isarray",
"keywords": [
"browser",
"isarray",
"array"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"email": "julian@juliangruber.com",
"name": "juliangruber"
}
],
"name": "isarray",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/juliangruber/isarray.git"
},
"scripts": {
"test": "tape test.js"
},
"testling": {
"browsers": [
"ie/8..latest",
"firefox/17..latest",
"firefox/nightly",
"chrome/22..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
],
"files": "test.js"
},
"version": "1.0.0"
}

View File

@@ -0,0 +1,20 @@
var isArray = require('./');
var test = require('tape');
test('is array', function(t){
t.ok(isArray([]));
t.notOk(isArray({}));
t.notOk(isArray(null));
t.notOk(isArray(false));
var obj = {};
obj[0] = true;
t.notOk(isArray(obj));
var arr = [];
arr.foo = 'bar';
t.ok(isArray(arr));
t.end();
});

View File

@@ -0,0 +1,123 @@
v2.2.1:
date: 2016-03-23
changes:
- Make sure that v8 flags are passed properly through the `respawn` event
v2.1.0:
date: 2015-05-20
changes:
- Use rechoir to autoload modules.
v2.0.3:
date: 2015-03-31
changes:
- Internal bugfix, don't wrap callback error in another error, idiot.
v2.0.2:
date: 2015-02-24
changes:
- Support process.env.NODE_PATH when resolving module.
v2.0.1:
date: 2015-02-01
changes:
- Find modulePath correctly when devving against yourself.
v2.0.0:
date: 2015-01-15
changes:
- Rename `nodeFlags` to `v8Flags` and make it async.
v1.0.4:
date: 2015-01-04
changes:
- Detect config extension using basename, not full path.
v1.0.0:
date: 2014-12-16
changes:
- Update dependencies
v0.13.6:
date: 2014-11-07
changes:
- Don't include artwork on npm.
v0.13.5:
date: 2014-10-10
changes:
- Only attempt to resolve the real path of configFile if it is actually a symlink.
v0.13.4:
date: 2014-10-07
changes:
- Set configBase to the directory of the symlink, not the directory of its real location.
v0.13.3:
date: 2014-10-06
changes:
- Return the real location of symlinked config files.
v0.13.2:
date: 2014-09-12
changes:
- Include flags in respawn event. I really miss `npm publish --force`.
v0.13.1:
date: 2014-09-12
changes:
- Slight performance tweak.
v0.13.0:
date: 2014-09-12
changes:
- Support passing flags to node with `nodeFlags` option.
v0.12.1:
date: 2014-06-27
changes:
- Support preloading modules for compound extensions like `.coffee.md`.
v0.12.0:
date: 2014-06-27
changes:
- Respect order of extensions when searching for config.
- Rename `configNameRegex` environment property to `configNameSearch`.
v0.11.3:
date: 2014-06-09
changes:
- Make cwd match configBase if cwd isn't explictly provided
v0.11.2:
date: 2014-06-04
changes:
- Regression fix: coerce preloads into array before attempting to push more
v0.11.1:
date: 2014-06-02
changes:
- Update dependencies.
v0.11.0:
date: 2014-05-27
changes:
- Refactor and remove options parsing.
v0.10.0:
date: 2014-05-06
changes:
- Remove `addExtension` in favor of `extension` option.
- Support preloading modules based on extension.
v0.9.7:
date: 2014-04-28
changes:
- Locate local module in cwd even if config isn't present.
v0.9.6:
date: 2014-04-02
changes:
- Fix regression where external modules are not properly required.
- Ignore configPathFlag / cwdFlag if the value isn't a string
v0.9.3:
date: 2014-02-28
changes:
- Fix regression where developing against self doesn't correctly set cwd.
v0.9.0:
date: 2014-02-28
changes:
- Use liftoff instance as context (`this`) for launch callback.
- Support split --cwd and --configfile locations.
- Rename `configLocationFlag` to `configPathFlag`
- Support node 0.8+
v0.8.7:
date: 2014-02-24
changes:
- Pass environment as first argument to `launch`.
v0.8.5:
date: 2014-02-19
changes:
- Implement `addExtensions` option.
- Default to `index.js` if `modulePackage` has no `main` property.
v0.8.4:
date: 2014-02-05
changes:
- Initial public release.

View File

@@ -0,0 +1,22 @@
Copyright (c) 2014 Tyler Kellen
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,304 @@
<p align="center">
<a href="http://liftoffjs.com">
<img height="100" width="297" src="https://cdn.rawgit.com/tkellen/js-liftoff/master/artwork/liftoff.svg"/>
</a>
</p>
# liftoff [![Build Status](https://secure.travis-ci.org/js-cli/js-liftoff.svg)](http://travis-ci.org/js-cli/js-liftoff) [![Build status](https://ci.appveyor.com/api/projects/status/5a6w8xuq8ed1ilc4/branch/master?svg=true)](https://ci.appveyor.com/project/js-cli/js-liftoff/branch/master)
> Launch your command line tool with ease.
[![NPM](https://nodei.co/npm/liftoff.png)](https://nodei.co/npm/liftoff/)
## What is it?
[See this blog post](http://weblog.bocoup.com/building-command-line-tools-in-node-with-liftoff/), [check out this proof of concept](https://github.com/js-cli/js-hacker), or read on.
Say you're writing a CLI tool. Let's call it [hacker](https://github.com/js-cli/js-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`&mdash;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.
## API
### constructor(opts)
Create an instance of Liftoff to invoke your application.
An example utilizing all options:
```js
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')
});
```
#### opts.name
Sugar for setting `processTitle`, `moduleName`, `configName` automatically.
Type: `String`
Default: `null`
These are equivalent:
```js
const Hacker = Liftoff({
processTitle: 'hacker',
moduleName: 'hacker',
configName: 'hackerfile'
});
```
```js
const Hacker = Liftoff({name:'hacker'});
```
#### opts.moduleName
Sets which module your application expects to find locally when being run.
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.
```js
const MyApp = new Liftoff({
name: 'myapp',
extensions: {
'.js': null,
'.json': null,
'.coffee': 'coffee-script/register'
}
});
```
In this example, Liftoff will look for `.myapp{rc}`.
```js
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 [node-interpret](https://github.com/tkellen/node-interpret) (as long as it does not require a register method).
```js
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](http://github.com/tkellen/node-flagged-respawn). To support all v8flags, see [node-v8flags](https://github.com/tkellen/node-v8flags).
Type: `Array|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](http://nodejs.org/api/process.html#process_process_title) will be.
Type: `String`
Default: `null`
#### opts.completions(type)
A method to handle bash/zsh/whatever completions.
Type: `Function`
Default: `null`
## launch(opts, callback(env))
Launches your application with provided options, builds an environment, and invokes your callback, passing the calculated environment as the first argument.
##### Example Configuration w/ Options Parsing:
```js
const Liftoff = require('liftoff');
const MyApp = new Liftoff({name:'myapp'});
const argv = require('minimist')(process.argv.slice(2));
const invoke = function (env) {
console.log('my environment is:', env);
console.log('my cli options are:', argv);
console.log('my liftoff config is:', this);
};
MyApp.launch({
cwd: argv.cwd,
configPath: argv.myappfile,
require: argv.require,
completion: argv.completion
}, invoke);
```
#### opts.cwd
Change the current working directory for this launch. Relative paths are calculated against `process.cwd()`.
Type: `String`
Default: `process.cwd()`
**Example Configuration:**
```js
const argv = require('minimist')(process.argv.slice(2));
MyApp.launch({
cwd: argv.cwd
}, 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:**
```js
var argv = require('minimist')(process.argv.slice(2));
MyApp.launch({
configPath: argv.myappfile
}, 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.require
A string or array of modules to attempt requiring from the local working directory before invoking the launch callback.
Type: `String|Array`
Default: `null`
**Example Configuration:**
```js
var argv = require('minimist')(process.argv.slice(2));
MyApp.launch({
require: argv.require
}, invoke);
```
**Matching CLI Invocation:**
```js
myapp --require coffee-script/register
```
#### callback(env)
A function to start your application. When invoked, `this` will be your instance of Liftoff. The `env` param will contain the following keys:
- `cwd`: the current working directory
- `require`: 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)
### events
#### require(name, module)
Emitted when a module is pre-loaded.
```js
var Hacker = new Liftoff({name:'hacker'});
Hacker.on('require', function (name, module) {
console.log('Requiring external module: '+name+'...');
// automatically register coffee-script extensions
if (name === 'coffee-script') {
module.register();
}
});
```
#### requireFail(name, err)
Emitted when a requested module cannot be preloaded.
```js
var Hacker = new Liftoff({name:'hacker'});
Hacker.on('requireFail', function (name, err) {
console.log('Unable to load:', name, err);
});
```
#### respawn(flags, child)
Emitted when Liftoff re-spawns your process (when a [`nodeFlag`](#optsnodeflags) is detected).
```js
var Hacker = new Liftoff({
name: 'hacker',
nodeFlags: ['--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](https://github.com/gulpjs/gulp/blob/master/bin/gulp.js) uses Liftoff.
For a bare-bones example, try [the hacker project](https://github.com/js-cli/js-hacker/blob/master/bin/hacker.js).
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`.
3. Run `hacker` while in the same parent folder.

View File

@@ -0,0 +1,28 @@
# 1.0.0 -> 2.0.0
The option `nodeFlags` was renamed to `v8flags` for accuracy. It can now be a callback taking method that yields an array of flags, **or** an array literal.
# 0.11 -> 0.12
For the environment passed into the `launch` callback, `configNameRegex` has been renamed to `configNameSearch`. It now returns an array of valid config names instead of a regular expression.
# 0.10 -> 0.11
The method signature for `launch` was changed in this version of Liftoff.
You must now provide your own options parser and pass your desired params directly into `launch` as the first argument. The second argument is now the invocation callback that starts your application.
To replicate the default functionality of 0.10, use the following:
```js
const Liftoff = require('liftoff');
const MyApp = new Liftoff({name:'myapp'});
const argv = require('minimist')(process.argv.slice(2));
const invoke = function (env) {
console.log('my environment is:', env);
console.log('my cli options are:', argv);
console.log('my liftoff config is:', this);
};
MyApp.launch({
cwd: argv.cwd,
configPath: argv.myappfile,
require: argv.require,
completion: argv.completion
}, invoke);
```

View File

@@ -0,0 +1,26 @@
# http://www.appveyor.com/docs/appveyor-yml
# http://www.appveyor.com/docs/lang/nodejs-iojs
environment:
matrix:
# node.js
- nodejs_version: "0.10"
- nodejs_version: "0.12"
# io.js
- nodejs_version: "1"
install:
- ps: Install-Product node $env:nodejs_version
- npm install
test_script:
- node --version
- npm --version
# power shell
- ps: "npm test"
# standard command line
- cmd: npm test
build: off
version: "{build}"

View File

@@ -0,0 +1,205 @@
const fs = require('fs');
const util = require('util');
const path = require('path');
const EE = require('events').EventEmitter;
const extend = require('extend');
const resolve = require('resolve');
const flaggedRespawn = require('flagged-respawn');
const rechoir = require('rechoir');
const findCwd = require('./lib/find_cwd');
const findConfig = require('./lib/find_config');
const fileSearch = require('./lib/file_search');
const parseOptions = require('./lib/parse_options');
const silentRequire = require('./lib/silent_require');
const buildConfigName = require('./lib/build_config_name');
function Liftoff (opts) {
EE.call(this);
extend(this, parseOptions(opts));
}
util.inherits(Liftoff, EE);
Liftoff.prototype.requireLocal = function (module, basedir) {
try {
var result = require(resolve.sync(module, {basedir: basedir}));
this.emit('require', module, result);
return result;
} catch (e) {
this.emit('requireFail', module, e);
}
};
Liftoff.prototype.buildEnvironment = function (opts) {
opts = opts || {};
// get modules we want to preload
var preload = opts.require || [];
// ensure items to preload is an array
if (!Array.isArray(preload)) {
preload = [preload];
}
// make a copy of search paths that can be mutated for this run
var searchPaths = this.searchPaths.slice();
// calculate current cwd
var cwd = findCwd(opts);
// if cwd was provided explicitly, only use it for searching config
if (opts.cwd) {
searchPaths = [cwd];
} else {
// otherwise just search in cwd first
searchPaths.unshift(cwd);
}
// calculate the regex to use for finding the config file
var configNameSearch = buildConfigName({
configName: this.configName,
extensions: Object.keys(this.extensions)
});
// calculate configPath
var configPath = findConfig({
configNameSearch: configNameSearch,
searchPaths: searchPaths,
configPath: opts.configPath
});
// if we have a config path, save the directory it resides in.
var configBase;
if (configPath) {
configBase = path.dirname(configPath);
// if cwd wasn't provided explicitly, it should match configBase
if (!opts.cwd) {
cwd = configBase;
}
// resolve symlink if needed
if (fs.lstatSync(configPath).isSymbolicLink()) {
configPath = fs.realpathSync(configPath);
}
}
// TODO: break this out into lib/
// locate local module and package next to config or explicitly provided cwd
var modulePath, modulePackage;
try {
var delim = (process.platform === 'win32' ? ';' : ':'),
paths = (process.env.NODE_PATH ? process.env.NODE_PATH.split(delim) : []);
modulePath = resolve.sync(this.moduleName, {basedir: configBase || cwd, paths: paths});
modulePackage = silentRequire(fileSearch('package.json', [modulePath]));
} catch (e) {}
// if we have a configuration but we failed to find a local module, maybe
// we are developing against ourselves?
if (!modulePath && configPath) {
// check the package.json sibling to our config to see if its `name`
// matches the module we're looking for
var modulePackagePath = fileSearch('package.json', [configBase]);
modulePackage = silentRequire(modulePackagePath);
if (modulePackage && modulePackage.name === this.moduleName) {
// if it does, our module path is `main` inside package.json
modulePath = path.join(path.dirname(modulePackagePath), modulePackage.main || 'index.js');
cwd = configBase;
} else {
// clear if we just required a package for some other project
modulePackage = {};
}
}
// load any modules which were requested to be required
if (preload.length) {
// unique results first
preload.filter(function (value, index, self) {
return self.indexOf(value) === index;
}).forEach(function (dep) {
this.requireLocal(dep, findCwd(opts));
}, this);
}
// use rechoir to autoload any required modules
var autoloads;
if (configPath) {
autoloads = rechoir.prepare(this.extensions, configPath, cwd, true);
if (autoloads instanceof Error) {
autoloads = autoloads.failures;
}
if (Array.isArray(autoloads)) {
autoloads.forEach(function (attempt) {
if (attempt.error) {
this.emit('requireFail', attempt.moduleName, attempt.error);
} else {
this.emit('require', attempt.moduleName, attempt.module);
}
}, this);
}
}
return {
cwd: cwd,
require: preload,
configNameSearch: configNameSearch,
configPath: configPath,
configBase: configBase,
modulePath: modulePath,
modulePackage: modulePackage || {}
};
};
Liftoff.prototype.handleFlags = function (cb) {
if (typeof this.v8flags === 'function') {
this.v8flags(function (err, flags) {
if (err) {
cb(err);
} else {
cb(null, flags);
}
});
} else {
process.nextTick(function () {
cb(null, this.v8flags);
}.bind(this));
}
};
Liftoff.prototype.launch = function (opts, fn) {
if (typeof fn !== 'function') {
throw new Error('You must provide a callback function.');
}
process.title = this.processTitle;
var completion = opts.completion;
if (completion && this.completions) {
return this.completions(completion);
}
this.handleFlags(function (err, flags) {
if (err) {
throw err;
} else {
if (flags) {
flaggedRespawn(flags, process.argv, function (ready, child) {
if (child !== process) {
this.emit('respawn', process.argv.filter(function (arg) {
var flag = arg.split('=')[0];
return flags.indexOf(flag) !== -1;
}.bind(this)), child);
}
if (ready) {
fn.call(this, this.buildEnvironment(opts));
}
}.bind(this));
} else {
fn.call(this, this.buildEnvironment(opts));
}
}
}.bind(this));
};
module.exports = Liftoff;

View File

@@ -0,0 +1,104 @@
{
"_args": [
[
"liftoff@^2.1.0",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp"
]
],
"_from": "liftoff@>=2.1.0 <3.0.0",
"_id": "liftoff@2.2.1",
"_inCache": true,
"_installable": true,
"_location": "/gulp/liftoff",
"_nodeVersion": "5.9.0",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/liftoff-2.2.1.tgz_1458739983596_0.09431072394363582"
},
"_npmUser": {
"email": "b@pk.am",
"name": "tusbar"
},
"_npmVersion": "3.7.3",
"_phantomChildren": {},
"_requested": {
"name": "liftoff",
"raw": "liftoff@^2.1.0",
"rawSpec": "^2.1.0",
"scope": null,
"spec": ">=2.1.0 <3.0.0",
"type": "range"
},
"_requiredBy": [
"/gulp"
],
"_resolved": "https://registry.npmjs.org/liftoff/-/liftoff-2.2.1.tgz",
"_shasum": "8dfef848d3f441921c4a311fc3203ae9c34c41a7",
"_shrinkwrap": null,
"_spec": "liftoff@^2.1.0",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp",
"author": {
"name": "Tyler Kellen",
"url": "http://goingslowly.com/"
},
"bugs": {
"url": "https://github.com/js-cli/js-liftoff/issues"
},
"dependencies": {
"extend": "^2.0.1",
"findup-sync": "^0.3.0",
"flagged-respawn": "^0.3.2",
"rechoir": "^0.6.0",
"resolve": "^1.1.6"
},
"description": "Launch your command line tool with ease.",
"devDependencies": {
"chai": "^2.3.0",
"coffee-script": "^1.9.2",
"istanbul": "^0.3.14",
"jscs": "^1.13.1",
"jshint": "^2.7.0",
"mocha": "^2.1.0",
"sinon": "~1.12.2"
},
"directories": {},
"dist": {
"shasum": "8dfef848d3f441921c4a311fc3203ae9c34c41a7",
"tarball": "https://registry.npmjs.org/liftoff/-/liftoff-2.2.1.tgz"
},
"engines": {
"node": ">= 0.8"
},
"gitHead": "82a6911aff57aee0b1bf121015fcc492d1129238",
"homepage": "https://github.com/js-cli/js-liftoff",
"keywords": [
"command line"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"email": "blaine.bublitz@gmail.com",
"name": "phated"
},
{
"email": "tyler@sleekcode.net",
"name": "tkellen"
},
{
"email": "b@pk.am",
"name": "tusbar"
}
],
"name": "liftoff",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/js-cli/js-liftoff.git"
},
"scripts": {
"test": "jshint lib index.js && jscs lib index.js && mocha -t 5000 -b -R spec test/index"
},
"version": "2.2.1"
}

View File

@@ -0,0 +1,21 @@
Copyright 2010 James Halliday (mail@substack.net)
This project is free software released under the MIT/X11 license:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,33 @@
#!/usr/bin/env node
var mkdirp = require('../');
var minimist = require('minimist');
var fs = require('fs');
var argv = minimist(process.argv.slice(2), {
alias: { m: 'mode', h: 'help' },
string: [ 'mode' ]
});
if (argv.help) {
fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout);
return;
}
var paths = argv._.slice();
var mode = argv.mode ? parseInt(argv.mode, 8) : undefined;
(function next () {
if (paths.length === 0) return;
var p = paths.shift();
if (mode === undefined) mkdirp(p, cb)
else mkdirp(p, mode, cb)
function cb (err) {
if (err) {
console.error(err.message);
process.exit(1);
}
else next();
}
})();

View File

@@ -0,0 +1,12 @@
usage: mkdirp [DIR1,DIR2..] {OPTIONS}
Create each supplied directory including any necessary parent directories that
don't yet exist.
If the directory already exists, do nothing.
OPTIONS are:
-m, --mode If a directory needs to be created, set the mode as an octal
permission string.

View File

@@ -0,0 +1,6 @@
var mkdirp = require('mkdirp');
mkdirp('/tmp/foo/bar/baz', function (err) {
if (err) console.error(err)
else console.log('pow!')
});

View File

@@ -0,0 +1,98 @@
var path = require('path');
var fs = require('fs');
var _0777 = parseInt('0777', 8);
module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
function mkdirP (p, opts, f, made) {
if (typeof opts === 'function') {
f = opts;
opts = {};
}
else if (!opts || typeof opts !== 'object') {
opts = { mode: opts };
}
var mode = opts.mode;
var xfs = opts.fs || fs;
if (mode === undefined) {
mode = _0777 & (~process.umask());
}
if (!made) made = null;
var cb = f || function () {};
p = path.resolve(p);
xfs.mkdir(p, mode, function (er) {
if (!er) {
made = made || p;
return cb(null, made);
}
switch (er.code) {
case 'ENOENT':
mkdirP(path.dirname(p), opts, function (er, made) {
if (er) cb(er, made);
else mkdirP(p, opts, cb, made);
});
break;
// In the case of any other error, just see if there's a dir
// there already. If so, then hooray! If not, then something
// is borked.
default:
xfs.stat(p, function (er2, stat) {
// if the stat fails, then that's super weird.
// let the original error be the failure reason.
if (er2 || !stat.isDirectory()) cb(er, made)
else cb(null, made);
});
break;
}
});
}
mkdirP.sync = function sync (p, opts, made) {
if (!opts || typeof opts !== 'object') {
opts = { mode: opts };
}
var mode = opts.mode;
var xfs = opts.fs || fs;
if (mode === undefined) {
mode = _0777 & (~process.umask());
}
if (!made) made = null;
p = path.resolve(p);
try {
xfs.mkdirSync(p, mode);
made = made || p;
}
catch (err0) {
switch (err0.code) {
case 'ENOENT' :
made = sync(path.dirname(p), opts, made);
sync(p, opts, made);
break;
// In the case of any other error, just see if there's a dir
// there already. If so, then hooray! If not, then something
// is borked.
default:
var stat;
try {
stat = xfs.statSync(p);
}
catch (err1) {
throw err0;
}
if (!stat.isDirectory()) throw err0;
break;
}
}
return made;
};

View File

@@ -0,0 +1,18 @@
This software is released under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,2 @@
var argv = require('../')(process.argv.slice(2));
console.dir(argv);

View File

@@ -0,0 +1,187 @@
module.exports = function (args, opts) {
if (!opts) opts = {};
var flags = { bools : {}, strings : {} };
[].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
flags.bools[key] = true;
});
[].concat(opts.string).filter(Boolean).forEach(function (key) {
flags.strings[key] = true;
});
var aliases = {};
Object.keys(opts.alias || {}).forEach(function (key) {
aliases[key] = [].concat(opts.alias[key]);
aliases[key].forEach(function (x) {
aliases[x] = [key].concat(aliases[key].filter(function (y) {
return x !== y;
}));
});
});
var defaults = opts['default'] || {};
var argv = { _ : [] };
Object.keys(flags.bools).forEach(function (key) {
setArg(key, defaults[key] === undefined ? false : defaults[key]);
});
var notFlags = [];
if (args.indexOf('--') !== -1) {
notFlags = args.slice(args.indexOf('--')+1);
args = args.slice(0, args.indexOf('--'));
}
function setArg (key, val) {
var value = !flags.strings[key] && isNumber(val)
? Number(val) : val
;
setKey(argv, key.split('.'), value);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), value);
});
}
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (/^--.+=/.test(arg)) {
// Using [\s\S] instead of . because js doesn't support the
// 'dotall' regex modifier. See:
// http://stackoverflow.com/a/1068308/13216
var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
setArg(m[1], m[2]);
}
else if (/^--no-.+/.test(arg)) {
var key = arg.match(/^--no-(.+)/)[1];
setArg(key, false);
}
else if (/^--.+/.test(arg)) {
var key = arg.match(/^--(.+)/)[1];
var next = args[i + 1];
if (next !== undefined && !/^-/.test(next)
&& !flags.bools[key]
&& (aliases[key] ? !flags.bools[aliases[key]] : true)) {
setArg(key, next);
i++;
}
else if (/^(true|false)$/.test(next)) {
setArg(key, next === 'true');
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true);
}
}
else if (/^-[^-]+/.test(arg)) {
var letters = arg.slice(1,-1).split('');
var broken = false;
for (var j = 0; j < letters.length; j++) {
var next = arg.slice(j+2);
if (next === '-') {
setArg(letters[j], next)
continue;
}
if (/[A-Za-z]/.test(letters[j])
&& /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
setArg(letters[j], next);
broken = true;
break;
}
if (letters[j+1] && letters[j+1].match(/\W/)) {
setArg(letters[j], arg.slice(j+2));
broken = true;
break;
}
else {
setArg(letters[j], flags.strings[letters[j]] ? '' : true);
}
}
var key = arg.slice(-1)[0];
if (!broken && key !== '-') {
if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
&& !flags.bools[key]
&& (aliases[key] ? !flags.bools[aliases[key]] : true)) {
setArg(key, args[i+1]);
i++;
}
else if (args[i+1] && /true|false/.test(args[i+1])) {
setArg(key, args[i+1] === 'true');
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true);
}
}
}
else {
argv._.push(
flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
);
}
}
Object.keys(defaults).forEach(function (key) {
if (!hasKey(argv, key.split('.'))) {
setKey(argv, key.split('.'), defaults[key]);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), defaults[key]);
});
}
});
notFlags.forEach(function(key) {
argv._.push(key);
});
return argv;
};
function hasKey (obj, keys) {
var o = obj;
keys.slice(0,-1).forEach(function (key) {
o = (o[key] || {});
});
var key = keys[keys.length - 1];
return key in o;
}
function setKey (obj, keys, value) {
var o = obj;
keys.slice(0,-1).forEach(function (key) {
if (o[key] === undefined) o[key] = {};
o = o[key];
});
var key = keys[keys.length - 1];
if (o[key] === undefined || typeof o[key] === 'boolean') {
o[key] = value;
}
else if (Array.isArray(o[key])) {
o[key].push(value);
}
else {
o[key] = [ o[key], value ];
}
}
function isNumber (x) {
if (typeof x === 'number') return true;
if (/^0x[0-9a-f]+$/i.test(x)) return true;
return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}
function longest (xs) {
return Math.max.apply(null, xs.map(function (x) { return x.length }));
}

View File

@@ -0,0 +1,93 @@
{
"_args": [
[
"minimist@0.0.8",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/mkdirp"
]
],
"_from": "minimist@0.0.8",
"_id": "minimist@0.0.8",
"_inCache": true,
"_installable": true,
"_location": "/gulp/mkdirp/minimist",
"_npmUser": {
"email": "mail@substack.net",
"name": "substack"
},
"_npmVersion": "1.4.3",
"_phantomChildren": {},
"_requested": {
"name": "minimist",
"raw": "minimist@0.0.8",
"rawSpec": "0.0.8",
"scope": null,
"spec": "0.0.8",
"type": "version"
},
"_requiredBy": [
"/gulp/mkdirp"
],
"_resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz",
"_shasum": "857fcabfc3397d2625b8228262e86aa7a011b05d",
"_shrinkwrap": null,
"_spec": "minimist@0.0.8",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/mkdirp",
"author": {
"email": "mail@substack.net",
"name": "James Halliday",
"url": "http://substack.net"
},
"bugs": {
"url": "https://github.com/substack/minimist/issues"
},
"dependencies": {},
"description": "parse argument options",
"devDependencies": {
"tap": "~0.4.0",
"tape": "~1.0.4"
},
"directories": {},
"dist": {
"shasum": "857fcabfc3397d2625b8228262e86aa7a011b05d",
"tarball": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz"
},
"homepage": "https://github.com/substack/minimist",
"keywords": [
"argv",
"getopt",
"parser",
"optimist"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"email": "mail@substack.net",
"name": "substack"
}
],
"name": "minimist",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/substack/minimist.git"
},
"scripts": {
"test": "tap test/*.js"
},
"testling": {
"browsers": [
"ie/6..latest",
"ff/5",
"firefox/latest",
"chrome/10",
"chrome/latest",
"safari/5.1",
"safari/latest",
"opera/12"
],
"files": "test/*.js"
},
"version": "0.0.8"
}

View File

@@ -0,0 +1,73 @@
# minimist
parse argument options
This module is the guts of optimist's argument parser without all the
fanciful decoration.
[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist)
[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist)
# example
``` js
var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);
```
```
$ node example/parse.js -a beep -b boop
{ _: [], a: 'beep', b: 'boop' }
```
```
$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz
{ _: [ 'foo', 'bar', 'baz' ],
x: 3,
y: 4,
n: 5,
a: true,
b: true,
c: true,
beep: 'boop' }
```
# methods
``` js
var parseArgs = require('minimist')
```
## var argv = parseArgs(args, opts={})
Return an argument object `argv` populated with the array arguments from `args`.
`argv._` contains all the arguments that didn't have an option associated with
them.
Numeric-looking arguments will be returned as numbers unless `opts.string` or
`opts.boolean` is set for that argument name.
Any arguments after `'--'` will not be parsed and will end up in `argv._`.
options can be:
* `opts.string` - a string or array of strings argument names to always treat as
strings
* `opts.boolean` - a string or array of strings to always treat as booleans
* `opts.alias` - an object mapping string names to strings or arrays of string
argument names to use as aliases
* `opts.default` - an object mapping string argument names to default values
# install
With [npm](https://npmjs.org) do:
```
npm install minimist
```
# license
MIT

View File

@@ -0,0 +1,24 @@
var parse = require('../');
var test = require('tape');
test('-', function (t) {
t.plan(5);
t.deepEqual(parse([ '-n', '-' ]), { n: '-', _: [] });
t.deepEqual(parse([ '-' ]), { _: [ '-' ] });
t.deepEqual(parse([ '-f-' ]), { f: '-', _: [] });
t.deepEqual(
parse([ '-b', '-' ], { boolean: 'b' }),
{ b: true, _: [ '-' ] }
);
t.deepEqual(
parse([ '-s', '-' ], { string: 's' }),
{ s: '-', _: [] }
);
});
test('-a -- b', function (t) {
t.plan(3);
t.deepEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] });
t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] });
t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] });
});

View File

@@ -0,0 +1,20 @@
var test = require('tape');
var parse = require('../');
test('boolean default true', function (t) {
var argv = parse([], {
boolean: 'sometrue',
default: { sometrue: true }
});
t.equal(argv.sometrue, true);
t.end();
});
test('boolean default false', function (t) {
var argv = parse([], {
boolean: 'somefalse',
default: { somefalse: false }
});
t.equal(argv.somefalse, false);
t.end();
});

View File

@@ -0,0 +1,16 @@
var parse = require('../');
var test = require('tape');
test('dotted alias', function (t) {
var argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}});
t.equal(argv.a.b, 22);
t.equal(argv.aa.bb, 22);
t.end();
});
test('dotted default', function (t) {
var argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}});
t.equal(argv.a.b, 11);
t.equal(argv.aa.bb, 11);
t.end();
});

View File

@@ -0,0 +1,31 @@
var test = require('tape');
var parse = require('../');
test('long opts', function (t) {
t.deepEqual(
parse([ '--bool' ]),
{ bool : true, _ : [] },
'long boolean'
);
t.deepEqual(
parse([ '--pow', 'xixxle' ]),
{ pow : 'xixxle', _ : [] },
'long capture sp'
);
t.deepEqual(
parse([ '--pow=xixxle' ]),
{ pow : 'xixxle', _ : [] },
'long capture eq'
);
t.deepEqual(
parse([ '--host', 'localhost', '--port', '555' ]),
{ host : 'localhost', port : 555, _ : [] },
'long captures sp'
);
t.deepEqual(
parse([ '--host=localhost', '--port=555' ]),
{ host : 'localhost', port : 555, _ : [] },
'long captures eq'
);
t.end();
});

View File

@@ -0,0 +1,318 @@
var parse = require('../');
var test = require('tape');
test('parse args', function (t) {
t.deepEqual(
parse([ '--no-moo' ]),
{ moo : false, _ : [] },
'no'
);
t.deepEqual(
parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]),
{ v : ['a','b','c'], _ : [] },
'multi'
);
t.end();
});
test('comprehensive', function (t) {
t.deepEqual(
parse([
'--name=meowmers', 'bare', '-cats', 'woo',
'-h', 'awesome', '--multi=quux',
'--key', 'value',
'-b', '--bool', '--no-meep', '--multi=baz',
'--', '--not-a-flag', 'eek'
]),
{
c : true,
a : true,
t : true,
s : 'woo',
h : 'awesome',
b : true,
bool : true,
key : 'value',
multi : [ 'quux', 'baz' ],
meep : false,
name : 'meowmers',
_ : [ 'bare', '--not-a-flag', 'eek' ]
}
);
t.end();
});
test('nums', function (t) {
var argv = parse([
'-x', '1234',
'-y', '5.67',
'-z', '1e7',
'-w', '10f',
'--hex', '0xdeadbeef',
'789'
]);
t.deepEqual(argv, {
x : 1234,
y : 5.67,
z : 1e7,
w : '10f',
hex : 0xdeadbeef,
_ : [ 789 ]
});
t.deepEqual(typeof argv.x, 'number');
t.deepEqual(typeof argv.y, 'number');
t.deepEqual(typeof argv.z, 'number');
t.deepEqual(typeof argv.w, 'string');
t.deepEqual(typeof argv.hex, 'number');
t.deepEqual(typeof argv._[0], 'number');
t.end();
});
test('flag boolean', function (t) {
var argv = parse([ '-t', 'moo' ], { boolean: 't' });
t.deepEqual(argv, { t : true, _ : [ 'moo' ] });
t.deepEqual(typeof argv.t, 'boolean');
t.end();
});
test('flag boolean value', function (t) {
var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], {
boolean: [ 't', 'verbose' ],
default: { verbose: true }
});
t.deepEqual(argv, {
verbose: false,
t: true,
_: ['moo']
});
t.deepEqual(typeof argv.verbose, 'boolean');
t.deepEqual(typeof argv.t, 'boolean');
t.end();
});
test('flag boolean default false', function (t) {
var argv = parse(['moo'], {
boolean: ['t', 'verbose'],
default: { verbose: false, t: false }
});
t.deepEqual(argv, {
verbose: false,
t: false,
_: ['moo']
});
t.deepEqual(typeof argv.verbose, 'boolean');
t.deepEqual(typeof argv.t, 'boolean');
t.end();
});
test('boolean groups', function (t) {
var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], {
boolean: ['x','y','z']
});
t.deepEqual(argv, {
x : true,
y : false,
z : true,
_ : [ 'one', 'two', 'three' ]
});
t.deepEqual(typeof argv.x, 'boolean');
t.deepEqual(typeof argv.y, 'boolean');
t.deepEqual(typeof argv.z, 'boolean');
t.end();
});
test('newlines in params' , function (t) {
var args = parse([ '-s', "X\nX" ])
t.deepEqual(args, { _ : [], s : "X\nX" });
// reproduce in bash:
// VALUE="new
// line"
// node program.js --s="$VALUE"
args = parse([ "--s=X\nX" ])
t.deepEqual(args, { _ : [], s : "X\nX" });
t.end();
});
test('strings' , function (t) {
var s = parse([ '-s', '0001234' ], { string: 's' }).s;
t.equal(s, '0001234');
t.equal(typeof s, 'string');
var x = parse([ '-x', '56' ], { string: 'x' }).x;
t.equal(x, '56');
t.equal(typeof x, 'string');
t.end();
});
test('stringArgs', function (t) {
var s = parse([ ' ', ' ' ], { string: '_' })._;
t.same(s.length, 2);
t.same(typeof s[0], 'string');
t.same(s[0], ' ');
t.same(typeof s[1], 'string');
t.same(s[1], ' ');
t.end();
});
test('empty strings', function(t) {
var s = parse([ '-s' ], { string: 's' }).s;
t.equal(s, '');
t.equal(typeof s, 'string');
var str = parse([ '--str' ], { string: 'str' }).str;
t.equal(str, '');
t.equal(typeof str, 'string');
var letters = parse([ '-art' ], {
string: [ 'a', 't' ]
});
t.equal(letters.a, '');
t.equal(letters.r, true);
t.equal(letters.t, '');
t.end();
});
test('slashBreak', function (t) {
t.same(
parse([ '-I/foo/bar/baz' ]),
{ I : '/foo/bar/baz', _ : [] }
);
t.same(
parse([ '-xyz/foo/bar/baz' ]),
{ x : true, y : true, z : '/foo/bar/baz', _ : [] }
);
t.end();
});
test('alias', function (t) {
var argv = parse([ '-f', '11', '--zoom', '55' ], {
alias: { z: 'zoom' }
});
t.equal(argv.zoom, 55);
t.equal(argv.z, argv.zoom);
t.equal(argv.f, 11);
t.end();
});
test('multiAlias', function (t) {
var argv = parse([ '-f', '11', '--zoom', '55' ], {
alias: { z: [ 'zm', 'zoom' ] }
});
t.equal(argv.zoom, 55);
t.equal(argv.z, argv.zoom);
t.equal(argv.z, argv.zm);
t.equal(argv.f, 11);
t.end();
});
test('nested dotted objects', function (t) {
var argv = parse([
'--foo.bar', '3', '--foo.baz', '4',
'--foo.quux.quibble', '5', '--foo.quux.o_O',
'--beep.boop'
]);
t.same(argv.foo, {
bar : 3,
baz : 4,
quux : {
quibble : 5,
o_O : true
}
});
t.same(argv.beep, { boop : true });
t.end();
});
test('boolean and alias with chainable api', function (t) {
var aliased = [ '-h', 'derp' ];
var regular = [ '--herp', 'derp' ];
var opts = {
herp: { alias: 'h', boolean: true }
};
var aliasedArgv = parse(aliased, {
boolean: 'herp',
alias: { h: 'herp' }
});
var propertyArgv = parse(regular, {
boolean: 'herp',
alias: { h: 'herp' }
});
var expected = {
herp: true,
h: true,
'_': [ 'derp' ]
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
test('boolean and alias with options hash', function (t) {
var aliased = [ '-h', 'derp' ];
var regular = [ '--herp', 'derp' ];
var opts = {
alias: { 'h': 'herp' },
boolean: 'herp'
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
var expected = {
herp: true,
h: true,
'_': [ 'derp' ]
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
test('boolean and alias using explicit true', function (t) {
var aliased = [ '-h', 'true' ];
var regular = [ '--herp', 'true' ];
var opts = {
alias: { h: 'herp' },
boolean: 'h'
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
var expected = {
herp: true,
h: true,
'_': [ ]
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
// regression, see https://github.com/substack/node-optimist/issues/71
test('boolean and --x=true', function(t) {
var parsed = parse(['--boool', '--other=true'], {
boolean: 'boool'
});
t.same(parsed.boool, true);
t.same(parsed.other, 'true');
parsed = parse(['--boool', '--other=false'], {
boolean: 'boool'
});
t.same(parsed.boool, true);
t.same(parsed.other, 'false');
t.end();
});

View File

@@ -0,0 +1,9 @@
var parse = require('../');
var test = require('tape');
test('parse with modifier functions' , function (t) {
t.plan(1);
var argv = parse([ '-b', '123' ], { boolean: 'b' });
t.deepEqual(argv, { b: true, _: ['123'] });
});

View File

@@ -0,0 +1,67 @@
var parse = require('../');
var test = require('tape');
test('numeric short args', function (t) {
t.plan(2);
t.deepEqual(parse([ '-n123' ]), { n: 123, _: [] });
t.deepEqual(
parse([ '-123', '456' ]),
{ 1: true, 2: true, 3: 456, _: [] }
);
});
test('short', function (t) {
t.deepEqual(
parse([ '-b' ]),
{ b : true, _ : [] },
'short boolean'
);
t.deepEqual(
parse([ 'foo', 'bar', 'baz' ]),
{ _ : [ 'foo', 'bar', 'baz' ] },
'bare'
);
t.deepEqual(
parse([ '-cats' ]),
{ c : true, a : true, t : true, s : true, _ : [] },
'group'
);
t.deepEqual(
parse([ '-cats', 'meow' ]),
{ c : true, a : true, t : true, s : 'meow', _ : [] },
'short group next'
);
t.deepEqual(
parse([ '-h', 'localhost' ]),
{ h : 'localhost', _ : [] },
'short capture'
);
t.deepEqual(
parse([ '-h', 'localhost', '-p', '555' ]),
{ h : 'localhost', p : 555, _ : [] },
'short captures'
);
t.end();
});
test('mixed short bool and capture', function (t) {
t.same(
parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
{
f : true, p : 555, h : 'localhost',
_ : [ 'script.js' ]
}
);
t.end();
});
test('short and long', function (t) {
t.deepEqual(
parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
{
f : true, p : 555, h : 'localhost',
_ : [ 'script.js' ]
}
);
t.end();
});

View File

@@ -0,0 +1,8 @@
var parse = require('../');
var test = require('tape');
test('whitespace should be whitespace' , function (t) {
t.plan(1);
var x = parse([ '-x', '\t' ]).x;
t.equal(x, '\t');
});

View File

@@ -0,0 +1,85 @@
{
"_args": [
[
"mkdirp@^0.5.0",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/vinyl-fs"
]
],
"_from": "mkdirp@>=0.5.0 <0.6.0",
"_id": "mkdirp@0.5.1",
"_inCache": true,
"_installable": true,
"_location": "/gulp/mkdirp",
"_nodeVersion": "2.0.0",
"_npmUser": {
"email": "substack@gmail.com",
"name": "substack"
},
"_npmVersion": "2.9.0",
"_phantomChildren": {},
"_requested": {
"name": "mkdirp",
"raw": "mkdirp@^0.5.0",
"rawSpec": "^0.5.0",
"scope": null,
"spec": ">=0.5.0 <0.6.0",
"type": "range"
},
"_requiredBy": [
"/gulp/vinyl-fs"
],
"_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz",
"_shasum": "30057438eac6cf7f8c4767f38648d6697d75c903",
"_shrinkwrap": null,
"_spec": "mkdirp@^0.5.0",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/gulp/node_modules/vinyl-fs",
"author": {
"email": "mail@substack.net",
"name": "James Halliday",
"url": "http://substack.net"
},
"bin": {
"mkdirp": "bin/cmd.js"
},
"bugs": {
"url": "https://github.com/substack/node-mkdirp/issues"
},
"dependencies": {
"minimist": "0.0.8"
},
"description": "Recursively mkdir, like `mkdir -p`",
"devDependencies": {
"mock-fs": "2 >=2.7.0",
"tap": "1"
},
"directories": {},
"dist": {
"shasum": "30057438eac6cf7f8c4767f38648d6697d75c903",
"tarball": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz"
},
"gitHead": "d4eff0f06093aed4f387e88e9fc301cb76beedc7",
"homepage": "https://github.com/substack/node-mkdirp#readme",
"keywords": [
"mkdir",
"directory"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"email": "mail@substack.net",
"name": "substack"
}
],
"name": "mkdirp",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/substack/node-mkdirp.git"
},
"scripts": {
"test": "tap test/*.js"
},
"version": "0.5.1"
}

View File

@@ -0,0 +1,100 @@
# mkdirp
Like `mkdir -p`, but in node.js!
[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp)
# example
## pow.js
```js
var mkdirp = require('mkdirp');
mkdirp('/tmp/foo/bar/baz', function (err) {
if (err) console.error(err)
else console.log('pow!')
});
```
Output
```
pow!
```
And now /tmp/foo/bar/baz exists, huzzah!
# methods
```js
var mkdirp = require('mkdirp');
```
## mkdirp(dir, opts, cb)
Create a new directory and any necessary subdirectories at `dir` with octal
permission string `opts.mode`. If `opts` is a non-object, it will be treated as
the `opts.mode`.
If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`.
`cb(err, made)` fires with the error or the first directory `made`
that had to be created, if any.
You can optionally pass in an alternate `fs` implementation by passing in
`opts.fs`. Your implementation should have `opts.fs.mkdir(path, mode, cb)` and
`opts.fs.stat(path, cb)`.
## mkdirp.sync(dir, opts)
Synchronously create a new directory and any necessary subdirectories at `dir`
with octal permission string `opts.mode`. If `opts` is a non-object, it will be
treated as the `opts.mode`.
If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`.
Returns the first directory that had to be created, if any.
You can optionally pass in an alternate `fs` implementation by passing in
`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and
`opts.fs.statSync(path)`.
# usage
This package also ships with a `mkdirp` command.
```
usage: mkdirp [DIR1,DIR2..] {OPTIONS}
Create each supplied directory including any necessary parent directories that
don't yet exist.
If the directory already exists, do nothing.
OPTIONS are:
-m, --mode If a directory needs to be created, set the mode as an octal
permission string.
```
# install
With [npm](http://npmjs.org) do:
```
npm install mkdirp
```
to get the library, or
```
npm install -g mkdirp
```
to get the command.
# license
MIT

View File

@@ -0,0 +1,41 @@
var mkdirp = require('../').mkdirp;
var path = require('path');
var fs = require('fs');
var test = require('tap').test;
var _0777 = parseInt('0777', 8);
var _0755 = parseInt('0755', 8);
var _0744 = parseInt('0744', 8);
var ps = [ '', 'tmp' ];
for (var i = 0; i < 25; i++) {
var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
ps.push(dir);
}
var file = ps.join('/');
test('chmod-pre', function (t) {
var mode = _0744
mkdirp(file, mode, function (er) {
t.ifError(er, 'should not error');
fs.stat(file, function (er, stat) {
t.ifError(er, 'should exist');
t.ok(stat && stat.isDirectory(), 'should be directory');
t.equal(stat && stat.mode & _0777, mode, 'should be 0744');
t.end();
});
});
});
test('chmod', function (t) {
var mode = _0755
mkdirp(file, mode, function (er) {
t.ifError(er, 'should not error');
fs.stat(file, function (er, stat) {
t.ifError(er, 'should exist');
t.ok(stat && stat.isDirectory(), 'should be directory');
t.end();
});
});
});

View File

@@ -0,0 +1,38 @@
var mkdirp = require('../').mkdirp;
var path = require('path');
var fs = require('fs');
var test = require('tap').test;
var _0755 = parseInt('0755', 8);
var ps = [ '', 'tmp' ];
for (var i = 0; i < 25; i++) {
var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
ps.push(dir);
}
var file = ps.join('/');
// a file in the way
var itw = ps.slice(0, 3).join('/');
test('clobber-pre', function (t) {
console.error("about to write to "+itw)
fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.');
fs.stat(itw, function (er, stat) {
t.ifError(er)
t.ok(stat && stat.isFile(), 'should be file')
t.end()
})
})
test('clobber', function (t) {
t.plan(2);
mkdirp(file, _0755, function (err) {
t.ok(err);
t.equal(err.code, 'ENOTDIR');
t.end();
});
});

View File

@@ -0,0 +1,28 @@
var mkdirp = require('../');
var path = require('path');
var fs = require('fs');
var exists = fs.exists || path.exists;
var test = require('tap').test;
var _0777 = parseInt('0777', 8);
var _0755 = parseInt('0755', 8);
test('woo', function (t) {
t.plan(5);
var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var file = '/tmp/' + [x,y,z].join('/');
mkdirp(file, _0755, function (err) {
t.ifError(err);
exists(file, function (ex) {
t.ok(ex, 'file created');
fs.stat(file, function (err, stat) {
t.ifError(err);
t.equal(stat.mode & _0777, _0755);
t.ok(stat.isDirectory(), 'target not a directory');
})
})
});
});

View File

@@ -0,0 +1,29 @@
var mkdirp = require('../');
var path = require('path');
var test = require('tap').test;
var mockfs = require('mock-fs');
var _0777 = parseInt('0777', 8);
var _0755 = parseInt('0755', 8);
test('opts.fs', function (t) {
t.plan(5);
var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var file = '/beep/boop/' + [x,y,z].join('/');
var xfs = mockfs.fs();
mkdirp(file, { fs: xfs, mode: _0755 }, function (err) {
t.ifError(err);
xfs.exists(file, function (ex) {
t.ok(ex, 'created file');
xfs.stat(file, function (err, stat) {
t.ifError(err);
t.equal(stat.mode & _0777, _0755);
t.ok(stat.isDirectory(), 'target not a directory');
});
});
});
});

View File

@@ -0,0 +1,27 @@
var mkdirp = require('../');
var path = require('path');
var test = require('tap').test;
var mockfs = require('mock-fs');
var _0777 = parseInt('0777', 8);
var _0755 = parseInt('0755', 8);
test('opts.fs sync', function (t) {
t.plan(4);
var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var file = '/beep/boop/' + [x,y,z].join('/');
var xfs = mockfs.fs();
mkdirp.sync(file, { fs: xfs, mode: _0755 });
xfs.exists(file, function (ex) {
t.ok(ex, 'created file');
xfs.stat(file, function (err, stat) {
t.ifError(err);
t.equal(stat.mode & _0777, _0755);
t.ok(stat.isDirectory(), 'target not a directory');
});
});
});

Some files were not shown because too many files have changed in this diff Show More