chushihua
This commit is contained in:
+20
@@ -0,0 +1,20 @@
|
||||
Copyright JS Foundation and other contributors
|
||||
|
||||
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.
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
<div align="center">
|
||||
<a href="https://github.com/webpack/webpack">
|
||||
<img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg">
|
||||
</a>
|
||||
</div>
|
||||
|
||||
[![npm][npm]][npm-url]
|
||||
[![node][node]][node-url]
|
||||
[![deps][deps]][deps-url]
|
||||
[![tests][tests]][tests-url]
|
||||
[![coverage][cover]][cover-url]
|
||||
[![chat][chat]][chat-url]
|
||||
|
||||
# webpack-dev-server
|
||||
|
||||
Use [webpack](https://webpack.js.org) with a development server that provides
|
||||
live reloading. This should be used for **development only**.
|
||||
|
||||
It uses [webpack-dev-middleware][middleware-url] under the hood, which provides
|
||||
fast in-memory access to the webpack assets.
|
||||
|
||||
## Project in Maintenance
|
||||
|
||||
**Please note that `webpack-dev-server` is presently in a maintenance-only mode**
|
||||
and will not be accepting any additional features in the near term. Most new feature
|
||||
requests can be accomplished with Express middleware; please look into using
|
||||
the [`before`](https://webpack.js.org/configuration/dev-server/#devserver-before)
|
||||
and [`after`](https://webpack.js.org/configuration/dev-server/#devserver-after)
|
||||
hooks in the documentation.
|
||||
|
||||
## Getting Started
|
||||
|
||||
First thing's first, install the module:
|
||||
|
||||
```console
|
||||
npm install webpack-dev-server --save-dev
|
||||
```
|
||||
|
||||
_Note: While you can install and run webpack-dev-server globally, we recommend
|
||||
installing it locally. webpack-dev-server will always use a local installation
|
||||
over a global one._
|
||||
|
||||
## Usage
|
||||
|
||||
There are two main, recommended methods of using the module:
|
||||
|
||||
### With the CLI
|
||||
|
||||
The easiest way to use it is with the CLI. In the directory where your
|
||||
`webpack.config.js` is, run:
|
||||
|
||||
```console
|
||||
node_modules/.bin/webpack-dev-server
|
||||
```
|
||||
|
||||
### With NPM Scripts
|
||||
|
||||
NPM package.json scripts are a convenient and useful means to run locally installed
|
||||
binaries without having to be concerned about their full paths. Simply define a
|
||||
script as such:
|
||||
|
||||
```json
|
||||
"scripts": {
|
||||
"start:dev": "webpack-dev-server"
|
||||
}
|
||||
```
|
||||
|
||||
And run the following in your terminal/console:
|
||||
|
||||
```console
|
||||
npm run start:dev
|
||||
```
|
||||
|
||||
NPM will automagically reference the binary in `node_modules` for you, and
|
||||
execute the file or command.
|
||||
|
||||
### The Result
|
||||
|
||||
Either method will start a server instance and begin listening for connections
|
||||
from `localhost` on port `8080`.
|
||||
|
||||
webpack-dev-server is configured by default to support live-reload of files as
|
||||
you edit your assets while the server is running.
|
||||
|
||||
See [**the documentation**][docs-url] for more use cases and options.
|
||||
|
||||
## Browser Support
|
||||
|
||||
While `webpack-dev-server` transpiles the client (browser) scripts to an ES5
|
||||
state, the project only officially supports the _last two versions of major
|
||||
browsers_. We simply don't have the resources to support every whacky
|
||||
browser out there.
|
||||
|
||||
If you find an bug with an obscure / old browser, we would actively welcome a
|
||||
Pull Request to resolve the bug.
|
||||
|
||||
## Support
|
||||
|
||||
We do our best to keep Issues in the repository focused on bugs, features, and
|
||||
needed modifications to the code for the module. Because of that, we ask users
|
||||
with general support, "how-to", or "why isn't this working" questions to try one
|
||||
of the other support channels that are available.
|
||||
|
||||
Your first-stop-shop for support for webpack-dev-server should by the excellent
|
||||
[documentation][docs-url] for the module. If you see an opportunity for improvement
|
||||
of those docs, please head over to the [webpack.js.org repo][wjo-url] and open a
|
||||
pull request.
|
||||
|
||||
From there, we encourage users to visit the [webpack Gitter chat][chat-url] and
|
||||
talk to the fine folks there. If your quest for answers comes up dry in chat,
|
||||
head over to [StackOverflow][stack-url] and do a quick search or open a new
|
||||
question. Remember; It's always much easier to answer questions that include your
|
||||
`webpack.config.js` and relevant files!
|
||||
|
||||
If you're twitter-savvy you can tweet [#webpack][hash-url] with your question
|
||||
and someone should be able to reach out and lend a hand.
|
||||
|
||||
If you have discovered a :bug:, have a feature suggestion, of would like to see
|
||||
a modification, please feel free to create an issue on Github. _Note: The issue
|
||||
template isn't optional, so please be sure not to remove it, and please fill it
|
||||
out completely._
|
||||
|
||||
## Contributing
|
||||
|
||||
We welcome your contributions! Please have a read of [CONTRIBUTING.md](CONTRIBUTING.md) for more information on how to get involved.
|
||||
|
||||
## Maintainers
|
||||
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<img src="https://avatars.githubusercontent.com/SpaceK33z?v=4&s=150">
|
||||
<br />
|
||||
<a href="https://github.com/SpaceK33z">Kees Kluskens</a>
|
||||
</td>
|
||||
<td align="center">
|
||||
<img src="https://i.imgur.com/4v6pgxh.png">
|
||||
<br />
|
||||
<a href="https://github.com/shellscape">Andrew Powell</a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
## Attribution
|
||||
|
||||
This project is heavily inspired by [peerigon/nof5](https://github.com/peerigon/nof5).
|
||||
|
||||
## License
|
||||
|
||||
#### [MIT](./LICENSE)
|
||||
|
||||
|
||||
[npm]: https://img.shields.io/npm/v/webpack-dev-server.svg
|
||||
[npm-url]: https://npmjs.com/package/webpack-dev-server
|
||||
|
||||
[node]: https://img.shields.io/node/v/webpack-dev-server.svg
|
||||
[node-url]: https://nodejs.org
|
||||
|
||||
[deps]: https://david-dm.org/webpack/webpack-dev-server.svg
|
||||
[deps-url]: https://david-dm.org/webpack/webpack-dev-server
|
||||
|
||||
[tests]: http://img.shields.io/travis/webpack/webpack-dev-server.svg
|
||||
[tests-url]: https://travis-ci.org/webpack/webpack-dev-server
|
||||
|
||||
[cover]: https://codecov.io/gh/webpack/webpack-dev-server/branch/master/graph/badge.svg
|
||||
[cover-url]: https://codecov.io/gh/webpack/webpack-dev-server
|
||||
|
||||
[chat]: https://badges.gitter.im/webpack/webpack.svg
|
||||
[chat-url]: https://gitter.im/webpack/webpack
|
||||
|
||||
[docs-url]: https://webpack.js.org/configuration/dev-server/#devserver
|
||||
[hash-url]: https://twitter.com/search?q=webpack
|
||||
[middleware-url]: https://github.com/webpack/webpack-dev-middleware
|
||||
[stack-url]: https://stackoverflow.com/questions/tagged/webpack-dev-server
|
||||
[uglify-url]: https://github.com/webpack-contrib/uglifyjs-webpack-plugin
|
||||
[wjo-url]: https://github.com/webpack/webpack.js.org
|
||||
+495
@@ -0,0 +1,495 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
'use strict';
|
||||
|
||||
/* eslint global-require: off, import/order: off, no-console: off */
|
||||
require('../lib/polyfills');
|
||||
|
||||
const debug = require('debug')('webpack-dev-server');
|
||||
const fs = require('fs');
|
||||
const net = require('net');
|
||||
const path = require('path');
|
||||
const importLocal = require('import-local');
|
||||
const open = require('opn');
|
||||
const portfinder = require('portfinder');
|
||||
const addDevServerEntrypoints = require('../lib/util/addDevServerEntrypoints');
|
||||
const createDomain = require('../lib/util/createDomain'); // eslint-disable-line
|
||||
|
||||
// Prefer the local installation of webpack-dev-server
|
||||
if (importLocal(__filename)) {
|
||||
debug('Using local install of webpack-dev-server');
|
||||
return;
|
||||
}
|
||||
|
||||
const Server = require('../lib/Server');
|
||||
const webpack = require('webpack'); // eslint-disable-line
|
||||
|
||||
function versionInfo() {
|
||||
return `webpack-dev-server ${require('../package.json').version}\n` +
|
||||
`webpack ${require('webpack/package.json').version}`;
|
||||
}
|
||||
|
||||
function colorInfo(useColor, msg) {
|
||||
if (useColor) {
|
||||
// Make text blue and bold, so it *pops*
|
||||
return `\u001b[1m\u001b[34m${msg}\u001b[39m\u001b[22m`;
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
function colorError(useColor, msg) {
|
||||
if (useColor) {
|
||||
// Make text red and bold, so it *pops*
|
||||
return `\u001b[1m\u001b[31m${msg}\u001b[39m\u001b[22m`;
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line
|
||||
const defaultTo = (value, def) => value == null ? def : value;
|
||||
|
||||
const yargs = require('yargs')
|
||||
.usage(`${versionInfo()}\nUsage: https://webpack.js.org/configuration/dev-server/`);
|
||||
|
||||
require('webpack/bin/config-yargs')(yargs);
|
||||
|
||||
// It is important that this is done after the webpack yargs config,
|
||||
// so it overrides webpack's version info.
|
||||
yargs
|
||||
.version(versionInfo());
|
||||
|
||||
const ADVANCED_GROUP = 'Advanced options:';
|
||||
const DISPLAY_GROUP = 'Stats options:';
|
||||
const SSL_GROUP = 'SSL options:';
|
||||
const CONNECTION_GROUP = 'Connection options:';
|
||||
const RESPONSE_GROUP = 'Response options:';
|
||||
const BASIC_GROUP = 'Basic options:';
|
||||
|
||||
// Taken out of yargs because we must know if
|
||||
// it wasn't given by the user, in which case
|
||||
// we should use portfinder.
|
||||
const DEFAULT_PORT = 8080;
|
||||
|
||||
yargs.options({
|
||||
bonjour: {
|
||||
type: 'boolean',
|
||||
describe: 'Broadcasts the server via ZeroConf networking on start'
|
||||
},
|
||||
lazy: {
|
||||
type: 'boolean',
|
||||
describe: 'Lazy'
|
||||
},
|
||||
inline: {
|
||||
type: 'boolean',
|
||||
default: true,
|
||||
describe: 'Inline mode (set to false to disable including client scripts like livereload)'
|
||||
},
|
||||
progress: {
|
||||
type: 'boolean',
|
||||
describe: 'Print compilation progress in percentage',
|
||||
group: BASIC_GROUP
|
||||
},
|
||||
'hot-only': {
|
||||
type: 'boolean',
|
||||
describe: 'Do not refresh page if HMR fails',
|
||||
group: ADVANCED_GROUP
|
||||
},
|
||||
stdin: {
|
||||
type: 'boolean',
|
||||
describe: 'close when stdin ends'
|
||||
},
|
||||
open: {
|
||||
type: 'string',
|
||||
describe: 'Open the default browser, or optionally specify a browser name'
|
||||
},
|
||||
useLocalIp: {
|
||||
type: 'boolean',
|
||||
describe: 'Open default browser with local IP'
|
||||
},
|
||||
'open-page': {
|
||||
type: 'string',
|
||||
describe: 'Open default browser with the specified page',
|
||||
requiresArg: true
|
||||
},
|
||||
color: {
|
||||
type: 'boolean',
|
||||
alias: 'colors',
|
||||
default: function supportsColor() {
|
||||
return require('supports-color');
|
||||
},
|
||||
group: DISPLAY_GROUP,
|
||||
describe: 'Enables/Disables colors on the console'
|
||||
},
|
||||
info: {
|
||||
type: 'boolean',
|
||||
group: DISPLAY_GROUP,
|
||||
default: true,
|
||||
describe: 'Info'
|
||||
},
|
||||
quiet: {
|
||||
type: 'boolean',
|
||||
group: DISPLAY_GROUP,
|
||||
describe: 'Quiet'
|
||||
},
|
||||
'client-log-level': {
|
||||
type: 'string',
|
||||
group: DISPLAY_GROUP,
|
||||
default: 'info',
|
||||
describe: 'Log level in the browser (info, warning, error or none)'
|
||||
},
|
||||
https: {
|
||||
type: 'boolean',
|
||||
group: SSL_GROUP,
|
||||
describe: 'HTTPS'
|
||||
},
|
||||
key: {
|
||||
type: 'string',
|
||||
describe: 'Path to a SSL key.',
|
||||
group: SSL_GROUP
|
||||
},
|
||||
cert: {
|
||||
type: 'string',
|
||||
describe: 'Path to a SSL certificate.',
|
||||
group: SSL_GROUP
|
||||
},
|
||||
cacert: {
|
||||
type: 'string',
|
||||
describe: 'Path to a SSL CA certificate.',
|
||||
group: SSL_GROUP
|
||||
},
|
||||
pfx: {
|
||||
type: 'string',
|
||||
describe: 'Path to a SSL pfx file.',
|
||||
group: SSL_GROUP
|
||||
},
|
||||
'pfx-passphrase': {
|
||||
type: 'string',
|
||||
describe: 'Passphrase for pfx file.',
|
||||
group: SSL_GROUP
|
||||
},
|
||||
'content-base': {
|
||||
type: 'string',
|
||||
describe: 'A directory or URL to serve HTML content from.',
|
||||
group: RESPONSE_GROUP
|
||||
},
|
||||
'watch-content-base': {
|
||||
type: 'boolean',
|
||||
describe: 'Enable live-reloading of the content-base.',
|
||||
group: RESPONSE_GROUP
|
||||
},
|
||||
'history-api-fallback': {
|
||||
type: 'boolean',
|
||||
describe: 'Fallback to /index.html for Single Page Applications.',
|
||||
group: RESPONSE_GROUP
|
||||
},
|
||||
compress: {
|
||||
type: 'boolean',
|
||||
describe: 'Enable gzip compression',
|
||||
group: RESPONSE_GROUP
|
||||
},
|
||||
port: {
|
||||
describe: 'The port',
|
||||
group: CONNECTION_GROUP
|
||||
},
|
||||
'disable-host-check': {
|
||||
type: 'boolean',
|
||||
describe: 'Will not check the host',
|
||||
group: CONNECTION_GROUP
|
||||
},
|
||||
socket: {
|
||||
type: 'String',
|
||||
describe: 'Socket to listen',
|
||||
group: CONNECTION_GROUP
|
||||
},
|
||||
public: {
|
||||
type: 'string',
|
||||
describe: 'The public hostname/ip address of the server',
|
||||
group: CONNECTION_GROUP
|
||||
},
|
||||
host: {
|
||||
type: 'string',
|
||||
default: 'localhost',
|
||||
describe: 'The hostname/ip address the server will bind to',
|
||||
group: CONNECTION_GROUP
|
||||
},
|
||||
'allowed-hosts': {
|
||||
type: 'string',
|
||||
describe: 'A comma-delimited string of hosts that are allowed to access the dev server',
|
||||
group: CONNECTION_GROUP
|
||||
}
|
||||
});
|
||||
|
||||
const argv = yargs.argv;
|
||||
const wpOpt = require('webpack/bin/convert-argv')(yargs, argv, {
|
||||
outputFilename: '/bundle.js'
|
||||
});
|
||||
|
||||
function processOptions(webpackOptions) {
|
||||
// process Promise
|
||||
if (typeof webpackOptions.then === 'function') {
|
||||
webpackOptions.then(processOptions).catch((err) => {
|
||||
console.error(err.stack || err);
|
||||
process.exit(); // eslint-disable-line
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const firstWpOpt = Array.isArray(webpackOptions) ? webpackOptions[0] : webpackOptions;
|
||||
|
||||
const options = webpackOptions.devServer || firstWpOpt.devServer || {};
|
||||
|
||||
if (argv.bonjour) { options.bonjour = true; }
|
||||
|
||||
if (argv.host !== 'localhost' || !options.host) { options.host = argv.host; }
|
||||
|
||||
if (argv['allowed-hosts']) { options.allowedHosts = argv['allowed-hosts'].split(','); }
|
||||
|
||||
if (argv.public) { options.public = argv.public; }
|
||||
|
||||
if (argv.socket) { options.socket = argv.socket; }
|
||||
|
||||
if (argv.progress) { options.progress = argv.progress; }
|
||||
|
||||
if (!options.publicPath) {
|
||||
// eslint-disable-next-line
|
||||
options.publicPath = firstWpOpt.output && firstWpOpt.output.publicPath || '';
|
||||
if (!/^(https?:)?\/\//.test(options.publicPath) && options.publicPath[0] !== '/') {
|
||||
options.publicPath = `/${options.publicPath}`;
|
||||
}
|
||||
}
|
||||
|
||||
if (!options.filename) { options.filename = firstWpOpt.output && firstWpOpt.output.filename; }
|
||||
|
||||
if (!options.watchOptions) { options.watchOptions = firstWpOpt.watchOptions; }
|
||||
|
||||
if (argv.stdin) {
|
||||
process.stdin.on('end', () => {
|
||||
process.exit(0); // eslint-disable-line no-process-exit
|
||||
});
|
||||
process.stdin.resume();
|
||||
}
|
||||
|
||||
if (!options.hot) { options.hot = argv.hot; }
|
||||
|
||||
if (!options.hotOnly) { options.hotOnly = argv['hot-only']; }
|
||||
|
||||
if (!options.clientLogLevel) { options.clientLogLevel = argv['client-log-level']; }
|
||||
|
||||
// eslint-disable-next-line
|
||||
if (options.contentBase === undefined) {
|
||||
if (argv['content-base']) {
|
||||
options.contentBase = argv['content-base'];
|
||||
if (Array.isArray(options.contentBase)) {
|
||||
options.contentBase = options.contentBase.map(val => path.resolve(val));
|
||||
} else if (/^[0-9]$/.test(options.contentBase)) { options.contentBase = +options.contentBase; } else if (!/^(https?:)?\/\//.test(options.contentBase)) { options.contentBase = path.resolve(options.contentBase); }
|
||||
// It is possible to disable the contentBase by using `--no-content-base`, which results in arg["content-base"] = false
|
||||
} else if (argv['content-base'] === false) {
|
||||
options.contentBase = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (argv['watch-content-base']) { options.watchContentBase = true; }
|
||||
|
||||
if (!options.stats) {
|
||||
options.stats = {
|
||||
cached: false,
|
||||
cachedAssets: false
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof options.stats === 'object' && typeof options.stats.colors === 'undefined') {
|
||||
options.stats = Object.assign({}, options.stats, { colors: argv.color });
|
||||
}
|
||||
|
||||
if (argv.lazy) { options.lazy = true; }
|
||||
|
||||
if (!argv.info) { options.noInfo = true; }
|
||||
|
||||
if (argv.quiet) { options.quiet = true; }
|
||||
|
||||
if (argv.https) { options.https = true; }
|
||||
|
||||
if (argv.cert) { options.cert = fs.readFileSync(path.resolve(argv.cert)); }
|
||||
|
||||
if (argv.key) { options.key = fs.readFileSync(path.resolve(argv.key)); }
|
||||
|
||||
if (argv.cacert) { options.ca = fs.readFileSync(path.resolve(argv.cacert)); }
|
||||
|
||||
if (argv.pfx) { options.pfx = fs.readFileSync(path.resolve(argv.pfx)); }
|
||||
|
||||
if (argv['pfx-passphrase']) { options.pfxPassphrase = argv['pfx-passphrase']; }
|
||||
|
||||
if (argv.inline === false) { options.inline = false; }
|
||||
|
||||
if (argv['history-api-fallback']) { options.historyApiFallback = true; }
|
||||
|
||||
if (argv.compress) { options.compress = true; }
|
||||
|
||||
if (argv['disable-host-check']) { options.disableHostCheck = true; }
|
||||
|
||||
if (argv['open-page']) {
|
||||
options.open = true;
|
||||
options.openPage = argv['open-page'];
|
||||
}
|
||||
|
||||
if (typeof argv.open !== 'undefined') {
|
||||
options.open = argv.open !== '' ? argv.open : true;
|
||||
}
|
||||
|
||||
if (options.open && !options.openPage) { options.openPage = ''; }
|
||||
|
||||
if (argv.useLocalIp) { options.useLocalIp = true; }
|
||||
|
||||
// Kind of weird, but ensures prior behavior isn't broken in cases
|
||||
// that wouldn't throw errors. E.g. both argv.port and options.port
|
||||
// were specified, but since argv.port is 8080, options.port will be
|
||||
// tried first instead.
|
||||
options.port = argv.port === DEFAULT_PORT ? defaultTo(options.port, argv.port) : defaultTo(argv.port, options.port);
|
||||
|
||||
if (options.port != null) {
|
||||
startDevServer(webpackOptions, options);
|
||||
return;
|
||||
}
|
||||
|
||||
portfinder.basePort = DEFAULT_PORT;
|
||||
portfinder.getPort((err, port) => {
|
||||
if (err) throw err;
|
||||
options.port = port;
|
||||
startDevServer(webpackOptions, options);
|
||||
});
|
||||
}
|
||||
|
||||
function startDevServer(webpackOptions, options) {
|
||||
addDevServerEntrypoints(webpackOptions, options);
|
||||
|
||||
let compiler;
|
||||
try {
|
||||
compiler = webpack(webpackOptions);
|
||||
} catch (e) {
|
||||
if (e instanceof webpack.WebpackOptionsValidationError) {
|
||||
console.error(colorError(options.stats.colors, e.message));
|
||||
process.exit(1); // eslint-disable-line
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
if (options.progress) {
|
||||
compiler.apply(new webpack.ProgressPlugin({
|
||||
profile: argv.profile
|
||||
}));
|
||||
}
|
||||
|
||||
const suffix = (options.inline !== false || options.lazy === true ? '/' : '/webpack-dev-server/');
|
||||
|
||||
let server;
|
||||
try {
|
||||
server = new Server(compiler, options);
|
||||
} catch (e) {
|
||||
const OptionsValidationError = require('../lib/OptionsValidationError');
|
||||
if (e instanceof OptionsValidationError) {
|
||||
console.error(colorError(options.stats.colors, e.message));
|
||||
process.exit(1); // eslint-disable-line
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
['SIGINT', 'SIGTERM'].forEach((sig) => {
|
||||
process.on(sig, () => {
|
||||
server.close(() => {
|
||||
process.exit(); // eslint-disable-line no-process-exit
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
if (options.socket) {
|
||||
server.listeningApp.on('error', (e) => {
|
||||
if (e.code === 'EADDRINUSE') {
|
||||
const clientSocket = new net.Socket();
|
||||
clientSocket.on('error', (clientError) => {
|
||||
if (clientError.code === 'ECONNREFUSED') {
|
||||
// No other server listening on this socket so it can be safely removed
|
||||
fs.unlinkSync(options.socket);
|
||||
server.listen(options.socket, options.host, (err) => {
|
||||
if (err) throw err;
|
||||
});
|
||||
}
|
||||
});
|
||||
clientSocket.connect({ path: options.socket }, () => {
|
||||
throw new Error('This socket is already used');
|
||||
});
|
||||
}
|
||||
});
|
||||
server.listen(options.socket, options.host, (err) => {
|
||||
if (err) throw err;
|
||||
// chmod 666 (rw rw rw)
|
||||
const READ_WRITE = 438;
|
||||
fs.chmod(options.socket, READ_WRITE, (fsError) => {
|
||||
if (fsError) throw fsError;
|
||||
|
||||
const uri = createDomain(options, server.listeningApp) + suffix;
|
||||
reportReadiness(uri, options);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
server.listen(options.port, options.host, (err) => {
|
||||
if (err) throw err;
|
||||
if (options.bonjour) broadcastZeroconf(options);
|
||||
|
||||
const uri = createDomain(options, server.listeningApp) + suffix;
|
||||
reportReadiness(uri, options);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function reportReadiness(uri, options) {
|
||||
const useColor = argv.color;
|
||||
const contentBase = Array.isArray(options.contentBase) ? options.contentBase.join(', ') : options.contentBase;
|
||||
|
||||
if (!options.quiet) {
|
||||
let startSentence = `Project is running at ${colorInfo(useColor, uri)}`;
|
||||
if (options.socket) {
|
||||
startSentence = `Listening to socket at ${colorInfo(useColor, options.socket)}`;
|
||||
}
|
||||
|
||||
console.log((options.progress ? '\n' : '') + startSentence);
|
||||
|
||||
console.log(`webpack output is served from ${colorInfo(useColor, options.publicPath)}`);
|
||||
|
||||
if (contentBase) { console.log(`Content not from webpack is served from ${colorInfo(useColor, contentBase)}`); }
|
||||
|
||||
if (options.historyApiFallback) { console.log(`404s will fallback to ${colorInfo(useColor, options.historyApiFallback.index || '/index.html')}`); }
|
||||
|
||||
if (options.bonjour) { console.log('Broadcasting "http" with subtype of "webpack" via ZeroConf DNS (Bonjour)'); }
|
||||
}
|
||||
|
||||
if (options.open) {
|
||||
let openOptions = {};
|
||||
let openMessage = 'Unable to open browser';
|
||||
|
||||
if (typeof options.open === 'string') {
|
||||
openOptions = { app: options.open };
|
||||
openMessage += `: ${options.open}`;
|
||||
}
|
||||
|
||||
open(uri + (options.openPage || ''), openOptions).catch(() => {
|
||||
console.log(`${openMessage}. If you are running in a headless environment, please do not use the open flag.`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function broadcastZeroconf(options) {
|
||||
const bonjour = require('bonjour')();
|
||||
bonjour.publish({
|
||||
name: 'Webpack Dev Server',
|
||||
port: options.port,
|
||||
type: 'http',
|
||||
subtypes: ['webpack']
|
||||
});
|
||||
process.on('exit', () => {
|
||||
bonjour.unpublishAll(() => {
|
||||
bonjour.destroy();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
processOptions(wpOpt);
|
||||
+1
File diff suppressed because one or more lines are too long
+253
@@ -0,0 +1,253 @@
|
||||
'use strict';
|
||||
|
||||
/* global __resourceQuery WorkerGlobalScope self */
|
||||
/* eslint prefer-destructuring: off */
|
||||
|
||||
var url = require('url');
|
||||
var stripAnsi = require('strip-ansi');
|
||||
var log = require('loglevel').getLogger('webpack-dev-server');
|
||||
var socket = require('./socket');
|
||||
var overlay = require('./overlay');
|
||||
|
||||
function getCurrentScriptSource() {
|
||||
// `document.currentScript` is the most accurate way to find the current script,
|
||||
// but is not supported in all browsers.
|
||||
if (document.currentScript) {
|
||||
return document.currentScript.getAttribute('src');
|
||||
}
|
||||
// Fall back to getting all scripts in the document.
|
||||
var scriptElements = document.scripts || [];
|
||||
var currentScript = scriptElements[scriptElements.length - 1];
|
||||
if (currentScript) {
|
||||
return currentScript.getAttribute('src');
|
||||
}
|
||||
// Fail as there was no script to use.
|
||||
throw new Error('[WDS] Failed to get current script source.');
|
||||
}
|
||||
|
||||
var urlParts = void 0;
|
||||
var hotReload = true;
|
||||
if (typeof window !== 'undefined') {
|
||||
var qs = window.location.search.toLowerCase();
|
||||
hotReload = qs.indexOf('hotreload=false') === -1;
|
||||
}
|
||||
if (typeof __resourceQuery === 'string' && __resourceQuery) {
|
||||
// If this bundle is inlined, use the resource query to get the correct url.
|
||||
urlParts = url.parse(__resourceQuery.substr(1));
|
||||
} else {
|
||||
// Else, get the url from the <script> this file was called with.
|
||||
var scriptHost = getCurrentScriptSource();
|
||||
// eslint-disable-next-line no-useless-escape
|
||||
scriptHost = scriptHost.replace(/\/[^\/]+$/, '');
|
||||
urlParts = url.parse(scriptHost || '/', false, true);
|
||||
}
|
||||
|
||||
if (!urlParts.port || urlParts.port === '0') {
|
||||
urlParts.port = self.location.port;
|
||||
}
|
||||
|
||||
var _hot = false;
|
||||
var initial = true;
|
||||
var currentHash = '';
|
||||
var useWarningOverlay = false;
|
||||
var useErrorOverlay = false;
|
||||
var useProgress = false;
|
||||
|
||||
var INFO = 'info';
|
||||
var WARNING = 'warning';
|
||||
var ERROR = 'error';
|
||||
var NONE = 'none';
|
||||
|
||||
// Set the default log level
|
||||
log.setDefaultLevel(INFO);
|
||||
|
||||
// Send messages to the outside, so plugins can consume it.
|
||||
function sendMsg(type, data) {
|
||||
if (typeof self !== 'undefined' && (typeof WorkerGlobalScope === 'undefined' || !(self instanceof WorkerGlobalScope))) {
|
||||
self.postMessage({
|
||||
type: 'webpack' + type,
|
||||
data: data
|
||||
}, '*');
|
||||
}
|
||||
}
|
||||
|
||||
var onSocketMsg = {
|
||||
hot: function hot() {
|
||||
_hot = true;
|
||||
log.info('[WDS] Hot Module Replacement enabled.');
|
||||
},
|
||||
invalid: function invalid() {
|
||||
log.info('[WDS] App updated. Recompiling...');
|
||||
// fixes #1042. overlay doesn't clear if errors are fixed but warnings remain.
|
||||
if (useWarningOverlay || useErrorOverlay) overlay.clear();
|
||||
sendMsg('Invalid');
|
||||
},
|
||||
hash: function hash(_hash) {
|
||||
currentHash = _hash;
|
||||
},
|
||||
|
||||
'still-ok': function stillOk() {
|
||||
log.info('[WDS] Nothing changed.');
|
||||
if (useWarningOverlay || useErrorOverlay) overlay.clear();
|
||||
sendMsg('StillOk');
|
||||
},
|
||||
'log-level': function logLevel(level) {
|
||||
var hotCtx = require.context('webpack/hot', false, /^\.\/log$/);
|
||||
if (hotCtx.keys().indexOf('./log') !== -1) {
|
||||
hotCtx('./log').setLogLevel(level);
|
||||
}
|
||||
switch (level) {
|
||||
case INFO:
|
||||
case ERROR:
|
||||
log.setLevel(level);
|
||||
break;
|
||||
case WARNING:
|
||||
// loglevel's warning name is different from webpack's
|
||||
log.setLevel('warn');
|
||||
break;
|
||||
case NONE:
|
||||
log.disableAll();
|
||||
break;
|
||||
default:
|
||||
log.error('[WDS] Unknown clientLogLevel \'' + level + '\'');
|
||||
}
|
||||
},
|
||||
overlay: function overlay(value) {
|
||||
if (typeof document !== 'undefined') {
|
||||
if (typeof value === 'boolean') {
|
||||
useWarningOverlay = false;
|
||||
useErrorOverlay = value;
|
||||
} else if (value) {
|
||||
useWarningOverlay = value.warnings;
|
||||
useErrorOverlay = value.errors;
|
||||
}
|
||||
}
|
||||
},
|
||||
progress: function progress(_progress) {
|
||||
if (typeof document !== 'undefined') {
|
||||
useProgress = _progress;
|
||||
}
|
||||
},
|
||||
|
||||
'progress-update': function progressUpdate(data) {
|
||||
if (useProgress) log.info('[WDS] ' + data.percent + '% - ' + data.msg + '.');
|
||||
},
|
||||
ok: function ok() {
|
||||
sendMsg('Ok');
|
||||
if (useWarningOverlay || useErrorOverlay) overlay.clear();
|
||||
if (initial) return initial = false; // eslint-disable-line no-return-assign
|
||||
reloadApp();
|
||||
},
|
||||
|
||||
'content-changed': function contentChanged() {
|
||||
log.info('[WDS] Content base changed. Reloading...');
|
||||
self.location.reload();
|
||||
},
|
||||
warnings: function warnings(_warnings) {
|
||||
log.warn('[WDS] Warnings while compiling.');
|
||||
var strippedWarnings = _warnings.map(function (warning) {
|
||||
return stripAnsi(warning);
|
||||
});
|
||||
sendMsg('Warnings', strippedWarnings);
|
||||
for (var i = 0; i < strippedWarnings.length; i++) {
|
||||
log.warn(strippedWarnings[i]);
|
||||
}
|
||||
if (useWarningOverlay) overlay.showMessage(_warnings);
|
||||
|
||||
if (initial) return initial = false; // eslint-disable-line no-return-assign
|
||||
reloadApp();
|
||||
},
|
||||
errors: function errors(_errors) {
|
||||
log.error('[WDS] Errors while compiling. Reload prevented.');
|
||||
var strippedErrors = _errors.map(function (error) {
|
||||
return stripAnsi(error);
|
||||
});
|
||||
sendMsg('Errors', strippedErrors);
|
||||
for (var i = 0; i < strippedErrors.length; i++) {
|
||||
log.error(strippedErrors[i]);
|
||||
}
|
||||
if (useErrorOverlay) overlay.showMessage(_errors);
|
||||
initial = false;
|
||||
},
|
||||
error: function error(_error) {
|
||||
log.error(_error);
|
||||
},
|
||||
close: function close() {
|
||||
log.error('[WDS] Disconnected!');
|
||||
sendMsg('Close');
|
||||
}
|
||||
};
|
||||
|
||||
var hostname = urlParts.hostname;
|
||||
var protocol = urlParts.protocol;
|
||||
|
||||
// check ipv4 and ipv6 `all hostname`
|
||||
if (hostname === '0.0.0.0' || hostname === '::') {
|
||||
// why do we need this check?
|
||||
// hostname n/a for file protocol (example, when using electron, ionic)
|
||||
// see: https://github.com/webpack/webpack-dev-server/pull/384
|
||||
// eslint-disable-next-line no-bitwise
|
||||
if (self.location.hostname && !!~self.location.protocol.indexOf('http')) {
|
||||
hostname = self.location.hostname;
|
||||
}
|
||||
}
|
||||
|
||||
// `hostname` can be empty when the script path is relative. In that case, specifying
|
||||
// a protocol would result in an invalid URL.
|
||||
// When https is used in the app, secure websockets are always necessary
|
||||
// because the browser doesn't accept non-secure websockets.
|
||||
if (hostname && (self.location.protocol === 'https:' || urlParts.hostname === '0.0.0.0')) {
|
||||
protocol = self.location.protocol;
|
||||
}
|
||||
|
||||
var socketUrl = url.format({
|
||||
protocol: protocol,
|
||||
auth: urlParts.auth,
|
||||
hostname: hostname,
|
||||
port: urlParts.port,
|
||||
pathname: urlParts.path == null || urlParts.path === '/' ? '/sockjs-node' : urlParts.path
|
||||
});
|
||||
|
||||
socket(socketUrl, onSocketMsg);
|
||||
|
||||
var isUnloading = false;
|
||||
self.addEventListener('beforeunload', function () {
|
||||
isUnloading = true;
|
||||
});
|
||||
|
||||
function reloadApp() {
|
||||
if (isUnloading || !hotReload) {
|
||||
return;
|
||||
}
|
||||
if (_hot) {
|
||||
log.info('[WDS] App hot update...');
|
||||
// eslint-disable-next-line global-require
|
||||
var hotEmitter = require('webpack/hot/emitter');
|
||||
hotEmitter.emit('webpackHotUpdate', currentHash);
|
||||
if (typeof self !== 'undefined' && self.window) {
|
||||
// broadcast update to window
|
||||
self.postMessage('webpackHotUpdate' + currentHash, '*');
|
||||
}
|
||||
} else {
|
||||
var rootWindow = self;
|
||||
// use parent window for reload (in case we're in an iframe with no valid src)
|
||||
var intervalId = self.setInterval(function () {
|
||||
if (rootWindow.location.protocol !== 'about:') {
|
||||
// reload immediately if protocol is valid
|
||||
applyReload(rootWindow, intervalId);
|
||||
} else {
|
||||
rootWindow = rootWindow.parent;
|
||||
if (rootWindow.parent === rootWindow) {
|
||||
// if parent equals current window we've reached the root which would continue forever, so trigger a reload anyways
|
||||
applyReload(rootWindow, intervalId);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function applyReload(rootWindow, intervalId) {
|
||||
clearInterval(intervalId);
|
||||
log.info('[WDS] App updated. Reloading...');
|
||||
rootWindow.location.reload();
|
||||
}
|
||||
}
|
||||
+24
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
<!DOCTYPE html><html><head><meta http-equiv="X-UA-Compatible" content="IE=edge"/><meta charset="utf-8"/><meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"/><script type="text/javascript" charset="utf-8" src="/__webpack_dev_server__/live.bundle.js"></script></head><body></body></html>
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
'use strict';
|
||||
|
||||
// The error overlay is inspired (and mostly copied) from Create React App (https://github.com/facebookincubator/create-react-app)
|
||||
// They, in turn, got inspired by webpack-hot-middleware (https://github.com/glenjamin/webpack-hot-middleware).
|
||||
|
||||
var ansiHTML = require('ansi-html');
|
||||
var Entities = require('html-entities').AllHtmlEntities;
|
||||
|
||||
var entities = new Entities();
|
||||
|
||||
var colors = {
|
||||
reset: ['transparent', 'transparent'],
|
||||
black: '181818',
|
||||
red: 'E36049',
|
||||
green: 'B3CB74',
|
||||
yellow: 'FFD080',
|
||||
blue: '7CAFC2',
|
||||
magenta: '7FACCA',
|
||||
cyan: 'C3C2EF',
|
||||
lightgrey: 'EBE7E3',
|
||||
darkgrey: '6D7891'
|
||||
};
|
||||
ansiHTML.setColors(colors);
|
||||
|
||||
function createOverlayIframe(onIframeLoad) {
|
||||
var iframe = document.createElement('iframe');
|
||||
iframe.id = 'webpack-dev-server-client-overlay';
|
||||
iframe.src = 'about:blank';
|
||||
iframe.style.position = 'fixed';
|
||||
iframe.style.left = 0;
|
||||
iframe.style.top = 0;
|
||||
iframe.style.right = 0;
|
||||
iframe.style.bottom = 0;
|
||||
iframe.style.width = '100vw';
|
||||
iframe.style.height = '100vh';
|
||||
iframe.style.border = 'none';
|
||||
iframe.style.zIndex = 9999999999;
|
||||
iframe.onload = onIframeLoad;
|
||||
return iframe;
|
||||
}
|
||||
|
||||
function addOverlayDivTo(iframe) {
|
||||
var div = iframe.contentDocument.createElement('div');
|
||||
div.id = 'webpack-dev-server-client-overlay-div';
|
||||
div.style.position = 'fixed';
|
||||
div.style.boxSizing = 'border-box';
|
||||
div.style.left = 0;
|
||||
div.style.top = 0;
|
||||
div.style.right = 0;
|
||||
div.style.bottom = 0;
|
||||
div.style.width = '100vw';
|
||||
div.style.height = '100vh';
|
||||
div.style.backgroundColor = 'rgba(0, 0, 0, 0.85)';
|
||||
div.style.color = '#E8E8E8';
|
||||
div.style.fontFamily = 'Menlo, Consolas, monospace';
|
||||
div.style.fontSize = 'large';
|
||||
div.style.padding = '2rem';
|
||||
div.style.lineHeight = '1.2';
|
||||
div.style.whiteSpace = 'pre-wrap';
|
||||
div.style.overflow = 'auto';
|
||||
iframe.contentDocument.body.appendChild(div);
|
||||
return div;
|
||||
}
|
||||
|
||||
var overlayIframe = null;
|
||||
var overlayDiv = null;
|
||||
var lastOnOverlayDivReady = null;
|
||||
|
||||
function ensureOverlayDivExists(onOverlayDivReady) {
|
||||
if (overlayDiv) {
|
||||
// Everything is ready, call the callback right away.
|
||||
onOverlayDivReady(overlayDiv);
|
||||
return;
|
||||
}
|
||||
|
||||
// Creating an iframe may be asynchronous so we'll schedule the callback.
|
||||
// In case of multiple calls, last callback wins.
|
||||
lastOnOverlayDivReady = onOverlayDivReady;
|
||||
|
||||
if (overlayIframe) {
|
||||
// We're already creating it.
|
||||
return;
|
||||
}
|
||||
|
||||
// Create iframe and, when it is ready, a div inside it.
|
||||
overlayIframe = createOverlayIframe(function () {
|
||||
overlayDiv = addOverlayDivTo(overlayIframe);
|
||||
// Now we can talk!
|
||||
lastOnOverlayDivReady(overlayDiv);
|
||||
});
|
||||
|
||||
// Zalgo alert: onIframeLoad() will be called either synchronously
|
||||
// or asynchronously depending on the browser.
|
||||
// We delay adding it so `overlayIframe` is set when `onIframeLoad` fires.
|
||||
document.body.appendChild(overlayIframe);
|
||||
}
|
||||
|
||||
function showMessageOverlay(message) {
|
||||
ensureOverlayDivExists(function (div) {
|
||||
// Make it look similar to our terminal.
|
||||
div.innerHTML = '<span style="color: #' + colors.red + '">Failed to compile.</span><br><br>' + ansiHTML(entities.encode(message));
|
||||
});
|
||||
}
|
||||
|
||||
function destroyErrorOverlay() {
|
||||
if (!overlayDiv) {
|
||||
// It is not there in the first place.
|
||||
return;
|
||||
}
|
||||
|
||||
// Clean up and reset internal state.
|
||||
document.body.removeChild(overlayIframe);
|
||||
overlayDiv = null;
|
||||
overlayIframe = null;
|
||||
lastOnOverlayDivReady = null;
|
||||
}
|
||||
|
||||
// Successful compilation.
|
||||
exports.clear = function handleSuccess() {
|
||||
destroyErrorOverlay();
|
||||
};
|
||||
|
||||
// Compilation with errors (e.g. syntax error or missing modules).
|
||||
exports.showMessage = function handleMessage(messages) {
|
||||
showMessageOverlay(messages[0]);
|
||||
};
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
var SockJS = require('sockjs-client/dist/sockjs');
|
||||
|
||||
var retries = 0;
|
||||
var sock = null;
|
||||
|
||||
var socket = function initSocket(url, handlers) {
|
||||
sock = new SockJS(url);
|
||||
|
||||
sock.onopen = function onopen() {
|
||||
retries = 0;
|
||||
};
|
||||
|
||||
sock.onclose = function onclose() {
|
||||
if (retries === 0) {
|
||||
handlers.close();
|
||||
}
|
||||
|
||||
// Try to reconnect.
|
||||
sock = null;
|
||||
|
||||
// After 10 retries stop trying, to prevent logspam.
|
||||
if (retries <= 10) {
|
||||
// Exponentially increase timeout to reconnect.
|
||||
// Respectfully copied from the package `got`.
|
||||
// eslint-disable-next-line no-mixed-operators, no-restricted-properties
|
||||
var retryInMs = 1000 * Math.pow(2, retries) + Math.random() * 100;
|
||||
retries += 1;
|
||||
|
||||
setTimeout(function () {
|
||||
socket(url, handlers);
|
||||
}, retryInMs);
|
||||
}
|
||||
};
|
||||
|
||||
sock.onmessage = function onmessage(e) {
|
||||
// This assumes that all data sent via the websocket is JSON.
|
||||
var msg = JSON.parse(e.data);
|
||||
if (handlers[msg.type]) {
|
||||
handlers[msg.type](msg.data);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = socket;
|
||||
+1
File diff suppressed because one or more lines are too long
+14
@@ -0,0 +1,14 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
mode: 'production',
|
||||
module: {
|
||||
rules: [{
|
||||
test: /\.js$/,
|
||||
exclude: /node_modules|web_modules/,
|
||||
use: [{
|
||||
loader: 'babel-loader'
|
||||
}]
|
||||
}]
|
||||
}
|
||||
};
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
'use strict';
|
||||
|
||||
/* eslint no-param-reassign: 'off' */
|
||||
|
||||
const optionsSchema = require('./optionsSchema.json');
|
||||
|
||||
const indent = (str, prefix, firstLine) => {
|
||||
if (firstLine) {
|
||||
return prefix + str.replace(/\n(?!$)/g, `\n${prefix}`);
|
||||
}
|
||||
return str.replace(/\n(?!$)/g, `\n${prefix}`);
|
||||
};
|
||||
|
||||
const getSchemaPart = (path, parents, additionalPath) => {
|
||||
parents = parents || 0;
|
||||
path = path.split('/');
|
||||
path = path.slice(0, path.length - parents);
|
||||
if (additionalPath) {
|
||||
additionalPath = additionalPath.split('/');
|
||||
path = path.concat(additionalPath);
|
||||
}
|
||||
let schemaPart = optionsSchema;
|
||||
for (let i = 1; i < path.length; i++) {
|
||||
const inner = schemaPart[path[i]];
|
||||
if (inner) { schemaPart = inner; }
|
||||
}
|
||||
return schemaPart;
|
||||
};
|
||||
|
||||
const getSchemaPartText = (schemaPart, additionalPath) => {
|
||||
if (additionalPath) {
|
||||
for (let i = 0; i < additionalPath.length; i++) {
|
||||
const inner = schemaPart[additionalPath[i]];
|
||||
if (inner) { schemaPart = inner; }
|
||||
}
|
||||
}
|
||||
while (schemaPart.$ref) schemaPart = getSchemaPart(schemaPart.$ref);
|
||||
let schemaText = OptionsValidationError.formatSchema(schemaPart); // eslint-disable-line
|
||||
if (schemaPart.description) { schemaText += `\n${schemaPart.description}`; }
|
||||
return schemaText;
|
||||
};
|
||||
|
||||
class OptionsValidationError extends Error {
|
||||
constructor(validationErrors) {
|
||||
super();
|
||||
|
||||
if (Error.hasOwnProperty('captureStackTrace')) { // eslint-disable-line
|
||||
Error.captureStackTrace(this, this.constructor);
|
||||
}
|
||||
this.name = 'WebpackDevServerOptionsValidationError';
|
||||
|
||||
this.message = `${'Invalid configuration object. ' +
|
||||
'webpack-dev-server has been initialised using a configuration object that does not match the API schema.\n'}${
|
||||
validationErrors.map(err => ` - ${indent(OptionsValidationError.formatValidationError(err), ' ', false)}`).join('\n')}`;
|
||||
this.validationErrors = validationErrors;
|
||||
}
|
||||
|
||||
static formatSchema(schema, prevSchemas) {
|
||||
prevSchemas = prevSchemas || [];
|
||||
|
||||
const formatInnerSchema = (innerSchema, addSelf) => {
|
||||
if (!addSelf) return OptionsValidationError.formatSchema(innerSchema, prevSchemas);
|
||||
if (prevSchemas.indexOf(innerSchema) >= 0) return '(recursive)';
|
||||
return OptionsValidationError.formatSchema(innerSchema, prevSchemas.concat(schema));
|
||||
};
|
||||
|
||||
if (schema.type === 'string') {
|
||||
if (schema.minLength === 1) { return 'non-empty string'; } else if (schema.minLength > 1) { return `string (min length ${schema.minLength})`; }
|
||||
return 'string';
|
||||
} else if (schema.type === 'boolean') {
|
||||
return 'boolean';
|
||||
} else if (schema.type === 'number') {
|
||||
return 'number';
|
||||
} else if (schema.type === 'object') {
|
||||
if (schema.properties) {
|
||||
const required = schema.required || [];
|
||||
return `object { ${Object.keys(schema.properties).map((property) => {
|
||||
if (required.indexOf(property) < 0) return `${property}?`;
|
||||
return property;
|
||||
}).concat(schema.additionalProperties ? ['...'] : []).join(', ')} }`;
|
||||
}
|
||||
if (schema.additionalProperties) {
|
||||
return `object { <key>: ${formatInnerSchema(schema.additionalProperties)} }`;
|
||||
}
|
||||
return 'object';
|
||||
} else if (schema.type === 'array') {
|
||||
return `[${formatInnerSchema(schema.items)}]`;
|
||||
}
|
||||
|
||||
switch (schema.instanceof) {
|
||||
case 'Function':
|
||||
return 'function';
|
||||
case 'RegExp':
|
||||
return 'RegExp';
|
||||
default:
|
||||
}
|
||||
|
||||
if (schema.$ref) return formatInnerSchema(getSchemaPart(schema.$ref), true);
|
||||
if (schema.allOf) return schema.allOf.map(formatInnerSchema).join(' & ');
|
||||
if (schema.oneOf) return schema.oneOf.map(formatInnerSchema).join(' | ');
|
||||
if (schema.anyOf) return schema.anyOf.map(formatInnerSchema).join(' | ');
|
||||
if (schema.enum) return schema.enum.map(item => JSON.stringify(item)).join(' | ');
|
||||
return JSON.stringify(schema, 0, 2);
|
||||
}
|
||||
|
||||
static formatValidationError(err) {
|
||||
const dataPath = `configuration${err.dataPath}`;
|
||||
if (err.keyword === 'additionalProperties') {
|
||||
return `${dataPath} has an unknown property '${err.params.additionalProperty}'. These properties are valid:\n${getSchemaPartText(err.parentSchema)}`;
|
||||
} else if (err.keyword === 'oneOf' || err.keyword === 'anyOf') {
|
||||
if (err.children && err.children.length > 0) {
|
||||
return `${dataPath} should be one of these:\n${getSchemaPartText(err.parentSchema)}\n` +
|
||||
`Details:\n${err.children.map(e => ` * ${indent(OptionsValidationError.formatValidationError(e), ' ', false)}`).join('\n')}`;
|
||||
}
|
||||
return `${dataPath} should be one of these:\n${getSchemaPartText(err.parentSchema)}`;
|
||||
} else if (err.keyword === 'enum') {
|
||||
if (err.parentSchema && err.parentSchema.enum && err.parentSchema.enum.length === 1) {
|
||||
return `${dataPath} should be ${getSchemaPartText(err.parentSchema)}`;
|
||||
}
|
||||
return `${dataPath} should be one of these:\n${getSchemaPartText(err.parentSchema)}`;
|
||||
} else if (err.keyword === 'allOf') {
|
||||
return `${dataPath} should be:\n${getSchemaPartText(err.parentSchema)}`;
|
||||
} else if (err.keyword === 'type') {
|
||||
switch (err.params.type) {
|
||||
case 'object':
|
||||
return `${dataPath} should be an object.`;
|
||||
case 'string':
|
||||
return `${dataPath} should be a string.`;
|
||||
case 'boolean':
|
||||
return `${dataPath} should be a boolean.`;
|
||||
case 'number':
|
||||
return `${dataPath} should be a number.`;
|
||||
case 'array':
|
||||
return `${dataPath} should be an array:\n${getSchemaPartText(err.parentSchema)}`;
|
||||
default:
|
||||
}
|
||||
return `${dataPath} should be ${err.params.type}:\n${getSchemaPartText(err.parentSchema)}`;
|
||||
} else if (err.keyword === 'instanceof') {
|
||||
return `${dataPath} should be an instance of ${getSchemaPartText(err.parentSchema)}.`;
|
||||
} else if (err.keyword === 'required') {
|
||||
const missingProperty = err.params.missingProperty.replace(/^\./, '');
|
||||
return `${dataPath} misses the property '${missingProperty}'.\n${getSchemaPartText(err.parentSchema, ['properties', missingProperty])}`;
|
||||
} else if (err.keyword === 'minLength' || err.keyword === 'minItems') {
|
||||
if (err.params.limit === 1) { return `${dataPath} should not be empty.`; }
|
||||
return `${dataPath} ${err.message}`;
|
||||
}
|
||||
// eslint-disable-line no-fallthrough
|
||||
return `${dataPath} ${err.message} (${JSON.stringify(err, 0, 2)}).\n${getSchemaPartText(err.parentSchema)}`;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OptionsValidationError;
|
||||
+728
@@ -0,0 +1,728 @@
|
||||
'use strict';
|
||||
|
||||
/* eslint func-names: off */
|
||||
require('./polyfills');
|
||||
|
||||
const fs = require('fs');
|
||||
const http = require('http');
|
||||
const path = require('path');
|
||||
const url = require('url');
|
||||
const chokidar = require('chokidar');
|
||||
const compress = require('compression');
|
||||
const del = require('del');
|
||||
const express = require('express');
|
||||
const httpProxyMiddleware = require('http-proxy-middleware');
|
||||
const ip = require('ip');
|
||||
const killable = require('killable');
|
||||
const serveIndex = require('serve-index');
|
||||
const historyApiFallback = require('connect-history-api-fallback');
|
||||
const selfsigned = require('selfsigned');
|
||||
const sockjs = require('sockjs');
|
||||
const spdy = require('spdy');
|
||||
const webpack = require('webpack');
|
||||
const webpackDevMiddleware = require('webpack-dev-middleware');
|
||||
const OptionsValidationError = require('./OptionsValidationError');
|
||||
const optionsSchema = require('./optionsSchema.json');
|
||||
|
||||
// Workaround for sockjs@~0.3.19
|
||||
// sockjs will remove Origin header, however Origin header is required for checking host.
|
||||
// See https://github.com/webpack/webpack-dev-server/issues/1604 for more information
|
||||
{
|
||||
// eslint-disable-next-line global-require
|
||||
const SockjsSession = require('sockjs/lib/transport').Session;
|
||||
const decorateConnection = SockjsSession.prototype.decorateConnection;
|
||||
SockjsSession.prototype.decorateConnection = function (req) {
|
||||
decorateConnection.call(this, req);
|
||||
const connection = this.connection;
|
||||
if (connection.headers && !('origin' in connection.headers) && 'origin' in req.headers) {
|
||||
connection.headers.origin = req.headers.origin;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const clientStats = { errorDetails: false };
|
||||
const log = console.log; // eslint-disable-line no-console
|
||||
|
||||
function Server(compiler, options) {
|
||||
// Default options
|
||||
if (!options) options = {};
|
||||
|
||||
const validationErrors = webpack.validateSchema(optionsSchema, options);
|
||||
if (validationErrors.length) {
|
||||
throw new OptionsValidationError(validationErrors);
|
||||
}
|
||||
|
||||
if (options.lazy && !options.filename) {
|
||||
throw new Error("'filename' option must be set in lazy mode.");
|
||||
}
|
||||
|
||||
this.hot = options.hot || options.hotOnly;
|
||||
this.headers = options.headers;
|
||||
this.clientLogLevel = options.clientLogLevel;
|
||||
this.clientOverlay = options.overlay;
|
||||
this.progress = options.progress;
|
||||
this.disableHostCheck = !!options.disableHostCheck;
|
||||
this.publicHost = options.public;
|
||||
this.allowedHosts = options.allowedHosts;
|
||||
this.sockets = [];
|
||||
this.contentBaseWatchers = [];
|
||||
this.watchOptions = options.watchOptions || {};
|
||||
|
||||
// Listening for events
|
||||
const invalidPlugin = () => {
|
||||
this.sockWrite(this.sockets, 'invalid');
|
||||
};
|
||||
if (this.progress) {
|
||||
const progressPlugin = new webpack.ProgressPlugin((percent, msg, addInfo) => {
|
||||
percent = Math.floor(percent * 100);
|
||||
if (percent === 100) msg = 'Compilation completed';
|
||||
if (addInfo) msg = `${msg} (${addInfo})`;
|
||||
this.sockWrite(this.sockets, 'progress-update', { percent, msg });
|
||||
});
|
||||
compiler.apply(progressPlugin);
|
||||
}
|
||||
compiler.plugin('compile', invalidPlugin);
|
||||
compiler.plugin('invalid', invalidPlugin);
|
||||
compiler.plugin('done', (stats) => {
|
||||
this._sendStats(this.sockets, stats.toJson(clientStats));
|
||||
this._stats = stats;
|
||||
});
|
||||
|
||||
// Init express server
|
||||
const app = this.app = new express(); // eslint-disable-line
|
||||
|
||||
app.all('*', (req, res, next) => { // eslint-disable-line
|
||||
if (this.checkHost(req.headers)) { return next(); }
|
||||
res.send('Invalid Host header');
|
||||
});
|
||||
|
||||
const wdmOptions = {};
|
||||
|
||||
if (options.quiet === true) {
|
||||
wdmOptions.logLevel = 'silent';
|
||||
}
|
||||
if (options.noInfo === true) {
|
||||
wdmOptions.logLevel = 'warn';
|
||||
}
|
||||
// middleware for serving webpack bundle
|
||||
this.middleware = webpackDevMiddleware(compiler, Object.assign({}, options, wdmOptions));
|
||||
|
||||
app.get('/__webpack_dev_server__/live.bundle.js', (req, res) => {
|
||||
res.setHeader('Content-Type', 'application/javascript');
|
||||
fs.createReadStream(path.join(__dirname, '..', 'client', 'live.bundle.js')).pipe(res);
|
||||
});
|
||||
|
||||
app.get('/__webpack_dev_server__/sockjs.bundle.js', (req, res) => {
|
||||
res.setHeader('Content-Type', 'application/javascript');
|
||||
fs.createReadStream(path.join(__dirname, '..', 'client', 'sockjs.bundle.js')).pipe(res);
|
||||
});
|
||||
|
||||
app.get('/webpack-dev-server.js', (req, res) => {
|
||||
res.setHeader('Content-Type', 'application/javascript');
|
||||
fs.createReadStream(path.join(__dirname, '..', 'client', 'index.bundle.js')).pipe(res);
|
||||
});
|
||||
|
||||
app.get('/webpack-dev-server/*', (req, res) => {
|
||||
res.setHeader('Content-Type', 'text/html');
|
||||
fs.createReadStream(path.join(__dirname, '..', 'client', 'live.html')).pipe(res);
|
||||
});
|
||||
|
||||
app.get('/webpack-dev-server', (req, res) => {
|
||||
res.setHeader('Content-Type', 'text/html');
|
||||
res.write('<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body>');
|
||||
const outputPath = this.middleware.getFilenameFromUrl(options.publicPath || '/');
|
||||
const filesystem = this.middleware.fileSystem;
|
||||
|
||||
function writeDirectory(baseUrl, basePath) {
|
||||
const content = filesystem.readdirSync(basePath);
|
||||
res.write('<ul>');
|
||||
content.forEach((item) => {
|
||||
const p = `${basePath}/${item}`;
|
||||
if (filesystem.statSync(p).isFile()) {
|
||||
res.write('<li><a href="');
|
||||
res.write(baseUrl + item);
|
||||
res.write('">');
|
||||
res.write(item);
|
||||
res.write('</a></li>');
|
||||
if (/\.js$/.test(item)) {
|
||||
const htmlItem = item.substr(0, item.length - 3);
|
||||
res.write('<li><a href="');
|
||||
res.write(baseUrl + htmlItem);
|
||||
res.write('">');
|
||||
res.write(htmlItem);
|
||||
res.write('</a> (magic html for ');
|
||||
res.write(item);
|
||||
res.write(') (<a href="');
|
||||
res.write(baseUrl.replace(/(^(https?:\/\/[^\/]+)?\/)/, "$1webpack-dev-server/") + htmlItem); // eslint-disable-line
|
||||
res.write('">webpack-dev-server</a>)</li>');
|
||||
}
|
||||
} else {
|
||||
res.write('<li>');
|
||||
res.write(item);
|
||||
res.write('<br>');
|
||||
writeDirectory(`${baseUrl + item}/`, p);
|
||||
res.write('</li>');
|
||||
}
|
||||
});
|
||||
res.write('</ul>');
|
||||
}
|
||||
writeDirectory(options.publicPath || '/', outputPath);
|
||||
res.end('</body></html>');
|
||||
});
|
||||
|
||||
let contentBase;
|
||||
if (options.contentBase !== undefined) { // eslint-disable-line
|
||||
contentBase = options.contentBase; // eslint-disable-line
|
||||
} else {
|
||||
contentBase = process.cwd();
|
||||
}
|
||||
|
||||
// Keep track of websocket proxies for external websocket upgrade.
|
||||
const websocketProxies = [];
|
||||
|
||||
const features = {
|
||||
compress() {
|
||||
if (options.compress) {
|
||||
// Enable gzip compression.
|
||||
app.use(compress());
|
||||
}
|
||||
},
|
||||
|
||||
proxy() {
|
||||
if (options.proxy) {
|
||||
/**
|
||||
* Assume a proxy configuration specified as:
|
||||
* proxy: {
|
||||
* 'context': { options }
|
||||
* }
|
||||
* OR
|
||||
* proxy: {
|
||||
* 'context': 'target'
|
||||
* }
|
||||
*/
|
||||
if (!Array.isArray(options.proxy)) {
|
||||
options.proxy = Object.keys(options.proxy).map((context) => {
|
||||
let proxyOptions;
|
||||
// For backwards compatibility reasons.
|
||||
const correctedContext = context.replace(/^\*$/, '**').replace(/\/\*$/, '');
|
||||
|
||||
if (typeof options.proxy[context] === 'string') {
|
||||
proxyOptions = {
|
||||
context: correctedContext,
|
||||
target: options.proxy[context]
|
||||
};
|
||||
} else {
|
||||
proxyOptions = Object.assign({}, options.proxy[context]);
|
||||
proxyOptions.context = correctedContext;
|
||||
}
|
||||
proxyOptions.logLevel = proxyOptions.logLevel || 'warn';
|
||||
|
||||
return proxyOptions;
|
||||
});
|
||||
}
|
||||
|
||||
const getProxyMiddleware = (proxyConfig) => {
|
||||
const context = proxyConfig.context || proxyConfig.path;
|
||||
|
||||
// It is possible to use the `bypass` method without a `target`.
|
||||
// However, the proxy middleware has no use in this case, and will fail to instantiate.
|
||||
if (proxyConfig.target) {
|
||||
return httpProxyMiddleware(context, proxyConfig);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Assume a proxy configuration specified as:
|
||||
* proxy: [
|
||||
* {
|
||||
* context: ...,
|
||||
* ...options...
|
||||
* },
|
||||
* // or:
|
||||
* function() {
|
||||
* return {
|
||||
* context: ...,
|
||||
* ...options...
|
||||
* };
|
||||
* }
|
||||
* ]
|
||||
*/
|
||||
options.proxy.forEach((proxyConfigOrCallback) => {
|
||||
let proxyConfig;
|
||||
let proxyMiddleware;
|
||||
|
||||
if (typeof proxyConfigOrCallback === 'function') {
|
||||
proxyConfig = proxyConfigOrCallback();
|
||||
} else {
|
||||
proxyConfig = proxyConfigOrCallback;
|
||||
}
|
||||
|
||||
proxyMiddleware = getProxyMiddleware(proxyConfig);
|
||||
if (proxyConfig.ws) {
|
||||
websocketProxies.push(proxyMiddleware);
|
||||
}
|
||||
|
||||
app.use((req, res, next) => {
|
||||
if (typeof proxyConfigOrCallback === 'function') {
|
||||
const newProxyConfig = proxyConfigOrCallback();
|
||||
if (newProxyConfig !== proxyConfig) {
|
||||
proxyConfig = newProxyConfig;
|
||||
proxyMiddleware = getProxyMiddleware(proxyConfig);
|
||||
}
|
||||
}
|
||||
const bypass = typeof proxyConfig.bypass === 'function';
|
||||
// eslint-disable-next-line
|
||||
const bypassUrl = bypass && proxyConfig.bypass(req, res, proxyConfig) || false;
|
||||
|
||||
if (bypassUrl) {
|
||||
req.url = bypassUrl;
|
||||
next();
|
||||
} else if (proxyMiddleware) {
|
||||
return proxyMiddleware(req, res, next);
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
historyApiFallback() {
|
||||
if (options.historyApiFallback) {
|
||||
// Fall back to /index.html if nothing else matches.
|
||||
app.use(historyApiFallback(typeof options.historyApiFallback === 'object' ? options.historyApiFallback : null));
|
||||
}
|
||||
},
|
||||
|
||||
contentBaseFiles() {
|
||||
if (Array.isArray(contentBase)) {
|
||||
contentBase.forEach((item) => {
|
||||
app.get('*', express.static(item));
|
||||
});
|
||||
} else if (/^(https?:)?\/\//.test(contentBase)) {
|
||||
log('Using a URL as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.');
|
||||
log('proxy: {\n\t"*": "<your current contentBase configuration>"\n}'); // eslint-disable-line quotes
|
||||
// Redirect every request to contentBase
|
||||
app.get('*', (req, res) => {
|
||||
res.writeHead(302, {
|
||||
Location: contentBase + req.path + (req._parsedUrl.search || '')
|
||||
});
|
||||
res.end();
|
||||
});
|
||||
} else if (typeof contentBase === 'number') {
|
||||
log('Using a number as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.');
|
||||
log('proxy: {\n\t"*": "//localhost:<your current contentBase configuration>"\n}'); // eslint-disable-line quotes
|
||||
// Redirect every request to the port contentBase
|
||||
app.get('*', (req, res) => {
|
||||
res.writeHead(302, {
|
||||
Location: `//localhost:${contentBase}${req.path}${req._parsedUrl.search || ''}`
|
||||
});
|
||||
res.end();
|
||||
});
|
||||
} else {
|
||||
// route content request
|
||||
app.get('*', express.static(contentBase, options.staticOptions));
|
||||
}
|
||||
},
|
||||
|
||||
contentBaseIndex() {
|
||||
if (Array.isArray(contentBase)) {
|
||||
contentBase.forEach((item) => {
|
||||
app.get('*', serveIndex(item));
|
||||
});
|
||||
} else if (!/^(https?:)?\/\//.test(contentBase) && typeof contentBase !== 'number') {
|
||||
app.get('*', serveIndex(contentBase));
|
||||
}
|
||||
},
|
||||
|
||||
watchContentBase: () => {
|
||||
if (/^(https?:)?\/\//.test(contentBase) || typeof contentBase === 'number') {
|
||||
throw new Error('Watching remote files is not supported.');
|
||||
} else if (Array.isArray(contentBase)) {
|
||||
contentBase.forEach((item) => {
|
||||
this._watch(item);
|
||||
});
|
||||
} else {
|
||||
this._watch(contentBase);
|
||||
}
|
||||
},
|
||||
|
||||
before: () => {
|
||||
if (typeof options.before === 'function') {
|
||||
options.before(app, this);
|
||||
}
|
||||
},
|
||||
|
||||
middleware: () => {
|
||||
// include our middleware to ensure it is able to handle '/index.html' request after redirect
|
||||
app.use(this.middleware);
|
||||
},
|
||||
|
||||
after: () => {
|
||||
if (typeof options.after === 'function') { options.after(app, this); }
|
||||
},
|
||||
|
||||
headers: () => {
|
||||
app.all('*', this.setContentHeaders.bind(this));
|
||||
},
|
||||
|
||||
magicHtml: () => {
|
||||
app.get('*', this.serveMagicHtml.bind(this));
|
||||
},
|
||||
|
||||
setup: () => {
|
||||
if (typeof options.setup === 'function') {
|
||||
log('The `setup` option is deprecated and will be removed in v3. Please update your config to use `before`');
|
||||
options.setup(app, this);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const defaultFeatures = ['before', 'setup', 'headers', 'middleware'];
|
||||
if (options.proxy) { defaultFeatures.push('proxy', 'middleware'); }
|
||||
if (contentBase !== false) { defaultFeatures.push('contentBaseFiles'); }
|
||||
if (options.watchContentBase) { defaultFeatures.push('watchContentBase'); }
|
||||
if (options.historyApiFallback) {
|
||||
defaultFeatures.push('historyApiFallback', 'middleware');
|
||||
if (contentBase !== false) { defaultFeatures.push('contentBaseFiles'); }
|
||||
}
|
||||
defaultFeatures.push('magicHtml');
|
||||
if (contentBase !== false) { defaultFeatures.push('contentBaseIndex'); }
|
||||
// compress is placed last and uses unshift so that it will be the first middleware used
|
||||
if (options.compress) { defaultFeatures.unshift('compress'); }
|
||||
if (options.after) { defaultFeatures.push('after'); }
|
||||
|
||||
(options.features || defaultFeatures).forEach((feature) => {
|
||||
features[feature]();
|
||||
});
|
||||
|
||||
if (options.https) {
|
||||
// for keep supporting CLI parameters
|
||||
if (typeof options.https === 'boolean') {
|
||||
options.https = {
|
||||
key: options.key,
|
||||
cert: options.cert,
|
||||
ca: options.ca,
|
||||
pfx: options.pfx,
|
||||
passphrase: options.pfxPassphrase,
|
||||
requestCert: options.requestCert || false
|
||||
};
|
||||
}
|
||||
|
||||
let fakeCert;
|
||||
if (!options.https.key || !options.https.cert) {
|
||||
// Use a self-signed certificate if no certificate was configured.
|
||||
// Cycle certs every 24 hours
|
||||
const certPath = path.join(__dirname, '../ssl/server.pem');
|
||||
let certExists = fs.existsSync(certPath);
|
||||
|
||||
if (certExists) {
|
||||
const certStat = fs.statSync(certPath);
|
||||
const certTtl = 1000 * 60 * 60 * 24;
|
||||
const now = new Date();
|
||||
|
||||
// cert is more than 30 days old, kill it with fire
|
||||
if ((now - certStat.ctime) / certTtl > 30) {
|
||||
log('SSL Certificate is more than 30 days old. Removing.');
|
||||
del.sync([certPath], { force: true });
|
||||
certExists = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!certExists) {
|
||||
log('Generating SSL Certificate');
|
||||
const attrs = [{ name: 'commonName', value: 'localhost' }];
|
||||
const pems = selfsigned.generate(attrs, {
|
||||
algorithm: 'sha256',
|
||||
days: 30,
|
||||
keySize: 2048,
|
||||
extensions: [{
|
||||
name: 'basicConstraints',
|
||||
cA: true
|
||||
}, {
|
||||
name: 'keyUsage',
|
||||
keyCertSign: true,
|
||||
digitalSignature: true,
|
||||
nonRepudiation: true,
|
||||
keyEncipherment: true,
|
||||
dataEncipherment: true
|
||||
}, {
|
||||
name: 'subjectAltName',
|
||||
altNames: [
|
||||
{
|
||||
// type 2 is DNS
|
||||
type: 2,
|
||||
value: 'localhost'
|
||||
},
|
||||
{
|
||||
type: 2,
|
||||
value: 'localhost.localdomain'
|
||||
},
|
||||
{
|
||||
type: 2,
|
||||
value: 'lvh.me'
|
||||
},
|
||||
{
|
||||
type: 2,
|
||||
value: '*.lvh.me'
|
||||
},
|
||||
{
|
||||
type: 2,
|
||||
value: '[::1]'
|
||||
},
|
||||
{
|
||||
// type 7 is IP
|
||||
type: 7,
|
||||
ip: '127.0.0.1'
|
||||
},
|
||||
{
|
||||
type: 7,
|
||||
ip: 'fe80::1'
|
||||
}
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
fs.writeFileSync(certPath, pems.private + pems.cert, { encoding: 'utf-8' });
|
||||
}
|
||||
fakeCert = fs.readFileSync(certPath);
|
||||
}
|
||||
|
||||
options.https.key = options.https.key || fakeCert;
|
||||
options.https.cert = options.https.cert || fakeCert;
|
||||
|
||||
if (!options.https.spdy) {
|
||||
options.https.spdy = {
|
||||
protocols: ['h2', 'http/1.1']
|
||||
};
|
||||
}
|
||||
|
||||
this.listeningApp = spdy.createServer(options.https, app);
|
||||
} else {
|
||||
this.listeningApp = http.createServer(app);
|
||||
}
|
||||
|
||||
killable(this.listeningApp);
|
||||
|
||||
// Proxy websockets without the initial http request
|
||||
// https://github.com/chimurai/http-proxy-middleware#external-websocket-upgrade
|
||||
websocketProxies.forEach(function (wsProxy) {
|
||||
this.listeningApp.on('upgrade', wsProxy.upgrade);
|
||||
}, this);
|
||||
}
|
||||
|
||||
Server.prototype.use = function () {
|
||||
// eslint-disable-next-line
|
||||
this.app.use.apply(this.app, arguments);
|
||||
};
|
||||
|
||||
Server.prototype.setContentHeaders = function (req, res, next) {
|
||||
if (this.headers) {
|
||||
for (const name in this.headers) { // eslint-disable-line
|
||||
res.setHeader(name, this.headers[name]);
|
||||
}
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
|
||||
Server.prototype.checkHost = function (headers, headerToCheck) {
|
||||
// allow user to opt-out this security check, at own risk
|
||||
if (this.disableHostCheck) return true;
|
||||
|
||||
if (!headerToCheck) headerToCheck = 'host';
|
||||
// get the Host header and extract hostname
|
||||
// we don't care about port not matching
|
||||
const hostHeader = headers[headerToCheck];
|
||||
if (!hostHeader) return false;
|
||||
|
||||
// use the node url-parser to retrieve the hostname from the host-header.
|
||||
const hostname = url.parse(
|
||||
// if hostHeader doesn't have scheme, add // for parsing.
|
||||
/^(.+:)?\/\//.test(hostHeader) ? hostHeader : `//${hostHeader}`,
|
||||
false,
|
||||
true
|
||||
).hostname;
|
||||
|
||||
// always allow requests with explicit IPv4 or IPv6-address.
|
||||
// A note on IPv6 addresses: hostHeader will always contain the brackets denoting
|
||||
// an IPv6-address in URLs, these are removed from the hostname in url.parse(),
|
||||
// so we have the pure IPv6-address in hostname.
|
||||
if (ip.isV4Format(hostname) || ip.isV6Format(hostname)) return true;
|
||||
|
||||
// always allow localhost host, for convience
|
||||
if (hostname === 'localhost') return true;
|
||||
|
||||
// allow if hostname is in allowedHosts
|
||||
if (this.allowedHosts && this.allowedHosts.length) {
|
||||
for (let hostIdx = 0; hostIdx < this.allowedHosts.length; hostIdx++) {
|
||||
const allowedHost = this.allowedHosts[hostIdx];
|
||||
if (allowedHost === hostname) return true;
|
||||
|
||||
// support "." as a subdomain wildcard
|
||||
// e.g. ".example.com" will allow "example.com", "www.example.com", "subdomain.example.com", etc
|
||||
if (allowedHost[0] === '.') {
|
||||
// "example.com"
|
||||
if (hostname === allowedHost.substring(1)) return true;
|
||||
// "*.example.com"
|
||||
if (hostname.endsWith(allowedHost)) return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// allow hostname of listening adress
|
||||
if (hostname === this.listenHostname) return true;
|
||||
|
||||
// also allow public hostname if provided
|
||||
if (typeof this.publicHost === 'string') {
|
||||
const idxPublic = this.publicHost.indexOf(':');
|
||||
const publicHostname = idxPublic >= 0 ? this.publicHost.substr(0, idxPublic) : this.publicHost;
|
||||
if (hostname === publicHostname) return true;
|
||||
}
|
||||
|
||||
// disallow
|
||||
return false;
|
||||
};
|
||||
|
||||
// delegate listen call and init sockjs
|
||||
Server.prototype.listen = function (port, hostname, fn) {
|
||||
this.listenHostname = hostname;
|
||||
// eslint-disable-next-line
|
||||
|
||||
const returnValue = this.listeningApp.listen(port, hostname, (err) => {
|
||||
const sockServer = sockjs.createServer({
|
||||
// Use provided up-to-date sockjs-client
|
||||
sockjs_url: '/__webpack_dev_server__/sockjs.bundle.js',
|
||||
// Limit useless logs
|
||||
log(severity, line) {
|
||||
if (severity === 'error') {
|
||||
log(line);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
sockServer.on('connection', (conn) => {
|
||||
if (!conn) return;
|
||||
if (!this.checkHost(conn.headers) || !this.checkHost(conn.headers, 'origin')) {
|
||||
this.sockWrite([conn], 'error', 'Invalid Host/Origin header');
|
||||
conn.close();
|
||||
return;
|
||||
}
|
||||
this.sockets.push(conn);
|
||||
|
||||
conn.on('close', () => {
|
||||
const connIndex = this.sockets.indexOf(conn);
|
||||
if (connIndex >= 0) {
|
||||
this.sockets.splice(connIndex, 1);
|
||||
}
|
||||
});
|
||||
|
||||
if (this.clientLogLevel) { this.sockWrite([conn], 'log-level', this.clientLogLevel); }
|
||||
|
||||
if (this.progress) { this.sockWrite([conn], 'progress', this.progress); }
|
||||
|
||||
if (this.clientOverlay) { this.sockWrite([conn], 'overlay', this.clientOverlay); }
|
||||
|
||||
if (this.hot) this.sockWrite([conn], 'hot');
|
||||
|
||||
if (!this._stats) return;
|
||||
this._sendStats([conn], this._stats.toJson(clientStats), true);
|
||||
});
|
||||
|
||||
sockServer.installHandlers(this.listeningApp, {
|
||||
prefix: '/sockjs-node'
|
||||
});
|
||||
|
||||
if (fn) {
|
||||
fn.call(this.listeningApp, err);
|
||||
}
|
||||
});
|
||||
|
||||
return returnValue;
|
||||
};
|
||||
|
||||
Server.prototype.close = function (callback) {
|
||||
this.sockets.forEach((sock) => {
|
||||
sock.close();
|
||||
});
|
||||
this.sockets = [];
|
||||
|
||||
this.contentBaseWatchers.forEach((watcher) => {
|
||||
watcher.close();
|
||||
});
|
||||
this.contentBaseWatchers = [];
|
||||
|
||||
this.listeningApp.kill(() => {
|
||||
this.middleware.close(callback);
|
||||
});
|
||||
};
|
||||
|
||||
Server.prototype.sockWrite = function (sockets, type, data) {
|
||||
sockets.forEach((sock) => {
|
||||
sock.write(JSON.stringify({
|
||||
type,
|
||||
data
|
||||
}));
|
||||
});
|
||||
};
|
||||
|
||||
Server.prototype.serveMagicHtml = function (req, res, next) {
|
||||
const _path = req.path;
|
||||
try {
|
||||
if (!this.middleware.fileSystem.statSync(this.middleware.getFilenameFromUrl(`${_path}.js`)).isFile()) { return next(); }
|
||||
// Serve a page that executes the javascript
|
||||
res.write('<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body><script type="text/javascript" charset="utf-8" src="');
|
||||
res.write(_path);
|
||||
res.write('.js');
|
||||
res.write(req._parsedUrl.search || '');
|
||||
res.end('"></script></body></html>');
|
||||
} catch (e) {
|
||||
return next();
|
||||
}
|
||||
};
|
||||
|
||||
// send stats to a socket or multiple sockets
|
||||
Server.prototype._sendStats = function (sockets, stats, force) {
|
||||
if (!force &&
|
||||
stats &&
|
||||
(!stats.errors || stats.errors.length === 0) &&
|
||||
stats.assets &&
|
||||
stats.assets.every(asset => !asset.emitted)
|
||||
) { return this.sockWrite(sockets, 'still-ok'); }
|
||||
this.sockWrite(sockets, 'hash', stats.hash);
|
||||
if (stats.errors.length > 0) { this.sockWrite(sockets, 'errors', stats.errors); } else if (stats.warnings.length > 0) { this.sockWrite(sockets, 'warnings', stats.warnings); } else { this.sockWrite(sockets, 'ok'); }
|
||||
};
|
||||
|
||||
Server.prototype._watch = function (watchPath) {
|
||||
// duplicate the same massaging of options that watchpack performs
|
||||
// https://github.com/webpack/watchpack/blob/master/lib/DirectoryWatcher.js#L49
|
||||
// this isn't an elegant solution, but we'll improve it in the future
|
||||
const usePolling = this.watchOptions.poll ? true : undefined; // eslint-disable-line no-undefined
|
||||
const interval = typeof this.watchOptions.poll === 'number' ? this.watchOptions.poll : undefined; // eslint-disable-line no-undefined
|
||||
const options = {
|
||||
ignoreInitial: true,
|
||||
persistent: true,
|
||||
followSymlinks: false,
|
||||
depth: 0,
|
||||
atomic: false,
|
||||
alwaysStat: true,
|
||||
ignorePermissionErrors: true,
|
||||
ignored: this.watchOptions.ignored,
|
||||
usePolling,
|
||||
interval
|
||||
};
|
||||
const watcher = chokidar.watch(watchPath, options).on('change', () => {
|
||||
this.sockWrite(this.sockets, 'content-changed');
|
||||
});
|
||||
|
||||
this.contentBaseWatchers.push(watcher);
|
||||
};
|
||||
|
||||
Server.prototype.invalidate = function () {
|
||||
if (this.middleware) this.middleware.invalidate();
|
||||
};
|
||||
|
||||
// Export this logic, so that other implementations, like task-runners can use it
|
||||
Server.addDevServerEntrypoints = require('./util/addDevServerEntrypoints');
|
||||
|
||||
module.exports = Server;
|
||||
+336
@@ -0,0 +1,336 @@
|
||||
{
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"hot": {
|
||||
"description": "Enables Hot Module Replacement.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"hotOnly": {
|
||||
"description": "Enables Hot Module Replacement without page refresh as fallback.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"lazy": {
|
||||
"description": "Disables watch mode and recompiles bundle only on a request.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"bonjour": {
|
||||
"description": "Publishes the ZeroConf DNS service",
|
||||
"type": "boolean"
|
||||
},
|
||||
"host": {
|
||||
"description": "The host the server listens to.",
|
||||
"type": "string"
|
||||
},
|
||||
"allowedHosts": {
|
||||
"description": "Specifies which hosts are allowed to access the dev server.",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"filename": {
|
||||
"description": "The filename that needs to be requested in order to trigger a recompile (only in lazy mode).",
|
||||
"anyOf": [
|
||||
{
|
||||
"instanceof": "RegExp"
|
||||
},
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
"publicPath": {
|
||||
"description": "URL path where the webpack files are served from.",
|
||||
"type": "string"
|
||||
},
|
||||
"port": {
|
||||
"description": "The port the server listens to.",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
"socket": {
|
||||
"description": "The Unix socket to listen to (instead of on a host).",
|
||||
"type": "string"
|
||||
},
|
||||
"watchOptions": {
|
||||
"description": "Options for changing the watch behavior.",
|
||||
"type": "object"
|
||||
},
|
||||
"headers": {
|
||||
"description": "Response headers that are added to each response.",
|
||||
"type": "object"
|
||||
},
|
||||
"clientLogLevel": {
|
||||
"description": "Controls the log messages shown in the browser.",
|
||||
"enum": [
|
||||
"none",
|
||||
"info",
|
||||
"warning",
|
||||
"error"
|
||||
]
|
||||
},
|
||||
"overlay": {
|
||||
"description": "Shows an error overlay in browser.",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"errors": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"warnings": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"progress": {
|
||||
"description": "Shows compilation progress in browser console.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"key": {
|
||||
"description": "The contents of a SSL key.",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"instanceof": "Buffer"
|
||||
}
|
||||
]
|
||||
},
|
||||
"cert": {
|
||||
"description": "The contents of a SSL certificate.",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"instanceof": "Buffer"
|
||||
}
|
||||
]
|
||||
},
|
||||
"ca": {
|
||||
"description": "The contents of a SSL CA certificate.",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"instanceof": "Buffer"
|
||||
}
|
||||
]
|
||||
},
|
||||
"pfx": {
|
||||
"description": "The contents of a SSL pfx file.",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"instanceof": "Buffer"
|
||||
}
|
||||
]
|
||||
},
|
||||
"pfxPassphrase": {
|
||||
"description": "The passphrase to a (SSL) PFX file.",
|
||||
"type": "string"
|
||||
},
|
||||
"requestCert": {
|
||||
"description": "Enables request for client certificate. This is passed directly to the https server.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"inline": {
|
||||
"description": "Enable inline mode to include client scripts in bundle (CLI-only).",
|
||||
"type": "boolean"
|
||||
},
|
||||
"disableHostCheck": {
|
||||
"description": "Disable the Host header check (Security).",
|
||||
"type": "boolean"
|
||||
},
|
||||
"public": {
|
||||
"description": "The public hostname/ip address of the server.",
|
||||
"type": "string"
|
||||
},
|
||||
"https": {
|
||||
"description": "Enable HTTPS for server.",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"type": "boolean"
|
||||
}
|
||||
]
|
||||
},
|
||||
"contentBase": {
|
||||
"description": "A directory to serve files non-webpack files from.",
|
||||
"anyOf": [
|
||||
{
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"minItems": 1,
|
||||
"type": "array"
|
||||
},
|
||||
{
|
||||
"enum": [
|
||||
false
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
"watchContentBase": {
|
||||
"description": "Watches the contentBase directory for changes.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"open": {
|
||||
"description": "Let the CLI open your browser with the URL.",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "boolean"
|
||||
}
|
||||
]
|
||||
},
|
||||
"useLocalIp": {
|
||||
"description": "Let the browser open with your local IP.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"openPage": {
|
||||
"description": "Let the CLI open your browser to a specific page on the site.",
|
||||
"type": "string"
|
||||
},
|
||||
"features": {
|
||||
"description": "The order of which the features will be triggered.",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"compress": {
|
||||
"description": "Gzip compression for all requests.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"proxy": {
|
||||
"description": "Proxy requests to another server.",
|
||||
"anyOf": [
|
||||
{
|
||||
"items": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"instanceof": "Function"
|
||||
}
|
||||
]
|
||||
},
|
||||
"minItems": 1,
|
||||
"type": "array"
|
||||
},
|
||||
{
|
||||
"type": "object"
|
||||
}
|
||||
]
|
||||
},
|
||||
"historyApiFallback": {
|
||||
"description": "404 fallback to a specified file.",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "object"
|
||||
}
|
||||
]
|
||||
},
|
||||
"staticOptions": {
|
||||
"description": "Options for static files served with contentBase.",
|
||||
"type": "object"
|
||||
},
|
||||
"setup": {
|
||||
"description": "Exposes the Express server to add custom middleware or routes.",
|
||||
"instanceof": "Function"
|
||||
},
|
||||
"before": {
|
||||
"description": "Exposes the Express server to add custom middleware or routes before webpack-dev-middleware will be added.",
|
||||
"instanceof": "Function"
|
||||
},
|
||||
"after": {
|
||||
"description": "Exposes the Express server to add custom middleware or routes after webpack-dev-middleware got added.",
|
||||
"instanceof": "Function"
|
||||
},
|
||||
"stats": {
|
||||
"description": "Decides what bundle information is displayed.",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"enum": [
|
||||
"none",
|
||||
"errors-only",
|
||||
"minimal",
|
||||
"normal",
|
||||
"verbose"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"reporter": {
|
||||
"description": "Customize what the console displays when compiling.",
|
||||
"instanceof": "Function"
|
||||
},
|
||||
"reportTime": {
|
||||
"description": "Report time before and after compiling in console displays.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"noInfo": {
|
||||
"description": "Hide all info messages on console.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"quiet": {
|
||||
"description": "Hide all messages on console.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"serverSideRender": {
|
||||
"description": "Expose stats for server side rendering (experimental).",
|
||||
"type": "boolean"
|
||||
},
|
||||
"index": {
|
||||
"description": "The filename that is considered the index file.",
|
||||
"type": "string"
|
||||
},
|
||||
"log": {
|
||||
"description": "Customize info logs for webpack-dev-middleware.",
|
||||
"instanceof": "Function"
|
||||
},
|
||||
"warn": {
|
||||
"description": "Customize warn logs for webpack-dev-middleware.",
|
||||
"instanceof": "Function"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
'use strict';
|
||||
|
||||
/* polyfills for Node 4.8.x users */
|
||||
|
||||
// internal-ip@2.x uses [].includes
|
||||
const includes = require('array-includes');
|
||||
|
||||
includes.shim();
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
'use strict';
|
||||
|
||||
/* eslint no-param-reassign: 'off' */
|
||||
|
||||
const createDomain = require('./createDomain');
|
||||
|
||||
module.exports = function addDevServerEntrypoints(webpackOptions, devServerOptions, listeningApp) {
|
||||
if (devServerOptions.inline !== false) {
|
||||
// we're stubbing the app in this method as it's static and doesn't require
|
||||
// a listeningApp to be supplied. createDomain requires an app with the
|
||||
// address() signature.
|
||||
const app = listeningApp || {
|
||||
address() {
|
||||
return { port: devServerOptions.port };
|
||||
}
|
||||
};
|
||||
const domain = createDomain(devServerOptions, app);
|
||||
const devClient = [`${require.resolve('../../client/')}?${domain}`];
|
||||
|
||||
if (devServerOptions.hotOnly) { devClient.push('webpack/hot/only-dev-server'); } else if (devServerOptions.hot) { devClient.push('webpack/hot/dev-server'); }
|
||||
|
||||
const prependDevClient = (entry) => {
|
||||
if (typeof entry === 'function') {
|
||||
return () => Promise.resolve(entry()).then(prependDevClient);
|
||||
}
|
||||
if (typeof entry === 'object' && !Array.isArray(entry)) {
|
||||
const entryClone = {};
|
||||
Object.keys(entry).forEach((key) => {
|
||||
entryClone[key] = devClient.concat(entry[key]);
|
||||
});
|
||||
return entryClone;
|
||||
}
|
||||
return devClient.concat(entry);
|
||||
};
|
||||
|
||||
[].concat(webpackOptions).forEach((wpOpt) => {
|
||||
wpOpt.entry = prependDevClient(wpOpt.entry);
|
||||
});
|
||||
}
|
||||
};
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
'use strict';
|
||||
|
||||
const url = require('url');
|
||||
const internalIp = require('internal-ip');
|
||||
|
||||
|
||||
module.exports = function createDomain(options, listeningApp) {
|
||||
const protocol = options.https ? 'https' : 'http';
|
||||
const appPort = listeningApp ? listeningApp.address().port : 0;
|
||||
const port = options.socket ? 0 : appPort;
|
||||
const hostname = options.useLocalIp ? internalIp.v4() : options.host;
|
||||
|
||||
// use explicitly defined public url (prefix with protocol if not explicitly given)
|
||||
if (options.public) {
|
||||
return /^[a-zA-Z]+:\/\//.test(options.public) ? `${options.public}` : `${protocol}://${options.public}`;
|
||||
}
|
||||
// the formatted domain (url without path) of the webpack server
|
||||
return url.format({
|
||||
protocol,
|
||||
hostname,
|
||||
port
|
||||
});
|
||||
};
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
The ISC License
|
||||
|
||||
Copyright (c) 2014 Elan Shanker
|
||||
|
||||
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.
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
anymatch [](https://travis-ci.org/micromatch/anymatch) [](https://coveralls.io/r/micromatch/anymatch?branch=master)
|
||||
======
|
||||
Javascript module to match a string against a regular expression, glob, string,
|
||||
or function that takes the string as an argument and returns a truthy or falsy
|
||||
value. The matcher can also be an array of any or all of these. Useful for
|
||||
allowing a very flexible user-defined config to define things like file paths.
|
||||
|
||||
__Note: This module has Bash-parity, please be aware that Windows-style backslashes are not supported as separators. See https://github.com/micromatch/micromatch#backslashes for more information.__
|
||||
|
||||
[](https://nodei.co/npm/anymatch/)
|
||||
[](https://nodei.co/npm-dl/anymatch/)
|
||||
|
||||
Usage
|
||||
-----
|
||||
```sh
|
||||
npm install anymatch --save
|
||||
```
|
||||
|
||||
#### anymatch (matchers, testString, [returnIndex], [startIndex], [endIndex])
|
||||
* __matchers__: (_Array|String|RegExp|Function_)
|
||||
String to be directly matched, string with glob patterns, regular expression
|
||||
test, function that takes the testString as an argument and returns a truthy
|
||||
value if it should be matched, or an array of any number and mix of these types.
|
||||
* __testString__: (_String|Array_) The string to test against the matchers. If
|
||||
passed as an array, the first element of the array will be used as the
|
||||
`testString` for non-function matchers, while the entire array will be applied
|
||||
as the arguments for function matchers.
|
||||
* __returnIndex__: (_Boolean [optional]_) If true, return the array index of
|
||||
the first matcher that that testString matched, or -1 if no match, instead of a
|
||||
boolean result.
|
||||
* __startIndex, endIndex__: (_Integer [optional]_) Can be used to define a
|
||||
subset out of the array of provided matchers to test against. Can be useful
|
||||
with bound matcher functions (see below). When used with `returnIndex = true`
|
||||
preserves original indexing. Behaves the same as `Array.prototype.slice` (i.e.
|
||||
includes array members up to, but not including endIndex).
|
||||
|
||||
```js
|
||||
var anymatch = require('anymatch');
|
||||
|
||||
var matchers = [
|
||||
'path/to/file.js',
|
||||
'path/anyjs/**/*.js',
|
||||
/foo\.js$/,
|
||||
function (string) {
|
||||
return string.indexOf('bar') !== -1 && string.length > 10
|
||||
}
|
||||
];
|
||||
|
||||
anymatch(matchers, 'path/to/file.js'); // true
|
||||
anymatch(matchers, 'path/anyjs/baz.js'); // true
|
||||
anymatch(matchers, 'path/to/foo.js'); // true
|
||||
anymatch(matchers, 'path/to/bar.js'); // true
|
||||
anymatch(matchers, 'bar.js'); // false
|
||||
|
||||
// returnIndex = true
|
||||
anymatch(matchers, 'foo.js', true); // 2
|
||||
anymatch(matchers, 'path/anyjs/foo.js', true); // 1
|
||||
|
||||
// skip matchers
|
||||
anymatch(matchers, 'path/to/file.js', false, 1); // false
|
||||
anymatch(matchers, 'path/anyjs/foo.js', true, 2, 3); // 2
|
||||
anymatch(matchers, 'path/to/bar.js', true, 0, 3); // -1
|
||||
|
||||
// using globs to match directories and their children
|
||||
anymatch('node_modules', 'node_modules'); // true
|
||||
anymatch('node_modules', 'node_modules/somelib/index.js'); // false
|
||||
anymatch('node_modules/**', 'node_modules/somelib/index.js'); // true
|
||||
anymatch('node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // false
|
||||
anymatch('**/node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // true
|
||||
```
|
||||
|
||||
#### anymatch (matchers)
|
||||
You can also pass in only your matcher(s) to get a curried function that has
|
||||
already been bound to the provided matching criteria. This can be used as an
|
||||
`Array.prototype.filter` callback.
|
||||
|
||||
```js
|
||||
var matcher = anymatch(matchers);
|
||||
|
||||
matcher('path/to/file.js'); // true
|
||||
matcher('path/anyjs/baz.js', true); // 1
|
||||
matcher('path/anyjs/baz.js', true, 2); // -1
|
||||
|
||||
['foo.js', 'bar.js'].filter(matcher); // ['foo.js']
|
||||
```
|
||||
|
||||
Change Log
|
||||
----------
|
||||
[See release notes page on GitHub](https://github.com/micromatch/anymatch/releases)
|
||||
|
||||
NOTE: As of v2.0.0, [micromatch](https://github.com/jonschlinkert/micromatch) moves away from minimatch-parity and inline with Bash. This includes handling backslashes differently (see https://github.com/micromatch/micromatch#backslashes for more information).
|
||||
|
||||
NOTE: As of v1.2.0, anymatch uses [micromatch](https://github.com/jonschlinkert/micromatch)
|
||||
for glob pattern matching. Issues with glob pattern matching should be
|
||||
reported directly to the [micromatch issue tracker](https://github.com/jonschlinkert/micromatch/issues).
|
||||
|
||||
License
|
||||
-------
|
||||
[ISC](https://raw.github.com/micromatch/anymatch/master/LICENSE)
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
'use strict';
|
||||
|
||||
var micromatch = require('micromatch');
|
||||
var normalize = require('normalize-path');
|
||||
var path = require('path'); // required for tests.
|
||||
var arrify = function(a) { return a == null ? [] : (Array.isArray(a) ? a : [a]); };
|
||||
|
||||
var anymatch = function(criteria, value, returnIndex, startIndex, endIndex) {
|
||||
criteria = arrify(criteria);
|
||||
value = arrify(value);
|
||||
if (arguments.length === 1) {
|
||||
return anymatch.bind(null, criteria.map(function(criterion) {
|
||||
return typeof criterion === 'string' && criterion[0] !== '!' ?
|
||||
micromatch.matcher(criterion) : criterion;
|
||||
}));
|
||||
}
|
||||
startIndex = startIndex || 0;
|
||||
var string = value[0];
|
||||
var altString, altValue;
|
||||
var matched = false;
|
||||
var matchIndex = -1;
|
||||
function testCriteria(criterion, index) {
|
||||
var result;
|
||||
switch (Object.prototype.toString.call(criterion)) {
|
||||
case '[object String]':
|
||||
result = string === criterion || altString && altString === criterion;
|
||||
result = result || micromatch.isMatch(string, criterion);
|
||||
break;
|
||||
case '[object RegExp]':
|
||||
result = criterion.test(string) || altString && criterion.test(altString);
|
||||
break;
|
||||
case '[object Function]':
|
||||
result = criterion.apply(null, value);
|
||||
result = result || altValue && criterion.apply(null, altValue);
|
||||
break;
|
||||
default:
|
||||
result = false;
|
||||
}
|
||||
if (result) {
|
||||
matchIndex = index + startIndex;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
var crit = criteria;
|
||||
var negGlobs = crit.reduce(function(arr, criterion, index) {
|
||||
if (typeof criterion === 'string' && criterion[0] === '!') {
|
||||
if (crit === criteria) {
|
||||
// make a copy before modifying
|
||||
crit = crit.slice();
|
||||
}
|
||||
crit[index] = null;
|
||||
arr.push(criterion.substr(1));
|
||||
}
|
||||
return arr;
|
||||
}, []);
|
||||
if (!negGlobs.length || !micromatch.any(string, negGlobs)) {
|
||||
if (path.sep === '\\' && typeof string === 'string') {
|
||||
altString = normalize(string);
|
||||
altString = altString === string ? null : altString;
|
||||
if (altString) altValue = [altString].concat(value.slice(1));
|
||||
}
|
||||
matched = crit.slice(startIndex, endIndex).some(testCriteria);
|
||||
}
|
||||
return returnIndex === true ? matchIndex : matched;
|
||||
};
|
||||
|
||||
module.exports = anymatch;
|
||||
Generated
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014-2017, Jon Schlinkert
|
||||
|
||||
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.
|
||||
Generated
Vendored
+92
@@ -0,0 +1,92 @@
|
||||
# normalize-path [](https://www.npmjs.com/package/normalize-path) [](https://npmjs.org/package/normalize-path) [](https://npmjs.org/package/normalize-path) [](https://travis-ci.org/jonschlinkert/normalize-path)
|
||||
|
||||
> Normalize file path slashes to be unix-like forward slashes. Also condenses repeat slashes to a single slash and removes and trailing slashes unless disabled.
|
||||
|
||||
## Install
|
||||
|
||||
Install with [npm](https://www.npmjs.com/):
|
||||
|
||||
```sh
|
||||
$ npm install --save normalize-path
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
var normalize = require('normalize-path');
|
||||
|
||||
normalize('\\foo\\bar\\baz\\');
|
||||
//=> '/foo/bar/baz'
|
||||
|
||||
normalize('./foo/bar/baz/');
|
||||
//=> './foo/bar/baz'
|
||||
```
|
||||
|
||||
Pass `false` as the last argument to **keep** trailing slashes:
|
||||
|
||||
```js
|
||||
normalize('./foo/bar/baz/', false);
|
||||
//=> './foo/bar/baz/'
|
||||
|
||||
normalize('foo\\bar\\baz\\', false);
|
||||
//=> 'foo/bar/baz/'
|
||||
```
|
||||
|
||||
## About
|
||||
|
||||
### Related projects
|
||||
|
||||
* [contains-path](https://www.npmjs.com/package/contains-path): Return true if a file path contains the given path. | [homepage](https://github.com/jonschlinkert/contains-path "Return true if a file path contains the given path.")
|
||||
* [ends-with](https://www.npmjs.com/package/ends-with): Returns `true` if the given `string` or `array` ends with `suffix` using strict equality for… [more](https://github.com/jonschlinkert/ends-with) | [homepage](https://github.com/jonschlinkert/ends-with "Returns `true` if the given `string` or `array` ends with `suffix` using strict equality for comparisons.")
|
||||
* [is-absolute](https://www.npmjs.com/package/is-absolute): Polyfill for node.js `path.isAbolute`. Returns true if a file path is absolute. | [homepage](https://github.com/jonschlinkert/is-absolute "Polyfill for node.js `path.isAbolute`. Returns true if a file path is absolute.")
|
||||
* [is-relative](https://www.npmjs.com/package/is-relative): Returns `true` if the path appears to be relative. | [homepage](https://github.com/jonschlinkert/is-relative "Returns `true` if the path appears to be relative.")
|
||||
* [parse-filepath](https://www.npmjs.com/package/parse-filepath): Pollyfill for node.js `path.parse`, parses a filepath into an object. | [homepage](https://github.com/jonschlinkert/parse-filepath "Pollyfill for node.js `path.parse`, parses a filepath into an object.")
|
||||
* [path-ends-with](https://www.npmjs.com/package/path-ends-with): Return `true` if a file path ends with the given string/suffix. | [homepage](https://github.com/jonschlinkert/path-ends-with "Return `true` if a file path ends with the given string/suffix.")
|
||||
* [path-segments](https://www.npmjs.com/package/path-segments): Get n specific segments of a file path, e.g. first 2, last 3, etc. | [homepage](https://github.com/jonschlinkert/path-segments "Get n specific segments of a file path, e.g. first 2, last 3, etc.")
|
||||
* [rewrite-ext](https://www.npmjs.com/package/rewrite-ext): Automatically re-write the destination extension of a filepath based on the source extension. e.g… [more](https://github.com/jonschlinkert/rewrite-ext) | [homepage](https://github.com/jonschlinkert/rewrite-ext "Automatically re-write the destination extension of a filepath based on the source extension. e.g `.coffee` => `.js`. This will only rename the ext, no other path parts are modified.")
|
||||
* [unixify](https://www.npmjs.com/package/unixify): Convert Windows file paths to unix paths. | [homepage](https://github.com/jonschlinkert/unixify "Convert Windows file paths to unix paths.")
|
||||
|
||||
### Contributing
|
||||
|
||||
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
|
||||
|
||||
### Contributors
|
||||
|
||||
| **Commits** | **Contributor** |
|
||||
| --- | --- |
|
||||
| 31 | [jonschlinkert](https://github.com/jonschlinkert) |
|
||||
| 1 | [phated](https://github.com/phated) |
|
||||
|
||||
### Building docs
|
||||
|
||||
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
|
||||
|
||||
To generate the readme, run the following command:
|
||||
|
||||
```sh
|
||||
$ npm install -g verbose/verb#dev verb-generate-readme && verb
|
||||
```
|
||||
|
||||
### Running tests
|
||||
|
||||
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
|
||||
|
||||
```sh
|
||||
$ npm install && npm test
|
||||
```
|
||||
|
||||
### Author
|
||||
|
||||
**Jon Schlinkert**
|
||||
|
||||
* [github/jonschlinkert](https://github.com/jonschlinkert)
|
||||
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
|
||||
|
||||
### License
|
||||
|
||||
Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert).
|
||||
Released under the [MIT License](LICENSE).
|
||||
|
||||
***
|
||||
|
||||
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.4.3, on March 29, 2017._
|
||||
Generated
Vendored
+19
@@ -0,0 +1,19 @@
|
||||
/*!
|
||||
* normalize-path <https://github.com/jonschlinkert/normalize-path>
|
||||
*
|
||||
* Copyright (c) 2014-2017, Jon Schlinkert.
|
||||
* Released under the MIT License.
|
||||
*/
|
||||
|
||||
var removeTrailingSeparator = require('remove-trailing-separator');
|
||||
|
||||
module.exports = function normalizePath(str, stripTrailing) {
|
||||
if (typeof str !== 'string') {
|
||||
throw new TypeError('expected a string');
|
||||
}
|
||||
str = str.replace(/[\\\/]+/g, '/');
|
||||
if (stripTrailing !== false) {
|
||||
str = removeTrailingSeparator(str);
|
||||
}
|
||||
return str;
|
||||
};
|
||||
Generated
Vendored
+78
@@ -0,0 +1,78 @@
|
||||
{
|
||||
"name": "normalize-path",
|
||||
"description": "Normalize file path slashes to be unix-like forward slashes. Also condenses repeat slashes to a single slash and removes and trailing slashes unless disabled.",
|
||||
"version": "2.1.1",
|
||||
"homepage": "https://github.com/jonschlinkert/normalize-path",
|
||||
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
|
||||
"contributors": [
|
||||
"Blaine Bublitz <blaine.bublitz@gmail.com> (https://twitter.com/BlaineBublitz)",
|
||||
"Jon Schlinkert <jon.schlinkert@sellside.com> (http://twitter.com/jonschlinkert)"
|
||||
],
|
||||
"repository": "jonschlinkert/normalize-path",
|
||||
"bugs": {
|
||||
"url": "https://github.com/jonschlinkert/normalize-path/issues"
|
||||
},
|
||||
"license": "MIT",
|
||||
"files": [
|
||||
"index.js"
|
||||
],
|
||||
"main": "index.js",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "mocha"
|
||||
},
|
||||
"dependencies": {
|
||||
"remove-trailing-separator": "^1.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"benchmarked": "^0.1.1",
|
||||
"gulp-format-md": "^0.1.11",
|
||||
"minimist": "^1.2.0",
|
||||
"mocha": "*"
|
||||
},
|
||||
"keywords": [
|
||||
"backslash",
|
||||
"file",
|
||||
"filepath",
|
||||
"fix",
|
||||
"forward",
|
||||
"fp",
|
||||
"fs",
|
||||
"normalize",
|
||||
"path",
|
||||
"slash",
|
||||
"slashes",
|
||||
"trailing",
|
||||
"unix",
|
||||
"urix"
|
||||
],
|
||||
"verb": {
|
||||
"related": {
|
||||
"list": [
|
||||
"contains-path",
|
||||
"ends-with",
|
||||
"is-absolute",
|
||||
"is-relative",
|
||||
"parse-filepath",
|
||||
"path-ends-with",
|
||||
"path-segments",
|
||||
"rewrite-ext",
|
||||
"unixify"
|
||||
],
|
||||
"description": "Other useful libraries for working with paths in node.js:"
|
||||
},
|
||||
"toc": false,
|
||||
"layout": "default",
|
||||
"tasks": [
|
||||
"readme"
|
||||
],
|
||||
"plugins": [
|
||||
"gulp-format-md"
|
||||
],
|
||||
"lint": {
|
||||
"reflinks": true
|
||||
}
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "anymatch",
|
||||
"version": "2.0.0",
|
||||
"description": "Matches strings against configurable strings, globs, regular expressions, and/or functions",
|
||||
"files": [
|
||||
"index.js"
|
||||
],
|
||||
"author": {
|
||||
"name": "Elan Shanker",
|
||||
"url": "http://github.com/es128"
|
||||
},
|
||||
"license": "ISC",
|
||||
"homepage": "https://github.com/micromatch/anymatch",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/micromatch/anymatch"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/micromatch/anymatch/issues"
|
||||
},
|
||||
"keywords": [
|
||||
"match",
|
||||
"any",
|
||||
"string",
|
||||
"file",
|
||||
"fs",
|
||||
"list",
|
||||
"glob",
|
||||
"regex",
|
||||
"regexp",
|
||||
"regular",
|
||||
"expression",
|
||||
"function"
|
||||
],
|
||||
"scripts": {
|
||||
"test": "istanbul cover _mocha && cat ./coverage/lcov.info | coveralls"
|
||||
},
|
||||
"dependencies": {
|
||||
"micromatch": "^3.1.4",
|
||||
"normalize-path": "^2.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"coveralls": "^2.7.0",
|
||||
"istanbul": "^0.4.5",
|
||||
"mocha": "^3.0.0"
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+252
@@ -0,0 +1,252 @@
|
||||
[
|
||||
"3dm",
|
||||
"3ds",
|
||||
"3g2",
|
||||
"3gp",
|
||||
"7z",
|
||||
"a",
|
||||
"aac",
|
||||
"adp",
|
||||
"ai",
|
||||
"aif",
|
||||
"aiff",
|
||||
"alz",
|
||||
"ape",
|
||||
"apk",
|
||||
"ar",
|
||||
"arj",
|
||||
"asf",
|
||||
"au",
|
||||
"avi",
|
||||
"bak",
|
||||
"baml",
|
||||
"bh",
|
||||
"bin",
|
||||
"bk",
|
||||
"bmp",
|
||||
"btif",
|
||||
"bz2",
|
||||
"bzip2",
|
||||
"cab",
|
||||
"caf",
|
||||
"cgm",
|
||||
"class",
|
||||
"cmx",
|
||||
"cpio",
|
||||
"cr2",
|
||||
"cur",
|
||||
"dat",
|
||||
"dcm",
|
||||
"deb",
|
||||
"dex",
|
||||
"djvu",
|
||||
"dll",
|
||||
"dmg",
|
||||
"dng",
|
||||
"doc",
|
||||
"docm",
|
||||
"docx",
|
||||
"dot",
|
||||
"dotm",
|
||||
"dra",
|
||||
"DS_Store",
|
||||
"dsk",
|
||||
"dts",
|
||||
"dtshd",
|
||||
"dvb",
|
||||
"dwg",
|
||||
"dxf",
|
||||
"ecelp4800",
|
||||
"ecelp7470",
|
||||
"ecelp9600",
|
||||
"egg",
|
||||
"eol",
|
||||
"eot",
|
||||
"epub",
|
||||
"exe",
|
||||
"f4v",
|
||||
"fbs",
|
||||
"fh",
|
||||
"fla",
|
||||
"flac",
|
||||
"fli",
|
||||
"flv",
|
||||
"fpx",
|
||||
"fst",
|
||||
"fvt",
|
||||
"g3",
|
||||
"gh",
|
||||
"gif",
|
||||
"graffle",
|
||||
"gz",
|
||||
"gzip",
|
||||
"h261",
|
||||
"h263",
|
||||
"h264",
|
||||
"icns",
|
||||
"ico",
|
||||
"ief",
|
||||
"img",
|
||||
"ipa",
|
||||
"iso",
|
||||
"jar",
|
||||
"jpeg",
|
||||
"jpg",
|
||||
"jpgv",
|
||||
"jpm",
|
||||
"jxr",
|
||||
"key",
|
||||
"ktx",
|
||||
"lha",
|
||||
"lib",
|
||||
"lvp",
|
||||
"lz",
|
||||
"lzh",
|
||||
"lzma",
|
||||
"lzo",
|
||||
"m3u",
|
||||
"m4a",
|
||||
"m4v",
|
||||
"mar",
|
||||
"mdi",
|
||||
"mht",
|
||||
"mid",
|
||||
"midi",
|
||||
"mj2",
|
||||
"mka",
|
||||
"mkv",
|
||||
"mmr",
|
||||
"mng",
|
||||
"mobi",
|
||||
"mov",
|
||||
"movie",
|
||||
"mp3",
|
||||
"mp4",
|
||||
"mp4a",
|
||||
"mpeg",
|
||||
"mpg",
|
||||
"mpga",
|
||||
"mxu",
|
||||
"nef",
|
||||
"npx",
|
||||
"numbers",
|
||||
"nupkg",
|
||||
"o",
|
||||
"oga",
|
||||
"ogg",
|
||||
"ogv",
|
||||
"otf",
|
||||
"pages",
|
||||
"pbm",
|
||||
"pcx",
|
||||
"pdb",
|
||||
"pdf",
|
||||
"pea",
|
||||
"pgm",
|
||||
"pic",
|
||||
"png",
|
||||
"pnm",
|
||||
"pot",
|
||||
"potm",
|
||||
"potx",
|
||||
"ppa",
|
||||
"ppam",
|
||||
"ppm",
|
||||
"pps",
|
||||
"ppsm",
|
||||
"ppsx",
|
||||
"ppt",
|
||||
"pptm",
|
||||
"pptx",
|
||||
"psd",
|
||||
"pya",
|
||||
"pyc",
|
||||
"pyo",
|
||||
"pyv",
|
||||
"qt",
|
||||
"rar",
|
||||
"ras",
|
||||
"raw",
|
||||
"resources",
|
||||
"rgb",
|
||||
"rip",
|
||||
"rlc",
|
||||
"rmf",
|
||||
"rmvb",
|
||||
"rtf",
|
||||
"rz",
|
||||
"s3m",
|
||||
"s7z",
|
||||
"scpt",
|
||||
"sgi",
|
||||
"shar",
|
||||
"sil",
|
||||
"sketch",
|
||||
"slk",
|
||||
"smv",
|
||||
"snk",
|
||||
"so",
|
||||
"stl",
|
||||
"suo",
|
||||
"sub",
|
||||
"swf",
|
||||
"tar",
|
||||
"tbz",
|
||||
"tbz2",
|
||||
"tga",
|
||||
"tgz",
|
||||
"thmx",
|
||||
"tif",
|
||||
"tiff",
|
||||
"tlz",
|
||||
"ttc",
|
||||
"ttf",
|
||||
"txz",
|
||||
"udf",
|
||||
"uvh",
|
||||
"uvi",
|
||||
"uvm",
|
||||
"uvp",
|
||||
"uvs",
|
||||
"uvu",
|
||||
"viv",
|
||||
"vob",
|
||||
"war",
|
||||
"wav",
|
||||
"wax",
|
||||
"wbmp",
|
||||
"wdp",
|
||||
"weba",
|
||||
"webm",
|
||||
"webp",
|
||||
"whl",
|
||||
"wim",
|
||||
"wm",
|
||||
"wma",
|
||||
"wmv",
|
||||
"wmx",
|
||||
"woff",
|
||||
"woff2",
|
||||
"wrm",
|
||||
"wvx",
|
||||
"xbm",
|
||||
"xif",
|
||||
"xla",
|
||||
"xlam",
|
||||
"xls",
|
||||
"xlsb",
|
||||
"xlsm",
|
||||
"xlsx",
|
||||
"xlt",
|
||||
"xltm",
|
||||
"xltx",
|
||||
"xm",
|
||||
"xmind",
|
||||
"xpi",
|
||||
"xpm",
|
||||
"xwd",
|
||||
"xz",
|
||||
"z",
|
||||
"zip",
|
||||
"zipx"
|
||||
]
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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.
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"name": "binary-extensions",
|
||||
"version": "1.13.1",
|
||||
"description": "List of binary file extensions",
|
||||
"license": "MIT",
|
||||
"repository": "sindresorhus/binary-extensions",
|
||||
"author": {
|
||||
"name": "Sindre Sorhus",
|
||||
"email": "sindresorhus@gmail.com",
|
||||
"url": "sindresorhus.com"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "ava"
|
||||
},
|
||||
"main": "binary-extensions.json",
|
||||
"files": [
|
||||
"binary-extensions.json"
|
||||
],
|
||||
"keywords": [
|
||||
"bin",
|
||||
"binary",
|
||||
"ext",
|
||||
"extensions",
|
||||
"extension",
|
||||
"file",
|
||||
"json",
|
||||
"list",
|
||||
"array"
|
||||
],
|
||||
"devDependencies": {
|
||||
"ava": "0.16.0"
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
# binary-extensions [](https://travis-ci.org/sindresorhus/binary-extensions)
|
||||
|
||||
> List of binary file extensions
|
||||
|
||||
The list is just a [JSON file](binary-extensions.json) and can be used anywhere.
|
||||
|
||||
|
||||
## Install
|
||||
|
||||
```
|
||||
$ npm install binary-extensions
|
||||
```
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
const binaryExtensions = require('binary-extensions');
|
||||
|
||||
console.log(binaryExtensions);
|
||||
//=> ['3ds', '3g2', …]
|
||||
```
|
||||
|
||||
|
||||
## Related
|
||||
|
||||
- [is-binary-path](https://github.com/sindresorhus/is-binary-path) - Check if a filepath is a binary file
|
||||
- [text-extensions](https://github.com/sindresorhus/text-extensions) - List of text file extensions
|
||||
|
||||
|
||||
## License
|
||||
|
||||
MIT © [Sindre Sorhus](https://sindresorhus.com), Paul Miller (https://paulmillr.com)
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014-2018, Jon Schlinkert.
|
||||
|
||||
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.
|
||||
+640
@@ -0,0 +1,640 @@
|
||||
# braces [](https://www.npmjs.com/package/braces) [](https://npmjs.org/package/braces) [](https://npmjs.org/package/braces) [](https://travis-ci.org/micromatch/braces) [](https://ci.appveyor.com/project/micromatch/braces)
|
||||
|
||||
> Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.
|
||||
|
||||
Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
|
||||
|
||||
## Install
|
||||
|
||||
Install with [npm](https://www.npmjs.com/):
|
||||
|
||||
```sh
|
||||
$ npm install --save braces
|
||||
```
|
||||
|
||||
## Why use braces?
|
||||
|
||||
Brace patterns are great for matching ranges. Users (and implementors) shouldn't have to think about whether or not they will break their application (or yours) from accidentally defining an aggressive brace pattern. _Braces is the only library that offers a [solution to this problem](#performance)_.
|
||||
|
||||
* **Safe(r)**: Braces isn't vulnerable to DoS attacks like [brace-expansion](https://github.com/juliangruber/brace-expansion), [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch) (a different bug than the [other regex DoS bug](https://medium.com/node-security/minimatch-redos-vulnerability-590da24e6d3c#.jew0b6mpc)).
|
||||
* **Accurate**: complete support for the [Bash 4.3 Brace Expansion](www.gnu.org/software/bash/) specification (passes all of the Bash braces tests)
|
||||
* **[fast and performant](#benchmarks)**: Starts fast, runs fast and [scales well](#performance) as patterns increase in complexity.
|
||||
* **Organized code base**: with parser and compiler that are eas(y|ier) to maintain and update when edge cases crop up.
|
||||
* **Well-tested**: thousands of test assertions. Passes 100% of the [minimatch](https://github.com/isaacs/minimatch) and [brace-expansion](https://github.com/juliangruber/brace-expansion) unit tests as well (as of the writing of this).
|
||||
|
||||
## Usage
|
||||
|
||||
The main export is a function that takes one or more brace `patterns` and `options`.
|
||||
|
||||
```js
|
||||
var braces = require('braces');
|
||||
braces(pattern[, options]);
|
||||
```
|
||||
|
||||
By default, braces returns an optimized regex-source string. To get an array of brace patterns, use `brace.expand()`.
|
||||
|
||||
The following section explains the difference in more detail. _(If you're curious about "why" braces does this by default, see [brace matching pitfalls](#brace-matching-pitfalls)_.
|
||||
|
||||
### Optimized vs. expanded braces
|
||||
|
||||
**Optimized**
|
||||
|
||||
By default, patterns are optimized for regex and matching:
|
||||
|
||||
```js
|
||||
console.log(braces('a/{x,y,z}/b'));
|
||||
//=> ['a/(x|y|z)/b']
|
||||
```
|
||||
|
||||
**Expanded**
|
||||
|
||||
To expand patterns the same way as Bash or [minimatch](https://github.com/isaacs/minimatch), use the [.expand](#expand) method:
|
||||
|
||||
```js
|
||||
console.log(braces.expand('a/{x,y,z}/b'));
|
||||
//=> ['a/x/b', 'a/y/b', 'a/z/b']
|
||||
```
|
||||
|
||||
Or use [options.expand](#optionsexpand):
|
||||
|
||||
```js
|
||||
console.log(braces('a/{x,y,z}/b', {expand: true}));
|
||||
//=> ['a/x/b', 'a/y/b', 'a/z/b']
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
* [lists](#lists): Supports "lists": `a/{b,c}/d` => `['a/b/d', 'a/c/d']`
|
||||
* [sequences](#sequences): Supports alphabetical or numerical "sequences" (ranges): `{1..3}` => `['1', '2', '3']`
|
||||
* [steps](#steps): Supports "steps" or increments: `{2..10..2}` => `['2', '4', '6', '8', '10']`
|
||||
* [escaping](#escaping)
|
||||
* [options](#options)
|
||||
|
||||
### Lists
|
||||
|
||||
Uses [fill-range](https://github.com/jonschlinkert/fill-range) for expanding alphabetical or numeric lists:
|
||||
|
||||
```js
|
||||
console.log(braces('a/{foo,bar,baz}/*.js'));
|
||||
//=> ['a/(foo|bar|baz)/*.js']
|
||||
|
||||
console.log(braces.expand('a/{foo,bar,baz}/*.js'));
|
||||
//=> ['a/foo/*.js', 'a/bar/*.js', 'a/baz/*.js']
|
||||
```
|
||||
|
||||
### Sequences
|
||||
|
||||
Uses [fill-range](https://github.com/jonschlinkert/fill-range) for expanding alphabetical or numeric ranges (bash "sequences"):
|
||||
|
||||
```js
|
||||
console.log(braces.expand('{1..3}')); // ['1', '2', '3']
|
||||
console.log(braces.expand('a{01..03}b')); // ['a01b', 'a02b', 'a03b']
|
||||
console.log(braces.expand('a{1..3}b')); // ['a1b', 'a2b', 'a3b']
|
||||
console.log(braces.expand('{a..c}')); // ['a', 'b', 'c']
|
||||
console.log(braces.expand('foo/{a..c}')); // ['foo/a', 'foo/b', 'foo/c']
|
||||
|
||||
// supports padded ranges
|
||||
console.log(braces('a{01..03}b')); //=> [ 'a(0[1-3])b' ]
|
||||
console.log(braces('a{001..300}b')); //=> [ 'a(0{2}[1-9]|0[1-9][0-9]|[12][0-9]{2}|300)b' ]
|
||||
```
|
||||
|
||||
### Steps
|
||||
|
||||
Steps, or increments, may be used with ranges:
|
||||
|
||||
```js
|
||||
console.log(braces.expand('{2..10..2}'));
|
||||
//=> ['2', '4', '6', '8', '10']
|
||||
|
||||
console.log(braces('{2..10..2}'));
|
||||
//=> ['(2|4|6|8|10)']
|
||||
```
|
||||
|
||||
When the [.optimize](#optimize) method is used, or [options.optimize](#optionsoptimize) is set to true, sequences are passed to [to-regex-range](https://github.com/jonschlinkert/to-regex-range) for expansion.
|
||||
|
||||
### Nesting
|
||||
|
||||
Brace patterns may be nested. The results of each expanded string are not sorted, and left to right order is preserved.
|
||||
|
||||
**"Expanded" braces**
|
||||
|
||||
```js
|
||||
console.log(braces.expand('a{b,c,/{x,y}}/e'));
|
||||
//=> ['ab/e', 'ac/e', 'a/x/e', 'a/y/e']
|
||||
|
||||
console.log(braces.expand('a/{x,{1..5},y}/c'));
|
||||
//=> ['a/x/c', 'a/1/c', 'a/2/c', 'a/3/c', 'a/4/c', 'a/5/c', 'a/y/c']
|
||||
```
|
||||
|
||||
**"Optimized" braces**
|
||||
|
||||
```js
|
||||
console.log(braces('a{b,c,/{x,y}}/e'));
|
||||
//=> ['a(b|c|/(x|y))/e']
|
||||
|
||||
console.log(braces('a/{x,{1..5},y}/c'));
|
||||
//=> ['a/(x|([1-5])|y)/c']
|
||||
```
|
||||
|
||||
### Escaping
|
||||
|
||||
**Escaping braces**
|
||||
|
||||
A brace pattern will not be expanded or evaluted if _either the opening or closing brace is escaped_:
|
||||
|
||||
```js
|
||||
console.log(braces.expand('a\\{d,c,b}e'));
|
||||
//=> ['a{d,c,b}e']
|
||||
|
||||
console.log(braces.expand('a{d,c,b\\}e'));
|
||||
//=> ['a{d,c,b}e']
|
||||
```
|
||||
|
||||
**Escaping commas**
|
||||
|
||||
Commas inside braces may also be escaped:
|
||||
|
||||
```js
|
||||
console.log(braces.expand('a{b\\,c}d'));
|
||||
//=> ['a{b,c}d']
|
||||
|
||||
console.log(braces.expand('a{d\\,c,b}e'));
|
||||
//=> ['ad,ce', 'abe']
|
||||
```
|
||||
|
||||
**Single items**
|
||||
|
||||
Following bash conventions, a brace pattern is also not expanded when it contains a single character:
|
||||
|
||||
```js
|
||||
console.log(braces.expand('a{b}c'));
|
||||
//=> ['a{b}c']
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
### options.maxLength
|
||||
|
||||
**Type**: `Number`
|
||||
|
||||
**Default**: `65,536`
|
||||
|
||||
**Description**: Limit the length of the input string. Useful when the input string is generated or your application allows users to pass a string, et cetera.
|
||||
|
||||
```js
|
||||
console.log(braces('a/{b,c}/d', { maxLength: 3 })); //=> throws an error
|
||||
```
|
||||
|
||||
### options.expand
|
||||
|
||||
**Type**: `Boolean`
|
||||
|
||||
**Default**: `undefined`
|
||||
|
||||
**Description**: Generate an "expanded" brace pattern (this option is unncessary with the `.expand` method, which does the same thing).
|
||||
|
||||
```js
|
||||
console.log(braces('a/{b,c}/d', {expand: true}));
|
||||
//=> [ 'a/b/d', 'a/c/d' ]
|
||||
```
|
||||
|
||||
### options.optimize
|
||||
|
||||
**Type**: `Boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
**Description**: Enabled by default.
|
||||
|
||||
```js
|
||||
console.log(braces('a/{b,c}/d'));
|
||||
//=> [ 'a/(b|c)/d' ]
|
||||
```
|
||||
|
||||
### options.nodupes
|
||||
|
||||
**Type**: `Boolean`
|
||||
|
||||
**Default**: `true`
|
||||
|
||||
**Description**: Duplicates are removed by default. To keep duplicates, pass `{nodupes: false}` on the options
|
||||
|
||||
### options.rangeLimit
|
||||
|
||||
**Type**: `Number`
|
||||
|
||||
**Default**: `250`
|
||||
|
||||
**Description**: When `braces.expand()` is used, or `options.expand` is true, brace patterns will automatically be [optimized](#optionsoptimize) when the difference between the range minimum and range maximum exceeds the `rangeLimit`. This is to prevent huge ranges from freezing your application.
|
||||
|
||||
You can set this to any number, or change `options.rangeLimit` to `Inifinity` to disable this altogether.
|
||||
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
// pattern exceeds the "rangeLimit", so it's optimized automatically
|
||||
console.log(braces.expand('{1..1000}'));
|
||||
//=> ['([1-9]|[1-9][0-9]{1,2}|1000)']
|
||||
|
||||
// pattern does not exceed "rangeLimit", so it's NOT optimized
|
||||
console.log(braces.expand('{1..100}'));
|
||||
//=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100']
|
||||
```
|
||||
|
||||
### options.transform
|
||||
|
||||
**Type**: `Function`
|
||||
|
||||
**Default**: `undefined`
|
||||
|
||||
**Description**: Customize range expansion.
|
||||
|
||||
```js
|
||||
var range = braces.expand('x{a..e}y', {
|
||||
transform: function(str) {
|
||||
return 'foo' + str;
|
||||
}
|
||||
});
|
||||
|
||||
console.log(range);
|
||||
//=> [ 'xfooay', 'xfooby', 'xfoocy', 'xfoody', 'xfooey' ]
|
||||
```
|
||||
|
||||
### options.quantifiers
|
||||
|
||||
**Type**: `Boolean`
|
||||
|
||||
**Default**: `undefined`
|
||||
|
||||
**Description**: In regular expressions, quanitifiers can be used to specify how many times a token can be repeated. For example, `a{1,3}` will match the letter `a` one to three times.
|
||||
|
||||
Unfortunately, regex quantifiers happen to share the same syntax as [Bash lists](#lists)
|
||||
|
||||
The `quantifiers` option tells braces to detect when [regex quantifiers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#quantifiers) are defined in the given pattern, and not to try to expand them as lists.
|
||||
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
var braces = require('braces');
|
||||
console.log(braces('a/b{1,3}/{x,y,z}'));
|
||||
//=> [ 'a/b(1|3)/(x|y|z)' ]
|
||||
console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true}));
|
||||
//=> [ 'a/b{1,3}/(x|y|z)' ]
|
||||
console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true, expand: true}));
|
||||
//=> [ 'a/b{1,3}/x', 'a/b{1,3}/y', 'a/b{1,3}/z' ]
|
||||
```
|
||||
|
||||
### options.unescape
|
||||
|
||||
**Type**: `Boolean`
|
||||
|
||||
**Default**: `undefined`
|
||||
|
||||
**Description**: Strip backslashes that were used for escaping from the result.
|
||||
|
||||
## What is "brace expansion"?
|
||||
|
||||
Brace expansion is a type of parameter expansion that was made popular by unix shells for generating lists of strings, as well as regex-like matching when used alongside wildcards (globs).
|
||||
|
||||
In addition to "expansion", braces are also used for matching. In other words:
|
||||
|
||||
* [brace expansion](#brace-expansion) is for generating new lists
|
||||
* [brace matching](#brace-matching) is for filtering existing lists
|
||||
|
||||
<details>
|
||||
<summary><strong>More about brace expansion</strong> (click to expand)</summary>
|
||||
|
||||
There are two main types of brace expansion:
|
||||
|
||||
1. **lists**: which are defined using comma-separated values inside curly braces: `{a,b,c}`
|
||||
2. **sequences**: which are defined using a starting value and an ending value, separated by two dots: `a{1..3}b`. Optionally, a third argument may be passed to define a "step" or increment to use: `a{1..100..10}b`. These are also sometimes referred to as "ranges".
|
||||
|
||||
Here are some example brace patterns to illustrate how they work:
|
||||
|
||||
**Sets**
|
||||
|
||||
```
|
||||
{a,b,c} => a b c
|
||||
{a,b,c}{1,2} => a1 a2 b1 b2 c1 c2
|
||||
```
|
||||
|
||||
**Sequences**
|
||||
|
||||
```
|
||||
{1..9} => 1 2 3 4 5 6 7 8 9
|
||||
{4..-4} => 4 3 2 1 0 -1 -2 -3 -4
|
||||
{1..20..3} => 1 4 7 10 13 16 19
|
||||
{a..j} => a b c d e f g h i j
|
||||
{j..a} => j i h g f e d c b a
|
||||
{a..z..3} => a d g j m p s v y
|
||||
```
|
||||
|
||||
**Combination**
|
||||
|
||||
Sets and sequences can be mixed together or used along with any other strings.
|
||||
|
||||
```
|
||||
{a,b,c}{1..3} => a1 a2 a3 b1 b2 b3 c1 c2 c3
|
||||
foo/{a,b,c}/bar => foo/a/bar foo/b/bar foo/c/bar
|
||||
```
|
||||
|
||||
The fact that braces can be "expanded" from relatively simple patterns makes them ideal for quickly generating test fixtures, file paths, and similar use cases.
|
||||
|
||||
## Brace matching
|
||||
|
||||
In addition to _expansion_, brace patterns are also useful for performing regular-expression-like matching.
|
||||
|
||||
For example, the pattern `foo/{1..3}/bar` would match any of following strings:
|
||||
|
||||
```
|
||||
foo/1/bar
|
||||
foo/2/bar
|
||||
foo/3/bar
|
||||
```
|
||||
|
||||
But not:
|
||||
|
||||
```
|
||||
baz/1/qux
|
||||
baz/2/qux
|
||||
baz/3/qux
|
||||
```
|
||||
|
||||
Braces can also be combined with [glob patterns](https://github.com/jonschlinkert/micromatch) to perform more advanced wildcard matching. For example, the pattern `*/{1..3}/*` would match any of following strings:
|
||||
|
||||
```
|
||||
foo/1/bar
|
||||
foo/2/bar
|
||||
foo/3/bar
|
||||
baz/1/qux
|
||||
baz/2/qux
|
||||
baz/3/qux
|
||||
```
|
||||
|
||||
## Brace matching pitfalls
|
||||
|
||||
Although brace patterns offer a user-friendly way of matching ranges or sets of strings, there are also some major disadvantages and potential risks you should be aware of.
|
||||
|
||||
### tldr
|
||||
|
||||
**"brace bombs"**
|
||||
|
||||
* brace expansion can eat up a huge amount of processing resources
|
||||
* as brace patterns increase _linearly in size_, the system resources required to expand the pattern increase exponentially
|
||||
* users can accidentally (or intentially) exhaust your system's resources resulting in the equivalent of a DoS attack (bonus: no programming knowledge is required!)
|
||||
|
||||
For a more detailed explanation with examples, see the [geometric complexity](#geometric-complexity) section.
|
||||
|
||||
### The solution
|
||||
|
||||
Jump to the [performance section](#performance) to see how Braces solves this problem in comparison to other libraries.
|
||||
|
||||
### Geometric complexity
|
||||
|
||||
At minimum, brace patterns with sets limited to two elements have quadradic or `O(n^2)` complexity. But the complexity of the algorithm increases exponentially as the number of sets, _and elements per set_, increases, which is `O(n^c)`.
|
||||
|
||||
For example, the following sets demonstrate quadratic (`O(n^2)`) complexity:
|
||||
|
||||
```
|
||||
{1,2}{3,4} => (2X2) => 13 14 23 24
|
||||
{1,2}{3,4}{5,6} => (2X2X2) => 135 136 145 146 235 236 245 246
|
||||
```
|
||||
|
||||
But add an element to a set, and we get a n-fold Cartesian product with `O(n^c)` complexity:
|
||||
|
||||
```
|
||||
{1,2,3}{4,5,6}{7,8,9} => (3X3X3) => 147 148 149 157 158 159 167 168 169 247 248
|
||||
249 257 258 259 267 268 269 347 348 349 357
|
||||
358 359 367 368 369
|
||||
```
|
||||
|
||||
Now, imagine how this complexity grows given that each element is a n-tuple:
|
||||
|
||||
```
|
||||
{1..100}{1..100} => (100X100) => 10,000 elements (38.4 kB)
|
||||
{1..100}{1..100}{1..100} => (100X100X100) => 1,000,000 elements (5.76 MB)
|
||||
```
|
||||
|
||||
Although these examples are clearly contrived, they demonstrate how brace patterns can quickly grow out of control.
|
||||
|
||||
**More information**
|
||||
|
||||
Interested in learning more about brace expansion?
|
||||
|
||||
* [linuxjournal/bash-brace-expansion](http://www.linuxjournal.com/content/bash-brace-expansion)
|
||||
* [rosettacode/Brace_expansion](https://rosettacode.org/wiki/Brace_expansion)
|
||||
* [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product)
|
||||
|
||||
</details>
|
||||
|
||||
## Performance
|
||||
|
||||
Braces is not only screaming fast, it's also more accurate the other brace expansion libraries.
|
||||
|
||||
### Better algorithms
|
||||
|
||||
Fortunately there is a solution to the ["brace bomb" problem](#brace-matching-pitfalls): _don't expand brace patterns into an array when they're used for matching_.
|
||||
|
||||
Instead, convert the pattern into an optimized regular expression. This is easier said than done, and braces is the only library that does this currently.
|
||||
|
||||
**The proof is in the numbers**
|
||||
|
||||
Minimatch gets exponentially slower as patterns increase in complexity, braces does not. The following results were generated using `braces()` and `minimatch.braceExpand()`, respectively.
|
||||
|
||||
| **Pattern** | **braces** | **[minimatch](https://github.com/isaacs/minimatch)** |
|
||||
| --- | --- | --- |
|
||||
| `{1..9007199254740991}`<sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup> | `298 B` (5ms 459μs) | N/A (freezes) |
|
||||
| `{1..1000000000000000}` | `41 B` (1ms 15μs) | N/A (freezes) |
|
||||
| `{1..100000000000000}` | `40 B` (890μs) | N/A (freezes) |
|
||||
| `{1..10000000000000}` | `39 B` (2ms 49μs) | N/A (freezes) |
|
||||
| `{1..1000000000000}` | `38 B` (608μs) | N/A (freezes) |
|
||||
| `{1..100000000000}` | `37 B` (397μs) | N/A (freezes) |
|
||||
| `{1..10000000000}` | `35 B` (983μs) | N/A (freezes) |
|
||||
| `{1..1000000000}` | `34 B` (798μs) | N/A (freezes) |
|
||||
| `{1..100000000}` | `33 B` (733μs) | N/A (freezes) |
|
||||
| `{1..10000000}` | `32 B` (5ms 632μs) | `78.89 MB` (16s 388ms 569μs) |
|
||||
| `{1..1000000}` | `31 B` (1ms 381μs) | `6.89 MB` (1s 496ms 887μs) |
|
||||
| `{1..100000}` | `30 B` (950μs) | `588.89 kB` (146ms 921μs) |
|
||||
| `{1..10000}` | `29 B` (1ms 114μs) | `48.89 kB` (14ms 187μs) |
|
||||
| `{1..1000}` | `28 B` (760μs) | `3.89 kB` (1ms 453μs) |
|
||||
| `{1..100}` | `22 B` (345μs) | `291 B` (196μs) |
|
||||
| `{1..10}` | `10 B` (533μs) | `20 B` (37μs) |
|
||||
| `{1..3}` | `7 B` (190μs) | `5 B` (27μs) |
|
||||
|
||||
### Faster algorithms
|
||||
|
||||
When you need expansion, braces is still much faster.
|
||||
|
||||
_(the following results were generated using `braces.expand()` and `minimatch.braceExpand()`, respectively)_
|
||||
|
||||
| **Pattern** | **braces** | **[minimatch](https://github.com/isaacs/minimatch)** |
|
||||
| --- | --- | --- |
|
||||
| `{1..10000000}` | `78.89 MB` (2s 698ms 642μs) | `78.89 MB` (18s 601ms 974μs) |
|
||||
| `{1..1000000}` | `6.89 MB` (458ms 576μs) | `6.89 MB` (1s 491ms 621μs) |
|
||||
| `{1..100000}` | `588.89 kB` (20ms 728μs) | `588.89 kB` (156ms 919μs) |
|
||||
| `{1..10000}` | `48.89 kB` (2ms 202μs) | `48.89 kB` (13ms 641μs) |
|
||||
| `{1..1000}` | `3.89 kB` (1ms 796μs) | `3.89 kB` (1ms 958μs) |
|
||||
| `{1..100}` | `291 B` (424μs) | `291 B` (211μs) |
|
||||
| `{1..10}` | `20 B` (487μs) | `20 B` (72μs) |
|
||||
| `{1..3}` | `5 B` (166μs) | `5 B` (27μs) |
|
||||
|
||||
If you'd like to run these comparisons yourself, see [test/support/generate.js](test/support/generate.js).
|
||||
|
||||
## Benchmarks
|
||||
|
||||
### Running benchmarks
|
||||
|
||||
Install dev dependencies:
|
||||
|
||||
```bash
|
||||
npm i -d && npm benchmark
|
||||
```
|
||||
|
||||
### Latest results
|
||||
|
||||
```bash
|
||||
Benchmarking: (8 of 8)
|
||||
· combination-nested
|
||||
· combination
|
||||
· escaped
|
||||
· list-basic
|
||||
· list-multiple
|
||||
· no-braces
|
||||
· sequence-basic
|
||||
· sequence-multiple
|
||||
|
||||
# benchmark/fixtures/combination-nested.js (52 bytes)
|
||||
brace-expansion x 4,756 ops/sec ±1.09% (86 runs sampled)
|
||||
braces x 11,202,303 ops/sec ±1.06% (88 runs sampled)
|
||||
minimatch x 4,816 ops/sec ±0.99% (87 runs sampled)
|
||||
|
||||
fastest is braces
|
||||
|
||||
# benchmark/fixtures/combination.js (51 bytes)
|
||||
brace-expansion x 625 ops/sec ±0.87% (87 runs sampled)
|
||||
braces x 11,031,884 ops/sec ±0.72% (90 runs sampled)
|
||||
minimatch x 637 ops/sec ±0.84% (88 runs sampled)
|
||||
|
||||
fastest is braces
|
||||
|
||||
# benchmark/fixtures/escaped.js (44 bytes)
|
||||
brace-expansion x 163,325 ops/sec ±1.05% (87 runs sampled)
|
||||
braces x 10,655,071 ops/sec ±1.22% (88 runs sampled)
|
||||
minimatch x 147,495 ops/sec ±0.96% (88 runs sampled)
|
||||
|
||||
fastest is braces
|
||||
|
||||
# benchmark/fixtures/list-basic.js (40 bytes)
|
||||
brace-expansion x 99,726 ops/sec ±1.07% (83 runs sampled)
|
||||
braces x 10,596,584 ops/sec ±0.98% (88 runs sampled)
|
||||
minimatch x 100,069 ops/sec ±1.17% (86 runs sampled)
|
||||
|
||||
fastest is braces
|
||||
|
||||
# benchmark/fixtures/list-multiple.js (52 bytes)
|
||||
brace-expansion x 34,348 ops/sec ±1.08% (88 runs sampled)
|
||||
braces x 9,264,131 ops/sec ±1.12% (88 runs sampled)
|
||||
minimatch x 34,893 ops/sec ±0.87% (87 runs sampled)
|
||||
|
||||
fastest is braces
|
||||
|
||||
# benchmark/fixtures/no-braces.js (48 bytes)
|
||||
brace-expansion x 275,368 ops/sec ±1.18% (89 runs sampled)
|
||||
braces x 9,134,677 ops/sec ±0.95% (88 runs sampled)
|
||||
minimatch x 3,755,954 ops/sec ±1.13% (89 runs sampled)
|
||||
|
||||
fastest is braces
|
||||
|
||||
# benchmark/fixtures/sequence-basic.js (41 bytes)
|
||||
brace-expansion x 5,492 ops/sec ±1.35% (87 runs sampled)
|
||||
braces x 8,485,034 ops/sec ±1.28% (89 runs sampled)
|
||||
minimatch x 5,341 ops/sec ±1.17% (87 runs sampled)
|
||||
|
||||
fastest is braces
|
||||
|
||||
# benchmark/fixtures/sequence-multiple.js (51 bytes)
|
||||
brace-expansion x 116 ops/sec ±0.77% (77 runs sampled)
|
||||
braces x 9,445,118 ops/sec ±1.32% (84 runs sampled)
|
||||
minimatch x 109 ops/sec ±1.16% (76 runs sampled)
|
||||
|
||||
fastest is braces
|
||||
```
|
||||
|
||||
## About
|
||||
|
||||
<details>
|
||||
<summary><strong>Contributing</strong></summary>
|
||||
|
||||
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Running Tests</strong></summary>
|
||||
|
||||
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
|
||||
|
||||
```sh
|
||||
$ npm install && npm test
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Building docs</strong></summary>
|
||||
|
||||
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
|
||||
|
||||
To generate the readme, run the following command:
|
||||
|
||||
```sh
|
||||
$ npm install -g verbose/verb#dev verb-generate-readme && verb
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
### Related projects
|
||||
|
||||
You might also be interested in these projects:
|
||||
|
||||
* [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/jonschlinkert/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.")
|
||||
* [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/micromatch/extglob) | [homepage](https://github.com/micromatch/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.")
|
||||
* [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`")
|
||||
* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.")
|
||||
* [nanomatch](https://www.npmjs.com/package/nanomatch): Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… [more](https://github.com/micromatch/nanomatch) | [homepage](https://github.com/micromatch/nanomatch "Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)")
|
||||
|
||||
### Contributors
|
||||
|
||||
| **Commits** | **Contributor** |
|
||||
| --- | --- |
|
||||
| 188 | [jonschlinkert](https://github.com/jonschlinkert) |
|
||||
| 4 | [doowb](https://github.com/doowb) |
|
||||
| 1 | [es128](https://github.com/es128) |
|
||||
| 1 | [eush77](https://github.com/eush77) |
|
||||
| 1 | [hemanth](https://github.com/hemanth) |
|
||||
|
||||
### Author
|
||||
|
||||
**Jon Schlinkert**
|
||||
|
||||
* [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert)
|
||||
* [github/jonschlinkert](https://github.com/jonschlinkert)
|
||||
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
|
||||
|
||||
### License
|
||||
|
||||
Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert).
|
||||
Released under the [MIT License](LICENSE).
|
||||
|
||||
***
|
||||
|
||||
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on February 17, 2018._
|
||||
|
||||
<hr class="footnotes-sep">
|
||||
<section class="footnotes">
|
||||
<ol class="footnotes-list">
|
||||
<li id="fn1" class="footnote-item">this is the largest safe integer allowed in JavaScript. <a href="#fnref1" class="footnote-backref">↩</a>
|
||||
|
||||
</li>
|
||||
</ol>
|
||||
</section>
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies
|
||||
*/
|
||||
|
||||
var toRegex = require('to-regex');
|
||||
var unique = require('array-unique');
|
||||
var extend = require('extend-shallow');
|
||||
|
||||
/**
|
||||
* Local dependencies
|
||||
*/
|
||||
|
||||
var compilers = require('./lib/compilers');
|
||||
var parsers = require('./lib/parsers');
|
||||
var Braces = require('./lib/braces');
|
||||
var utils = require('./lib/utils');
|
||||
var MAX_LENGTH = 1024 * 64;
|
||||
var cache = {};
|
||||
|
||||
/**
|
||||
* Convert the given `braces` pattern into a regex-compatible string. By default, only one string is generated for every input string. Set `options.expand` to true to return an array of patterns (similar to Bash or minimatch. Before using `options.expand`, it's recommended that you read the [performance notes](#performance)).
|
||||
*
|
||||
* ```js
|
||||
* var braces = require('braces');
|
||||
* console.log(braces('{a,b,c}'));
|
||||
* //=> ['(a|b|c)']
|
||||
*
|
||||
* console.log(braces('{a,b,c}', {expand: true}));
|
||||
* //=> ['a', 'b', 'c']
|
||||
* ```
|
||||
* @param {String} `str`
|
||||
* @param {Object} `options`
|
||||
* @return {String}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function braces(pattern, options) {
|
||||
var key = utils.createKey(String(pattern), options);
|
||||
var arr = [];
|
||||
|
||||
var disabled = options && options.cache === false;
|
||||
if (!disabled && cache.hasOwnProperty(key)) {
|
||||
return cache[key];
|
||||
}
|
||||
|
||||
if (Array.isArray(pattern)) {
|
||||
for (var i = 0; i < pattern.length; i++) {
|
||||
arr.push.apply(arr, braces.create(pattern[i], options));
|
||||
}
|
||||
} else {
|
||||
arr = braces.create(pattern, options);
|
||||
}
|
||||
|
||||
if (options && options.nodupes === true) {
|
||||
arr = unique(arr);
|
||||
}
|
||||
|
||||
if (!disabled) {
|
||||
cache[key] = arr;
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expands a brace pattern into an array. This method is called by the main [braces](#braces) function when `options.expand` is true. Before using this method it's recommended that you read the [performance notes](#performance)) and advantages of using [.optimize](#optimize) instead.
|
||||
*
|
||||
* ```js
|
||||
* var braces = require('braces');
|
||||
* console.log(braces.expand('a/{b,c}/d'));
|
||||
* //=> ['a/b/d', 'a/c/d'];
|
||||
* ```
|
||||
* @param {String} `pattern` Brace pattern
|
||||
* @param {Object} `options`
|
||||
* @return {Array} Returns an array of expanded values.
|
||||
* @api public
|
||||
*/
|
||||
|
||||
braces.expand = function(pattern, options) {
|
||||
return braces.create(pattern, extend({}, options, {expand: true}));
|
||||
};
|
||||
|
||||
/**
|
||||
* Expands a brace pattern into a regex-compatible, optimized string. This method is called by the main [braces](#braces) function by default.
|
||||
*
|
||||
* ```js
|
||||
* var braces = require('braces');
|
||||
* console.log(braces.expand('a/{b,c}/d'));
|
||||
* //=> ['a/(b|c)/d']
|
||||
* ```
|
||||
* @param {String} `pattern` Brace pattern
|
||||
* @param {Object} `options`
|
||||
* @return {Array} Returns an array of expanded values.
|
||||
* @api public
|
||||
*/
|
||||
|
||||
braces.optimize = function(pattern, options) {
|
||||
return braces.create(pattern, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Processes a brace pattern and returns either an expanded array (if `options.expand` is true), a highly optimized regex-compatible string. This method is called by the main [braces](#braces) function.
|
||||
*
|
||||
* ```js
|
||||
* var braces = require('braces');
|
||||
* console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
|
||||
* //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
|
||||
* ```
|
||||
* @param {String} `pattern` Brace pattern
|
||||
* @param {Object} `options`
|
||||
* @return {Array} Returns an array of expanded values.
|
||||
* @api public
|
||||
*/
|
||||
|
||||
braces.create = function(pattern, options) {
|
||||
if (typeof pattern !== 'string') {
|
||||
throw new TypeError('expected a string');
|
||||
}
|
||||
|
||||
var maxLength = (options && options.maxLength) || MAX_LENGTH;
|
||||
if (pattern.length >= maxLength) {
|
||||
throw new Error('expected pattern to be less than ' + maxLength + ' characters');
|
||||
}
|
||||
|
||||
function create() {
|
||||
if (pattern === '' || pattern.length < 3) {
|
||||
return [pattern];
|
||||
}
|
||||
|
||||
if (utils.isEmptySets(pattern)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (utils.isQuotedString(pattern)) {
|
||||
return [pattern.slice(1, -1)];
|
||||
}
|
||||
|
||||
var proto = new Braces(options);
|
||||
var result = !options || options.expand !== true
|
||||
? proto.optimize(pattern, options)
|
||||
: proto.expand(pattern, options);
|
||||
|
||||
// get the generated pattern(s)
|
||||
var arr = result.output;
|
||||
|
||||
// filter out empty strings if specified
|
||||
if (options && options.noempty === true) {
|
||||
arr = arr.filter(Boolean);
|
||||
}
|
||||
|
||||
// filter out duplicates if specified
|
||||
if (options && options.nodupes === true) {
|
||||
arr = unique(arr);
|
||||
}
|
||||
|
||||
Object.defineProperty(arr, 'result', {
|
||||
enumerable: false,
|
||||
value: result
|
||||
});
|
||||
|
||||
return arr;
|
||||
}
|
||||
|
||||
return memoize('create', pattern, options, create);
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a regular expression from the given string `pattern`.
|
||||
*
|
||||
* ```js
|
||||
* var braces = require('braces');
|
||||
*
|
||||
* console.log(braces.makeRe('id-{200..300}'));
|
||||
* //=> /^(?:id-(20[0-9]|2[1-9][0-9]|300))$/
|
||||
* ```
|
||||
* @param {String} `pattern` The pattern to convert to regex.
|
||||
* @param {Object} `options`
|
||||
* @return {RegExp}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
braces.makeRe = function(pattern, options) {
|
||||
if (typeof pattern !== 'string') {
|
||||
throw new TypeError('expected a string');
|
||||
}
|
||||
|
||||
var maxLength = (options && options.maxLength) || MAX_LENGTH;
|
||||
if (pattern.length >= maxLength) {
|
||||
throw new Error('expected pattern to be less than ' + maxLength + ' characters');
|
||||
}
|
||||
|
||||
function makeRe() {
|
||||
var arr = braces(pattern, options);
|
||||
var opts = extend({strictErrors: false}, options);
|
||||
return toRegex(arr, opts);
|
||||
}
|
||||
|
||||
return memoize('makeRe', pattern, options, makeRe);
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse the given `str` with the given `options`.
|
||||
*
|
||||
* ```js
|
||||
* var braces = require('braces');
|
||||
* var ast = braces.parse('a/{b,c}/d');
|
||||
* console.log(ast);
|
||||
* // { type: 'root',
|
||||
* // errors: [],
|
||||
* // input: 'a/{b,c}/d',
|
||||
* // nodes:
|
||||
* // [ { type: 'bos', val: '' },
|
||||
* // { type: 'text', val: 'a/' },
|
||||
* // { type: 'brace',
|
||||
* // nodes:
|
||||
* // [ { type: 'brace.open', val: '{' },
|
||||
* // { type: 'text', val: 'b,c' },
|
||||
* // { type: 'brace.close', val: '}' } ] },
|
||||
* // { type: 'text', val: '/d' },
|
||||
* // { type: 'eos', val: '' } ] }
|
||||
* ```
|
||||
* @param {String} `pattern` Brace pattern to parse
|
||||
* @param {Object} `options`
|
||||
* @return {Object} Returns an AST
|
||||
* @api public
|
||||
*/
|
||||
|
||||
braces.parse = function(pattern, options) {
|
||||
var proto = new Braces(options);
|
||||
return proto.parse(pattern, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Compile the given `ast` or string with the given `options`.
|
||||
*
|
||||
* ```js
|
||||
* var braces = require('braces');
|
||||
* var ast = braces.parse('a/{b,c}/d');
|
||||
* console.log(braces.compile(ast));
|
||||
* // { options: { source: 'string' },
|
||||
* // state: {},
|
||||
* // compilers:
|
||||
* // { eos: [Function],
|
||||
* // noop: [Function],
|
||||
* // bos: [Function],
|
||||
* // brace: [Function],
|
||||
* // 'brace.open': [Function],
|
||||
* // text: [Function],
|
||||
* // 'brace.close': [Function] },
|
||||
* // output: [ 'a/(b|c)/d' ],
|
||||
* // ast:
|
||||
* // { ... },
|
||||
* // parsingErrors: [] }
|
||||
* ```
|
||||
* @param {Object|String} `ast` AST from [.parse](#parse). If a string is passed it will be parsed first.
|
||||
* @param {Object} `options`
|
||||
* @return {Object} Returns an object that has an `output` property with the compiled string.
|
||||
* @api public
|
||||
*/
|
||||
|
||||
braces.compile = function(ast, options) {
|
||||
var proto = new Braces(options);
|
||||
return proto.compile(ast, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Clear the regex cache.
|
||||
*
|
||||
* ```js
|
||||
* braces.clearCache();
|
||||
* ```
|
||||
* @api public
|
||||
*/
|
||||
|
||||
braces.clearCache = function() {
|
||||
cache = braces.cache = {};
|
||||
};
|
||||
|
||||
/**
|
||||
* Memoize a generated regex or function. A unique key is generated
|
||||
* from the method name, pattern, and user-defined options. Set
|
||||
* options.memoize to false to disable.
|
||||
*/
|
||||
|
||||
function memoize(type, pattern, options, fn) {
|
||||
var key = utils.createKey(type + ':' + pattern, options);
|
||||
var disabled = options && options.cache === false;
|
||||
if (disabled) {
|
||||
braces.clearCache();
|
||||
return fn(pattern, options);
|
||||
}
|
||||
|
||||
if (cache.hasOwnProperty(key)) {
|
||||
return cache[key];
|
||||
}
|
||||
|
||||
var res = fn(pattern, options);
|
||||
cache[key] = res;
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expose `Braces` constructor and methods
|
||||
* @type {Function}
|
||||
*/
|
||||
|
||||
braces.Braces = Braces;
|
||||
braces.compilers = compilers;
|
||||
braces.parsers = parsers;
|
||||
braces.cache = cache;
|
||||
|
||||
/**
|
||||
* Expose `braces`
|
||||
* @type {Function}
|
||||
*/
|
||||
|
||||
module.exports = braces;
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
'use strict';
|
||||
|
||||
var extend = require('extend-shallow');
|
||||
var Snapdragon = require('snapdragon');
|
||||
var compilers = require('./compilers');
|
||||
var parsers = require('./parsers');
|
||||
var utils = require('./utils');
|
||||
|
||||
/**
|
||||
* Customize Snapdragon parser and renderer
|
||||
*/
|
||||
|
||||
function Braces(options) {
|
||||
this.options = extend({}, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize braces
|
||||
*/
|
||||
|
||||
Braces.prototype.init = function(options) {
|
||||
if (this.isInitialized) return;
|
||||
this.isInitialized = true;
|
||||
var opts = utils.createOptions({}, this.options, options);
|
||||
this.snapdragon = this.options.snapdragon || new Snapdragon(opts);
|
||||
this.compiler = this.snapdragon.compiler;
|
||||
this.parser = this.snapdragon.parser;
|
||||
|
||||
compilers(this.snapdragon, opts);
|
||||
parsers(this.snapdragon, opts);
|
||||
|
||||
/**
|
||||
* Call Snapdragon `.parse` method. When AST is returned, we check to
|
||||
* see if any unclosed braces are left on the stack and, if so, we iterate
|
||||
* over the stack and correct the AST so that compilers are called in the correct
|
||||
* order and unbalance braces are properly escaped.
|
||||
*/
|
||||
|
||||
utils.define(this.snapdragon, 'parse', function(pattern, options) {
|
||||
var parsed = Snapdragon.prototype.parse.apply(this, arguments);
|
||||
this.parser.ast.input = pattern;
|
||||
|
||||
var stack = this.parser.stack;
|
||||
while (stack.length) {
|
||||
addParent({type: 'brace.close', val: ''}, stack.pop());
|
||||
}
|
||||
|
||||
function addParent(node, parent) {
|
||||
utils.define(node, 'parent', parent);
|
||||
parent.nodes.push(node);
|
||||
}
|
||||
|
||||
// add non-enumerable parser reference
|
||||
utils.define(parsed, 'parser', this.parser);
|
||||
return parsed;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Decorate `.parse` method
|
||||
*/
|
||||
|
||||
Braces.prototype.parse = function(ast, options) {
|
||||
if (ast && typeof ast === 'object' && ast.nodes) return ast;
|
||||
this.init(options);
|
||||
return this.snapdragon.parse(ast, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Decorate `.compile` method
|
||||
*/
|
||||
|
||||
Braces.prototype.compile = function(ast, options) {
|
||||
if (typeof ast === 'string') {
|
||||
ast = this.parse(ast, options);
|
||||
} else {
|
||||
this.init(options);
|
||||
}
|
||||
return this.snapdragon.compile(ast, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Expand
|
||||
*/
|
||||
|
||||
Braces.prototype.expand = function(pattern) {
|
||||
var ast = this.parse(pattern, {expand: true});
|
||||
return this.compile(ast, {expand: true});
|
||||
};
|
||||
|
||||
/**
|
||||
* Optimize
|
||||
*/
|
||||
|
||||
Braces.prototype.optimize = function(pattern) {
|
||||
var ast = this.parse(pattern, {optimize: true});
|
||||
return this.compile(ast, {optimize: true});
|
||||
};
|
||||
|
||||
/**
|
||||
* Expose `Braces`
|
||||
*/
|
||||
|
||||
module.exports = Braces;
|
||||
+282
@@ -0,0 +1,282 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./utils');
|
||||
|
||||
module.exports = function(braces, options) {
|
||||
braces.compiler
|
||||
|
||||
/**
|
||||
* bos
|
||||
*/
|
||||
|
||||
.set('bos', function() {
|
||||
if (this.output) return;
|
||||
this.ast.queue = isEscaped(this.ast) ? [this.ast.val] : [];
|
||||
this.ast.count = 1;
|
||||
})
|
||||
|
||||
/**
|
||||
* Square brackets
|
||||
*/
|
||||
|
||||
.set('bracket', function(node) {
|
||||
var close = node.close;
|
||||
var open = !node.escaped ? '[' : '\\[';
|
||||
var negated = node.negated;
|
||||
var inner = node.inner;
|
||||
|
||||
inner = inner.replace(/\\(?=[\\\w]|$)/g, '\\\\');
|
||||
if (inner === ']-') {
|
||||
inner = '\\]\\-';
|
||||
}
|
||||
|
||||
if (negated && inner.indexOf('.') === -1) {
|
||||
inner += '.';
|
||||
}
|
||||
if (negated && inner.indexOf('/') === -1) {
|
||||
inner += '/';
|
||||
}
|
||||
|
||||
var val = open + negated + inner + close;
|
||||
var queue = node.parent.queue;
|
||||
var last = utils.arrayify(queue.pop());
|
||||
|
||||
queue.push(utils.join(last, val));
|
||||
queue.push.apply(queue, []);
|
||||
})
|
||||
|
||||
/**
|
||||
* Brace
|
||||
*/
|
||||
|
||||
.set('brace', function(node) {
|
||||
node.queue = isEscaped(node) ? [node.val] : [];
|
||||
node.count = 1;
|
||||
return this.mapVisit(node.nodes);
|
||||
})
|
||||
|
||||
/**
|
||||
* Open
|
||||
*/
|
||||
|
||||
.set('brace.open', function(node) {
|
||||
node.parent.open = node.val;
|
||||
})
|
||||
|
||||
/**
|
||||
* Inner
|
||||
*/
|
||||
|
||||
.set('text', function(node) {
|
||||
var queue = node.parent.queue;
|
||||
var escaped = node.escaped;
|
||||
var segs = [node.val];
|
||||
|
||||
if (node.optimize === false) {
|
||||
options = utils.extend({}, options, {optimize: false});
|
||||
}
|
||||
|
||||
if (node.multiplier > 1) {
|
||||
node.parent.count *= node.multiplier;
|
||||
}
|
||||
|
||||
if (options.quantifiers === true && utils.isQuantifier(node.val)) {
|
||||
escaped = true;
|
||||
|
||||
} else if (node.val.length > 1) {
|
||||
if (isType(node.parent, 'brace') && !isEscaped(node)) {
|
||||
var expanded = utils.expand(node.val, options);
|
||||
segs = expanded.segs;
|
||||
|
||||
if (expanded.isOptimized) {
|
||||
node.parent.isOptimized = true;
|
||||
}
|
||||
|
||||
// if nothing was expanded, we probably have a literal brace
|
||||
if (!segs.length) {
|
||||
var val = (expanded.val || node.val);
|
||||
if (options.unescape !== false) {
|
||||
// unescape unexpanded brace sequence/set separators
|
||||
val = val.replace(/\\([,.])/g, '$1');
|
||||
// strip quotes
|
||||
val = val.replace(/["'`]/g, '');
|
||||
}
|
||||
|
||||
segs = [val];
|
||||
escaped = true;
|
||||
}
|
||||
}
|
||||
|
||||
} else if (node.val === ',') {
|
||||
if (options.expand) {
|
||||
node.parent.queue.push(['']);
|
||||
segs = [''];
|
||||
} else {
|
||||
segs = ['|'];
|
||||
}
|
||||
} else {
|
||||
escaped = true;
|
||||
}
|
||||
|
||||
if (escaped && isType(node.parent, 'brace')) {
|
||||
if (node.parent.nodes.length <= 4 && node.parent.count === 1) {
|
||||
node.parent.escaped = true;
|
||||
} else if (node.parent.length <= 3) {
|
||||
node.parent.escaped = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasQueue(node.parent)) {
|
||||
node.parent.queue = segs;
|
||||
return;
|
||||
}
|
||||
|
||||
var last = utils.arrayify(queue.pop());
|
||||
if (node.parent.count > 1 && options.expand) {
|
||||
last = multiply(last, node.parent.count);
|
||||
node.parent.count = 1;
|
||||
}
|
||||
|
||||
queue.push(utils.join(utils.flatten(last), segs.shift()));
|
||||
queue.push.apply(queue, segs);
|
||||
})
|
||||
|
||||
/**
|
||||
* Close
|
||||
*/
|
||||
|
||||
.set('brace.close', function(node) {
|
||||
var queue = node.parent.queue;
|
||||
var prev = node.parent.parent;
|
||||
var last = prev.queue.pop();
|
||||
var open = node.parent.open;
|
||||
var close = node.val;
|
||||
|
||||
if (open && close && isOptimized(node, options)) {
|
||||
open = '(';
|
||||
close = ')';
|
||||
}
|
||||
|
||||
// if a close brace exists, and the previous segment is one character
|
||||
// don't wrap the result in braces or parens
|
||||
var ele = utils.last(queue);
|
||||
if (node.parent.count > 1 && options.expand) {
|
||||
ele = multiply(queue.pop(), node.parent.count);
|
||||
node.parent.count = 1;
|
||||
queue.push(ele);
|
||||
}
|
||||
|
||||
if (close && typeof ele === 'string' && ele.length === 1) {
|
||||
open = '';
|
||||
close = '';
|
||||
}
|
||||
|
||||
if ((isLiteralBrace(node, options) || noInner(node)) && !node.parent.hasEmpty) {
|
||||
queue.push(utils.join(open, queue.pop() || ''));
|
||||
queue = utils.flatten(utils.join(queue, close));
|
||||
}
|
||||
|
||||
if (typeof last === 'undefined') {
|
||||
prev.queue = [queue];
|
||||
} else {
|
||||
prev.queue.push(utils.flatten(utils.join(last, queue)));
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* eos
|
||||
*/
|
||||
|
||||
.set('eos', function(node) {
|
||||
if (this.input) return;
|
||||
|
||||
if (options.optimize !== false) {
|
||||
this.output = utils.last(utils.flatten(this.ast.queue));
|
||||
} else if (Array.isArray(utils.last(this.ast.queue))) {
|
||||
this.output = utils.flatten(this.ast.queue.pop());
|
||||
} else {
|
||||
this.output = utils.flatten(this.ast.queue);
|
||||
}
|
||||
|
||||
if (node.parent.count > 1 && options.expand) {
|
||||
this.output = multiply(this.output, node.parent.count);
|
||||
}
|
||||
|
||||
this.output = utils.arrayify(this.output);
|
||||
this.ast.queue = [];
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Multiply the segments in the current brace level
|
||||
*/
|
||||
|
||||
function multiply(queue, n, options) {
|
||||
return utils.flatten(utils.repeat(utils.arrayify(queue), n));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if `node` is escaped
|
||||
*/
|
||||
|
||||
function isEscaped(node) {
|
||||
return node.escaped === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if regex parens should be used for sets. If the parent `type`
|
||||
* is not `brace`, then we're on a root node, which means we should never
|
||||
* expand segments and open/close braces should be `{}` (since this indicates
|
||||
* a brace is missing from the set)
|
||||
*/
|
||||
|
||||
function isOptimized(node, options) {
|
||||
if (node.parent.isOptimized) return true;
|
||||
return isType(node.parent, 'brace')
|
||||
&& !isEscaped(node.parent)
|
||||
&& options.expand !== true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the value in `node` should be wrapped in a literal brace.
|
||||
* @return {Boolean}
|
||||
*/
|
||||
|
||||
function isLiteralBrace(node, options) {
|
||||
return isEscaped(node.parent) || options.optimize !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the given `node` does not have an inner value.
|
||||
* @return {Boolean}
|
||||
*/
|
||||
|
||||
function noInner(node, type) {
|
||||
if (node.parent.queue.length === 1) {
|
||||
return true;
|
||||
}
|
||||
var nodes = node.parent.nodes;
|
||||
return nodes.length === 3
|
||||
&& isType(nodes[0], 'brace.open')
|
||||
&& !isType(nodes[1], 'text')
|
||||
&& isType(nodes[2], 'brace.close');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the given `node` is the given `type`
|
||||
* @return {Boolean}
|
||||
*/
|
||||
|
||||
function isType(node, type) {
|
||||
return typeof node !== 'undefined' && node.type === type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the given `node` has a non-empty queue.
|
||||
* @return {Boolean}
|
||||
*/
|
||||
|
||||
function hasQueue(node) {
|
||||
return Array.isArray(node.queue) && node.queue.length;
|
||||
}
|
||||
+360
@@ -0,0 +1,360 @@
|
||||
'use strict';
|
||||
|
||||
var Node = require('snapdragon-node');
|
||||
var utils = require('./utils');
|
||||
|
||||
/**
|
||||
* Braces parsers
|
||||
*/
|
||||
|
||||
module.exports = function(braces, options) {
|
||||
braces.parser
|
||||
.set('bos', function() {
|
||||
if (!this.parsed) {
|
||||
this.ast = this.nodes[0] = new Node(this.ast);
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* Character parsers
|
||||
*/
|
||||
|
||||
.set('escape', function() {
|
||||
var pos = this.position();
|
||||
var m = this.match(/^(?:\\(.)|\$\{)/);
|
||||
if (!m) return;
|
||||
|
||||
var prev = this.prev();
|
||||
var last = utils.last(prev.nodes);
|
||||
|
||||
var node = pos(new Node({
|
||||
type: 'text',
|
||||
multiplier: 1,
|
||||
val: m[0]
|
||||
}));
|
||||
|
||||
if (node.val === '\\\\') {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (node.val === '${') {
|
||||
var str = this.input;
|
||||
var idx = -1;
|
||||
var ch;
|
||||
|
||||
while ((ch = str[++idx])) {
|
||||
this.consume(1);
|
||||
node.val += ch;
|
||||
if (ch === '\\') {
|
||||
node.val += str[++idx];
|
||||
continue;
|
||||
}
|
||||
if (ch === '}') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.options.unescape !== false) {
|
||||
node.val = node.val.replace(/\\([{}])/g, '$1');
|
||||
}
|
||||
|
||||
if (last.val === '"' && this.input.charAt(0) === '"') {
|
||||
last.val = node.val;
|
||||
this.consume(1);
|
||||
return;
|
||||
}
|
||||
|
||||
return concatNodes.call(this, pos, node, prev, options);
|
||||
})
|
||||
|
||||
/**
|
||||
* Brackets: "[...]" (basic, this is overridden by
|
||||
* other parsers in more advanced implementations)
|
||||
*/
|
||||
|
||||
.set('bracket', function() {
|
||||
var isInside = this.isInside('brace');
|
||||
var pos = this.position();
|
||||
var m = this.match(/^(?:\[([!^]?)([^\]]{2,}|\]-)(\]|[^*+?]+)|\[)/);
|
||||
if (!m) return;
|
||||
|
||||
var prev = this.prev();
|
||||
var val = m[0];
|
||||
var negated = m[1] ? '^' : '';
|
||||
var inner = m[2] || '';
|
||||
var close = m[3] || '';
|
||||
|
||||
if (isInside && prev.type === 'brace') {
|
||||
prev.text = prev.text || '';
|
||||
prev.text += val;
|
||||
}
|
||||
|
||||
var esc = this.input.slice(0, 2);
|
||||
if (inner === '' && esc === '\\]') {
|
||||
inner += esc;
|
||||
this.consume(2);
|
||||
|
||||
var str = this.input;
|
||||
var idx = -1;
|
||||
var ch;
|
||||
|
||||
while ((ch = str[++idx])) {
|
||||
this.consume(1);
|
||||
if (ch === ']') {
|
||||
close = ch;
|
||||
break;
|
||||
}
|
||||
inner += ch;
|
||||
}
|
||||
}
|
||||
|
||||
return pos(new Node({
|
||||
type: 'bracket',
|
||||
val: val,
|
||||
escaped: close !== ']',
|
||||
negated: negated,
|
||||
inner: inner,
|
||||
close: close
|
||||
}));
|
||||
})
|
||||
|
||||
/**
|
||||
* Empty braces (we capture these early to
|
||||
* speed up processing in the compiler)
|
||||
*/
|
||||
|
||||
.set('multiplier', function() {
|
||||
var isInside = this.isInside('brace');
|
||||
var pos = this.position();
|
||||
var m = this.match(/^\{((?:,|\{,+\})+)\}/);
|
||||
if (!m) return;
|
||||
|
||||
this.multiplier = true;
|
||||
var prev = this.prev();
|
||||
var val = m[0];
|
||||
|
||||
if (isInside && prev.type === 'brace') {
|
||||
prev.text = prev.text || '';
|
||||
prev.text += val;
|
||||
}
|
||||
|
||||
var node = pos(new Node({
|
||||
type: 'text',
|
||||
multiplier: 1,
|
||||
match: m,
|
||||
val: val
|
||||
}));
|
||||
|
||||
return concatNodes.call(this, pos, node, prev, options);
|
||||
})
|
||||
|
||||
/**
|
||||
* Open
|
||||
*/
|
||||
|
||||
.set('brace.open', function() {
|
||||
var pos = this.position();
|
||||
var m = this.match(/^\{(?!(?:[^\\}]?|,+)\})/);
|
||||
if (!m) return;
|
||||
|
||||
var prev = this.prev();
|
||||
var last = utils.last(prev.nodes);
|
||||
|
||||
// if the last parsed character was an extglob character
|
||||
// we need to _not optimize_ the brace pattern because
|
||||
// it might be mistaken for an extglob by a downstream parser
|
||||
if (last && last.val && isExtglobChar(last.val.slice(-1))) {
|
||||
last.optimize = false;
|
||||
}
|
||||
|
||||
var open = pos(new Node({
|
||||
type: 'brace.open',
|
||||
val: m[0]
|
||||
}));
|
||||
|
||||
var node = pos(new Node({
|
||||
type: 'brace',
|
||||
nodes: []
|
||||
}));
|
||||
|
||||
node.push(open);
|
||||
prev.push(node);
|
||||
this.push('brace', node);
|
||||
})
|
||||
|
||||
/**
|
||||
* Close
|
||||
*/
|
||||
|
||||
.set('brace.close', function() {
|
||||
var pos = this.position();
|
||||
var m = this.match(/^\}/);
|
||||
if (!m || !m[0]) return;
|
||||
|
||||
var brace = this.pop('brace');
|
||||
var node = pos(new Node({
|
||||
type: 'brace.close',
|
||||
val: m[0]
|
||||
}));
|
||||
|
||||
if (!this.isType(brace, 'brace')) {
|
||||
if (this.options.strict) {
|
||||
throw new Error('missing opening "{"');
|
||||
}
|
||||
node.type = 'text';
|
||||
node.multiplier = 0;
|
||||
node.escaped = true;
|
||||
return node;
|
||||
}
|
||||
|
||||
var prev = this.prev();
|
||||
var last = utils.last(prev.nodes);
|
||||
if (last.text) {
|
||||
var lastNode = utils.last(last.nodes);
|
||||
if (lastNode.val === ')' && /[!@*?+]\(/.test(last.text)) {
|
||||
var open = last.nodes[0];
|
||||
var text = last.nodes[1];
|
||||
if (open.type === 'brace.open' && text && text.type === 'text') {
|
||||
text.optimize = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (brace.nodes.length > 2) {
|
||||
var first = brace.nodes[1];
|
||||
if (first.type === 'text' && first.val === ',') {
|
||||
brace.nodes.splice(1, 1);
|
||||
brace.nodes.push(first);
|
||||
}
|
||||
}
|
||||
|
||||
brace.push(node);
|
||||
})
|
||||
|
||||
/**
|
||||
* Capture boundary characters
|
||||
*/
|
||||
|
||||
.set('boundary', function() {
|
||||
var pos = this.position();
|
||||
var m = this.match(/^[$^](?!\{)/);
|
||||
if (!m) return;
|
||||
return pos(new Node({
|
||||
type: 'text',
|
||||
val: m[0]
|
||||
}));
|
||||
})
|
||||
|
||||
/**
|
||||
* One or zero, non-comma characters wrapped in braces
|
||||
*/
|
||||
|
||||
.set('nobrace', function() {
|
||||
var isInside = this.isInside('brace');
|
||||
var pos = this.position();
|
||||
var m = this.match(/^\{[^,]?\}/);
|
||||
if (!m) return;
|
||||
|
||||
var prev = this.prev();
|
||||
var val = m[0];
|
||||
|
||||
if (isInside && prev.type === 'brace') {
|
||||
prev.text = prev.text || '';
|
||||
prev.text += val;
|
||||
}
|
||||
|
||||
return pos(new Node({
|
||||
type: 'text',
|
||||
multiplier: 0,
|
||||
val: val
|
||||
}));
|
||||
})
|
||||
|
||||
/**
|
||||
* Text
|
||||
*/
|
||||
|
||||
.set('text', function() {
|
||||
var isInside = this.isInside('brace');
|
||||
var pos = this.position();
|
||||
var m = this.match(/^((?!\\)[^${}[\]])+/);
|
||||
if (!m) return;
|
||||
|
||||
var prev = this.prev();
|
||||
var val = m[0];
|
||||
|
||||
if (isInside && prev.type === 'brace') {
|
||||
prev.text = prev.text || '';
|
||||
prev.text += val;
|
||||
}
|
||||
|
||||
var node = pos(new Node({
|
||||
type: 'text',
|
||||
multiplier: 1,
|
||||
val: val
|
||||
}));
|
||||
|
||||
return concatNodes.call(this, pos, node, prev, options);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns true if the character is an extglob character.
|
||||
*/
|
||||
|
||||
function isExtglobChar(ch) {
|
||||
return ch === '!' || ch === '@' || ch === '*' || ch === '?' || ch === '+';
|
||||
}
|
||||
|
||||
/**
|
||||
* Combine text nodes, and calculate empty sets (`{,,}`)
|
||||
* @param {Function} `pos` Function to calculate node position
|
||||
* @param {Object} `node` AST node
|
||||
* @return {Object}
|
||||
*/
|
||||
|
||||
function concatNodes(pos, node, parent, options) {
|
||||
node.orig = node.val;
|
||||
var prev = this.prev();
|
||||
var last = utils.last(prev.nodes);
|
||||
var isEscaped = false;
|
||||
|
||||
if (node.val.length > 1) {
|
||||
var a = node.val.charAt(0);
|
||||
var b = node.val.slice(-1);
|
||||
|
||||
isEscaped = (a === '"' && b === '"')
|
||||
|| (a === "'" && b === "'")
|
||||
|| (a === '`' && b === '`');
|
||||
}
|
||||
|
||||
if (isEscaped && options.unescape !== false) {
|
||||
node.val = node.val.slice(1, node.val.length - 1);
|
||||
node.escaped = true;
|
||||
}
|
||||
|
||||
if (node.match) {
|
||||
var match = node.match[1];
|
||||
if (!match || match.indexOf('}') === -1) {
|
||||
match = node.match[0];
|
||||
}
|
||||
|
||||
// replace each set with a single ","
|
||||
var val = match.replace(/\{/g, ',').replace(/\}/g, '');
|
||||
node.multiplier *= val.length;
|
||||
node.val = '';
|
||||
}
|
||||
|
||||
var simpleText = last.type === 'text'
|
||||
&& last.multiplier === 1
|
||||
&& node.multiplier === 1
|
||||
&& node.val;
|
||||
|
||||
if (simpleText) {
|
||||
last.val += node.val;
|
||||
return;
|
||||
}
|
||||
|
||||
prev.push(node);
|
||||
}
|
||||
+343
@@ -0,0 +1,343 @@
|
||||
'use strict';
|
||||
|
||||
var splitString = require('split-string');
|
||||
var utils = module.exports;
|
||||
|
||||
/**
|
||||
* Module dependencies
|
||||
*/
|
||||
|
||||
utils.extend = require('extend-shallow');
|
||||
utils.flatten = require('arr-flatten');
|
||||
utils.isObject = require('isobject');
|
||||
utils.fillRange = require('fill-range');
|
||||
utils.repeat = require('repeat-element');
|
||||
utils.unique = require('array-unique');
|
||||
|
||||
utils.define = function(obj, key, val) {
|
||||
Object.defineProperty(obj, key, {
|
||||
writable: true,
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
value: val
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns true if the given string contains only empty brace sets.
|
||||
*/
|
||||
|
||||
utils.isEmptySets = function(str) {
|
||||
return /^(?:\{,\})+$/.test(str);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns true if the given string contains only empty brace sets.
|
||||
*/
|
||||
|
||||
utils.isQuotedString = function(str) {
|
||||
var open = str.charAt(0);
|
||||
if (open === '\'' || open === '"' || open === '`') {
|
||||
return str.slice(-1) === open;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Create the key to use for memoization. The unique key is generated
|
||||
* by iterating over the options and concatenating key-value pairs
|
||||
* to the pattern string.
|
||||
*/
|
||||
|
||||
utils.createKey = function(pattern, options) {
|
||||
var id = pattern;
|
||||
if (typeof options === 'undefined') {
|
||||
return id;
|
||||
}
|
||||
var keys = Object.keys(options);
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
var key = keys[i];
|
||||
id += ';' + key + '=' + String(options[key]);
|
||||
}
|
||||
return id;
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalize options
|
||||
*/
|
||||
|
||||
utils.createOptions = function(options) {
|
||||
var opts = utils.extend.apply(null, arguments);
|
||||
if (typeof opts.expand === 'boolean') {
|
||||
opts.optimize = !opts.expand;
|
||||
}
|
||||
if (typeof opts.optimize === 'boolean') {
|
||||
opts.expand = !opts.optimize;
|
||||
}
|
||||
if (opts.optimize === true) {
|
||||
opts.makeRe = true;
|
||||
}
|
||||
return opts;
|
||||
};
|
||||
|
||||
/**
|
||||
* Join patterns in `a` to patterns in `b`
|
||||
*/
|
||||
|
||||
utils.join = function(a, b, options) {
|
||||
options = options || {};
|
||||
a = utils.arrayify(a);
|
||||
b = utils.arrayify(b);
|
||||
|
||||
if (!a.length) return b;
|
||||
if (!b.length) return a;
|
||||
|
||||
var len = a.length;
|
||||
var idx = -1;
|
||||
var arr = [];
|
||||
|
||||
while (++idx < len) {
|
||||
var val = a[idx];
|
||||
if (Array.isArray(val)) {
|
||||
for (var i = 0; i < val.length; i++) {
|
||||
val[i] = utils.join(val[i], b, options);
|
||||
}
|
||||
arr.push(val);
|
||||
continue;
|
||||
}
|
||||
|
||||
for (var j = 0; j < b.length; j++) {
|
||||
var bval = b[j];
|
||||
|
||||
if (Array.isArray(bval)) {
|
||||
arr.push(utils.join(val, bval, options));
|
||||
} else {
|
||||
arr.push(val + bval);
|
||||
}
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
};
|
||||
|
||||
/**
|
||||
* Split the given string on `,` if not escaped.
|
||||
*/
|
||||
|
||||
utils.split = function(str, options) {
|
||||
var opts = utils.extend({sep: ','}, options);
|
||||
if (typeof opts.keepQuotes !== 'boolean') {
|
||||
opts.keepQuotes = true;
|
||||
}
|
||||
if (opts.unescape === false) {
|
||||
opts.keepEscaping = true;
|
||||
}
|
||||
return splitString(str, opts, utils.escapeBrackets(opts));
|
||||
};
|
||||
|
||||
/**
|
||||
* Expand ranges or sets in the given `pattern`.
|
||||
*
|
||||
* @param {String} `str`
|
||||
* @param {Object} `options`
|
||||
* @return {Object}
|
||||
*/
|
||||
|
||||
utils.expand = function(str, options) {
|
||||
var opts = utils.extend({rangeLimit: 10000}, options);
|
||||
var segs = utils.split(str, opts);
|
||||
var tok = { segs: segs };
|
||||
|
||||
if (utils.isQuotedString(str)) {
|
||||
return tok;
|
||||
}
|
||||
|
||||
if (opts.rangeLimit === true) {
|
||||
opts.rangeLimit = 10000;
|
||||
}
|
||||
|
||||
if (segs.length > 1) {
|
||||
if (opts.optimize === false) {
|
||||
tok.val = segs[0];
|
||||
return tok;
|
||||
}
|
||||
|
||||
tok.segs = utils.stringifyArray(tok.segs);
|
||||
} else if (segs.length === 1) {
|
||||
var arr = str.split('..');
|
||||
|
||||
if (arr.length === 1) {
|
||||
tok.val = tok.segs[tok.segs.length - 1] || tok.val || str;
|
||||
tok.segs = [];
|
||||
return tok;
|
||||
}
|
||||
|
||||
if (arr.length === 2 && arr[0] === arr[1]) {
|
||||
tok.escaped = true;
|
||||
tok.val = arr[0];
|
||||
tok.segs = [];
|
||||
return tok;
|
||||
}
|
||||
|
||||
if (arr.length > 1) {
|
||||
if (opts.optimize !== false) {
|
||||
opts.optimize = true;
|
||||
delete opts.expand;
|
||||
}
|
||||
|
||||
if (opts.optimize !== true) {
|
||||
var min = Math.min(arr[0], arr[1]);
|
||||
var max = Math.max(arr[0], arr[1]);
|
||||
var step = arr[2] || 1;
|
||||
|
||||
if (opts.rangeLimit !== false && ((max - min) / step >= opts.rangeLimit)) {
|
||||
throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
|
||||
}
|
||||
}
|
||||
|
||||
arr.push(opts);
|
||||
tok.segs = utils.fillRange.apply(null, arr);
|
||||
|
||||
if (!tok.segs.length) {
|
||||
tok.escaped = true;
|
||||
tok.val = str;
|
||||
return tok;
|
||||
}
|
||||
|
||||
if (opts.optimize === true) {
|
||||
tok.segs = utils.stringifyArray(tok.segs);
|
||||
}
|
||||
|
||||
if (tok.segs === '') {
|
||||
tok.val = str;
|
||||
} else {
|
||||
tok.val = tok.segs[0];
|
||||
}
|
||||
return tok;
|
||||
}
|
||||
} else {
|
||||
tok.val = str;
|
||||
}
|
||||
return tok;
|
||||
};
|
||||
|
||||
/**
|
||||
* Ensure commas inside brackets and parens are not split.
|
||||
* @param {Object} `tok` Token from the `split-string` module
|
||||
* @return {undefined}
|
||||
*/
|
||||
|
||||
utils.escapeBrackets = function(options) {
|
||||
return function(tok) {
|
||||
if (tok.escaped && tok.val === 'b') {
|
||||
tok.val = '\\b';
|
||||
return;
|
||||
}
|
||||
|
||||
if (tok.val !== '(' && tok.val !== '[') return;
|
||||
var opts = utils.extend({}, options);
|
||||
var brackets = [];
|
||||
var parens = [];
|
||||
var stack = [];
|
||||
var val = tok.val;
|
||||
var str = tok.str;
|
||||
var i = tok.idx - 1;
|
||||
|
||||
while (++i < str.length) {
|
||||
var ch = str[i];
|
||||
|
||||
if (ch === '\\') {
|
||||
val += (opts.keepEscaping === false ? '' : ch) + str[++i];
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '(') {
|
||||
parens.push(ch);
|
||||
stack.push(ch);
|
||||
}
|
||||
|
||||
if (ch === '[') {
|
||||
brackets.push(ch);
|
||||
stack.push(ch);
|
||||
}
|
||||
|
||||
if (ch === ')') {
|
||||
parens.pop();
|
||||
stack.pop();
|
||||
if (!stack.length) {
|
||||
val += ch;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (ch === ']') {
|
||||
brackets.pop();
|
||||
stack.pop();
|
||||
if (!stack.length) {
|
||||
val += ch;
|
||||
break;
|
||||
}
|
||||
}
|
||||
val += ch;
|
||||
}
|
||||
|
||||
tok.split = false;
|
||||
tok.val = val.slice(1);
|
||||
tok.idx = i;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns true if the given string looks like a regex quantifier
|
||||
* @return {Boolean}
|
||||
*/
|
||||
|
||||
utils.isQuantifier = function(str) {
|
||||
return /^(?:[0-9]?,[0-9]|[0-9],)$/.test(str);
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast `val` to an array.
|
||||
* @param {*} `val`
|
||||
*/
|
||||
|
||||
utils.stringifyArray = function(arr) {
|
||||
return [utils.arrayify(arr).join('|')];
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast `val` to an array.
|
||||
* @param {*} `val`
|
||||
*/
|
||||
|
||||
utils.arrayify = function(arr) {
|
||||
if (typeof arr === 'undefined') {
|
||||
return [];
|
||||
}
|
||||
if (typeof arr === 'string') {
|
||||
return [arr];
|
||||
}
|
||||
return arr;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns true if the given `str` is a non-empty string
|
||||
* @return {Boolean}
|
||||
*/
|
||||
|
||||
utils.isString = function(str) {
|
||||
return str != null && typeof str === 'string';
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the last element from `array`
|
||||
* @param {Array} `array`
|
||||
* @return {*}
|
||||
*/
|
||||
|
||||
utils.last = function(arr, n) {
|
||||
return arr[arr.length - (n || 1)];
|
||||
};
|
||||
|
||||
utils.escapeRegex = function(str) {
|
||||
return str.replace(/\\?([!^*?()[\]{}+?/])/g, '\\$1');
|
||||
};
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
{
|
||||
"name": "braces",
|
||||
"description": "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.",
|
||||
"version": "2.3.2",
|
||||
"homepage": "https://github.com/micromatch/braces",
|
||||
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
|
||||
"contributors": [
|
||||
"Brian Woodward (https://twitter.com/doowb)",
|
||||
"Elan Shanker (https://github.com/es128)",
|
||||
"Eugene Sharygin (https://github.com/eush77)",
|
||||
"hemanth.hm (http://h3manth.com)",
|
||||
"Jon Schlinkert (http://twitter.com/jonschlinkert)"
|
||||
],
|
||||
"repository": "micromatch/braces",
|
||||
"bugs": {
|
||||
"url": "https://github.com/micromatch/braces/issues"
|
||||
},
|
||||
"license": "MIT",
|
||||
"files": [
|
||||
"index.js",
|
||||
"lib"
|
||||
],
|
||||
"main": "index.js",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "mocha",
|
||||
"benchmark": "node benchmark"
|
||||
},
|
||||
"dependencies": {
|
||||
"arr-flatten": "^1.1.0",
|
||||
"array-unique": "^0.3.2",
|
||||
"extend-shallow": "^2.0.1",
|
||||
"fill-range": "^4.0.0",
|
||||
"isobject": "^3.0.1",
|
||||
"repeat-element": "^1.1.2",
|
||||
"snapdragon": "^0.8.1",
|
||||
"snapdragon-node": "^2.0.1",
|
||||
"split-string": "^3.0.2",
|
||||
"to-regex": "^3.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"ansi-cyan": "^0.1.1",
|
||||
"benchmarked": "^2.0.0",
|
||||
"brace-expansion": "^1.1.8",
|
||||
"cross-spawn": "^5.1.0",
|
||||
"gulp": "^3.9.1",
|
||||
"gulp-eslint": "^4.0.0",
|
||||
"gulp-format-md": "^1.0.0",
|
||||
"gulp-istanbul": "^1.1.2",
|
||||
"gulp-mocha": "^3.0.1",
|
||||
"gulp-unused": "^0.2.1",
|
||||
"is-windows": "^1.0.1",
|
||||
"minimatch": "^3.0.4",
|
||||
"mocha": "^3.2.0",
|
||||
"noncharacters": "^1.1.0",
|
||||
"text-table": "^0.2.0",
|
||||
"time-diff": "^0.3.1",
|
||||
"yargs-parser": "^8.0.0"
|
||||
},
|
||||
"keywords": [
|
||||
"alpha",
|
||||
"alphabetical",
|
||||
"bash",
|
||||
"brace",
|
||||
"braces",
|
||||
"expand",
|
||||
"expansion",
|
||||
"filepath",
|
||||
"fill",
|
||||
"fs",
|
||||
"glob",
|
||||
"globbing",
|
||||
"letter",
|
||||
"match",
|
||||
"matches",
|
||||
"matching",
|
||||
"number",
|
||||
"numerical",
|
||||
"path",
|
||||
"range",
|
||||
"ranges",
|
||||
"sh"
|
||||
],
|
||||
"verb": {
|
||||
"toc": false,
|
||||
"layout": "default",
|
||||
"tasks": [
|
||||
"readme"
|
||||
],
|
||||
"lint": {
|
||||
"reflinks": true
|
||||
},
|
||||
"plugins": [
|
||||
"gulp-format-md"
|
||||
],
|
||||
"related": {
|
||||
"list": [
|
||||
"expand-brackets",
|
||||
"extglob",
|
||||
"fill-range",
|
||||
"micromatch",
|
||||
"nanomatch"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
'use strict';
|
||||
|
||||
function preserveCamelCase(str) {
|
||||
var isLastCharLower = false;
|
||||
|
||||
for (var i = 0; i < str.length; i++) {
|
||||
var c = str.charAt(i);
|
||||
|
||||
if (isLastCharLower && (/[a-zA-Z]/).test(c) && c.toUpperCase() === c) {
|
||||
str = str.substr(0, i) + '-' + str.substr(i);
|
||||
isLastCharLower = false;
|
||||
i++;
|
||||
} else {
|
||||
isLastCharLower = (c.toLowerCase() === c);
|
||||
}
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
module.exports = function () {
|
||||
var str = [].map.call(arguments, function (str) {
|
||||
return str.trim();
|
||||
}).filter(function (str) {
|
||||
return str.length;
|
||||
}).join('-');
|
||||
|
||||
if (!str.length) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (str.length === 1) {
|
||||
return str.toLowerCase();
|
||||
}
|
||||
|
||||
if (!(/[_.\- ]+/).test(str)) {
|
||||
if (str === str.toUpperCase()) {
|
||||
return str.toLowerCase();
|
||||
}
|
||||
|
||||
if (str[0] !== str[0].toLowerCase()) {
|
||||
return str[0].toLowerCase() + str.slice(1);
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
str = preserveCamelCase(str);
|
||||
|
||||
return str
|
||||
.replace(/^[_.\- ]+/, '')
|
||||
.toLowerCase()
|
||||
.replace(/[_.\- ]+(\w|$)/g, function (m, p1) {
|
||||
return p1.toUpperCase();
|
||||
});
|
||||
};
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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.
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "camelcase",
|
||||
"version": "3.0.0",
|
||||
"description": "Convert a dash/dot/underscore/space separated string to camelCase: foo-bar → fooBar",
|
||||
"license": "MIT",
|
||||
"repository": "sindresorhus/camelcase",
|
||||
"author": {
|
||||
"name": "Sindre Sorhus",
|
||||
"email": "sindresorhus@gmail.com",
|
||||
"url": "http://sindresorhus.com"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "xo && ava"
|
||||
},
|
||||
"files": [
|
||||
"index.js"
|
||||
],
|
||||
"keywords": [
|
||||
"camelcase",
|
||||
"camel-case",
|
||||
"camel",
|
||||
"case",
|
||||
"dash",
|
||||
"hyphen",
|
||||
"dot",
|
||||
"underscore",
|
||||
"separator",
|
||||
"string",
|
||||
"text",
|
||||
"convert"
|
||||
],
|
||||
"devDependencies": {
|
||||
"ava": "*",
|
||||
"xo": "*"
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
# camelcase [](https://travis-ci.org/sindresorhus/camelcase)
|
||||
|
||||
> Convert a dash/dot/underscore/space separated string to camelCase: `foo-bar` → `fooBar`
|
||||
|
||||
|
||||
## Install
|
||||
|
||||
```
|
||||
$ npm install --save camelcase
|
||||
```
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
const camelCase = require('camelcase');
|
||||
|
||||
camelCase('foo-bar');
|
||||
//=> 'fooBar'
|
||||
|
||||
camelCase('foo_bar');
|
||||
//=> 'fooBar'
|
||||
|
||||
camelCase('Foo-Bar');
|
||||
//=> 'fooBar'
|
||||
|
||||
camelCase('--foo.bar');
|
||||
//=> 'fooBar'
|
||||
|
||||
camelCase('__foo__bar__');
|
||||
//=> 'fooBar'
|
||||
|
||||
camelCase('foo bar');
|
||||
//=> 'fooBar'
|
||||
|
||||
console.log(process.argv[3]);
|
||||
//=> '--foo-bar'
|
||||
camelCase(process.argv[3]);
|
||||
//=> 'fooBar'
|
||||
|
||||
camelCase('foo', 'bar');
|
||||
//=> 'fooBar'
|
||||
|
||||
camelCase('__foo__', '--bar');
|
||||
//=> 'fooBar'
|
||||
```
|
||||
|
||||
|
||||
## Related
|
||||
|
||||
- [decamelize](https://github.com/sindresorhus/decamelize) - The inverse of this module
|
||||
- [uppercamelcase](https://github.com/SamVerschueren/uppercamelcase) - Like this module, but to PascalCase instead of camelCase
|
||||
|
||||
|
||||
## License
|
||||
|
||||
MIT © [Sindre Sorhus](http://sindresorhus.com)
|
||||
+317
@@ -0,0 +1,317 @@
|
||||
# Chokidar 2.1.5 (Mar 22, 2019)
|
||||
* Revert 2.1.3 atomic writing changes.
|
||||
|
||||
# Chokidar 2.1.4 (Mar 22, 2019)
|
||||
* Improve TypeScript type definitions for `on` method.
|
||||
|
||||
# Chokidar 2.1.3 (Mar 22, 2019)
|
||||
* Improve atomic writes handling
|
||||
|
||||
# Chokidar 2.1.2 (Feb 18, 2019)
|
||||
* Add TypeScript type definitions
|
||||
* More fixes for accessTime behavior (#800)
|
||||
|
||||
# Chokidar 2.1.1 (Feb 8, 2019)
|
||||
* Handle simultaneous change of LastAccessTime and ModifiedTime (#793)
|
||||
|
||||
# Chokidar 2.1.0 (Feb 5, 2019)
|
||||
* Ignore accessTime updates caused by read operations (#762).
|
||||
* Updated dependencies. Removed `lodash.debounce`.
|
||||
|
||||
# Chokidar 2.0.4 (Jun 18, 2018)
|
||||
* Prevent watcher.close() from crashing (#730).
|
||||
|
||||
# Chokidar 2.0.3 (Mar 22, 2018)
|
||||
* Fixes an issue that using fd = 0 is not closed in case
|
||||
Windows is used and a `EPERM` error is triggered.
|
||||
|
||||
# Chokidar 2.0.2 (Feb 14, 2018)
|
||||
* Allow semver range updates for upath dependency
|
||||
|
||||
# Chokidar 2.0.1 (Feb 8, 2018)
|
||||
* Fix #668 glob issue on Windows when using `ignore` and `cwd`. Thanks @remy!
|
||||
* Fix #546 possible uncaught exception when using `awaitWriteFinish`.
|
||||
Thanks @dsagal!
|
||||
|
||||
# Chokidar 2.0.0 (Dec 29, 2017)
|
||||
* Breaking: Upgrade globbing dependencies which require globs to be more strict and always use POSIX-style slashes because Windows-style slashes are used as escape sequences
|
||||
* Update tests to work with upgraded globbing dependencies
|
||||
* Add ability to log FSEvents require error by setting `CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR` env
|
||||
* Fix for handling braces in globs
|
||||
* Add node 8 & 9 to CI configs
|
||||
* Allow node 0.10 failures on Windows
|
||||
|
||||
# Chokidar 1.7.0 (May 8, 2017)
|
||||
* Add `disableGlobbing` option
|
||||
* Add ability to force interval value by setting CHOKIDAR_INTERVAL env
|
||||
variable
|
||||
* Fix issue with `.close()` being called before `ready`
|
||||
|
||||
# Chokidar 1.6.0 (Jun 22, 2016)
|
||||
* Added ability for force `usePolling` mode by setting `CHOKIDAR_USEPOLLING`
|
||||
env variable
|
||||
|
||||
# Chokidar 1.5.2 (Jun 7, 2016)
|
||||
* Fix missing `addDir` events when using `cwd` and `alwaysStat` options
|
||||
* Fix missing `add` events for files within a renamed directory
|
||||
|
||||
# Chokidar 1.5.1 (May 20, 2016)
|
||||
* To help prevent exhaustion of FSEvents system limitations, consolidate watch
|
||||
instances to the common parent upon detection of separate watch instances on
|
||||
many siblings
|
||||
|
||||
# Chokidar 1.5.0 (May 10, 2016)
|
||||
* Make debounce delay setting used with `atomic: true` user-customizable
|
||||
* Fixes and improvements to `awaitWriteFinish` features
|
||||
|
||||
# Chokidar 1.4.3 (Feb 26, 2016)
|
||||
* Update async-each dependency to ^1.0.0
|
||||
|
||||
# Chokidar 1.4.2 (Dec 30, 2015)
|
||||
* Now correctly emitting `stats` with `awaitWriteFinish` option.
|
||||
|
||||
# Chokidar 1.4.1 (Dec 9, 2015)
|
||||
* The watcher could now be correctly subclassed with ES6 class syntax.
|
||||
|
||||
# Chokidar 1.4.0 (Dec 3, 2015)
|
||||
* Add `.getWatched()` method, exposing all file system entries being watched
|
||||
* Apply `awaitWriteFinish` methodology to `change` events (in addition to `add`)
|
||||
* Fix handling of symlinks within glob paths (#293)
|
||||
* Fix `addDir` and `unlinkDir` events under globs (#337, #401)
|
||||
* Fix issues with `.unwatch()` (#374, #403)
|
||||
|
||||
# Chokidar 1.3.0 (Nov 18, 2015)
|
||||
* Improve `awaitWriteFinish` option behavior
|
||||
* Fix some `cwd` option behavior on Windows
|
||||
* `awaitWriteFinish` and `cwd` are now compatible
|
||||
* Fix some race conditions.
|
||||
* #379: Recreating deleted directory doesn't trigger event
|
||||
* When adding a previously-deleted file, emit 'add', not 'change'
|
||||
|
||||
# Chokidar 1.2.0 (Oct 1, 2015)
|
||||
* Allow nested arrays of paths to be provided to `.watch()` and `.add()`
|
||||
* Add `awaitWriteFinish` option
|
||||
|
||||
# Chokidar 1.1.0 (Sep 23, 2015)
|
||||
* Dependency updates including fsevents@1.0.0, improving installation
|
||||
|
||||
# Chokidar 1.0.6 (Sep 18, 2015)
|
||||
* Fix issue with `.unwatch()` method and relative paths
|
||||
|
||||
# Chokidar 1.0.5 (Jul 20, 2015)
|
||||
* Fix regression with regexes/fns using in `ignored`
|
||||
|
||||
# Chokidar 1.0.4 (Jul 15, 2015)
|
||||
* Fix bug with `ignored` files/globs while `cwd` option is set
|
||||
|
||||
# Chokidar 1.0.3 (Jun 4, 2015)
|
||||
* Fix race issue with `alwaysStat` option and removed files
|
||||
|
||||
# Chokidar 1.0.2 (May 30, 2015)
|
||||
* Fix bug with absolute paths and ENAMETOOLONG error
|
||||
|
||||
# Chokidar 1.0.1 (Apr 8, 2015)
|
||||
* Fix bug with `.close()` method in `fs.watch` mode with `persistent: false`
|
||||
option
|
||||
|
||||
# Chokidar 1.0.0 (Apr 7, 2015)
|
||||
* Glob support! Use globs in `watch`, `add`, and `unwatch` methods
|
||||
* Comprehensive symlink support
|
||||
* New `unwatch` method to turn off watching of previously watched paths
|
||||
* More flexible `ignored` option allowing regex, function, glob, or array
|
||||
courtesy of [anymatch](https://github.com/es128/anymatch)
|
||||
* New `cwd` option to set base dir from which relative paths are derived
|
||||
* New `depth` option for limiting recursion
|
||||
* New `alwaysStat` option to ensure
|
||||
[`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) gets passed
|
||||
with every add/change event
|
||||
* New `ready` event emitted when initial fs tree scan is done and watcher is
|
||||
ready for changes
|
||||
* New `raw` event exposing data and events from the lower-level watch modules
|
||||
* New `followSymlinks` option to impact whether symlinks' targets or the symlink
|
||||
files themselves are watched
|
||||
* New `atomic` option for normalizing artifacts from text editors that use
|
||||
atomic write methods
|
||||
* Ensured watcher's stability with lots of bugfixes.
|
||||
|
||||
# Chokidar 0.12.6 (Jan 6, 2015)
|
||||
* Fix bug which breaks `persistent: false` mode when change events occur
|
||||
|
||||
# Chokidar 0.12.5 (Dec 17, 2014)
|
||||
* Fix bug with matching parent path detection for fsevents instance sharing
|
||||
* Fix bug with ignored watch path in nodefs modes
|
||||
|
||||
# Chokidar 0.12.4 (Dec 14, 2014)
|
||||
* Fix bug in `fs.watch` mode that caused watcher to leak into `cwd`
|
||||
* Fix bug preventing ready event when there are symlinks to ignored paths
|
||||
|
||||
# Chokidar 0.12.3 (Dec 13, 2014)
|
||||
* Fix handling of special files such as named pipes and sockets
|
||||
|
||||
# Chokidar 0.12.2 (Dec 12, 2014)
|
||||
* Fix recursive symlink handling and some other path resolution problems
|
||||
|
||||
# Chokidar 0.12.1 (Dec 10, 2014)
|
||||
* Fix a case where file symlinks were not followed properly
|
||||
|
||||
# Chokidar 0.12.0 (Dec 8, 2014)
|
||||
* Symlink support
|
||||
* Add `followSymlinks` option, which defaults to `true`
|
||||
* Change default watch mode on Linux to non-polling `fs.watch`
|
||||
* Add `atomic` option to normalize events from editors using atomic writes
|
||||
* Particularly Vim and Sublime
|
||||
* Add `raw` event which exposes data from the underlying watch method
|
||||
|
||||
# Chokidar 0.11.1 (Nov 19, 2014)
|
||||
* Fix a bug where an error is thrown when `fs.watch` instantiation fails
|
||||
|
||||
# Chokidar 0.11.0 (Nov 16, 2014)
|
||||
* Add a `ready` event, which is emitted after initial file scan completes
|
||||
* Fix issue with options keys passed in defined as `undefined`
|
||||
* Rename some internal `FSWatcher` properties to indicate they're private
|
||||
|
||||
# Chokidar 0.10.9 (Nov 15, 2014)
|
||||
* Fix some leftover issues from adding watcher reuse
|
||||
|
||||
# Chokidar 0.10.8 (Nov 14, 2014)
|
||||
* Remove accidentally committed/published `console.log` statement.
|
||||
* Sry 'bout that :crying_cat_face:
|
||||
|
||||
# Chokidar 0.10.7 (Nov 14, 2014)
|
||||
* Apply watcher reuse methodology to `fs.watch` and `fs.watchFile` as well
|
||||
|
||||
# Chokidar 0.10.6 (Nov 12, 2014)
|
||||
* More efficient creation/reuse of FSEvents instances to avoid system limits
|
||||
* Reduce simultaneous FSEvents instances allowed in a process
|
||||
* Handle errors thrown by `fs.watch` upon invocation
|
||||
|
||||
# Chokidar 0.10.5 (Nov 6, 2014)
|
||||
* Limit number of simultaneous FSEvents instances (fall back to other methods)
|
||||
* Prevent some cases of EMFILE errors during initialization
|
||||
* Fix ignored files emitting events in some fsevents-mode circumstances
|
||||
|
||||
# Chokidar 0.10.4 (Nov 5, 2014)
|
||||
* Bump fsevents dependency to ~0.3.1
|
||||
* Should resolve build warnings and `npm rebuild` on non-Macs
|
||||
|
||||
# Chokidar 0.10.3 (Oct 28, 2014)
|
||||
* Fix removed dir emitting as `unlink` instead of `unlinkDir`
|
||||
* Fix issues with file changing to dir or vice versa (gh-165)
|
||||
* Fix handling of `ignored` option in fsevents mode
|
||||
|
||||
# Chokidar 0.10.2 (Oct 23, 2014)
|
||||
* Improve individual file watching
|
||||
* Fix fsevents keeping process alive when `persistent: false`
|
||||
|
||||
# Chokidar 0.10.1 (19 October 2014)
|
||||
* Improve handling of text editor atomic writes
|
||||
|
||||
# Chokidar 0.10.0 (Oct 18, 2014)
|
||||
* Many stability and consistency improvements
|
||||
* Resolve many cases of duplicate or wrong events
|
||||
* Correct for fsevents inconsistencies
|
||||
* Standardize handling of errors and relative paths
|
||||
* Fix issues with watching `./`
|
||||
|
||||
# Chokidar 0.9.0 (Sep 25, 2014)
|
||||
* Updated fsevents to 0.3
|
||||
* Update per-system defaults
|
||||
* Fix issues with closing chokidar instance
|
||||
* Fix duplicate change events on win32
|
||||
|
||||
# Chokidar 0.8.2 (Mar 26, 2014)
|
||||
* Fixed npm issues related to fsevents dep.
|
||||
* Updated fsevents to 0.2.
|
||||
|
||||
# Chokidar 0.8.1 (Dec 16, 2013)
|
||||
* Optional deps are now truly optional on windows and
|
||||
linux.
|
||||
* Rewritten in JS, again.
|
||||
* Fixed some FSEvents-related bugs.
|
||||
|
||||
# Chokidar 0.8.0 (Nov 29, 2013)
|
||||
* Added ultra-fast low-CPU OS X file watching with FSEvents.
|
||||
It is enabled by default.
|
||||
* Added `addDir` and `unlinkDir` events.
|
||||
* Polling is now disabled by default on all platforms.
|
||||
|
||||
# Chokidar 0.7.1 (Nov 18, 2013)
|
||||
* `Watcher#close` now also removes all event listeners.
|
||||
|
||||
# Chokidar 0.7.0 (Oct 22, 2013)
|
||||
* When `options.ignored` is two-argument function, it will
|
||||
also be called after stating the FS, with `stats` argument.
|
||||
* `unlink` is no longer emitted on directories.
|
||||
|
||||
# Chokidar 0.6.3 (Aug 12, 2013)
|
||||
* Added `usePolling` option (default: `true`).
|
||||
When `false`, chokidar will use `fs.watch` as backend.
|
||||
`fs.watch` is much faster, but not like super reliable.
|
||||
|
||||
# Chokidar 0.6.2 (Mar 19, 2013)
|
||||
* Fixed watching initially empty directories with `ignoreInitial` option.
|
||||
|
||||
# Chokidar 0.6.1 (Mar 19, 2013)
|
||||
* Added node.js 0.10 support.
|
||||
|
||||
# Chokidar 0.6.0 (Mar 10, 2013)
|
||||
* File attributes (stat()) are now passed to `add` and `change` events as second
|
||||
arguments.
|
||||
* Changed default polling interval for binary files to 300ms.
|
||||
|
||||
# Chokidar 0.5.3 (Jan 13, 2013)
|
||||
* Removed emitting of `change` events before `unlink`.
|
||||
|
||||
# Chokidar 0.5.2 (Jan 13, 2013)
|
||||
* Removed postinstall script to prevent various npm bugs.
|
||||
|
||||
# Chokidar 0.5.1 (Jan 6, 2013)
|
||||
* When starting to watch non-existing paths, chokidar will no longer throw
|
||||
ENOENT error.
|
||||
* Fixed bug with absolute path.
|
||||
|
||||
# Chokidar 0.5.0 (Dec 9, 2012)
|
||||
* Added a bunch of new options:
|
||||
* `ignoreInitial` that allows to ignore initial `add` events.
|
||||
* `ignorePermissionErrors` that allows to ignore ENOENT etc perm errors.
|
||||
* `interval` and `binaryInterval` that allow to change default
|
||||
fs polling intervals.
|
||||
|
||||
# Chokidar 0.4.0 (Jul 26, 2012)
|
||||
* Added `all` event that receives two args (event name and path) that combines
|
||||
`add`, `change` and `unlink` events.
|
||||
* Switched to `fs.watchFile` on node.js 0.8 on windows.
|
||||
* Files are now correctly unwatched after unlink.
|
||||
|
||||
# Chokidar 0.3.0 (Jun 24, 2012)
|
||||
* `unlink` event are no longer emitted for directories, for consistency with
|
||||
`add`.
|
||||
|
||||
# Chokidar 0.2.6 (Jun 8, 2012)
|
||||
* Prevented creating of duplicate 'add' events.
|
||||
|
||||
# Chokidar 0.2.5 (Jun 8, 2012)
|
||||
* Fixed a bug when new files in new directories hadn't been added.
|
||||
|
||||
# Chokidar 0.2.4 (Jun 7, 2012)
|
||||
* Fixed a bug when unlinked files emitted events after unlink.
|
||||
|
||||
# Chokidar 0.2.3 (May 12, 2012)
|
||||
* Fixed watching of files on windows.
|
||||
|
||||
# Chokidar 0.2.2 (May 4, 2012)
|
||||
* Fixed watcher signature.
|
||||
|
||||
# Chokidar 0.2.1 (May 4, 2012)
|
||||
* Fixed invalid API bug when using `watch()`.
|
||||
|
||||
# Chokidar 0.2.0 (May 4, 2012)
|
||||
* Rewritten in js.
|
||||
|
||||
# Chokidar 0.1.1 (Apr 26, 2012)
|
||||
* Changed api to `chokidar.watch()`.
|
||||
* Fixed compilation on windows.
|
||||
|
||||
# Chokidar 0.1.0 (Apr 20, 2012)
|
||||
* Initial release, extracted from
|
||||
[Brunch](https://github.com/brunch/brunch/blob/9847a065aea300da99bd0753f90354cde9de1261/src/helpers.coffee#L66)
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
# Chokidar [](https://github.com/paulmillr/chokidar) [](https://github.com/paulmillr/chokidar) [](https://travis-ci.org/paulmillr/chokidar) [](https://ci.appveyor.com/project/paulmillr/chokidar/branch/master) [](https://coveralls.io/r/paulmillr/chokidar)
|
||||
|
||||
> A neat wrapper around node.js fs.watch / fs.watchFile / FSEvents.
|
||||
|
||||
[](https://www.npmjs.com/package/chokidar)
|
||||
|
||||
## Why?
|
||||
Node.js `fs.watch`:
|
||||
|
||||
* Doesn't report filenames on MacOS.
|
||||
* Doesn't report events at all when using editors like Sublime on MacOS.
|
||||
* Often reports events twice.
|
||||
* Emits most changes as `rename`.
|
||||
* Has [a lot of other issues](https://github.com/nodejs/node/search?q=fs.watch&type=Issues)
|
||||
* Does not provide an easy way to recursively watch file trees.
|
||||
|
||||
Node.js `fs.watchFile`:
|
||||
|
||||
* Almost as bad at event handling.
|
||||
* Also does not provide any recursive watching.
|
||||
* Results in high CPU utilization.
|
||||
|
||||
Chokidar resolves these problems.
|
||||
|
||||
Initially made for **[Brunch](http://brunch.io)** (an ultra-swift web app build tool), it is now used in
|
||||
[gulp](https://github.com/gulpjs/gulp/),
|
||||
[karma](http://karma-runner.github.io),
|
||||
[PM2](https://github.com/Unitech/PM2),
|
||||
[browserify](http://browserify.org/),
|
||||
[webpack](http://webpack.github.io/),
|
||||
[BrowserSync](http://www.browsersync.io/),
|
||||
[Microsoft's Visual Studio Code](https://github.com/microsoft/vscode),
|
||||
and [many others](https://www.npmjs.org/browse/depended/chokidar/).
|
||||
It has proven itself in production environments.
|
||||
|
||||
## How?
|
||||
Chokidar does still rely on the Node.js core `fs` module, but when using
|
||||
`fs.watch` and `fs.watchFile` for watching, it normalizes the events it
|
||||
receives, often checking for truth by getting file stats and/or dir contents.
|
||||
|
||||
On MacOS, chokidar by default uses a native extension exposing the Darwin
|
||||
`FSEvents` API. This provides very efficient recursive watching compared with
|
||||
implementations like `kqueue` available on most \*nix platforms. Chokidar still
|
||||
does have to do some work to normalize the events received that way as well.
|
||||
|
||||
On other platforms, the `fs.watch`-based implementation is the default, which
|
||||
avoids polling and keeps CPU usage down. Be advised that chokidar will initiate
|
||||
watchers recursively for everything within scope of the paths that have been
|
||||
specified, so be judicious about not wasting system resources by watching much
|
||||
more than needed.
|
||||
|
||||
## Getting started
|
||||
Install with npm:
|
||||
|
||||
```sh
|
||||
npm install chokidar
|
||||
```
|
||||
|
||||
Then `require` and use it in your code:
|
||||
|
||||
```javascript
|
||||
var chokidar = require('chokidar');
|
||||
|
||||
// One-liner for current directory, ignores .dotfiles
|
||||
chokidar.watch('.', {ignored: /(^|[\/\\])\../}).on('all', (event, path) => {
|
||||
console.log(event, path);
|
||||
});
|
||||
```
|
||||
|
||||
```javascript
|
||||
// Example of a more typical implementation structure:
|
||||
|
||||
// Initialize watcher.
|
||||
var watcher = chokidar.watch('file, dir, glob, or array', {
|
||||
ignored: /(^|[\/\\])\../,
|
||||
persistent: true
|
||||
});
|
||||
|
||||
// Something to use when events are received.
|
||||
var log = console.log.bind(console);
|
||||
// Add event listeners.
|
||||
watcher
|
||||
.on('add', path => log(`File ${path} has been added`))
|
||||
.on('change', path => log(`File ${path} has been changed`))
|
||||
.on('unlink', path => log(`File ${path} has been removed`));
|
||||
|
||||
// More possible events.
|
||||
watcher
|
||||
.on('addDir', path => log(`Directory ${path} has been added`))
|
||||
.on('unlinkDir', path => log(`Directory ${path} has been removed`))
|
||||
.on('error', error => log(`Watcher error: ${error}`))
|
||||
.on('ready', () => log('Initial scan complete. Ready for changes'))
|
||||
.on('raw', (event, path, details) => {
|
||||
log('Raw event info:', event, path, details);
|
||||
});
|
||||
|
||||
// 'add', 'addDir' and 'change' events also receive stat() results as second
|
||||
// argument when available: http://nodejs.org/api/fs.html#fs_class_fs_stats
|
||||
watcher.on('change', (path, stats) => {
|
||||
if (stats) console.log(`File ${path} changed size to ${stats.size}`);
|
||||
});
|
||||
|
||||
// Watch new files.
|
||||
watcher.add('new-file');
|
||||
watcher.add(['new-file-2', 'new-file-3', '**/other-file*']);
|
||||
|
||||
// Get list of actual paths being watched on the filesystem
|
||||
var watchedPaths = watcher.getWatched();
|
||||
|
||||
// Un-watch some files.
|
||||
watcher.unwatch('new-file*');
|
||||
|
||||
// Stop watching.
|
||||
watcher.close();
|
||||
|
||||
// Full list of options. See below for descriptions. (do not use this example)
|
||||
chokidar.watch('file', {
|
||||
persistent: true,
|
||||
|
||||
ignored: '*.txt',
|
||||
ignoreInitial: false,
|
||||
followSymlinks: true,
|
||||
cwd: '.',
|
||||
disableGlobbing: false,
|
||||
|
||||
usePolling: true,
|
||||
interval: 100,
|
||||
binaryInterval: 300,
|
||||
alwaysStat: false,
|
||||
depth: 99,
|
||||
awaitWriteFinish: {
|
||||
stabilityThreshold: 2000,
|
||||
pollInterval: 100
|
||||
},
|
||||
|
||||
ignorePermissionErrors: false,
|
||||
atomic: true // or a custom 'atomicity delay', in milliseconds (default 100)
|
||||
});
|
||||
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
`chokidar.watch(paths, [options])`
|
||||
|
||||
* `paths` (string or array of strings). Paths to files, dirs to be watched
|
||||
recursively, or glob patterns.
|
||||
* `options` (object) Options object as defined below:
|
||||
|
||||
#### Persistence
|
||||
|
||||
* `persistent` (default: `true`). Indicates whether the process
|
||||
should continue to run as long as files are being watched. If set to
|
||||
`false` when using `fsevents` to watch, no more events will be emitted
|
||||
after `ready`, even if the process continues to run.
|
||||
|
||||
#### Path filtering
|
||||
|
||||
* `ignored` ([anymatch](https://github.com/es128/anymatch)-compatible definition)
|
||||
Defines files/paths to be ignored. The whole relative or absolute path is
|
||||
tested, not just filename. If a function with two arguments is provided, it
|
||||
gets called twice per path - once with a single argument (the path), second
|
||||
time with two arguments (the path and the
|
||||
[`fs.Stats`](http://nodejs.org/api/fs.html#fs_class_fs_stats)
|
||||
object of that path).
|
||||
* `ignoreInitial` (default: `false`). If set to `false` then `add`/`addDir` events are also emitted for matching paths while
|
||||
instantiating the watching as chokidar discovers these file paths (before the `ready` event).
|
||||
* `followSymlinks` (default: `true`). When `false`, only the
|
||||
symlinks themselves will be watched for changes instead of following
|
||||
the link references and bubbling events through the link's path.
|
||||
* `cwd` (no default). The base directory from which watch `paths` are to be
|
||||
derived. Paths emitted with events will be relative to this.
|
||||
* `disableGlobbing` (default: `false`). If set to `true` then the strings passed to `.watch()` and `.add()` are treated as
|
||||
literal path names, even if they look like globs.
|
||||
|
||||
#### Performance
|
||||
|
||||
* `usePolling` (default: `false`).
|
||||
Whether to use fs.watchFile (backed by polling), or fs.watch. If polling
|
||||
leads to high CPU utilization, consider setting this to `false`. It is
|
||||
typically necessary to **set this to `true` to successfully watch files over
|
||||
a network**, and it may be necessary to successfully watch files in other
|
||||
non-standard situations. Setting to `true` explicitly on MacOS overrides the
|
||||
`useFsEvents` default. You may also set the CHOKIDAR_USEPOLLING env variable
|
||||
to true (1) or false (0) in order to override this option.
|
||||
* _Polling-specific settings_ (effective when `usePolling: true`)
|
||||
* `interval` (default: `100`). Interval of file system polling. You may also
|
||||
set the CHOKIDAR_INTERVAL env variable to override this option.
|
||||
* `binaryInterval` (default: `300`). Interval of file system
|
||||
polling for binary files.
|
||||
([see list of binary extensions](https://github.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
|
||||
* `useFsEvents` (default: `true` on MacOS). Whether to use the
|
||||
`fsevents` watching interface if available. When set to `true` explicitly
|
||||
and `fsevents` is available this supercedes the `usePolling` setting. When
|
||||
set to `false` on MacOS, `usePolling: true` becomes the default.
|
||||
* `alwaysStat` (default: `false`). If relying upon the
|
||||
[`fs.Stats`](http://nodejs.org/api/fs.html#fs_class_fs_stats)
|
||||
object that may get passed with `add`, `addDir`, and `change` events, set
|
||||
this to `true` to ensure it is provided even in cases where it wasn't
|
||||
already available from the underlying watch events.
|
||||
* `depth` (default: `undefined`). If set, limits how many levels of
|
||||
subdirectories will be traversed.
|
||||
* `awaitWriteFinish` (default: `false`).
|
||||
By default, the `add` event will fire when a file first appears on disk, before
|
||||
the entire file has been written. Furthermore, in some cases some `change`
|
||||
events will be emitted while the file is being written. In some cases,
|
||||
especially when watching for large files there will be a need to wait for the
|
||||
write operation to finish before responding to a file creation or modification.
|
||||
Setting `awaitWriteFinish` to `true` (or a truthy value) will poll file size,
|
||||
holding its `add` and `change` events until the size does not change for a
|
||||
configurable amount of time. The appropriate duration setting is heavily
|
||||
dependent on the OS and hardware. For accurate detection this parameter should
|
||||
be relatively high, making file watching much less responsive.
|
||||
Use with caution.
|
||||
* *`options.awaitWriteFinish` can be set to an object in order to adjust
|
||||
timing params:*
|
||||
* `awaitWriteFinish.stabilityThreshold` (default: 2000). Amount of time in
|
||||
milliseconds for a file size to remain constant before emitting its event.
|
||||
* `awaitWriteFinish.pollInterval` (default: 100). File size polling interval.
|
||||
|
||||
#### Errors
|
||||
* `ignorePermissionErrors` (default: `false`). Indicates whether to watch files
|
||||
that don't have read permissions if possible. If watching fails due to `EPERM`
|
||||
or `EACCES` with this set to `true`, the errors will be suppressed silently.
|
||||
* `atomic` (default: `true` if `useFsEvents` and `usePolling` are `false`).
|
||||
Automatically filters out artifacts that occur when using editors that use
|
||||
"atomic writes" instead of writing directly to the source file. If a file is
|
||||
re-added within 100 ms of being deleted, Chokidar emits a `change` event
|
||||
rather than `unlink` then `add`. If the default of 100 ms does not work well
|
||||
for you, you can override it by setting `atomic` to a custom value, in
|
||||
milliseconds.
|
||||
|
||||
### Methods & Events
|
||||
|
||||
`chokidar.watch()` produces an instance of `FSWatcher`. Methods of `FSWatcher`:
|
||||
|
||||
* `.add(path / paths)`: Add files, directories, or glob patterns for tracking.
|
||||
Takes an array of strings or just one string.
|
||||
* `.on(event, callback)`: Listen for an FS event.
|
||||
Available events: `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `ready`,
|
||||
`raw`, `error`.
|
||||
Additionally `all` is available which gets emitted with the underlying event
|
||||
name and path for every event other than `ready`, `raw`, and `error`.
|
||||
* `.unwatch(path / paths)`: Stop watching files, directories, or glob patterns.
|
||||
Takes an array of strings or just one string.
|
||||
* `.close()`: Removes all listeners from watched files.
|
||||
* `.getWatched()`: Returns an object representing all the paths on the file
|
||||
system being watched by this `FSWatcher` instance. The object's keys are all the
|
||||
directories (using absolute paths unless the `cwd` option was used), and the
|
||||
values are arrays of the names of the items contained in each directory.
|
||||
|
||||
## CLI
|
||||
|
||||
If you need a CLI interface for your file watching, check out
|
||||
[chokidar-cli](https://github.com/kimmobrunfeldt/chokidar-cli), allowing you to
|
||||
execute a command on each change, or get a stdio stream of change events.
|
||||
|
||||
## Install Troubleshooting
|
||||
|
||||
* `npm WARN optional dep failed, continuing fsevents@n.n.n`
|
||||
* This message is normal part of how `npm` handles optional dependencies and is
|
||||
not indicative of a problem. Even if accompanied by other related error messages,
|
||||
Chokidar should function properly.
|
||||
|
||||
* `ERR! stack Error: Python executable "python" is v3.4.1, which is not supported by gyp.`
|
||||
* You should be able to resolve this by installing python 2.7 and running:
|
||||
`npm config set python python2.7`
|
||||
|
||||
* `gyp ERR! stack Error: not found: make`
|
||||
* On Mac, install the XCode command-line tools
|
||||
|
||||
## License
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com) & Elan Shanker
|
||||
|
||||
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.
|
||||
+747
@@ -0,0 +1,747 @@
|
||||
'use strict';
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
var fs = require('fs');
|
||||
var sysPath = require('path');
|
||||
var asyncEach = require('async-each');
|
||||
var anymatch = require('anymatch');
|
||||
var globParent = require('glob-parent');
|
||||
var isGlob = require('is-glob');
|
||||
var isAbsolute = require('path-is-absolute');
|
||||
var inherits = require('inherits');
|
||||
var braces = require('braces');
|
||||
var normalizePath = require('normalize-path');
|
||||
var upath = require('upath');
|
||||
|
||||
var NodeFsHandler = require('./lib/nodefs-handler');
|
||||
var FsEventsHandler = require('./lib/fsevents-handler');
|
||||
|
||||
var arrify = function(value) {
|
||||
if (value == null) return [];
|
||||
return Array.isArray(value) ? value : [value];
|
||||
};
|
||||
|
||||
var flatten = function(list, result) {
|
||||
if (result == null) result = [];
|
||||
list.forEach(function(item) {
|
||||
if (Array.isArray(item)) {
|
||||
flatten(item, result);
|
||||
} else {
|
||||
result.push(item);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
// Little isString util for use in Array#every.
|
||||
var isString = function(thing) {
|
||||
return typeof thing === 'string';
|
||||
};
|
||||
|
||||
// Public: Main class.
|
||||
// Watches files & directories for changes.
|
||||
//
|
||||
// * _opts - object, chokidar options hash
|
||||
//
|
||||
// Emitted events:
|
||||
// `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
|
||||
//
|
||||
// Examples
|
||||
//
|
||||
// var watcher = new FSWatcher()
|
||||
// .add(directories)
|
||||
// .on('add', path => console.log('File', path, 'was added'))
|
||||
// .on('change', path => console.log('File', path, 'was changed'))
|
||||
// .on('unlink', path => console.log('File', path, 'was removed'))
|
||||
// .on('all', (event, path) => console.log(path, ' emitted ', event))
|
||||
//
|
||||
function FSWatcher(_opts) {
|
||||
EventEmitter.call(this);
|
||||
var opts = {};
|
||||
// in case _opts that is passed in is a frozen object
|
||||
if (_opts) for (var opt in _opts) opts[opt] = _opts[opt];
|
||||
this._watched = Object.create(null);
|
||||
this._closers = Object.create(null);
|
||||
this._ignoredPaths = Object.create(null);
|
||||
Object.defineProperty(this, '_globIgnored', {
|
||||
get: function() { return Object.keys(this._ignoredPaths); }
|
||||
});
|
||||
this.closed = false;
|
||||
this._throttled = Object.create(null);
|
||||
this._symlinkPaths = Object.create(null);
|
||||
|
||||
function undef(key) {
|
||||
return opts[key] === undefined;
|
||||
}
|
||||
|
||||
// Set up default options.
|
||||
if (undef('persistent')) opts.persistent = true;
|
||||
if (undef('ignoreInitial')) opts.ignoreInitial = false;
|
||||
if (undef('ignorePermissionErrors')) opts.ignorePermissionErrors = false;
|
||||
if (undef('interval')) opts.interval = 100;
|
||||
if (undef('binaryInterval')) opts.binaryInterval = 300;
|
||||
if (undef('disableGlobbing')) opts.disableGlobbing = false;
|
||||
this.enableBinaryInterval = opts.binaryInterval !== opts.interval;
|
||||
|
||||
// Enable fsevents on OS X when polling isn't explicitly enabled.
|
||||
if (undef('useFsEvents')) opts.useFsEvents = !opts.usePolling;
|
||||
|
||||
// If we can't use fsevents, ensure the options reflect it's disabled.
|
||||
if (!FsEventsHandler.canUse()) opts.useFsEvents = false;
|
||||
|
||||
// Use polling on Mac if not using fsevents.
|
||||
// Other platforms use non-polling fs.watch.
|
||||
if (undef('usePolling') && !opts.useFsEvents) {
|
||||
opts.usePolling = process.platform === 'darwin';
|
||||
}
|
||||
|
||||
// Global override (useful for end-developers that need to force polling for all
|
||||
// instances of chokidar, regardless of usage/dependency depth)
|
||||
var envPoll = process.env.CHOKIDAR_USEPOLLING;
|
||||
if (envPoll !== undefined) {
|
||||
var envLower = envPoll.toLowerCase();
|
||||
|
||||
if (envLower === 'false' || envLower === '0') {
|
||||
opts.usePolling = false;
|
||||
} else if (envLower === 'true' || envLower === '1') {
|
||||
opts.usePolling = true;
|
||||
} else {
|
||||
opts.usePolling = !!envLower
|
||||
}
|
||||
}
|
||||
var envInterval = process.env.CHOKIDAR_INTERVAL;
|
||||
if (envInterval) {
|
||||
opts.interval = parseInt(envInterval);
|
||||
}
|
||||
|
||||
// Editor atomic write normalization enabled by default with fs.watch
|
||||
if (undef('atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
|
||||
if (opts.atomic) this._pendingUnlinks = Object.create(null);
|
||||
|
||||
if (undef('followSymlinks')) opts.followSymlinks = true;
|
||||
|
||||
if (undef('awaitWriteFinish')) opts.awaitWriteFinish = false;
|
||||
if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
|
||||
var awf = opts.awaitWriteFinish;
|
||||
if (awf) {
|
||||
if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
|
||||
if (!awf.pollInterval) awf.pollInterval = 100;
|
||||
|
||||
this._pendingWrites = Object.create(null);
|
||||
}
|
||||
if (opts.ignored) opts.ignored = arrify(opts.ignored);
|
||||
|
||||
this._isntIgnored = function(path, stat) {
|
||||
return !this._isIgnored(path, stat);
|
||||
}.bind(this);
|
||||
|
||||
var readyCalls = 0;
|
||||
this._emitReady = function() {
|
||||
if (++readyCalls >= this._readyCount) {
|
||||
this._emitReady = Function.prototype;
|
||||
this._readyEmitted = true;
|
||||
// use process.nextTick to allow time for listener to be bound
|
||||
process.nextTick(this.emit.bind(this, 'ready'));
|
||||
}
|
||||
}.bind(this);
|
||||
|
||||
this.options = opts;
|
||||
|
||||
// You’re frozen when your heart’s not open.
|
||||
Object.freeze(opts);
|
||||
}
|
||||
|
||||
inherits(FSWatcher, EventEmitter);
|
||||
|
||||
// Common helpers
|
||||
// --------------
|
||||
|
||||
// Private method: Normalize and emit events
|
||||
//
|
||||
// * event - string, type of event
|
||||
// * path - string, file or directory path
|
||||
// * val[1..3] - arguments to be passed with event
|
||||
//
|
||||
// Returns the error if defined, otherwise the value of the
|
||||
// FSWatcher instance's `closed` flag
|
||||
FSWatcher.prototype._emit = function(event, path, val1, val2, val3) {
|
||||
if (this.options.cwd) path = sysPath.relative(this.options.cwd, path);
|
||||
var args = [event, path];
|
||||
if (val3 !== undefined) args.push(val1, val2, val3);
|
||||
else if (val2 !== undefined) args.push(val1, val2);
|
||||
else if (val1 !== undefined) args.push(val1);
|
||||
|
||||
var awf = this.options.awaitWriteFinish;
|
||||
if (awf && this._pendingWrites[path]) {
|
||||
this._pendingWrites[path].lastChange = new Date();
|
||||
return this;
|
||||
}
|
||||
|
||||
if (this.options.atomic) {
|
||||
if (event === 'unlink') {
|
||||
this._pendingUnlinks[path] = args;
|
||||
setTimeout(function() {
|
||||
Object.keys(this._pendingUnlinks).forEach(function(path) {
|
||||
this.emit.apply(this, this._pendingUnlinks[path]);
|
||||
this.emit.apply(this, ['all'].concat(this._pendingUnlinks[path]));
|
||||
delete this._pendingUnlinks[path];
|
||||
}.bind(this));
|
||||
}.bind(this), typeof this.options.atomic === "number"
|
||||
? this.options.atomic
|
||||
: 100);
|
||||
return this;
|
||||
} else if (event === 'add' && this._pendingUnlinks[path]) {
|
||||
event = args[0] = 'change';
|
||||
delete this._pendingUnlinks[path];
|
||||
}
|
||||
}
|
||||
|
||||
var emitEvent = function() {
|
||||
this.emit.apply(this, args);
|
||||
if (event !== 'error') this.emit.apply(this, ['all'].concat(args));
|
||||
}.bind(this);
|
||||
|
||||
if (awf && (event === 'add' || event === 'change') && this._readyEmitted) {
|
||||
var awfEmit = function(err, stats) {
|
||||
if (err) {
|
||||
event = args[0] = 'error';
|
||||
args[1] = err;
|
||||
emitEvent();
|
||||
} else if (stats) {
|
||||
// if stats doesn't exist the file must have been deleted
|
||||
if (args.length > 2) {
|
||||
args[2] = stats;
|
||||
} else {
|
||||
args.push(stats);
|
||||
}
|
||||
emitEvent();
|
||||
}
|
||||
};
|
||||
|
||||
this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
|
||||
return this;
|
||||
}
|
||||
|
||||
if (event === 'change') {
|
||||
if (!this._throttle('change', path, 50)) return this;
|
||||
}
|
||||
|
||||
if (
|
||||
this.options.alwaysStat && val1 === undefined &&
|
||||
(event === 'add' || event === 'addDir' || event === 'change')
|
||||
) {
|
||||
var fullPath = this.options.cwd ? sysPath.join(this.options.cwd, path) : path;
|
||||
fs.stat(fullPath, function(error, stats) {
|
||||
// Suppress event when fs.stat fails, to avoid sending undefined 'stat'
|
||||
if (error || !stats) return;
|
||||
|
||||
args.push(stats);
|
||||
emitEvent();
|
||||
});
|
||||
} else {
|
||||
emitEvent();
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
// Private method: Common handler for errors
|
||||
//
|
||||
// * error - object, Error instance
|
||||
//
|
||||
// Returns the error if defined, otherwise the value of the
|
||||
// FSWatcher instance's `closed` flag
|
||||
FSWatcher.prototype._handleError = function(error) {
|
||||
var code = error && error.code;
|
||||
var ipe = this.options.ignorePermissionErrors;
|
||||
if (error &&
|
||||
code !== 'ENOENT' &&
|
||||
code !== 'ENOTDIR' &&
|
||||
(!ipe || (code !== 'EPERM' && code !== 'EACCES'))
|
||||
) this.emit('error', error);
|
||||
return error || this.closed;
|
||||
};
|
||||
|
||||
// Private method: Helper utility for throttling
|
||||
//
|
||||
// * action - string, type of action being throttled
|
||||
// * path - string, path being acted upon
|
||||
// * timeout - int, duration of time to suppress duplicate actions
|
||||
//
|
||||
// Returns throttle tracking object or false if action should be suppressed
|
||||
FSWatcher.prototype._throttle = function(action, path, timeout) {
|
||||
if (!(action in this._throttled)) {
|
||||
this._throttled[action] = Object.create(null);
|
||||
}
|
||||
var throttled = this._throttled[action];
|
||||
if (path in throttled) {
|
||||
throttled[path].count++;
|
||||
return false;
|
||||
}
|
||||
function clear() {
|
||||
var count = throttled[path] ? throttled[path].count : 0;
|
||||
delete throttled[path];
|
||||
clearTimeout(timeoutObject);
|
||||
return count;
|
||||
}
|
||||
var timeoutObject = setTimeout(clear, timeout);
|
||||
throttled[path] = {timeoutObject: timeoutObject, clear: clear, count: 0};
|
||||
return throttled[path];
|
||||
};
|
||||
|
||||
// Private method: Awaits write operation to finish
|
||||
//
|
||||
// * path - string, path being acted upon
|
||||
// * threshold - int, time in milliseconds a file size must be fixed before
|
||||
// acknowledging write operation is finished
|
||||
// * awfEmit - function, to be called when ready for event to be emitted
|
||||
// Polls a newly created file for size variations. When files size does not
|
||||
// change for 'threshold' milliseconds calls callback.
|
||||
FSWatcher.prototype._awaitWriteFinish = function(path, threshold, event, awfEmit) {
|
||||
var timeoutHandler;
|
||||
|
||||
var fullPath = path;
|
||||
if (this.options.cwd && !isAbsolute(path)) {
|
||||
fullPath = sysPath.join(this.options.cwd, path);
|
||||
}
|
||||
|
||||
var now = new Date();
|
||||
|
||||
var awaitWriteFinish = (function (prevStat) {
|
||||
fs.stat(fullPath, function(err, curStat) {
|
||||
if (err || !(path in this._pendingWrites)) {
|
||||
if (err && err.code !== 'ENOENT') awfEmit(err);
|
||||
return;
|
||||
}
|
||||
|
||||
var now = new Date();
|
||||
|
||||
if (prevStat && curStat.size != prevStat.size) {
|
||||
this._pendingWrites[path].lastChange = now;
|
||||
}
|
||||
|
||||
if (now - this._pendingWrites[path].lastChange >= threshold) {
|
||||
delete this._pendingWrites[path];
|
||||
awfEmit(null, curStat);
|
||||
} else {
|
||||
timeoutHandler = setTimeout(
|
||||
awaitWriteFinish.bind(this, curStat),
|
||||
this.options.awaitWriteFinish.pollInterval
|
||||
);
|
||||
}
|
||||
}.bind(this));
|
||||
}.bind(this));
|
||||
|
||||
if (!(path in this._pendingWrites)) {
|
||||
this._pendingWrites[path] = {
|
||||
lastChange: now,
|
||||
cancelWait: function() {
|
||||
delete this._pendingWrites[path];
|
||||
clearTimeout(timeoutHandler);
|
||||
return event;
|
||||
}.bind(this)
|
||||
};
|
||||
timeoutHandler = setTimeout(
|
||||
awaitWriteFinish.bind(this),
|
||||
this.options.awaitWriteFinish.pollInterval
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Private method: Determines whether user has asked to ignore this path
|
||||
//
|
||||
// * path - string, path to file or directory
|
||||
// * stats - object, result of fs.stat
|
||||
//
|
||||
// Returns boolean
|
||||
var dotRe = /\..*\.(sw[px])$|\~$|\.subl.*\.tmp/;
|
||||
FSWatcher.prototype._isIgnored = function(path, stats) {
|
||||
if (this.options.atomic && dotRe.test(path)) return true;
|
||||
|
||||
if (!this._userIgnored) {
|
||||
var cwd = this.options.cwd;
|
||||
var ignored = this.options.ignored;
|
||||
if (cwd && ignored) {
|
||||
ignored = ignored.map(function (path) {
|
||||
if (typeof path !== 'string') return path;
|
||||
return upath.normalize(isAbsolute(path) ? path : sysPath.join(cwd, path));
|
||||
});
|
||||
}
|
||||
var paths = arrify(ignored)
|
||||
.filter(function(path) {
|
||||
return typeof path === 'string' && !isGlob(path);
|
||||
}).map(function(path) {
|
||||
return path + '/**';
|
||||
});
|
||||
this._userIgnored = anymatch(
|
||||
this._globIgnored.concat(ignored).concat(paths)
|
||||
);
|
||||
}
|
||||
|
||||
return this._userIgnored([path, stats]);
|
||||
};
|
||||
|
||||
// Private method: Provides a set of common helpers and properties relating to
|
||||
// symlink and glob handling
|
||||
//
|
||||
// * path - string, file, directory, or glob pattern being watched
|
||||
// * depth - int, at any depth > 0, this isn't a glob
|
||||
//
|
||||
// Returns object containing helpers for this path
|
||||
var replacerRe = /^\.[\/\\]/;
|
||||
FSWatcher.prototype._getWatchHelpers = function(path, depth) {
|
||||
path = path.replace(replacerRe, '');
|
||||
var watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
|
||||
var fullWatchPath = sysPath.resolve(watchPath);
|
||||
var hasGlob = watchPath !== path;
|
||||
var globFilter = hasGlob ? anymatch(path) : false;
|
||||
var follow = this.options.followSymlinks;
|
||||
var globSymlink = hasGlob && follow ? null : false;
|
||||
|
||||
var checkGlobSymlink = function(entry) {
|
||||
// only need to resolve once
|
||||
// first entry should always have entry.parentDir === ''
|
||||
if (globSymlink == null) {
|
||||
globSymlink = entry.fullParentDir === fullWatchPath ? false : {
|
||||
realPath: entry.fullParentDir,
|
||||
linkPath: fullWatchPath
|
||||
};
|
||||
}
|
||||
|
||||
if (globSymlink) {
|
||||
return entry.fullPath.replace(globSymlink.realPath, globSymlink.linkPath);
|
||||
}
|
||||
|
||||
return entry.fullPath;
|
||||
};
|
||||
|
||||
var entryPath = function(entry) {
|
||||
return sysPath.join(watchPath,
|
||||
sysPath.relative(watchPath, checkGlobSymlink(entry))
|
||||
);
|
||||
};
|
||||
|
||||
var filterPath = function(entry) {
|
||||
if (entry.stat && entry.stat.isSymbolicLink()) return filterDir(entry);
|
||||
var resolvedPath = entryPath(entry);
|
||||
return (!hasGlob || globFilter(resolvedPath)) &&
|
||||
this._isntIgnored(resolvedPath, entry.stat) &&
|
||||
(this.options.ignorePermissionErrors ||
|
||||
this._hasReadPermissions(entry.stat));
|
||||
}.bind(this);
|
||||
|
||||
var getDirParts = function(path) {
|
||||
if (!hasGlob) return false;
|
||||
var parts = [];
|
||||
var expandedPath = braces.expand(path);
|
||||
expandedPath.forEach(function(path) {
|
||||
parts.push(sysPath.relative(watchPath, path).split(/[\/\\]/));
|
||||
});
|
||||
return parts;
|
||||
};
|
||||
|
||||
var dirParts = getDirParts(path);
|
||||
if (dirParts) {
|
||||
dirParts.forEach(function(parts) {
|
||||
if (parts.length > 1) parts.pop();
|
||||
});
|
||||
}
|
||||
var unmatchedGlob;
|
||||
|
||||
var filterDir = function(entry) {
|
||||
if (hasGlob) {
|
||||
var entryParts = getDirParts(checkGlobSymlink(entry));
|
||||
var globstar = false;
|
||||
unmatchedGlob = !dirParts.some(function(parts) {
|
||||
return parts.every(function(part, i) {
|
||||
if (part === '**') globstar = true;
|
||||
return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i]);
|
||||
});
|
||||
});
|
||||
}
|
||||
return !unmatchedGlob && this._isntIgnored(entryPath(entry), entry.stat);
|
||||
}.bind(this);
|
||||
|
||||
return {
|
||||
followSymlinks: follow,
|
||||
statMethod: follow ? 'stat' : 'lstat',
|
||||
path: path,
|
||||
watchPath: watchPath,
|
||||
entryPath: entryPath,
|
||||
hasGlob: hasGlob,
|
||||
globFilter: globFilter,
|
||||
filterPath: filterPath,
|
||||
filterDir: filterDir
|
||||
};
|
||||
};
|
||||
|
||||
// Directory helpers
|
||||
// -----------------
|
||||
|
||||
// Private method: Provides directory tracking objects
|
||||
//
|
||||
// * directory - string, path of the directory
|
||||
//
|
||||
// Returns the directory's tracking object
|
||||
FSWatcher.prototype._getWatchedDir = function(directory) {
|
||||
var dir = sysPath.resolve(directory);
|
||||
var watcherRemove = this._remove.bind(this);
|
||||
if (!(dir in this._watched)) this._watched[dir] = {
|
||||
_items: Object.create(null),
|
||||
add: function(item) {
|
||||
if (item !== '.' && item !== '..') this._items[item] = true;
|
||||
},
|
||||
remove: function(item) {
|
||||
delete this._items[item];
|
||||
if (!this.children().length) {
|
||||
fs.readdir(dir, function(err) {
|
||||
if (err) watcherRemove(sysPath.dirname(dir), sysPath.basename(dir));
|
||||
});
|
||||
}
|
||||
},
|
||||
has: function(item) {return item in this._items;},
|
||||
children: function() {return Object.keys(this._items);}
|
||||
};
|
||||
return this._watched[dir];
|
||||
};
|
||||
|
||||
// File helpers
|
||||
// ------------
|
||||
|
||||
// Private method: Check for read permissions
|
||||
// Based on this answer on SO: http://stackoverflow.com/a/11781404/1358405
|
||||
//
|
||||
// * stats - object, result of fs.stat
|
||||
//
|
||||
// Returns boolean
|
||||
FSWatcher.prototype._hasReadPermissions = function(stats) {
|
||||
return Boolean(4 & parseInt(((stats && stats.mode) & 0x1ff).toString(8)[0], 10));
|
||||
};
|
||||
|
||||
// Private method: Handles emitting unlink events for
|
||||
// files and directories, and via recursion, for
|
||||
// files and directories within directories that are unlinked
|
||||
//
|
||||
// * directory - string, directory within which the following item is located
|
||||
// * item - string, base path of item/directory
|
||||
//
|
||||
// Returns nothing
|
||||
FSWatcher.prototype._remove = function(directory, item) {
|
||||
// if what is being deleted is a directory, get that directory's paths
|
||||
// for recursive deleting and cleaning of watched object
|
||||
// if it is not a directory, nestedDirectoryChildren will be empty array
|
||||
var path = sysPath.join(directory, item);
|
||||
var fullPath = sysPath.resolve(path);
|
||||
var isDirectory = this._watched[path] || this._watched[fullPath];
|
||||
|
||||
// prevent duplicate handling in case of arriving here nearly simultaneously
|
||||
// via multiple paths (such as _handleFile and _handleDir)
|
||||
if (!this._throttle('remove', path, 100)) return;
|
||||
|
||||
// if the only watched file is removed, watch for its return
|
||||
var watchedDirs = Object.keys(this._watched);
|
||||
if (!isDirectory && !this.options.useFsEvents && watchedDirs.length === 1) {
|
||||
this.add(directory, item, true);
|
||||
}
|
||||
|
||||
// This will create a new entry in the watched object in either case
|
||||
// so we got to do the directory check beforehand
|
||||
var nestedDirectoryChildren = this._getWatchedDir(path).children();
|
||||
|
||||
// Recursively remove children directories / files.
|
||||
nestedDirectoryChildren.forEach(function(nestedItem) {
|
||||
this._remove(path, nestedItem);
|
||||
}, this);
|
||||
|
||||
// Check if item was on the watched list and remove it
|
||||
var parent = this._getWatchedDir(directory);
|
||||
var wasTracked = parent.has(item);
|
||||
parent.remove(item);
|
||||
|
||||
// If we wait for this file to be fully written, cancel the wait.
|
||||
var relPath = path;
|
||||
if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
|
||||
if (this.options.awaitWriteFinish && this._pendingWrites[relPath]) {
|
||||
var event = this._pendingWrites[relPath].cancelWait();
|
||||
if (event === 'add') return;
|
||||
}
|
||||
|
||||
// The Entry will either be a directory that just got removed
|
||||
// or a bogus entry to a file, in either case we have to remove it
|
||||
delete this._watched[path];
|
||||
delete this._watched[fullPath];
|
||||
var eventName = isDirectory ? 'unlinkDir' : 'unlink';
|
||||
if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
|
||||
|
||||
// Avoid conflicts if we later create another file with the same name
|
||||
if (!this.options.useFsEvents) {
|
||||
this._closePath(path);
|
||||
}
|
||||
};
|
||||
|
||||
FSWatcher.prototype._closePath = function(path) {
|
||||
if (!this._closers[path]) return;
|
||||
this._closers[path].forEach(function(closer) {
|
||||
closer();
|
||||
});
|
||||
delete this._closers[path];
|
||||
this._getWatchedDir(sysPath.dirname(path)).remove(sysPath.basename(path));
|
||||
}
|
||||
|
||||
// Public method: Adds paths to be watched on an existing FSWatcher instance
|
||||
|
||||
// * paths - string or array of strings, file/directory paths and/or globs
|
||||
// * _origAdd - private boolean, for handling non-existent paths to be watched
|
||||
// * _internal - private boolean, indicates a non-user add
|
||||
|
||||
// Returns an instance of FSWatcher for chaining.
|
||||
FSWatcher.prototype.add = function(paths, _origAdd, _internal) {
|
||||
var disableGlobbing = this.options.disableGlobbing;
|
||||
var cwd = this.options.cwd;
|
||||
this.closed = false;
|
||||
paths = flatten(arrify(paths));
|
||||
|
||||
if (!paths.every(isString)) {
|
||||
throw new TypeError('Non-string provided as watch path: ' + paths);
|
||||
}
|
||||
|
||||
if (cwd) paths = paths.map(function(path) {
|
||||
var absPath;
|
||||
if (isAbsolute(path)) {
|
||||
absPath = path;
|
||||
} else if (path[0] === '!') {
|
||||
absPath = '!' + sysPath.join(cwd, path.substring(1));
|
||||
} else {
|
||||
absPath = sysPath.join(cwd, path);
|
||||
}
|
||||
|
||||
// Check `path` instead of `absPath` because the cwd portion can't be a glob
|
||||
if (disableGlobbing || !isGlob(path)) {
|
||||
return absPath;
|
||||
} else {
|
||||
return normalizePath(absPath);
|
||||
}
|
||||
});
|
||||
|
||||
// set aside negated glob strings
|
||||
paths = paths.filter(function(path) {
|
||||
if (path[0] === '!') {
|
||||
this._ignoredPaths[path.substring(1)] = true;
|
||||
} else {
|
||||
// if a path is being added that was previously ignored, stop ignoring it
|
||||
delete this._ignoredPaths[path];
|
||||
delete this._ignoredPaths[path + '/**'];
|
||||
|
||||
// reset the cached userIgnored anymatch fn
|
||||
// to make ignoredPaths changes effective
|
||||
this._userIgnored = null;
|
||||
|
||||
return true;
|
||||
}
|
||||
}, this);
|
||||
|
||||
if (this.options.useFsEvents && FsEventsHandler.canUse()) {
|
||||
if (!this._readyCount) this._readyCount = paths.length;
|
||||
if (this.options.persistent) this._readyCount *= 2;
|
||||
paths.forEach(this._addToFsEvents, this);
|
||||
} else {
|
||||
if (!this._readyCount) this._readyCount = 0;
|
||||
this._readyCount += paths.length;
|
||||
asyncEach(paths, function(path, next) {
|
||||
this._addToNodeFs(path, !_internal, 0, 0, _origAdd, function(err, res) {
|
||||
if (res) this._emitReady();
|
||||
next(err, res);
|
||||
}.bind(this));
|
||||
}.bind(this), function(error, results) {
|
||||
results.forEach(function(item) {
|
||||
if (!item || this.closed) return;
|
||||
this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
|
||||
}, this);
|
||||
}.bind(this));
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
// Public method: Close watchers or start ignoring events from specified paths.
|
||||
|
||||
// * paths - string or array of strings, file/directory paths and/or globs
|
||||
|
||||
// Returns instance of FSWatcher for chaining.
|
||||
FSWatcher.prototype.unwatch = function(paths) {
|
||||
if (this.closed) return this;
|
||||
paths = flatten(arrify(paths));
|
||||
|
||||
paths.forEach(function(path) {
|
||||
// convert to absolute path unless relative path already matches
|
||||
if (!isAbsolute(path) && !this._closers[path]) {
|
||||
if (this.options.cwd) path = sysPath.join(this.options.cwd, path);
|
||||
path = sysPath.resolve(path);
|
||||
}
|
||||
|
||||
this._closePath(path);
|
||||
|
||||
this._ignoredPaths[path] = true;
|
||||
if (path in this._watched) {
|
||||
this._ignoredPaths[path + '/**'] = true;
|
||||
}
|
||||
|
||||
// reset the cached userIgnored anymatch fn
|
||||
// to make ignoredPaths changes effective
|
||||
this._userIgnored = null;
|
||||
}, this);
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
// Public method: Close watchers and remove all listeners from watched paths.
|
||||
|
||||
// Returns instance of FSWatcher for chaining.
|
||||
FSWatcher.prototype.close = function() {
|
||||
if (this.closed) return this;
|
||||
|
||||
this.closed = true;
|
||||
Object.keys(this._closers).forEach(function(watchPath) {
|
||||
this._closers[watchPath].forEach(function(closer) {
|
||||
closer();
|
||||
});
|
||||
delete this._closers[watchPath];
|
||||
}, this);
|
||||
this._watched = Object.create(null);
|
||||
|
||||
this.removeAllListeners();
|
||||
return this;
|
||||
};
|
||||
|
||||
// Public method: Expose list of watched paths
|
||||
|
||||
// Returns object w/ dir paths as keys and arrays of contained paths as values.
|
||||
FSWatcher.prototype.getWatched = function() {
|
||||
var watchList = {};
|
||||
Object.keys(this._watched).forEach(function(dir) {
|
||||
var key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
|
||||
watchList[key || '.'] = Object.keys(this._watched[dir]._items).sort();
|
||||
}.bind(this));
|
||||
return watchList;
|
||||
};
|
||||
|
||||
// Attach watch handler prototype methods
|
||||
function importHandler(handler) {
|
||||
Object.keys(handler.prototype).forEach(function(method) {
|
||||
FSWatcher.prototype[method] = handler.prototype[method];
|
||||
});
|
||||
}
|
||||
importHandler(NodeFsHandler);
|
||||
if (FsEventsHandler.canUse()) importHandler(FsEventsHandler);
|
||||
|
||||
// Export FSWatcher class
|
||||
exports.FSWatcher = FSWatcher;
|
||||
|
||||
// Public function: Instantiates watcher with paths to be tracked.
|
||||
|
||||
// * paths - string or array of strings, file/directory paths and/or globs
|
||||
// * options - object, chokidar options
|
||||
|
||||
// Returns an instance of FSWatcher for chaining.
|
||||
exports.watch = function(paths, options) {
|
||||
return new FSWatcher(options).add(paths);
|
||||
};
|
||||
+412
@@ -0,0 +1,412 @@
|
||||
'use strict';
|
||||
|
||||
var fs = require('fs');
|
||||
var sysPath = require('path');
|
||||
var readdirp = require('readdirp');
|
||||
var fsevents;
|
||||
try { fsevents = require('fsevents'); } catch (error) {
|
||||
if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error)
|
||||
}
|
||||
|
||||
// fsevents instance helper functions
|
||||
|
||||
// object to hold per-process fsevents instances
|
||||
// (may be shared across chokidar FSWatcher instances)
|
||||
var FSEventsWatchers = Object.create(null);
|
||||
|
||||
// Threshold of duplicate path prefixes at which to start
|
||||
// consolidating going forward
|
||||
var consolidateThreshhold = 10;
|
||||
|
||||
// Private function: Instantiates the fsevents interface
|
||||
|
||||
// * path - string, path to be watched
|
||||
// * callback - function, called when fsevents is bound and ready
|
||||
|
||||
// Returns new fsevents instance
|
||||
function createFSEventsInstance(path, callback) {
|
||||
return (new fsevents(path)).on('fsevent', callback).start();
|
||||
}
|
||||
|
||||
// Private function: Instantiates the fsevents interface or binds listeners
|
||||
// to an existing one covering the same file tree
|
||||
|
||||
// * path - string, path to be watched
|
||||
// * realPath - string, real path (in case of symlinks)
|
||||
// * listener - function, called when fsevents emits events
|
||||
// * rawEmitter - function, passes data to listeners of the 'raw' event
|
||||
|
||||
// Returns close function
|
||||
function setFSEventsListener(path, realPath, listener, rawEmitter) {
|
||||
var watchPath = sysPath.extname(path) ? sysPath.dirname(path) : path;
|
||||
var watchContainer;
|
||||
var parentPath = sysPath.dirname(watchPath);
|
||||
|
||||
// If we've accumulated a substantial number of paths that
|
||||
// could have been consolidated by watching one directory
|
||||
// above the current one, create a watcher on the parent
|
||||
// path instead, so that we do consolidate going forward.
|
||||
if (couldConsolidate(parentPath)) {
|
||||
watchPath = parentPath;
|
||||
}
|
||||
|
||||
var resolvedPath = sysPath.resolve(path);
|
||||
var hasSymlink = resolvedPath !== realPath;
|
||||
function filteredListener(fullPath, flags, info) {
|
||||
if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
|
||||
if (
|
||||
fullPath === resolvedPath ||
|
||||
!fullPath.indexOf(resolvedPath + sysPath.sep)
|
||||
) listener(fullPath, flags, info);
|
||||
}
|
||||
|
||||
// check if there is already a watcher on a parent path
|
||||
// modifies `watchPath` to the parent path when it finds a match
|
||||
function watchedParent() {
|
||||
return Object.keys(FSEventsWatchers).some(function(watchedPath) {
|
||||
// condition is met when indexOf returns 0
|
||||
if (!realPath.indexOf(sysPath.resolve(watchedPath) + sysPath.sep)) {
|
||||
watchPath = watchedPath;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (watchPath in FSEventsWatchers || watchedParent()) {
|
||||
watchContainer = FSEventsWatchers[watchPath];
|
||||
watchContainer.listeners.push(filteredListener);
|
||||
} else {
|
||||
watchContainer = FSEventsWatchers[watchPath] = {
|
||||
listeners: [filteredListener],
|
||||
rawEmitters: [rawEmitter],
|
||||
watcher: createFSEventsInstance(watchPath, function(fullPath, flags) {
|
||||
var info = fsevents.getInfo(fullPath, flags);
|
||||
watchContainer.listeners.forEach(function(listener) {
|
||||
listener(fullPath, flags, info);
|
||||
});
|
||||
watchContainer.rawEmitters.forEach(function(emitter) {
|
||||
emitter(info.event, fullPath, info);
|
||||
});
|
||||
})
|
||||
};
|
||||
}
|
||||
var listenerIndex = watchContainer.listeners.length - 1;
|
||||
|
||||
// removes this instance's listeners and closes the underlying fsevents
|
||||
// instance if there are no more listeners left
|
||||
return function close() {
|
||||
delete watchContainer.listeners[listenerIndex];
|
||||
delete watchContainer.rawEmitters[listenerIndex];
|
||||
if (!Object.keys(watchContainer.listeners).length) {
|
||||
watchContainer.watcher.stop();
|
||||
delete FSEventsWatchers[watchPath];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Decide whether or not we should start a new higher-level
|
||||
// parent watcher
|
||||
function couldConsolidate(path) {
|
||||
var keys = Object.keys(FSEventsWatchers);
|
||||
var count = 0;
|
||||
|
||||
for (var i = 0, len = keys.length; i < len; ++i) {
|
||||
var watchPath = keys[i];
|
||||
if (watchPath.indexOf(path) === 0) {
|
||||
count++;
|
||||
if (count >= consolidateThreshhold) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function isConstructor(obj) {
|
||||
return obj.prototype !== undefined && obj.prototype.constructor !== undefined;
|
||||
}
|
||||
|
||||
// returns boolean indicating whether fsevents can be used
|
||||
function canUse() {
|
||||
return fsevents && Object.keys(FSEventsWatchers).length < 128 && isConstructor(fsevents);
|
||||
}
|
||||
|
||||
// determines subdirectory traversal levels from root to path
|
||||
function depth(path, root) {
|
||||
var i = 0;
|
||||
while (!path.indexOf(root) && (path = sysPath.dirname(path)) !== root) i++;
|
||||
return i;
|
||||
}
|
||||
|
||||
// fake constructor for attaching fsevents-specific prototype methods that
|
||||
// will be copied to FSWatcher's prototype
|
||||
function FsEventsHandler() {}
|
||||
|
||||
// Private method: Handle symlinks encountered during directory scan
|
||||
|
||||
// * watchPath - string, file/dir path to be watched with fsevents
|
||||
// * realPath - string, real path (in case of symlinks)
|
||||
// * transform - function, path transformer
|
||||
// * globFilter - function, path filter in case a glob pattern was provided
|
||||
|
||||
// Returns close function for the watcher instance
|
||||
FsEventsHandler.prototype._watchWithFsEvents =
|
||||
function(watchPath, realPath, transform, globFilter) {
|
||||
if (this._isIgnored(watchPath)) return;
|
||||
var watchCallback = function(fullPath, flags, info) {
|
||||
if (
|
||||
this.options.depth !== undefined &&
|
||||
depth(fullPath, realPath) > this.options.depth
|
||||
) return;
|
||||
var path = transform(sysPath.join(
|
||||
watchPath, sysPath.relative(watchPath, fullPath)
|
||||
));
|
||||
if (globFilter && !globFilter(path)) return;
|
||||
// ensure directories are tracked
|
||||
var parent = sysPath.dirname(path);
|
||||
var item = sysPath.basename(path);
|
||||
var watchedDir = this._getWatchedDir(
|
||||
info.type === 'directory' ? path : parent
|
||||
);
|
||||
var checkIgnored = function(stats) {
|
||||
if (this._isIgnored(path, stats)) {
|
||||
this._ignoredPaths[path] = true;
|
||||
if (stats && stats.isDirectory()) {
|
||||
this._ignoredPaths[path + '/**/*'] = true;
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
delete this._ignoredPaths[path];
|
||||
delete this._ignoredPaths[path + '/**/*'];
|
||||
}
|
||||
}.bind(this);
|
||||
|
||||
var handleEvent = function(event) {
|
||||
if (checkIgnored()) return;
|
||||
|
||||
if (event === 'unlink') {
|
||||
// suppress unlink events on never before seen files
|
||||
if (info.type === 'directory' || watchedDir.has(item)) {
|
||||
this._remove(parent, item);
|
||||
}
|
||||
} else {
|
||||
if (event === 'add') {
|
||||
// track new directories
|
||||
if (info.type === 'directory') this._getWatchedDir(path);
|
||||
|
||||
if (info.type === 'symlink' && this.options.followSymlinks) {
|
||||
// push symlinks back to the top of the stack to get handled
|
||||
var curDepth = this.options.depth === undefined ?
|
||||
undefined : depth(fullPath, realPath) + 1;
|
||||
return this._addToFsEvents(path, false, true, curDepth);
|
||||
} else {
|
||||
// track new paths
|
||||
// (other than symlinks being followed, which will be tracked soon)
|
||||
this._getWatchedDir(parent).add(item);
|
||||
}
|
||||
}
|
||||
var eventName = info.type === 'directory' ? event + 'Dir' : event;
|
||||
this._emit(eventName, path);
|
||||
if (eventName === 'addDir') this._addToFsEvents(path, false, true);
|
||||
}
|
||||
}.bind(this);
|
||||
|
||||
function addOrChange() {
|
||||
handleEvent(watchedDir.has(item) ? 'change' : 'add');
|
||||
}
|
||||
function checkFd() {
|
||||
fs.open(path, 'r', function(error, fd) {
|
||||
if (error) {
|
||||
error.code !== 'EACCES' ?
|
||||
handleEvent('unlink') : addOrChange();
|
||||
} else {
|
||||
fs.close(fd, function(err) {
|
||||
err && err.code !== 'EACCES' ?
|
||||
handleEvent('unlink') : addOrChange();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
// correct for wrong events emitted
|
||||
var wrongEventFlags = [
|
||||
69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
|
||||
];
|
||||
if (wrongEventFlags.indexOf(flags) !== -1 || info.event === 'unknown') {
|
||||
if (typeof this.options.ignored === 'function') {
|
||||
fs.stat(path, function(error, stats) {
|
||||
if (checkIgnored(stats)) return;
|
||||
stats ? addOrChange() : handleEvent('unlink');
|
||||
});
|
||||
} else {
|
||||
checkFd();
|
||||
}
|
||||
} else {
|
||||
switch (info.event) {
|
||||
case 'created':
|
||||
case 'modified':
|
||||
return addOrChange();
|
||||
case 'deleted':
|
||||
case 'moved':
|
||||
return checkFd();
|
||||
}
|
||||
}
|
||||
}.bind(this);
|
||||
|
||||
var closer = setFSEventsListener(
|
||||
watchPath,
|
||||
realPath,
|
||||
watchCallback,
|
||||
this.emit.bind(this, 'raw')
|
||||
);
|
||||
|
||||
this._emitReady();
|
||||
return closer;
|
||||
};
|
||||
|
||||
// Private method: Handle symlinks encountered during directory scan
|
||||
|
||||
// * linkPath - string, path to symlink
|
||||
// * fullPath - string, absolute path to the symlink
|
||||
// * transform - function, pre-existing path transformer
|
||||
// * curDepth - int, level of subdirectories traversed to where symlink is
|
||||
|
||||
// Returns nothing
|
||||
FsEventsHandler.prototype._handleFsEventsSymlink =
|
||||
function(linkPath, fullPath, transform, curDepth) {
|
||||
// don't follow the same symlink more than once
|
||||
if (this._symlinkPaths[fullPath]) return;
|
||||
else this._symlinkPaths[fullPath] = true;
|
||||
|
||||
this._readyCount++;
|
||||
|
||||
fs.realpath(linkPath, function(error, linkTarget) {
|
||||
if (this._handleError(error) || this._isIgnored(linkTarget)) {
|
||||
return this._emitReady();
|
||||
}
|
||||
|
||||
this._readyCount++;
|
||||
|
||||
// add the linkTarget for watching with a wrapper for transform
|
||||
// that causes emitted paths to incorporate the link's path
|
||||
this._addToFsEvents(linkTarget || linkPath, function(path) {
|
||||
var dotSlash = '.' + sysPath.sep;
|
||||
var aliasedPath = linkPath;
|
||||
if (linkTarget && linkTarget !== dotSlash) {
|
||||
aliasedPath = path.replace(linkTarget, linkPath);
|
||||
} else if (path !== dotSlash) {
|
||||
aliasedPath = sysPath.join(linkPath, path);
|
||||
}
|
||||
return transform(aliasedPath);
|
||||
}, false, curDepth);
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
// Private method: Handle added path with fsevents
|
||||
|
||||
// * path - string, file/directory path or glob pattern
|
||||
// * transform - function, converts working path to what the user expects
|
||||
// * forceAdd - boolean, ensure add is emitted
|
||||
// * priorDepth - int, level of subdirectories already traversed
|
||||
|
||||
// Returns nothing
|
||||
FsEventsHandler.prototype._addToFsEvents =
|
||||
function(path, transform, forceAdd, priorDepth) {
|
||||
|
||||
// applies transform if provided, otherwise returns same value
|
||||
var processPath = typeof transform === 'function' ?
|
||||
transform : function(val) { return val; };
|
||||
|
||||
var emitAdd = function(newPath, stats) {
|
||||
var pp = processPath(newPath);
|
||||
var isDir = stats.isDirectory();
|
||||
var dirObj = this._getWatchedDir(sysPath.dirname(pp));
|
||||
var base = sysPath.basename(pp);
|
||||
|
||||
// ensure empty dirs get tracked
|
||||
if (isDir) this._getWatchedDir(pp);
|
||||
|
||||
if (dirObj.has(base)) return;
|
||||
dirObj.add(base);
|
||||
|
||||
if (!this.options.ignoreInitial || forceAdd === true) {
|
||||
this._emit(isDir ? 'addDir' : 'add', pp, stats);
|
||||
}
|
||||
}.bind(this);
|
||||
|
||||
var wh = this._getWatchHelpers(path);
|
||||
|
||||
// evaluate what is at the path we're being asked to watch
|
||||
fs[wh.statMethod](wh.watchPath, function(error, stats) {
|
||||
if (this._handleError(error) || this._isIgnored(wh.watchPath, stats)) {
|
||||
this._emitReady();
|
||||
return this._emitReady();
|
||||
}
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
// emit addDir unless this is a glob parent
|
||||
if (!wh.globFilter) emitAdd(processPath(path), stats);
|
||||
|
||||
// don't recurse further if it would exceed depth setting
|
||||
if (priorDepth && priorDepth > this.options.depth) return;
|
||||
|
||||
// scan the contents of the dir
|
||||
readdirp({
|
||||
root: wh.watchPath,
|
||||
entryType: 'all',
|
||||
fileFilter: wh.filterPath,
|
||||
directoryFilter: wh.filterDir,
|
||||
lstat: true,
|
||||
depth: this.options.depth - (priorDepth || 0)
|
||||
}).on('data', function(entry) {
|
||||
// need to check filterPath on dirs b/c filterDir is less restrictive
|
||||
if (entry.stat.isDirectory() && !wh.filterPath(entry)) return;
|
||||
|
||||
var joinedPath = sysPath.join(wh.watchPath, entry.path);
|
||||
var fullPath = entry.fullPath;
|
||||
|
||||
if (wh.followSymlinks && entry.stat.isSymbolicLink()) {
|
||||
// preserve the current depth here since it can't be derived from
|
||||
// real paths past the symlink
|
||||
var curDepth = this.options.depth === undefined ?
|
||||
undefined : depth(joinedPath, sysPath.resolve(wh.watchPath)) + 1;
|
||||
|
||||
this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
|
||||
} else {
|
||||
emitAdd(joinedPath, entry.stat);
|
||||
}
|
||||
}.bind(this)).on('error', function() {
|
||||
// Ignore readdirp errors
|
||||
}).on('end', this._emitReady);
|
||||
} else {
|
||||
emitAdd(wh.watchPath, stats);
|
||||
this._emitReady();
|
||||
}
|
||||
}.bind(this));
|
||||
|
||||
if (this.options.persistent && forceAdd !== true) {
|
||||
var initWatch = function(error, realPath) {
|
||||
if (this.closed) return;
|
||||
var closer = this._watchWithFsEvents(
|
||||
wh.watchPath,
|
||||
sysPath.resolve(realPath || wh.watchPath),
|
||||
processPath,
|
||||
wh.globFilter
|
||||
);
|
||||
if (closer) {
|
||||
this._closers[path] = this._closers[path] || [];
|
||||
this._closers[path].push(closer);
|
||||
}
|
||||
}.bind(this);
|
||||
|
||||
if (typeof transform === 'function') {
|
||||
// realpath has already been resolved
|
||||
initWatch();
|
||||
} else {
|
||||
fs.realpath(wh.watchPath, initWatch);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = FsEventsHandler;
|
||||
module.exports.canUse = canUse;
|
||||
+506
@@ -0,0 +1,506 @@
|
||||
'use strict';
|
||||
|
||||
var fs = require('fs');
|
||||
var sysPath = require('path');
|
||||
var readdirp = require('readdirp');
|
||||
var isBinaryPath = require('is-binary-path');
|
||||
|
||||
// fs.watch helpers
|
||||
|
||||
// object to hold per-process fs.watch instances
|
||||
// (may be shared across chokidar FSWatcher instances)
|
||||
var FsWatchInstances = Object.create(null);
|
||||
|
||||
|
||||
// Private function: Instantiates the fs.watch interface
|
||||
|
||||
// * path - string, path to be watched
|
||||
// * options - object, options to be passed to fs.watch
|
||||
// * listener - function, main event handler
|
||||
// * errHandler - function, handler which emits info about errors
|
||||
// * emitRaw - function, handler which emits raw event data
|
||||
|
||||
// Returns new fsevents instance
|
||||
function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
|
||||
var handleEvent = function(rawEvent, evPath) {
|
||||
listener(path);
|
||||
emitRaw(rawEvent, evPath, {watchedPath: path});
|
||||
|
||||
// emit based on events occurring for files from a directory's watcher in
|
||||
// case the file's watcher misses it (and rely on throttling to de-dupe)
|
||||
if (evPath && path !== evPath) {
|
||||
fsWatchBroadcast(
|
||||
sysPath.resolve(path, evPath), 'listeners', sysPath.join(path, evPath)
|
||||
);
|
||||
}
|
||||
};
|
||||
try {
|
||||
return fs.watch(path, options, handleEvent);
|
||||
} catch (error) {
|
||||
errHandler(error);
|
||||
}
|
||||
}
|
||||
|
||||
// Private function: Helper for passing fs.watch event data to a
|
||||
// collection of listeners
|
||||
|
||||
// * fullPath - string, absolute path bound to the fs.watch instance
|
||||
// * type - string, listener type
|
||||
// * val[1..3] - arguments to be passed to listeners
|
||||
|
||||
// Returns nothing
|
||||
function fsWatchBroadcast(fullPath, type, val1, val2, val3) {
|
||||
if (!FsWatchInstances[fullPath]) return;
|
||||
FsWatchInstances[fullPath][type].forEach(function(listener) {
|
||||
listener(val1, val2, val3);
|
||||
});
|
||||
}
|
||||
|
||||
// Private function: Instantiates the fs.watch interface or binds listeners
|
||||
// to an existing one covering the same file system entry
|
||||
|
||||
// * path - string, path to be watched
|
||||
// * fullPath - string, absolute path
|
||||
// * options - object, options to be passed to fs.watch
|
||||
// * handlers - object, container for event listener functions
|
||||
|
||||
// Returns close function
|
||||
function setFsWatchListener(path, fullPath, options, handlers) {
|
||||
var listener = handlers.listener;
|
||||
var errHandler = handlers.errHandler;
|
||||
var rawEmitter = handlers.rawEmitter;
|
||||
var container = FsWatchInstances[fullPath];
|
||||
var watcher;
|
||||
if (!options.persistent) {
|
||||
watcher = createFsWatchInstance(
|
||||
path, options, listener, errHandler, rawEmitter
|
||||
);
|
||||
return watcher.close.bind(watcher);
|
||||
}
|
||||
if (!container) {
|
||||
watcher = createFsWatchInstance(
|
||||
path,
|
||||
options,
|
||||
fsWatchBroadcast.bind(null, fullPath, 'listeners'),
|
||||
errHandler, // no need to use broadcast here
|
||||
fsWatchBroadcast.bind(null, fullPath, 'rawEmitters')
|
||||
);
|
||||
if (!watcher) return;
|
||||
var broadcastErr = fsWatchBroadcast.bind(null, fullPath, 'errHandlers');
|
||||
watcher.on('error', function(error) {
|
||||
container.watcherUnusable = true; // documented since Node 10.4.1
|
||||
// Workaround for https://github.com/joyent/node/issues/4337
|
||||
if (process.platform === 'win32' && error.code === 'EPERM') {
|
||||
fs.open(path, 'r', function(err, fd) {
|
||||
if (!err) fs.close(fd, function(err) {
|
||||
if (!err) broadcastErr(error);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
broadcastErr(error);
|
||||
}
|
||||
});
|
||||
container = FsWatchInstances[fullPath] = {
|
||||
listeners: [listener],
|
||||
errHandlers: [errHandler],
|
||||
rawEmitters: [rawEmitter],
|
||||
watcher: watcher
|
||||
};
|
||||
} else {
|
||||
container.listeners.push(listener);
|
||||
container.errHandlers.push(errHandler);
|
||||
container.rawEmitters.push(rawEmitter);
|
||||
}
|
||||
var listenerIndex = container.listeners.length - 1;
|
||||
|
||||
// removes this instance's listeners and closes the underlying fs.watch
|
||||
// instance if there are no more listeners left
|
||||
return function close() {
|
||||
delete container.listeners[listenerIndex];
|
||||
delete container.errHandlers[listenerIndex];
|
||||
delete container.rawEmitters[listenerIndex];
|
||||
if (!Object.keys(container.listeners).length) {
|
||||
if (!container.watcherUnusable) { // check to protect against issue #730
|
||||
container.watcher.close();
|
||||
}
|
||||
delete FsWatchInstances[fullPath];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// fs.watchFile helpers
|
||||
|
||||
// object to hold per-process fs.watchFile instances
|
||||
// (may be shared across chokidar FSWatcher instances)
|
||||
var FsWatchFileInstances = Object.create(null);
|
||||
|
||||
// Private function: Instantiates the fs.watchFile interface or binds listeners
|
||||
// to an existing one covering the same file system entry
|
||||
|
||||
// * path - string, path to be watched
|
||||
// * fullPath - string, absolute path
|
||||
// * options - object, options to be passed to fs.watchFile
|
||||
// * handlers - object, container for event listener functions
|
||||
|
||||
// Returns close function
|
||||
function setFsWatchFileListener(path, fullPath, options, handlers) {
|
||||
var listener = handlers.listener;
|
||||
var rawEmitter = handlers.rawEmitter;
|
||||
var container = FsWatchFileInstances[fullPath];
|
||||
var listeners = [];
|
||||
var rawEmitters = [];
|
||||
if (
|
||||
container && (
|
||||
container.options.persistent < options.persistent ||
|
||||
container.options.interval > options.interval
|
||||
)
|
||||
) {
|
||||
// "Upgrade" the watcher to persistence or a quicker interval.
|
||||
// This creates some unlikely edge case issues if the user mixes
|
||||
// settings in a very weird way, but solving for those cases
|
||||
// doesn't seem worthwhile for the added complexity.
|
||||
listeners = container.listeners;
|
||||
rawEmitters = container.rawEmitters;
|
||||
fs.unwatchFile(fullPath);
|
||||
container = false;
|
||||
}
|
||||
if (!container) {
|
||||
listeners.push(listener);
|
||||
rawEmitters.push(rawEmitter);
|
||||
container = FsWatchFileInstances[fullPath] = {
|
||||
listeners: listeners,
|
||||
rawEmitters: rawEmitters,
|
||||
options: options,
|
||||
watcher: fs.watchFile(fullPath, options, function(curr, prev) {
|
||||
container.rawEmitters.forEach(function(rawEmitter) {
|
||||
rawEmitter('change', fullPath, {curr: curr, prev: prev});
|
||||
});
|
||||
var currmtime = curr.mtime.getTime();
|
||||
if (curr.size !== prev.size || currmtime > prev.mtime.getTime() || currmtime === 0) {
|
||||
container.listeners.forEach(function(listener) {
|
||||
listener(path, curr);
|
||||
});
|
||||
}
|
||||
})
|
||||
};
|
||||
} else {
|
||||
container.listeners.push(listener);
|
||||
container.rawEmitters.push(rawEmitter);
|
||||
}
|
||||
var listenerIndex = container.listeners.length - 1;
|
||||
|
||||
// removes this instance's listeners and closes the underlying fs.watchFile
|
||||
// instance if there are no more listeners left
|
||||
return function close() {
|
||||
delete container.listeners[listenerIndex];
|
||||
delete container.rawEmitters[listenerIndex];
|
||||
if (!Object.keys(container.listeners).length) {
|
||||
fs.unwatchFile(fullPath);
|
||||
delete FsWatchFileInstances[fullPath];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// fake constructor for attaching nodefs-specific prototype methods that
|
||||
// will be copied to FSWatcher's prototype
|
||||
function NodeFsHandler() {}
|
||||
|
||||
// Private method: Watch file for changes with fs.watchFile or fs.watch.
|
||||
|
||||
// * path - string, path to file or directory.
|
||||
// * listener - function, to be executed on fs change.
|
||||
|
||||
// Returns close function for the watcher instance
|
||||
NodeFsHandler.prototype._watchWithNodeFs =
|
||||
function(path, listener) {
|
||||
var directory = sysPath.dirname(path);
|
||||
var basename = sysPath.basename(path);
|
||||
var parent = this._getWatchedDir(directory);
|
||||
parent.add(basename);
|
||||
var absolutePath = sysPath.resolve(path);
|
||||
var options = {persistent: this.options.persistent};
|
||||
if (!listener) listener = Function.prototype; // empty function
|
||||
|
||||
var closer;
|
||||
if (this.options.usePolling) {
|
||||
options.interval = this.enableBinaryInterval && isBinaryPath(basename) ?
|
||||
this.options.binaryInterval : this.options.interval;
|
||||
closer = setFsWatchFileListener(path, absolutePath, options, {
|
||||
listener: listener,
|
||||
rawEmitter: this.emit.bind(this, 'raw')
|
||||
});
|
||||
} else {
|
||||
closer = setFsWatchListener(path, absolutePath, options, {
|
||||
listener: listener,
|
||||
errHandler: this._handleError.bind(this),
|
||||
rawEmitter: this.emit.bind(this, 'raw')
|
||||
});
|
||||
}
|
||||
return closer;
|
||||
};
|
||||
|
||||
// Private method: Watch a file and emit add event if warranted
|
||||
|
||||
// * file - string, the file's path
|
||||
// * stats - object, result of fs.stat
|
||||
// * initialAdd - boolean, was the file added at watch instantiation?
|
||||
// * callback - function, called when done processing as a newly seen file
|
||||
|
||||
// Returns close function for the watcher instance
|
||||
NodeFsHandler.prototype._handleFile =
|
||||
function(file, stats, initialAdd, callback) {
|
||||
var dirname = sysPath.dirname(file);
|
||||
var basename = sysPath.basename(file);
|
||||
var parent = this._getWatchedDir(dirname);
|
||||
// stats is always present
|
||||
var prevStats = stats;
|
||||
|
||||
// if the file is already being watched, do nothing
|
||||
if (parent.has(basename)) return callback();
|
||||
|
||||
// kick off the watcher
|
||||
var closer = this._watchWithNodeFs(file, function(path, newStats) {
|
||||
if (!this._throttle('watch', file, 5)) return;
|
||||
if (!newStats || newStats && newStats.mtime.getTime() === 0) {
|
||||
fs.stat(file, function(error, newStats) {
|
||||
// Fix issues where mtime is null but file is still present
|
||||
if (error) {
|
||||
this._remove(dirname, basename);
|
||||
} else {
|
||||
// Check that change event was not fired because of changed only accessTime.
|
||||
var at = newStats.atime.getTime();
|
||||
var mt = newStats.mtime.getTime();
|
||||
if (!at || at <= mt || mt !== prevStats.mtime.getTime()) {
|
||||
this._emit('change', file, newStats);
|
||||
}
|
||||
prevStats = newStats;
|
||||
}
|
||||
}.bind(this));
|
||||
// add is about to be emitted if file not already tracked in parent
|
||||
} else if (parent.has(basename)) {
|
||||
// Check that change event was not fired because of changed only accessTime.
|
||||
var at = newStats.atime.getTime();
|
||||
var mt = newStats.mtime.getTime();
|
||||
if (!at || at <= mt || mt !== prevStats.mtime.getTime()) {
|
||||
this._emit('change', file, newStats);
|
||||
}
|
||||
prevStats = newStats;
|
||||
}
|
||||
}.bind(this));
|
||||
|
||||
// emit an add event if we're supposed to
|
||||
if (!(initialAdd && this.options.ignoreInitial)) {
|
||||
if (!this._throttle('add', file, 0)) return;
|
||||
this._emit('add', file, stats);
|
||||
}
|
||||
|
||||
if (callback) callback();
|
||||
return closer;
|
||||
};
|
||||
|
||||
// Private method: Handle symlinks encountered while reading a dir
|
||||
|
||||
// * entry - object, entry object returned by readdirp
|
||||
// * directory - string, path of the directory being read
|
||||
// * path - string, path of this item
|
||||
// * item - string, basename of this item
|
||||
|
||||
// Returns true if no more processing is needed for this entry.
|
||||
NodeFsHandler.prototype._handleSymlink =
|
||||
function(entry, directory, path, item) {
|
||||
var full = entry.fullPath;
|
||||
var dir = this._getWatchedDir(directory);
|
||||
|
||||
if (!this.options.followSymlinks) {
|
||||
// watch symlink directly (don't follow) and detect changes
|
||||
this._readyCount++;
|
||||
fs.realpath(path, function(error, linkPath) {
|
||||
if (dir.has(item)) {
|
||||
if (this._symlinkPaths[full] !== linkPath) {
|
||||
this._symlinkPaths[full] = linkPath;
|
||||
this._emit('change', path, entry.stat);
|
||||
}
|
||||
} else {
|
||||
dir.add(item);
|
||||
this._symlinkPaths[full] = linkPath;
|
||||
this._emit('add', path, entry.stat);
|
||||
}
|
||||
this._emitReady();
|
||||
}.bind(this));
|
||||
return true;
|
||||
}
|
||||
|
||||
// don't follow the same symlink more than once
|
||||
if (this._symlinkPaths[full]) return true;
|
||||
else this._symlinkPaths[full] = true;
|
||||
};
|
||||
|
||||
// Private method: Read directory to add / remove files from `@watched` list
|
||||
// and re-read it on change.
|
||||
|
||||
// * dir - string, fs path.
|
||||
// * stats - object, result of fs.stat
|
||||
// * initialAdd - boolean, was the file added at watch instantiation?
|
||||
// * depth - int, depth relative to user-supplied path
|
||||
// * target - string, child path actually targeted for watch
|
||||
// * wh - object, common watch helpers for this path
|
||||
// * callback - function, called when dir scan is complete
|
||||
|
||||
// Returns close function for the watcher instance
|
||||
NodeFsHandler.prototype._handleDir =
|
||||
function(dir, stats, initialAdd, depth, target, wh, callback) {
|
||||
var parentDir = this._getWatchedDir(sysPath.dirname(dir));
|
||||
var tracked = parentDir.has(sysPath.basename(dir));
|
||||
if (!(initialAdd && this.options.ignoreInitial) && !target && !tracked) {
|
||||
if (!wh.hasGlob || wh.globFilter(dir)) this._emit('addDir', dir, stats);
|
||||
}
|
||||
|
||||
// ensure dir is tracked (harmless if redundant)
|
||||
parentDir.add(sysPath.basename(dir));
|
||||
this._getWatchedDir(dir);
|
||||
|
||||
var read = function(directory, initialAdd, done) {
|
||||
// Normalize the directory name on Windows
|
||||
directory = sysPath.join(directory, '');
|
||||
|
||||
if (!wh.hasGlob) {
|
||||
var throttler = this._throttle('readdir', directory, 1000);
|
||||
if (!throttler) return;
|
||||
}
|
||||
|
||||
var previous = this._getWatchedDir(wh.path);
|
||||
var current = [];
|
||||
|
||||
readdirp({
|
||||
root: directory,
|
||||
entryType: 'all',
|
||||
fileFilter: wh.filterPath,
|
||||
directoryFilter: wh.filterDir,
|
||||
depth: 0,
|
||||
lstat: true
|
||||
}).on('data', function(entry) {
|
||||
var item = entry.path;
|
||||
var path = sysPath.join(directory, item);
|
||||
current.push(item);
|
||||
|
||||
if (entry.stat.isSymbolicLink() &&
|
||||
this._handleSymlink(entry, directory, path, item)) return;
|
||||
|
||||
// Files that present in current directory snapshot
|
||||
// but absent in previous are added to watch list and
|
||||
// emit `add` event.
|
||||
if (item === target || !target && !previous.has(item)) {
|
||||
this._readyCount++;
|
||||
|
||||
// ensure relativeness of path is preserved in case of watcher reuse
|
||||
path = sysPath.join(dir, sysPath.relative(dir, path));
|
||||
|
||||
this._addToNodeFs(path, initialAdd, wh, depth + 1);
|
||||
}
|
||||
}.bind(this)).on('end', function() {
|
||||
var wasThrottled = throttler ? throttler.clear() : false;
|
||||
if (done) done();
|
||||
|
||||
// Files that absent in current directory snapshot
|
||||
// but present in previous emit `remove` event
|
||||
// and are removed from @watched[directory].
|
||||
previous.children().filter(function(item) {
|
||||
return item !== directory &&
|
||||
current.indexOf(item) === -1 &&
|
||||
// in case of intersecting globs;
|
||||
// a path may have been filtered out of this readdir, but
|
||||
// shouldn't be removed because it matches a different glob
|
||||
(!wh.hasGlob || wh.filterPath({
|
||||
fullPath: sysPath.resolve(directory, item)
|
||||
}));
|
||||
}).forEach(function(item) {
|
||||
this._remove(directory, item);
|
||||
}, this);
|
||||
|
||||
// one more time for any missed in case changes came in extremely quickly
|
||||
if (wasThrottled) read(directory, false);
|
||||
}.bind(this)).on('error', this._handleError.bind(this));
|
||||
}.bind(this);
|
||||
|
||||
var closer;
|
||||
|
||||
if (this.options.depth == null || depth <= this.options.depth) {
|
||||
if (!target) read(dir, initialAdd, callback);
|
||||
closer = this._watchWithNodeFs(dir, function(dirPath, stats) {
|
||||
// if current directory is removed, do nothing
|
||||
if (stats && stats.mtime.getTime() === 0) return;
|
||||
|
||||
read(dirPath, false);
|
||||
});
|
||||
} else {
|
||||
callback();
|
||||
}
|
||||
return closer;
|
||||
};
|
||||
|
||||
// Private method: Handle added file, directory, or glob pattern.
|
||||
// Delegates call to _handleFile / _handleDir after checks.
|
||||
|
||||
// * path - string, path to file or directory.
|
||||
// * initialAdd - boolean, was the file added at watch instantiation?
|
||||
// * depth - int, depth relative to user-supplied path
|
||||
// * target - string, child path actually targeted for watch
|
||||
// * callback - function, indicates whether the path was found or not
|
||||
|
||||
// Returns nothing
|
||||
NodeFsHandler.prototype._addToNodeFs =
|
||||
function(path, initialAdd, priorWh, depth, target, callback) {
|
||||
if (!callback) callback = Function.prototype;
|
||||
var ready = this._emitReady;
|
||||
if (this._isIgnored(path) || this.closed) {
|
||||
ready();
|
||||
return callback(null, false);
|
||||
}
|
||||
|
||||
var wh = this._getWatchHelpers(path, depth);
|
||||
if (!wh.hasGlob && priorWh) {
|
||||
wh.hasGlob = priorWh.hasGlob;
|
||||
wh.globFilter = priorWh.globFilter;
|
||||
wh.filterPath = priorWh.filterPath;
|
||||
wh.filterDir = priorWh.filterDir;
|
||||
}
|
||||
|
||||
// evaluate what is at the path we're being asked to watch
|
||||
fs[wh.statMethod](wh.watchPath, function(error, stats) {
|
||||
if (this._handleError(error)) return callback(null, path);
|
||||
if (this._isIgnored(wh.watchPath, stats)) {
|
||||
ready();
|
||||
return callback(null, false);
|
||||
}
|
||||
|
||||
var initDir = function(dir, target) {
|
||||
return this._handleDir(dir, stats, initialAdd, depth, target, wh, ready);
|
||||
}.bind(this);
|
||||
|
||||
var closer;
|
||||
if (stats.isDirectory()) {
|
||||
closer = initDir(wh.watchPath, target);
|
||||
} else if (stats.isSymbolicLink()) {
|
||||
var parent = sysPath.dirname(wh.watchPath);
|
||||
this._getWatchedDir(parent).add(wh.watchPath);
|
||||
this._emit('add', wh.watchPath, stats);
|
||||
closer = initDir(parent, path);
|
||||
|
||||
// preserve this symlink's target path
|
||||
fs.realpath(path, function(error, targetPath) {
|
||||
this._symlinkPaths[sysPath.resolve(path)] = targetPath;
|
||||
ready();
|
||||
}.bind(this));
|
||||
} else {
|
||||
closer = this._handleFile(wh.watchPath, stats, initialAdd, ready);
|
||||
}
|
||||
|
||||
if (closer) {
|
||||
this._closers[path] = this._closers[path] || [];
|
||||
this._closers[path].push(closer);
|
||||
}
|
||||
callback(null, false);
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
module.exports = NodeFsHandler;
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"name": "chokidar",
|
||||
"description": "A neat wrapper around node.js fs.watch / fs.watchFile / fsevents.",
|
||||
"version": "2.1.8",
|
||||
"keywords": [
|
||||
"fs",
|
||||
"watch",
|
||||
"watchFile",
|
||||
"watcher",
|
||||
"watching",
|
||||
"file",
|
||||
"fsevents"
|
||||
],
|
||||
"types": "./types/index.d.ts",
|
||||
"homepage": "https://github.com/paulmillr/chokidar",
|
||||
"author": "Paul Miller (https://paulmillr.com), Elan Shanker",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/paulmillr/chokidar.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/paulmillr/chokidar/issues"
|
||||
},
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"test": "nyc mocha --exit",
|
||||
"coveralls": "nyc report --reporter=text-lcov | coveralls",
|
||||
"dtslint": "dtslint types"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"lib/",
|
||||
"types/index.d.ts"
|
||||
],
|
||||
"dependencies": {
|
||||
"anymatch": "^2.0.0",
|
||||
"async-each": "^1.0.1",
|
||||
"braces": "^2.3.2",
|
||||
"glob-parent": "^3.1.0",
|
||||
"inherits": "^2.0.3",
|
||||
"is-binary-path": "^1.0.0",
|
||||
"is-glob": "^4.0.0",
|
||||
"normalize-path": "^3.0.0",
|
||||
"path-is-absolute": "^1.0.0",
|
||||
"readdirp": "^2.2.1",
|
||||
"upath": "^1.1.1"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "^1.2.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^11.9.4",
|
||||
"chai": "^3.2.0",
|
||||
"coveralls": "^3.0.1",
|
||||
"dtslint": "0.4.1",
|
||||
"graceful-fs": "4.1.4",
|
||||
"mocha": "^5.2.0",
|
||||
"nyc": "^11.8.0",
|
||||
"rimraf": "^2.4.3",
|
||||
"sinon": "^1.10.3",
|
||||
"sinon-chai": "^2.6.0"
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
// TypeScript Version: 3.0
|
||||
|
||||
/// <reference types="node" />
|
||||
|
||||
import * as fs from "fs";
|
||||
import { EventEmitter } from "events";
|
||||
|
||||
/**
|
||||
* The object's keys are all the directories (using absolute paths unless the `cwd` option was
|
||||
* used), and the values are arrays of the names of the items contained in each directory.
|
||||
*/
|
||||
export interface WatchedPaths {
|
||||
[directory: string]: string[];
|
||||
}
|
||||
|
||||
export class FSWatcher extends EventEmitter implements fs.FSWatcher {
|
||||
/**
|
||||
* Constructs a new FSWatcher instance with optional WatchOptions parameter.
|
||||
*/
|
||||
constructor(options?: WatchOptions);
|
||||
|
||||
/**
|
||||
* Add files, directories, or glob patterns for tracking. Takes an array of strings or just one
|
||||
* string.
|
||||
*/
|
||||
add(paths: string | string[]): void;
|
||||
|
||||
/**
|
||||
* Stop watching files, directories, or glob patterns. Takes an array of strings or just one
|
||||
* string.
|
||||
*/
|
||||
unwatch(paths: string | string[]): void;
|
||||
|
||||
/**
|
||||
* Returns an object representing all the paths on the file system being watched by this
|
||||
* `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless
|
||||
* the `cwd` option was used), and the values are arrays of the names of the items contained in
|
||||
* each directory.
|
||||
*/
|
||||
getWatched(): WatchedPaths;
|
||||
|
||||
/**
|
||||
* Removes all listeners from watched files.
|
||||
*/
|
||||
close(): void;
|
||||
|
||||
on(event: 'add'|'addDir'|'change', listener: (path: string, stats?: fs.Stats) => void): this;
|
||||
|
||||
on(event: 'all', listener: (eventName: 'add'|'addDir'|'change'|'unlink'|'unlinkDir', path: string, stats?: fs.Stats) => void): this;
|
||||
|
||||
/**
|
||||
* Error occured
|
||||
*/
|
||||
on(event: 'error', listener: (error: Error) => void): this;
|
||||
|
||||
/**
|
||||
* Exposes the native Node `fs.FSWatcher events`
|
||||
*/
|
||||
on(event: 'raw', listener: (eventName: string, path: string, details: any) => void): this;
|
||||
|
||||
/**
|
||||
* Fires when the initial scan is complete
|
||||
*/
|
||||
on(event: 'ready', listener: () => void): this;
|
||||
|
||||
on(event: 'unlink'|'unlinkDir', listener: (path: string) => void): this;
|
||||
|
||||
on(event: string, listener: (...args: any[]) => void): this;
|
||||
}
|
||||
|
||||
export interface WatchOptions {
|
||||
/**
|
||||
* Indicates whether the process should continue to run as long as files are being watched. If
|
||||
* set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`,
|
||||
* even if the process continues to run.
|
||||
*/
|
||||
persistent?: boolean;
|
||||
|
||||
/**
|
||||
* ([anymatch](https://github.com/es128/anymatch)-compatible definition) Defines files/paths to
|
||||
* be ignored. The whole relative or absolute path is tested, not just filename. If a function
|
||||
* with two arguments is provided, it gets called twice per path - once with a single argument
|
||||
* (the path), second time with two arguments (the path and the
|
||||
* [`fs.Stats`](http://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path).
|
||||
*/
|
||||
ignored?: any;
|
||||
|
||||
/**
|
||||
* If set to `false` then `add`/`addDir` events are also emitted for matching paths while
|
||||
* instantiating the watching as chokidar discovers these file paths (before the `ready` event).
|
||||
*/
|
||||
ignoreInitial?: boolean;
|
||||
|
||||
/**
|
||||
* When `false`, only the symlinks themselves will be watched for changes instead of following
|
||||
* the link references and bubbling events through the link's path.
|
||||
*/
|
||||
followSymlinks?: boolean;
|
||||
|
||||
/**
|
||||
* The base directory from which watch `paths` are to be derived. Paths emitted with events will
|
||||
* be relative to this.
|
||||
*/
|
||||
cwd?: string;
|
||||
|
||||
/**
|
||||
* If set to true then the strings passed to .watch() and .add() are treated as literal path
|
||||
* names, even if they look like globs. Default: false.
|
||||
*/
|
||||
disableGlobbing?: boolean;
|
||||
|
||||
/**
|
||||
* Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU
|
||||
* utilization, consider setting this to `false`. It is typically necessary to **set this to
|
||||
* `true` to successfully watch files over a network**, and it may be necessary to successfully
|
||||
* watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides
|
||||
* the `useFsEvents` default.
|
||||
*/
|
||||
usePolling?: boolean;
|
||||
|
||||
/**
|
||||
* Whether to use the `fsevents` watching interface if available. When set to `true` explicitly
|
||||
* and `fsevents` is available this supercedes the `usePolling` setting. When set to `false` on
|
||||
* OS X, `usePolling: true` becomes the default.
|
||||
*/
|
||||
useFsEvents?: boolean;
|
||||
|
||||
/**
|
||||
* If relying upon the [`fs.Stats`](http://nodejs.org/api/fs.html#fs_class_fs_stats) object that
|
||||
* may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is
|
||||
* provided even in cases where it wasn't already available from the underlying watch events.
|
||||
*/
|
||||
alwaysStat?: boolean;
|
||||
|
||||
/**
|
||||
* If set, limits how many levels of subdirectories will be traversed.
|
||||
*/
|
||||
depth?: number;
|
||||
|
||||
/**
|
||||
* Interval of file system polling.
|
||||
*/
|
||||
interval?: number;
|
||||
|
||||
/**
|
||||
* Interval of file system polling for binary files. ([see list of binary extensions](https://gi
|
||||
* thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
|
||||
*/
|
||||
binaryInterval?: number;
|
||||
|
||||
/**
|
||||
* Indicates whether to watch files that don't have read permissions if possible. If watching
|
||||
* fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed
|
||||
* silently.
|
||||
*/
|
||||
ignorePermissionErrors?: boolean;
|
||||
|
||||
/**
|
||||
* `true` if `useFsEvents` and `usePolling` are `false`). Automatically filters out artifacts
|
||||
* that occur when using editors that use "atomic writes" instead of writing directly to the
|
||||
* source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change`
|
||||
* event rather than `unlink` then `add`. If the default of 100 ms does not work well for you,
|
||||
* you can override it by setting `atomic` to a custom value, in milliseconds.
|
||||
*/
|
||||
atomic?: boolean | number;
|
||||
|
||||
/**
|
||||
* can be set to an object in order to adjust timing params:
|
||||
*/
|
||||
awaitWriteFinish?: AwaitWriteFinishOptions | boolean;
|
||||
}
|
||||
|
||||
export interface AwaitWriteFinishOptions {
|
||||
/**
|
||||
* Amount of time in milliseconds for a file size to remain constant before emitting its event.
|
||||
*/
|
||||
stabilityThreshold?: number;
|
||||
|
||||
/**
|
||||
* File size polling interval.
|
||||
*/
|
||||
pollInterval?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* produces an instance of `FSWatcher`.
|
||||
*/
|
||||
export function watch(
|
||||
paths: string | string[],
|
||||
options?: WatchOptions
|
||||
): FSWatcher;
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
# Change Log
|
||||
|
||||
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
|
||||
|
||||
<a name="3.2.0"></a>
|
||||
# [3.2.0](https://github.com/yargs/cliui/compare/v3.1.2...v3.2.0) (2016-04-11)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* reduces tarball size ([acc6c33](https://github.com/yargs/cliui/commit/acc6c33))
|
||||
|
||||
### Features
|
||||
|
||||
* adds standard-version for release management ([ff84e32](https://github.com/yargs/cliui/commit/ff84e32))
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
Copyright (c) 2015, 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.
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
# cliui
|
||||
|
||||
[](https://travis-ci.org/yargs/cliui)
|
||||
[](https://coveralls.io/r/yargs/cliui?branch=)
|
||||
[](https://www.npmjs.com/package/cliui)
|
||||
[](https://github.com/conventional-changelog/standard-version)
|
||||
|
||||
easily create complex multi-column command-line-interfaces.
|
||||
|
||||
## Example
|
||||
|
||||
```js
|
||||
var ui = require('cliui')({
|
||||
width: 80
|
||||
})
|
||||
|
||||
ui.div('Usage: $0 [command] [options]')
|
||||
|
||||
ui.div({
|
||||
text: 'Options:',
|
||||
padding: [2, 0, 2, 0]
|
||||
})
|
||||
|
||||
ui.div(
|
||||
{
|
||||
text: "-f, --file",
|
||||
width: 20,
|
||||
padding: [0, 4, 0, 4]
|
||||
},
|
||||
{
|
||||
text: "the file to load." +
|
||||
chalk.green("(if this description is long it wraps).")
|
||||
,
|
||||
width: 20
|
||||
},
|
||||
{
|
||||
text: chalk.red("[required]"),
|
||||
align: 'right'
|
||||
}
|
||||
)
|
||||
|
||||
console.log(ui.toString())
|
||||
```
|
||||
|
||||
<img width="500" src="screenshot.png">
|
||||
|
||||
## Layout DSL
|
||||
|
||||
cliui exposes a simple layout DSL:
|
||||
|
||||
If you create a single `ui.row`, passing a string rather than an
|
||||
object:
|
||||
|
||||
* `\n`: characters will be interpreted as new rows.
|
||||
* `\t`: characters will be interpreted as new columns.
|
||||
* `\s`: characters will be interpreted as padding.
|
||||
|
||||
**as an example...**
|
||||
|
||||
```js
|
||||
var ui = require('./')({
|
||||
width: 60
|
||||
})
|
||||
|
||||
ui.div(
|
||||
'Usage: node ./bin/foo.js\n' +
|
||||
' <regex>\t provide a regex\n' +
|
||||
' <glob>\t provide a glob\t [required]'
|
||||
)
|
||||
|
||||
console.log(ui.toString())
|
||||
```
|
||||
|
||||
**will output:**
|
||||
|
||||
```shell
|
||||
Usage: node ./bin/foo.js
|
||||
<regex> provide a regex
|
||||
<glob> provide a glob [required]
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
```js
|
||||
cliui = require('cliui')
|
||||
```
|
||||
|
||||
### cliui({width: integer})
|
||||
|
||||
Specify the maximum width of the UI being generated.
|
||||
|
||||
### cliui({wrap: boolean})
|
||||
|
||||
Enable or disable the wrapping of text in a column.
|
||||
|
||||
### cliui.div(column, column, column)
|
||||
|
||||
Create a row with any number of columns, a column
|
||||
can either be a string, or an object with the following
|
||||
options:
|
||||
|
||||
* **width:** the width of a column.
|
||||
* **align:** alignment, `right` or `center`.
|
||||
* **padding:** `[top, right, bottom, left]`.
|
||||
* **border:** should a border be placed around the div?
|
||||
|
||||
### cliui.span(column, column, column)
|
||||
|
||||
Similar to `div`, except the next row will be appended without
|
||||
a new line being created.
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
var stringWidth = require('string-width')
|
||||
var stripAnsi = require('strip-ansi')
|
||||
var wrap = require('wrap-ansi')
|
||||
var align = {
|
||||
right: alignRight,
|
||||
center: alignCenter
|
||||
}
|
||||
var top = 0
|
||||
var right = 1
|
||||
var bottom = 2
|
||||
var left = 3
|
||||
|
||||
function UI (opts) {
|
||||
this.width = opts.width
|
||||
this.wrap = opts.wrap
|
||||
this.rows = []
|
||||
}
|
||||
|
||||
UI.prototype.span = function () {
|
||||
var cols = this.div.apply(this, arguments)
|
||||
cols.span = true
|
||||
}
|
||||
|
||||
UI.prototype.div = function () {
|
||||
if (arguments.length === 0) this.div('')
|
||||
if (this.wrap && this._shouldApplyLayoutDSL.apply(this, arguments)) {
|
||||
return this._applyLayoutDSL(arguments[0])
|
||||
}
|
||||
|
||||
var cols = []
|
||||
|
||||
for (var i = 0, arg; (arg = arguments[i]) !== undefined; i++) {
|
||||
if (typeof arg === 'string') cols.push(this._colFromString(arg))
|
||||
else cols.push(arg)
|
||||
}
|
||||
|
||||
this.rows.push(cols)
|
||||
return cols
|
||||
}
|
||||
|
||||
UI.prototype._shouldApplyLayoutDSL = function () {
|
||||
return arguments.length === 1 && typeof arguments[0] === 'string' &&
|
||||
/[\t\n]/.test(arguments[0])
|
||||
}
|
||||
|
||||
UI.prototype._applyLayoutDSL = function (str) {
|
||||
var _this = this
|
||||
var rows = str.split('\n')
|
||||
var leftColumnWidth = 0
|
||||
|
||||
// simple heuristic for layout, make sure the
|
||||
// second column lines up along the left-hand.
|
||||
// don't allow the first column to take up more
|
||||
// than 50% of the screen.
|
||||
rows.forEach(function (row) {
|
||||
var columns = row.split('\t')
|
||||
if (columns.length > 1 && stringWidth(columns[0]) > leftColumnWidth) {
|
||||
leftColumnWidth = Math.min(
|
||||
Math.floor(_this.width * 0.5),
|
||||
stringWidth(columns[0])
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
// generate a table:
|
||||
// replacing ' ' with padding calculations.
|
||||
// using the algorithmically generated width.
|
||||
rows.forEach(function (row) {
|
||||
var columns = row.split('\t')
|
||||
_this.div.apply(_this, columns.map(function (r, i) {
|
||||
return {
|
||||
text: r.trim(),
|
||||
padding: _this._measurePadding(r),
|
||||
width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
|
||||
}
|
||||
}))
|
||||
})
|
||||
|
||||
return this.rows[this.rows.length - 1]
|
||||
}
|
||||
|
||||
UI.prototype._colFromString = function (str) {
|
||||
return {
|
||||
text: str,
|
||||
padding: this._measurePadding(str)
|
||||
}
|
||||
}
|
||||
|
||||
UI.prototype._measurePadding = function (str) {
|
||||
// measure padding without ansi escape codes
|
||||
var noAnsi = stripAnsi(str)
|
||||
return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]
|
||||
}
|
||||
|
||||
UI.prototype.toString = function () {
|
||||
var _this = this
|
||||
var lines = []
|
||||
|
||||
_this.rows.forEach(function (row, i) {
|
||||
_this.rowToString(row, lines)
|
||||
})
|
||||
|
||||
// don't display any lines with the
|
||||
// hidden flag set.
|
||||
lines = lines.filter(function (line) {
|
||||
return !line.hidden
|
||||
})
|
||||
|
||||
return lines.map(function (line) {
|
||||
return line.text
|
||||
}).join('\n')
|
||||
}
|
||||
|
||||
UI.prototype.rowToString = function (row, lines) {
|
||||
var _this = this
|
||||
var padding
|
||||
var rrows = this._rasterize(row)
|
||||
var str = ''
|
||||
var ts
|
||||
var width
|
||||
var wrapWidth
|
||||
|
||||
rrows.forEach(function (rrow, r) {
|
||||
str = ''
|
||||
rrow.forEach(function (col, c) {
|
||||
ts = '' // temporary string used during alignment/padding.
|
||||
width = row[c].width // the width with padding.
|
||||
wrapWidth = _this._negatePadding(row[c]) // the width without padding.
|
||||
|
||||
ts += col
|
||||
|
||||
for (var i = 0; i < wrapWidth - stringWidth(col); i++) {
|
||||
ts += ' '
|
||||
}
|
||||
|
||||
// align the string within its column.
|
||||
if (row[c].align && row[c].align !== 'left' && _this.wrap) {
|
||||
ts = align[row[c].align](ts, wrapWidth)
|
||||
if (stringWidth(ts) < wrapWidth) ts += new Array(width - stringWidth(ts)).join(' ')
|
||||
}
|
||||
|
||||
// apply border and padding to string.
|
||||
padding = row[c].padding || [0, 0, 0, 0]
|
||||
if (padding[left]) str += new Array(padding[left] + 1).join(' ')
|
||||
str += addBorder(row[c], ts, '| ')
|
||||
str += ts
|
||||
str += addBorder(row[c], ts, ' |')
|
||||
if (padding[right]) str += new Array(padding[right] + 1).join(' ')
|
||||
|
||||
// if prior row is span, try to render the
|
||||
// current row on the prior line.
|
||||
if (r === 0 && lines.length > 0) {
|
||||
str = _this._renderInline(str, lines[lines.length - 1])
|
||||
}
|
||||
})
|
||||
|
||||
// remove trailing whitespace.
|
||||
lines.push({
|
||||
text: str.replace(/ +$/, ''),
|
||||
span: row.span
|
||||
})
|
||||
})
|
||||
|
||||
return lines
|
||||
}
|
||||
|
||||
function addBorder (col, ts, style) {
|
||||
if (col.border) {
|
||||
if (/[.']-+[.']/.test(ts)) return ''
|
||||
else if (ts.trim().length) return style
|
||||
else return ' '
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
// if the full 'source' can render in
|
||||
// the target line, do so.
|
||||
UI.prototype._renderInline = function (source, previousLine) {
|
||||
var leadingWhitespace = source.match(/^ */)[0].length
|
||||
var target = previousLine.text
|
||||
var targetTextWidth = stringWidth(target.trimRight())
|
||||
|
||||
if (!previousLine.span) return source
|
||||
|
||||
// if we're not applying wrapping logic,
|
||||
// just always append to the span.
|
||||
if (!this.wrap) {
|
||||
previousLine.hidden = true
|
||||
return target + source
|
||||
}
|
||||
|
||||
if (leadingWhitespace < targetTextWidth) return source
|
||||
|
||||
previousLine.hidden = true
|
||||
|
||||
return target.trimRight() + new Array(leadingWhitespace - targetTextWidth + 1).join(' ') + source.trimLeft()
|
||||
}
|
||||
|
||||
UI.prototype._rasterize = function (row) {
|
||||
var _this = this
|
||||
var i
|
||||
var rrow
|
||||
var rrows = []
|
||||
var widths = this._columnWidths(row)
|
||||
var wrapped
|
||||
|
||||
// word wrap all columns, and create
|
||||
// a data-structure that is easy to rasterize.
|
||||
row.forEach(function (col, c) {
|
||||
// leave room for left and right padding.
|
||||
col.width = widths[c]
|
||||
if (_this.wrap) wrapped = wrap(col.text, _this._negatePadding(col), {hard: true}).split('\n')
|
||||
else wrapped = col.text.split('\n')
|
||||
|
||||
if (col.border) {
|
||||
wrapped.unshift('.' + new Array(_this._negatePadding(col) + 3).join('-') + '.')
|
||||
wrapped.push("'" + new Array(_this._negatePadding(col) + 3).join('-') + "'")
|
||||
}
|
||||
|
||||
// add top and bottom padding.
|
||||
if (col.padding) {
|
||||
for (i = 0; i < (col.padding[top] || 0); i++) wrapped.unshift('')
|
||||
for (i = 0; i < (col.padding[bottom] || 0); i++) wrapped.push('')
|
||||
}
|
||||
|
||||
wrapped.forEach(function (str, r) {
|
||||
if (!rrows[r]) rrows.push([])
|
||||
|
||||
rrow = rrows[r]
|
||||
|
||||
for (var i = 0; i < c; i++) {
|
||||
if (rrow[i] === undefined) rrow.push('')
|
||||
}
|
||||
rrow.push(str)
|
||||
})
|
||||
})
|
||||
|
||||
return rrows
|
||||
}
|
||||
|
||||
UI.prototype._negatePadding = function (col) {
|
||||
var wrapWidth = col.width
|
||||
if (col.padding) wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0)
|
||||
if (col.border) wrapWidth -= 4
|
||||
return wrapWidth
|
||||
}
|
||||
|
||||
UI.prototype._columnWidths = function (row) {
|
||||
var _this = this
|
||||
var widths = []
|
||||
var unset = row.length
|
||||
var unsetWidth
|
||||
var remainingWidth = this.width
|
||||
|
||||
// column widths can be set in config.
|
||||
row.forEach(function (col, i) {
|
||||
if (col.width) {
|
||||
unset--
|
||||
widths[i] = col.width
|
||||
remainingWidth -= col.width
|
||||
} else {
|
||||
widths[i] = undefined
|
||||
}
|
||||
})
|
||||
|
||||
// any unset widths should be calculated.
|
||||
if (unset) unsetWidth = Math.floor(remainingWidth / unset)
|
||||
widths.forEach(function (w, i) {
|
||||
if (!_this.wrap) widths[i] = row[i].width || stringWidth(row[i].text)
|
||||
else if (w === undefined) widths[i] = Math.max(unsetWidth, _minWidth(row[i]))
|
||||
})
|
||||
|
||||
return widths
|
||||
}
|
||||
|
||||
// calculates the minimum width of
|
||||
// a column, based on padding preferences.
|
||||
function _minWidth (col) {
|
||||
var padding = col.padding || []
|
||||
var minWidth = 1 + (padding[left] || 0) + (padding[right] || 0)
|
||||
if (col.border) minWidth += 4
|
||||
return minWidth
|
||||
}
|
||||
|
||||
function alignRight (str, width) {
|
||||
str = str.trim()
|
||||
var padding = ''
|
||||
var strWidth = stringWidth(str)
|
||||
|
||||
if (strWidth < width) {
|
||||
padding = new Array(width - strWidth + 1).join(' ')
|
||||
}
|
||||
|
||||
return padding + str
|
||||
}
|
||||
|
||||
function alignCenter (str, width) {
|
||||
str = str.trim()
|
||||
var padding = ''
|
||||
var strWidth = stringWidth(str.trim())
|
||||
|
||||
if (strWidth < width) {
|
||||
padding = new Array(parseInt((width - strWidth) / 2, 10) + 1).join(' ')
|
||||
}
|
||||
|
||||
return padding + str
|
||||
}
|
||||
|
||||
module.exports = function (opts) {
|
||||
opts = opts || {}
|
||||
|
||||
return new UI({
|
||||
width: (opts || {}).width || 80,
|
||||
wrap: typeof opts.wrap === 'boolean' ? opts.wrap : true
|
||||
})
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"name": "cliui",
|
||||
"version": "3.2.0",
|
||||
"description": "easily create complex multi-column command-line-interfaces",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"pretest": "standard",
|
||||
"test": "nyc mocha",
|
||||
"coverage": "nyc --reporter=text-lcov mocha | coveralls",
|
||||
"version": "standard-version"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "http://github.com/yargs/cliui.git"
|
||||
},
|
||||
"config": {
|
||||
"blanket": {
|
||||
"pattern": [
|
||||
"index.js"
|
||||
],
|
||||
"data-cover-never": [
|
||||
"node_modules",
|
||||
"test"
|
||||
],
|
||||
"output-reporter": "spec"
|
||||
}
|
||||
},
|
||||
"standard": {
|
||||
"ignore": [
|
||||
"**/example/**"
|
||||
],
|
||||
"globals": [
|
||||
"it"
|
||||
]
|
||||
},
|
||||
"keywords": [
|
||||
"cli",
|
||||
"command-line",
|
||||
"layout",
|
||||
"design",
|
||||
"console",
|
||||
"wrap",
|
||||
"table"
|
||||
],
|
||||
"author": "Ben Coe <ben@npmjs.com>",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"string-width": "^1.0.1",
|
||||
"strip-ansi": "^3.0.1",
|
||||
"wrap-ansi": "^2.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"chai": "^3.5.0",
|
||||
"chalk": "^1.1.2",
|
||||
"coveralls": "^2.11.8",
|
||||
"mocha": "^2.4.5",
|
||||
"nyc": "^6.4.0",
|
||||
"standard": "^6.0.8",
|
||||
"standard-version": "^2.1.2"
|
||||
},
|
||||
"files": [
|
||||
"index.js"
|
||||
]
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014-2015, Jon Schlinkert.
|
||||
|
||||
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.
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
# extend-shallow [](http://badge.fury.io/js/extend-shallow) [](https://travis-ci.org/jonschlinkert/extend-shallow)
|
||||
|
||||
> Extend an object with the properties of additional objects. node.js/javascript util.
|
||||
|
||||
## Install
|
||||
|
||||
Install with [npm](https://www.npmjs.com/)
|
||||
|
||||
```sh
|
||||
$ npm i extend-shallow --save
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
var extend = require('extend-shallow');
|
||||
|
||||
extend({a: 'b'}, {c: 'd'})
|
||||
//=> {a: 'b', c: 'd'}
|
||||
```
|
||||
|
||||
Pass an empty object to shallow clone:
|
||||
|
||||
```js
|
||||
var obj = {};
|
||||
extend(obj, {a: 'b'}, {c: 'd'})
|
||||
//=> {a: 'b', c: 'd'}
|
||||
```
|
||||
|
||||
## Related
|
||||
|
||||
* [extend-shallow](https://github.com/jonschlinkert/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util.
|
||||
* [for-own](https://github.com/jonschlinkert/for-own): Iterate over the own enumerable properties of an object, and return an object with properties… [more](https://github.com/jonschlinkert/for-own)
|
||||
* [for-in](https://github.com/jonschlinkert/for-in): Iterate over the own and inherited enumerable properties of an objecte, and return an object… [more](https://github.com/jonschlinkert/for-in)
|
||||
* [is-plain-object](https://github.com/jonschlinkert/is-plain-object): Returns true if an object was created by the `Object` constructor.
|
||||
* [isobject](https://github.com/jonschlinkert/isobject): Returns true if the value is an object and not an array or null.
|
||||
* [kind-of](https://github.com/jonschlinkert/kind-of): Get the native type of a value.
|
||||
|
||||
## Running tests
|
||||
|
||||
Install dev dependencies:
|
||||
|
||||
```sh
|
||||
$ npm i -d && npm test
|
||||
```
|
||||
|
||||
## Author
|
||||
|
||||
**Jon Schlinkert**
|
||||
|
||||
+ [github/jonschlinkert](https://github.com/jonschlinkert)
|
||||
+ [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
|
||||
|
||||
## License
|
||||
|
||||
Copyright © 2015 Jon Schlinkert
|
||||
Released under the MIT license.
|
||||
|
||||
***
|
||||
|
||||
_This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on June 29, 2015._
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
'use strict';
|
||||
|
||||
var isObject = require('is-extendable');
|
||||
|
||||
module.exports = function extend(o/*, objects*/) {
|
||||
if (!isObject(o)) { o = {}; }
|
||||
|
||||
var len = arguments.length;
|
||||
for (var i = 1; i < len; i++) {
|
||||
var obj = arguments[i];
|
||||
|
||||
if (isObject(obj)) {
|
||||
assign(o, obj);
|
||||
}
|
||||
}
|
||||
return o;
|
||||
};
|
||||
|
||||
function assign(a, b) {
|
||||
for (var key in b) {
|
||||
if (hasOwn(b, key)) {
|
||||
a[key] = b[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the given `key` is an own property of `obj`.
|
||||
*/
|
||||
|
||||
function hasOwn(obj, key) {
|
||||
return Object.prototype.hasOwnProperty.call(obj, key);
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"name": "extend-shallow",
|
||||
"description": "Extend an object with the properties of additional objects. node.js/javascript util.",
|
||||
"version": "2.0.1",
|
||||
"homepage": "https://github.com/jonschlinkert/extend-shallow",
|
||||
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
|
||||
"repository": "jonschlinkert/extend-shallow",
|
||||
"bugs": {
|
||||
"url": "https://github.com/jonschlinkert/extend-shallow/issues"
|
||||
},
|
||||
"license": "MIT",
|
||||
"files": [
|
||||
"index.js"
|
||||
],
|
||||
"main": "index.js",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "mocha"
|
||||
},
|
||||
"dependencies": {
|
||||
"is-extendable": "^0.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"array-slice": "^0.2.3",
|
||||
"benchmarked": "^0.1.4",
|
||||
"chalk": "^1.0.0",
|
||||
"for-own": "^0.1.3",
|
||||
"glob": "^5.0.12",
|
||||
"is-plain-object": "^2.0.1",
|
||||
"kind-of": "^2.0.0",
|
||||
"minimist": "^1.1.1",
|
||||
"mocha": "^2.2.5",
|
||||
"should": "^7.0.1"
|
||||
},
|
||||
"keywords": [
|
||||
"assign",
|
||||
"extend",
|
||||
"javascript",
|
||||
"js",
|
||||
"keys",
|
||||
"merge",
|
||||
"obj",
|
||||
"object",
|
||||
"prop",
|
||||
"properties",
|
||||
"property",
|
||||
"props",
|
||||
"shallow",
|
||||
"util",
|
||||
"utility",
|
||||
"utils",
|
||||
"value"
|
||||
]
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014-2017, Jon Schlinkert
|
||||
|
||||
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.
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
# fill-range [](https://www.npmjs.com/package/fill-range) [](https://npmjs.org/package/fill-range) [](https://npmjs.org/package/fill-range) [](https://travis-ci.org/jonschlinkert/fill-range)
|
||||
|
||||
> Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Install](#install)
|
||||
- [Usage](#usage)
|
||||
- [Examples](#examples)
|
||||
- [Options](#options)
|
||||
* [options.step](#optionsstep)
|
||||
* [options.strictRanges](#optionsstrictranges)
|
||||
* [options.stringify](#optionsstringify)
|
||||
* [options.toRegex](#optionstoregex)
|
||||
* [options.transform](#optionstransform)
|
||||
- [About](#about)
|
||||
|
||||
_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_
|
||||
|
||||
## Install
|
||||
|
||||
Install with [npm](https://www.npmjs.com/):
|
||||
|
||||
```sh
|
||||
$ npm install --save fill-range
|
||||
```
|
||||
|
||||
Install with [yarn](https://yarnpkg.com):
|
||||
|
||||
```sh
|
||||
$ yarn add fill-range
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Expands numbers and letters, optionally using a `step` as the last argument. _(Numbers may be defined as JavaScript numbers or strings)_.
|
||||
|
||||
```js
|
||||
var fill = require('fill-range');
|
||||
fill(from, to[, step, options]);
|
||||
|
||||
// examples
|
||||
console.log(fill('1', '10')); //=> '[ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10' ]'
|
||||
console.log(fill('1', '10', {toRegex: true})); //=> [1-9]|10
|
||||
```
|
||||
|
||||
**Params**
|
||||
|
||||
* `from`: **{String|Number}** the number or letter to start with
|
||||
* `to`: **{String|Number}** the number or letter to end with
|
||||
* `step`: **{String|Number|Object|Function}** Optionally pass a [step](#optionsstep) to use.
|
||||
* `options`: **{Object|Function}**: See all available [options](#options)
|
||||
|
||||
## Examples
|
||||
|
||||
By default, an array of values is returned.
|
||||
|
||||
**Alphabetical ranges**
|
||||
|
||||
```js
|
||||
console.log(fill('a', 'e')); //=> ['a', 'b', 'c', 'd', 'e']
|
||||
console.log(fill('A', 'E')); //=> [ 'A', 'B', 'C', 'D', 'E' ]
|
||||
```
|
||||
|
||||
**Numerical ranges**
|
||||
|
||||
Numbers can be defined as actual numbers or strings.
|
||||
|
||||
```js
|
||||
console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ]
|
||||
console.log(fill('1', '5')); //=> [ 1, 2, 3, 4, 5 ]
|
||||
```
|
||||
|
||||
**Negative ranges**
|
||||
|
||||
Numbers can be defined as actual numbers or strings.
|
||||
|
||||
```js
|
||||
console.log(fill('-5', '-1')); //=> [ '-5', '-4', '-3', '-2', '-1' ]
|
||||
console.log(fill('-5', '5')); //=> [ '-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5' ]
|
||||
```
|
||||
|
||||
**Steps (increments)**
|
||||
|
||||
```js
|
||||
// numerical ranges with increments
|
||||
console.log(fill('0', '25', 4)); //=> [ '0', '4', '8', '12', '16', '20', '24' ]
|
||||
console.log(fill('0', '25', 5)); //=> [ '0', '5', '10', '15', '20', '25' ]
|
||||
console.log(fill('0', '25', 6)); //=> [ '0', '6', '12', '18', '24' ]
|
||||
|
||||
// alphabetical ranges with increments
|
||||
console.log(fill('a', 'z', 4)); //=> [ 'a', 'e', 'i', 'm', 'q', 'u', 'y' ]
|
||||
console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ]
|
||||
console.log(fill('a', 'z', 6)); //=> [ 'a', 'g', 'm', 's', 'y' ]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
### options.step
|
||||
|
||||
**Type**: `number` (formatted as a string or number)
|
||||
|
||||
**Default**: `undefined`
|
||||
|
||||
**Description**: The increment to use for the range. Can be used with letters or numbers.
|
||||
|
||||
**Example(s)**
|
||||
|
||||
```js
|
||||
// numbers
|
||||
console.log(fill('1', '10', 2)); //=> [ '1', '3', '5', '7', '9' ]
|
||||
console.log(fill('1', '10', 3)); //=> [ '1', '4', '7', '10' ]
|
||||
console.log(fill('1', '10', 4)); //=> [ '1', '5', '9' ]
|
||||
|
||||
// letters
|
||||
console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ]
|
||||
console.log(fill('a', 'z', 7)); //=> [ 'a', 'h', 'o', 'v' ]
|
||||
console.log(fill('a', 'z', 9)); //=> [ 'a', 'j', 's' ]
|
||||
```
|
||||
|
||||
### options.strictRanges
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `false`
|
||||
|
||||
**Description**: By default, `null` is returned when an invalid range is passed. Enable this option to throw a `RangeError` on invalid ranges.
|
||||
|
||||
**Example(s)**
|
||||
|
||||
The following are all invalid:
|
||||
|
||||
```js
|
||||
fill('1.1', '2'); // decimals not supported in ranges
|
||||
fill('a', '2'); // incompatible range values
|
||||
fill(1, 10, 'foo'); // invalid "step" argument
|
||||
```
|
||||
|
||||
### options.stringify
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `undefined`
|
||||
|
||||
**Description**: Cast all returned values to strings. By default, integers are returned as numbers.
|
||||
|
||||
**Example(s)**
|
||||
|
||||
```js
|
||||
console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ]
|
||||
console.log(fill(1, 5, {stringify: true})); //=> [ '1', '2', '3', '4', '5' ]
|
||||
```
|
||||
|
||||
### options.toRegex
|
||||
|
||||
**Type**: `boolean`
|
||||
|
||||
**Default**: `undefined`
|
||||
|
||||
**Description**: Create a regex-compatible source string, instead of expanding values to an array.
|
||||
|
||||
**Example(s)**
|
||||
|
||||
```js
|
||||
// alphabetical range
|
||||
console.log(fill('a', 'e', {toRegex: true})); //=> '[a-e]'
|
||||
// alphabetical with step
|
||||
console.log(fill('a', 'z', 3, {toRegex: true})); //=> 'a|d|g|j|m|p|s|v|y'
|
||||
// numerical range
|
||||
console.log(fill('1', '100', {toRegex: true})); //=> '[1-9]|[1-9][0-9]|100'
|
||||
// numerical range with zero padding
|
||||
console.log(fill('000001', '100000', {toRegex: true}));
|
||||
//=> '0{5}[1-9]|0{4}[1-9][0-9]|0{3}[1-9][0-9]{2}|0{2}[1-9][0-9]{3}|0[1-9][0-9]{4}|100000'
|
||||
```
|
||||
|
||||
### options.transform
|
||||
|
||||
**Type**: `function`
|
||||
|
||||
**Default**: `undefined`
|
||||
|
||||
**Description**: Customize each value in the returned array (or [string](#optionstoRegex)). _(you can also pass this function as the last argument to `fill()`)_.
|
||||
|
||||
**Example(s)**
|
||||
|
||||
```js
|
||||
// increase padding by two
|
||||
var arr = fill('01', '05', function(val, a, b, step, idx, arr, options) {
|
||||
return repeat('0', (options.maxLength + 2) - val.length) + val;
|
||||
});
|
||||
|
||||
console.log(arr);
|
||||
//=> ['0001', '0002', '0003', '0004', '0005']
|
||||
```
|
||||
|
||||
## About
|
||||
|
||||
### Related projects
|
||||
|
||||
* [braces](https://www.npmjs.com/package/braces): Fast, comprehensive, bash-like brace expansion implemented in JavaScript. Complete support for the Bash 4.3 braces… [more](https://github.com/jonschlinkert/braces) | [homepage](https://github.com/jonschlinkert/braces "Fast, comprehensive, bash-like brace expansion implemented in JavaScript. Complete support for the Bash 4.3 braces specification, without sacrificing speed.")
|
||||
* [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. See… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. See the benchmarks. Used by micromatch.")
|
||||
* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.")
|
||||
* [to-regex-range](https://www.npmjs.com/package/to-regex-range): Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than… [more](https://github.com/jonschlinkert/to-regex-range) | [homepage](https://github.com/jonschlinkert/to-regex-range "Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.87 million test assertions.")
|
||||
|
||||
### Contributing
|
||||
|
||||
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
|
||||
|
||||
### Contributors
|
||||
|
||||
| **Commits** | **Contributor** |
|
||||
| --- | --- |
|
||||
| 103 | [jonschlinkert](https://github.com/jonschlinkert) |
|
||||
| 2 | [paulmillr](https://github.com/paulmillr) |
|
||||
| 1 | [edorivai](https://github.com/edorivai) |
|
||||
| 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) |
|
||||
|
||||
### Building docs
|
||||
|
||||
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
|
||||
|
||||
To generate the readme, run the following command:
|
||||
|
||||
```sh
|
||||
$ npm install -g verbose/verb#dev verb-generate-readme && verb
|
||||
```
|
||||
|
||||
### Running tests
|
||||
|
||||
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
|
||||
|
||||
```sh
|
||||
$ npm install && npm test
|
||||
```
|
||||
|
||||
### Author
|
||||
|
||||
**Jon Schlinkert**
|
||||
|
||||
* [github/jonschlinkert](https://github.com/jonschlinkert)
|
||||
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
|
||||
|
||||
### License
|
||||
|
||||
Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert).
|
||||
Released under the [MIT License](LICENSE).
|
||||
|
||||
***
|
||||
|
||||
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.5.0, on April 23, 2017._
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
/*!
|
||||
* fill-range <https://github.com/jonschlinkert/fill-range>
|
||||
*
|
||||
* Copyright (c) 2014-2015, 2017, Jon Schlinkert.
|
||||
* Released under the MIT License.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var util = require('util');
|
||||
var isNumber = require('is-number');
|
||||
var extend = require('extend-shallow');
|
||||
var repeat = require('repeat-string');
|
||||
var toRegex = require('to-regex-range');
|
||||
|
||||
/**
|
||||
* Return a range of numbers or letters.
|
||||
*
|
||||
* @param {String} `start` Start of the range
|
||||
* @param {String} `stop` End of the range
|
||||
* @param {String} `step` Increment or decrement to use.
|
||||
* @param {Function} `fn` Custom function to modify each element in the range.
|
||||
* @return {Array}
|
||||
*/
|
||||
|
||||
function fillRange(start, stop, step, options) {
|
||||
if (typeof start === 'undefined') {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (typeof stop === 'undefined' || start === stop) {
|
||||
// special case, for handling negative zero
|
||||
var isString = typeof start === 'string';
|
||||
if (isNumber(start) && !toNumber(start)) {
|
||||
return [isString ? '0' : 0];
|
||||
}
|
||||
return [start];
|
||||
}
|
||||
|
||||
if (typeof step !== 'number' && typeof step !== 'string') {
|
||||
options = step;
|
||||
step = undefined;
|
||||
}
|
||||
|
||||
if (typeof options === 'function') {
|
||||
options = { transform: options };
|
||||
}
|
||||
|
||||
var opts = extend({step: step}, options);
|
||||
if (opts.step && !isValidNumber(opts.step)) {
|
||||
if (opts.strictRanges === true) {
|
||||
throw new TypeError('expected options.step to be a number');
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
opts.isNumber = isValidNumber(start) && isValidNumber(stop);
|
||||
if (!opts.isNumber && !isValid(start, stop)) {
|
||||
if (opts.strictRanges === true) {
|
||||
throw new RangeError('invalid range arguments: ' + util.inspect([start, stop]));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
opts.isPadded = isPadded(start) || isPadded(stop);
|
||||
opts.toString = opts.stringify
|
||||
|| typeof opts.step === 'string'
|
||||
|| typeof start === 'string'
|
||||
|| typeof stop === 'string'
|
||||
|| !opts.isNumber;
|
||||
|
||||
if (opts.isPadded) {
|
||||
opts.maxLength = Math.max(String(start).length, String(stop).length);
|
||||
}
|
||||
|
||||
// support legacy minimatch/fill-range options
|
||||
if (typeof opts.optimize === 'boolean') opts.toRegex = opts.optimize;
|
||||
if (typeof opts.makeRe === 'boolean') opts.toRegex = opts.makeRe;
|
||||
return expand(start, stop, opts);
|
||||
}
|
||||
|
||||
function expand(start, stop, options) {
|
||||
var a = options.isNumber ? toNumber(start) : start.charCodeAt(0);
|
||||
var b = options.isNumber ? toNumber(stop) : stop.charCodeAt(0);
|
||||
|
||||
var step = Math.abs(toNumber(options.step)) || 1;
|
||||
if (options.toRegex && step === 1) {
|
||||
return toRange(a, b, start, stop, options);
|
||||
}
|
||||
|
||||
var zero = {greater: [], lesser: []};
|
||||
var asc = a < b;
|
||||
var arr = new Array(Math.round((asc ? b - a : a - b) / step));
|
||||
var idx = 0;
|
||||
|
||||
while (asc ? a <= b : a >= b) {
|
||||
var val = options.isNumber ? a : String.fromCharCode(a);
|
||||
if (options.toRegex && (val >= 0 || !options.isNumber)) {
|
||||
zero.greater.push(val);
|
||||
} else {
|
||||
zero.lesser.push(Math.abs(val));
|
||||
}
|
||||
|
||||
if (options.isPadded) {
|
||||
val = zeros(val, options);
|
||||
}
|
||||
|
||||
if (options.toString) {
|
||||
val = String(val);
|
||||
}
|
||||
|
||||
if (typeof options.transform === 'function') {
|
||||
arr[idx++] = options.transform(val, a, b, step, idx, arr, options);
|
||||
} else {
|
||||
arr[idx++] = val;
|
||||
}
|
||||
|
||||
if (asc) {
|
||||
a += step;
|
||||
} else {
|
||||
a -= step;
|
||||
}
|
||||
}
|
||||
|
||||
if (options.toRegex === true) {
|
||||
return toSequence(arr, zero, options);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
function toRange(a, b, start, stop, options) {
|
||||
if (options.isPadded) {
|
||||
return toRegex(start, stop, options);
|
||||
}
|
||||
|
||||
if (options.isNumber) {
|
||||
return toRegex(Math.min(a, b), Math.max(a, b), options);
|
||||
}
|
||||
|
||||
var start = String.fromCharCode(Math.min(a, b));
|
||||
var stop = String.fromCharCode(Math.max(a, b));
|
||||
return '[' + start + '-' + stop + ']';
|
||||
}
|
||||
|
||||
function toSequence(arr, zeros, options) {
|
||||
var greater = '', lesser = '';
|
||||
if (zeros.greater.length) {
|
||||
greater = zeros.greater.join('|');
|
||||
}
|
||||
if (zeros.lesser.length) {
|
||||
lesser = '-(' + zeros.lesser.join('|') + ')';
|
||||
}
|
||||
var res = greater && lesser
|
||||
? greater + '|' + lesser
|
||||
: greater || lesser;
|
||||
|
||||
if (options.capture) {
|
||||
return '(' + res + ')';
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
function zeros(val, options) {
|
||||
if (options.isPadded) {
|
||||
var str = String(val);
|
||||
var len = str.length;
|
||||
var dash = '';
|
||||
if (str.charAt(0) === '-') {
|
||||
dash = '-';
|
||||
str = str.slice(1);
|
||||
}
|
||||
var diff = options.maxLength - len;
|
||||
var pad = repeat('0', diff);
|
||||
val = (dash + pad + str);
|
||||
}
|
||||
if (options.stringify) {
|
||||
return String(val);
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
function toNumber(val) {
|
||||
return Number(val) || 0;
|
||||
}
|
||||
|
||||
function isPadded(str) {
|
||||
return /^-?0\d/.test(str);
|
||||
}
|
||||
|
||||
function isValid(min, max) {
|
||||
return (isValidNumber(min) || isValidLetter(min))
|
||||
&& (isValidNumber(max) || isValidLetter(max));
|
||||
}
|
||||
|
||||
function isValidLetter(ch) {
|
||||
return typeof ch === 'string' && ch.length === 1 && /^\w+$/.test(ch);
|
||||
}
|
||||
|
||||
function isValidNumber(n) {
|
||||
return isNumber(n) && !/\./.test(n);
|
||||
}
|
||||
|
||||
/**
|
||||
* Expose `fillRange`
|
||||
* @type {Function}
|
||||
*/
|
||||
|
||||
module.exports = fillRange;
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
{
|
||||
"name": "fill-range",
|
||||
"description": "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`",
|
||||
"version": "4.0.0",
|
||||
"homepage": "https://github.com/jonschlinkert/fill-range",
|
||||
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
|
||||
"contributors": [
|
||||
"<wtgtybhertgeghgtwtg@gmail.com> (https://github.com/wtgtybhertgeghgtwtg)",
|
||||
"Edo Rivai <edo.rivai@gmail.com> (edo.rivai.nl)",
|
||||
"Jon Schlinkert <jon.schlinkert@sellside.com> (http://twitter.com/jonschlinkert)",
|
||||
"Paul Miller <paul+gh@paulmillr.com> (paulmillr.com)"
|
||||
],
|
||||
"repository": "jonschlinkert/fill-range",
|
||||
"bugs": {
|
||||
"url": "https://github.com/jonschlinkert/fill-range/issues"
|
||||
},
|
||||
"license": "MIT",
|
||||
"files": [
|
||||
"index.js"
|
||||
],
|
||||
"main": "index.js",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "mocha"
|
||||
},
|
||||
"dependencies": {
|
||||
"extend-shallow": "^2.0.1",
|
||||
"is-number": "^3.0.0",
|
||||
"repeat-string": "^1.6.1",
|
||||
"to-regex-range": "^2.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"ansi-cyan": "^0.1.1",
|
||||
"benchmarked": "^1.0.0",
|
||||
"gulp-format-md": "^0.1.12",
|
||||
"minimist": "^1.2.0",
|
||||
"mocha": "^3.2.0"
|
||||
},
|
||||
"keywords": [
|
||||
"alpha",
|
||||
"alphabetical",
|
||||
"array",
|
||||
"bash",
|
||||
"brace",
|
||||
"expand",
|
||||
"expansion",
|
||||
"fill",
|
||||
"glob",
|
||||
"match",
|
||||
"matches",
|
||||
"matching",
|
||||
"number",
|
||||
"numerical",
|
||||
"range",
|
||||
"ranges",
|
||||
"regex",
|
||||
"sh"
|
||||
],
|
||||
"verb": {
|
||||
"related": {
|
||||
"list": [
|
||||
"braces",
|
||||
"expand-range",
|
||||
"micromatch",
|
||||
"to-regex-range"
|
||||
]
|
||||
},
|
||||
"toc": true,
|
||||
"layout": "default",
|
||||
"tasks": [
|
||||
"readme"
|
||||
],
|
||||
"plugins": [
|
||||
"gulp-format-md"
|
||||
],
|
||||
"lint": {
|
||||
"reflinks": true
|
||||
}
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
var path = require('path');
|
||||
var pathExists = require('path-exists');
|
||||
var Promise = require('pinkie-promise');
|
||||
|
||||
function splitPath(x) {
|
||||
return path.resolve(x || '').split(path.sep);
|
||||
}
|
||||
|
||||
function join(parts, filename) {
|
||||
return path.resolve(parts.join(path.sep) + path.sep, filename);
|
||||
}
|
||||
|
||||
module.exports = function (filename, opts) {
|
||||
opts = opts || {};
|
||||
|
||||
var parts = splitPath(opts.cwd);
|
||||
|
||||
return new Promise(function (resolve) {
|
||||
(function find() {
|
||||
var fp = join(parts, filename);
|
||||
|
||||
pathExists(fp).then(function (exists) {
|
||||
if (exists) {
|
||||
resolve(fp);
|
||||
} else if (parts.pop()) {
|
||||
find();
|
||||
} else {
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
})();
|
||||
});
|
||||
};
|
||||
|
||||
module.exports.sync = function (filename, opts) {
|
||||
opts = opts || {};
|
||||
|
||||
var parts = splitPath(opts.cwd);
|
||||
var len = parts.length;
|
||||
|
||||
while (len--) {
|
||||
var fp = join(parts, filename);
|
||||
|
||||
if (pathExists.sync(fp)) {
|
||||
return fp;
|
||||
}
|
||||
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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.
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "find-up",
|
||||
"version": "1.1.2",
|
||||
"description": "Find a file by walking up parent directories",
|
||||
"license": "MIT",
|
||||
"repository": "sindresorhus/find-up",
|
||||
"author": {
|
||||
"name": "Sindre Sorhus",
|
||||
"email": "sindresorhus@gmail.com",
|
||||
"url": "sindresorhus.com"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "xo && ava"
|
||||
},
|
||||
"files": [
|
||||
"index.js"
|
||||
],
|
||||
"keywords": [
|
||||
"find",
|
||||
"up",
|
||||
"find-up",
|
||||
"findup",
|
||||
"look-up",
|
||||
"look",
|
||||
"file",
|
||||
"search",
|
||||
"match",
|
||||
"package",
|
||||
"resolve",
|
||||
"parent",
|
||||
"parents",
|
||||
"folder",
|
||||
"directory",
|
||||
"dir",
|
||||
"walk",
|
||||
"walking",
|
||||
"path"
|
||||
],
|
||||
"dependencies": {
|
||||
"path-exists": "^2.0.0",
|
||||
"pinkie-promise": "^2.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"ava": "*",
|
||||
"tempfile": "^1.1.1",
|
||||
"xo": "*"
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
# find-up [](https://travis-ci.org/sindresorhus/find-up)
|
||||
|
||||
> Find a file by walking up parent directories
|
||||
|
||||
|
||||
## Install
|
||||
|
||||
```
|
||||
$ npm install --save find-up
|
||||
```
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
```
|
||||
/
|
||||
└── Users
|
||||
└── sindresorhus
|
||||
├── unicorn.png
|
||||
└── foo
|
||||
└── bar
|
||||
├── baz
|
||||
└── example.js
|
||||
```
|
||||
|
||||
```js
|
||||
// example.js
|
||||
const findUp = require('find-up');
|
||||
|
||||
findUp('unicorn.png').then(filepath => {
|
||||
console.log(filepath);
|
||||
//=> '/Users/sindresorhus/unicorn.png'
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
## API
|
||||
|
||||
### findUp(filename, [options])
|
||||
|
||||
Returns a promise for the filepath or `null`.
|
||||
|
||||
### findUp.sync(filename, [options])
|
||||
|
||||
Returns a filepath or `null`.
|
||||
|
||||
#### filename
|
||||
|
||||
Type: `string`
|
||||
|
||||
Filename of the file to find.
|
||||
|
||||
#### options
|
||||
|
||||
##### cwd
|
||||
|
||||
Type: `string`
|
||||
Default: `process.cwd()`
|
||||
|
||||
Directory to start from.
|
||||
|
||||
|
||||
## Related
|
||||
|
||||
- [find-up-cli](https://github.com/sindresorhus/find-up-cli) - CLI for this module
|
||||
- [pkg-up](https://github.com/sindresorhus/pkg-up) - Find the closest package.json file
|
||||
- [pkg-dir](https://github.com/sindresorhus/pkg-dir) - Find the root directory of an npm package
|
||||
|
||||
|
||||
## License
|
||||
|
||||
MIT © [Sindre Sorhus](http://sindresorhus.com)
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
language: objective-c
|
||||
|
||||
|
||||
env:
|
||||
global:
|
||||
- secure: "gve1nkeKkwFEG1VAT3i+JwYyAdF0gKXwKx0uxbkBTsmm2M+0MDusohQdFLoEIkSIFktXBIDefoa7iGpLKRfG2VsZLpwJgnvnD0HqbnuR+k+W+bu7BHt4CAaR6GTllsDCjyq9zNyhUThzSnf2WNIpOEF5kHspZlbGfawURuUJH/U="
|
||||
- secure: "jqVpmWxxBVXu2X8+XJMpKH0cooc2EKz9xKL2znBfYdNafJORSXcFAVbjCX5mZmVDcgIMwDtm2+gIG4P73hzJ2e3S+y2Z9ROJGyXHa3AxUTvXHQsxqzH8coHHqB8vTvfr0t2O5aKfpvpICpSea39r0hzNoMv6Ie5SwBdqj1YY9K0="
|
||||
matrix:
|
||||
- NODE_VERSION="v13"
|
||||
- NODE_VERSION="v12"
|
||||
- NODE_VERSION="v11"
|
||||
- NODE_VERSION="v10"
|
||||
- NODE_VERSION="v9"
|
||||
- NODE_VERSION="v8"
|
||||
- NODE_VERSION="v7"
|
||||
- NODE_VERSION="v6"
|
||||
|
||||
before_install:
|
||||
|
||||
- echo $TRAVIS_OS_NAME
|
||||
|
||||
# commit
|
||||
# ------------------------
|
||||
# The commit message is used to determine the whether to manually
|
||||
# invoke a binary publish
|
||||
|
||||
- COMMIT_MESSAGE=$(git show -s --format=%B $TRAVIS_COMMIT | tr -d '\n')
|
||||
|
||||
# node
|
||||
# ------------------------
|
||||
|
||||
- export PATH=./node_modules/.bin/:$PATH
|
||||
- rm -rf ~/.nvm && git clone --depth 1 https://github.com/creationix/nvm.git ~/.nvm
|
||||
- source ~/.nvm/nvm.sh
|
||||
- nvm install $NODE_VERSION
|
||||
- nvm use $NODE_VERSION
|
||||
- npm install -g npm@3
|
||||
- node --version
|
||||
- npm --version
|
||||
- nvm --version
|
||||
|
||||
# publish dependencies
|
||||
# ------------------------
|
||||
|
||||
- npm install node-gyp -g
|
||||
- npm install aws-sdk
|
||||
|
||||
install:
|
||||
|
||||
# in the first instance we build from source to create the initial binary
|
||||
# which can then be used to create a package
|
||||
|
||||
- npm install --build-from-source
|
||||
- npm test
|
||||
|
||||
before_script:
|
||||
|
||||
# Detemine if a publish is required.
|
||||
#
|
||||
# a) we are building a tag
|
||||
# b) we put [publish binary] in the commit message
|
||||
|
||||
- PUBLISH_BINARY=false
|
||||
|
||||
- if [[ $TRAVIS_BRANCH == `git describe --tags --always HEAD` ]]; then PUBLISH_BINARY=true; fi; # a
|
||||
- if test "${COMMIT_MESSAGE#*'[publish binary]'}" != "$COMMIT_MESSAGE"; then PUBLISH_BINARY=true; fi; # b
|
||||
|
||||
# package & publish
|
||||
# ------------------------
|
||||
|
||||
- if [[ $PUBLISH_BINARY == true ]]; then ./node_modules/.bin/node-pre-gyp package publish; fi;
|
||||
|
||||
# clean-up
|
||||
# ------------------------
|
||||
|
||||
- ./node_modules/.bin/node-pre-gyp clean
|
||||
- node-gyp clean
|
||||
|
||||
script:
|
||||
|
||||
# validate
|
||||
# ------------------------
|
||||
# Post publishing a release verify that installing will pull down latest
|
||||
# binary from remote host
|
||||
|
||||
- INSTALL_RESULT=0
|
||||
- if [[ $PUBLISH_BINARY == true ]]; then INSTALL_RESULT=$(npm install --fallback-to-build=false > /dev/null)$? || true; fi;
|
||||
|
||||
- ./node_modules/.bin/node-pre-gyp clean
|
||||
|
||||
# failure?
|
||||
# ------------------------
|
||||
# if install returned non zero (errored) then we first unpublish and then
|
||||
# call false so travis will bail at this line.
|
||||
|
||||
- if [[ $INSTALL_RESULT != 0 ]]; then ./node_modules/.bin/node-pre-gyp unpublish; fi;
|
||||
- if [[ $INSTALL_RESULT != 0 ]]; then echo "returned $INSTALL_RESULT";false; fi;
|
||||
|
||||
after_success:
|
||||
|
||||
# display all published binaries
|
||||
|
||||
- npm run node-pre-gyp info
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
If you are NOT on OS X and have come here to file an issue about compatibility problems,
|
||||
please stop and go to #115 for your answer.
|
||||
|
||||
You can look through many other similar closed issues as well if you're interested:
|
||||
https://github.com/strongloop/fsevents/search?utf8=%E2%9C%93&q=%22notsup%22+OR+%22EBADPLATFORM%22&type=Issues.
|
||||
|
||||
If you are here to report an issue observed while using this module on OS X, please delete
|
||||
all this pre-filled text then go ahead and submit your report.
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
MIT License
|
||||
-----------
|
||||
|
||||
Copyright (C) 2010-2014 Philipp Dunkel
|
||||
|
||||
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.
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
# fsevents [](https://nodei.co/npm/fsevents/)
|
||||
|
||||
Native access to OS X FSEvents in [Node.js](http://nodejs.org/)
|
||||
|
||||
The FSEvents API in OS X allows applications to register for notifications of
|
||||
changes to a given directory tree. It is a very fast and lightweight alternative
|
||||
to kqueue.
|
||||
|
||||
This is a low-level library. For a cross-compatible file watching module that
|
||||
uses fsevents, check out [Chokidar](https://www.npmjs.com/package/chokidar).
|
||||
|
||||
* [Module Site & GitHub](https://github.com/strongloop/fsevents)
|
||||
* [NPM Page](https://npmjs.org/package/fsevents)
|
||||
|
||||
## Installation
|
||||
|
||||
$ npm install fsevents
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
var fsevents = require('fsevents');
|
||||
var watcher = fsevents(__dirname);
|
||||
watcher.on('fsevent', function(path, flags, id) { }); // RAW Event as emitted by OS-X
|
||||
watcher.on('change', function(path, info) { }); // Common Event for all changes
|
||||
watcher.start() // To start observation
|
||||
watcher.stop() // To end observation
|
||||
```
|
||||
|
||||
### Events
|
||||
|
||||
* *fsevent* - RAW Event as emitted by OS-X
|
||||
* *change* - Common Event for all changes
|
||||
* *created* - A File-System-Item has been created
|
||||
* *deleted* - A File-System-Item has been deleted
|
||||
* *modified* - A File-System-Item has been modified
|
||||
* *moved-out* - A File-System-Item has been moved away from this location
|
||||
* *moved-in* - A File-System-Item has been moved into this location
|
||||
|
||||
All events except *fsevent* take an *info* object as the second parameter of the callback. The structure of this object is:
|
||||
|
||||
```js
|
||||
{
|
||||
"event": "<event-type>",
|
||||
"id": <eventi-id>,
|
||||
"path": "<path-that-this-is-about>",
|
||||
"type": "<file|directory|symlink>",
|
||||
"changes": {
|
||||
"inode": true, // Has the iNode Meta-Information changed
|
||||
"finder": false, // Has the Finder Meta-Data changed
|
||||
"access": false, // Have the access permissions changed
|
||||
"xattrs": false // Have the xAttributes changed
|
||||
},
|
||||
"flags": <raw-flags>
|
||||
}
|
||||
```
|
||||
|
||||
## MIT License
|
||||
|
||||
Copyright (C) 2010-2014 Philipp Dunkel
|
||||
|
||||
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.
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"targets": [
|
||||
{ "target_name": "" }
|
||||
],
|
||||
"conditions": [
|
||||
['OS=="mac"', {
|
||||
"targets": [{
|
||||
"target_name": "fse",
|
||||
"sources": ["fsevents.cc"],
|
||||
"xcode_settings": {
|
||||
"OTHER_LDFLAGS": [
|
||||
"-framework CoreFoundation -framework CoreServices"
|
||||
]
|
||||
},
|
||||
"include_dirs": [
|
||||
"<!(node -e \"require('nan')\")"
|
||||
]
|
||||
}]
|
||||
}]
|
||||
]
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
# This file is generated by gyp; do not edit.
|
||||
|
||||
TOOLSET := target
|
||||
TARGET :=
|
||||
### Rules for final target.
|
||||
LDFLAGS_Debug := \
|
||||
-undefined dynamic_lookup \
|
||||
-Wl,-search_paths_first \
|
||||
-mmacosx-version-min=11.0 \
|
||||
-arch \
|
||||
arm64 \
|
||||
-L$(builddir) \
|
||||
-stdlib=libc++
|
||||
|
||||
LIBTOOLFLAGS_Debug := \
|
||||
-undefined dynamic_lookup \
|
||||
-Wl,-search_paths_first
|
||||
|
||||
LDFLAGS_Release := \
|
||||
-undefined dynamic_lookup \
|
||||
-Wl,-search_paths_first \
|
||||
-mmacosx-version-min=11.0 \
|
||||
-arch \
|
||||
arm64 \
|
||||
-L$(builddir) \
|
||||
-stdlib=libc++
|
||||
|
||||
LIBTOOLFLAGS_Release := \
|
||||
-undefined dynamic_lookup \
|
||||
-Wl,-search_paths_first
|
||||
|
||||
LIBS :=
|
||||
|
||||
$(builddir)/.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))
|
||||
$(builddir)/.node: LIBS := $(LIBS)
|
||||
$(builddir)/.node: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))
|
||||
$(builddir)/.node: TOOLSET := $(TOOLSET)
|
||||
$(builddir)/.node: FORCE_DO_CMD
|
||||
$(call do_cmd,solink_module)
|
||||
|
||||
all_deps += $(builddir)/.node
|
||||
# Add target alias
|
||||
.PHONY:
|
||||
: $(builddir)/.node
|
||||
|
||||
# Short alias for building this executable.
|
||||
.PHONY: .node
|
||||
.node: $(builddir)/.node
|
||||
|
||||
# Add executable to "all" target.
|
||||
.PHONY: all
|
||||
all: $(builddir)/.node
|
||||
|
||||
+352
@@ -0,0 +1,352 @@
|
||||
# We borrow heavily from the kernel build setup, though we are simpler since
|
||||
# we don't have Kconfig tweaking settings on us.
|
||||
|
||||
# The implicit make rules have it looking for RCS files, among other things.
|
||||
# We instead explicitly write all the rules we care about.
|
||||
# It's even quicker (saves ~200ms) to pass -r on the command line.
|
||||
MAKEFLAGS=-r
|
||||
|
||||
# The source directory tree.
|
||||
srcdir := ..
|
||||
abs_srcdir := $(abspath $(srcdir))
|
||||
|
||||
# The name of the builddir.
|
||||
builddir_name ?= .
|
||||
|
||||
# The V=1 flag on command line makes us verbosely print command lines.
|
||||
ifdef V
|
||||
quiet=
|
||||
else
|
||||
quiet=quiet_
|
||||
endif
|
||||
|
||||
# Specify BUILDTYPE=Release on the command line for a release build.
|
||||
BUILDTYPE ?= Release
|
||||
|
||||
# Directory all our build output goes into.
|
||||
# Note that this must be two directories beneath src/ for unit tests to pass,
|
||||
# as they reach into the src/ directory for data with relative paths.
|
||||
builddir ?= $(builddir_name)/$(BUILDTYPE)
|
||||
abs_builddir := $(abspath $(builddir))
|
||||
depsdir := $(builddir)/.deps
|
||||
|
||||
# Object output directory.
|
||||
obj := $(builddir)/obj
|
||||
abs_obj := $(abspath $(obj))
|
||||
|
||||
# We build up a list of every single one of the targets so we can slurp in the
|
||||
# generated dependency rule Makefiles in one pass.
|
||||
all_deps :=
|
||||
|
||||
|
||||
|
||||
CC.target ?= $(CC)
|
||||
CFLAGS.target ?= $(CPPFLAGS) $(CFLAGS)
|
||||
CXX.target ?= $(CXX)
|
||||
CXXFLAGS.target ?= $(CPPFLAGS) $(CXXFLAGS)
|
||||
LINK.target ?= $(LINK)
|
||||
LDFLAGS.target ?= $(LDFLAGS)
|
||||
AR.target ?= $(AR)
|
||||
PLI.target ?= pli
|
||||
|
||||
# C++ apps need to be linked with g++.
|
||||
LINK ?= $(CXX.target)
|
||||
|
||||
# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
|
||||
# to replicate this environment fallback in make as well.
|
||||
CC.host ?= gcc
|
||||
CFLAGS.host ?= $(CPPFLAGS_host) $(CFLAGS_host)
|
||||
CXX.host ?= g++
|
||||
CXXFLAGS.host ?= $(CPPFLAGS_host) $(CXXFLAGS_host)
|
||||
LINK.host ?= $(CXX.host)
|
||||
LDFLAGS.host ?= $(LDFLAGS_host)
|
||||
AR.host ?= ar
|
||||
PLI.host ?= pli
|
||||
|
||||
# Define a dir function that can handle spaces.
|
||||
# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
|
||||
# "leading spaces cannot appear in the text of the first argument as written.
|
||||
# These characters can be put into the argument value by variable substitution."
|
||||
empty :=
|
||||
space := $(empty) $(empty)
|
||||
|
||||
# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
|
||||
replace_spaces = $(subst $(space),?,$1)
|
||||
unreplace_spaces = $(subst ?,$(space),$1)
|
||||
dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
|
||||
|
||||
# Flags to make gcc output dependency info. Note that you need to be
|
||||
# careful here to use the flags that ccache and distcc can understand.
|
||||
# We write to a dep file on the side first and then rename at the end
|
||||
# so we can't end up with a broken dep file.
|
||||
depfile = $(depsdir)/$(call replace_spaces,$@).d
|
||||
DEPFLAGS = -MMD -MF $(depfile).raw
|
||||
|
||||
# We have to fixup the deps output in a few ways.
|
||||
# (1) the file output should mention the proper .o file.
|
||||
# ccache or distcc lose the path to the target, so we convert a rule of
|
||||
# the form:
|
||||
# foobar.o: DEP1 DEP2
|
||||
# into
|
||||
# path/to/foobar.o: DEP1 DEP2
|
||||
# (2) we want missing files not to cause us to fail to build.
|
||||
# We want to rewrite
|
||||
# foobar.o: DEP1 DEP2 \
|
||||
# DEP3
|
||||
# to
|
||||
# DEP1:
|
||||
# DEP2:
|
||||
# DEP3:
|
||||
# so if the files are missing, they're just considered phony rules.
|
||||
# We have to do some pretty insane escaping to get those backslashes
|
||||
# and dollar signs past make, the shell, and sed at the same time.
|
||||
# Doesn't work with spaces, but that's fine: .d files have spaces in
|
||||
# their names replaced with other characters.
|
||||
define fixup_dep
|
||||
# The depfile may not exist if the input file didn't have any #includes.
|
||||
touch $(depfile).raw
|
||||
# Fixup path as in (1).
|
||||
sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
|
||||
# Add extra rules as in (2).
|
||||
# We remove slashes and replace spaces with new lines;
|
||||
# remove blank lines;
|
||||
# delete the first line and append a colon to the remaining lines.
|
||||
sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
|
||||
grep -v '^$$' |\
|
||||
sed -e 1d -e 's|$$|:|' \
|
||||
>> $(depfile)
|
||||
rm $(depfile).raw
|
||||
endef
|
||||
|
||||
# Command definitions:
|
||||
# - cmd_foo is the actual command to run;
|
||||
# - quiet_cmd_foo is the brief-output summary of the command.
|
||||
|
||||
quiet_cmd_cc = CC($(TOOLSET)) $@
|
||||
cmd_cc = $(CC.$(TOOLSET)) -o $@ $< $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c
|
||||
|
||||
quiet_cmd_cxx = CXX($(TOOLSET)) $@
|
||||
cmd_cxx = $(CXX.$(TOOLSET)) -o $@ $< $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c
|
||||
|
||||
quiet_cmd_objc = CXX($(TOOLSET)) $@
|
||||
cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
|
||||
|
||||
quiet_cmd_objcxx = CXX($(TOOLSET)) $@
|
||||
cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
|
||||
|
||||
# Commands for precompiled header files.
|
||||
quiet_cmd_pch_c = CXX($(TOOLSET)) $@
|
||||
cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
|
||||
quiet_cmd_pch_cc = CXX($(TOOLSET)) $@
|
||||
cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
|
||||
quiet_cmd_pch_m = CXX($(TOOLSET)) $@
|
||||
cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
|
||||
quiet_cmd_pch_mm = CXX($(TOOLSET)) $@
|
||||
cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
|
||||
|
||||
# gyp-mac-tool is written next to the root Makefile by gyp.
|
||||
# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd
|
||||
# already.
|
||||
quiet_cmd_mac_tool = MACTOOL $(4) $<
|
||||
cmd_mac_tool = /opt/homebrew/opt/python@3.14/bin/python3.14 gyp-mac-tool $(4) $< "$@"
|
||||
|
||||
quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@
|
||||
cmd_mac_package_framework = /opt/homebrew/opt/python@3.14/bin/python3.14 gyp-mac-tool package-framework "$@" $(4)
|
||||
|
||||
quiet_cmd_infoplist = INFOPLIST $@
|
||||
cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@"
|
||||
|
||||
quiet_cmd_touch = TOUCH $@
|
||||
cmd_touch = touch $@
|
||||
|
||||
quiet_cmd_copy = COPY $@
|
||||
# send stderr to /dev/null to ignore messages when linking directories.
|
||||
cmd_copy = ln -f "$<" "$@" 2>/dev/null || (rm -rf "$@" && cp -af "$<" "$@")
|
||||
|
||||
quiet_cmd_symlink = SYMLINK $@
|
||||
cmd_symlink = ln -sf "$<" "$@"
|
||||
|
||||
quiet_cmd_alink = LIBTOOL-STATIC $@
|
||||
cmd_alink = rm -f $@ && /opt/homebrew/opt/python@3.14/bin/python3.14 gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^)
|
||||
|
||||
quiet_cmd_link = LINK($(TOOLSET)) $@
|
||||
cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
|
||||
|
||||
quiet_cmd_solink = SOLINK($(TOOLSET)) $@
|
||||
cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
|
||||
|
||||
quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
|
||||
cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
|
||||
|
||||
|
||||
# Define an escape_quotes function to escape single quotes.
|
||||
# This allows us to handle quotes properly as long as we always use
|
||||
# use single quotes and escape_quotes.
|
||||
escape_quotes = $(subst ','\'',$(1))
|
||||
# This comment is here just to include a ' to unconfuse syntax highlighting.
|
||||
# Define an escape_vars function to escape '$' variable syntax.
|
||||
# This allows us to read/write command lines with shell variables (e.g.
|
||||
# $LD_LIBRARY_PATH), without triggering make substitution.
|
||||
escape_vars = $(subst $$,$$$$,$(1))
|
||||
# Helper that expands to a shell command to echo a string exactly as it is in
|
||||
# make. This uses printf instead of echo because printf's behaviour with respect
|
||||
# to escape sequences is more portable than echo's across different shells
|
||||
# (e.g., dash, bash).
|
||||
exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
|
||||
|
||||
# Helper to compare the command we're about to run against the command
|
||||
# we logged the last time we ran the command. Produces an empty
|
||||
# string (false) when the commands match.
|
||||
# Tricky point: Make has no string-equality test function.
|
||||
# The kernel uses the following, but it seems like it would have false
|
||||
# positives, where one string reordered its arguments.
|
||||
# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
|
||||
# $(filter-out $(cmd_$@), $(cmd_$(1))))
|
||||
# We instead substitute each for the empty string into the other, and
|
||||
# say they're equal if both substitutions produce the empty string.
|
||||
# .d files contain ? instead of spaces, take that into account.
|
||||
command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
|
||||
$(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
|
||||
|
||||
# Helper that is non-empty when a prerequisite changes.
|
||||
# Normally make does this implicitly, but we force rules to always run
|
||||
# so we can check their command lines.
|
||||
# $? -- new prerequisites
|
||||
# $| -- order-only dependencies
|
||||
prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
|
||||
|
||||
# Helper that executes all postbuilds until one fails.
|
||||
define do_postbuilds
|
||||
@E=0;\
|
||||
for p in $(POSTBUILDS); do\
|
||||
eval $$p;\
|
||||
E=$$?;\
|
||||
if [ $$E -ne 0 ]; then\
|
||||
break;\
|
||||
fi;\
|
||||
done;\
|
||||
if [ $$E -ne 0 ]; then\
|
||||
rm -rf "$@";\
|
||||
exit $$E;\
|
||||
fi
|
||||
endef
|
||||
|
||||
# do_cmd: run a command via the above cmd_foo names, if necessary.
|
||||
# Should always run for a given target to handle command-line changes.
|
||||
# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
|
||||
# Third argument, if non-zero, makes it do POSTBUILDS processing.
|
||||
# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
|
||||
# spaces already and dirx strips the ? characters.
|
||||
define do_cmd
|
||||
$(if $(or $(command_changed),$(prereq_changed)),
|
||||
@$(call exact_echo, $($(quiet)cmd_$(1)))
|
||||
@mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
|
||||
$(if $(findstring flock,$(word 2,$(cmd_$1))),
|
||||
@$(cmd_$(1))
|
||||
@echo " $(quiet_cmd_$(1)): Finished",
|
||||
@$(cmd_$(1))
|
||||
)
|
||||
@$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
|
||||
@$(if $(2),$(fixup_dep))
|
||||
$(if $(and $(3), $(POSTBUILDS)),
|
||||
$(call do_postbuilds)
|
||||
)
|
||||
)
|
||||
endef
|
||||
|
||||
# Declare the "all" target first so it is the default,
|
||||
# even though we don't have the deps yet.
|
||||
.PHONY: all
|
||||
all:
|
||||
|
||||
# make looks for ways to re-generate included makefiles, but in our case, we
|
||||
# don't have a direct way. Explicitly telling make that it has nothing to do
|
||||
# for them makes it go faster.
|
||||
%.d: ;
|
||||
|
||||
# Use FORCE_DO_CMD to force a target to run. Should be coupled with
|
||||
# do_cmd.
|
||||
.PHONY: FORCE_DO_CMD
|
||||
FORCE_DO_CMD:
|
||||
|
||||
TOOLSET := target
|
||||
# Suffix rules, putting all outputs into $(obj).
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD
|
||||
@$(call do_cmd,objc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD
|
||||
@$(call do_cmd,objcxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
|
||||
# Try building from generated source, too.
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD
|
||||
@$(call do_cmd,objc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD
|
||||
@$(call do_cmd,objcxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD
|
||||
@$(call do_cmd,objc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD
|
||||
@$(call do_cmd,objcxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
|
||||
|
||||
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
|
||||
$(findstring $(join ^,$(prefix)),\
|
||||
$(join ^,.target.mk)))),)
|
||||
include .target.mk
|
||||
endif
|
||||
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
|
||||
$(findstring $(join ^,$(prefix)),\
|
||||
$(join ^,fse.target.mk)))),)
|
||||
include fse.target.mk
|
||||
endif
|
||||
|
||||
quiet_cmd_regen_makefile = ACTION Regenerating $@
|
||||
cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/li/Library/Caches/node-gyp/22.20.0" "-Dnode_gyp_dir=/usr/local/lib/node_modules/npm/node_modules/node-gyp" "-Dnode_lib_file=/Users/li/Library/Caches/node-gyp/22.20.0/<(target_arch)/node.lib" "-Dmodule_root_dir=/Users/li/Desktop/work/work2/OG/PC/node_modules/webpack-dev-server/node_modules/fsevents" "-Dnode_engine=v8" "--depth=." "-Goutput_dir=." "--generator-output=build" -I/Users/li/Desktop/work/work2/OG/PC/node_modules/webpack-dev-server/node_modules/fsevents/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/Users/li/Library/Caches/node-gyp/22.20.0/include/node/common.gypi "--toplevel-dir=." binding.gyp
|
||||
Makefile: $(srcdir)/../../../../../../../../../Library/Caches/node-gyp/22.20.0/include/node/common.gypi $(srcdir)/build/config.gypi $(srcdir)/../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/binding.gyp
|
||||
$(call do_cmd,regen_makefile)
|
||||
|
||||
# "all" is a concatenation of the "all" targets from all the included
|
||||
# sub-makefiles. This is just here to clarify.
|
||||
all:
|
||||
|
||||
# Add in dependency-tracking rules. $(all_deps) is the list of every single
|
||||
# target in our tree. Only consider the ones with .d (dependency) info:
|
||||
d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
|
||||
ifneq ($(d_files),)
|
||||
include $(d_files)
|
||||
endif
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
cmd_Release/.node := c++ -bundle -undefined dynamic_lookup -Wl,-search_paths_first -mmacosx-version-min=11.0 -arch arm64 -L./Release -stdlib=libc++ -o Release/.node
|
||||
Generated
Vendored
+74
@@ -0,0 +1,74 @@
|
||||
Release/obj.target/fse/fsevents.o: ../fsevents.cc ../../../../nan/nan.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/node_version.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/uv.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/uv/errno.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/uv/version.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/uv/unix.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/uv/threadpool.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/uv/darwin.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/node.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/cppgc/common.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8config.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-array-buffer.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-local-handle.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-handle-base.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-internal.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-object.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-maybe.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-persistent-handle.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-weak-callback-info.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-primitive.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-data.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-value.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-traced-handle.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-container.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-context.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-snapshot.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-isolate.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-callbacks.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-promise.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-debug.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-script.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-memory-span.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-message.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-embedder-heap.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-function-callback.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-microtask.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-statistics.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-unwinder.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-embedder-state-scope.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-date.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-exception.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-extension.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-external.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-function.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-template.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-initialization.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-platform.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-source-location.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-json.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-locker.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-microtask-queue.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-primitive-object.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-proxy.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-regexp.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-typed-array.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-value-serializer.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-version.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/v8-wasm.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/node_api.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/js_native_api.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/js_native_api_types.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/node_api_types.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/node_buffer.h \
|
||||
/Users/li/Library/Caches/node-gyp/22.20.0/include/node/node_object_wrap.h \
|
||||
../../../../nan/nan_callbacks.h ../../../../nan/nan_callbacks_12_inl.h \
|
||||
../../../../nan/nan_maybe_43_inl.h ../../../../nan/nan_converters.h \
|
||||
../../../../nan/nan_converters_43_inl.h ../../../../nan/nan_new.h \
|
||||
../../../../nan/nan_implementation_12_inl.h \
|
||||
../../../../nan/nan_persistent_12_inl.h ../../../../nan/nan_weak.h \
|
||||
../../../../nan/nan_object_wrap.h ../../../../nan/nan_private.h \
|
||||
../../../../nan/nan_typedarray_contents.h ../../../../nan/nan_json.h \
|
||||
../../../../nan/nan_scriptorigin.h ../src/storage.cc ../src/async.cc \
|
||||
../src/thread.cc ../src/constants.cc ../src/methods.cc
|
||||
Generated
Vendored
Executable
BIN
Binary file not shown.
+6
@@ -0,0 +1,6 @@
|
||||
# This file is generated by gyp; do not edit.
|
||||
|
||||
export builddir_name ?= ./build/.
|
||||
.PHONY: all
|
||||
all:
|
||||
$(MAKE) fse
|
||||
+511
@@ -0,0 +1,511 @@
|
||||
# Do not edit. File was generated by node-gyp's "configure" step
|
||||
{
|
||||
"target_defaults": {
|
||||
"cflags": [],
|
||||
"configurations": {
|
||||
"Debug": {
|
||||
"v8_enable_v8_checks": 0,
|
||||
"variables": {}
|
||||
},
|
||||
"Release": {
|
||||
"v8_enable_v8_checks": 1,
|
||||
"variables": {}
|
||||
}
|
||||
},
|
||||
"default_configuration": "Release",
|
||||
"defines": [],
|
||||
"include_dirs": [],
|
||||
"libraries": [],
|
||||
"msvs_configuration_platform": "ARM64",
|
||||
"xcode_configuration_platform": "arm64"
|
||||
},
|
||||
"variables": {
|
||||
"arm_fpu": "neon",
|
||||
"asan": 0,
|
||||
"clang": 1,
|
||||
"control_flow_guard": "false",
|
||||
"coverage": "false",
|
||||
"dcheck_always_on": 0,
|
||||
"debug_nghttp2": "false",
|
||||
"debug_node": "false",
|
||||
"enable_lto": "false",
|
||||
"enable_pgo_generate": "false",
|
||||
"enable_pgo_use": "false",
|
||||
"error_on_warn": "false",
|
||||
"force_dynamic_crt": 0,
|
||||
"host_arch": "arm64",
|
||||
"icu_data_in": "../../deps/icu-tmp/icudt77l.dat",
|
||||
"icu_endianness": "l",
|
||||
"icu_gyp_path": "tools/icu/icu-generic.gyp",
|
||||
"icu_path": "deps/icu-small",
|
||||
"icu_small": "false",
|
||||
"icu_ver_major": "77",
|
||||
"libdir": "lib",
|
||||
"llvm_version": "16.0",
|
||||
"napi_build_version": "10",
|
||||
"node_builtin_shareable_builtins": [
|
||||
"deps/cjs-module-lexer/lexer.js",
|
||||
"deps/cjs-module-lexer/dist/lexer.js",
|
||||
"deps/undici/undici.js",
|
||||
"deps/amaro/dist/index.js"
|
||||
],
|
||||
"node_byteorder": "little",
|
||||
"node_cctest_sources": [
|
||||
"src/node_snapshot_stub.cc",
|
||||
"test/cctest/inspector/test_node_protocol.cc",
|
||||
"test/cctest/node_test_fixture.cc",
|
||||
"test/cctest/test_aliased_buffer.cc",
|
||||
"test/cctest/test_base64.cc",
|
||||
"test/cctest/test_base_object_ptr.cc",
|
||||
"test/cctest/test_cppgc.cc",
|
||||
"test/cctest/test_crypto_clienthello.cc",
|
||||
"test/cctest/test_dataqueue.cc",
|
||||
"test/cctest/test_environment.cc",
|
||||
"test/cctest/test_inspector_socket.cc",
|
||||
"test/cctest/test_inspector_socket_server.cc",
|
||||
"test/cctest/test_json_utils.cc",
|
||||
"test/cctest/test_linked_binding.cc",
|
||||
"test/cctest/test_node_api.cc",
|
||||
"test/cctest/test_node_crypto.cc",
|
||||
"test/cctest/test_node_crypto_env.cc",
|
||||
"test/cctest/test_node_postmortem_metadata.cc",
|
||||
"test/cctest/test_node_task_runner.cc",
|
||||
"test/cctest/test_path.cc",
|
||||
"test/cctest/test_per_process.cc",
|
||||
"test/cctest/test_platform.cc",
|
||||
"test/cctest/test_quic_cid.cc",
|
||||
"test/cctest/test_quic_error.cc",
|
||||
"test/cctest/test_quic_tokens.cc",
|
||||
"test/cctest/test_report.cc",
|
||||
"test/cctest/test_sockaddr.cc",
|
||||
"test/cctest/test_traced_value.cc",
|
||||
"test/cctest/test_util.cc",
|
||||
"test/cctest/node_test_fixture.h"
|
||||
],
|
||||
"node_debug_lib": "false",
|
||||
"node_enable_d8": "false",
|
||||
"node_enable_v8_vtunejit": "false",
|
||||
"node_enable_v8windbg": "false",
|
||||
"node_fipsinstall": "false",
|
||||
"node_install_corepack": "true",
|
||||
"node_install_npm": "true",
|
||||
"node_library_files": [
|
||||
"lib/_http_agent.js",
|
||||
"lib/_http_client.js",
|
||||
"lib/_http_common.js",
|
||||
"lib/_http_incoming.js",
|
||||
"lib/_http_outgoing.js",
|
||||
"lib/_http_server.js",
|
||||
"lib/_stream_duplex.js",
|
||||
"lib/_stream_passthrough.js",
|
||||
"lib/_stream_readable.js",
|
||||
"lib/_stream_transform.js",
|
||||
"lib/_stream_wrap.js",
|
||||
"lib/_stream_writable.js",
|
||||
"lib/_tls_common.js",
|
||||
"lib/_tls_wrap.js",
|
||||
"lib/assert.js",
|
||||
"lib/assert/strict.js",
|
||||
"lib/async_hooks.js",
|
||||
"lib/buffer.js",
|
||||
"lib/child_process.js",
|
||||
"lib/cluster.js",
|
||||
"lib/console.js",
|
||||
"lib/constants.js",
|
||||
"lib/crypto.js",
|
||||
"lib/dgram.js",
|
||||
"lib/diagnostics_channel.js",
|
||||
"lib/dns.js",
|
||||
"lib/dns/promises.js",
|
||||
"lib/domain.js",
|
||||
"lib/events.js",
|
||||
"lib/fs.js",
|
||||
"lib/fs/promises.js",
|
||||
"lib/http.js",
|
||||
"lib/http2.js",
|
||||
"lib/https.js",
|
||||
"lib/inspector.js",
|
||||
"lib/inspector/promises.js",
|
||||
"lib/internal/abort_controller.js",
|
||||
"lib/internal/assert.js",
|
||||
"lib/internal/assert/assertion_error.js",
|
||||
"lib/internal/assert/calltracker.js",
|
||||
"lib/internal/assert/myers_diff.js",
|
||||
"lib/internal/assert/utils.js",
|
||||
"lib/internal/async_context_frame.js",
|
||||
"lib/internal/async_hooks.js",
|
||||
"lib/internal/async_local_storage/async_context_frame.js",
|
||||
"lib/internal/async_local_storage/async_hooks.js",
|
||||
"lib/internal/blob.js",
|
||||
"lib/internal/blocklist.js",
|
||||
"lib/internal/bootstrap/node.js",
|
||||
"lib/internal/bootstrap/realm.js",
|
||||
"lib/internal/bootstrap/shadow_realm.js",
|
||||
"lib/internal/bootstrap/switches/does_not_own_process_state.js",
|
||||
"lib/internal/bootstrap/switches/does_own_process_state.js",
|
||||
"lib/internal/bootstrap/switches/is_main_thread.js",
|
||||
"lib/internal/bootstrap/switches/is_not_main_thread.js",
|
||||
"lib/internal/bootstrap/web/exposed-wildcard.js",
|
||||
"lib/internal/bootstrap/web/exposed-window-or-worker.js",
|
||||
"lib/internal/buffer.js",
|
||||
"lib/internal/child_process.js",
|
||||
"lib/internal/child_process/serialization.js",
|
||||
"lib/internal/cli_table.js",
|
||||
"lib/internal/cluster/child.js",
|
||||
"lib/internal/cluster/primary.js",
|
||||
"lib/internal/cluster/round_robin_handle.js",
|
||||
"lib/internal/cluster/shared_handle.js",
|
||||
"lib/internal/cluster/utils.js",
|
||||
"lib/internal/cluster/worker.js",
|
||||
"lib/internal/console/constructor.js",
|
||||
"lib/internal/console/global.js",
|
||||
"lib/internal/constants.js",
|
||||
"lib/internal/crypto/aes.js",
|
||||
"lib/internal/crypto/certificate.js",
|
||||
"lib/internal/crypto/cfrg.js",
|
||||
"lib/internal/crypto/cipher.js",
|
||||
"lib/internal/crypto/diffiehellman.js",
|
||||
"lib/internal/crypto/ec.js",
|
||||
"lib/internal/crypto/hash.js",
|
||||
"lib/internal/crypto/hashnames.js",
|
||||
"lib/internal/crypto/hkdf.js",
|
||||
"lib/internal/crypto/keygen.js",
|
||||
"lib/internal/crypto/keys.js",
|
||||
"lib/internal/crypto/mac.js",
|
||||
"lib/internal/crypto/pbkdf2.js",
|
||||
"lib/internal/crypto/random.js",
|
||||
"lib/internal/crypto/rsa.js",
|
||||
"lib/internal/crypto/scrypt.js",
|
||||
"lib/internal/crypto/sig.js",
|
||||
"lib/internal/crypto/util.js",
|
||||
"lib/internal/crypto/webcrypto.js",
|
||||
"lib/internal/crypto/webidl.js",
|
||||
"lib/internal/crypto/x509.js",
|
||||
"lib/internal/data_url.js",
|
||||
"lib/internal/debugger/inspect.js",
|
||||
"lib/internal/debugger/inspect_client.js",
|
||||
"lib/internal/debugger/inspect_repl.js",
|
||||
"lib/internal/dgram.js",
|
||||
"lib/internal/dns/callback_resolver.js",
|
||||
"lib/internal/dns/promises.js",
|
||||
"lib/internal/dns/utils.js",
|
||||
"lib/internal/encoding.js",
|
||||
"lib/internal/error_serdes.js",
|
||||
"lib/internal/errors.js",
|
||||
"lib/internal/event_target.js",
|
||||
"lib/internal/events/abort_listener.js",
|
||||
"lib/internal/events/symbols.js",
|
||||
"lib/internal/file.js",
|
||||
"lib/internal/fixed_queue.js",
|
||||
"lib/internal/freelist.js",
|
||||
"lib/internal/freeze_intrinsics.js",
|
||||
"lib/internal/fs/cp/cp-sync.js",
|
||||
"lib/internal/fs/cp/cp.js",
|
||||
"lib/internal/fs/dir.js",
|
||||
"lib/internal/fs/glob.js",
|
||||
"lib/internal/fs/promises.js",
|
||||
"lib/internal/fs/read/context.js",
|
||||
"lib/internal/fs/recursive_watch.js",
|
||||
"lib/internal/fs/rimraf.js",
|
||||
"lib/internal/fs/streams.js",
|
||||
"lib/internal/fs/sync_write_stream.js",
|
||||
"lib/internal/fs/utils.js",
|
||||
"lib/internal/fs/watchers.js",
|
||||
"lib/internal/heap_utils.js",
|
||||
"lib/internal/histogram.js",
|
||||
"lib/internal/http.js",
|
||||
"lib/internal/http2/compat.js",
|
||||
"lib/internal/http2/core.js",
|
||||
"lib/internal/http2/util.js",
|
||||
"lib/internal/inspector/network.js",
|
||||
"lib/internal/inspector/network_http.js",
|
||||
"lib/internal/inspector/network_http2.js",
|
||||
"lib/internal/inspector/network_resources.js",
|
||||
"lib/internal/inspector/network_undici.js",
|
||||
"lib/internal/inspector_async_hook.js",
|
||||
"lib/internal/inspector_network_tracking.js",
|
||||
"lib/internal/js_stream_socket.js",
|
||||
"lib/internal/legacy/processbinding.js",
|
||||
"lib/internal/linkedlist.js",
|
||||
"lib/internal/main/check_syntax.js",
|
||||
"lib/internal/main/embedding.js",
|
||||
"lib/internal/main/eval_stdin.js",
|
||||
"lib/internal/main/eval_string.js",
|
||||
"lib/internal/main/inspect.js",
|
||||
"lib/internal/main/mksnapshot.js",
|
||||
"lib/internal/main/print_help.js",
|
||||
"lib/internal/main/prof_process.js",
|
||||
"lib/internal/main/repl.js",
|
||||
"lib/internal/main/run_main_module.js",
|
||||
"lib/internal/main/test_runner.js",
|
||||
"lib/internal/main/watch_mode.js",
|
||||
"lib/internal/main/worker_thread.js",
|
||||
"lib/internal/mime.js",
|
||||
"lib/internal/modules/cjs/loader.js",
|
||||
"lib/internal/modules/customization_hooks.js",
|
||||
"lib/internal/modules/esm/assert.js",
|
||||
"lib/internal/modules/esm/create_dynamic_module.js",
|
||||
"lib/internal/modules/esm/formats.js",
|
||||
"lib/internal/modules/esm/get_format.js",
|
||||
"lib/internal/modules/esm/hooks.js",
|
||||
"lib/internal/modules/esm/initialize_import_meta.js",
|
||||
"lib/internal/modules/esm/load.js",
|
||||
"lib/internal/modules/esm/loader.js",
|
||||
"lib/internal/modules/esm/module_job.js",
|
||||
"lib/internal/modules/esm/module_map.js",
|
||||
"lib/internal/modules/esm/resolve.js",
|
||||
"lib/internal/modules/esm/shared_constants.js",
|
||||
"lib/internal/modules/esm/translators.js",
|
||||
"lib/internal/modules/esm/utils.js",
|
||||
"lib/internal/modules/esm/worker.js",
|
||||
"lib/internal/modules/helpers.js",
|
||||
"lib/internal/modules/package_json_reader.js",
|
||||
"lib/internal/modules/run_main.js",
|
||||
"lib/internal/modules/typescript.js",
|
||||
"lib/internal/navigator.js",
|
||||
"lib/internal/net.js",
|
||||
"lib/internal/options.js",
|
||||
"lib/internal/per_context/domexception.js",
|
||||
"lib/internal/per_context/messageport.js",
|
||||
"lib/internal/per_context/primordials.js",
|
||||
"lib/internal/perf/event_loop_delay.js",
|
||||
"lib/internal/perf/event_loop_utilization.js",
|
||||
"lib/internal/perf/nodetiming.js",
|
||||
"lib/internal/perf/observe.js",
|
||||
"lib/internal/perf/performance.js",
|
||||
"lib/internal/perf/performance_entry.js",
|
||||
"lib/internal/perf/resource_timing.js",
|
||||
"lib/internal/perf/timerify.js",
|
||||
"lib/internal/perf/usertiming.js",
|
||||
"lib/internal/perf/utils.js",
|
||||
"lib/internal/priority_queue.js",
|
||||
"lib/internal/process/execution.js",
|
||||
"lib/internal/process/finalization.js",
|
||||
"lib/internal/process/per_thread.js",
|
||||
"lib/internal/process/permission.js",
|
||||
"lib/internal/process/pre_execution.js",
|
||||
"lib/internal/process/promises.js",
|
||||
"lib/internal/process/report.js",
|
||||
"lib/internal/process/signal.js",
|
||||
"lib/internal/process/task_queues.js",
|
||||
"lib/internal/process/warning.js",
|
||||
"lib/internal/process/worker_thread_only.js",
|
||||
"lib/internal/promise_hooks.js",
|
||||
"lib/internal/querystring.js",
|
||||
"lib/internal/quic/quic.js",
|
||||
"lib/internal/quic/state.js",
|
||||
"lib/internal/quic/stats.js",
|
||||
"lib/internal/quic/symbols.js",
|
||||
"lib/internal/readline/callbacks.js",
|
||||
"lib/internal/readline/emitKeypressEvents.js",
|
||||
"lib/internal/readline/interface.js",
|
||||
"lib/internal/readline/promises.js",
|
||||
"lib/internal/readline/utils.js",
|
||||
"lib/internal/repl.js",
|
||||
"lib/internal/repl/await.js",
|
||||
"lib/internal/repl/history.js",
|
||||
"lib/internal/repl/utils.js",
|
||||
"lib/internal/socket_list.js",
|
||||
"lib/internal/socketaddress.js",
|
||||
"lib/internal/source_map/prepare_stack_trace.js",
|
||||
"lib/internal/source_map/source_map.js",
|
||||
"lib/internal/source_map/source_map_cache.js",
|
||||
"lib/internal/source_map/source_map_cache_map.js",
|
||||
"lib/internal/stream_base_commons.js",
|
||||
"lib/internal/streams/add-abort-signal.js",
|
||||
"lib/internal/streams/compose.js",
|
||||
"lib/internal/streams/destroy.js",
|
||||
"lib/internal/streams/duplex.js",
|
||||
"lib/internal/streams/duplexify.js",
|
||||
"lib/internal/streams/duplexpair.js",
|
||||
"lib/internal/streams/end-of-stream.js",
|
||||
"lib/internal/streams/from.js",
|
||||
"lib/internal/streams/lazy_transform.js",
|
||||
"lib/internal/streams/legacy.js",
|
||||
"lib/internal/streams/operators.js",
|
||||
"lib/internal/streams/passthrough.js",
|
||||
"lib/internal/streams/pipeline.js",
|
||||
"lib/internal/streams/readable.js",
|
||||
"lib/internal/streams/state.js",
|
||||
"lib/internal/streams/transform.js",
|
||||
"lib/internal/streams/utils.js",
|
||||
"lib/internal/streams/writable.js",
|
||||
"lib/internal/test/binding.js",
|
||||
"lib/internal/test/transfer.js",
|
||||
"lib/internal/test_runner/assert.js",
|
||||
"lib/internal/test_runner/coverage.js",
|
||||
"lib/internal/test_runner/harness.js",
|
||||
"lib/internal/test_runner/mock/loader.js",
|
||||
"lib/internal/test_runner/mock/mock.js",
|
||||
"lib/internal/test_runner/mock/mock_timers.js",
|
||||
"lib/internal/test_runner/reporter/dot.js",
|
||||
"lib/internal/test_runner/reporter/junit.js",
|
||||
"lib/internal/test_runner/reporter/lcov.js",
|
||||
"lib/internal/test_runner/reporter/spec.js",
|
||||
"lib/internal/test_runner/reporter/tap.js",
|
||||
"lib/internal/test_runner/reporter/utils.js",
|
||||
"lib/internal/test_runner/reporter/v8-serializer.js",
|
||||
"lib/internal/test_runner/runner.js",
|
||||
"lib/internal/test_runner/snapshot.js",
|
||||
"lib/internal/test_runner/test.js",
|
||||
"lib/internal/test_runner/tests_stream.js",
|
||||
"lib/internal/test_runner/utils.js",
|
||||
"lib/internal/timers.js",
|
||||
"lib/internal/tls/secure-context.js",
|
||||
"lib/internal/tls/secure-pair.js",
|
||||
"lib/internal/trace_events_async_hooks.js",
|
||||
"lib/internal/tty.js",
|
||||
"lib/internal/url.js",
|
||||
"lib/internal/util.js",
|
||||
"lib/internal/util/colors.js",
|
||||
"lib/internal/util/comparisons.js",
|
||||
"lib/internal/util/debuglog.js",
|
||||
"lib/internal/util/diff.js",
|
||||
"lib/internal/util/inspect.js",
|
||||
"lib/internal/util/inspector.js",
|
||||
"lib/internal/util/parse_args/parse_args.js",
|
||||
"lib/internal/util/parse_args/utils.js",
|
||||
"lib/internal/util/trace_sigint.js",
|
||||
"lib/internal/util/types.js",
|
||||
"lib/internal/v8/startup_snapshot.js",
|
||||
"lib/internal/v8_prof_polyfill.js",
|
||||
"lib/internal/v8_prof_processor.js",
|
||||
"lib/internal/validators.js",
|
||||
"lib/internal/vm.js",
|
||||
"lib/internal/vm/module.js",
|
||||
"lib/internal/wasm_web_api.js",
|
||||
"lib/internal/watch_mode/files_watcher.js",
|
||||
"lib/internal/watchdog.js",
|
||||
"lib/internal/webidl.js",
|
||||
"lib/internal/webstorage.js",
|
||||
"lib/internal/webstreams/adapters.js",
|
||||
"lib/internal/webstreams/compression.js",
|
||||
"lib/internal/webstreams/encoding.js",
|
||||
"lib/internal/webstreams/queuingstrategies.js",
|
||||
"lib/internal/webstreams/readablestream.js",
|
||||
"lib/internal/webstreams/transfer.js",
|
||||
"lib/internal/webstreams/transformstream.js",
|
||||
"lib/internal/webstreams/util.js",
|
||||
"lib/internal/webstreams/writablestream.js",
|
||||
"lib/internal/worker.js",
|
||||
"lib/internal/worker/clone_dom_exception.js",
|
||||
"lib/internal/worker/io.js",
|
||||
"lib/internal/worker/js_transferable.js",
|
||||
"lib/internal/worker/messaging.js",
|
||||
"lib/module.js",
|
||||
"lib/net.js",
|
||||
"lib/os.js",
|
||||
"lib/path.js",
|
||||
"lib/path/posix.js",
|
||||
"lib/path/win32.js",
|
||||
"lib/perf_hooks.js",
|
||||
"lib/process.js",
|
||||
"lib/punycode.js",
|
||||
"lib/querystring.js",
|
||||
"lib/readline.js",
|
||||
"lib/readline/promises.js",
|
||||
"lib/repl.js",
|
||||
"lib/sea.js",
|
||||
"lib/sqlite.js",
|
||||
"lib/stream.js",
|
||||
"lib/stream/consumers.js",
|
||||
"lib/stream/promises.js",
|
||||
"lib/stream/web.js",
|
||||
"lib/string_decoder.js",
|
||||
"lib/sys.js",
|
||||
"lib/test.js",
|
||||
"lib/test/reporters.js",
|
||||
"lib/timers.js",
|
||||
"lib/timers/promises.js",
|
||||
"lib/tls.js",
|
||||
"lib/trace_events.js",
|
||||
"lib/tty.js",
|
||||
"lib/url.js",
|
||||
"lib/util.js",
|
||||
"lib/util/types.js",
|
||||
"lib/v8.js",
|
||||
"lib/vm.js",
|
||||
"lib/wasi.js",
|
||||
"lib/worker_threads.js",
|
||||
"lib/zlib.js"
|
||||
],
|
||||
"node_module_version": 127,
|
||||
"node_no_browser_globals": "false",
|
||||
"node_prefix": "/usr/local",
|
||||
"node_release_urlbase": "https://nodejs.org/download/release/",
|
||||
"node_shared": "false",
|
||||
"node_shared_ada": "false",
|
||||
"node_shared_brotli": "false",
|
||||
"node_shared_cares": "false",
|
||||
"node_shared_http_parser": "false",
|
||||
"node_shared_libuv": "false",
|
||||
"node_shared_nghttp2": "false",
|
||||
"node_shared_nghttp3": "false",
|
||||
"node_shared_ngtcp2": "false",
|
||||
"node_shared_openssl": "false",
|
||||
"node_shared_simdjson": "false",
|
||||
"node_shared_simdutf": "false",
|
||||
"node_shared_sqlite": "false",
|
||||
"node_shared_uvwasi": "false",
|
||||
"node_shared_zlib": "false",
|
||||
"node_shared_zstd": "false",
|
||||
"node_tag": "",
|
||||
"node_target_type": "executable",
|
||||
"node_use_amaro": "true",
|
||||
"node_use_bundled_v8": "true",
|
||||
"node_use_node_code_cache": "true",
|
||||
"node_use_node_snapshot": "true",
|
||||
"node_use_openssl": "true",
|
||||
"node_use_sqlite": "true",
|
||||
"node_use_v8_platform": "true",
|
||||
"node_with_ltcg": "false",
|
||||
"node_without_node_options": "false",
|
||||
"node_write_snapshot_as_array_literals": "false",
|
||||
"openssl_is_fips": "false",
|
||||
"openssl_quic": "false",
|
||||
"ossfuzz": "false",
|
||||
"shlib_suffix": "127.dylib",
|
||||
"single_executable_application": "true",
|
||||
"suppress_all_error_on_warn": "false",
|
||||
"target_arch": "arm64",
|
||||
"ubsan": 0,
|
||||
"use_ccache_win": 0,
|
||||
"use_prefix_to_find_headers": "false",
|
||||
"v8_enable_31bit_smis_on_64bit_arch": 0,
|
||||
"v8_enable_extensible_ro_snapshot": 0,
|
||||
"v8_enable_external_code_space": 0,
|
||||
"v8_enable_gdbjit": 0,
|
||||
"v8_enable_hugepage": 0,
|
||||
"v8_enable_i18n_support": 1,
|
||||
"v8_enable_inspector": 1,
|
||||
"v8_enable_javascript_promise_hooks": 1,
|
||||
"v8_enable_lite_mode": 0,
|
||||
"v8_enable_maglev": 0,
|
||||
"v8_enable_object_print": 1,
|
||||
"v8_enable_pointer_compression": 0,
|
||||
"v8_enable_pointer_compression_shared_cage": 0,
|
||||
"v8_enable_sandbox": 0,
|
||||
"v8_enable_shared_ro_heap": 1,
|
||||
"v8_enable_webassembly": 1,
|
||||
"v8_optimized_debug": 1,
|
||||
"v8_promise_internal_field_count": 1,
|
||||
"v8_random_seed": 0,
|
||||
"v8_trace_maps": 0,
|
||||
"v8_use_siphash": 1,
|
||||
"want_separate_host_toolset": 0,
|
||||
"xcode_version": "16.0",
|
||||
"nodedir": "/Users/li/Library/Caches/node-gyp/22.20.0",
|
||||
"python": "/opt/homebrew/opt/python@3.14/bin/python3.14",
|
||||
"standalone_static_library": 1,
|
||||
"global_prefix": "/Users/li/.npm-global",
|
||||
"local_prefix": "/Users/li/Desktop/work/work2/OG/PC",
|
||||
"globalconfig": "/Users/li/.npm-global/etc/npmrc",
|
||||
"init_module": "/Users/li/.npm-init.js",
|
||||
"userconfig": "/Users/li/.npmrc",
|
||||
"npm_version": "10.9.3",
|
||||
"node_gyp": "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js",
|
||||
"cache": "/Users/li/.npm",
|
||||
"user_agent": "npm/10.9.3 node/v22.20.0 darwin arm64 workspaces/false",
|
||||
"prefix": "/Users/li/.npm-global"
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
# This file is generated by gyp; do not edit.
|
||||
|
||||
TOOLSET := target
|
||||
TARGET := fse
|
||||
DEFS_Debug := \
|
||||
'-DNODE_GYP_MODULE_NAME=fse' \
|
||||
'-DUSING_UV_SHARED=1' \
|
||||
'-DUSING_V8_SHARED=1' \
|
||||
'-DV8_DEPRECATION_WARNINGS=1' \
|
||||
'-D_GLIBCXX_USE_CXX11_ABI=1' \
|
||||
'-D_FILE_OFFSET_BITS=64' \
|
||||
'-D_DARWIN_USE_64_BIT_INODE=1' \
|
||||
'-D_LARGEFILE_SOURCE' \
|
||||
'-DOPENSSL_NO_PINSHARED' \
|
||||
'-DOPENSSL_THREADS' \
|
||||
'-DBUILDING_NODE_EXTENSION' \
|
||||
'-DDEBUG' \
|
||||
'-D_DEBUG'
|
||||
|
||||
# Flags passed to all source files.
|
||||
CFLAGS_Debug := \
|
||||
-O0 \
|
||||
-gdwarf-2 \
|
||||
-fno-strict-aliasing \
|
||||
-mmacosx-version-min=11.0 \
|
||||
-arch \
|
||||
arm64 \
|
||||
-Wall \
|
||||
-Wendif-labels \
|
||||
-W \
|
||||
-Wno-unused-parameter
|
||||
|
||||
# Flags passed to only C files.
|
||||
CFLAGS_C_Debug :=
|
||||
|
||||
# Flags passed to only C++ files.
|
||||
CFLAGS_CC_Debug := \
|
||||
-std=gnu++17 \
|
||||
-stdlib=libc++ \
|
||||
-fno-rtti \
|
||||
-fno-exceptions
|
||||
|
||||
# Flags passed to only ObjC files.
|
||||
CFLAGS_OBJC_Debug :=
|
||||
|
||||
# Flags passed to only ObjC++ files.
|
||||
CFLAGS_OBJCC_Debug :=
|
||||
|
||||
INCS_Debug := \
|
||||
-I/Users/li/Library/Caches/node-gyp/22.20.0/include/node \
|
||||
-I/Users/li/Library/Caches/node-gyp/22.20.0/src \
|
||||
-I/Users/li/Library/Caches/node-gyp/22.20.0/deps/openssl/config \
|
||||
-I/Users/li/Library/Caches/node-gyp/22.20.0/deps/openssl/openssl/include \
|
||||
-I/Users/li/Library/Caches/node-gyp/22.20.0/deps/uv/include \
|
||||
-I/Users/li/Library/Caches/node-gyp/22.20.0/deps/zlib \
|
||||
-I/Users/li/Library/Caches/node-gyp/22.20.0/deps/v8/include \
|
||||
-I$(srcdir)/../../../nan
|
||||
|
||||
DEFS_Release := \
|
||||
'-DNODE_GYP_MODULE_NAME=fse' \
|
||||
'-DUSING_UV_SHARED=1' \
|
||||
'-DUSING_V8_SHARED=1' \
|
||||
'-DV8_DEPRECATION_WARNINGS=1' \
|
||||
'-D_GLIBCXX_USE_CXX11_ABI=1' \
|
||||
'-D_FILE_OFFSET_BITS=64' \
|
||||
'-D_DARWIN_USE_64_BIT_INODE=1' \
|
||||
'-D_LARGEFILE_SOURCE' \
|
||||
'-DOPENSSL_NO_PINSHARED' \
|
||||
'-DOPENSSL_THREADS' \
|
||||
'-DBUILDING_NODE_EXTENSION'
|
||||
|
||||
# Flags passed to all source files.
|
||||
CFLAGS_Release := \
|
||||
-O3 \
|
||||
-gdwarf-2 \
|
||||
-fno-strict-aliasing \
|
||||
-mmacosx-version-min=11.0 \
|
||||
-arch \
|
||||
arm64 \
|
||||
-Wall \
|
||||
-Wendif-labels \
|
||||
-W \
|
||||
-Wno-unused-parameter
|
||||
|
||||
# Flags passed to only C files.
|
||||
CFLAGS_C_Release :=
|
||||
|
||||
# Flags passed to only C++ files.
|
||||
CFLAGS_CC_Release := \
|
||||
-std=gnu++17 \
|
||||
-stdlib=libc++ \
|
||||
-fno-rtti \
|
||||
-fno-exceptions
|
||||
|
||||
# Flags passed to only ObjC files.
|
||||
CFLAGS_OBJC_Release :=
|
||||
|
||||
# Flags passed to only ObjC++ files.
|
||||
CFLAGS_OBJCC_Release :=
|
||||
|
||||
INCS_Release := \
|
||||
-I/Users/li/Library/Caches/node-gyp/22.20.0/include/node \
|
||||
-I/Users/li/Library/Caches/node-gyp/22.20.0/src \
|
||||
-I/Users/li/Library/Caches/node-gyp/22.20.0/deps/openssl/config \
|
||||
-I/Users/li/Library/Caches/node-gyp/22.20.0/deps/openssl/openssl/include \
|
||||
-I/Users/li/Library/Caches/node-gyp/22.20.0/deps/uv/include \
|
||||
-I/Users/li/Library/Caches/node-gyp/22.20.0/deps/zlib \
|
||||
-I/Users/li/Library/Caches/node-gyp/22.20.0/deps/v8/include \
|
||||
-I$(srcdir)/../../../nan
|
||||
|
||||
OBJS := \
|
||||
$(obj).target/$(TARGET)/fsevents.o
|
||||
|
||||
# Add to the list of files we specially track dependencies for.
|
||||
all_deps += $(OBJS)
|
||||
|
||||
# CFLAGS et al overrides must be target-local.
|
||||
# See "Target-specific Variable Values" in the GNU Make manual.
|
||||
$(OBJS): TOOLSET := $(TOOLSET)
|
||||
$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE))
|
||||
$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE))
|
||||
$(OBJS): GYP_OBJCFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE))
|
||||
$(OBJS): GYP_OBJCXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE))
|
||||
|
||||
# Suffix rules, putting all outputs into $(obj).
|
||||
|
||||
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
|
||||
# Try building from generated source, too.
|
||||
|
||||
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
|
||||
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
|
||||
# End of this set of suffix rules
|
||||
### Rules for final target.
|
||||
LDFLAGS_Debug := \
|
||||
-framework CoreFoundation -framework CoreServices \
|
||||
-undefined dynamic_lookup \
|
||||
-Wl,-search_paths_first \
|
||||
-mmacosx-version-min=11.0 \
|
||||
-arch \
|
||||
arm64 \
|
||||
-L$(builddir) \
|
||||
-stdlib=libc++
|
||||
|
||||
LIBTOOLFLAGS_Debug := \
|
||||
-framework CoreFoundation -framework CoreServices \
|
||||
-undefined dynamic_lookup \
|
||||
-Wl,-search_paths_first
|
||||
|
||||
LDFLAGS_Release := \
|
||||
-framework CoreFoundation -framework CoreServices \
|
||||
-undefined dynamic_lookup \
|
||||
-Wl,-search_paths_first \
|
||||
-mmacosx-version-min=11.0 \
|
||||
-arch \
|
||||
arm64 \
|
||||
-L$(builddir) \
|
||||
-stdlib=libc++
|
||||
|
||||
LIBTOOLFLAGS_Release := \
|
||||
-framework CoreFoundation -framework CoreServices \
|
||||
-undefined dynamic_lookup \
|
||||
-Wl,-search_paths_first
|
||||
|
||||
LIBS :=
|
||||
|
||||
$(builddir)/fse.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))
|
||||
$(builddir)/fse.node: LIBS := $(LIBS)
|
||||
$(builddir)/fse.node: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))
|
||||
$(builddir)/fse.node: TOOLSET := $(TOOLSET)
|
||||
$(builddir)/fse.node: $(OBJS) FORCE_DO_CMD
|
||||
$(call do_cmd,solink_module)
|
||||
|
||||
all_deps += $(builddir)/fse.node
|
||||
# Add target alias
|
||||
.PHONY: fse
|
||||
fse: $(builddir)/fse.node
|
||||
|
||||
# Short alias for building this executable.
|
||||
.PHONY: fse.node
|
||||
fse.node: $(builddir)/fse.node
|
||||
|
||||
# Add executable to "all" target.
|
||||
.PHONY: all
|
||||
all: $(builddir)/fse.node
|
||||
|
||||
Generated
Vendored
Executable
+768
@@ -0,0 +1,768 @@
|
||||
#!/usr/bin/env python3
|
||||
# Generated by gyp. Do not edit.
|
||||
# Copyright (c) 2012 Google Inc. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
"""Utility functions to perform Xcode-style build steps.
|
||||
|
||||
These functions are executed via gyp-mac-tool when using the Makefile generator.
|
||||
"""
|
||||
|
||||
|
||||
import fcntl
|
||||
import fnmatch
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import plistlib
|
||||
import re
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
|
||||
def main(args):
|
||||
executor = MacTool()
|
||||
exit_code = executor.Dispatch(args)
|
||||
if exit_code is not None:
|
||||
sys.exit(exit_code)
|
||||
|
||||
|
||||
class MacTool:
|
||||
"""This class performs all the Mac tooling steps. The methods can either be
|
||||
executed directly, or dispatched from an argument list."""
|
||||
|
||||
def Dispatch(self, args):
|
||||
"""Dispatches a string command to a method."""
|
||||
if len(args) < 1:
|
||||
raise Exception("Not enough arguments")
|
||||
|
||||
method = "Exec%s" % self._CommandifyName(args[0])
|
||||
return getattr(self, method)(*args[1:])
|
||||
|
||||
def _CommandifyName(self, name_string):
|
||||
"""Transforms a tool name like copy-info-plist to CopyInfoPlist"""
|
||||
return name_string.title().replace("-", "")
|
||||
|
||||
def ExecCopyBundleResource(self, source, dest, convert_to_binary):
|
||||
"""Copies a resource file to the bundle/Resources directory, performing any
|
||||
necessary compilation on each resource."""
|
||||
convert_to_binary = convert_to_binary == "True"
|
||||
extension = os.path.splitext(source)[1].lower()
|
||||
if os.path.isdir(source):
|
||||
# Copy tree.
|
||||
# TODO(thakis): This copies file attributes like mtime, while the
|
||||
# single-file branch below doesn't. This should probably be changed to
|
||||
# be consistent with the single-file branch.
|
||||
if os.path.exists(dest):
|
||||
shutil.rmtree(dest)
|
||||
shutil.copytree(source, dest)
|
||||
elif extension in {".xib", ".storyboard"}:
|
||||
return self._CopyXIBFile(source, dest)
|
||||
elif extension == ".strings" and not convert_to_binary:
|
||||
self._CopyStringsFile(source, dest)
|
||||
else:
|
||||
if os.path.exists(dest):
|
||||
os.unlink(dest)
|
||||
shutil.copy(source, dest)
|
||||
|
||||
if convert_to_binary and extension in {".plist", ".strings"}:
|
||||
self._ConvertToBinary(dest)
|
||||
|
||||
def _CopyXIBFile(self, source, dest):
|
||||
"""Compiles a XIB file with ibtool into a binary plist in the bundle."""
|
||||
|
||||
# ibtool sometimes crashes with relative paths. See crbug.com/314728.
|
||||
base = os.path.dirname(os.path.realpath(__file__))
|
||||
if os.path.relpath(source):
|
||||
source = os.path.join(base, source)
|
||||
if os.path.relpath(dest):
|
||||
dest = os.path.join(base, dest)
|
||||
|
||||
args = ["xcrun", "ibtool", "--errors", "--warnings", "--notices"]
|
||||
|
||||
if os.environ["XCODE_VERSION_ACTUAL"] > "0700":
|
||||
args.extend(["--auto-activate-custom-fonts"])
|
||||
if "IPHONEOS_DEPLOYMENT_TARGET" in os.environ:
|
||||
args.extend(
|
||||
[
|
||||
"--target-device",
|
||||
"iphone",
|
||||
"--target-device",
|
||||
"ipad",
|
||||
"--minimum-deployment-target",
|
||||
os.environ["IPHONEOS_DEPLOYMENT_TARGET"],
|
||||
]
|
||||
)
|
||||
else:
|
||||
args.extend(
|
||||
[
|
||||
"--target-device",
|
||||
"mac",
|
||||
"--minimum-deployment-target",
|
||||
os.environ["MACOSX_DEPLOYMENT_TARGET"],
|
||||
]
|
||||
)
|
||||
|
||||
args.extend(
|
||||
["--output-format", "human-readable-text", "--compile", dest, source]
|
||||
)
|
||||
|
||||
ibtool_section_re = re.compile(r"/\*.*\*/")
|
||||
ibtool_re = re.compile(r".*note:.*is clipping its content")
|
||||
try:
|
||||
stdout = subprocess.check_output(args)
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(e.output)
|
||||
raise
|
||||
current_section_header = None
|
||||
for line in stdout.splitlines():
|
||||
if ibtool_section_re.match(line):
|
||||
current_section_header = line
|
||||
elif not ibtool_re.match(line):
|
||||
if current_section_header:
|
||||
print(current_section_header)
|
||||
current_section_header = None
|
||||
print(line)
|
||||
return 0
|
||||
|
||||
def _ConvertToBinary(self, dest):
|
||||
subprocess.check_call(
|
||||
["xcrun", "plutil", "-convert", "binary1", "-o", dest, dest]
|
||||
)
|
||||
|
||||
def _CopyStringsFile(self, source, dest):
|
||||
"""Copies a .strings file using iconv to reconvert the input into UTF-16."""
|
||||
input_code = self._DetectInputEncoding(source) or "UTF-8"
|
||||
|
||||
# Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call
|
||||
# CFPropertyListCreateFromXMLData() behind the scenes; at least it prints
|
||||
# CFPropertyListCreateFromXMLData(): Old-style plist parser: missing
|
||||
# semicolon in dictionary.
|
||||
# on invalid files. Do the same kind of validation.
|
||||
import CoreFoundation
|
||||
|
||||
with open(source, "rb") as in_file:
|
||||
s = in_file.read()
|
||||
d = CoreFoundation.CFDataCreate(None, s, len(s))
|
||||
_, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None)
|
||||
if error:
|
||||
return
|
||||
|
||||
with open(dest, "wb") as fp:
|
||||
fp.write(s.decode(input_code).encode("UTF-16"))
|
||||
|
||||
def _DetectInputEncoding(self, file_name):
|
||||
"""Reads the first few bytes from file_name and tries to guess the text
|
||||
encoding. Returns None as a guess if it can't detect it."""
|
||||
with open(file_name, "rb") as fp:
|
||||
try:
|
||||
header = fp.read(3)
|
||||
except Exception:
|
||||
return None
|
||||
if header.startswith((b"\xFE\xFF", b"\xFF\xFE")):
|
||||
return "UTF-16"
|
||||
elif header.startswith(b"\xEF\xBB\xBF"):
|
||||
return "UTF-8"
|
||||
else:
|
||||
return None
|
||||
|
||||
def ExecCopyInfoPlist(self, source, dest, convert_to_binary, *keys):
|
||||
"""Copies the |source| Info.plist to the destination directory |dest|."""
|
||||
# Read the source Info.plist into memory.
|
||||
with open(source) as fd:
|
||||
lines = fd.read()
|
||||
|
||||
# Insert synthesized key/value pairs (e.g. BuildMachineOSBuild).
|
||||
plist = plistlib.readPlistFromString(lines)
|
||||
if keys:
|
||||
plist.update(json.loads(keys[0]))
|
||||
lines = plistlib.writePlistToString(plist)
|
||||
|
||||
# Go through all the environment variables and replace them as variables in
|
||||
# the file.
|
||||
IDENT_RE = re.compile(r"[_/\s]")
|
||||
for key in os.environ:
|
||||
if key.startswith("_"):
|
||||
continue
|
||||
evar = "${%s}" % key
|
||||
evalue = os.environ[key]
|
||||
lines = lines.replace(lines, evar, evalue)
|
||||
|
||||
# Xcode supports various suffices on environment variables, which are
|
||||
# all undocumented. :rfc1034identifier is used in the standard project
|
||||
# template these days, and :identifier was used earlier. They are used to
|
||||
# convert non-url characters into things that look like valid urls --
|
||||
# except that the replacement character for :identifier, '_' isn't valid
|
||||
# in a URL either -- oops, hence :rfc1034identifier was born.
|
||||
evar = "${%s:identifier}" % key
|
||||
evalue = IDENT_RE.sub("_", os.environ[key])
|
||||
lines = lines.replace(lines, evar, evalue)
|
||||
|
||||
evar = "${%s:rfc1034identifier}" % key
|
||||
evalue = IDENT_RE.sub("-", os.environ[key])
|
||||
lines = lines.replace(lines, evar, evalue)
|
||||
|
||||
# Remove any keys with values that haven't been replaced.
|
||||
lines = lines.splitlines()
|
||||
for i in range(len(lines)):
|
||||
if lines[i].strip().startswith("<string>${"):
|
||||
lines[i] = None
|
||||
lines[i - 1] = None
|
||||
lines = "\n".join(line for line in lines if line is not None)
|
||||
|
||||
# Write out the file with variables replaced.
|
||||
with open(dest, "w") as fd:
|
||||
fd.write(lines)
|
||||
|
||||
# Now write out PkgInfo file now that the Info.plist file has been
|
||||
# "compiled".
|
||||
self._WritePkgInfo(dest)
|
||||
|
||||
if convert_to_binary == "True":
|
||||
self._ConvertToBinary(dest)
|
||||
|
||||
def _WritePkgInfo(self, info_plist):
|
||||
"""This writes the PkgInfo file from the data stored in Info.plist."""
|
||||
plist = plistlib.readPlist(info_plist)
|
||||
if not plist:
|
||||
return
|
||||
|
||||
# Only create PkgInfo for executable types.
|
||||
package_type = plist["CFBundlePackageType"]
|
||||
if package_type != "APPL":
|
||||
return
|
||||
|
||||
# The format of PkgInfo is eight characters, representing the bundle type
|
||||
# and bundle signature, each four characters. If that is missing, four
|
||||
# '?' characters are used instead.
|
||||
signature_code = plist.get("CFBundleSignature", "????")
|
||||
if len(signature_code) != 4: # Wrong length resets everything, too.
|
||||
signature_code = "?" * 4
|
||||
|
||||
dest = os.path.join(os.path.dirname(info_plist), "PkgInfo")
|
||||
with open(dest, "w") as fp:
|
||||
fp.write(f"{package_type}{signature_code}")
|
||||
|
||||
def ExecFlock(self, lockfile, *cmd_list):
|
||||
"""Emulates the most basic behavior of Linux's flock(1)."""
|
||||
# Rely on exception handling to report errors.
|
||||
fd = os.open(lockfile, os.O_RDONLY | os.O_NOCTTY | os.O_CREAT, 0o666)
|
||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
||||
return subprocess.call(cmd_list)
|
||||
|
||||
def ExecFilterLibtool(self, *cmd_list):
|
||||
"""Calls libtool and filters out '/path/to/libtool: file: foo.o has no
|
||||
symbols'."""
|
||||
libtool_re = re.compile(
|
||||
r"^.*libtool: (?:for architecture: \S* )?file: .* has no symbols$"
|
||||
)
|
||||
libtool_re5 = re.compile(
|
||||
r"^.*libtool: warning for library: "
|
||||
+ r".* the table of contents is empty "
|
||||
+ r"\(no object file members in the library define global symbols\)$"
|
||||
)
|
||||
env = os.environ.copy()
|
||||
# Ref:
|
||||
# http://www.opensource.apple.com/source/cctools/cctools-809/misc/libtool.c
|
||||
# The problem with this flag is that it resets the file mtime on the file to
|
||||
# epoch=0, e.g. 1970-1-1 or 1969-12-31 depending on timezone.
|
||||
env["ZERO_AR_DATE"] = "1"
|
||||
libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE, env=env)
|
||||
err = libtoolout.communicate()[1].decode("utf-8")
|
||||
for line in err.splitlines():
|
||||
if not libtool_re.match(line) and not libtool_re5.match(line):
|
||||
print(line, file=sys.stderr)
|
||||
# Unconditionally touch the output .a file on the command line if present
|
||||
# and the command succeeded. A bit hacky.
|
||||
if not libtoolout.returncode:
|
||||
for i in range(len(cmd_list) - 1):
|
||||
if cmd_list[i] == "-o" and cmd_list[i + 1].endswith(".a"):
|
||||
os.utime(cmd_list[i + 1], None)
|
||||
break
|
||||
return libtoolout.returncode
|
||||
|
||||
def ExecPackageIosFramework(self, framework):
|
||||
# Find the name of the binary based on the part before the ".framework".
|
||||
binary = os.path.basename(framework).split(".")[0]
|
||||
module_path = os.path.join(framework, "Modules")
|
||||
if not os.path.exists(module_path):
|
||||
os.mkdir(module_path)
|
||||
module_template = (
|
||||
"framework module %s {\n"
|
||||
' umbrella header "%s.h"\n'
|
||||
"\n"
|
||||
" export *\n"
|
||||
" module * { export * }\n"
|
||||
"}\n" % (binary, binary)
|
||||
)
|
||||
|
||||
with open(os.path.join(module_path, "module.modulemap"), "w") as module_file:
|
||||
module_file.write(module_template)
|
||||
|
||||
def ExecPackageFramework(self, framework, version):
|
||||
"""Takes a path to Something.framework and the Current version of that and
|
||||
sets up all the symlinks."""
|
||||
# Find the name of the binary based on the part before the ".framework".
|
||||
binary = os.path.basename(framework).split(".")[0]
|
||||
|
||||
CURRENT = "Current"
|
||||
RESOURCES = "Resources"
|
||||
VERSIONS = "Versions"
|
||||
|
||||
if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)):
|
||||
# Binary-less frameworks don't seem to contain symlinks (see e.g.
|
||||
# chromium's out/Debug/org.chromium.Chromium.manifest/ bundle).
|
||||
return
|
||||
|
||||
# Move into the framework directory to set the symlinks correctly.
|
||||
pwd = os.getcwd()
|
||||
os.chdir(framework)
|
||||
|
||||
# Set up the Current version.
|
||||
self._Relink(version, os.path.join(VERSIONS, CURRENT))
|
||||
|
||||
# Set up the root symlinks.
|
||||
self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary)
|
||||
self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES)
|
||||
|
||||
# Back to where we were before!
|
||||
os.chdir(pwd)
|
||||
|
||||
def _Relink(self, dest, link):
|
||||
"""Creates a symlink to |dest| named |link|. If |link| already exists,
|
||||
it is overwritten."""
|
||||
if os.path.lexists(link):
|
||||
os.remove(link)
|
||||
os.symlink(dest, link)
|
||||
|
||||
def ExecCompileIosFrameworkHeaderMap(self, out, framework, *all_headers):
|
||||
framework_name = os.path.basename(framework).split(".")[0]
|
||||
all_headers = [os.path.abspath(header) for header in all_headers]
|
||||
filelist = {}
|
||||
for header in all_headers:
|
||||
filename = os.path.basename(header)
|
||||
filelist[filename] = header
|
||||
filelist[os.path.join(framework_name, filename)] = header
|
||||
WriteHmap(out, filelist)
|
||||
|
||||
def ExecCopyIosFrameworkHeaders(self, framework, *copy_headers):
|
||||
header_path = os.path.join(framework, "Headers")
|
||||
if not os.path.exists(header_path):
|
||||
os.makedirs(header_path)
|
||||
for header in copy_headers:
|
||||
shutil.copy(header, os.path.join(header_path, os.path.basename(header)))
|
||||
|
||||
def ExecCompileXcassets(self, keys, *inputs):
|
||||
"""Compiles multiple .xcassets files into a single .car file.
|
||||
|
||||
This invokes 'actool' to compile all the inputs .xcassets files. The
|
||||
|keys| arguments is a json-encoded dictionary of extra arguments to
|
||||
pass to 'actool' when the asset catalogs contains an application icon
|
||||
or a launch image.
|
||||
|
||||
Note that 'actool' does not create the Assets.car file if the asset
|
||||
catalogs does not contains imageset.
|
||||
"""
|
||||
command_line = [
|
||||
"xcrun",
|
||||
"actool",
|
||||
"--output-format",
|
||||
"human-readable-text",
|
||||
"--compress-pngs",
|
||||
"--notices",
|
||||
"--warnings",
|
||||
"--errors",
|
||||
]
|
||||
is_iphone_target = "IPHONEOS_DEPLOYMENT_TARGET" in os.environ
|
||||
if is_iphone_target:
|
||||
platform = os.environ["CONFIGURATION"].split("-")[-1]
|
||||
if platform not in ("iphoneos", "iphonesimulator"):
|
||||
platform = "iphonesimulator"
|
||||
command_line.extend(
|
||||
[
|
||||
"--platform",
|
||||
platform,
|
||||
"--target-device",
|
||||
"iphone",
|
||||
"--target-device",
|
||||
"ipad",
|
||||
"--minimum-deployment-target",
|
||||
os.environ["IPHONEOS_DEPLOYMENT_TARGET"],
|
||||
"--compile",
|
||||
os.path.abspath(os.environ["CONTENTS_FOLDER_PATH"]),
|
||||
]
|
||||
)
|
||||
else:
|
||||
command_line.extend(
|
||||
[
|
||||
"--platform",
|
||||
"macosx",
|
||||
"--target-device",
|
||||
"mac",
|
||||
"--minimum-deployment-target",
|
||||
os.environ["MACOSX_DEPLOYMENT_TARGET"],
|
||||
"--compile",
|
||||
os.path.abspath(os.environ["UNLOCALIZED_RESOURCES_FOLDER_PATH"]),
|
||||
]
|
||||
)
|
||||
if keys:
|
||||
keys = json.loads(keys)
|
||||
for key, value in keys.items():
|
||||
arg_name = "--" + key
|
||||
if isinstance(value, bool):
|
||||
if value:
|
||||
command_line.append(arg_name)
|
||||
elif isinstance(value, list):
|
||||
for v in value:
|
||||
command_line.append(arg_name)
|
||||
command_line.append(str(v))
|
||||
else:
|
||||
command_line.append(arg_name)
|
||||
command_line.append(str(value))
|
||||
# Note: actool crashes if inputs path are relative, so use os.path.abspath
|
||||
# to get absolute path name for inputs.
|
||||
command_line.extend(map(os.path.abspath, inputs))
|
||||
subprocess.check_call(command_line)
|
||||
|
||||
def ExecMergeInfoPlist(self, output, *inputs):
|
||||
"""Merge multiple .plist files into a single .plist file."""
|
||||
merged_plist = {}
|
||||
for path in inputs:
|
||||
plist = self._LoadPlistMaybeBinary(path)
|
||||
self._MergePlist(merged_plist, plist)
|
||||
plistlib.writePlist(merged_plist, output)
|
||||
|
||||
def ExecCodeSignBundle(self, key, entitlements, provisioning, path, preserve):
|
||||
"""Code sign a bundle.
|
||||
|
||||
This function tries to code sign an iOS bundle, following the same
|
||||
algorithm as Xcode:
|
||||
1. pick the provisioning profile that best match the bundle identifier,
|
||||
and copy it into the bundle as embedded.mobileprovision,
|
||||
2. copy Entitlements.plist from user or SDK next to the bundle,
|
||||
3. code sign the bundle.
|
||||
"""
|
||||
substitutions, overrides = self._InstallProvisioningProfile(
|
||||
provisioning, self._GetCFBundleIdentifier()
|
||||
)
|
||||
entitlements_path = self._InstallEntitlements(
|
||||
entitlements, substitutions, overrides
|
||||
)
|
||||
|
||||
args = ["codesign", "--force", "--sign", key]
|
||||
if preserve == "True":
|
||||
args.extend(["--deep", "--preserve-metadata=identifier,entitlements"])
|
||||
else:
|
||||
args.extend(["--entitlements", entitlements_path])
|
||||
args.extend(["--timestamp=none", path])
|
||||
subprocess.check_call(args)
|
||||
|
||||
def _InstallProvisioningProfile(self, profile, bundle_identifier):
|
||||
"""Installs embedded.mobileprovision into the bundle.
|
||||
|
||||
Args:
|
||||
profile: string, optional, short name of the .mobileprovision file
|
||||
to use, if empty or the file is missing, the best file installed
|
||||
will be used
|
||||
bundle_identifier: string, value of CFBundleIdentifier from Info.plist
|
||||
|
||||
Returns:
|
||||
A tuple containing two dictionary: variables substitutions and values
|
||||
to overrides when generating the entitlements file.
|
||||
"""
|
||||
source_path, provisioning_data, team_id = self._FindProvisioningProfile(
|
||||
profile, bundle_identifier
|
||||
)
|
||||
target_path = os.path.join(
|
||||
os.environ["BUILT_PRODUCTS_DIR"],
|
||||
os.environ["CONTENTS_FOLDER_PATH"],
|
||||
"embedded.mobileprovision",
|
||||
)
|
||||
shutil.copy2(source_path, target_path)
|
||||
substitutions = self._GetSubstitutions(bundle_identifier, team_id + ".")
|
||||
return substitutions, provisioning_data["Entitlements"]
|
||||
|
||||
def _FindProvisioningProfile(self, profile, bundle_identifier):
|
||||
"""Finds the .mobileprovision file to use for signing the bundle.
|
||||
|
||||
Checks all the installed provisioning profiles (or if the user specified
|
||||
the PROVISIONING_PROFILE variable, only consult it) and select the most
|
||||
specific that correspond to the bundle identifier.
|
||||
|
||||
Args:
|
||||
profile: string, optional, short name of the .mobileprovision file
|
||||
to use, if empty or the file is missing, the best file installed
|
||||
will be used
|
||||
bundle_identifier: string, value of CFBundleIdentifier from Info.plist
|
||||
|
||||
Returns:
|
||||
A tuple of the path to the selected provisioning profile, the data of
|
||||
the embedded plist in the provisioning profile and the team identifier
|
||||
to use for code signing.
|
||||
|
||||
Raises:
|
||||
SystemExit: if no .mobileprovision can be used to sign the bundle.
|
||||
"""
|
||||
profiles_dir = os.path.join(
|
||||
os.environ["HOME"], "Library", "MobileDevice", "Provisioning Profiles"
|
||||
)
|
||||
if not os.path.isdir(profiles_dir):
|
||||
print(
|
||||
"cannot find mobile provisioning for %s" % (bundle_identifier),
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
provisioning_profiles = None
|
||||
if profile:
|
||||
profile_path = os.path.join(profiles_dir, profile + ".mobileprovision")
|
||||
if os.path.exists(profile_path):
|
||||
provisioning_profiles = [profile_path]
|
||||
if not provisioning_profiles:
|
||||
provisioning_profiles = glob.glob(
|
||||
os.path.join(profiles_dir, "*.mobileprovision")
|
||||
)
|
||||
valid_provisioning_profiles = {}
|
||||
for profile_path in provisioning_profiles:
|
||||
profile_data = self._LoadProvisioningProfile(profile_path)
|
||||
app_id_pattern = profile_data.get("Entitlements", {}).get(
|
||||
"application-identifier", ""
|
||||
)
|
||||
for team_identifier in profile_data.get("TeamIdentifier", []):
|
||||
app_id = f"{team_identifier}.{bundle_identifier}"
|
||||
if fnmatch.fnmatch(app_id, app_id_pattern):
|
||||
valid_provisioning_profiles[app_id_pattern] = (
|
||||
profile_path,
|
||||
profile_data,
|
||||
team_identifier,
|
||||
)
|
||||
if not valid_provisioning_profiles:
|
||||
print(
|
||||
"cannot find mobile provisioning for %s" % (bundle_identifier),
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
# If the user has multiple provisioning profiles installed that can be
|
||||
# used for ${bundle_identifier}, pick the most specific one (ie. the
|
||||
# provisioning profile whose pattern is the longest).
|
||||
selected_key = max(valid_provisioning_profiles, key=lambda v: len(v))
|
||||
return valid_provisioning_profiles[selected_key]
|
||||
|
||||
def _LoadProvisioningProfile(self, profile_path):
|
||||
"""Extracts the plist embedded in a provisioning profile.
|
||||
|
||||
Args:
|
||||
profile_path: string, path to the .mobileprovision file
|
||||
|
||||
Returns:
|
||||
Content of the plist embedded in the provisioning profile as a dictionary.
|
||||
"""
|
||||
with tempfile.NamedTemporaryFile() as temp:
|
||||
subprocess.check_call(
|
||||
["security", "cms", "-D", "-i", profile_path, "-o", temp.name]
|
||||
)
|
||||
return self._LoadPlistMaybeBinary(temp.name)
|
||||
|
||||
def _MergePlist(self, merged_plist, plist):
|
||||
"""Merge |plist| into |merged_plist|."""
|
||||
for key, value in plist.items():
|
||||
if isinstance(value, dict):
|
||||
merged_value = merged_plist.get(key, {})
|
||||
if isinstance(merged_value, dict):
|
||||
self._MergePlist(merged_value, value)
|
||||
merged_plist[key] = merged_value
|
||||
else:
|
||||
merged_plist[key] = value
|
||||
else:
|
||||
merged_plist[key] = value
|
||||
|
||||
def _LoadPlistMaybeBinary(self, plist_path):
|
||||
"""Loads into a memory a plist possibly encoded in binary format.
|
||||
|
||||
This is a wrapper around plistlib.readPlist that tries to convert the
|
||||
plist to the XML format if it can't be parsed (assuming that it is in
|
||||
the binary format).
|
||||
|
||||
Args:
|
||||
plist_path: string, path to a plist file, in XML or binary format
|
||||
|
||||
Returns:
|
||||
Content of the plist as a dictionary.
|
||||
"""
|
||||
try:
|
||||
# First, try to read the file using plistlib that only supports XML,
|
||||
# and if an exception is raised, convert a temporary copy to XML and
|
||||
# load that copy.
|
||||
return plistlib.readPlist(plist_path)
|
||||
except Exception:
|
||||
pass
|
||||
with tempfile.NamedTemporaryFile() as temp:
|
||||
shutil.copy2(plist_path, temp.name)
|
||||
subprocess.check_call(["plutil", "-convert", "xml1", temp.name])
|
||||
return plistlib.readPlist(temp.name)
|
||||
|
||||
def _GetSubstitutions(self, bundle_identifier, app_identifier_prefix):
|
||||
"""Constructs a dictionary of variable substitutions for Entitlements.plist.
|
||||
|
||||
Args:
|
||||
bundle_identifier: string, value of CFBundleIdentifier from Info.plist
|
||||
app_identifier_prefix: string, value for AppIdentifierPrefix
|
||||
|
||||
Returns:
|
||||
Dictionary of substitutions to apply when generating Entitlements.plist.
|
||||
"""
|
||||
return {
|
||||
"CFBundleIdentifier": bundle_identifier,
|
||||
"AppIdentifierPrefix": app_identifier_prefix,
|
||||
}
|
||||
|
||||
def _GetCFBundleIdentifier(self):
|
||||
"""Extracts CFBundleIdentifier value from Info.plist in the bundle.
|
||||
|
||||
Returns:
|
||||
Value of CFBundleIdentifier in the Info.plist located in the bundle.
|
||||
"""
|
||||
info_plist_path = os.path.join(
|
||||
os.environ["TARGET_BUILD_DIR"], os.environ["INFOPLIST_PATH"]
|
||||
)
|
||||
info_plist_data = self._LoadPlistMaybeBinary(info_plist_path)
|
||||
return info_plist_data["CFBundleIdentifier"]
|
||||
|
||||
def _InstallEntitlements(self, entitlements, substitutions, overrides):
|
||||
"""Generates and install the ${BundleName}.xcent entitlements file.
|
||||
|
||||
Expands variables "$(variable)" pattern in the source entitlements file,
|
||||
add extra entitlements defined in the .mobileprovision file and the copy
|
||||
the generated plist to "${BundlePath}.xcent".
|
||||
|
||||
Args:
|
||||
entitlements: string, optional, path to the Entitlements.plist template
|
||||
to use, defaults to "${SDKROOT}/Entitlements.plist"
|
||||
substitutions: dictionary, variable substitutions
|
||||
overrides: dictionary, values to add to the entitlements
|
||||
|
||||
Returns:
|
||||
Path to the generated entitlements file.
|
||||
"""
|
||||
source_path = entitlements
|
||||
target_path = os.path.join(
|
||||
os.environ["BUILT_PRODUCTS_DIR"], os.environ["PRODUCT_NAME"] + ".xcent"
|
||||
)
|
||||
if not source_path:
|
||||
source_path = os.path.join(os.environ["SDKROOT"], "Entitlements.plist")
|
||||
shutil.copy2(source_path, target_path)
|
||||
data = self._LoadPlistMaybeBinary(target_path)
|
||||
data = self._ExpandVariables(data, substitutions)
|
||||
if overrides:
|
||||
for key in overrides:
|
||||
if key not in data:
|
||||
data[key] = overrides[key]
|
||||
plistlib.writePlist(data, target_path)
|
||||
return target_path
|
||||
|
||||
def _ExpandVariables(self, data, substitutions):
|
||||
"""Expands variables "$(variable)" in data.
|
||||
|
||||
Args:
|
||||
data: object, can be either string, list or dictionary
|
||||
substitutions: dictionary, variable substitutions to perform
|
||||
|
||||
Returns:
|
||||
Copy of data where each references to "$(variable)" has been replaced
|
||||
by the corresponding value found in substitutions, or left intact if
|
||||
the key was not found.
|
||||
"""
|
||||
if isinstance(data, str):
|
||||
for key, value in substitutions.items():
|
||||
data = data.replace("$(%s)" % key, value)
|
||||
return data
|
||||
if isinstance(data, list):
|
||||
return [self._ExpandVariables(v, substitutions) for v in data]
|
||||
if isinstance(data, dict):
|
||||
return {k: self._ExpandVariables(data[k], substitutions) for k in data}
|
||||
return data
|
||||
|
||||
|
||||
def NextGreaterPowerOf2(x):
|
||||
return 2 ** (x).bit_length()
|
||||
|
||||
|
||||
def WriteHmap(output_name, filelist):
|
||||
"""Generates a header map based on |filelist|.
|
||||
|
||||
Per Mark Mentovai:
|
||||
A header map is structured essentially as a hash table, keyed by names used
|
||||
in #includes, and providing pathnames to the actual files.
|
||||
|
||||
The implementation below and the comment above comes from inspecting:
|
||||
http://www.opensource.apple.com/source/distcc/distcc-2503/distcc_dist/include_server/headermap.py?txt
|
||||
while also looking at the implementation in clang in:
|
||||
https://llvm.org/svn/llvm-project/cfe/trunk/lib/Lex/HeaderMap.cpp
|
||||
"""
|
||||
magic = 1751998832
|
||||
version = 1
|
||||
_reserved = 0
|
||||
count = len(filelist)
|
||||
capacity = NextGreaterPowerOf2(count)
|
||||
strings_offset = 24 + (12 * capacity)
|
||||
max_value_length = max(len(value) for value in filelist.values())
|
||||
|
||||
out = open(output_name, "wb")
|
||||
out.write(
|
||||
struct.pack(
|
||||
"<LHHLLLL",
|
||||
magic,
|
||||
version,
|
||||
_reserved,
|
||||
strings_offset,
|
||||
count,
|
||||
capacity,
|
||||
max_value_length,
|
||||
)
|
||||
)
|
||||
|
||||
# Create empty hashmap buckets.
|
||||
buckets = [None] * capacity
|
||||
for file, path in filelist.items():
|
||||
key = 0
|
||||
for c in file:
|
||||
key += ord(c.lower()) * 13
|
||||
|
||||
# Fill next empty bucket.
|
||||
while buckets[key & capacity - 1] is not None:
|
||||
key = key + 1
|
||||
buckets[key & capacity - 1] = (file, path)
|
||||
|
||||
next_offset = 1
|
||||
for bucket in buckets:
|
||||
if bucket is None:
|
||||
out.write(struct.pack("<LLL", 0, 0, 0))
|
||||
else:
|
||||
(file, path) = bucket
|
||||
key_offset = next_offset
|
||||
prefix_offset = key_offset + len(file) + 1
|
||||
suffix_offset = prefix_offset + len(os.path.dirname(path) + os.sep) + 1
|
||||
next_offset = suffix_offset + len(os.path.basename(path)) + 1
|
||||
out.write(struct.pack("<LLL", key_offset, prefix_offset, suffix_offset))
|
||||
|
||||
# Pad byte since next offset starts at 1.
|
||||
out.write(struct.pack("<x"))
|
||||
|
||||
for bucket in buckets:
|
||||
if bucket is not None:
|
||||
(file, path) = bucket
|
||||
out.write(struct.pack("<%ds" % len(file), file))
|
||||
out.write(struct.pack("<s", "\0"))
|
||||
base = os.path.dirname(path) + os.sep
|
||||
out.write(struct.pack("<%ds" % len(base), base))
|
||||
out.write(struct.pack("<s", "\0"))
|
||||
path = os.path.basename(path)
|
||||
out.write(struct.pack("<%ds" % len(path), path))
|
||||
out.write(struct.pack("<s", "\0"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
** © 2014 by Philipp Dunkel <pip@pipobscure.com>
|
||||
** Licensed under MIT License.
|
||||
*/
|
||||
|
||||
#include "nan.h"
|
||||
#include "uv.h"
|
||||
#include "v8.h"
|
||||
#include "CoreFoundation/CoreFoundation.h"
|
||||
#include "CoreServices/CoreServices.h"
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
#include "src/storage.cc"
|
||||
namespace fse {
|
||||
class FSEvents : public Nan::ObjectWrap {
|
||||
public:
|
||||
explicit FSEvents(const char *path);
|
||||
~FSEvents();
|
||||
|
||||
uv_mutex_t mutex;
|
||||
|
||||
// async.cc
|
||||
uv_async_t async;
|
||||
void asyncStart();
|
||||
void asyncTrigger();
|
||||
void asyncStop();
|
||||
|
||||
// thread.cc
|
||||
uv_thread_t thread;
|
||||
CFRunLoopRef threadloop;
|
||||
void threadStart();
|
||||
static void threadRun(void *ctx);
|
||||
void threadStop();
|
||||
|
||||
// methods.cc - internal
|
||||
Nan::AsyncResource async_resource;
|
||||
void emitEvent(const char *path, UInt32 flags, UInt64 id);
|
||||
|
||||
// Common
|
||||
CFArrayRef paths;
|
||||
std::vector<fse_event*> events;
|
||||
static void Initialize(v8::Local<v8::Object> exports);
|
||||
|
||||
// methods.cc - exposed
|
||||
static NAN_METHOD(New);
|
||||
static NAN_METHOD(Stop);
|
||||
static NAN_METHOD(Start);
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
using namespace fse;
|
||||
|
||||
FSEvents::FSEvents(const char *path)
|
||||
: async_resource("fsevents:FSEvents") {
|
||||
CFStringRef dirs[] = { CFStringCreateWithCString(NULL, path, kCFStringEncodingUTF8) };
|
||||
paths = CFArrayCreate(NULL, (const void **)&dirs, 1, NULL);
|
||||
threadloop = NULL;
|
||||
if (uv_mutex_init(&mutex)) abort();
|
||||
}
|
||||
FSEvents::~FSEvents() {
|
||||
CFRelease(paths);
|
||||
uv_mutex_destroy(&mutex);
|
||||
}
|
||||
|
||||
#ifndef kFSEventStreamEventFlagItemCreated
|
||||
#define kFSEventStreamEventFlagItemCreated 0x00000010
|
||||
#endif
|
||||
|
||||
#include "src/async.cc"
|
||||
#include "src/thread.cc"
|
||||
#include "src/constants.cc"
|
||||
#include "src/methods.cc"
|
||||
|
||||
void FSEvents::Initialize(v8::Local<v8::Object> exports) {
|
||||
v8::Isolate* isolate = exports->GetIsolate();
|
||||
v8::Local<v8::Context> context = isolate->GetCurrentContext();
|
||||
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(FSEvents::New);
|
||||
tpl->SetClassName(Nan::New<v8::String>("FSEvents").ToLocalChecked());
|
||||
tpl->InstanceTemplate()->SetInternalFieldCount(1);
|
||||
Nan::SetPrototypeTemplate(tpl, "start", Nan::New<v8::FunctionTemplate>(FSEvents::Start));
|
||||
Nan::SetPrototypeTemplate(tpl, "stop", Nan::New<v8::FunctionTemplate>(FSEvents::Stop));
|
||||
Nan::Set(exports, Nan::New<v8::String>("Constants").ToLocalChecked(), Constants());
|
||||
Nan::Set(exports, Nan::New<v8::String>("FSEvents").ToLocalChecked(), tpl->GetFunction(context).ToLocalChecked());
|
||||
}
|
||||
|
||||
NODE_MODULE(fse, FSEvents::Initialize)
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
** © 2014 by Philipp Dunkel <pip@pipobscure.com>
|
||||
** Licensed under MIT License.
|
||||
*/
|
||||
|
||||
/* jshint node:true */
|
||||
'use strict';
|
||||
|
||||
if (process.platform !== 'darwin')
|
||||
throw new Error('Module \'fsevents\' is not compatible with platform \'' + process.platform + '\'');
|
||||
|
||||
var Native = require("bindings")("fse");
|
||||
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
var fs = require('fs');
|
||||
var inherits = require('util').inherits;
|
||||
|
||||
function FSEvents(path, handler) {
|
||||
EventEmitter.call(this);
|
||||
|
||||
Object.defineProperty(this, '_impl', {
|
||||
value: new Native.FSEvents(String(path || ''), handler),
|
||||
enumerable: false,
|
||||
writable: false
|
||||
});
|
||||
}
|
||||
|
||||
inherits(FSEvents, EventEmitter);
|
||||
proxies(FSEvents, Native.FSEvents);
|
||||
|
||||
module.exports = watch;
|
||||
module.exports.getInfo = getInfo;
|
||||
module.exports.FSEvents = Native.FSEvents;
|
||||
module.exports.Constants = Native.Constants;
|
||||
|
||||
var defer = global.setImmediate || process.nextTick;
|
||||
|
||||
function watch(path) {
|
||||
var fse = new FSEvents(String(path || ''), handler);
|
||||
EventEmitter.call(fse);
|
||||
return fse;
|
||||
|
||||
function handler(path, flags, id) {
|
||||
defer(function() {
|
||||
fse.emit('fsevent', path, flags, id);
|
||||
var info = getInfo(path, flags);
|
||||
info.id = id;
|
||||
if (info.event === 'moved') {
|
||||
fs.stat(info.path, function(err, stat) {
|
||||
info.event = (err || !stat) ? 'moved-out' : 'moved-in';
|
||||
fse.emit('change', path, info);
|
||||
fse.emit(info.event, path, info);
|
||||
});
|
||||
} else {
|
||||
fse.emit('change', path, info);
|
||||
fse.emit(info.event, path, info);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function proxies(ctor, target) {
|
||||
Object.keys(target.prototype).filter(function(key) {
|
||||
return typeof target.prototype[key] === 'function';
|
||||
}).forEach(function(key) {
|
||||
ctor.prototype[key] = function() {
|
||||
this._impl[key].apply(this._impl, arguments);
|
||||
return this;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function getFileType(flags) {
|
||||
if (Native.Constants.kFSEventStreamEventFlagItemIsFile & flags) return 'file';
|
||||
if (Native.Constants.kFSEventStreamEventFlagItemIsDir & flags) return 'directory';
|
||||
if (Native.Constants.kFSEventStreamEventFlagItemIsSymlink & flags) return 'symlink';
|
||||
}
|
||||
|
||||
function getEventType(flags) {
|
||||
if (Native.Constants.kFSEventStreamEventFlagItemRemoved & flags) return 'deleted';
|
||||
if (Native.Constants.kFSEventStreamEventFlagItemRenamed & flags) return 'moved';
|
||||
if (Native.Constants.kFSEventStreamEventFlagItemCreated & flags) return 'created';
|
||||
if (Native.Constants.kFSEventStreamEventFlagItemModified & flags) return 'modified';
|
||||
if (Native.Constants.kFSEventStreamEventFlagRootChanged & flags) return 'root-changed';
|
||||
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
function getFileChanges(flags) {
|
||||
return {
|
||||
inode: !! (Native.Constants.kFSEventStreamEventFlagItemInodeMetaMod & flags),
|
||||
finder: !! (Native.Constants.kFSEventStreamEventFlagItemFinderInfoMod & flags),
|
||||
access: !! (Native.Constants.kFSEventStreamEventFlagItemChangeOwner & flags),
|
||||
xattrs: !! (Native.Constants.kFSEventStreamEventFlagItemXattrMod & flags)
|
||||
};
|
||||
}
|
||||
|
||||
function getInfo(path, flags) {
|
||||
return {
|
||||
path: path,
|
||||
event: getEventType(flags),
|
||||
type: getFileType(flags),
|
||||
changes: getFileChanges(flags),
|
||||
flags: flags
|
||||
};
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
const rebuildIfDarwin = () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
console.log();
|
||||
console.log(`Skipping 'fsevents' build as platform ${process.platform} is not supported`);
|
||||
process.exit(0);
|
||||
} else {
|
||||
spawn('node-gyp', ['rebuild'], { stdio: 'inherit' });
|
||||
}
|
||||
};
|
||||
|
||||
rebuildIfDarwin();
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "fsevents",
|
||||
"version": "1.2.13",
|
||||
"description": "Native Access to Mac OS-X FSEvents",
|
||||
"main": "fsevents.js",
|
||||
"dependencies": {
|
||||
"bindings": "^1.5.0",
|
||||
"nan": "^2.12.1"
|
||||
},
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 4.0"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "node ./test/fsevents.js && node ./test/function.js 2> /dev/null",
|
||||
"install": "node install.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/strongloop/fsevents.git"
|
||||
},
|
||||
"keywords": [
|
||||
"fsevents",
|
||||
"mac"
|
||||
],
|
||||
"author": "Philipp Dunkel <pip@pipobscure.com>",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/strongloop/fsevents/issues"
|
||||
},
|
||||
"homepage": "https://github.com/strongloop/fsevents"
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
** © 2014 by Philipp Dunkel <pip@pipobscure.com>
|
||||
** Licensed under MIT License.
|
||||
*/
|
||||
|
||||
|
||||
void async_propagate(uv_async_t *async) {
|
||||
if (!async->data) return;
|
||||
FSEvents *fse = (FSEvents *)async->data;
|
||||
CFIndex idx, cnt;
|
||||
fse_event *event;
|
||||
char pathbuf[1024];
|
||||
const char *pathptr = NULL;
|
||||
uv_mutex_lock(&fse->mutex);
|
||||
cnt = fse->events.size();
|
||||
for (idx=0; idx<cnt; idx++) {
|
||||
event = fse->events.at(idx);
|
||||
if (event == NULL) continue;
|
||||
pathptr = CFStringGetCStringPtr(event->path, kCFStringEncodingUTF8);
|
||||
if (!pathptr) CFStringGetCString(event->path, pathbuf, 1024, kCFStringEncodingUTF8);
|
||||
fse->emitEvent(pathptr ? pathptr : pathbuf, event->flags, event->id);
|
||||
delete event;
|
||||
}
|
||||
if (cnt>0) fse->events.clear();
|
||||
uv_mutex_unlock(&fse->mutex);
|
||||
}
|
||||
|
||||
void FSEvents::asyncStart() {
|
||||
if (async.data == this) return;
|
||||
async.data = this;
|
||||
uv_async_init(uv_default_loop(), &async, (uv_async_cb) async_propagate);
|
||||
}
|
||||
|
||||
void FSEvents::asyncTrigger() {
|
||||
if (async.data != this) return;
|
||||
uv_async_send(&async);
|
||||
}
|
||||
|
||||
void FSEvents::asyncStop() {
|
||||
if (async.data != this) return;
|
||||
async.data = NULL;
|
||||
uv_close((uv_handle_t *) &async, NULL);
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
** © 2014 by Philipp Dunkel <pip@pipobscure.com>
|
||||
** Licensed under MIT License.
|
||||
*/
|
||||
|
||||
// constants from https://developer.apple.com/library/mac/documentation/Darwin/Reference/FSEvents_Ref/index.html#//apple_ref/doc/constant_group/FSEventStreamEventFlags
|
||||
#ifndef kFSEventStreamEventFlagNone
|
||||
#define kFSEventStreamEventFlagNone 0x00000000
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagMustScanSubDirs
|
||||
#define kFSEventStreamEventFlagMustScanSubDirs 0x00000001
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagUserDropped
|
||||
#define kFSEventStreamEventFlagUserDropped 0x00000002
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagKernelDropped
|
||||
#define kFSEventStreamEventFlagKernelDropped 0x00000004
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagEventIdsWrapped
|
||||
#define kFSEventStreamEventFlagEventIdsWrapped 0x00000008
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagHistoryDone
|
||||
#define kFSEventStreamEventFlagHistoryDone 0x00000010
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagRootChanged
|
||||
#define kFSEventStreamEventFlagRootChanged 0x00000020
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagMount
|
||||
#define kFSEventStreamEventFlagMount 0x00000040
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagUnmount
|
||||
#define kFSEventStreamEventFlagUnmount 0x00000080
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagItemCreated
|
||||
#define kFSEventStreamEventFlagItemCreated 0x00000100
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagItemRemoved
|
||||
#define kFSEventStreamEventFlagItemRemoved 0x00000200
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagItemInodeMetaMod
|
||||
#define kFSEventStreamEventFlagItemInodeMetaMod 0x00000400
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagItemRenamed
|
||||
#define kFSEventStreamEventFlagItemRenamed 0x00000800
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagItemModified
|
||||
#define kFSEventStreamEventFlagItemModified 0x00001000
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagItemFinderInfoMod
|
||||
#define kFSEventStreamEventFlagItemFinderInfoMod 0x00002000
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagItemChangeOwner
|
||||
#define kFSEventStreamEventFlagItemChangeOwner 0x00004000
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagItemXattrMod
|
||||
#define kFSEventStreamEventFlagItemXattrMod 0x00008000
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagItemIsFile
|
||||
#define kFSEventStreamEventFlagItemIsFile 0x00010000
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagItemIsDir
|
||||
#define kFSEventStreamEventFlagItemIsDir 0x00020000
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamEventFlagItemIsSymlink
|
||||
#define kFSEventStreamEventFlagItemIsSymlink 0x00040000
|
||||
#endif
|
||||
|
||||
static v8::Local<v8::Object> Constants() {
|
||||
v8::Local<v8::Object> object = Nan::New<v8::Object>();
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagNone").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagNone));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagMustScanSubDirs").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagMustScanSubDirs));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagUserDropped").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagUserDropped));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagKernelDropped").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagKernelDropped));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagEventIdsWrapped").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagEventIdsWrapped));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagHistoryDone").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagHistoryDone));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagRootChanged").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagRootChanged));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagMount").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagMount));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagUnmount").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagUnmount));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagItemCreated").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagItemCreated));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagItemRemoved").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagItemRemoved));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagItemInodeMetaMod").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagItemInodeMetaMod));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagItemRenamed").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagItemRenamed));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagItemModified").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagItemModified));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagItemFinderInfoMod").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagItemFinderInfoMod));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagItemChangeOwner").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagItemChangeOwner));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagItemXattrMod").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagItemXattrMod));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagItemIsFile").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagItemIsFile));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagItemIsDir").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagItemIsDir));
|
||||
Nan::Set(object, Nan::New<v8::String>("kFSEventStreamEventFlagItemIsSymlink").ToLocalChecked(), Nan::New<v8::Integer>(kFSEventStreamEventFlagItemIsSymlink));
|
||||
return object;
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
** © 2014 by Philipp Dunkel <pip@pipobscure.com>
|
||||
** Licensed under MIT License.
|
||||
*/
|
||||
|
||||
void FSEvents::emitEvent(const char *path, UInt32 flags, UInt64 id) {
|
||||
Nan::HandleScope handle_scope;
|
||||
v8::Local<v8::Object> object = handle();
|
||||
v8::Local<v8::Value> key = Nan::New<v8::String>("handler").ToLocalChecked();
|
||||
Nan::Callback handler(Nan::To<v8::Function>(Nan::Get(object, key).ToLocalChecked()).ToLocalChecked());
|
||||
v8::Local<v8::Value> argv[] = {
|
||||
Nan::New<v8::String>(path).ToLocalChecked(),
|
||||
Nan::New<v8::Number>(flags),
|
||||
Nan::New<v8::Number>(id)
|
||||
};
|
||||
handler.Call(3, argv, &async_resource);
|
||||
}
|
||||
|
||||
NAN_METHOD(FSEvents::New) {
|
||||
Nan::Utf8String path(info[0]);
|
||||
|
||||
FSEvents *fse = new FSEvents(*path);
|
||||
fse->Wrap(info.This());
|
||||
Nan::Set(info.This(), Nan::New<v8::String>("handler").ToLocalChecked(), info[1]);
|
||||
|
||||
info.GetReturnValue().Set(info.This());
|
||||
}
|
||||
|
||||
NAN_METHOD(FSEvents::Stop) {
|
||||
FSEvents* fse = Nan::ObjectWrap::Unwrap<FSEvents>(info.This());
|
||||
|
||||
fse->threadStop();
|
||||
fse->asyncStop();
|
||||
|
||||
info.GetReturnValue().Set(info.This());
|
||||
}
|
||||
|
||||
NAN_METHOD(FSEvents::Start) {
|
||||
FSEvents* fse = Nan::ObjectWrap::Unwrap<FSEvents>(info.This());
|
||||
fse->asyncStart();
|
||||
fse->threadStart();
|
||||
|
||||
info.GetReturnValue().Set(info.This());
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
** © 2014 by Philipp Dunkel <pip@pipobscure.com>
|
||||
** Licensed under MIT License.
|
||||
*/
|
||||
|
||||
struct fse_event {
|
||||
UInt64 id;
|
||||
UInt32 flags;
|
||||
CFStringRef path;
|
||||
|
||||
fse_event(CFStringRef eventPath, UInt32 eventFlag, UInt64 eventId) {
|
||||
this->path = eventPath;
|
||||
this->flags = eventFlag;
|
||||
this->id = eventId;
|
||||
if (this->path != NULL)
|
||||
CFRetain(this->path);
|
||||
}
|
||||
|
||||
~fse_event() {
|
||||
if (this->path != NULL)
|
||||
CFRelease(this->path);
|
||||
}
|
||||
|
||||
private:
|
||||
fse_event(const fse_event&);
|
||||
void operator=(const fse_event&);
|
||||
};
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
** © 2014 by Philipp Dunkel <pip@pipobscure.com>
|
||||
** Licensed under MIT License.
|
||||
*/
|
||||
|
||||
// constants from https://developer.apple.com/library/mac/documentation/Darwin/Reference/FSEvents_Ref/index.html#//apple_ref/doc/constant_group/FSEventStreamCreateFlags
|
||||
#ifndef kFSEventStreamCreateFlagNone
|
||||
#define kFSEventStreamCreateFlagNone 0x00000000
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamCreateFlagUseCFTypes
|
||||
#define kFSEventStreamCreateFlagUseCFTypes 0x00000001
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamCreateFlagNoDefer
|
||||
#define kFSEventStreamCreateFlagNoDefer 0x00000002
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamCreateFlagWatchRoot
|
||||
#define kFSEventStreamCreateFlagWatchRoot 0x00000004
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamCreateFlagIgnoreSelf
|
||||
#define kFSEventStreamCreateFlagIgnoreSelf 0x00000008
|
||||
#endif
|
||||
|
||||
#ifndef kFSEventStreamCreateFlagFileEvents
|
||||
#define kFSEventStreamCreateFlagFileEvents 0x00000010
|
||||
#endif
|
||||
|
||||
void FSEvents::threadStart() {
|
||||
if (threadloop) return;
|
||||
if (uv_thread_create(&thread, &FSEvents::threadRun, this)) abort();
|
||||
}
|
||||
|
||||
void HandleStreamEvents(ConstFSEventStreamRef stream, void *ctx, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[]) {
|
||||
FSEvents * fse = (FSEvents *)ctx;
|
||||
size_t idx;
|
||||
uv_mutex_lock(&fse->mutex);
|
||||
for (idx=0; idx < numEvents; idx++) {
|
||||
fse_event *event = new fse_event(
|
||||
(CFStringRef)CFArrayGetValueAtIndex((CFArrayRef)eventPaths, idx),
|
||||
eventFlags[idx],
|
||||
eventIds[idx]
|
||||
);
|
||||
fse->events.push_back(event);
|
||||
}
|
||||
fse->asyncTrigger();
|
||||
uv_mutex_unlock(&fse->mutex);
|
||||
}
|
||||
|
||||
void FSEvents::threadRun(void *ctx) {
|
||||
FSEvents *fse = (FSEvents*)ctx;
|
||||
FSEventStreamContext context = { 0, ctx, NULL, NULL, NULL };
|
||||
fse->threadloop = CFRunLoopGetCurrent();
|
||||
FSEventStreamRef stream = FSEventStreamCreate(NULL, &HandleStreamEvents, &context, fse->paths, kFSEventStreamEventIdSinceNow, (CFAbsoluteTime) 0.1, kFSEventStreamCreateFlagNone | kFSEventStreamCreateFlagWatchRoot | kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagUseCFTypes);
|
||||
FSEventStreamScheduleWithRunLoop(stream, fse->threadloop, kCFRunLoopDefaultMode);
|
||||
FSEventStreamStart(stream);
|
||||
CFRunLoopRun();
|
||||
FSEventStreamStop(stream);
|
||||
FSEventStreamUnscheduleFromRunLoop(stream, fse->threadloop, kCFRunLoopDefaultMode);
|
||||
FSEventStreamInvalidate(stream);
|
||||
FSEventStreamRelease(stream);
|
||||
fse->threadloop = NULL;
|
||||
}
|
||||
|
||||
void FSEvents::threadStop() {
|
||||
if (!threadloop) return;
|
||||
CFRunLoopStop(threadloop);
|
||||
if (uv_thread_join(&thread)) abort();
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
The ISC License
|
||||
|
||||
Copyright (c) 2015 Elan Shanker
|
||||
|
||||
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.
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
glob-parent [](https://travis-ci.org/es128/glob-parent) [](https://coveralls.io/r/es128/glob-parent?branch=master)
|
||||
======
|
||||
Javascript module to extract the non-magic parent path from a glob string.
|
||||
|
||||
[](https://nodei.co/npm/glob-parent/)
|
||||
[](https://nodei.co/npm-dl/glob-parent/)
|
||||
|
||||
Usage
|
||||
-----
|
||||
```sh
|
||||
npm install glob-parent --save
|
||||
```
|
||||
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
var globParent = require('glob-parent');
|
||||
|
||||
globParent('path/to/*.js'); // 'path/to'
|
||||
globParent('/root/path/to/*.js'); // '/root/path/to'
|
||||
globParent('/*.js'); // '/'
|
||||
globParent('*.js'); // '.'
|
||||
globParent('**/*.js'); // '.'
|
||||
globParent('path/{to,from}'); // 'path'
|
||||
globParent('path/!(to|from)'); // 'path'
|
||||
globParent('path/?(to|from)'); // 'path'
|
||||
globParent('path/+(to|from)'); // 'path'
|
||||
globParent('path/*(to|from)'); // 'path'
|
||||
globParent('path/@(to|from)'); // 'path'
|
||||
globParent('path/**/*'); // 'path'
|
||||
|
||||
// if provided a non-glob path, returns the nearest dir
|
||||
globParent('path/foo/bar.js'); // 'path/foo'
|
||||
globParent('path/foo/'); // 'path/foo'
|
||||
globParent('path/foo'); // 'path' (see issue #3 for details)
|
||||
```
|
||||
|
||||
## Escaping
|
||||
|
||||
The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters:
|
||||
|
||||
- `?` (question mark)
|
||||
- `*` (star)
|
||||
- `|` (pipe)
|
||||
- `(` (opening parenthesis)
|
||||
- `)` (closing parenthesis)
|
||||
- `{` (opening curly brace)
|
||||
- `}` (closing curly brace)
|
||||
- `[` (opening bracket)
|
||||
- `]` (closing bracket)
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
globParent('foo/[bar]/') // 'foo'
|
||||
globParent('foo/\\[bar]/') // 'foo/[bar]'
|
||||
```
|
||||
|
||||
## Limitations
|
||||
|
||||
#### Braces & Brackets
|
||||
This library attempts a quick and imperfect method of determining which path
|
||||
parts have glob magic without fully parsing/lexing the pattern. There are some
|
||||
advanced use cases that can trip it up, such as nested braces where the outer
|
||||
pair is escaped and the inner one contains a path separator. If you find
|
||||
yourself in the unlikely circumstance of being affected by this or need to
|
||||
ensure higher-fidelity glob handling in your library, it is recommended that you
|
||||
pre-process your input with [expand-braces] and/or [expand-brackets].
|
||||
|
||||
#### Windows
|
||||
Backslashes are not valid path separators for globs. If a path with backslashes
|
||||
is provided anyway, for simple cases, glob-parent will replace the path
|
||||
separator for you and return the non-glob parent path (now with
|
||||
forward-slashes, which are still valid as Windows path separators).
|
||||
|
||||
This cannot be used in conjunction with escape characters.
|
||||
|
||||
```js
|
||||
// BAD
|
||||
globParent('C:\\Program Files \\(x86\\)\\*.ext') // 'C:/Program Files /(x86/)'
|
||||
|
||||
// GOOD
|
||||
globParent('C:/Program Files\\(x86\\)/*.ext') // 'C:/Program Files (x86)'
|
||||
```
|
||||
|
||||
If you are using escape characters for a pattern without path parts (i.e.
|
||||
relative to `cwd`), prefix with `./` to avoid confusing glob-parent.
|
||||
|
||||
```js
|
||||
// BAD
|
||||
globParent('foo \\[bar]') // 'foo '
|
||||
globParent('foo \\[bar]*') // 'foo '
|
||||
|
||||
// GOOD
|
||||
globParent('./foo \\[bar]') // 'foo [bar]'
|
||||
globParent('./foo \\[bar]*') // '.'
|
||||
```
|
||||
|
||||
|
||||
Change Log
|
||||
----------
|
||||
[See release notes page on GitHub](https://github.com/es128/glob-parent/releases)
|
||||
|
||||
License
|
||||
-------
|
||||
[ISC](https://raw.github.com/es128/glob-parent/master/LICENSE)
|
||||
|
||||
[expand-braces]: https://github.com/jonschlinkert/expand-braces
|
||||
[expand-brackets]: https://github.com/jonschlinkert/expand-brackets
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
'use strict';
|
||||
|
||||
var path = require('path');
|
||||
var isglob = require('is-glob');
|
||||
var pathDirname = require('path-dirname');
|
||||
var isWin32 = require('os').platform() === 'win32';
|
||||
|
||||
module.exports = function globParent(str) {
|
||||
// flip windows path separators
|
||||
if (isWin32 && str.indexOf('/') < 0) str = str.split('\\').join('/');
|
||||
|
||||
// special case for strings ending in enclosure containing path separator
|
||||
if (/[\{\[].*[\/]*.*[\}\]]$/.test(str)) str += '/';
|
||||
|
||||
// preserves full path in case of trailing path separator
|
||||
str += 'a';
|
||||
|
||||
// remove path parts that are globby
|
||||
do {str = pathDirname.posix(str)}
|
||||
while (isglob(str) || /(^|[^\\])([\{\[]|\([^\)]+$)/.test(str));
|
||||
|
||||
// remove escape chars and return result
|
||||
return str.replace(/\\([\*\?\|\[\]\(\)\{\}])/g, '$1');
|
||||
};
|
||||
Generated
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014-2016, Jon Schlinkert.
|
||||
|
||||
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.
|
||||
Generated
Vendored
+142
@@ -0,0 +1,142 @@
|
||||
# is-glob [](https://www.npmjs.com/package/is-glob) [](https://npmjs.org/package/is-glob) [](https://travis-ci.org/jonschlinkert/is-glob)
|
||||
|
||||
> Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience.
|
||||
|
||||
## Install
|
||||
|
||||
Install with [npm](https://www.npmjs.com/):
|
||||
|
||||
```sh
|
||||
$ npm install --save is-glob
|
||||
```
|
||||
|
||||
You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob).
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
var isGlob = require('is-glob');
|
||||
```
|
||||
|
||||
**True**
|
||||
|
||||
Patterns that have glob characters or regex patterns will return `true`:
|
||||
|
||||
```js
|
||||
isGlob('!foo.js');
|
||||
isGlob('*.js');
|
||||
isGlob('**/abc.js');
|
||||
isGlob('abc/*.js');
|
||||
isGlob('abc/(aaa|bbb).js');
|
||||
isGlob('abc/[a-z].js');
|
||||
isGlob('abc/{a,b}.js');
|
||||
isGlob('abc/?.js');
|
||||
//=> true
|
||||
```
|
||||
|
||||
Extglobs
|
||||
|
||||
```js
|
||||
isGlob('abc/@(a).js');
|
||||
isGlob('abc/!(a).js');
|
||||
isGlob('abc/+(a).js');
|
||||
isGlob('abc/*(a).js');
|
||||
isGlob('abc/?(a).js');
|
||||
//=> true
|
||||
```
|
||||
|
||||
**False**
|
||||
|
||||
Escaped globs or extglobs return `false`:
|
||||
|
||||
```js
|
||||
isGlob('abc/\\@(a).js');
|
||||
isGlob('abc/\\!(a).js');
|
||||
isGlob('abc/\\+(a).js');
|
||||
isGlob('abc/\\*(a).js');
|
||||
isGlob('abc/\\?(a).js');
|
||||
isGlob('\\!foo.js');
|
||||
isGlob('\\*.js');
|
||||
isGlob('\\*\\*/abc.js');
|
||||
isGlob('abc/\\*.js');
|
||||
isGlob('abc/\\(aaa|bbb).js');
|
||||
isGlob('abc/\\[a-z].js');
|
||||
isGlob('abc/\\{a,b}.js');
|
||||
isGlob('abc/\\?.js');
|
||||
//=> false
|
||||
```
|
||||
|
||||
Patterns that do not have glob patterns return `false`:
|
||||
|
||||
```js
|
||||
isGlob('abc.js');
|
||||
isGlob('abc/def/ghi.js');
|
||||
isGlob('foo.js');
|
||||
isGlob('abc/@.js');
|
||||
isGlob('abc/+.js');
|
||||
isGlob();
|
||||
isGlob(null);
|
||||
//=> false
|
||||
```
|
||||
|
||||
Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)):
|
||||
|
||||
```js
|
||||
isGlob(['**/*.js']);
|
||||
isGlob(['foo.js']);
|
||||
//=> false
|
||||
```
|
||||
|
||||
## About
|
||||
|
||||
### Related projects
|
||||
|
||||
* [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit")
|
||||
* [base](https://www.npmjs.com/package/base): base is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting… [more](https://github.com/node-base/base) | [homepage](https://github.com/node-base/base "base is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting with a handful of common methods, like `set`, `get`, `del` and `use`.")
|
||||
* [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.")
|
||||
* [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.")
|
||||
|
||||
### Contributing
|
||||
|
||||
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
|
||||
|
||||
### Contributors
|
||||
|
||||
| **Commits** | **Contributor**<br/> |
|
||||
| --- | --- |
|
||||
| 40 | [jonschlinkert](https://github.com/jonschlinkert) |
|
||||
| 1 | [tuvistavie](https://github.com/tuvistavie) |
|
||||
|
||||
### Building docs
|
||||
|
||||
_(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_
|
||||
|
||||
To generate the readme and API documentation with [verb](https://github.com/verbose/verb):
|
||||
|
||||
```sh
|
||||
$ npm install -g verb verb-generate-readme && verb
|
||||
```
|
||||
|
||||
### Running tests
|
||||
|
||||
Install dev dependencies:
|
||||
|
||||
```sh
|
||||
$ npm install -d && npm test
|
||||
```
|
||||
|
||||
### Author
|
||||
|
||||
**Jon Schlinkert**
|
||||
|
||||
* [github/jonschlinkert](https://github.com/jonschlinkert)
|
||||
* [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
|
||||
|
||||
### License
|
||||
|
||||
Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert).
|
||||
Released under the [MIT license](https://github.com/jonschlinkert/is-glob/blob/master/LICENSE).
|
||||
|
||||
***
|
||||
|
||||
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._
|
||||
Generated
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
/*!
|
||||
* is-glob <https://github.com/jonschlinkert/is-glob>
|
||||
*
|
||||
* Copyright (c) 2014-2016, Jon Schlinkert.
|
||||
* Licensed under the MIT License.
|
||||
*/
|
||||
|
||||
var isExtglob = require('is-extglob');
|
||||
|
||||
module.exports = function isGlob(str) {
|
||||
if (typeof str !== 'string' || str === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isExtglob(str)) return true;
|
||||
|
||||
var regex = /(\\).|([*?]|\[.*\]|\{.*\}|\(.*\|.*\)|^!)/;
|
||||
var match;
|
||||
|
||||
while ((match = regex.exec(str))) {
|
||||
if (match[2]) return true;
|
||||
str = str.slice(match.index + match[0].length);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
Generated
Vendored
+80
@@ -0,0 +1,80 @@
|
||||
{
|
||||
"name": "is-glob",
|
||||
"description": "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience.",
|
||||
"version": "3.1.0",
|
||||
"homepage": "https://github.com/jonschlinkert/is-glob",
|
||||
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
|
||||
"contributors": [
|
||||
"Daniel Perez <daniel@claudetech.com> (http://tuvistavie.com)",
|
||||
"Jon Schlinkert <jon.schlinkert@sellside.com> (http://twitter.com/jonschlinkert)"
|
||||
],
|
||||
"repository": "jonschlinkert/is-glob",
|
||||
"bugs": {
|
||||
"url": "https://github.com/jonschlinkert/is-glob/issues"
|
||||
},
|
||||
"license": "MIT",
|
||||
"files": [
|
||||
"index.js"
|
||||
],
|
||||
"main": "index.js",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "mocha"
|
||||
},
|
||||
"dependencies": {
|
||||
"is-extglob": "^2.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"gulp-format-md": "^0.1.10",
|
||||
"mocha": "^3.0.2"
|
||||
},
|
||||
"keywords": [
|
||||
"bash",
|
||||
"braces",
|
||||
"check",
|
||||
"exec",
|
||||
"expression",
|
||||
"extglob",
|
||||
"glob",
|
||||
"globbing",
|
||||
"globstar",
|
||||
"is",
|
||||
"match",
|
||||
"matches",
|
||||
"pattern",
|
||||
"regex",
|
||||
"regular",
|
||||
"string",
|
||||
"test"
|
||||
],
|
||||
"verb": {
|
||||
"layout": "default",
|
||||
"plugins": [
|
||||
"gulp-format-md"
|
||||
],
|
||||
"related": {
|
||||
"list": [
|
||||
"assemble",
|
||||
"base",
|
||||
"update",
|
||||
"verb"
|
||||
]
|
||||
},
|
||||
"reflinks": [
|
||||
"assemble",
|
||||
"bach",
|
||||
"base",
|
||||
"composer",
|
||||
"gulp",
|
||||
"has-glob",
|
||||
"is-valid-glob",
|
||||
"micromatch",
|
||||
"npm",
|
||||
"scaffold",
|
||||
"verb",
|
||||
"vinyl"
|
||||
]
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "glob-parent",
|
||||
"version": "3.1.0",
|
||||
"description": "Strips glob magic from a string to provide the parent directory path",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "istanbul test node_modules/mocha/bin/_mocha",
|
||||
"ci-test": "istanbul cover _mocha && cat ./coverage/lcov.info | coveralls"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/es128/glob-parent"
|
||||
},
|
||||
"keywords": [
|
||||
"glob",
|
||||
"parent",
|
||||
"strip",
|
||||
"path",
|
||||
"dirname",
|
||||
"directory",
|
||||
"base",
|
||||
"wildcard"
|
||||
],
|
||||
"files": [
|
||||
"index.js"
|
||||
],
|
||||
"author": "Elan Shanker (https://github.com/es128)",
|
||||
"license": "ISC",
|
||||
"bugs": {
|
||||
"url": "https://github.com/es128/glob-parent/issues"
|
||||
},
|
||||
"homepage": "https://github.com/es128/glob-parent",
|
||||
"dependencies": {
|
||||
"is-glob": "^3.1.0",
|
||||
"path-dirname": "^1.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"coveralls": "^2.11.2",
|
||||
"istanbul": "^0.3.5",
|
||||
"mocha": "^2.1.0"
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
The ISC License
|
||||
|
||||
Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, 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.
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
# 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](https://nodejs.org/api/fs.html)
|
||||
|
||||
* 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.readFile('some-file-or-whatever', (err, data) => {
|
||||
// Do stuff here.
|
||||
})
|
||||
```
|
||||
|
||||
## Sync methods
|
||||
|
||||
This module cannot intercept or handle `EMFILE` or `ENFILE` errors from sync
|
||||
methods. If you use sync methods which open file descriptors then you are
|
||||
responsible for dealing with any errors.
|
||||
|
||||
This is a known limitation, not a bug.
|
||||
|
||||
## Global Patching
|
||||
|
||||
If you want to patch the global fs module (or any other fs-like
|
||||
module) you can do this:
|
||||
|
||||
```javascript
|
||||
// Make sure to read the caveat below.
|
||||
var realFs = require('fs')
|
||||
var gracefulFs = require('graceful-fs')
|
||||
gracefulFs.gracefulify(realFs)
|
||||
```
|
||||
|
||||
This should only ever be done at the top-level application layer, in
|
||||
order to delay on EMFILE errors from any fs-using dependencies. You
|
||||
should **not** do this in a library, because it can cause unexpected
|
||||
delays in other parts of the program.
|
||||
|
||||
## Changes
|
||||
|
||||
This module is fairly stable at this point, and used by a lot of
|
||||
things. That being said, because it implements a subtle behavior
|
||||
change in a core part of the node API, even modest changes can be
|
||||
extremely breaking, and the versioning is thus biased towards
|
||||
bumping the major when in doubt.
|
||||
|
||||
The main change between major versions has been switching between
|
||||
providing a fully-patched `fs` module vs monkey-patching the node core
|
||||
builtin, and the approach by which a non-monkey-patched `fs` was
|
||||
created.
|
||||
|
||||
The goal is to trade `EMFILE` errors for slower fs operations. So, if
|
||||
you try to open a zillion files, rather than crashing, `open`
|
||||
operations will be queued up and wait for something else to `close`.
|
||||
|
||||
There are advantages to each approach. Monkey-patching the fs means
|
||||
that no `EMFILE` errors can possibly occur anywhere in your
|
||||
application, because everything is using the same core `fs` module,
|
||||
which is patched. However, it can also obviously cause undesirable
|
||||
side-effects, especially if the module is loaded multiple times.
|
||||
|
||||
Implementing a separate-but-identical patched `fs` module is more
|
||||
surgical (and doesn't run the risk of patching multiple times), but
|
||||
also imposes the challenge of keeping in sync with the core module.
|
||||
|
||||
The current approach loads the `fs` module, and then creates a
|
||||
lookalike object that has all the same methods, except a few that are
|
||||
patched. It is safe to use in all versions of Node from 0.8 through
|
||||
7.0.
|
||||
|
||||
### v4
|
||||
|
||||
* Do not monkey-patch the fs module. This module may now be used as a
|
||||
drop-in dep, and users can opt into monkey-patching the fs builtin
|
||||
if their app requires it.
|
||||
|
||||
### v3
|
||||
|
||||
* Monkey-patch fs, because the eval approach no longer works on recent
|
||||
node.
|
||||
* fixed possible type-error throw if rename fails on windows
|
||||
* verify that we *never* get EMFILE errors
|
||||
* Ignore ENOSYS from chmod/chown
|
||||
* clarify that graceful-fs must be used as a drop-in
|
||||
|
||||
### v2.1.0
|
||||
|
||||
* Use eval rather than monkey-patching fs.
|
||||
* readdir: Always sort the results
|
||||
* win32: requeue a file if error has an OK status
|
||||
|
||||
### v2.0
|
||||
|
||||
* A return to monkey patching
|
||||
* wrap process.cwd
|
||||
|
||||
### v1.1
|
||||
|
||||
* wrap readFile
|
||||
* Wrap fs.writeFile.
|
||||
* readdir protection
|
||||
* Don't clobber the fs builtin
|
||||
* Handle fs.read EAGAIN errors by trying again
|
||||
* Expose the curOpen counter
|
||||
* No-op lchown/lchmod if not implemented
|
||||
* fs.rename patch only for win32
|
||||
* Patch fs.rename to handle AV software on Windows
|
||||
* Close #4 Chown should not fail on einval or eperm if non-root
|
||||
* Fix isaacs/fstream#1 Only wrap fs one time
|
||||
* Fix #3 Start at 1024 max files, then back off on EMFILE
|
||||
* lutimes that doens't blow up on Linux
|
||||
* A full on-rewrite using a queue instead of just swallowing the EMFILE error
|
||||
* Wrap Read/Write streams as well
|
||||
|
||||
### 1.0
|
||||
|
||||
* Update engines for node 0.6
|
||||
* Be lstat-graceful on Windows
|
||||
* first
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
'use strict'
|
||||
|
||||
module.exports = clone
|
||||
|
||||
var getPrototypeOf = Object.getPrototypeOf || function (obj) {
|
||||
return obj.__proto__
|
||||
}
|
||||
|
||||
function clone (obj) {
|
||||
if (obj === null || typeof obj !== 'object')
|
||||
return obj
|
||||
|
||||
if (obj instanceof Object)
|
||||
var copy = { __proto__: getPrototypeOf(obj) }
|
||||
else
|
||||
var copy = Object.create(null)
|
||||
|
||||
Object.getOwnPropertyNames(obj).forEach(function (key) {
|
||||
Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key))
|
||||
})
|
||||
|
||||
return copy
|
||||
}
|
||||
+448
@@ -0,0 +1,448 @@
|
||||
var fs = require('fs')
|
||||
var polyfills = require('./polyfills.js')
|
||||
var legacy = require('./legacy-streams.js')
|
||||
var clone = require('./clone.js')
|
||||
|
||||
var util = require('util')
|
||||
|
||||
/* istanbul ignore next - node 0.x polyfill */
|
||||
var gracefulQueue
|
||||
var previousSymbol
|
||||
|
||||
/* istanbul ignore else - node 0.x polyfill */
|
||||
if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {
|
||||
gracefulQueue = Symbol.for('graceful-fs.queue')
|
||||
// This is used in testing by future versions
|
||||
previousSymbol = Symbol.for('graceful-fs.previous')
|
||||
} else {
|
||||
gracefulQueue = '___graceful-fs.queue'
|
||||
previousSymbol = '___graceful-fs.previous'
|
||||
}
|
||||
|
||||
function noop () {}
|
||||
|
||||
function publishQueue(context, queue) {
|
||||
Object.defineProperty(context, gracefulQueue, {
|
||||
get: function() {
|
||||
return queue
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
var debug = noop
|
||||
if (util.debuglog)
|
||||
debug = util.debuglog('gfs4')
|
||||
else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
|
||||
debug = function() {
|
||||
var m = util.format.apply(util, arguments)
|
||||
m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ')
|
||||
console.error(m)
|
||||
}
|
||||
|
||||
// Once time initialization
|
||||
if (!fs[gracefulQueue]) {
|
||||
// This queue can be shared by multiple loaded instances
|
||||
var queue = global[gracefulQueue] || []
|
||||
publishQueue(fs, queue)
|
||||
|
||||
// Patch fs.close/closeSync to shared queue version, because we need
|
||||
// to retry() whenever a close happens *anywhere* in the program.
|
||||
// This is essential when multiple graceful-fs instances are
|
||||
// in play at the same time.
|
||||
fs.close = (function (fs$close) {
|
||||
function close (fd, cb) {
|
||||
return fs$close.call(fs, fd, function (err) {
|
||||
// This function uses the graceful-fs shared queue
|
||||
if (!err) {
|
||||
resetQueue()
|
||||
}
|
||||
|
||||
if (typeof cb === 'function')
|
||||
cb.apply(this, arguments)
|
||||
})
|
||||
}
|
||||
|
||||
Object.defineProperty(close, previousSymbol, {
|
||||
value: fs$close
|
||||
})
|
||||
return close
|
||||
})(fs.close)
|
||||
|
||||
fs.closeSync = (function (fs$closeSync) {
|
||||
function closeSync (fd) {
|
||||
// This function uses the graceful-fs shared queue
|
||||
fs$closeSync.apply(fs, arguments)
|
||||
resetQueue()
|
||||
}
|
||||
|
||||
Object.defineProperty(closeSync, previousSymbol, {
|
||||
value: fs$closeSync
|
||||
})
|
||||
return closeSync
|
||||
})(fs.closeSync)
|
||||
|
||||
if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
|
||||
process.on('exit', function() {
|
||||
debug(fs[gracefulQueue])
|
||||
require('assert').equal(fs[gracefulQueue].length, 0)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (!global[gracefulQueue]) {
|
||||
publishQueue(global, fs[gracefulQueue]);
|
||||
}
|
||||
|
||||
module.exports = patch(clone(fs))
|
||||
if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
|
||||
module.exports = patch(fs)
|
||||
fs.__patched = true;
|
||||
}
|
||||
|
||||
function patch (fs) {
|
||||
// Everything that references the open() function needs to be in here
|
||||
polyfills(fs)
|
||||
fs.gracefulify = patch
|
||||
|
||||
fs.createReadStream = createReadStream
|
||||
fs.createWriteStream = createWriteStream
|
||||
var fs$readFile = fs.readFile
|
||||
fs.readFile = readFile
|
||||
function readFile (path, options, cb) {
|
||||
if (typeof options === 'function')
|
||||
cb = options, options = null
|
||||
|
||||
return go$readFile(path, options, cb)
|
||||
|
||||
function go$readFile (path, options, cb, startTime) {
|
||||
return fs$readFile(path, options, function (err) {
|
||||
if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
|
||||
enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()])
|
||||
else {
|
||||
if (typeof cb === 'function')
|
||||
cb.apply(this, arguments)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var fs$writeFile = fs.writeFile
|
||||
fs.writeFile = writeFile
|
||||
function writeFile (path, data, options, cb) {
|
||||
if (typeof options === 'function')
|
||||
cb = options, options = null
|
||||
|
||||
return go$writeFile(path, data, options, cb)
|
||||
|
||||
function go$writeFile (path, data, options, cb, startTime) {
|
||||
return fs$writeFile(path, data, options, function (err) {
|
||||
if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
|
||||
enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()])
|
||||
else {
|
||||
if (typeof cb === 'function')
|
||||
cb.apply(this, arguments)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var fs$appendFile = fs.appendFile
|
||||
if (fs$appendFile)
|
||||
fs.appendFile = appendFile
|
||||
function appendFile (path, data, options, cb) {
|
||||
if (typeof options === 'function')
|
||||
cb = options, options = null
|
||||
|
||||
return go$appendFile(path, data, options, cb)
|
||||
|
||||
function go$appendFile (path, data, options, cb, startTime) {
|
||||
return fs$appendFile(path, data, options, function (err) {
|
||||
if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
|
||||
enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()])
|
||||
else {
|
||||
if (typeof cb === 'function')
|
||||
cb.apply(this, arguments)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var fs$copyFile = fs.copyFile
|
||||
if (fs$copyFile)
|
||||
fs.copyFile = copyFile
|
||||
function copyFile (src, dest, flags, cb) {
|
||||
if (typeof flags === 'function') {
|
||||
cb = flags
|
||||
flags = 0
|
||||
}
|
||||
return go$copyFile(src, dest, flags, cb)
|
||||
|
||||
function go$copyFile (src, dest, flags, cb, startTime) {
|
||||
return fs$copyFile(src, dest, flags, function (err) {
|
||||
if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
|
||||
enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()])
|
||||
else {
|
||||
if (typeof cb === 'function')
|
||||
cb.apply(this, arguments)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var fs$readdir = fs.readdir
|
||||
fs.readdir = readdir
|
||||
var noReaddirOptionVersions = /^v[0-5]\./
|
||||
function readdir (path, options, cb) {
|
||||
if (typeof options === 'function')
|
||||
cb = options, options = null
|
||||
|
||||
var go$readdir = noReaddirOptionVersions.test(process.version)
|
||||
? function go$readdir (path, options, cb, startTime) {
|
||||
return fs$readdir(path, fs$readdirCallback(
|
||||
path, options, cb, startTime
|
||||
))
|
||||
}
|
||||
: function go$readdir (path, options, cb, startTime) {
|
||||
return fs$readdir(path, options, fs$readdirCallback(
|
||||
path, options, cb, startTime
|
||||
))
|
||||
}
|
||||
|
||||
return go$readdir(path, options, cb)
|
||||
|
||||
function fs$readdirCallback (path, options, cb, startTime) {
|
||||
return function (err, files) {
|
||||
if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
|
||||
enqueue([
|
||||
go$readdir,
|
||||
[path, options, cb],
|
||||
err,
|
||||
startTime || Date.now(),
|
||||
Date.now()
|
||||
])
|
||||
else {
|
||||
if (files && files.sort)
|
||||
files.sort()
|
||||
|
||||
if (typeof cb === 'function')
|
||||
cb.call(this, err, files)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (process.version.substr(0, 4) === 'v0.8') {
|
||||
var legStreams = legacy(fs)
|
||||
ReadStream = legStreams.ReadStream
|
||||
WriteStream = legStreams.WriteStream
|
||||
}
|
||||
|
||||
var fs$ReadStream = fs.ReadStream
|
||||
if (fs$ReadStream) {
|
||||
ReadStream.prototype = Object.create(fs$ReadStream.prototype)
|
||||
ReadStream.prototype.open = ReadStream$open
|
||||
}
|
||||
|
||||
var fs$WriteStream = fs.WriteStream
|
||||
if (fs$WriteStream) {
|
||||
WriteStream.prototype = Object.create(fs$WriteStream.prototype)
|
||||
WriteStream.prototype.open = WriteStream$open
|
||||
}
|
||||
|
||||
Object.defineProperty(fs, 'ReadStream', {
|
||||
get: function () {
|
||||
return ReadStream
|
||||
},
|
||||
set: function (val) {
|
||||
ReadStream = val
|
||||
},
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
})
|
||||
Object.defineProperty(fs, 'WriteStream', {
|
||||
get: function () {
|
||||
return WriteStream
|
||||
},
|
||||
set: function (val) {
|
||||
WriteStream = val
|
||||
},
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
})
|
||||
|
||||
// legacy names
|
||||
var FileReadStream = ReadStream
|
||||
Object.defineProperty(fs, 'FileReadStream', {
|
||||
get: function () {
|
||||
return FileReadStream
|
||||
},
|
||||
set: function (val) {
|
||||
FileReadStream = val
|
||||
},
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
})
|
||||
var FileWriteStream = WriteStream
|
||||
Object.defineProperty(fs, 'FileWriteStream', {
|
||||
get: function () {
|
||||
return FileWriteStream
|
||||
},
|
||||
set: function (val) {
|
||||
FileWriteStream = val
|
||||
},
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
})
|
||||
|
||||
function ReadStream (path, options) {
|
||||
if (this instanceof ReadStream)
|
||||
return fs$ReadStream.apply(this, arguments), this
|
||||
else
|
||||
return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
|
||||
}
|
||||
|
||||
function ReadStream$open () {
|
||||
var that = this
|
||||
open(that.path, that.flags, that.mode, function (err, fd) {
|
||||
if (err) {
|
||||
if (that.autoClose)
|
||||
that.destroy()
|
||||
|
||||
that.emit('error', err)
|
||||
} else {
|
||||
that.fd = fd
|
||||
that.emit('open', fd)
|
||||
that.read()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function WriteStream (path, options) {
|
||||
if (this instanceof WriteStream)
|
||||
return fs$WriteStream.apply(this, arguments), this
|
||||
else
|
||||
return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
|
||||
}
|
||||
|
||||
function WriteStream$open () {
|
||||
var that = this
|
||||
open(that.path, that.flags, that.mode, function (err, fd) {
|
||||
if (err) {
|
||||
that.destroy()
|
||||
that.emit('error', err)
|
||||
} else {
|
||||
that.fd = fd
|
||||
that.emit('open', fd)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function createReadStream (path, options) {
|
||||
return new fs.ReadStream(path, options)
|
||||
}
|
||||
|
||||
function createWriteStream (path, options) {
|
||||
return new fs.WriteStream(path, options)
|
||||
}
|
||||
|
||||
var fs$open = fs.open
|
||||
fs.open = open
|
||||
function open (path, flags, mode, cb) {
|
||||
if (typeof mode === 'function')
|
||||
cb = mode, mode = null
|
||||
|
||||
return go$open(path, flags, mode, cb)
|
||||
|
||||
function go$open (path, flags, mode, cb, startTime) {
|
||||
return fs$open(path, flags, mode, function (err, fd) {
|
||||
if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
|
||||
enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()])
|
||||
else {
|
||||
if (typeof cb === 'function')
|
||||
cb.apply(this, arguments)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return fs
|
||||
}
|
||||
|
||||
function enqueue (elem) {
|
||||
debug('ENQUEUE', elem[0].name, elem[1])
|
||||
fs[gracefulQueue].push(elem)
|
||||
retry()
|
||||
}
|
||||
|
||||
// keep track of the timeout between retry() calls
|
||||
var retryTimer
|
||||
|
||||
// reset the startTime and lastTime to now
|
||||
// this resets the start of the 60 second overall timeout as well as the
|
||||
// delay between attempts so that we'll retry these jobs sooner
|
||||
function resetQueue () {
|
||||
var now = Date.now()
|
||||
for (var i = 0; i < fs[gracefulQueue].length; ++i) {
|
||||
// entries that are only a length of 2 are from an older version, don't
|
||||
// bother modifying those since they'll be retried anyway.
|
||||
if (fs[gracefulQueue][i].length > 2) {
|
||||
fs[gracefulQueue][i][3] = now // startTime
|
||||
fs[gracefulQueue][i][4] = now // lastTime
|
||||
}
|
||||
}
|
||||
// call retry to make sure we're actively processing the queue
|
||||
retry()
|
||||
}
|
||||
|
||||
function retry () {
|
||||
// clear the timer and remove it to help prevent unintended concurrency
|
||||
clearTimeout(retryTimer)
|
||||
retryTimer = undefined
|
||||
|
||||
if (fs[gracefulQueue].length === 0)
|
||||
return
|
||||
|
||||
var elem = fs[gracefulQueue].shift()
|
||||
var fn = elem[0]
|
||||
var args = elem[1]
|
||||
// these items may be unset if they were added by an older graceful-fs
|
||||
var err = elem[2]
|
||||
var startTime = elem[3]
|
||||
var lastTime = elem[4]
|
||||
|
||||
// if we don't have a startTime we have no way of knowing if we've waited
|
||||
// long enough, so go ahead and retry this item now
|
||||
if (startTime === undefined) {
|
||||
debug('RETRY', fn.name, args)
|
||||
fn.apply(null, args)
|
||||
} else if (Date.now() - startTime >= 60000) {
|
||||
// it's been more than 60 seconds total, bail now
|
||||
debug('TIMEOUT', fn.name, args)
|
||||
var cb = args.pop()
|
||||
if (typeof cb === 'function')
|
||||
cb.call(null, err)
|
||||
} else {
|
||||
// the amount of time between the last attempt and right now
|
||||
var sinceAttempt = Date.now() - lastTime
|
||||
// the amount of time between when we first tried, and when we last tried
|
||||
// rounded up to at least 1
|
||||
var sinceStart = Math.max(lastTime - startTime, 1)
|
||||
// backoff. wait longer than the total time we've been retrying, but only
|
||||
// up to a maximum of 100ms
|
||||
var desiredDelay = Math.min(sinceStart * 1.2, 100)
|
||||
// it's been long enough since the last retry, do it again
|
||||
if (sinceAttempt >= desiredDelay) {
|
||||
debug('RETRY', fn.name, args)
|
||||
fn.apply(null, args.concat([startTime]))
|
||||
} else {
|
||||
// if we can't do this job yet, push it to the end of the queue
|
||||
// and let the next iteration check again
|
||||
fs[gracefulQueue].push(elem)
|
||||
}
|
||||
}
|
||||
|
||||
// schedule our next run if one isn't already scheduled
|
||||
if (retryTimer === undefined) {
|
||||
retryTimer = setTimeout(retry, 0)
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user