mirror of
https://github.com/apache/cordova-android.git
synced 2026-07-06 00:00:08 +08:00
CB-9782 Implements PlatformApi contract for Android platform.
This closes #226
This commit is contained in:
+1
@@ -0,0 +1 @@
|
||||
node_modules
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
language: node_js
|
||||
|
||||
node_js:
|
||||
- 0.6
|
||||
|
||||
script: make test
|
||||
|
||||
notifications:
|
||||
email:
|
||||
- tomaz+travisci@tomaz.me
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
elementtree v0.1.6 (in development)
|
||||
|
||||
* Add support for CData elements. (#14)
|
||||
[hermannpencole]
|
||||
|
||||
elementtree v0.1.5 - 2012-11-14
|
||||
|
||||
* Fix a bug in the find() and findtext() method which could manifest itself
|
||||
under some conditions.
|
||||
[metagriffin]
|
||||
|
||||
elementtree v0.1.4 - 2012-10-15
|
||||
|
||||
* Allow user to use namespaced attributes when using find* functions.
|
||||
[Andrew Lunny]
|
||||
|
||||
elementtree v0.1.3 - 2012-09-21
|
||||
|
||||
* Improve the output of text content in the tags (strip unnecessary line break
|
||||
characters).
|
||||
|
||||
[Darryl Pogue]
|
||||
|
||||
elementtree v0.1.2 - 2012-09-04
|
||||
|
||||
* Allow user to pass 'indent' option to ElementTree.write method. If this
|
||||
option is specified (e.g. {'indent': 4}). XML will be pretty printed.
|
||||
[Darryl Pogue, Tomaz Muraus]
|
||||
|
||||
* Bump sax dependency version.
|
||||
|
||||
elementtree v0.1.1 - 2011-09-23
|
||||
|
||||
* Improve special character escaping.
|
||||
[Ryan Phillips]
|
||||
|
||||
elementtree v0.1.0 - 2011-09-05
|
||||
|
||||
* Initial release.
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
TESTS := \
|
||||
tests/test-simple.js
|
||||
|
||||
|
||||
|
||||
PATH := ./node_modules/.bin:$(PATH)
|
||||
|
||||
WHISKEY := $(shell bash -c 'PATH=$(PATH) type -p whiskey')
|
||||
|
||||
default: test
|
||||
|
||||
test:
|
||||
NODE_PATH=`pwd`/lib/ ${WHISKEY} --scope-leaks --sequential --real-time --tests "${TESTS}"
|
||||
|
||||
tap:
|
||||
NODE_PATH=`pwd`/lib/ ${WHISKEY} --test-reporter tap --sequential --real-time --tests "${TESTS}"
|
||||
|
||||
coverage:
|
||||
NODE_PATH=`pwd`/lib/ ${WHISKEY} --sequential --coverage --coverage-reporter html --coverage-dir coverage_html --tests "${TESTS}"
|
||||
|
||||
.PHONY: default test coverage tap scope
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
node-elementtree
|
||||
Copyright (c) 2011, Rackspace, Inc.
|
||||
|
||||
The ElementTree toolkit is Copyright (c) 1999-2007 by Fredrik Lundh
|
||||
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
node-elementtree
|
||||
====================
|
||||
|
||||
node-elementtree is a [Node.js](http://nodejs.org) XML parser and serializer based upon the [Python ElementTree v1.3](http://effbot.org/zone/element-index.htm) module.
|
||||
|
||||
Installation
|
||||
====================
|
||||
|
||||
$ npm install elementtree
|
||||
|
||||
Using the library
|
||||
====================
|
||||
|
||||
For the usage refer to the Python ElementTree library documentation - [http://effbot.org/zone/element-index.htm#usage](http://effbot.org/zone/element-index.htm#usage).
|
||||
|
||||
Supported XPath expressions in `find`, `findall` and `findtext` methods are listed on [http://effbot.org/zone/element-xpath.htm](http://effbot.org/zone/element-xpath.htm).
|
||||
|
||||
Example 1 – Creating An XML Document
|
||||
====================
|
||||
|
||||
This example shows how to build a valid XML document that can be published to
|
||||
Atom Hopper. Atom Hopper is used internally as a bridge from products all the
|
||||
way to collecting revenue, called “Usage.” MaaS and other products send similar
|
||||
events to it every time user performs an action on a resource
|
||||
(e.g. creates,updates or deletes). Below is an example of leveraging the API
|
||||
to create a new XML document.
|
||||
|
||||
```javascript
|
||||
var et = require('elementtree');
|
||||
var XML = et.XML;
|
||||
var ElementTree = et.ElementTree;
|
||||
var element = et.Element;
|
||||
var subElement = et.SubElement;
|
||||
|
||||
var date, root, tenantId, serviceName, eventType, usageId, dataCenter, region,
|
||||
checks, resourceId, category, startTime, resourceName, etree, xml;
|
||||
|
||||
date = new Date();
|
||||
|
||||
root = element('entry');
|
||||
root.set('xmlns', 'http://www.w3.org/2005/Atom');
|
||||
|
||||
tenantId = subElement(root, 'TenantId');
|
||||
tenantId.text = '12345';
|
||||
|
||||
serviceName = subElement(root, 'ServiceName');
|
||||
serviceName.text = 'MaaS';
|
||||
|
||||
resourceId = subElement(root, 'ResourceID');
|
||||
resourceId.text = 'enAAAA';
|
||||
|
||||
usageId = subElement(root, 'UsageID');
|
||||
usageId.text = '550e8400-e29b-41d4-a716-446655440000';
|
||||
|
||||
eventType = subElement(root, 'EventType');
|
||||
eventType.text = 'create';
|
||||
|
||||
category = subElement(root, 'category');
|
||||
category.set('term', 'monitoring.entity.create');
|
||||
|
||||
dataCenter = subElement(root, 'DataCenter');
|
||||
dataCenter.text = 'global';
|
||||
|
||||
region = subElement(root, 'Region');
|
||||
region.text = 'global';
|
||||
|
||||
startTime = subElement(root, 'StartTime');
|
||||
startTime.text = date;
|
||||
|
||||
resourceName = subElement(root, 'ResourceName');
|
||||
resourceName.text = 'entity';
|
||||
|
||||
etree = new ElementTree(root);
|
||||
xml = etree.write({'xml_declaration': false});
|
||||
console.log(xml);
|
||||
```
|
||||
|
||||
As you can see, both et.Element and et.SubElement are factory methods which
|
||||
return a new instance of Element and SubElement class, respectively.
|
||||
When you create a new element (tag) you can use set method to set an attribute.
|
||||
To set the tag value, assign a value to the .text attribute.
|
||||
|
||||
This example would output a document that looks like this:
|
||||
|
||||
```xml
|
||||
<entry xmlns="http://www.w3.org/2005/Atom">
|
||||
<TenantId>12345</TenantId>
|
||||
<ServiceName>MaaS</ServiceName>
|
||||
<ResourceID>enAAAA</ResourceID>
|
||||
<UsageID>550e8400-e29b-41d4-a716-446655440000</UsageID>
|
||||
<EventType>create</EventType>
|
||||
<category term="monitoring.entity.create"/>
|
||||
<DataCenter>global</DataCenter>
|
||||
<Region>global</Region>
|
||||
<StartTime>Sun Apr 29 2012 16:37:32 GMT-0700 (PDT)</StartTime>
|
||||
<ResourceName>entity</ResourceName>
|
||||
</entry>
|
||||
```
|
||||
|
||||
Example 2 – Parsing An XML Document
|
||||
====================
|
||||
|
||||
This example shows how to parse an XML document and use simple XPath selectors.
|
||||
For demonstration purposes, we will use the XML document located at
|
||||
https://gist.github.com/2554343.
|
||||
|
||||
Behind the scenes, node-elementtree uses Isaac’s sax library for parsing XML,
|
||||
but the library has a concept of “parsers,” which means it’s pretty simple to
|
||||
add support for a different parser.
|
||||
|
||||
```javascript
|
||||
var fs = require('fs');
|
||||
|
||||
var et = require('elementtree');
|
||||
|
||||
var XML = et.XML;
|
||||
var ElementTree = et.ElementTree;
|
||||
var element = et.Element;
|
||||
var subElement = et.SubElement;
|
||||
|
||||
var data, etree;
|
||||
|
||||
data = fs.readFileSync('document.xml').toString();
|
||||
etree = et.parse(data);
|
||||
|
||||
console.log(etree.findall('./entry/TenantId').length); // 2
|
||||
console.log(etree.findtext('./entry/ServiceName')); // MaaS
|
||||
console.log(etree.findall('./entry/category')[0].get('term')); // monitoring.entity.create
|
||||
console.log(etree.findall('*/category/[@term="monitoring.entity.update"]').length); // 1
|
||||
```
|
||||
|
||||
Build status
|
||||
====================
|
||||
|
||||
[](http://travis-ci.org/racker/node-elementtree)
|
||||
|
||||
|
||||
License
|
||||
====================
|
||||
|
||||
node-elementtree is distributed under the [Apache license](http://www.apache.org/licenses/LICENSE-2.0.html).
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2011 Rackspace
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
var DEFAULT_PARSER = 'sax';
|
||||
|
||||
exports.DEFAULT_PARSER = DEFAULT_PARSER;
|
||||
+343
@@ -0,0 +1,343 @@
|
||||
/**
|
||||
* Copyright 2011 Rackspace
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
var sprintf = require('./sprintf').sprintf;
|
||||
|
||||
var utils = require('./utils');
|
||||
var SyntaxError = require('./errors').SyntaxError;
|
||||
|
||||
var _cache = {};
|
||||
|
||||
var RE = new RegExp(
|
||||
"(" +
|
||||
"'[^']*'|\"[^\"]*\"|" +
|
||||
"::|" +
|
||||
"//?|" +
|
||||
"\\.\\.|" +
|
||||
"\\(\\)|" +
|
||||
"[/.*:\\[\\]\\(\\)@=])|" +
|
||||
"((?:\\{[^}]+\\})?[^/\\[\\]\\(\\)@=\\s]+)|" +
|
||||
"\\s+", 'g'
|
||||
);
|
||||
|
||||
var xpath_tokenizer = utils.findall.bind(null, RE);
|
||||
|
||||
function prepare_tag(next, token) {
|
||||
var tag = token[0];
|
||||
|
||||
function select(context, result) {
|
||||
var i, len, elem, rv = [];
|
||||
|
||||
for (i = 0, len = result.length; i < len; i++) {
|
||||
elem = result[i];
|
||||
elem._children.forEach(function(e) {
|
||||
if (e.tag === tag) {
|
||||
rv.push(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
return select;
|
||||
}
|
||||
|
||||
function prepare_star(next, token) {
|
||||
function select(context, result) {
|
||||
var i, len, elem, rv = [];
|
||||
|
||||
for (i = 0, len = result.length; i < len; i++) {
|
||||
elem = result[i];
|
||||
elem._children.forEach(function(e) {
|
||||
rv.push(e);
|
||||
});
|
||||
}
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
return select;
|
||||
}
|
||||
|
||||
function prepare_dot(next, token) {
|
||||
function select(context, result) {
|
||||
var i, len, elem, rv = [];
|
||||
|
||||
for (i = 0, len = result.length; i < len; i++) {
|
||||
elem = result[i];
|
||||
rv.push(elem);
|
||||
}
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
return select;
|
||||
}
|
||||
|
||||
function prepare_iter(next, token) {
|
||||
var tag;
|
||||
token = next();
|
||||
|
||||
if (token[1] === '*') {
|
||||
tag = '*';
|
||||
}
|
||||
else if (!token[1]) {
|
||||
tag = token[0] || '';
|
||||
}
|
||||
else {
|
||||
throw new SyntaxError(token);
|
||||
}
|
||||
|
||||
function select(context, result) {
|
||||
var i, len, elem, rv = [];
|
||||
|
||||
for (i = 0, len = result.length; i < len; i++) {
|
||||
elem = result[i];
|
||||
elem.iter(tag, function(e) {
|
||||
if (e !== elem) {
|
||||
rv.push(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
return select;
|
||||
}
|
||||
|
||||
function prepare_dot_dot(next, token) {
|
||||
function select(context, result) {
|
||||
var i, len, elem, rv = [], parent_map = context.parent_map;
|
||||
|
||||
if (!parent_map) {
|
||||
context.parent_map = parent_map = {};
|
||||
|
||||
context.root.iter(null, function(p) {
|
||||
p._children.forEach(function(e) {
|
||||
parent_map[e] = p;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
for (i = 0, len = result.length; i < len; i++) {
|
||||
elem = result[i];
|
||||
|
||||
if (parent_map.hasOwnProperty(elem)) {
|
||||
rv.push(parent_map[elem]);
|
||||
}
|
||||
}
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
return select;
|
||||
}
|
||||
|
||||
|
||||
function prepare_predicate(next, token) {
|
||||
var tag, key, value, select;
|
||||
token = next();
|
||||
|
||||
if (token[1] === '@') {
|
||||
// attribute
|
||||
token = next();
|
||||
|
||||
if (token[1]) {
|
||||
throw new SyntaxError(token, 'Invalid attribute predicate');
|
||||
}
|
||||
|
||||
key = token[0];
|
||||
token = next();
|
||||
|
||||
if (token[1] === ']') {
|
||||
select = function(context, result) {
|
||||
var i, len, elem, rv = [];
|
||||
|
||||
for (i = 0, len = result.length; i < len; i++) {
|
||||
elem = result[i];
|
||||
|
||||
if (elem.get(key)) {
|
||||
rv.push(elem);
|
||||
}
|
||||
}
|
||||
|
||||
return rv;
|
||||
};
|
||||
}
|
||||
else if (token[1] === '=') {
|
||||
value = next()[1];
|
||||
|
||||
if (value[0] === '"' || value[value.length - 1] === '\'') {
|
||||
value = value.slice(1, value.length - 1);
|
||||
}
|
||||
else {
|
||||
throw new SyntaxError(token, 'Ivalid comparison target');
|
||||
}
|
||||
|
||||
token = next();
|
||||
select = function(context, result) {
|
||||
var i, len, elem, rv = [];
|
||||
|
||||
for (i = 0, len = result.length; i < len; i++) {
|
||||
elem = result[i];
|
||||
|
||||
if (elem.get(key) === value) {
|
||||
rv.push(elem);
|
||||
}
|
||||
}
|
||||
|
||||
return rv;
|
||||
};
|
||||
}
|
||||
|
||||
if (token[1] !== ']') {
|
||||
throw new SyntaxError(token, 'Invalid attribute predicate');
|
||||
}
|
||||
}
|
||||
else if (!token[1]) {
|
||||
tag = token[0] || '';
|
||||
token = next();
|
||||
|
||||
if (token[1] !== ']') {
|
||||
throw new SyntaxError(token, 'Invalid node predicate');
|
||||
}
|
||||
|
||||
select = function(context, result) {
|
||||
var i, len, elem, rv = [];
|
||||
|
||||
for (i = 0, len = result.length; i < len; i++) {
|
||||
elem = result[i];
|
||||
|
||||
if (elem.find(tag)) {
|
||||
rv.push(elem);
|
||||
}
|
||||
}
|
||||
|
||||
return rv;
|
||||
};
|
||||
}
|
||||
else {
|
||||
throw new SyntaxError(null, 'Invalid predicate');
|
||||
}
|
||||
|
||||
return select;
|
||||
}
|
||||
|
||||
|
||||
|
||||
var ops = {
|
||||
"": prepare_tag,
|
||||
"*": prepare_star,
|
||||
".": prepare_dot,
|
||||
"..": prepare_dot_dot,
|
||||
"//": prepare_iter,
|
||||
"[": prepare_predicate,
|
||||
};
|
||||
|
||||
function _SelectorContext(root) {
|
||||
this.parent_map = null;
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
function findall(elem, path) {
|
||||
var selector, result, i, len, token, value, select, context;
|
||||
|
||||
if (_cache.hasOwnProperty(path)) {
|
||||
selector = _cache[path];
|
||||
}
|
||||
else {
|
||||
// TODO: Use smarter cache purging approach
|
||||
if (Object.keys(_cache).length > 100) {
|
||||
_cache = {};
|
||||
}
|
||||
|
||||
if (path.charAt(0) === '/') {
|
||||
throw new SyntaxError(null, 'Cannot use absolute path on element');
|
||||
}
|
||||
|
||||
result = xpath_tokenizer(path);
|
||||
selector = [];
|
||||
|
||||
function getToken() {
|
||||
return result.shift();
|
||||
}
|
||||
|
||||
token = getToken();
|
||||
while (true) {
|
||||
var c = token[1] || '';
|
||||
value = ops[c](getToken, token);
|
||||
|
||||
if (!value) {
|
||||
throw new SyntaxError(null, sprintf('Invalid path: %s', path));
|
||||
}
|
||||
|
||||
selector.push(value);
|
||||
token = getToken();
|
||||
|
||||
if (!token) {
|
||||
break;
|
||||
}
|
||||
else if (token[1] === '/') {
|
||||
token = getToken();
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
_cache[path] = selector;
|
||||
}
|
||||
|
||||
// Execute slector pattern
|
||||
result = [elem];
|
||||
context = new _SelectorContext(elem);
|
||||
|
||||
for (i = 0, len = selector.length; i < len; i++) {
|
||||
select = selector[i];
|
||||
result = select(context, result);
|
||||
}
|
||||
|
||||
return result || [];
|
||||
}
|
||||
|
||||
function find(element, path) {
|
||||
var resultElements = findall(element, path);
|
||||
|
||||
if (resultElements && resultElements.length > 0) {
|
||||
return resultElements[0];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function findtext(element, path, defvalue) {
|
||||
var resultElements = findall(element, path);
|
||||
|
||||
if (resultElements && resultElements.length > 0) {
|
||||
return resultElements[0].text;
|
||||
}
|
||||
|
||||
return defvalue;
|
||||
}
|
||||
|
||||
|
||||
exports.find = find;
|
||||
exports.findall = findall;
|
||||
exports.findtext = findtext;
|
||||
+611
@@ -0,0 +1,611 @@
|
||||
/**
|
||||
* Copyright 2011 Rackspace
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
var sprintf = require('./sprintf').sprintf;
|
||||
|
||||
var utils = require('./utils');
|
||||
var ElementPath = require('./elementpath');
|
||||
var TreeBuilder = require('./treebuilder').TreeBuilder;
|
||||
var get_parser = require('./parser').get_parser;
|
||||
var constants = require('./constants');
|
||||
|
||||
var element_ids = 0;
|
||||
|
||||
function Element(tag, attrib)
|
||||
{
|
||||
this._id = element_ids++;
|
||||
this.tag = tag;
|
||||
this.attrib = {};
|
||||
this.text = null;
|
||||
this.tail = null;
|
||||
this._children = [];
|
||||
|
||||
if (attrib) {
|
||||
this.attrib = utils.merge(this.attrib, attrib);
|
||||
}
|
||||
}
|
||||
|
||||
Element.prototype.toString = function()
|
||||
{
|
||||
return sprintf("<Element %s at %s>", this.tag, this._id);
|
||||
};
|
||||
|
||||
Element.prototype.makeelement = function(tag, attrib)
|
||||
{
|
||||
return new Element(tag, attrib);
|
||||
};
|
||||
|
||||
Element.prototype.len = function()
|
||||
{
|
||||
return this._children.length;
|
||||
};
|
||||
|
||||
Element.prototype.getItem = function(index)
|
||||
{
|
||||
return this._children[index];
|
||||
};
|
||||
|
||||
Element.prototype.setItem = function(index, element)
|
||||
{
|
||||
this._children[index] = element;
|
||||
};
|
||||
|
||||
Element.prototype.delItem = function(index)
|
||||
{
|
||||
this._children.splice(index, 1);
|
||||
};
|
||||
|
||||
Element.prototype.getSlice = function(start, stop)
|
||||
{
|
||||
return this._children.slice(start, stop);
|
||||
};
|
||||
|
||||
Element.prototype.setSlice = function(start, stop, elements)
|
||||
{
|
||||
var i;
|
||||
var k = 0;
|
||||
for (i = start; i < stop; i++, k++) {
|
||||
this._children[i] = elements[k];
|
||||
}
|
||||
};
|
||||
|
||||
Element.prototype.delSlice = function(start, stop)
|
||||
{
|
||||
this._children.splice(start, stop - start);
|
||||
};
|
||||
|
||||
Element.prototype.append = function(element)
|
||||
{
|
||||
this._children.push(element);
|
||||
};
|
||||
|
||||
Element.prototype.extend = function(elements)
|
||||
{
|
||||
this._children.concat(elements);
|
||||
};
|
||||
|
||||
Element.prototype.insert = function(index, element)
|
||||
{
|
||||
this._children[index] = element;
|
||||
};
|
||||
|
||||
Element.prototype.remove = function(element)
|
||||
{
|
||||
this._children = this._children.filter(function(e) {
|
||||
/* TODO: is this the right way to do this? */
|
||||
if (e._id === element._id) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
Element.prototype.getchildren = function() {
|
||||
return this._children;
|
||||
};
|
||||
|
||||
Element.prototype.find = function(path)
|
||||
{
|
||||
return ElementPath.find(this, path);
|
||||
};
|
||||
|
||||
Element.prototype.findtext = function(path, defvalue)
|
||||
{
|
||||
return ElementPath.findtext(this, path, defvalue);
|
||||
};
|
||||
|
||||
Element.prototype.findall = function(path, defvalue)
|
||||
{
|
||||
return ElementPath.findall(this, path, defvalue);
|
||||
};
|
||||
|
||||
Element.prototype.clear = function()
|
||||
{
|
||||
this.attrib = {};
|
||||
this._children = [];
|
||||
this.text = null;
|
||||
this.tail = null;
|
||||
};
|
||||
|
||||
Element.prototype.get = function(key, defvalue)
|
||||
{
|
||||
if (this.attrib[key] !== undefined) {
|
||||
return this.attrib[key];
|
||||
}
|
||||
else {
|
||||
return defvalue;
|
||||
}
|
||||
};
|
||||
|
||||
Element.prototype.set = function(key, value)
|
||||
{
|
||||
this.attrib[key] = value;
|
||||
};
|
||||
|
||||
Element.prototype.keys = function()
|
||||
{
|
||||
return Object.keys(this.attrib);
|
||||
};
|
||||
|
||||
Element.prototype.items = function()
|
||||
{
|
||||
return utils.items(this.attrib);
|
||||
};
|
||||
|
||||
/*
|
||||
* In python this uses a generator, but in v8 we don't have em,
|
||||
* so we use a callback instead.
|
||||
**/
|
||||
Element.prototype.iter = function(tag, callback)
|
||||
{
|
||||
var self = this;
|
||||
var i, child;
|
||||
|
||||
if (tag === "*") {
|
||||
tag = null;
|
||||
}
|
||||
|
||||
if (tag === null || this.tag === tag) {
|
||||
callback(self);
|
||||
}
|
||||
|
||||
for (i = 0; i < this._children.length; i++) {
|
||||
child = this._children[i];
|
||||
child.iter(tag, function(e) {
|
||||
callback(e);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
Element.prototype.itertext = function(callback)
|
||||
{
|
||||
this.iter(null, function(e) {
|
||||
if (e.text) {
|
||||
callback(e.text);
|
||||
}
|
||||
|
||||
if (e.tail) {
|
||||
callback(e.tail);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
function SubElement(parent, tag, attrib) {
|
||||
var element = parent.makeelement(tag, attrib);
|
||||
parent.append(element);
|
||||
return element;
|
||||
}
|
||||
|
||||
function Comment(text) {
|
||||
var element = new Element(Comment);
|
||||
if (text) {
|
||||
element.text = text;
|
||||
}
|
||||
return element;
|
||||
}
|
||||
|
||||
function CData(text) {
|
||||
var element = new Element(CData);
|
||||
if (text) {
|
||||
element.text = text;
|
||||
}
|
||||
return element;
|
||||
}
|
||||
|
||||
function ProcessingInstruction(target, text)
|
||||
{
|
||||
var element = new Element(ProcessingInstruction);
|
||||
element.text = target;
|
||||
if (text) {
|
||||
element.text = element.text + " " + text;
|
||||
}
|
||||
return element;
|
||||
}
|
||||
|
||||
function QName(text_or_uri, tag)
|
||||
{
|
||||
if (tag) {
|
||||
text_or_uri = sprintf("{%s}%s", text_or_uri, tag);
|
||||
}
|
||||
this.text = text_or_uri;
|
||||
}
|
||||
|
||||
QName.prototype.toString = function() {
|
||||
return this.text;
|
||||
};
|
||||
|
||||
function ElementTree(element)
|
||||
{
|
||||
this._root = element;
|
||||
}
|
||||
|
||||
ElementTree.prototype.getroot = function() {
|
||||
return this._root;
|
||||
};
|
||||
|
||||
ElementTree.prototype._setroot = function(element) {
|
||||
this._root = element;
|
||||
};
|
||||
|
||||
ElementTree.prototype.parse = function(source, parser) {
|
||||
if (!parser) {
|
||||
parser = get_parser(constants.DEFAULT_PARSER);
|
||||
parser = new parser.XMLParser(new TreeBuilder());
|
||||
}
|
||||
|
||||
parser.feed(source);
|
||||
this._root = parser.close();
|
||||
return this._root;
|
||||
};
|
||||
|
||||
ElementTree.prototype.iter = function(tag, callback) {
|
||||
this._root.iter(tag, callback);
|
||||
};
|
||||
|
||||
ElementTree.prototype.find = function(path) {
|
||||
return this._root.find(path);
|
||||
};
|
||||
|
||||
ElementTree.prototype.findtext = function(path, defvalue) {
|
||||
return this._root.findtext(path, defvalue);
|
||||
};
|
||||
|
||||
ElementTree.prototype.findall = function(path) {
|
||||
return this._root.findall(path);
|
||||
};
|
||||
|
||||
/**
|
||||
* Unlike ElementTree, we don't write to a file, we return you a string.
|
||||
*/
|
||||
ElementTree.prototype.write = function(options) {
|
||||
var sb = [];
|
||||
options = utils.merge({
|
||||
encoding: 'utf-8',
|
||||
xml_declaration: null,
|
||||
default_namespace: null,
|
||||
method: 'xml'}, options);
|
||||
|
||||
if (options.xml_declaration !== false) {
|
||||
sb.push("<?xml version='1.0' encoding='"+options.encoding +"'?>\n");
|
||||
}
|
||||
|
||||
if (options.method === "text") {
|
||||
_serialize_text(sb, self._root, encoding);
|
||||
}
|
||||
else {
|
||||
var qnames, namespaces, indent, indent_string;
|
||||
var x = _namespaces(this._root, options.encoding, options.default_namespace);
|
||||
qnames = x[0];
|
||||
namespaces = x[1];
|
||||
|
||||
if (options.hasOwnProperty('indent')) {
|
||||
indent = 0;
|
||||
indent_string = new Array(options.indent + 1).join(' ');
|
||||
}
|
||||
else {
|
||||
indent = false;
|
||||
}
|
||||
|
||||
if (options.method === "xml") {
|
||||
_serialize_xml(function(data) {
|
||||
sb.push(data);
|
||||
}, this._root, options.encoding, qnames, namespaces, indent, indent_string);
|
||||
}
|
||||
else {
|
||||
/* TODO: html */
|
||||
throw new Error("unknown serialization method "+ options.method);
|
||||
}
|
||||
}
|
||||
|
||||
return sb.join("");
|
||||
};
|
||||
|
||||
var _namespace_map = {
|
||||
/* "well-known" namespace prefixes */
|
||||
"http://www.w3.org/XML/1998/namespace": "xml",
|
||||
"http://www.w3.org/1999/xhtml": "html",
|
||||
"http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
|
||||
"http://schemas.xmlsoap.org/wsdl/": "wsdl",
|
||||
/* xml schema */
|
||||
"http://www.w3.org/2001/XMLSchema": "xs",
|
||||
"http://www.w3.org/2001/XMLSchema-instance": "xsi",
|
||||
/* dublic core */
|
||||
"http://purl.org/dc/elements/1.1/": "dc",
|
||||
};
|
||||
|
||||
function register_namespace(prefix, uri) {
|
||||
if (/ns\d+$/.test(prefix)) {
|
||||
throw new Error('Prefix format reserved for internal use');
|
||||
}
|
||||
|
||||
if (_namespace_map.hasOwnProperty(uri) && _namespace_map[uri] === prefix) {
|
||||
delete _namespace_map[uri];
|
||||
}
|
||||
|
||||
_namespace_map[uri] = prefix;
|
||||
}
|
||||
|
||||
|
||||
function _escape(text, encoding, isAttribute, isText) {
|
||||
if (text) {
|
||||
text = text.toString();
|
||||
text = text.replace(/&/g, '&');
|
||||
text = text.replace(/</g, '<');
|
||||
text = text.replace(/>/g, '>');
|
||||
if (!isText) {
|
||||
text = text.replace(/\n/g, '
');
|
||||
text = text.replace(/\r/g, '
');
|
||||
}
|
||||
if (isAttribute) {
|
||||
text = text.replace(/"/g, '"');
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/* TODO: benchmark single regex */
|
||||
function _escape_attrib(text, encoding) {
|
||||
return _escape(text, encoding, true);
|
||||
}
|
||||
|
||||
function _escape_cdata(text, encoding) {
|
||||
return _escape(text, encoding, false);
|
||||
}
|
||||
|
||||
function _escape_text(text, encoding) {
|
||||
return _escape(text, encoding, false, true);
|
||||
}
|
||||
|
||||
function _namespaces(elem, encoding, default_namespace) {
|
||||
var qnames = {};
|
||||
var namespaces = {};
|
||||
|
||||
if (default_namespace) {
|
||||
namespaces[default_namespace] = "";
|
||||
}
|
||||
|
||||
function encode(text) {
|
||||
return text;
|
||||
}
|
||||
|
||||
function add_qname(qname) {
|
||||
if (qname[0] === "{") {
|
||||
var tmp = qname.substring(1).split("}", 2);
|
||||
var uri = tmp[0];
|
||||
var tag = tmp[1];
|
||||
var prefix = namespaces[uri];
|
||||
|
||||
if (prefix === undefined) {
|
||||
prefix = _namespace_map[uri];
|
||||
if (prefix === undefined) {
|
||||
prefix = "ns" + Object.keys(namespaces).length;
|
||||
}
|
||||
if (prefix !== "xml") {
|
||||
namespaces[uri] = prefix;
|
||||
}
|
||||
}
|
||||
|
||||
if (prefix) {
|
||||
qnames[qname] = sprintf("%s:%s", prefix, tag);
|
||||
}
|
||||
else {
|
||||
qnames[qname] = tag;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (default_namespace) {
|
||||
throw new Error('cannot use non-qualified names with default_namespace option');
|
||||
}
|
||||
|
||||
qnames[qname] = qname;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
elem.iter(null, function(e) {
|
||||
var i;
|
||||
var tag = e.tag;
|
||||
var text = e.text;
|
||||
var items = e.items();
|
||||
|
||||
if (tag instanceof QName && qnames[tag.text] === undefined) {
|
||||
add_qname(tag.text);
|
||||
}
|
||||
else if (typeof(tag) === "string") {
|
||||
add_qname(tag);
|
||||
}
|
||||
else if (tag !== null && tag !== Comment && tag !== CData && tag !== ProcessingInstruction) {
|
||||
throw new Error('Invalid tag type for serialization: '+ tag);
|
||||
}
|
||||
|
||||
if (text instanceof QName && qnames[text.text] === undefined) {
|
||||
add_qname(text.text);
|
||||
}
|
||||
|
||||
items.forEach(function(item) {
|
||||
var key = item[0],
|
||||
value = item[1];
|
||||
if (key instanceof QName) {
|
||||
key = key.text;
|
||||
}
|
||||
|
||||
if (qnames[key] === undefined) {
|
||||
add_qname(key);
|
||||
}
|
||||
|
||||
if (value instanceof QName && qnames[value.text] === undefined) {
|
||||
add_qname(value.text);
|
||||
}
|
||||
});
|
||||
});
|
||||
return [qnames, namespaces];
|
||||
}
|
||||
|
||||
function _serialize_xml(write, elem, encoding, qnames, namespaces, indent, indent_string) {
|
||||
var tag = elem.tag;
|
||||
var text = elem.text;
|
||||
var items;
|
||||
var i;
|
||||
|
||||
var newlines = indent || (indent === 0);
|
||||
write(Array(indent + 1).join(indent_string));
|
||||
|
||||
if (tag === Comment) {
|
||||
write(sprintf("<!--%s-->", _escape_cdata(text, encoding)));
|
||||
}
|
||||
else if (tag === ProcessingInstruction) {
|
||||
write(sprintf("<?%s?>", _escape_cdata(text, encoding)));
|
||||
}
|
||||
else if (tag === CData) {
|
||||
text = text || '';
|
||||
write(sprintf("<![CDATA[%s]]>", text));
|
||||
}
|
||||
else {
|
||||
tag = qnames[tag];
|
||||
if (tag === undefined) {
|
||||
if (text) {
|
||||
write(_escape_text(text, encoding));
|
||||
}
|
||||
elem.iter(function(e) {
|
||||
_serialize_xml(write, e, encoding, qnames, null, newlines ? indent + 1 : false, indent_string);
|
||||
});
|
||||
}
|
||||
else {
|
||||
write("<" + tag);
|
||||
items = elem.items();
|
||||
|
||||
if (items || namespaces) {
|
||||
items.sort(); // lexical order
|
||||
|
||||
items.forEach(function(item) {
|
||||
var k = item[0],
|
||||
v = item[1];
|
||||
|
||||
if (k instanceof QName) {
|
||||
k = k.text;
|
||||
}
|
||||
|
||||
if (v instanceof QName) {
|
||||
v = qnames[v.text];
|
||||
}
|
||||
else {
|
||||
v = _escape_attrib(v, encoding);
|
||||
}
|
||||
write(sprintf(" %s=\"%s\"", qnames[k], v));
|
||||
});
|
||||
|
||||
if (namespaces) {
|
||||
items = utils.items(namespaces);
|
||||
items.sort(function(a, b) { return a[1] < b[1]; });
|
||||
|
||||
items.forEach(function(item) {
|
||||
var k = item[1],
|
||||
v = item[0];
|
||||
|
||||
if (k) {
|
||||
k = ':' + k;
|
||||
}
|
||||
|
||||
write(sprintf(" xmlns%s=\"%s\"", k, _escape_attrib(v, encoding)));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (text || elem.len()) {
|
||||
if (text && text.toString().match(/^\s*$/)) {
|
||||
text = null;
|
||||
}
|
||||
|
||||
write(">");
|
||||
if (!text && newlines) {
|
||||
write("\n");
|
||||
}
|
||||
|
||||
if (text) {
|
||||
write(_escape_text(text, encoding));
|
||||
}
|
||||
elem._children.forEach(function(e) {
|
||||
_serialize_xml(write, e, encoding, qnames, null, newlines ? indent + 1 : false, indent_string);
|
||||
});
|
||||
|
||||
if (!text && indent) {
|
||||
write(Array(indent + 1).join(indent_string));
|
||||
}
|
||||
write("</" + tag + ">");
|
||||
}
|
||||
else {
|
||||
write(" />");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (newlines) {
|
||||
write("\n");
|
||||
}
|
||||
}
|
||||
|
||||
function parse(source, parser) {
|
||||
var tree = new ElementTree();
|
||||
tree.parse(source, parser);
|
||||
return tree;
|
||||
}
|
||||
|
||||
function tostring(element, options) {
|
||||
return new ElementTree(element).write(options);
|
||||
}
|
||||
|
||||
exports.PI = ProcessingInstruction;
|
||||
exports.Comment = Comment;
|
||||
exports.CData = CData;
|
||||
exports.ProcessingInstruction = ProcessingInstruction;
|
||||
exports.SubElement = SubElement;
|
||||
exports.QName = QName;
|
||||
exports.ElementTree = ElementTree;
|
||||
exports.ElementPath = ElementPath;
|
||||
exports.Element = function(tag, attrib) {
|
||||
return new Element(tag, attrib);
|
||||
};
|
||||
|
||||
exports.XML = function(data) {
|
||||
var et = new ElementTree();
|
||||
return et.parse(data);
|
||||
};
|
||||
|
||||
exports.parse = parse;
|
||||
exports.register_namespace = register_namespace;
|
||||
exports.tostring = tostring;
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Copyright 2011 Rackspace
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
var util = require('util');
|
||||
|
||||
var sprintf = require('./sprintf').sprintf;
|
||||
|
||||
function SyntaxError(token, msg) {
|
||||
msg = msg || sprintf('Syntax Error at token %s', token.toString());
|
||||
this.token = token;
|
||||
this.message = msg;
|
||||
Error.call(this, msg);
|
||||
}
|
||||
|
||||
util.inherits(SyntaxError, Error);
|
||||
|
||||
exports.SyntaxError = SyntaxError;
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright 2011 Rackspace
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
/* TODO: support node-expat C++ module optionally */
|
||||
|
||||
var util = require('util');
|
||||
var parsers = require('./parsers/index');
|
||||
|
||||
function get_parser(name) {
|
||||
if (name === 'sax') {
|
||||
return parsers.sax;
|
||||
}
|
||||
else {
|
||||
throw new Error('Invalid parser: ' + name);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
exports.get_parser = get_parser;
|
||||
+1
@@ -0,0 +1 @@
|
||||
exports.sax = require('./sax');
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
var util = require('util');
|
||||
|
||||
var sax = require('sax');
|
||||
|
||||
var TreeBuilder = require('./../treebuilder').TreeBuilder;
|
||||
|
||||
function XMLParser(target) {
|
||||
this.parser = sax.parser(true);
|
||||
|
||||
this.target = (target) ? target : new TreeBuilder();
|
||||
|
||||
this.parser.onopentag = this._handleOpenTag.bind(this);
|
||||
this.parser.ontext = this._handleText.bind(this);
|
||||
this.parser.oncdata = this._handleCdata.bind(this);
|
||||
this.parser.ondoctype = this._handleDoctype.bind(this);
|
||||
this.parser.oncomment = this._handleComment.bind(this);
|
||||
this.parser.onclosetag = this._handleCloseTag.bind(this);
|
||||
this.parser.onerror = this._handleError.bind(this);
|
||||
}
|
||||
|
||||
XMLParser.prototype._handleOpenTag = function(tag) {
|
||||
this.target.start(tag.name, tag.attributes);
|
||||
};
|
||||
|
||||
XMLParser.prototype._handleText = function(text) {
|
||||
this.target.data(text);
|
||||
};
|
||||
|
||||
XMLParser.prototype._handleCdata = function(text) {
|
||||
this.target.data(text);
|
||||
};
|
||||
|
||||
XMLParser.prototype._handleDoctype = function(text) {
|
||||
};
|
||||
|
||||
XMLParser.prototype._handleComment = function(comment) {
|
||||
};
|
||||
|
||||
XMLParser.prototype._handleCloseTag = function(tag) {
|
||||
this.target.end(tag);
|
||||
};
|
||||
|
||||
XMLParser.prototype._handleError = function(err) {
|
||||
throw err;
|
||||
};
|
||||
|
||||
XMLParser.prototype.feed = function(chunk) {
|
||||
this.parser.write(chunk);
|
||||
};
|
||||
|
||||
XMLParser.prototype.close = function() {
|
||||
this.parser.close();
|
||||
return this.target.close();
|
||||
};
|
||||
|
||||
exports.XMLParser = XMLParser;
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright 2011 Rackspace
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
var cache = {};
|
||||
|
||||
|
||||
// Do any others need escaping?
|
||||
var TO_ESCAPE = {
|
||||
'\'': '\\\'',
|
||||
'\n': '\\n'
|
||||
};
|
||||
|
||||
|
||||
function populate(formatter) {
|
||||
var i, type,
|
||||
key = formatter,
|
||||
prev = 0,
|
||||
arg = 1,
|
||||
builder = 'return \'';
|
||||
|
||||
for (i = 0; i < formatter.length; i++) {
|
||||
if (formatter[i] === '%') {
|
||||
type = formatter[i + 1];
|
||||
|
||||
switch (type) {
|
||||
case 's':
|
||||
builder += formatter.slice(prev, i) + '\' + arguments[' + arg + '] + \'';
|
||||
prev = i + 2;
|
||||
arg++;
|
||||
break;
|
||||
case 'j':
|
||||
builder += formatter.slice(prev, i) + '\' + JSON.stringify(arguments[' + arg + ']) + \'';
|
||||
prev = i + 2;
|
||||
arg++;
|
||||
break;
|
||||
case '%':
|
||||
builder += formatter.slice(prev, i + 1);
|
||||
prev = i + 2;
|
||||
i++;
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
} else if (TO_ESCAPE[formatter[i]]) {
|
||||
builder += formatter.slice(prev, i) + TO_ESCAPE[formatter[i]];
|
||||
prev = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
builder += formatter.slice(prev) + '\';';
|
||||
cache[key] = new Function(builder);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* A fast version of sprintf(), which currently only supports the %s and %j.
|
||||
* This caches a formatting function for each format string that is used, so
|
||||
* you should only use this sprintf() will be called many times with a single
|
||||
* format string and a limited number of format strings will ever be used (in
|
||||
* general this means that format strings should be string literals).
|
||||
*
|
||||
* @param {String} formatter A format string.
|
||||
* @param {...String} var_args Values that will be formatted by %s and %j.
|
||||
* @return {String} The formatted output.
|
||||
*/
|
||||
exports.sprintf = function(formatter, var_args) {
|
||||
if (!cache[formatter]) {
|
||||
populate(formatter);
|
||||
}
|
||||
|
||||
return cache[formatter].apply(null, arguments);
|
||||
};
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
function TreeBuilder(element_factory) {
|
||||
this._data = [];
|
||||
this._elem = [];
|
||||
this._last = null;
|
||||
this._tail = null;
|
||||
if (!element_factory) {
|
||||
/* evil circular dep */
|
||||
element_factory = require('./elementtree').Element;
|
||||
}
|
||||
this._factory = element_factory;
|
||||
}
|
||||
|
||||
TreeBuilder.prototype.close = function() {
|
||||
return this._last;
|
||||
};
|
||||
|
||||
TreeBuilder.prototype._flush = function() {
|
||||
if (this._data) {
|
||||
if (this._last !== null) {
|
||||
var text = this._data.join("");
|
||||
if (this._tail) {
|
||||
this._last.tail = text;
|
||||
}
|
||||
else {
|
||||
this._last.text = text;
|
||||
}
|
||||
}
|
||||
this._data = [];
|
||||
}
|
||||
};
|
||||
|
||||
TreeBuilder.prototype.data = function(data) {
|
||||
this._data.push(data);
|
||||
};
|
||||
|
||||
TreeBuilder.prototype.start = function(tag, attrs) {
|
||||
this._flush();
|
||||
var elem = this._factory(tag, attrs);
|
||||
this._last = elem;
|
||||
|
||||
if (this._elem.length) {
|
||||
this._elem[this._elem.length - 1].append(elem);
|
||||
}
|
||||
|
||||
this._elem.push(elem);
|
||||
|
||||
this._tail = null;
|
||||
};
|
||||
|
||||
TreeBuilder.prototype.end = function(tag) {
|
||||
this._flush();
|
||||
this._last = this._elem.pop();
|
||||
if (this._last.tag !== tag) {
|
||||
throw new Error("end tag mismatch");
|
||||
}
|
||||
this._tail = 1;
|
||||
return this._last;
|
||||
};
|
||||
|
||||
exports.TreeBuilder = TreeBuilder;
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Copyright 2011 Rackspace
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {Object} hash.
|
||||
* @param {Array} ignored.
|
||||
*/
|
||||
function items(hash, ignored) {
|
||||
ignored = ignored || null;
|
||||
var k, rv = [];
|
||||
|
||||
function is_ignored(key) {
|
||||
if (!ignored || ignored.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return ignored.indexOf(key);
|
||||
}
|
||||
|
||||
for (k in hash) {
|
||||
if (hash.hasOwnProperty(k) && !(is_ignored(ignored))) {
|
||||
rv.push([k, hash[k]]);
|
||||
}
|
||||
}
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
|
||||
function findall(re, str) {
|
||||
var match, matches = [];
|
||||
|
||||
while ((match = re.exec(str))) {
|
||||
matches.push(match);
|
||||
}
|
||||
|
||||
return matches;
|
||||
}
|
||||
|
||||
function merge(a, b) {
|
||||
var c = {}, attrname;
|
||||
|
||||
for (attrname in a) {
|
||||
if (a.hasOwnProperty(attrname)) {
|
||||
c[attrname] = a[attrname];
|
||||
}
|
||||
}
|
||||
for (attrname in b) {
|
||||
if (b.hasOwnProperty(attrname)) {
|
||||
c[attrname] = b[attrname];
|
||||
}
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
exports.items = items;
|
||||
exports.findall = findall;
|
||||
exports.merge = merge;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
# contributors sorted by whether or not they're me.
|
||||
Isaac Z. Schlueter <i@izs.me>
|
||||
Stein Martin Hustad <stein@hustad.com>
|
||||
Mikeal Rogers <mikeal.rogers@gmail.com>
|
||||
Laurie Harper <laurie@holoweb.net>
|
||||
Jann Horn <jann@Jann-PC.fritz.box>
|
||||
Elijah Insua <tmpvar@gmail.com>
|
||||
Henry Rawas <henryr@schakra.com>
|
||||
Justin Makeig <jmpublic@makeig.com>
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
Copyright 2009, 2010, 2011 Isaac Z. Schlueter.
|
||||
All rights reserved.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
# sax js
|
||||
|
||||
A sax-style parser for XML and HTML.
|
||||
|
||||
Designed with [node](http://nodejs.org/) in mind, but should work fine in
|
||||
the browser or other CommonJS implementations.
|
||||
|
||||
## What This Is
|
||||
|
||||
* A very simple tool to parse through an XML string.
|
||||
* A stepping stone to a streaming HTML parser.
|
||||
* A handy way to deal with RSS and other mostly-ok-but-kinda-broken XML
|
||||
docs.
|
||||
|
||||
## What This Is (probably) Not
|
||||
|
||||
* An HTML Parser - That's a fine goal, but this isn't it. It's just
|
||||
XML.
|
||||
* A DOM Builder - You can use it to build an object model out of XML,
|
||||
but it doesn't do that out of the box.
|
||||
* XSLT - No DOM = no querying.
|
||||
* 100% Compliant with (some other SAX implementation) - Most SAX
|
||||
implementations are in Java and do a lot more than this does.
|
||||
* An XML Validator - It does a little validation when in strict mode, but
|
||||
not much.
|
||||
* A Schema-Aware XSD Thing - Schemas are an exercise in fetishistic
|
||||
masochism.
|
||||
* A DTD-aware Thing - Fetching DTDs is a much bigger job.
|
||||
|
||||
## Regarding `<!DOCTYPE`s and `<!ENTITY`s
|
||||
|
||||
The parser will handle the basic XML entities in text nodes and attribute
|
||||
values: `& < > ' "`. It's possible to define additional
|
||||
entities in XML by putting them in the DTD. This parser doesn't do anything
|
||||
with that. If you want to listen to the `ondoctype` event, and then fetch
|
||||
the doctypes, and read the entities and add them to `parser.ENTITIES`, then
|
||||
be my guest.
|
||||
|
||||
Unknown entities will fail in strict mode, and in loose mode, will pass
|
||||
through unmolested.
|
||||
|
||||
## Usage
|
||||
|
||||
var sax = require("./lib/sax"),
|
||||
strict = true, // set to false for html-mode
|
||||
parser = sax.parser(strict);
|
||||
|
||||
parser.onerror = function (e) {
|
||||
// an error happened.
|
||||
};
|
||||
parser.ontext = function (t) {
|
||||
// got some text. t is the string of text.
|
||||
};
|
||||
parser.onopentag = function (node) {
|
||||
// opened a tag. node has "name" and "attributes"
|
||||
};
|
||||
parser.onattribute = function (attr) {
|
||||
// an attribute. attr has "name" and "value"
|
||||
};
|
||||
parser.onend = function () {
|
||||
// parser stream is done, and ready to have more stuff written to it.
|
||||
};
|
||||
|
||||
parser.write('<xml>Hello, <who name="world">world</who>!</xml>').close();
|
||||
|
||||
// stream usage
|
||||
// takes the same options as the parser
|
||||
var saxStream = require("sax").createStream(strict, options)
|
||||
saxStream.on("error", function (e) {
|
||||
// unhandled errors will throw, since this is a proper node
|
||||
// event emitter.
|
||||
console.error("error!", e)
|
||||
// clear the error
|
||||
this._parser.error = null
|
||||
this._parser.resume()
|
||||
})
|
||||
saxStream.on("opentag", function (node) {
|
||||
// same object as above
|
||||
})
|
||||
// pipe is supported, and it's readable/writable
|
||||
// same chunks coming in also go out.
|
||||
fs.createReadStream("file.xml")
|
||||
.pipe(saxStream)
|
||||
.pipe(fs.createReadStream("file-copy.xml"))
|
||||
|
||||
|
||||
|
||||
## Arguments
|
||||
|
||||
Pass the following arguments to the parser function. All are optional.
|
||||
|
||||
`strict` - Boolean. Whether or not to be a jerk. Default: `false`.
|
||||
|
||||
`opt` - Object bag of settings regarding string formatting. All default to `false`.
|
||||
|
||||
Settings supported:
|
||||
|
||||
* `trim` - Boolean. Whether or not to trim text and comment nodes.
|
||||
* `normalize` - Boolean. If true, then turn any whitespace into a single
|
||||
space.
|
||||
* `lowercasetags` - Boolean. If true, then lowercase tags in loose mode,
|
||||
rather than uppercasing them.
|
||||
* `xmlns` - Boolean. If true, then namespaces are supported.
|
||||
|
||||
## Methods
|
||||
|
||||
`write` - Write bytes onto the stream. You don't have to do this all at
|
||||
once. You can keep writing as much as you want.
|
||||
|
||||
`close` - Close the stream. Once closed, no more data may be written until
|
||||
it is done processing the buffer, which is signaled by the `end` event.
|
||||
|
||||
`resume` - To gracefully handle errors, assign a listener to the `error`
|
||||
event. Then, when the error is taken care of, you can call `resume` to
|
||||
continue parsing. Otherwise, the parser will not continue while in an error
|
||||
state.
|
||||
|
||||
## Members
|
||||
|
||||
At all times, the parser object will have the following members:
|
||||
|
||||
`line`, `column`, `position` - Indications of the position in the XML
|
||||
document where the parser currently is looking.
|
||||
|
||||
`startTagPosition` - Indicates the position where the current tag starts.
|
||||
|
||||
`closed` - Boolean indicating whether or not the parser can be written to.
|
||||
If it's `true`, then wait for the `ready` event to write again.
|
||||
|
||||
`strict` - Boolean indicating whether or not the parser is a jerk.
|
||||
|
||||
`opt` - Any options passed into the constructor.
|
||||
|
||||
`tag` - The current tag being dealt with.
|
||||
|
||||
And a bunch of other stuff that you probably shouldn't touch.
|
||||
|
||||
## Events
|
||||
|
||||
All events emit with a single argument. To listen to an event, assign a
|
||||
function to `on<eventname>`. Functions get executed in the this-context of
|
||||
the parser object. The list of supported events are also in the exported
|
||||
`EVENTS` array.
|
||||
|
||||
When using the stream interface, assign handlers using the EventEmitter
|
||||
`on` function in the normal fashion.
|
||||
|
||||
`error` - Indication that something bad happened. The error will be hanging
|
||||
out on `parser.error`, and must be deleted before parsing can continue. By
|
||||
listening to this event, you can keep an eye on that kind of stuff. Note:
|
||||
this happens *much* more in strict mode. Argument: instance of `Error`.
|
||||
|
||||
`text` - Text node. Argument: string of text.
|
||||
|
||||
`doctype` - The `<!DOCTYPE` declaration. Argument: doctype string.
|
||||
|
||||
`processinginstruction` - Stuff like `<?xml foo="blerg" ?>`. Argument:
|
||||
object with `name` and `body` members. Attributes are not parsed, as
|
||||
processing instructions have implementation dependent semantics.
|
||||
|
||||
`sgmldeclaration` - Random SGML declarations. Stuff like `<!ENTITY p>`
|
||||
would trigger this kind of event. This is a weird thing to support, so it
|
||||
might go away at some point. SAX isn't intended to be used to parse SGML,
|
||||
after all.
|
||||
|
||||
`opentag` - An opening tag. Argument: object with `name` and `attributes`.
|
||||
In non-strict mode, tag names are uppercased, unless the `lowercasetags`
|
||||
option is set. If the `xmlns` option is set, then it will contain
|
||||
namespace binding information on the `ns` member, and will have a
|
||||
`local`, `prefix`, and `uri` member.
|
||||
|
||||
`closetag` - A closing tag. In loose mode, tags are auto-closed if their
|
||||
parent closes. In strict mode, well-formedness is enforced. Note that
|
||||
self-closing tags will have `closeTag` emitted immediately after `openTag`.
|
||||
Argument: tag name.
|
||||
|
||||
`attribute` - An attribute node. Argument: object with `name` and `value`,
|
||||
and also namespace information if the `xmlns` option flag is set.
|
||||
|
||||
`comment` - A comment node. Argument: the string of the comment.
|
||||
|
||||
`opencdata` - The opening tag of a `<![CDATA[` block.
|
||||
|
||||
`cdata` - The text of a `<![CDATA[` block. Since `<![CDATA[` blocks can get
|
||||
quite large, this event may fire multiple times for a single block, if it
|
||||
is broken up into multiple `write()`s. Argument: the string of random
|
||||
character data.
|
||||
|
||||
`closecdata` - The closing tag (`]]>`) of a `<![CDATA[` block.
|
||||
|
||||
`opennamespace` - If the `xmlns` option is set, then this event will
|
||||
signal the start of a new namespace binding.
|
||||
|
||||
`closenamespace` - If the `xmlns` option is set, then this event will
|
||||
signal the end of a namespace binding.
|
||||
|
||||
`end` - Indication that the closed stream has ended.
|
||||
|
||||
`ready` - Indication that the stream has reset, and is ready to be written
|
||||
to.
|
||||
|
||||
`noscript` - In non-strict mode, `<script>` tags trigger a `"script"`
|
||||
event, and their contents are not checked for special xml characters.
|
||||
If you pass `noscript: true`, then this behavior is suppressed.
|
||||
|
||||
## Reporting Problems
|
||||
|
||||
It's best to write a failing test if you find an issue. I will always
|
||||
accept pull requests with failing tests if they demonstrate intended
|
||||
behavior, but it is very hard to figure out what issue you're describing
|
||||
without a test. Writing a test is also the best way for you yourself
|
||||
to figure out if you really understand the issue you think you have with
|
||||
sax-js.
|
||||
+1006
File diff suppressed because it is too large
Load Diff
+89
@@ -0,0 +1,89 @@
|
||||
{
|
||||
"name": "sax",
|
||||
"description": "An evented streaming XML parser in JavaScript",
|
||||
"author": {
|
||||
"name": "Isaac Z. Schlueter",
|
||||
"email": "i@izs.me",
|
||||
"url": "http://blog.izs.me/"
|
||||
},
|
||||
"version": "0.3.5",
|
||||
"main": "lib/sax.js",
|
||||
"license": {
|
||||
"type": "MIT",
|
||||
"url": "https://raw.github.com/isaacs/sax-js/master/LICENSE"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "node test/index.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/isaacs/sax-js.git"
|
||||
},
|
||||
"_npmUser": {
|
||||
"name": "isaacs",
|
||||
"email": "i@izs.me"
|
||||
},
|
||||
"_id": "sax@0.3.5",
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Isaac Z. Schlueter",
|
||||
"email": "i@izs.me"
|
||||
},
|
||||
{
|
||||
"name": "Stein Martin Hustad",
|
||||
"email": "stein@hustad.com"
|
||||
},
|
||||
{
|
||||
"name": "Mikeal Rogers",
|
||||
"email": "mikeal.rogers@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "Laurie Harper",
|
||||
"email": "laurie@holoweb.net"
|
||||
},
|
||||
{
|
||||
"name": "Jann Horn",
|
||||
"email": "jann@Jann-PC.fritz.box"
|
||||
},
|
||||
{
|
||||
"name": "Elijah Insua",
|
||||
"email": "tmpvar@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "Henry Rawas",
|
||||
"email": "henryr@schakra.com"
|
||||
},
|
||||
{
|
||||
"name": "Justin Makeig",
|
||||
"email": "jmpublic@makeig.com"
|
||||
}
|
||||
],
|
||||
"dependencies": {},
|
||||
"devDependencies": {},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"_engineSupported": true,
|
||||
"_npmVersion": "1.1.0-beta-7",
|
||||
"_nodeVersion": "v0.6.7-pre",
|
||||
"_defaultsLoaded": true,
|
||||
"dist": {
|
||||
"shasum": "88fcfc1f73c0c8bbd5b7c776b6d3f3501eed073d",
|
||||
"tarball": "http://registry.npmjs.org/sax/-/sax-0.3.5.tgz"
|
||||
},
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "isaacs",
|
||||
"email": "i@izs.me"
|
||||
}
|
||||
],
|
||||
"directories": {},
|
||||
"_shasum": "88fcfc1f73c0c8bbd5b7c776b6d3f3501eed073d",
|
||||
"_resolved": "https://registry.npmjs.org/sax/-/sax-0.3.5.tgz",
|
||||
"_from": "sax@0.3.5",
|
||||
"bugs": {
|
||||
"url": "https://github.com/isaacs/sax-js/issues"
|
||||
},
|
||||
"readme": "ERROR: No README data found!",
|
||||
"homepage": "https://github.com/isaacs/sax-js#readme"
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"author": {
|
||||
"name": "Rackspace US, Inc."
|
||||
},
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Paul Querna",
|
||||
"email": "paul.querna@rackspace.com"
|
||||
},
|
||||
{
|
||||
"name": "Tomaz Muraus",
|
||||
"email": "tomaz.muraus@rackspace.com"
|
||||
}
|
||||
],
|
||||
"name": "elementtree",
|
||||
"description": "XML Serialization and Parsing module based on Python's ElementTree.",
|
||||
"version": "0.1.6",
|
||||
"keywords": [
|
||||
"xml",
|
||||
"sax",
|
||||
"parser",
|
||||
"seralization",
|
||||
"elementtree"
|
||||
],
|
||||
"homepage": "https://github.com/racker/node-elementtree",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/racker/node-elementtree.git"
|
||||
},
|
||||
"main": "lib/elementtree.js",
|
||||
"directories": {
|
||||
"lib": "lib"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "make test"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"sax": "0.3.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"whiskey": "0.8.x"
|
||||
},
|
||||
"licenses": [
|
||||
{
|
||||
"type": "Apache",
|
||||
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
|
||||
}
|
||||
],
|
||||
"bugs": {
|
||||
"url": "https://github.com/racker/node-elementtree/issues"
|
||||
},
|
||||
"_id": "elementtree@0.1.6",
|
||||
"dist": {
|
||||
"shasum": "2ac4c46ea30516c8c4cbdb5e3ac7418e592de20c",
|
||||
"tarball": "http://registry.npmjs.org/elementtree/-/elementtree-0.1.6.tgz"
|
||||
},
|
||||
"_from": "elementtree@>=0.1.6 <0.2.0",
|
||||
"_npmVersion": "1.3.24",
|
||||
"_npmUser": {
|
||||
"name": "rphillips",
|
||||
"email": "ryan@trolocsis.com"
|
||||
},
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "rphillips",
|
||||
"email": "ryan@trolocsis.com"
|
||||
}
|
||||
],
|
||||
"_shasum": "2ac4c46ea30516c8c4cbdb5e3ac7418e592de20c",
|
||||
"_resolved": "https://registry.npmjs.org/elementtree/-/elementtree-0.1.6.tgz",
|
||||
"readme": "ERROR: No README data found!"
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
node_modules
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
language: node_js
|
||||
language: node_js
|
||||
node_js:
|
||||
- '0.8'
|
||||
- '0.10'
|
||||
- '0.12'
|
||||
- 'iojs'
|
||||
before_install:
|
||||
- npm install -g npm@latest
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
The ISC License
|
||||
|
||||
Copyright (c) Isaac Z. Schlueter and Contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
|
||||
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
If you want to write an option parser, and have it be good, there are
|
||||
two ways to do it. The Right Way, and the Wrong Way.
|
||||
|
||||
The Wrong Way is to sit down and write an option parser. We've all done
|
||||
that.
|
||||
|
||||
The Right Way is to write some complex configurable program with so many
|
||||
options that you hit the limit of your frustration just trying to
|
||||
manage them all, and defer it with duct-tape solutions until you see
|
||||
exactly to the core of the problem, and finally snap and write an
|
||||
awesome option parser.
|
||||
|
||||
If you want to write an option parser, don't write an option parser.
|
||||
Write a package manager, or a source control system, or a service
|
||||
restarter, or an operating system. You probably won't end up with a
|
||||
good one of those, but if you don't give up, and you are relentless and
|
||||
diligent enough in your procrastination, you may just end up with a very
|
||||
nice option parser.
|
||||
|
||||
## USAGE
|
||||
|
||||
// my-program.js
|
||||
var nopt = require("nopt")
|
||||
, Stream = require("stream").Stream
|
||||
, path = require("path")
|
||||
, knownOpts = { "foo" : [String, null]
|
||||
, "bar" : [Stream, Number]
|
||||
, "baz" : path
|
||||
, "bloo" : [ "big", "medium", "small" ]
|
||||
, "flag" : Boolean
|
||||
, "pick" : Boolean
|
||||
, "many1" : [String, Array]
|
||||
, "many2" : [path]
|
||||
}
|
||||
, shortHands = { "foofoo" : ["--foo", "Mr. Foo"]
|
||||
, "b7" : ["--bar", "7"]
|
||||
, "m" : ["--bloo", "medium"]
|
||||
, "p" : ["--pick"]
|
||||
, "f" : ["--flag"]
|
||||
}
|
||||
// everything is optional.
|
||||
// knownOpts and shorthands default to {}
|
||||
// arg list defaults to process.argv
|
||||
// slice defaults to 2
|
||||
, parsed = nopt(knownOpts, shortHands, process.argv, 2)
|
||||
console.log(parsed)
|
||||
|
||||
This would give you support for any of the following:
|
||||
|
||||
```bash
|
||||
$ node my-program.js --foo "blerp" --no-flag
|
||||
{ "foo" : "blerp", "flag" : false }
|
||||
|
||||
$ node my-program.js ---bar 7 --foo "Mr. Hand" --flag
|
||||
{ bar: 7, foo: "Mr. Hand", flag: true }
|
||||
|
||||
$ node my-program.js --foo "blerp" -f -----p
|
||||
{ foo: "blerp", flag: true, pick: true }
|
||||
|
||||
$ node my-program.js -fp --foofoo
|
||||
{ foo: "Mr. Foo", flag: true, pick: true }
|
||||
|
||||
$ node my-program.js --foofoo -- -fp # -- stops the flag parsing.
|
||||
{ foo: "Mr. Foo", argv: { remain: ["-fp"] } }
|
||||
|
||||
$ node my-program.js --blatzk -fp # unknown opts are ok.
|
||||
{ blatzk: true, flag: true, pick: true }
|
||||
|
||||
$ node my-program.js --blatzk=1000 -fp # but you need to use = if they have a value
|
||||
{ blatzk: 1000, flag: true, pick: true }
|
||||
|
||||
$ node my-program.js --no-blatzk -fp # unless they start with "no-"
|
||||
{ blatzk: false, flag: true, pick: true }
|
||||
|
||||
$ node my-program.js --baz b/a/z # known paths are resolved.
|
||||
{ baz: "/Users/isaacs/b/a/z" }
|
||||
|
||||
# if Array is one of the types, then it can take many
|
||||
# values, and will always be an array. The other types provided
|
||||
# specify what types are allowed in the list.
|
||||
|
||||
$ node my-program.js --many1 5 --many1 null --many1 foo
|
||||
{ many1: ["5", "null", "foo"] }
|
||||
|
||||
$ node my-program.js --many2 foo --many2 bar
|
||||
{ many2: ["/path/to/foo", "path/to/bar"] }
|
||||
```
|
||||
|
||||
Read the tests at the bottom of `lib/nopt.js` for more examples of
|
||||
what this puppy can do.
|
||||
|
||||
## Types
|
||||
|
||||
The following types are supported, and defined on `nopt.typeDefs`
|
||||
|
||||
* String: A normal string. No parsing is done.
|
||||
* path: A file system path. Gets resolved against cwd if not absolute.
|
||||
* url: A url. If it doesn't parse, it isn't accepted.
|
||||
* Number: Must be numeric.
|
||||
* Date: Must parse as a date. If it does, and `Date` is one of the options,
|
||||
then it will return a Date object, not a string.
|
||||
* Boolean: Must be either `true` or `false`. If an option is a boolean,
|
||||
then it does not need a value, and its presence will imply `true` as
|
||||
the value. To negate boolean flags, do `--no-whatever` or `--whatever
|
||||
false`
|
||||
* NaN: Means that the option is strictly not allowed. Any value will
|
||||
fail.
|
||||
* Stream: An object matching the "Stream" class in node. Valuable
|
||||
for use when validating programmatically. (npm uses this to let you
|
||||
supply any WriteStream on the `outfd` and `logfd` config options.)
|
||||
* Array: If `Array` is specified as one of the types, then the value
|
||||
will be parsed as a list of options. This means that multiple values
|
||||
can be specified, and that the value will always be an array.
|
||||
|
||||
If a type is an array of values not on this list, then those are
|
||||
considered valid values. For instance, in the example above, the
|
||||
`--bloo` option can only be one of `"big"`, `"medium"`, or `"small"`,
|
||||
and any other value will be rejected.
|
||||
|
||||
When parsing unknown fields, `"true"`, `"false"`, and `"null"` will be
|
||||
interpreted as their JavaScript equivalents.
|
||||
|
||||
You can also mix types and values, or multiple types, in a list. For
|
||||
instance `{ blah: [Number, null] }` would allow a value to be set to
|
||||
either a Number or null. When types are ordered, this implies a
|
||||
preference, and the first type that can be used to properly interpret
|
||||
the value will be used.
|
||||
|
||||
To define a new type, add it to `nopt.typeDefs`. Each item in that
|
||||
hash is an object with a `type` member and a `validate` method. The
|
||||
`type` member is an object that matches what goes in the type list. The
|
||||
`validate` method is a function that gets called with `validate(data,
|
||||
key, val)`. Validate methods should assign `data[key]` to the valid
|
||||
value of `val` if it can be handled properly, or return boolean
|
||||
`false` if it cannot.
|
||||
|
||||
You can also call `nopt.clean(data, types, typeDefs)` to clean up a
|
||||
config object and remove its invalid properties.
|
||||
|
||||
## Error Handling
|
||||
|
||||
By default, nopt outputs a warning to standard error when invalid values for
|
||||
known options are found. You can change this behavior by assigning a method
|
||||
to `nopt.invalidHandler`. This method will be called with
|
||||
the offending `nopt.invalidHandler(key, val, types)`.
|
||||
|
||||
If no `nopt.invalidHandler` is assigned, then it will console.error
|
||||
its whining. If it is assigned to boolean `false` then the warning is
|
||||
suppressed.
|
||||
|
||||
## Abbreviations
|
||||
|
||||
Yes, they are supported. If you define options like this:
|
||||
|
||||
```javascript
|
||||
{ "foolhardyelephants" : Boolean
|
||||
, "pileofmonkeys" : Boolean }
|
||||
```
|
||||
|
||||
Then this will work:
|
||||
|
||||
```bash
|
||||
node program.js --foolhar --pil
|
||||
node program.js --no-f --pileofmon
|
||||
# etc.
|
||||
```
|
||||
|
||||
## Shorthands
|
||||
|
||||
Shorthands are a hash of shorter option names to a snippet of args that
|
||||
they expand to.
|
||||
|
||||
If multiple one-character shorthands are all combined, and the
|
||||
combination does not unambiguously match any other option or shorthand,
|
||||
then they will be broken up into their constituent parts. For example:
|
||||
|
||||
```json
|
||||
{ "s" : ["--loglevel", "silent"]
|
||||
, "g" : "--global"
|
||||
, "f" : "--force"
|
||||
, "p" : "--parseable"
|
||||
, "l" : "--long"
|
||||
}
|
||||
```
|
||||
|
||||
```bash
|
||||
npm ls -sgflp
|
||||
# just like doing this:
|
||||
npm ls --loglevel silent --global --force --long --parseable
|
||||
```
|
||||
|
||||
## The Rest of the args
|
||||
|
||||
The config object returned by nopt is given a special member called
|
||||
`argv`, which is an object with the following fields:
|
||||
|
||||
* `remain`: The remaining args after all the parsing has occurred.
|
||||
* `original`: The args as they originally appeared.
|
||||
* `cooked`: The args after flags and shorthands are expanded.
|
||||
|
||||
## Slicing
|
||||
|
||||
Node programs are called with more or less the exact argv as it appears
|
||||
in C land, after the v8 and node-specific options have been plucked off.
|
||||
As such, `argv[0]` is always `node` and `argv[1]` is always the
|
||||
JavaScript program being run.
|
||||
|
||||
That's usually not very useful to you. So they're sliced off by
|
||||
default. If you want them, then you can pass in `0` as the last
|
||||
argument, or any other number that you'd like to slice off the start of
|
||||
the list.
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env node
|
||||
var nopt = require("../lib/nopt")
|
||||
, path = require("path")
|
||||
, types = { num: Number
|
||||
, bool: Boolean
|
||||
, help: Boolean
|
||||
, list: Array
|
||||
, "num-list": [Number, Array]
|
||||
, "str-list": [String, Array]
|
||||
, "bool-list": [Boolean, Array]
|
||||
, str: String
|
||||
, clear: Boolean
|
||||
, config: Boolean
|
||||
, length: Number
|
||||
, file: path
|
||||
}
|
||||
, shorthands = { s: [ "--str", "astring" ]
|
||||
, b: [ "--bool" ]
|
||||
, nb: [ "--no-bool" ]
|
||||
, tft: [ "--bool-list", "--no-bool-list", "--bool-list", "true" ]
|
||||
, "?": ["--help"]
|
||||
, h: ["--help"]
|
||||
, H: ["--help"]
|
||||
, n: [ "--num", "125" ]
|
||||
, c: ["--config"]
|
||||
, l: ["--length"]
|
||||
, f: ["--file"]
|
||||
}
|
||||
, parsed = nopt( types
|
||||
, shorthands
|
||||
, process.argv
|
||||
, 2 )
|
||||
|
||||
console.log("parsed", parsed)
|
||||
|
||||
if (parsed.help) {
|
||||
console.log("")
|
||||
console.log("nopt cli tester")
|
||||
console.log("")
|
||||
console.log("types")
|
||||
console.log(Object.keys(types).map(function M (t) {
|
||||
var type = types[t]
|
||||
if (Array.isArray(type)) {
|
||||
return [t, type.map(function (type) { return type.name })]
|
||||
}
|
||||
return [t, type && type.name]
|
||||
}).reduce(function (s, i) {
|
||||
s[i[0]] = i[1]
|
||||
return s
|
||||
}, {}))
|
||||
console.log("")
|
||||
console.log("shorthands")
|
||||
console.log(shorthands)
|
||||
}
|
||||
+414
@@ -0,0 +1,414 @@
|
||||
// info about each config option.
|
||||
|
||||
var debug = process.env.DEBUG_NOPT || process.env.NOPT_DEBUG
|
||||
? function () { console.error.apply(console, arguments) }
|
||||
: function () {}
|
||||
|
||||
var url = require("url")
|
||||
, path = require("path")
|
||||
, Stream = require("stream").Stream
|
||||
, abbrev = require("abbrev")
|
||||
|
||||
module.exports = exports = nopt
|
||||
exports.clean = clean
|
||||
|
||||
exports.typeDefs =
|
||||
{ String : { type: String, validate: validateString }
|
||||
, Boolean : { type: Boolean, validate: validateBoolean }
|
||||
, url : { type: url, validate: validateUrl }
|
||||
, Number : { type: Number, validate: validateNumber }
|
||||
, path : { type: path, validate: validatePath }
|
||||
, Stream : { type: Stream, validate: validateStream }
|
||||
, Date : { type: Date, validate: validateDate }
|
||||
}
|
||||
|
||||
function nopt (types, shorthands, args, slice) {
|
||||
args = args || process.argv
|
||||
types = types || {}
|
||||
shorthands = shorthands || {}
|
||||
if (typeof slice !== "number") slice = 2
|
||||
|
||||
debug(types, shorthands, args, slice)
|
||||
|
||||
args = args.slice(slice)
|
||||
var data = {}
|
||||
, key
|
||||
, remain = []
|
||||
, cooked = args
|
||||
, original = args.slice(0)
|
||||
|
||||
parse(args, data, remain, types, shorthands)
|
||||
// now data is full
|
||||
clean(data, types, exports.typeDefs)
|
||||
data.argv = {remain:remain,cooked:cooked,original:original}
|
||||
Object.defineProperty(data.argv, 'toString', { value: function () {
|
||||
return this.original.map(JSON.stringify).join(" ")
|
||||
}, enumerable: false })
|
||||
return data
|
||||
}
|
||||
|
||||
function clean (data, types, typeDefs) {
|
||||
typeDefs = typeDefs || exports.typeDefs
|
||||
var remove = {}
|
||||
, typeDefault = [false, true, null, String, Array]
|
||||
|
||||
Object.keys(data).forEach(function (k) {
|
||||
if (k === "argv") return
|
||||
var val = data[k]
|
||||
, isArray = Array.isArray(val)
|
||||
, type = types[k]
|
||||
if (!isArray) val = [val]
|
||||
if (!type) type = typeDefault
|
||||
if (type === Array) type = typeDefault.concat(Array)
|
||||
if (!Array.isArray(type)) type = [type]
|
||||
|
||||
debug("val=%j", val)
|
||||
debug("types=", type)
|
||||
val = val.map(function (val) {
|
||||
// if it's an unknown value, then parse false/true/null/numbers/dates
|
||||
if (typeof val === "string") {
|
||||
debug("string %j", val)
|
||||
val = val.trim()
|
||||
if ((val === "null" && ~type.indexOf(null))
|
||||
|| (val === "true" &&
|
||||
(~type.indexOf(true) || ~type.indexOf(Boolean)))
|
||||
|| (val === "false" &&
|
||||
(~type.indexOf(false) || ~type.indexOf(Boolean)))) {
|
||||
val = JSON.parse(val)
|
||||
debug("jsonable %j", val)
|
||||
} else if (~type.indexOf(Number) && !isNaN(val)) {
|
||||
debug("convert to number", val)
|
||||
val = +val
|
||||
} else if (~type.indexOf(Date) && !isNaN(Date.parse(val))) {
|
||||
debug("convert to date", val)
|
||||
val = new Date(val)
|
||||
}
|
||||
}
|
||||
|
||||
if (!types.hasOwnProperty(k)) {
|
||||
return val
|
||||
}
|
||||
|
||||
// allow `--no-blah` to set 'blah' to null if null is allowed
|
||||
if (val === false && ~type.indexOf(null) &&
|
||||
!(~type.indexOf(false) || ~type.indexOf(Boolean))) {
|
||||
val = null
|
||||
}
|
||||
|
||||
var d = {}
|
||||
d[k] = val
|
||||
debug("prevalidated val", d, val, types[k])
|
||||
if (!validate(d, k, val, types[k], typeDefs)) {
|
||||
if (exports.invalidHandler) {
|
||||
exports.invalidHandler(k, val, types[k], data)
|
||||
} else if (exports.invalidHandler !== false) {
|
||||
debug("invalid: "+k+"="+val, types[k])
|
||||
}
|
||||
return remove
|
||||
}
|
||||
debug("validated val", d, val, types[k])
|
||||
return d[k]
|
||||
}).filter(function (val) { return val !== remove })
|
||||
|
||||
if (!val.length) delete data[k]
|
||||
else if (isArray) {
|
||||
debug(isArray, data[k], val)
|
||||
data[k] = val
|
||||
} else data[k] = val[0]
|
||||
|
||||
debug("k=%s val=%j", k, val, data[k])
|
||||
})
|
||||
}
|
||||
|
||||
function validateString (data, k, val) {
|
||||
data[k] = String(val)
|
||||
}
|
||||
|
||||
function validatePath (data, k, val) {
|
||||
if (val === true) return false
|
||||
if (val === null) return true
|
||||
|
||||
val = String(val)
|
||||
var homePattern = process.platform === 'win32' ? /^~(\/|\\)/ : /^~\//
|
||||
if (val.match(homePattern) && process.env.HOME) {
|
||||
val = path.resolve(process.env.HOME, val.substr(2))
|
||||
}
|
||||
data[k] = path.resolve(String(val))
|
||||
return true
|
||||
}
|
||||
|
||||
function validateNumber (data, k, val) {
|
||||
debug("validate Number %j %j %j", k, val, isNaN(val))
|
||||
if (isNaN(val)) return false
|
||||
data[k] = +val
|
||||
}
|
||||
|
||||
function validateDate (data, k, val) {
|
||||
debug("validate Date %j %j %j", k, val, Date.parse(val))
|
||||
var s = Date.parse(val)
|
||||
if (isNaN(s)) return false
|
||||
data[k] = new Date(val)
|
||||
}
|
||||
|
||||
function validateBoolean (data, k, val) {
|
||||
if (val instanceof Boolean) val = val.valueOf()
|
||||
else if (typeof val === "string") {
|
||||
if (!isNaN(val)) val = !!(+val)
|
||||
else if (val === "null" || val === "false") val = false
|
||||
else val = true
|
||||
} else val = !!val
|
||||
data[k] = val
|
||||
}
|
||||
|
||||
function validateUrl (data, k, val) {
|
||||
val = url.parse(String(val))
|
||||
if (!val.host) return false
|
||||
data[k] = val.href
|
||||
}
|
||||
|
||||
function validateStream (data, k, val) {
|
||||
if (!(val instanceof Stream)) return false
|
||||
data[k] = val
|
||||
}
|
||||
|
||||
function validate (data, k, val, type, typeDefs) {
|
||||
// arrays are lists of types.
|
||||
if (Array.isArray(type)) {
|
||||
for (var i = 0, l = type.length; i < l; i ++) {
|
||||
if (type[i] === Array) continue
|
||||
if (validate(data, k, val, type[i], typeDefs)) return true
|
||||
}
|
||||
delete data[k]
|
||||
return false
|
||||
}
|
||||
|
||||
// an array of anything?
|
||||
if (type === Array) return true
|
||||
|
||||
// NaN is poisonous. Means that something is not allowed.
|
||||
if (type !== type) {
|
||||
debug("Poison NaN", k, val, type)
|
||||
delete data[k]
|
||||
return false
|
||||
}
|
||||
|
||||
// explicit list of values
|
||||
if (val === type) {
|
||||
debug("Explicitly allowed %j", val)
|
||||
// if (isArray) (data[k] = data[k] || []).push(val)
|
||||
// else data[k] = val
|
||||
data[k] = val
|
||||
return true
|
||||
}
|
||||
|
||||
// now go through the list of typeDefs, validate against each one.
|
||||
var ok = false
|
||||
, types = Object.keys(typeDefs)
|
||||
for (var i = 0, l = types.length; i < l; i ++) {
|
||||
debug("test type %j %j %j", k, val, types[i])
|
||||
var t = typeDefs[types[i]]
|
||||
if (t && type === t.type) {
|
||||
var d = {}
|
||||
ok = false !== t.validate(d, k, val)
|
||||
val = d[k]
|
||||
if (ok) {
|
||||
// if (isArray) (data[k] = data[k] || []).push(val)
|
||||
// else data[k] = val
|
||||
data[k] = val
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
debug("OK? %j (%j %j %j)", ok, k, val, types[i])
|
||||
|
||||
if (!ok) delete data[k]
|
||||
return ok
|
||||
}
|
||||
|
||||
function parse (args, data, remain, types, shorthands) {
|
||||
debug("parse", args, data, remain)
|
||||
|
||||
var key = null
|
||||
, abbrevs = abbrev(Object.keys(types))
|
||||
, shortAbbr = abbrev(Object.keys(shorthands))
|
||||
|
||||
for (var i = 0; i < args.length; i ++) {
|
||||
var arg = args[i]
|
||||
debug("arg", arg)
|
||||
|
||||
if (arg.match(/^-{2,}$/)) {
|
||||
// done with keys.
|
||||
// the rest are args.
|
||||
remain.push.apply(remain, args.slice(i + 1))
|
||||
args[i] = "--"
|
||||
break
|
||||
}
|
||||
var hadEq = false
|
||||
if (arg.charAt(0) === "-" && arg.length > 1) {
|
||||
if (arg.indexOf("=") !== -1) {
|
||||
hadEq = true
|
||||
var v = arg.split("=")
|
||||
arg = v.shift()
|
||||
v = v.join("=")
|
||||
args.splice.apply(args, [i, 1].concat([arg, v]))
|
||||
}
|
||||
|
||||
// see if it's a shorthand
|
||||
// if so, splice and back up to re-parse it.
|
||||
var shRes = resolveShort(arg, shorthands, shortAbbr, abbrevs)
|
||||
debug("arg=%j shRes=%j", arg, shRes)
|
||||
if (shRes) {
|
||||
debug(arg, shRes)
|
||||
args.splice.apply(args, [i, 1].concat(shRes))
|
||||
if (arg !== shRes[0]) {
|
||||
i --
|
||||
continue
|
||||
}
|
||||
}
|
||||
arg = arg.replace(/^-+/, "")
|
||||
var no = null
|
||||
while (arg.toLowerCase().indexOf("no-") === 0) {
|
||||
no = !no
|
||||
arg = arg.substr(3)
|
||||
}
|
||||
|
||||
if (abbrevs[arg]) arg = abbrevs[arg]
|
||||
|
||||
var isArray = types[arg] === Array ||
|
||||
Array.isArray(types[arg]) && types[arg].indexOf(Array) !== -1
|
||||
|
||||
// allow unknown things to be arrays if specified multiple times.
|
||||
if (!types.hasOwnProperty(arg) && data.hasOwnProperty(arg)) {
|
||||
if (!Array.isArray(data[arg]))
|
||||
data[arg] = [data[arg]]
|
||||
isArray = true
|
||||
}
|
||||
|
||||
var val
|
||||
, la = args[i + 1]
|
||||
|
||||
var isBool = typeof no === 'boolean' ||
|
||||
types[arg] === Boolean ||
|
||||
Array.isArray(types[arg]) && types[arg].indexOf(Boolean) !== -1 ||
|
||||
(typeof types[arg] === 'undefined' && !hadEq) ||
|
||||
(la === "false" &&
|
||||
(types[arg] === null ||
|
||||
Array.isArray(types[arg]) && ~types[arg].indexOf(null)))
|
||||
|
||||
if (isBool) {
|
||||
// just set and move along
|
||||
val = !no
|
||||
// however, also support --bool true or --bool false
|
||||
if (la === "true" || la === "false") {
|
||||
val = JSON.parse(la)
|
||||
la = null
|
||||
if (no) val = !val
|
||||
i ++
|
||||
}
|
||||
|
||||
// also support "foo":[Boolean, "bar"] and "--foo bar"
|
||||
if (Array.isArray(types[arg]) && la) {
|
||||
if (~types[arg].indexOf(la)) {
|
||||
// an explicit type
|
||||
val = la
|
||||
i ++
|
||||
} else if ( la === "null" && ~types[arg].indexOf(null) ) {
|
||||
// null allowed
|
||||
val = null
|
||||
i ++
|
||||
} else if ( !la.match(/^-{2,}[^-]/) &&
|
||||
!isNaN(la) &&
|
||||
~types[arg].indexOf(Number) ) {
|
||||
// number
|
||||
val = +la
|
||||
i ++
|
||||
} else if ( !la.match(/^-[^-]/) && ~types[arg].indexOf(String) ) {
|
||||
// string
|
||||
val = la
|
||||
i ++
|
||||
}
|
||||
}
|
||||
|
||||
if (isArray) (data[arg] = data[arg] || []).push(val)
|
||||
else data[arg] = val
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if (types[arg] === String && la === undefined)
|
||||
la = ""
|
||||
|
||||
if (la && la.match(/^-{2,}$/)) {
|
||||
la = undefined
|
||||
i --
|
||||
}
|
||||
|
||||
val = la === undefined ? true : la
|
||||
if (isArray) (data[arg] = data[arg] || []).push(val)
|
||||
else data[arg] = val
|
||||
|
||||
i ++
|
||||
continue
|
||||
}
|
||||
remain.push(arg)
|
||||
}
|
||||
}
|
||||
|
||||
function resolveShort (arg, shorthands, shortAbbr, abbrevs) {
|
||||
// handle single-char shorthands glommed together, like
|
||||
// npm ls -glp, but only if there is one dash, and only if
|
||||
// all of the chars are single-char shorthands, and it's
|
||||
// not a match to some other abbrev.
|
||||
arg = arg.replace(/^-+/, '')
|
||||
|
||||
// if it's an exact known option, then don't go any further
|
||||
if (abbrevs[arg] === arg)
|
||||
return null
|
||||
|
||||
// if it's an exact known shortopt, same deal
|
||||
if (shorthands[arg]) {
|
||||
// make it an array, if it's a list of words
|
||||
if (shorthands[arg] && !Array.isArray(shorthands[arg]))
|
||||
shorthands[arg] = shorthands[arg].split(/\s+/)
|
||||
|
||||
return shorthands[arg]
|
||||
}
|
||||
|
||||
// first check to see if this arg is a set of single-char shorthands
|
||||
var singles = shorthands.___singles
|
||||
if (!singles) {
|
||||
singles = Object.keys(shorthands).filter(function (s) {
|
||||
return s.length === 1
|
||||
}).reduce(function (l,r) {
|
||||
l[r] = true
|
||||
return l
|
||||
}, {})
|
||||
shorthands.___singles = singles
|
||||
debug('shorthand singles', singles)
|
||||
}
|
||||
|
||||
var chrs = arg.split("").filter(function (c) {
|
||||
return singles[c]
|
||||
})
|
||||
|
||||
if (chrs.join("") === arg) return chrs.map(function (c) {
|
||||
return shorthands[c]
|
||||
}).reduce(function (l, r) {
|
||||
return l.concat(r)
|
||||
}, [])
|
||||
|
||||
|
||||
// if it's an arg abbrev, and not a literal shorthand, then prefer the arg
|
||||
if (abbrevs[arg] && !shorthands[arg])
|
||||
return null
|
||||
|
||||
// if it's an abbr for a shorthand, then use that
|
||||
if (shortAbbr[arg])
|
||||
arg = shortAbbr[arg]
|
||||
|
||||
// make it an array, if it's a list of words
|
||||
if (shorthands[arg] && !Array.isArray(shorthands[arg]))
|
||||
shorthands[arg] = shorthands[arg].split(/\s+/)
|
||||
|
||||
return shorthands[arg]
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
.nyc_output
|
||||
nyc_output
|
||||
node_modules
|
||||
coverage
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- '0.10'
|
||||
- '0.12'
|
||||
- 'iojs'
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
To get started, <a
|
||||
href="http://www.clahub.com/agreements/isaacs/abbrev-js">sign the
|
||||
Contributor License Agreement</a>.
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
The ISC License
|
||||
|
||||
Copyright (c) Isaac Z. Schlueter and Contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
|
||||
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
# abbrev-js
|
||||
|
||||
Just like [ruby's Abbrev](http://apidock.com/ruby/Abbrev).
|
||||
|
||||
Usage:
|
||||
|
||||
var abbrev = require("abbrev");
|
||||
abbrev("foo", "fool", "folding", "flop");
|
||||
|
||||
// returns:
|
||||
{ fl: 'flop'
|
||||
, flo: 'flop'
|
||||
, flop: 'flop'
|
||||
, fol: 'folding'
|
||||
, fold: 'folding'
|
||||
, foldi: 'folding'
|
||||
, foldin: 'folding'
|
||||
, folding: 'folding'
|
||||
, foo: 'foo'
|
||||
, fool: 'fool'
|
||||
}
|
||||
|
||||
This is handy for command-line scripts, or other cases where you want to be able to accept shorthands.
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
|
||||
module.exports = exports = abbrev.abbrev = abbrev
|
||||
|
||||
abbrev.monkeyPatch = monkeyPatch
|
||||
|
||||
function monkeyPatch () {
|
||||
Object.defineProperty(Array.prototype, 'abbrev', {
|
||||
value: function () { return abbrev(this) },
|
||||
enumerable: false, configurable: true, writable: true
|
||||
})
|
||||
|
||||
Object.defineProperty(Object.prototype, 'abbrev', {
|
||||
value: function () { return abbrev(Object.keys(this)) },
|
||||
enumerable: false, configurable: true, writable: true
|
||||
})
|
||||
}
|
||||
|
||||
function abbrev (list) {
|
||||
if (arguments.length !== 1 || !Array.isArray(list)) {
|
||||
list = Array.prototype.slice.call(arguments, 0)
|
||||
}
|
||||
for (var i = 0, l = list.length, args = [] ; i < l ; i ++) {
|
||||
args[i] = typeof list[i] === "string" ? list[i] : String(list[i])
|
||||
}
|
||||
|
||||
// sort them lexicographically, so that they're next to their nearest kin
|
||||
args = args.sort(lexSort)
|
||||
|
||||
// walk through each, seeing how much it has in common with the next and previous
|
||||
var abbrevs = {}
|
||||
, prev = ""
|
||||
for (var i = 0, l = args.length ; i < l ; i ++) {
|
||||
var current = args[i]
|
||||
, next = args[i + 1] || ""
|
||||
, nextMatches = true
|
||||
, prevMatches = true
|
||||
if (current === next) continue
|
||||
for (var j = 0, cl = current.length ; j < cl ; j ++) {
|
||||
var curChar = current.charAt(j)
|
||||
nextMatches = nextMatches && curChar === next.charAt(j)
|
||||
prevMatches = prevMatches && curChar === prev.charAt(j)
|
||||
if (!nextMatches && !prevMatches) {
|
||||
j ++
|
||||
break
|
||||
}
|
||||
}
|
||||
prev = current
|
||||
if (j === cl) {
|
||||
abbrevs[current] = current
|
||||
continue
|
||||
}
|
||||
for (var a = current.substr(0, j) ; j <= cl ; j ++) {
|
||||
abbrevs[a] = current
|
||||
a += current.charAt(j)
|
||||
}
|
||||
}
|
||||
return abbrevs
|
||||
}
|
||||
|
||||
function lexSort (a, b) {
|
||||
return a === b ? 0 : a > b ? 1 : -1
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"name": "abbrev",
|
||||
"version": "1.0.7",
|
||||
"description": "Like ruby's abbrev module, but in js",
|
||||
"author": {
|
||||
"name": "Isaac Z. Schlueter",
|
||||
"email": "i@izs.me"
|
||||
},
|
||||
"main": "abbrev.js",
|
||||
"scripts": {
|
||||
"test": "tap test.js --cov"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+ssh://git@github.com/isaacs/abbrev-js.git"
|
||||
},
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"tap": "^1.2.0"
|
||||
},
|
||||
"gitHead": "821d09ce7da33627f91bbd8ed631497ed6f760c2",
|
||||
"bugs": {
|
||||
"url": "https://github.com/isaacs/abbrev-js/issues"
|
||||
},
|
||||
"homepage": "https://github.com/isaacs/abbrev-js#readme",
|
||||
"_id": "abbrev@1.0.7",
|
||||
"_shasum": "5b6035b2ee9d4fb5cf859f08a9be81b208491843",
|
||||
"_from": "abbrev@>=1.0.0 <2.0.0",
|
||||
"_npmVersion": "2.10.1",
|
||||
"_nodeVersion": "2.0.1",
|
||||
"_npmUser": {
|
||||
"name": "isaacs",
|
||||
"email": "isaacs@npmjs.com"
|
||||
},
|
||||
"dist": {
|
||||
"shasum": "5b6035b2ee9d4fb5cf859f08a9be81b208491843",
|
||||
"tarball": "http://registry.npmjs.org/abbrev/-/abbrev-1.0.7.tgz"
|
||||
},
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "isaacs",
|
||||
"email": "i@izs.me"
|
||||
}
|
||||
],
|
||||
"directories": {},
|
||||
"_resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.7.tgz",
|
||||
"readme": "ERROR: No README data found!"
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
var abbrev = require('./abbrev.js')
|
||||
var assert = require("assert")
|
||||
var util = require("util")
|
||||
|
||||
console.log("TAP version 13")
|
||||
var count = 0
|
||||
|
||||
function test (list, expect) {
|
||||
count++
|
||||
var actual = abbrev(list)
|
||||
assert.deepEqual(actual, expect,
|
||||
"abbrev("+util.inspect(list)+") === " + util.inspect(expect) + "\n"+
|
||||
"actual: "+util.inspect(actual))
|
||||
actual = abbrev.apply(exports, list)
|
||||
assert.deepEqual(abbrev.apply(exports, list), expect,
|
||||
"abbrev("+list.map(JSON.stringify).join(",")+") === " + util.inspect(expect) + "\n"+
|
||||
"actual: "+util.inspect(actual))
|
||||
console.log('ok - ' + list.join(' '))
|
||||
}
|
||||
|
||||
test([ "ruby", "ruby", "rules", "rules", "rules" ],
|
||||
{ rub: 'ruby'
|
||||
, ruby: 'ruby'
|
||||
, rul: 'rules'
|
||||
, rule: 'rules'
|
||||
, rules: 'rules'
|
||||
})
|
||||
test(["fool", "foom", "pool", "pope"],
|
||||
{ fool: 'fool'
|
||||
, foom: 'foom'
|
||||
, poo: 'pool'
|
||||
, pool: 'pool'
|
||||
, pop: 'pope'
|
||||
, pope: 'pope'
|
||||
})
|
||||
test(["a", "ab", "abc", "abcd", "abcde", "acde"],
|
||||
{ a: 'a'
|
||||
, ab: 'ab'
|
||||
, abc: 'abc'
|
||||
, abcd: 'abcd'
|
||||
, abcde: 'abcde'
|
||||
, ac: 'acde'
|
||||
, acd: 'acde'
|
||||
, acde: 'acde'
|
||||
})
|
||||
|
||||
console.log("1..%d", count)
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
{
|
||||
"name": "nopt",
|
||||
"version": "3.0.4",
|
||||
"description": "Option parsing for Node, supporting types, shorthands, etc. Used by npm.",
|
||||
"author": {
|
||||
"name": "Isaac Z. Schlueter",
|
||||
"email": "i@izs.me",
|
||||
"url": "http://blog.izs.me/"
|
||||
},
|
||||
"main": "lib/nopt.js",
|
||||
"scripts": {
|
||||
"test": "tap test/*.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+ssh://git@github.com/isaacs/nopt.git"
|
||||
},
|
||||
"bin": {
|
||||
"nopt": "./bin/nopt.js"
|
||||
},
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"abbrev": "1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"tap": "^1.2.0"
|
||||
},
|
||||
"gitHead": "f52626631ea1afef5a6dd9acf23ddd1466831a08",
|
||||
"bugs": {
|
||||
"url": "https://github.com/isaacs/nopt/issues"
|
||||
},
|
||||
"homepage": "https://github.com/isaacs/nopt#readme",
|
||||
"_id": "nopt@3.0.4",
|
||||
"_shasum": "dd63bc9c72a6e4e85b85cdc0ca314598facede5e",
|
||||
"_from": "nopt@>=3.0.1 <4.0.0",
|
||||
"_npmVersion": "2.14.3",
|
||||
"_nodeVersion": "2.2.2",
|
||||
"_npmUser": {
|
||||
"name": "zkat",
|
||||
"email": "kat@sykosomatic.org"
|
||||
},
|
||||
"dist": {
|
||||
"shasum": "dd63bc9c72a6e4e85b85cdc0ca314598facede5e",
|
||||
"tarball": "http://registry.npmjs.org/nopt/-/nopt-3.0.4.tgz"
|
||||
},
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "isaacs",
|
||||
"email": "isaacs@npmjs.com"
|
||||
},
|
||||
{
|
||||
"name": "zkat",
|
||||
"email": "kat@sykosomatic.org"
|
||||
}
|
||||
],
|
||||
"directories": {},
|
||||
"_resolved": "https://registry.npmjs.org/nopt/-/nopt-3.0.4.tgz",
|
||||
"readme": "ERROR: No README data found!"
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
# node-properties-parser
|
||||
|
||||
A parser for [.properties](http://en.wikipedia.org/wiki/.properties) files written in javascript. Properties files store key-value pairs. They are typically used for configuration and internationalization in Java applications as well as in Actionscript projects. Here's an example of the format:
|
||||
|
||||
# You are reading the ".properties" entry.
|
||||
! The exclamation mark can also mark text as comments.
|
||||
website = http://en.wikipedia.org/
|
||||
language = English
|
||||
# The backslash below tells the application to continue reading
|
||||
# the value onto the next line.
|
||||
message = Welcome to \
|
||||
Wikipedia!
|
||||
# Add spaces to the key
|
||||
key\ with\ spaces = This is the value that could be looked up with the key "key with spaces".
|
||||
# Unicode
|
||||
tab : \u0009
|
||||
*(taken from [Wikipedia](http://en.wikipedia.org/wiki/.properties#Format))*
|
||||
|
||||
Currently works with any version of node.js.
|
||||
|
||||
## The API
|
||||
|
||||
- `parse(text)`: Parses `text` into key-value pairs. Returns an object containing the key-value pairs.
|
||||
- `read(path[, callback])`: Opens the file specified by `path` and calls `parse` on its content. If the optional `callback` parameter is provided, the result is then passed to it as the second parameter. If an error occurs, the error object is passed to `callback` as the first parameter. If `callback` is not provided, the file specified by `path` is synchronously read and calls `parse` on its contents. The resulting object is immediately returned.
|
||||
- `createEditor([path][, options][, callback]])`: If neither `path` or `callback` are provided an empty editor object is returned synchronously. If only `path` is provided, the file specified by `path` is synchronously read and parsed. An editor object with the results in then immediately returned. If both `path` and `callback` are provided, the file specified by `path` is read and parsed asynchronously. An editor object with the results are then passed to `callback` as the second parameters. If an error occurs, the error object is passed to `callback` as the first parameter. The following options are supported:
|
||||
- `options.separator`: The character used to separate key/values. Defaults to "=".
|
||||
- `options.path`: Treated the same way as the optional `path` argument. If both are provided the arguement wins.
|
||||
- `options.callback`: Treated the same way as the optional `callback` parameter. If both are provided the arguement wins.
|
||||
- `Editor`: The editor object is returned by `createEditor`. Has the following API:
|
||||
- `get(key)`: Returns the value currently associated with `key`.
|
||||
- `set(key, [value[, comment]])`: Associates `key` with `value`. An optional comment can be provided. If `value` is not specified or is `null`, then `key` is unset.
|
||||
- `unset(key)`: Unsets the specified `key`.
|
||||
- `save([path][, callback]])`: Writes the current contents of this editor object to a file specified by `path`. If `path` is not provided, then it'll be defaulted to the `path` value passed to `createEditor`. The `callback` parameter is called when the file has been written to disk.
|
||||
- `addHeadComment`: Added a comment to the head of the file.
|
||||
- `toString`: Returns the string representation of this properties editor object. This string will be written to a file if `save` is called.
|
||||
|
||||
## Getting node-properties-parser
|
||||
|
||||
The easiest way to get node-properties-parser is with [npm](http://npmjs.org/):
|
||||
|
||||
npm install properties-parser
|
||||
|
||||
Alternatively you can clone this git repository:
|
||||
|
||||
git://github.com/xavi-/node-properties-parser.git
|
||||
|
||||
## Developed by
|
||||
* Xavi Ramirez
|
||||
|
||||
## License
|
||||
This project is released under [The MIT License](http://www.opensource.org/licenses/mit-license.php).
|
||||
+420
@@ -0,0 +1,420 @@
|
||||
var fs = require("fs");
|
||||
|
||||
function Iterator(text) {
|
||||
var pos = 0, length = text.length;
|
||||
|
||||
this.peek = function(num) {
|
||||
num = num || 0;
|
||||
if(pos + num >= length) { return null; }
|
||||
|
||||
return text.charAt(pos + num);
|
||||
};
|
||||
this.next = function(inc) {
|
||||
inc = inc || 1;
|
||||
|
||||
if(pos >= length) { return null; }
|
||||
|
||||
return text.charAt((pos += inc) - inc);
|
||||
};
|
||||
this.pos = function() {
|
||||
return pos;
|
||||
};
|
||||
}
|
||||
|
||||
var rWhitespace = /\s/;
|
||||
function isWhitespace(chr) {
|
||||
return rWhitespace.test(chr);
|
||||
}
|
||||
function consumeWhiteSpace(iter) {
|
||||
var start = iter.pos();
|
||||
|
||||
while(isWhitespace(iter.peek())) { iter.next(); }
|
||||
|
||||
return { type: "whitespace", start: start, end: iter.pos() };
|
||||
}
|
||||
|
||||
function startsComment(chr) {
|
||||
return chr === "!" || chr === "#";
|
||||
}
|
||||
function isEOL(chr) {
|
||||
return chr == null || chr === "\n" || chr === "\r";
|
||||
}
|
||||
function consumeComment(iter) {
|
||||
var start = iter.pos();
|
||||
|
||||
while(!isEOL(iter.peek())) { iter.next(); }
|
||||
|
||||
return { type: "comment", start: start, end: iter.pos() };
|
||||
}
|
||||
|
||||
function startsKeyVal(chr) {
|
||||
return !isWhitespace(chr) && !startsComment(chr);
|
||||
}
|
||||
function startsSeparator(chr) {
|
||||
return chr === "=" || chr === ":" || isWhitespace(chr);
|
||||
}
|
||||
function startsEscapedVal(chr) {
|
||||
return chr === "\\";
|
||||
}
|
||||
function consumeEscapedVal(iter) {
|
||||
var start = iter.pos();
|
||||
|
||||
iter.next(); // move past "\"
|
||||
var curChar = iter.next();
|
||||
if(curChar === "u") { // encoded unicode char
|
||||
iter.next(4); // Read in the 4 hex values
|
||||
}
|
||||
|
||||
return { type: "escaped-value", start: start, end: iter.pos() };
|
||||
}
|
||||
function consumeKey(iter) {
|
||||
var start = iter.pos(), children = [];
|
||||
|
||||
var curChar;
|
||||
while((curChar = iter.peek()) !== null) {
|
||||
if(startsSeparator(curChar)) { break; }
|
||||
if(startsEscapedVal(curChar)) { children.push(consumeEscapedVal(iter)); continue; }
|
||||
|
||||
iter.next();
|
||||
}
|
||||
|
||||
return { type: "key", start: start, end: iter.pos(), children: children };
|
||||
}
|
||||
function consumeKeyValSeparator(iter) {
|
||||
var start = iter.pos();
|
||||
|
||||
var seenHardSep = false, curChar;
|
||||
while((curChar = iter.peek()) !== null) {
|
||||
if(isEOL(curChar)) { break; }
|
||||
|
||||
if(isWhitespace(curChar)) { iter.next(); continue; }
|
||||
|
||||
if(seenHardSep) { break; }
|
||||
|
||||
seenHardSep = (curChar === ":" || curChar === "=");
|
||||
if(seenHardSep) { iter.next(); continue; }
|
||||
|
||||
break; // curChar is a non-separtor char
|
||||
}
|
||||
|
||||
return { type: "key-value-separator", start: start, end: iter.pos() };
|
||||
}
|
||||
function startsLineBreak(iter) {
|
||||
return iter.peek() === "\\" && isEOL(iter.peek(1));
|
||||
}
|
||||
function consumeLineBreak(iter) {
|
||||
var start = iter.pos();
|
||||
|
||||
iter.next(); // consume \
|
||||
if(iter.peek() === "\r") { iter.next(); }
|
||||
iter.next(); // consume \n
|
||||
|
||||
var curChar;
|
||||
while((curChar = iter.peek()) !== null) {
|
||||
if(isEOL(curChar)) { break; }
|
||||
if(!isWhitespace(curChar)) { break; }
|
||||
|
||||
iter.next();
|
||||
}
|
||||
|
||||
return { type: "line-break", start: start, end: iter.pos() };
|
||||
}
|
||||
function consumeVal(iter) {
|
||||
var start = iter.pos(), children = [];
|
||||
|
||||
var curChar;
|
||||
while((curChar = iter.peek()) !== null) {
|
||||
if(startsLineBreak(iter)) { children.push(consumeLineBreak(iter)); continue; }
|
||||
if(startsEscapedVal(curChar)) { children.push(consumeEscapedVal(iter)); continue; }
|
||||
if(isEOL(curChar)) { break; }
|
||||
|
||||
iter.next();
|
||||
}
|
||||
|
||||
return { type: "value", start: start, end: iter.pos(), children: children };
|
||||
}
|
||||
function consumeKeyVal(iter) {
|
||||
return {
|
||||
type: "key-value",
|
||||
start: iter.pos(),
|
||||
children: [
|
||||
consumeKey(iter),
|
||||
consumeKeyValSeparator(iter),
|
||||
consumeVal(iter)
|
||||
],
|
||||
end: iter.pos()
|
||||
};
|
||||
}
|
||||
|
||||
var renderChild = {
|
||||
"escaped-value": function(child, text) {
|
||||
var type = text.charAt(child.start + 1);
|
||||
|
||||
if(type === "t") { return "\t"; }
|
||||
if(type === "r") { return "\r"; }
|
||||
if(type === "n") { return "\n"; }
|
||||
if(type === "f") { return "\f"; }
|
||||
if(type !== "u") { return type; }
|
||||
|
||||
return String.fromCharCode(parseInt(text.substr(child.start + 2, 4), 16));
|
||||
},
|
||||
"line-break": function (child, text) {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
function rangeToBuffer(range, text) {
|
||||
var start = range.start, buffer = [];
|
||||
|
||||
for(var i = 0; i < range.children.length; i++) {
|
||||
var child = range.children[i];
|
||||
|
||||
buffer.push(text.substring(start, child.start));
|
||||
buffer.push(renderChild[child.type](child, text));
|
||||
start = child.end;
|
||||
}
|
||||
buffer.push(text.substring(start, range.end));
|
||||
|
||||
return buffer;
|
||||
}
|
||||
function rangesToObject(ranges, text) {
|
||||
var obj = Object.create(null); // Creates to a true hash map
|
||||
|
||||
for(var i = 0; i < ranges.length; i++) {
|
||||
var range = ranges[i];
|
||||
|
||||
if(range.type !== "key-value") { continue; }
|
||||
|
||||
var key = rangeToBuffer(range.children[0], text).join("");
|
||||
var val = rangeToBuffer(range.children[2], text).join("");
|
||||
obj[key] = val;
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
function stringToRanges(text) {
|
||||
var iter = new Iterator(text), ranges = [];
|
||||
|
||||
var curChar;
|
||||
while((curChar = iter.peek()) !== null) {
|
||||
if(isWhitespace(curChar)) { ranges.push(consumeWhiteSpace(iter)); continue; }
|
||||
if(startsComment(curChar)) { ranges.push(consumeComment(iter)); continue; }
|
||||
if(startsKeyVal(curChar)) { ranges.push(consumeKeyVal(iter)); continue; }
|
||||
|
||||
throw Error("Something crazy happened. text: '" + text + "'; curChar: '" + curChar + "'");
|
||||
}
|
||||
|
||||
return ranges;
|
||||
}
|
||||
|
||||
function isNewLineRange(range) {
|
||||
if(!range) { return false; }
|
||||
|
||||
if(range.type === "whitespace") { return true; }
|
||||
|
||||
if(range.type === "literal") {
|
||||
return isWhitespace(range.text) && range.text.indexOf("\n") > -1;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function escapeMaker(escapes) {
|
||||
return function escapeKey(key) {
|
||||
var zeros = [ "", "0", "00", "000" ];
|
||||
var buf = [];
|
||||
|
||||
for(var i = 0; i < key.length; i++) {
|
||||
var chr = key.charAt(i);
|
||||
|
||||
if(escapes[chr]) { buf.push(escapes[chr]); continue; }
|
||||
|
||||
var code = chr.codePointAt(0);
|
||||
|
||||
if(code <= 0x7F) { buf.push(chr); continue; }
|
||||
|
||||
var hex = code.toString(16);
|
||||
|
||||
buf.push("\\u");
|
||||
buf.push(zeros[4 - hex.length]);
|
||||
buf.push(hex);
|
||||
}
|
||||
|
||||
return buf.join("");
|
||||
};
|
||||
}
|
||||
|
||||
var escapeKey = escapeMaker({ " ": "\\ ", "\n": "\\n", ":": "\\:", "=": "\\=" });
|
||||
var escapeVal = escapeMaker({ "\n": "\\n" });
|
||||
|
||||
function Editor(text, options) {
|
||||
if (typeof text === 'object') {
|
||||
options = text;
|
||||
text = null;
|
||||
}
|
||||
text = text || "";
|
||||
var path = options.path;
|
||||
var separator = options.separator || '=';
|
||||
|
||||
var ranges = stringToRanges(text);
|
||||
var obj = rangesToObject(ranges, text);
|
||||
var keyRange = Object.create(null); // Creates to a true hash map
|
||||
|
||||
for(var i = 0; i < ranges.length; i++) {
|
||||
var range = ranges[i];
|
||||
|
||||
if(range.type !== "key-value") { continue; }
|
||||
|
||||
var key = rangeToBuffer(range.children[0], text).join("");
|
||||
keyRange[key] = range;
|
||||
}
|
||||
|
||||
this.addHeadComment = function(comment) {
|
||||
if(comment == null) { return; }
|
||||
|
||||
ranges.unshift({ type: "literal", text: "# " + comment.replace(/\n/g, "\n# ") + "\n" });
|
||||
};
|
||||
|
||||
this.get = function(key) { return obj[key]; };
|
||||
this.set = function(key, val, comment) {
|
||||
if(val == null) { this.unset(key); return; }
|
||||
|
||||
obj[key] = val;
|
||||
var escapedKey = escapeKey(key);
|
||||
var escapedVal = escapeVal(val);
|
||||
|
||||
var range = keyRange[key];
|
||||
if(!range) {
|
||||
keyRange[key] = range = {
|
||||
type: "literal",
|
||||
text: escapedKey + separator + escapedVal
|
||||
};
|
||||
|
||||
var prevRange = ranges[ranges.length - 1];
|
||||
if(prevRange != null && !isNewLineRange(prevRange)) {
|
||||
ranges.push({ type: "literal", text: "\n" });
|
||||
}
|
||||
ranges.push(range);
|
||||
}
|
||||
|
||||
// comment === null deletes comment. if comment === undefined, it's left alone
|
||||
if(comment !== undefined) {
|
||||
range.comment = comment && "# " + comment.replace(/\n/g, "\n# ") + "\n";
|
||||
}
|
||||
|
||||
if(range.type === "literal") {
|
||||
range.text = escapedKey + separator + escapedVal;
|
||||
if(range.comment != null) { range.text = range.comment + range.text; }
|
||||
} else if(range.type === "key-value") {
|
||||
range.children[2] = { type: "literal", text: escapedVal };
|
||||
} else {
|
||||
throw "Unknown node type: " + range.type;
|
||||
}
|
||||
};
|
||||
this.unset = function(key) {
|
||||
if(!(key in obj)) { return; }
|
||||
|
||||
var range = keyRange[key];
|
||||
var idx = ranges.indexOf(range);
|
||||
|
||||
ranges.splice(idx, (isNewLineRange(ranges[idx + 1]) ? 2 : 1));
|
||||
|
||||
delete keyRange[key];
|
||||
delete obj[key];
|
||||
};
|
||||
this.valueOf = this.toString = function() {
|
||||
var buffer = [], stack = [].concat(ranges);
|
||||
|
||||
var node;
|
||||
while((node = stack.shift()) != null) {
|
||||
switch(node.type) {
|
||||
case "literal":
|
||||
buffer.push(node.text);
|
||||
break;
|
||||
case "key":
|
||||
case "value":
|
||||
case "comment":
|
||||
case "whitespace":
|
||||
case "key-value-separator":
|
||||
case "escaped-value":
|
||||
case "line-break":
|
||||
buffer.push(text.substring(node.start, node.end));
|
||||
break;
|
||||
case "key-value":
|
||||
Array.prototype.unshift.apply(stack, node.children);
|
||||
if(node.comment) { stack.unshift({ type: "literal", text: node.comment }); }
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return buffer.join("");
|
||||
};
|
||||
this.save = function(newPath, callback) {
|
||||
if(typeof newPath === 'function') {
|
||||
callback = newPath;
|
||||
newPath = path;
|
||||
}
|
||||
newPath = newPath || path;
|
||||
|
||||
if(!newPath) {
|
||||
if (callback) {
|
||||
return callback("Unknown path");
|
||||
}
|
||||
throw new Error("Unknown path");
|
||||
}
|
||||
|
||||
if (callback) {
|
||||
fs.writeFile(newPath, this.toString(), callback);
|
||||
} else {
|
||||
fs.writeFileSync(newPath, this.toString());
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
function createEditor(/*path, options, callback*/) {
|
||||
var path, options, callback;
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
for (var i = 0; i < args.length; i ++) {
|
||||
var arg = args[i];
|
||||
if (!path && typeof arg === 'string') {
|
||||
path = arg;
|
||||
} else if (!options && typeof arg === 'object') {
|
||||
options = arg;
|
||||
} else if (!callback && typeof arg === 'function') {
|
||||
callback = arg;
|
||||
}
|
||||
}
|
||||
options = options || {};
|
||||
path = path || options.path;
|
||||
callback = callback || options.callback;
|
||||
options.path = path;
|
||||
|
||||
if(!path) { return new Editor(options); }
|
||||
|
||||
if(!callback) { return new Editor(fs.readFileSync(path).toString(), options); }
|
||||
|
||||
return fs.readFile(path, function(err, text) {
|
||||
if(err) { return callback(err, null); }
|
||||
|
||||
text = text.toString();
|
||||
return callback(null, new Editor(text, options));
|
||||
});
|
||||
}
|
||||
|
||||
function parse(text) {
|
||||
text = text.toString();
|
||||
var ranges = stringToRanges(text);
|
||||
return rangesToObject(ranges, text);
|
||||
}
|
||||
|
||||
function read(path, callback) {
|
||||
if(!callback) { return parse(fs.readFileSync(path)); }
|
||||
|
||||
return fs.readFile(path, function(err, data) {
|
||||
if(err) { return callback(err, null); }
|
||||
|
||||
return callback(null, parse(data));
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { parse: parse, read: read, createEditor: createEditor };
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"name": "properties-parser",
|
||||
"version": "0.3.0",
|
||||
"description": "A parser for .properties files written in javascript",
|
||||
"keywords": [
|
||||
"parser",
|
||||
".properties",
|
||||
"properties",
|
||||
"java",
|
||||
"file parser",
|
||||
"actionscript"
|
||||
],
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "xavi",
|
||||
"email": "xavi.rmz@gmail.com"
|
||||
}
|
||||
],
|
||||
"main": "./index.js",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/xavi-/node-properties-parser.git"
|
||||
},
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.3.1"
|
||||
},
|
||||
"gitHead": "d9f75e462c3da0e6eb33261e578e040994ff50c9",
|
||||
"bugs": {
|
||||
"url": "https://github.com/xavi-/node-properties-parser/issues"
|
||||
},
|
||||
"homepage": "https://github.com/xavi-/node-properties-parser",
|
||||
"_id": "properties-parser@0.3.0",
|
||||
"scripts": {},
|
||||
"_shasum": "6ba6dc6ac40cf53b1ee2c2045f86623e70213caa",
|
||||
"_from": "properties-parser@>=0.3.0 <0.4.0",
|
||||
"_npmVersion": "2.5.1",
|
||||
"_nodeVersion": "1.2.0",
|
||||
"_npmUser": {
|
||||
"name": "xavi",
|
||||
"email": "xavi.rmz@gmail.com"
|
||||
},
|
||||
"dist": {
|
||||
"shasum": "6ba6dc6ac40cf53b1ee2c2045f86623e70213caa",
|
||||
"tarball": "http://registry.npmjs.org/properties-parser/-/properties-parser-0.3.0.tgz"
|
||||
},
|
||||
"directories": {},
|
||||
"_resolved": "https://registry.npmjs.org/properties-parser/-/properties-parser-0.3.0.tgz",
|
||||
"readme": "ERROR: No README data found!"
|
||||
}
|
||||
+786
@@ -0,0 +1,786 @@
|
||||
|
||||
## 1.4.1
|
||||
|
||||
- Address an issue that prevented Q from being used as a `<script>` for
|
||||
Firefox add-ons. Q can now be used in any environment that provides `window`
|
||||
or `self` globals, favoring `window` since add-ons have an an immutable
|
||||
`self` that is distinct from `window`.
|
||||
|
||||
## 1.4.0
|
||||
|
||||
- Add `noConflict` support for use in `<script>` (@jahnjw).
|
||||
|
||||
## 1.3.0
|
||||
|
||||
- Add tracking for unhandled and handled rejections in Node.js (@benjamingr).
|
||||
|
||||
## 1.2.1
|
||||
|
||||
- Fix Node.js environment detection for modern Browserify (@kahnjw).
|
||||
|
||||
## 1.2.0
|
||||
|
||||
- Added Q.any(promisesArray) method (@vergara).
|
||||
Returns a promise fulfilled with the value of the first resolved promise in
|
||||
promisesArray. If all promises in promisesArray are rejected, it returns
|
||||
a rejected promise.
|
||||
|
||||
## 1.1.2
|
||||
|
||||
- Removed extraneous files from the npm package by using the "files"
|
||||
whitelist in package.json instead of the .npmignore blacklist.
|
||||
(@anton-rudeshko)
|
||||
|
||||
## 1.1.1
|
||||
|
||||
- Fix a pair of regressions in bootstrapping, one which precluded
|
||||
WebWorker support, and another that precluded support in
|
||||
``<script>`` usage outright. #607
|
||||
|
||||
## 1.1.0
|
||||
|
||||
- Adds support for enabling long stack traces in node.js by setting
|
||||
environment variable `Q_DEBUG=1`.
|
||||
- Introduces the `tap` method to promises, which will see a value
|
||||
pass through without alteration.
|
||||
- Use instanceof to recognize own promise instances as opposed to
|
||||
thenables.
|
||||
- Construct timeout errors with `code === ETIMEDOUT` (Kornel Lesiński)
|
||||
- More descriminant CommonJS module environment detection.
|
||||
- Dropped continuous integration for Node.js 0.6 and 0.8 because of
|
||||
changes to npm that preclude the use of new `^` version predicate
|
||||
operator in any transitive dependency.
|
||||
- Users can now override `Q.nextTick`.
|
||||
|
||||
## 1.0.1
|
||||
|
||||
- Adds support for `Q.Promise`, which implements common usage of the
|
||||
ES6 `Promise` constructor and its methods. `Promise` does not have
|
||||
a valid promise constructor and a proper implementation awaits
|
||||
version 2 of Q.
|
||||
- Removes the console stopgap for a promise inspector. This no longer
|
||||
works with any degree of reliability.
|
||||
- Fixes support for content security policies that forbid eval. Now
|
||||
using the `StopIteration` global to distinguish SpiderMonkey
|
||||
generators from ES6 generators, assuming that they will never
|
||||
coexist.
|
||||
|
||||
## 1.0.0
|
||||
|
||||
:cake: This is all but a re-release of version 0.9, which has settled
|
||||
into a gentle maintenance mode and rightly deserves an official 1.0.
|
||||
An ambitious 2.0 release is already around the corner, but 0.9/1.0
|
||||
have been distributed far and wide and demand long term support.
|
||||
|
||||
- Q will now attempt to post a debug message in browsers regardless
|
||||
of whether window.Touch is defined. Chrome at least now has this
|
||||
property regardless of whether touch is supported by the underlying
|
||||
hardware.
|
||||
- Remove deprecation warning from `promise.valueOf`. The function is
|
||||
called by the browser in various ways so there is no way to
|
||||
distinguish usage that should be migrated from usage that cannot be
|
||||
altered.
|
||||
|
||||
## 0.9.7
|
||||
|
||||
- :warning: `q.min.js` is no longer checked-in. It is however still
|
||||
created by Grunt and NPM.
|
||||
- Fixes a bug that inhibited `Q.async` with implementations of the new
|
||||
ES6 generators.
|
||||
- Fixes a bug with `nextTick` affecting Safari 6.0.5 the first time a
|
||||
page loads when an `iframe` is involved.
|
||||
- Introduces `passByCopy`, `join`, and `race`.
|
||||
- Shows stack traces or error messages on the console, instead of
|
||||
`Error` objects.
|
||||
- Elimintates wrapper methods for improved performance.
|
||||
- `Q.all` now propagates progress notifications of the form you might
|
||||
expect of ES6 iterations, `{value, index}` where the `value` is the
|
||||
progress notification from the promise at `index`.
|
||||
|
||||
## 0.9.6
|
||||
|
||||
- Fixes a bug in recognizing the difference between compatible Q
|
||||
promises, and Q promises from before the implementation of "inspect".
|
||||
The latter are now coerced.
|
||||
- Fixes an infinite asynchronous coercion cycle introduced by former
|
||||
solution, in two independently sufficient ways. 1.) All promises
|
||||
returned by makePromise now implement "inspect", albeit a default
|
||||
that reports that the promise has an "unknown" state. 2.) The
|
||||
implementation of "then/when" is now in "then" instead of "when", so
|
||||
that the responsibility to "coerce" the given promise rests solely in
|
||||
the "when" method and the "then" method may assume that "this" is a
|
||||
promise of the right type.
|
||||
- Refactors `nextTick` to use an unrolled microtask within Q regardless
|
||||
of how new ticks a requested. #316 @rkatic
|
||||
|
||||
## 0.9.5
|
||||
|
||||
- Introduces `inspect` for getting the state of a promise as
|
||||
`{state: "fulfilled" | "rejected" | "pending", value | reason}`.
|
||||
- Introduces `allSettled` which produces an array of promises states
|
||||
for the input promises once they have all "settled". This is in
|
||||
accordance with a discussion on Promises/A+ that "settled" refers to
|
||||
a promise that is "fulfilled" or "rejected". "resolved" refers to a
|
||||
deferred promise that has been "resolved" to another promise,
|
||||
"sealing its fate" to the fate of the successor promise.
|
||||
- Long stack traces are now off by default. Set `Q.longStackSupport`
|
||||
to true to enable long stack traces.
|
||||
- Long stack traces can now follow the entire asynchronous history of a
|
||||
promise, not just a single jump.
|
||||
- Introduces `spawn` for an immediately invoked asychronous generator.
|
||||
@jlongster
|
||||
- Support for *experimental* synonyms `mapply`, `mcall`, `nmapply`,
|
||||
`nmcall` for method invocation.
|
||||
|
||||
## 0.9.4
|
||||
|
||||
- `isPromise` and `isPromiseAlike` now always returns a boolean
|
||||
(even for falsy values). #284 @lfac-pt
|
||||
- Support for ES6 Generators in `async` #288 @andywingo
|
||||
- Clear duplicate promise rejections from dispatch methods #238 @SLaks
|
||||
- Unhandled rejection API #296 @domenic
|
||||
`stopUnhandledRejectionTracking`, `getUnhandledReasons`,
|
||||
`resetUnhandledRejections`.
|
||||
|
||||
## 0.9.3
|
||||
|
||||
- Add the ability to give `Q.timeout`'s errors a custom error message. #270
|
||||
@jgrenon
|
||||
- Fix Q's call-stack busting behavior in Node.js 0.10, by switching from
|
||||
`process.nextTick` to `setImmediate`. #254 #259
|
||||
- Fix Q's behavior when used with the Mocha test runner in the browser, since
|
||||
Mocha introduces a fake `process` global without a `nextTick` property. #267
|
||||
- Fix some, but not all, cases wherein Q would give false positives in its
|
||||
unhandled rejection detection (#252). A fix for other cases (#238) is
|
||||
hopefully coming soon.
|
||||
- Made `Q.promise` throw early if given a non-function.
|
||||
|
||||
## 0.9.2
|
||||
|
||||
- Pass through progress notifications when using `timeout`. #229 @omares
|
||||
- Pass through progress notifications when using `delay`.
|
||||
- Fix `nbind` to actually bind the `thisArg`. #232 @davidpadbury
|
||||
|
||||
## 0.9.1
|
||||
|
||||
- Made the AMD detection compatible with the RequireJS optimizer's `namespace`
|
||||
option. #225 @terinjokes
|
||||
- Fix side effects from `valueOf`, and thus from `isFulfilled`, `isRejected`,
|
||||
and `isPending`. #226 @benjamn
|
||||
|
||||
## 0.9.0
|
||||
|
||||
This release removes many layers of deprecated methods and brings Q closer to
|
||||
alignment with Mark Miller’s TC39 [strawman][] for concurrency. At the same
|
||||
time, it fixes many bugs and adds a few features around error handling. Finally,
|
||||
it comes with an updated and comprehensive [API Reference][].
|
||||
|
||||
[strawman]: http://wiki.ecmascript.org/doku.php?id=strawman:concurrency
|
||||
[API Reference]: https://github.com/kriskowal/q/wiki/API-Reference
|
||||
|
||||
### API Cleanup
|
||||
|
||||
The following deprecated or undocumented methods have been removed.
|
||||
Their replacements are listed here:
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>0.8.x method</th>
|
||||
<th>0.9 replacement</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><code>Q.ref</code></td>
|
||||
<td><code>Q</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>call</code>, <code>apply</code>, <code>bind</code> (*)</td>
|
||||
<td><code>fcall</code>/<code>invoke</code>, <code>fapply</code>/<code>post</code>, <code>fbind</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>ncall</code>, <code>napply</code> (*)</td>
|
||||
<td><code>nfcall</code>/<code>ninvoke</code>, <code>nfapply</code>/<code>npost</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>end</code></td>
|
||||
<td><code>done</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>put</code></td>
|
||||
<td><code>set</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>node</code></td>
|
||||
<td><code>nbind</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>nend</code></td>
|
||||
<td><code>nodeify</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>isResolved</code></td>
|
||||
<td><code>isPending</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>deferred.node</code></td>
|
||||
<td><code>deferred.makeNodeResolver</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Method</code>, <code>sender</code></td>
|
||||
<td><code>dispatcher</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>send</code></td>
|
||||
<td><code>dispatch</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>view</code>, <code>viewInfo</code></td>
|
||||
<td>(none)</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
|
||||
(*) Use of ``thisp`` is discouraged. For calling methods, use ``post`` or
|
||||
``invoke``.
|
||||
|
||||
### Alignment with the Concurrency Strawman
|
||||
|
||||
- Q now exports a `Q(value)` function, an alias for `resolve`.
|
||||
`Q.call`, `Q.apply`, and `Q.bind` were removed to make room for the
|
||||
same methods on the function prototype.
|
||||
- `invoke` has been aliased to `send` in all its forms.
|
||||
- `post` with no method name acts like `fapply`.
|
||||
|
||||
### Error Handling
|
||||
|
||||
- Long stack traces can be turned off by setting `Q.stackJumpLimit` to zero.
|
||||
In the future, this property will be used to fine tune how many stack jumps
|
||||
are retained in long stack traces; for now, anything nonzero is treated as
|
||||
one (since Q only tracks one stack jump at the moment, see #144). #168
|
||||
- In Node.js, if there are unhandled rejections when the process exits, they
|
||||
are output to the console. #115
|
||||
|
||||
### Other
|
||||
|
||||
- `delete` and `set` (née `put`) no longer have a fulfillment value.
|
||||
- Q promises are no longer frozen, which
|
||||
[helps with performance](http://code.google.com/p/v8/issues/detail?id=1858).
|
||||
- `thenReject` is now included, as a counterpart to `thenResolve`.
|
||||
- The included browser `nextTick` shim is now faster. #195 @rkatic.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- Q now works in Internet Explorer 10. #186 @ForbesLindesay
|
||||
- `fbind` no longer hard-binds the returned function's `this` to `undefined`.
|
||||
#202
|
||||
- `Q.reject` no longer leaks memory. #148
|
||||
- `npost` with no arguments now works. #207
|
||||
- `allResolved` now works with non-Q promises ("thenables"). #179
|
||||
- `keys` behavior is now correct even in browsers without native
|
||||
`Object.keys`. #192 @rkatic
|
||||
- `isRejected` and the `exception` property now work correctly if the
|
||||
rejection reason is falsy. #198
|
||||
|
||||
### Internals and Advanced
|
||||
|
||||
- The internal interface for a promise now uses
|
||||
`dispatchPromise(resolve, op, operands)` instead of `sendPromise(op,
|
||||
resolve, ...operands)`, which reduces the cases where Q needs to do
|
||||
argument slicing.
|
||||
- The internal protocol uses different operands. "put" is now "set".
|
||||
"del" is now "delete". "view" and "viewInfo" have been removed.
|
||||
- `Q.fulfill` has been added. It is distinct from `Q.resolve` in that
|
||||
it does not pass promises through, nor coerces promises from other
|
||||
systems. The promise becomes the fulfillment value. This is only
|
||||
recommended for use when trying to fulfill a promise with an object that has
|
||||
a `then` function that is at the same time not a promise.
|
||||
|
||||
## 0.8.12
|
||||
- Treat foreign promises as unresolved in `Q.isFulfilled`; this lets `Q.all`
|
||||
work on arrays containing foreign promises. #154
|
||||
- Fix minor incompliances with the [Promises/A+ spec][] and [test suite][]. #157
|
||||
#158
|
||||
|
||||
[Promises/A+ spec]: http://promises-aplus.github.com/promises-spec/
|
||||
[test suite]: https://github.com/promises-aplus/promises-tests
|
||||
|
||||
## 0.8.11
|
||||
|
||||
- Added ``nfcall``, ``nfapply``, and ``nfbind`` as ``thisp``-less versions of
|
||||
``ncall``, ``napply``, and ``nbind``. The latter are now deprecated. #142
|
||||
- Long stack traces no longer cause linearly-growing memory usage when chaining
|
||||
promises together. #111
|
||||
- Inspecting ``error.stack`` in a rejection handler will now give a long stack
|
||||
trace. #103
|
||||
- Fixed ``Q.timeout`` to clear its timeout handle when the promise is rejected;
|
||||
previously, it kept the event loop alive until the timeout period expired.
|
||||
#145 @dfilatov
|
||||
- Added `q/queue` module, which exports an infinite promise queue
|
||||
constructor.
|
||||
|
||||
## 0.8.10
|
||||
|
||||
- Added ``done`` as a replacement for ``end``, taking the usual fulfillment,
|
||||
rejection, and progress handlers. It's essentially equivalent to
|
||||
``then(f, r, p).end()``.
|
||||
- Added ``Q.onerror``, a settable error trap that you can use to get full stack
|
||||
traces for uncaught errors. #94
|
||||
- Added ``thenResolve`` as a shortcut for returning a constant value once a
|
||||
promise is fulfilled. #108 @ForbesLindesay
|
||||
- Various tweaks to progress notification, including propagation and
|
||||
transformation of progress values and only forwarding a single progress
|
||||
object.
|
||||
- Renamed ``nend`` to ``nodeify``. It no longer returns an always-fulfilled
|
||||
promise when a Node callback is passed.
|
||||
- ``deferred.resolve`` and ``deferred.reject`` no longer (sometimes) return
|
||||
``deferred.promise``.
|
||||
- Fixed stack traces getting mangled if they hit ``end`` twice. #116 #121 @ef4
|
||||
- Fixed ``ninvoke`` and ``npost`` to work on promises for objects with Node
|
||||
methods. #134
|
||||
- Fixed accidental coercion of objects with nontrivial ``valueOf`` methods,
|
||||
like ``Date``s, by the promise's ``valueOf`` method. #135
|
||||
- Fixed ``spread`` not calling the passed rejection handler if given a rejected
|
||||
promise.
|
||||
|
||||
## 0.8.9
|
||||
|
||||
- Added ``nend``
|
||||
- Added preliminary progress notification support, via
|
||||
``promise.then(onFulfilled, onRejected, onProgress)``,
|
||||
``promise.progress(onProgress)``, and ``deferred.notify(...progressData)``.
|
||||
- Made ``put`` and ``del`` return the object acted upon for easier chaining.
|
||||
#84
|
||||
- Fixed coercion cycles with cooperating promises. #106
|
||||
|
||||
## 0.8.7
|
||||
|
||||
- Support [Montage Require](http://github.com/kriskowal/mr)
|
||||
|
||||
## 0.8.6
|
||||
|
||||
- Fixed ``npost`` and ``ninvoke`` to pass the correct ``thisp``. #74
|
||||
- Fixed various cases involving unorthodox rejection reasons. #73 #90
|
||||
@ef4
|
||||
- Fixed double-resolving of misbehaved custom promises. #75
|
||||
- Sped up ``Q.all`` for arrays contain already-resolved promises or scalar
|
||||
values. @ForbesLindesay
|
||||
- Made stack trace filtering work when concatenating assets. #93 @ef4
|
||||
- Added warnings for deprecated methods. @ForbesLindesay
|
||||
- Added ``.npmignore`` file so that dependent packages get a slimmer
|
||||
``node_modules`` directory.
|
||||
|
||||
## 0.8.5
|
||||
|
||||
- Added preliminary support for long traces (@domenic)
|
||||
- Added ``fapply``, ``fcall``, ``fbind`` for non-thisp
|
||||
promised function calls.
|
||||
- Added ``return`` for async generators, where generators
|
||||
are implemented.
|
||||
- Rejected promises now have an "exception" property. If an object
|
||||
isRejected(object), then object.valueOf().exception will
|
||||
be the wrapped error.
|
||||
- Added Jasmine specifications
|
||||
- Support Internet Explorers 7–9 (with multiple bug fixes @domenic)
|
||||
- Support Firefox 12
|
||||
- Support Safari 5.1.5
|
||||
- Support Chrome 18
|
||||
|
||||
## 0.8.4
|
||||
|
||||
- WARNING: ``promise.timeout`` is now rejected with an ``Error`` object
|
||||
and the message now includes the duration of the timeout in
|
||||
miliseconds. This doesn't constitute (in my opinion) a
|
||||
backward-incompatibility since it is a change of an undocumented and
|
||||
unspecified public behavior, but if you happened to depend on the
|
||||
exception being a string, you will need to revise your code.
|
||||
- Added ``deferred.makeNodeResolver()`` to replace the more cryptic
|
||||
``deferred.node()`` method.
|
||||
- Added experimental ``Q.promise(maker(resolve, reject))`` to make a
|
||||
promise inside a callback, such that thrown exceptions in the
|
||||
callback are converted and the resolver and rejecter are arguments.
|
||||
This is a shorthand for making a deferred directly and inspired by
|
||||
@gozala’s stream constructor pattern and the Microsoft Windows Metro
|
||||
Promise constructor interface.
|
||||
- Added experimental ``Q.begin()`` that is intended to kick off chains
|
||||
of ``.then`` so that each of these can be reordered without having to
|
||||
edit the new and former first step.
|
||||
|
||||
## 0.8.3
|
||||
|
||||
- Added ``isFulfilled``, ``isRejected``, and ``isResolved``
|
||||
to the promise prototype.
|
||||
- Added ``allResolved`` for waiting for every promise to either be
|
||||
fulfilled or rejected, without propagating an error. @utvara #53
|
||||
- Added ``Q.bind`` as a method to transform functions that
|
||||
return and throw into promise-returning functions. See
|
||||
[an example](https://gist.github.com/1782808). @domenic
|
||||
- Renamed ``node`` export to ``nbind``, and added ``napply`` to
|
||||
complete the set. ``node`` remains as deprecated. @domenic #58
|
||||
- Renamed ``Method`` export to ``sender``. ``Method``
|
||||
remains as deprecated and will be removed in the next
|
||||
major version since I expect it has very little usage.
|
||||
- Added browser console message indicating a live list of
|
||||
unhandled errors.
|
||||
- Added support for ``msSetImmediate`` (IE10) or ``setImmediate``
|
||||
(available via [polyfill](https://github.com/NobleJS/setImmediate))
|
||||
as a browser-side ``nextTick`` implementation. #44 #50 #59
|
||||
- Stopped using the event-queue dependency, which was in place for
|
||||
Narwhal support: now directly using ``process.nextTick``.
|
||||
- WARNING: EXPERIMENTAL: added ``finally`` alias for ``fin``, ``catch``
|
||||
alias for ``fail``, ``try`` alias for ``call``, and ``delete`` alias
|
||||
for ``del``. These properties are enquoted in the library for
|
||||
cross-browser compatibility, but may be used as property names in
|
||||
modern engines.
|
||||
|
||||
## 0.8.2
|
||||
|
||||
- Deprecated ``ref`` in favor of ``resolve`` as recommended by
|
||||
@domenic.
|
||||
- Update event-queue dependency.
|
||||
|
||||
## 0.8.1
|
||||
|
||||
- Fixed Opera bug. #35 @cadorn
|
||||
- Fixed ``Q.all([])`` #32 @domenic
|
||||
|
||||
## 0.8.0
|
||||
|
||||
- WARNING: ``enqueue`` removed. Use ``nextTick`` instead.
|
||||
This is more consistent with NodeJS and (subjectively)
|
||||
more explicit and intuitive.
|
||||
- WARNING: ``def`` removed. Use ``master`` instead. The
|
||||
term ``def`` was too confusing to new users.
|
||||
- WARNING: ``spy`` removed in favor of ``fin``.
|
||||
- WARNING: ``wait`` removed. Do ``all(args).get(0)`` instead.
|
||||
- WARNING: ``join`` removed. Do ``all(args).spread(callback)`` instead.
|
||||
- WARNING: Removed the ``Q`` function module.exports alias
|
||||
for ``Q.ref``. It conflicts with ``Q.apply`` in weird
|
||||
ways, making it uncallable.
|
||||
- Revised ``delay`` so that it accepts both ``(value,
|
||||
timeout)`` and ``(timeout)`` variations based on
|
||||
arguments length.
|
||||
- Added ``ref().spread(cb(...args))``, a variant of
|
||||
``then`` that spreads an array across multiple arguments.
|
||||
Useful with ``all()``.
|
||||
- Added ``defer().node()`` Node callback generator. The
|
||||
callback accepts ``(error, value)`` or ``(error,
|
||||
...values)``. For multiple value arguments, the
|
||||
fulfillment value is an array, useful in conjunction with
|
||||
``spread``.
|
||||
- Added ``node`` and ``ncall``, both with the signature
|
||||
``(fun, thisp_opt, ...args)``. The former is a decorator
|
||||
and the latter calls immediately. ``node`` optional
|
||||
binds and partially applies. ``ncall`` can bind and pass
|
||||
arguments.
|
||||
|
||||
## 0.7.2
|
||||
|
||||
- Fixed thenable promise assimilation.
|
||||
|
||||
## 0.7.1
|
||||
|
||||
- Stopped shimming ``Array.prototype.reduce``. The
|
||||
enumerable property has bad side-effects. Libraries that
|
||||
depend on this (for example, QQ) will need to be revised.
|
||||
|
||||
## 0.7.0 - BACKWARD INCOMPATIBILITY
|
||||
|
||||
- WARNING: Removed ``report`` and ``asap``
|
||||
- WARNING: The ``callback`` argument of the ``fin``
|
||||
function no longer receives any arguments. Thus, it can
|
||||
be used to call functions that should not receive
|
||||
arguments on resolution. Use ``when``, ``then``, or
|
||||
``fail`` if you need a value.
|
||||
- IMPORTANT: Fixed a bug in the use of ``MessageChannel``
|
||||
for ``nextTick``.
|
||||
- Renamed ``enqueue`` to ``nextTick``.
|
||||
- Added experimental ``view`` and ``viewInfo`` for creating
|
||||
views of promises either when or before they're
|
||||
fulfilled.
|
||||
- Shims are now externally applied so subsequent scripts or
|
||||
dependees can use them.
|
||||
- Improved minification results.
|
||||
- Improved readability.
|
||||
|
||||
## 0.6.0 - BACKWARD INCOMPATIBILITY
|
||||
|
||||
- WARNING: In practice, the implementation of ``spy`` and
|
||||
the name ``fin`` were useful. I've removed the old
|
||||
``fin`` implementation and renamed/aliased ``spy``.
|
||||
- The "q" module now exports its ``ref`` function as a "Q"
|
||||
constructor, with module systems that support exports
|
||||
assignment including NodeJS, RequireJS, and when used as
|
||||
a ``<script>`` tag. Notably, strictly compliant CommonJS
|
||||
does not support this, but UncommonJS does.
|
||||
- Added ``async`` decorator for generators that use yield
|
||||
to "trampoline" promises. In engines that support
|
||||
generators (SpiderMonkey), this will greatly reduce the
|
||||
need for nested callbacks.
|
||||
- Made ``when`` chainable.
|
||||
- Made ``all`` chainable.
|
||||
|
||||
## 0.5.3
|
||||
|
||||
- Added ``all`` and refactored ``join`` and ``wait`` to use
|
||||
it. All of these will now reject at the earliest
|
||||
rejection.
|
||||
|
||||
## 0.5.2
|
||||
|
||||
- Minor improvement to ``spy``; now waits for resolution of
|
||||
callback promise.
|
||||
|
||||
## 0.5.1
|
||||
|
||||
- Made most Q API methods chainable on promise objects, and
|
||||
turned the previous promise-methods of ``join``,
|
||||
``wait``, and ``report`` into Q API methods.
|
||||
- Added ``apply`` and ``call`` to the Q API, and ``apply``
|
||||
as a promise handler.
|
||||
- Added ``fail``, ``fin``, and ``spy`` to Q and the promise
|
||||
prototype for convenience when observing rejection,
|
||||
fulfillment and rejection, or just observing without
|
||||
affecting the resolution.
|
||||
- Renamed ``def`` (although ``def`` remains shimmed until
|
||||
the next major release) to ``master``.
|
||||
- Switched to using ``MessageChannel`` for next tick task
|
||||
enqueue in browsers that support it.
|
||||
|
||||
## 0.5.0 - MINOR BACKWARD INCOMPATIBILITY
|
||||
|
||||
- Exceptions are no longer reported when consumed.
|
||||
- Removed ``error`` from the API. Since exceptions are
|
||||
getting consumed, throwing them in an errback causes the
|
||||
exception to silently disappear. Use ``end``.
|
||||
- Added ``end`` as both an API method and a promise-chain
|
||||
ending method. It causes propagated rejections to be
|
||||
thrown, which allows Node to write stack traces and
|
||||
emit ``uncaughtException`` events, and browsers to
|
||||
likewise emit ``onerror`` and log to the console.
|
||||
- Added ``join`` and ``wait`` as promise chain functions,
|
||||
so you can wait for variadic promises, returning your own
|
||||
promise back, or join variadic promises, resolving with a
|
||||
callback that receives variadic fulfillment values.
|
||||
|
||||
## 0.4.4
|
||||
|
||||
- ``end`` no longer returns a promise. It is the end of the
|
||||
promise chain.
|
||||
- Stopped reporting thrown exceptions in ``when`` callbacks
|
||||
and errbacks. These must be explicitly reported through
|
||||
``.end()``, ``.then(null, Q.error)``, or some other
|
||||
mechanism.
|
||||
- Added ``report`` as an API method, which can be used as
|
||||
an errback to report and propagate an error.
|
||||
- Added ``report`` as a promise-chain method, so an error
|
||||
can be reported if it passes such a gate.
|
||||
|
||||
## 0.4.3
|
||||
|
||||
- Fixed ``<script>`` support that regressed with 0.4.2
|
||||
because of "use strict" in the module system
|
||||
multi-plexer.
|
||||
|
||||
## 0.4.2
|
||||
|
||||
- Added support for RequireJS (jburke)
|
||||
|
||||
## 0.4.1
|
||||
|
||||
- Added an "end" method to the promise prototype,
|
||||
as a shorthand for waiting for the promise to
|
||||
be resolved gracefully, and failing to do so,
|
||||
to dump an error message.
|
||||
|
||||
## 0.4.0 - BACKWARD INCOMPATIBLE*
|
||||
|
||||
- *Removed the utility modules. NPM and Node no longer
|
||||
expose any module except the main module. These have
|
||||
been moved and merged into the "qq" package.
|
||||
- *In a non-CommonJS browser, q.js can be used as a script.
|
||||
It now creates a Q global variable.
|
||||
- Fixed thenable assimilation.
|
||||
- Fixed some issues with asap, when it resolves to
|
||||
undefined, or throws an exception.
|
||||
|
||||
## 0.3.0 - BACKWARD-INCOMPATIBLE
|
||||
|
||||
- The `post` method has been reverted to its original
|
||||
signature, as provided in Tyler Close's `ref_send` API.
|
||||
That is, `post` accepts two arguments, the second of
|
||||
which is an arbitrary object, but usually invocation
|
||||
arguments as an `Array`. To provide variadic arguments
|
||||
to `post`, there is a new `invoke` function that posts
|
||||
the variadic arguments to the value given in the first
|
||||
argument.
|
||||
- The `defined` method has been moved from `q` to `q/util`
|
||||
since it gets no use in practice but is still
|
||||
theoretically useful.
|
||||
- The `Promise` constructor has been renamed to
|
||||
`makePromise` to be consistent with the convention that
|
||||
functions that do not require the `new` keyword to be
|
||||
used as constructors have camelCase names.
|
||||
- The `isResolved` function has been renamed to
|
||||
`isFulfilled`. There is a new `isResolved` function that
|
||||
indicates whether a value is not a promise or, if it is a
|
||||
promise, whether it has been either fulfilled or
|
||||
rejected. The code has been revised to reflect this
|
||||
nuance in terminology.
|
||||
|
||||
## 0.2.10
|
||||
|
||||
- Added `join` to `"q/util"` for variadically joining
|
||||
multiple promises.
|
||||
|
||||
## 0.2.9
|
||||
|
||||
- The future-compatible `invoke` method has been added,
|
||||
to replace `post`, since `post` will become backward-
|
||||
incompatible in the next major release.
|
||||
- Exceptions thrown in the callbacks of a `when` call are
|
||||
now emitted to Node's `"uncaughtException"` `process`
|
||||
event in addition to being returned as a rejection reason.
|
||||
|
||||
## 0.2.8
|
||||
|
||||
- Exceptions thrown in the callbacks of a `when` call
|
||||
are now consumed, warned, and transformed into
|
||||
rejections of the promise returned by `when`.
|
||||
|
||||
## 0.2.7
|
||||
|
||||
- Fixed a minor bug in thenable assimilation, regressed
|
||||
because of the change in the forwarding protocol.
|
||||
- Fixed behavior of "q/util" `deep` method on dates and
|
||||
other primitives. Github issue #11.
|
||||
|
||||
## 0.2.6
|
||||
|
||||
- Thenables (objects with a "then" method) are accepted
|
||||
and provided, bringing this implementation of Q
|
||||
into conformance with Promises/A, B, and D.
|
||||
- Added `makePromise`, to replace the `Promise` function
|
||||
eventually.
|
||||
- Rejections are now also duck-typed. A rejection is a
|
||||
promise with a valueOf method that returns a rejection
|
||||
descriptor. A rejection descriptor has a
|
||||
"promiseRejected" property equal to "true" and a
|
||||
"reason" property corresponding to the rejection reason.
|
||||
- Altered the `makePromise` API such that the `fallback`
|
||||
method no longer receives a superfluous `resolved` method
|
||||
after the `operator`. The fallback method is responsible
|
||||
only for returning a resolution. This breaks an
|
||||
undocumented API, so third-party API's depending on the
|
||||
previous undocumented behavior may break.
|
||||
|
||||
## 0.2.5
|
||||
|
||||
- Changed promises into a duck-type such that multiple
|
||||
instances of the Q module can exchange promise objects.
|
||||
A promise is now defined as "an object that implements the
|
||||
`promiseSend(op, resolved, ...)` method and `valueOf`".
|
||||
- Exceptions in promises are now captured and returned
|
||||
as rejections.
|
||||
|
||||
## 0.2.4
|
||||
|
||||
- Fixed bug in `ref` that prevented `del` messages from
|
||||
being received (gozala)
|
||||
- Fixed a conflict with FireFox 4; constructor property
|
||||
is now read-only.
|
||||
|
||||
## 0.2.3
|
||||
|
||||
- Added `keys` message to promises and to the promise API.
|
||||
|
||||
## 0.2.2
|
||||
|
||||
- Added boilerplate to `q/queue` and `q/util`.
|
||||
- Fixed missing dependency to `q/queue`.
|
||||
|
||||
## 0.2.1
|
||||
|
||||
- The `resolve` and `reject` methods of `defer` objects now
|
||||
return the resolution promise for convenience.
|
||||
- Added `q/util`, which provides `step`, `delay`, `shallow`,
|
||||
`deep`, and three reduction orders.
|
||||
- Added `q/queue` module for a promise `Queue`.
|
||||
- Added `q-comm` to the list of compatible libraries.
|
||||
- Deprecated `defined` from `q`, with intent to move it to
|
||||
`q/util`.
|
||||
|
||||
## 0.2.0 - BACKWARD INCOMPATIBLE
|
||||
|
||||
- Changed post(ref, name, args) to variadic
|
||||
post(ref, name, ...args). BACKWARD INCOMPATIBLE
|
||||
- Added a def(value) method to annotate an object as being
|
||||
necessarily a local value that cannot be serialized, such
|
||||
that inter-process/worker/vat promise communication
|
||||
libraries will send messages to it, but never send it
|
||||
back.
|
||||
- Added a send(value, op, ...args) method to the public API, for
|
||||
forwarding messages to a value or promise in a future turn.
|
||||
|
||||
## 0.1.9
|
||||
|
||||
- Added isRejected() for testing whether a value is a rejected
|
||||
promise. isResolved() retains the behavior of stating
|
||||
that rejected promises are not resolved.
|
||||
|
||||
## 0.1.8
|
||||
|
||||
- Fixed isResolved(null) and isResolved(undefined) [issue #9]
|
||||
- Fixed a problem with the Object.create shim
|
||||
|
||||
## 0.1.7
|
||||
|
||||
- shimmed ES5 Object.create in addition to Object.freeze
|
||||
for compatibility on non-ES5 engines (gozala)
|
||||
|
||||
## 0.1.6
|
||||
|
||||
- Q.isResolved added
|
||||
- promise.valueOf() now returns the value of resolved
|
||||
and near values
|
||||
- asap retried
|
||||
- promises are frozen when possible
|
||||
|
||||
## 0.1.5
|
||||
|
||||
- fixed dependency list for Teleport (gozala)
|
||||
- all unit tests now pass (gozala)
|
||||
|
||||
## 0.1.4
|
||||
|
||||
- added support for Teleport as an engine (gozala)
|
||||
- simplified and updated methods for getting internal
|
||||
print and enqueue functions universally (gozala)
|
||||
|
||||
## 0.1.3
|
||||
|
||||
- fixed erroneous link to the q module in package.json
|
||||
|
||||
## 0.1.2
|
||||
|
||||
- restructured for overlay style package compatibility
|
||||
|
||||
## 0.1.0
|
||||
|
||||
- removed asap because it was broken, probably down to the
|
||||
philosophy.
|
||||
|
||||
## 0.0.3
|
||||
|
||||
- removed q-util
|
||||
- fixed asap so it returns a value if completed
|
||||
|
||||
## 0.0.2
|
||||
|
||||
- added q-util
|
||||
|
||||
## 0.0.1
|
||||
|
||||
- initial version
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
Copyright 2009–2014 Kristopher Michael Kowal. All rights reserved.
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to
|
||||
deal in the Software without restriction, including without limitation the
|
||||
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
sell copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
IN THE SOFTWARE.
|
||||
+881
@@ -0,0 +1,881 @@
|
||||
[](http://travis-ci.org/kriskowal/q)
|
||||
|
||||
<a href="http://promises-aplus.github.com/promises-spec">
|
||||
<img src="http://kriskowal.github.io/q/q.png"
|
||||
align="right" alt="Q logo" />
|
||||
</a>
|
||||
|
||||
*This is Q version 1, from the `v1` branch in Git. This documentation applies to
|
||||
the latest of both the version 1 and version 0.9 release trains. These releases
|
||||
are stable. There will be no further releases of 0.9 after 0.9.7 which is nearly
|
||||
equivalent to version 1.0.0. All further releases of `q@~1.0` will be backward
|
||||
compatible. The version 2 release train introduces significant and
|
||||
backward-incompatible changes and is experimental at this time.*
|
||||
|
||||
If a function cannot return a value or throw an exception without
|
||||
blocking, it can return a promise instead. A promise is an object
|
||||
that represents the return value or the thrown exception that the
|
||||
function may eventually provide. A promise can also be used as a
|
||||
proxy for a [remote object][Q-Connection] to overcome latency.
|
||||
|
||||
[Q-Connection]: https://github.com/kriskowal/q-connection
|
||||
|
||||
On the first pass, promises can mitigate the “[Pyramid of
|
||||
Doom][POD]”: the situation where code marches to the right faster
|
||||
than it marches forward.
|
||||
|
||||
[POD]: http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/
|
||||
|
||||
```javascript
|
||||
step1(function (value1) {
|
||||
step2(value1, function(value2) {
|
||||
step3(value2, function(value3) {
|
||||
step4(value3, function(value4) {
|
||||
// Do something with value4
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
With a promise library, you can flatten the pyramid.
|
||||
|
||||
```javascript
|
||||
Q.fcall(promisedStep1)
|
||||
.then(promisedStep2)
|
||||
.then(promisedStep3)
|
||||
.then(promisedStep4)
|
||||
.then(function (value4) {
|
||||
// Do something with value4
|
||||
})
|
||||
.catch(function (error) {
|
||||
// Handle any error from all above steps
|
||||
})
|
||||
.done();
|
||||
```
|
||||
|
||||
With this approach, you also get implicit error propagation, just like `try`,
|
||||
`catch`, and `finally`. An error in `promisedStep1` will flow all the way to
|
||||
the `catch` function, where it’s caught and handled. (Here `promisedStepN` is
|
||||
a version of `stepN` that returns a promise.)
|
||||
|
||||
The callback approach is called an “inversion of control”.
|
||||
A function that accepts a callback instead of a return value
|
||||
is saying, “Don’t call me, I’ll call you.”. Promises
|
||||
[un-invert][IOC] the inversion, cleanly separating the input
|
||||
arguments from control flow arguments. This simplifies the
|
||||
use and creation of API’s, particularly variadic,
|
||||
rest and spread arguments.
|
||||
|
||||
[IOC]: http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript
|
||||
|
||||
|
||||
## Getting Started
|
||||
|
||||
The Q module can be loaded as:
|
||||
|
||||
- A ``<script>`` tag (creating a ``Q`` global variable): ~2.5 KB minified and
|
||||
gzipped.
|
||||
- A Node.js and CommonJS module, available in [npm](https://npmjs.org/) as
|
||||
the [q](https://npmjs.org/package/q) package
|
||||
- An AMD module
|
||||
- A [component](https://github.com/component/component) as ``microjs/q``
|
||||
- Using [bower](http://bower.io/) as `q#1.0.1`
|
||||
- Using [NuGet](http://nuget.org/) as [Q](https://nuget.org/packages/q)
|
||||
|
||||
Q can exchange promises with jQuery, Dojo, When.js, WinJS, and more.
|
||||
|
||||
## Resources
|
||||
|
||||
Our [wiki][] contains a number of useful resources, including:
|
||||
|
||||
- A method-by-method [Q API reference][reference].
|
||||
- A growing [examples gallery][examples], showing how Q can be used to make
|
||||
everything better. From XHR to database access to accessing the Flickr API,
|
||||
Q is there for you.
|
||||
- There are many libraries that produce and consume Q promises for everything
|
||||
from file system/database access or RPC to templating. For a list of some of
|
||||
the more popular ones, see [Libraries][].
|
||||
- If you want materials that introduce the promise concept generally, and the
|
||||
below tutorial isn't doing it for you, check out our collection of
|
||||
[presentations, blog posts, and podcasts][resources].
|
||||
- A guide for those [coming from jQuery's `$.Deferred`][jquery].
|
||||
|
||||
We'd also love to have you join the Q-Continuum [mailing list][].
|
||||
|
||||
[wiki]: https://github.com/kriskowal/q/wiki
|
||||
[reference]: https://github.com/kriskowal/q/wiki/API-Reference
|
||||
[examples]: https://github.com/kriskowal/q/wiki/Examples-Gallery
|
||||
[Libraries]: https://github.com/kriskowal/q/wiki/Libraries
|
||||
[resources]: https://github.com/kriskowal/q/wiki/General-Promise-Resources
|
||||
[jquery]: https://github.com/kriskowal/q/wiki/Coming-from-jQuery
|
||||
[mailing list]: https://groups.google.com/forum/#!forum/q-continuum
|
||||
|
||||
|
||||
## Tutorial
|
||||
|
||||
Promises have a ``then`` method, which you can use to get the eventual
|
||||
return value (fulfillment) or thrown exception (rejection).
|
||||
|
||||
```javascript
|
||||
promiseMeSomething()
|
||||
.then(function (value) {
|
||||
}, function (reason) {
|
||||
});
|
||||
```
|
||||
|
||||
If ``promiseMeSomething`` returns a promise that gets fulfilled later
|
||||
with a return value, the first function (the fulfillment handler) will be
|
||||
called with the value. However, if the ``promiseMeSomething`` function
|
||||
gets rejected later by a thrown exception, the second function (the
|
||||
rejection handler) will be called with the exception.
|
||||
|
||||
Note that resolution of a promise is always asynchronous: that is, the
|
||||
fulfillment or rejection handler will always be called in the next turn of the
|
||||
event loop (i.e. `process.nextTick` in Node). This gives you a nice
|
||||
guarantee when mentally tracing the flow of your code, namely that
|
||||
``then`` will always return before either handler is executed.
|
||||
|
||||
In this tutorial, we begin with how to consume and work with promises. We'll
|
||||
talk about how to create them, and thus create functions like
|
||||
`promiseMeSomething` that return promises, [below](#the-beginning).
|
||||
|
||||
|
||||
### Propagation
|
||||
|
||||
The ``then`` method returns a promise, which in this example, I’m
|
||||
assigning to ``outputPromise``.
|
||||
|
||||
```javascript
|
||||
var outputPromise = getInputPromise()
|
||||
.then(function (input) {
|
||||
}, function (reason) {
|
||||
});
|
||||
```
|
||||
|
||||
The ``outputPromise`` variable becomes a new promise for the return
|
||||
value of either handler. Since a function can only either return a
|
||||
value or throw an exception, only one handler will ever be called and it
|
||||
will be responsible for resolving ``outputPromise``.
|
||||
|
||||
- If you return a value in a handler, ``outputPromise`` will get
|
||||
fulfilled.
|
||||
|
||||
- If you throw an exception in a handler, ``outputPromise`` will get
|
||||
rejected.
|
||||
|
||||
- If you return a **promise** in a handler, ``outputPromise`` will
|
||||
“become” that promise. Being able to become a new promise is useful
|
||||
for managing delays, combining results, or recovering from errors.
|
||||
|
||||
If the ``getInputPromise()`` promise gets rejected and you omit the
|
||||
rejection handler, the **error** will go to ``outputPromise``:
|
||||
|
||||
```javascript
|
||||
var outputPromise = getInputPromise()
|
||||
.then(function (value) {
|
||||
});
|
||||
```
|
||||
|
||||
If the input promise gets fulfilled and you omit the fulfillment handler, the
|
||||
**value** will go to ``outputPromise``:
|
||||
|
||||
```javascript
|
||||
var outputPromise = getInputPromise()
|
||||
.then(null, function (error) {
|
||||
});
|
||||
```
|
||||
|
||||
Q promises provide a ``fail`` shorthand for ``then`` when you are only
|
||||
interested in handling the error:
|
||||
|
||||
```javascript
|
||||
var outputPromise = getInputPromise()
|
||||
.fail(function (error) {
|
||||
});
|
||||
```
|
||||
|
||||
If you are writing JavaScript for modern engines only or using
|
||||
CoffeeScript, you may use `catch` instead of `fail`.
|
||||
|
||||
Promises also have a ``fin`` function that is like a ``finally`` clause.
|
||||
The final handler gets called, with no arguments, when the promise
|
||||
returned by ``getInputPromise()`` either returns a value or throws an
|
||||
error. The value returned or error thrown by ``getInputPromise()``
|
||||
passes directly to ``outputPromise`` unless the final handler fails, and
|
||||
may be delayed if the final handler returns a promise.
|
||||
|
||||
```javascript
|
||||
var outputPromise = getInputPromise()
|
||||
.fin(function () {
|
||||
// close files, database connections, stop servers, conclude tests
|
||||
});
|
||||
```
|
||||
|
||||
- If the handler returns a value, the value is ignored
|
||||
- If the handler throws an error, the error passes to ``outputPromise``
|
||||
- If the handler returns a promise, ``outputPromise`` gets postponed. The
|
||||
eventual value or error has the same effect as an immediate return
|
||||
value or thrown error: a value would be ignored, an error would be
|
||||
forwarded.
|
||||
|
||||
If you are writing JavaScript for modern engines only or using
|
||||
CoffeeScript, you may use `finally` instead of `fin`.
|
||||
|
||||
### Chaining
|
||||
|
||||
There are two ways to chain promises. You can chain promises either
|
||||
inside or outside handlers. The next two examples are equivalent.
|
||||
|
||||
```javascript
|
||||
return getUsername()
|
||||
.then(function (username) {
|
||||
return getUser(username)
|
||||
.then(function (user) {
|
||||
// if we get here without an error,
|
||||
// the value returned here
|
||||
// or the exception thrown here
|
||||
// resolves the promise returned
|
||||
// by the first line
|
||||
})
|
||||
});
|
||||
```
|
||||
|
||||
```javascript
|
||||
return getUsername()
|
||||
.then(function (username) {
|
||||
return getUser(username);
|
||||
})
|
||||
.then(function (user) {
|
||||
// if we get here without an error,
|
||||
// the value returned here
|
||||
// or the exception thrown here
|
||||
// resolves the promise returned
|
||||
// by the first line
|
||||
});
|
||||
```
|
||||
|
||||
The only difference is nesting. It’s useful to nest handlers if you
|
||||
need to capture multiple input values in your closure.
|
||||
|
||||
```javascript
|
||||
function authenticate() {
|
||||
return getUsername()
|
||||
.then(function (username) {
|
||||
return getUser(username);
|
||||
})
|
||||
// chained because we will not need the user name in the next event
|
||||
.then(function (user) {
|
||||
return getPassword()
|
||||
// nested because we need both user and password next
|
||||
.then(function (password) {
|
||||
if (user.passwordHash !== hash(password)) {
|
||||
throw new Error("Can't authenticate");
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Combination
|
||||
|
||||
You can turn an array of promises into a promise for the whole,
|
||||
fulfilled array using ``all``.
|
||||
|
||||
```javascript
|
||||
return Q.all([
|
||||
eventualAdd(2, 2),
|
||||
eventualAdd(10, 20)
|
||||
]);
|
||||
```
|
||||
|
||||
If you have a promise for an array, you can use ``spread`` as a
|
||||
replacement for ``then``. The ``spread`` function “spreads” the
|
||||
values over the arguments of the fulfillment handler. The rejection handler
|
||||
will get called at the first sign of failure. That is, whichever of
|
||||
the received promises fails first gets handled by the rejection handler.
|
||||
|
||||
```javascript
|
||||
function eventualAdd(a, b) {
|
||||
return Q.spread([a, b], function (a, b) {
|
||||
return a + b;
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
But ``spread`` calls ``all`` initially, so you can skip it in chains.
|
||||
|
||||
```javascript
|
||||
return getUsername()
|
||||
.then(function (username) {
|
||||
return [username, getUser(username)];
|
||||
})
|
||||
.spread(function (username, user) {
|
||||
});
|
||||
```
|
||||
|
||||
The ``all`` function returns a promise for an array of values. When this
|
||||
promise is fulfilled, the array contains the fulfillment values of the original
|
||||
promises, in the same order as those promises. If one of the given promises
|
||||
is rejected, the returned promise is immediately rejected, not waiting for the
|
||||
rest of the batch. If you want to wait for all of the promises to either be
|
||||
fulfilled or rejected, you can use ``allSettled``.
|
||||
|
||||
```javascript
|
||||
Q.allSettled(promises)
|
||||
.then(function (results) {
|
||||
results.forEach(function (result) {
|
||||
if (result.state === "fulfilled") {
|
||||
var value = result.value;
|
||||
} else {
|
||||
var reason = result.reason;
|
||||
}
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
The ``any`` function accepts an array of promises and returns a promise that is
|
||||
fulfilled by the first given promise to be fulfilled, or rejected if all of the
|
||||
given promises are rejected.
|
||||
|
||||
```javascript
|
||||
Q.any(promises)
|
||||
.then(function (first) {
|
||||
// Any of the promises was fulfilled.
|
||||
}, function (error) {
|
||||
// All of the promises were rejected.
|
||||
});
|
||||
```
|
||||
|
||||
### Sequences
|
||||
|
||||
If you have a number of promise-producing functions that need
|
||||
to be run sequentially, you can of course do so manually:
|
||||
|
||||
```javascript
|
||||
return foo(initialVal).then(bar).then(baz).then(qux);
|
||||
```
|
||||
|
||||
However, if you want to run a dynamically constructed sequence of
|
||||
functions, you'll want something like this:
|
||||
|
||||
```javascript
|
||||
var funcs = [foo, bar, baz, qux];
|
||||
|
||||
var result = Q(initialVal);
|
||||
funcs.forEach(function (f) {
|
||||
result = result.then(f);
|
||||
});
|
||||
return result;
|
||||
```
|
||||
|
||||
You can make this slightly more compact using `reduce`:
|
||||
|
||||
```javascript
|
||||
return funcs.reduce(function (soFar, f) {
|
||||
return soFar.then(f);
|
||||
}, Q(initialVal));
|
||||
```
|
||||
|
||||
Or, you could use the ultra-compact version:
|
||||
|
||||
```javascript
|
||||
return funcs.reduce(Q.when, Q(initialVal));
|
||||
```
|
||||
|
||||
### Handling Errors
|
||||
|
||||
One sometimes-unintuive aspect of promises is that if you throw an
|
||||
exception in the fulfillment handler, it will not be caught by the error
|
||||
handler.
|
||||
|
||||
```javascript
|
||||
return foo()
|
||||
.then(function (value) {
|
||||
throw new Error("Can't bar.");
|
||||
}, function (error) {
|
||||
// We only get here if "foo" fails
|
||||
});
|
||||
```
|
||||
|
||||
To see why this is, consider the parallel between promises and
|
||||
``try``/``catch``. We are ``try``-ing to execute ``foo()``: the error
|
||||
handler represents a ``catch`` for ``foo()``, while the fulfillment handler
|
||||
represents code that happens *after* the ``try``/``catch`` block.
|
||||
That code then needs its own ``try``/``catch`` block.
|
||||
|
||||
In terms of promises, this means chaining your rejection handler:
|
||||
|
||||
```javascript
|
||||
return foo()
|
||||
.then(function (value) {
|
||||
throw new Error("Can't bar.");
|
||||
})
|
||||
.fail(function (error) {
|
||||
// We get here with either foo's error or bar's error
|
||||
});
|
||||
```
|
||||
|
||||
### Progress Notification
|
||||
|
||||
It's possible for promises to report their progress, e.g. for tasks that take a
|
||||
long time like a file upload. Not all promises will implement progress
|
||||
notifications, but for those that do, you can consume the progress values using
|
||||
a third parameter to ``then``:
|
||||
|
||||
```javascript
|
||||
return uploadFile()
|
||||
.then(function () {
|
||||
// Success uploading the file
|
||||
}, function (err) {
|
||||
// There was an error, and we get the reason for error
|
||||
}, function (progress) {
|
||||
// We get notified of the upload's progress as it is executed
|
||||
});
|
||||
```
|
||||
|
||||
Like `fail`, Q also provides a shorthand for progress callbacks
|
||||
called `progress`:
|
||||
|
||||
```javascript
|
||||
return uploadFile().progress(function (progress) {
|
||||
// We get notified of the upload's progress
|
||||
});
|
||||
```
|
||||
|
||||
### The End
|
||||
|
||||
When you get to the end of a chain of promises, you should either
|
||||
return the last promise or end the chain. Since handlers catch
|
||||
errors, it’s an unfortunate pattern that the exceptions can go
|
||||
unobserved.
|
||||
|
||||
So, either return it,
|
||||
|
||||
```javascript
|
||||
return foo()
|
||||
.then(function () {
|
||||
return "bar";
|
||||
});
|
||||
```
|
||||
|
||||
Or, end it.
|
||||
|
||||
```javascript
|
||||
foo()
|
||||
.then(function () {
|
||||
return "bar";
|
||||
})
|
||||
.done();
|
||||
```
|
||||
|
||||
Ending a promise chain makes sure that, if an error doesn’t get
|
||||
handled before the end, it will get rethrown and reported.
|
||||
|
||||
This is a stopgap. We are exploring ways to make unhandled errors
|
||||
visible without any explicit handling.
|
||||
|
||||
|
||||
### The Beginning
|
||||
|
||||
Everything above assumes you get a promise from somewhere else. This
|
||||
is the common case. Every once in a while, you will need to create a
|
||||
promise from scratch.
|
||||
|
||||
#### Using ``Q.fcall``
|
||||
|
||||
You can create a promise from a value using ``Q.fcall``. This returns a
|
||||
promise for 10.
|
||||
|
||||
```javascript
|
||||
return Q.fcall(function () {
|
||||
return 10;
|
||||
});
|
||||
```
|
||||
|
||||
You can also use ``fcall`` to get a promise for an exception.
|
||||
|
||||
```javascript
|
||||
return Q.fcall(function () {
|
||||
throw new Error("Can't do it");
|
||||
});
|
||||
```
|
||||
|
||||
As the name implies, ``fcall`` can call functions, or even promised
|
||||
functions. This uses the ``eventualAdd`` function above to add two
|
||||
numbers.
|
||||
|
||||
```javascript
|
||||
return Q.fcall(eventualAdd, 2, 2);
|
||||
```
|
||||
|
||||
|
||||
#### Using Deferreds
|
||||
|
||||
If you have to interface with asynchronous functions that are callback-based
|
||||
instead of promise-based, Q provides a few shortcuts (like ``Q.nfcall`` and
|
||||
friends). But much of the time, the solution will be to use *deferreds*.
|
||||
|
||||
```javascript
|
||||
var deferred = Q.defer();
|
||||
FS.readFile("foo.txt", "utf-8", function (error, text) {
|
||||
if (error) {
|
||||
deferred.reject(new Error(error));
|
||||
} else {
|
||||
deferred.resolve(text);
|
||||
}
|
||||
});
|
||||
return deferred.promise;
|
||||
```
|
||||
|
||||
Note that a deferred can be resolved with a value or a promise. The
|
||||
``reject`` function is a shorthand for resolving with a rejected
|
||||
promise.
|
||||
|
||||
```javascript
|
||||
// this:
|
||||
deferred.reject(new Error("Can't do it"));
|
||||
|
||||
// is shorthand for:
|
||||
var rejection = Q.fcall(function () {
|
||||
throw new Error("Can't do it");
|
||||
});
|
||||
deferred.resolve(rejection);
|
||||
```
|
||||
|
||||
This is a simplified implementation of ``Q.delay``.
|
||||
|
||||
```javascript
|
||||
function delay(ms) {
|
||||
var deferred = Q.defer();
|
||||
setTimeout(deferred.resolve, ms);
|
||||
return deferred.promise;
|
||||
}
|
||||
```
|
||||
|
||||
This is a simplified implementation of ``Q.timeout``
|
||||
|
||||
```javascript
|
||||
function timeout(promise, ms) {
|
||||
var deferred = Q.defer();
|
||||
Q.when(promise, deferred.resolve);
|
||||
delay(ms).then(function () {
|
||||
deferred.reject(new Error("Timed out"));
|
||||
});
|
||||
return deferred.promise;
|
||||
}
|
||||
```
|
||||
|
||||
Finally, you can send a progress notification to the promise with
|
||||
``deferred.notify``.
|
||||
|
||||
For illustration, this is a wrapper for XML HTTP requests in the browser. Note
|
||||
that a more [thorough][XHR] implementation would be in order in practice.
|
||||
|
||||
[XHR]: https://github.com/montagejs/mr/blob/71e8df99bb4f0584985accd6f2801ef3015b9763/browser.js#L29-L73
|
||||
|
||||
```javascript
|
||||
function requestOkText(url) {
|
||||
var request = new XMLHttpRequest();
|
||||
var deferred = Q.defer();
|
||||
|
||||
request.open("GET", url, true);
|
||||
request.onload = onload;
|
||||
request.onerror = onerror;
|
||||
request.onprogress = onprogress;
|
||||
request.send();
|
||||
|
||||
function onload() {
|
||||
if (request.status === 200) {
|
||||
deferred.resolve(request.responseText);
|
||||
} else {
|
||||
deferred.reject(new Error("Status code was " + request.status));
|
||||
}
|
||||
}
|
||||
|
||||
function onerror() {
|
||||
deferred.reject(new Error("Can't XHR " + JSON.stringify(url)));
|
||||
}
|
||||
|
||||
function onprogress(event) {
|
||||
deferred.notify(event.loaded / event.total);
|
||||
}
|
||||
|
||||
return deferred.promise;
|
||||
}
|
||||
```
|
||||
|
||||
Below is an example of how to use this ``requestOkText`` function:
|
||||
|
||||
```javascript
|
||||
requestOkText("http://localhost:3000")
|
||||
.then(function (responseText) {
|
||||
// If the HTTP response returns 200 OK, log the response text.
|
||||
console.log(responseText);
|
||||
}, function (error) {
|
||||
// If there's an error or a non-200 status code, log the error.
|
||||
console.error(error);
|
||||
}, function (progress) {
|
||||
// Log the progress as it comes in.
|
||||
console.log("Request progress: " + Math.round(progress * 100) + "%");
|
||||
});
|
||||
```
|
||||
|
||||
#### Using `Q.Promise`
|
||||
|
||||
This is an alternative promise-creation API that has the same power as
|
||||
the deferred concept, but without introducing another conceptual entity.
|
||||
|
||||
Rewriting the `requestOkText` example above using `Q.Promise`:
|
||||
|
||||
```javascript
|
||||
function requestOkText(url) {
|
||||
return Q.Promise(function(resolve, reject, notify) {
|
||||
var request = new XMLHttpRequest();
|
||||
|
||||
request.open("GET", url, true);
|
||||
request.onload = onload;
|
||||
request.onerror = onerror;
|
||||
request.onprogress = onprogress;
|
||||
request.send();
|
||||
|
||||
function onload() {
|
||||
if (request.status === 200) {
|
||||
resolve(request.responseText);
|
||||
} else {
|
||||
reject(new Error("Status code was " + request.status));
|
||||
}
|
||||
}
|
||||
|
||||
function onerror() {
|
||||
reject(new Error("Can't XHR " + JSON.stringify(url)));
|
||||
}
|
||||
|
||||
function onprogress(event) {
|
||||
notify(event.loaded / event.total);
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
If `requestOkText` were to throw an exception, the returned promise would be
|
||||
rejected with that thrown exception as the rejection reason.
|
||||
|
||||
### The Middle
|
||||
|
||||
If you are using a function that may return a promise, but just might
|
||||
return a value if it doesn’t need to defer, you can use the “static”
|
||||
methods of the Q library.
|
||||
|
||||
The ``when`` function is the static equivalent for ``then``.
|
||||
|
||||
```javascript
|
||||
return Q.when(valueOrPromise, function (value) {
|
||||
}, function (error) {
|
||||
});
|
||||
```
|
||||
|
||||
All of the other methods on a promise have static analogs with the
|
||||
same name.
|
||||
|
||||
The following are equivalent:
|
||||
|
||||
```javascript
|
||||
return Q.all([a, b]);
|
||||
```
|
||||
|
||||
```javascript
|
||||
return Q.fcall(function () {
|
||||
return [a, b];
|
||||
})
|
||||
.all();
|
||||
```
|
||||
|
||||
When working with promises provided by other libraries, you should
|
||||
convert it to a Q promise. Not all promise libraries make the same
|
||||
guarantees as Q and certainly don’t provide all of the same methods.
|
||||
Most libraries only provide a partially functional ``then`` method.
|
||||
This thankfully is all we need to turn them into vibrant Q promises.
|
||||
|
||||
```javascript
|
||||
return Q($.ajax(...))
|
||||
.then(function () {
|
||||
});
|
||||
```
|
||||
|
||||
If there is any chance that the promise you receive is not a Q promise
|
||||
as provided by your library, you should wrap it using a Q function.
|
||||
You can even use ``Q.invoke`` as a shorthand.
|
||||
|
||||
```javascript
|
||||
return Q.invoke($, 'ajax', ...)
|
||||
.then(function () {
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
### Over the Wire
|
||||
|
||||
A promise can serve as a proxy for another object, even a remote
|
||||
object. There are methods that allow you to optimistically manipulate
|
||||
properties or call functions. All of these interactions return
|
||||
promises, so they can be chained.
|
||||
|
||||
```
|
||||
direct manipulation using a promise as a proxy
|
||||
-------------------------- -------------------------------
|
||||
value.foo promise.get("foo")
|
||||
value.foo = value promise.put("foo", value)
|
||||
delete value.foo promise.del("foo")
|
||||
value.foo(...args) promise.post("foo", [args])
|
||||
value.foo(...args) promise.invoke("foo", ...args)
|
||||
value(...args) promise.fapply([args])
|
||||
value(...args) promise.fcall(...args)
|
||||
```
|
||||
|
||||
If the promise is a proxy for a remote object, you can shave
|
||||
round-trips by using these functions instead of ``then``. To take
|
||||
advantage of promises for remote objects, check out [Q-Connection][].
|
||||
|
||||
[Q-Connection]: https://github.com/kriskowal/q-connection
|
||||
|
||||
Even in the case of non-remote objects, these methods can be used as
|
||||
shorthand for particularly-simple fulfillment handlers. For example, you
|
||||
can replace
|
||||
|
||||
```javascript
|
||||
return Q.fcall(function () {
|
||||
return [{ foo: "bar" }, { foo: "baz" }];
|
||||
})
|
||||
.then(function (value) {
|
||||
return value[0].foo;
|
||||
});
|
||||
```
|
||||
|
||||
with
|
||||
|
||||
```javascript
|
||||
return Q.fcall(function () {
|
||||
return [{ foo: "bar" }, { foo: "baz" }];
|
||||
})
|
||||
.get(0)
|
||||
.get("foo");
|
||||
```
|
||||
|
||||
|
||||
### Adapting Node
|
||||
|
||||
If you're working with functions that make use of the Node.js callback pattern,
|
||||
where callbacks are in the form of `function(err, result)`, Q provides a few
|
||||
useful utility functions for converting between them. The most straightforward
|
||||
are probably `Q.nfcall` and `Q.nfapply` ("Node function call/apply") for calling
|
||||
Node.js-style functions and getting back a promise:
|
||||
|
||||
```javascript
|
||||
return Q.nfcall(FS.readFile, "foo.txt", "utf-8");
|
||||
return Q.nfapply(FS.readFile, ["foo.txt", "utf-8"]);
|
||||
```
|
||||
|
||||
If you are working with methods, instead of simple functions, you can easily
|
||||
run in to the usual problems where passing a method to another function—like
|
||||
`Q.nfcall`—"un-binds" the method from its owner. To avoid this, you can either
|
||||
use `Function.prototype.bind` or some nice shortcut methods we provide:
|
||||
|
||||
```javascript
|
||||
return Q.ninvoke(redisClient, "get", "user:1:id");
|
||||
return Q.npost(redisClient, "get", ["user:1:id"]);
|
||||
```
|
||||
|
||||
You can also create reusable wrappers with `Q.denodeify` or `Q.nbind`:
|
||||
|
||||
```javascript
|
||||
var readFile = Q.denodeify(FS.readFile);
|
||||
return readFile("foo.txt", "utf-8");
|
||||
|
||||
var redisClientGet = Q.nbind(redisClient.get, redisClient);
|
||||
return redisClientGet("user:1:id");
|
||||
```
|
||||
|
||||
Finally, if you're working with raw deferred objects, there is a
|
||||
`makeNodeResolver` method on deferreds that can be handy:
|
||||
|
||||
```javascript
|
||||
var deferred = Q.defer();
|
||||
FS.readFile("foo.txt", "utf-8", deferred.makeNodeResolver());
|
||||
return deferred.promise;
|
||||
```
|
||||
|
||||
### Long Stack Traces
|
||||
|
||||
Q comes with optional support for “long stack traces,” wherein the `stack`
|
||||
property of `Error` rejection reasons is rewritten to be traced along
|
||||
asynchronous jumps instead of stopping at the most recent one. As an example:
|
||||
|
||||
```js
|
||||
function theDepthsOfMyProgram() {
|
||||
Q.delay(100).done(function explode() {
|
||||
throw new Error("boo!");
|
||||
});
|
||||
}
|
||||
|
||||
theDepthsOfMyProgram();
|
||||
```
|
||||
|
||||
usually would give a rather unhelpful stack trace looking something like
|
||||
|
||||
```
|
||||
Error: boo!
|
||||
at explode (/path/to/test.js:3:11)
|
||||
at _fulfilled (/path/to/test.js:q:54)
|
||||
at resolvedValue.promiseDispatch.done (/path/to/q.js:823:30)
|
||||
at makePromise.promise.promiseDispatch (/path/to/q.js:496:13)
|
||||
at pending (/path/to/q.js:397:39)
|
||||
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
|
||||
```
|
||||
|
||||
But, if you turn this feature on by setting
|
||||
|
||||
```js
|
||||
Q.longStackSupport = true;
|
||||
```
|
||||
|
||||
then the above code gives a nice stack trace to the tune of
|
||||
|
||||
```
|
||||
Error: boo!
|
||||
at explode (/path/to/test.js:3:11)
|
||||
From previous event:
|
||||
at theDepthsOfMyProgram (/path/to/test.js:2:16)
|
||||
at Object.<anonymous> (/path/to/test.js:7:1)
|
||||
```
|
||||
|
||||
Note how you can see the function that triggered the async operation in the
|
||||
stack trace! This is very helpful for debugging, as otherwise you end up getting
|
||||
only the first line, plus a bunch of Q internals, with no sign of where the
|
||||
operation started.
|
||||
|
||||
In node.js, this feature can also be enabled through the Q_DEBUG environment
|
||||
variable:
|
||||
|
||||
```
|
||||
Q_DEBUG=1 node server.js
|
||||
```
|
||||
|
||||
This will enable long stack support in every instance of Q.
|
||||
|
||||
This feature does come with somewhat-serious performance and memory overhead,
|
||||
however. If you're working with lots of promises, or trying to scale a server
|
||||
to many users, you should probably keep it off. But in development, go for it!
|
||||
|
||||
## Tests
|
||||
|
||||
You can view the results of the Q test suite [in your browser][tests]!
|
||||
|
||||
[tests]: https://rawgithub.com/kriskowal/q/v1/spec/q-spec.html
|
||||
|
||||
## License
|
||||
|
||||
Copyright 2009–2015 Kristopher Michael Kowal and contributors
|
||||
MIT License (enclosed)
|
||||
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
{
|
||||
"name": "q",
|
||||
"version": "1.4.1",
|
||||
"description": "A library for promises (CommonJS/Promises/A,B,D)",
|
||||
"homepage": "https://github.com/kriskowal/q",
|
||||
"author": {
|
||||
"name": "Kris Kowal",
|
||||
"email": "kris@cixar.com",
|
||||
"url": "https://github.com/kriskowal"
|
||||
},
|
||||
"keywords": [
|
||||
"q",
|
||||
"promise",
|
||||
"promises",
|
||||
"promises-a",
|
||||
"promises-aplus",
|
||||
"deferred",
|
||||
"future",
|
||||
"async",
|
||||
"flow control",
|
||||
"fluent",
|
||||
"browser",
|
||||
"node"
|
||||
],
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Kris Kowal",
|
||||
"email": "kris@cixar.com",
|
||||
"url": "https://github.com/kriskowal"
|
||||
},
|
||||
{
|
||||
"name": "Irakli Gozalishvili",
|
||||
"email": "rfobic@gmail.com",
|
||||
"url": "http://jeditoolkit.com"
|
||||
},
|
||||
{
|
||||
"name": "Domenic Denicola",
|
||||
"email": "domenic@domenicdenicola.com",
|
||||
"url": "http://domenicdenicola.com"
|
||||
}
|
||||
],
|
||||
"bugs": {
|
||||
"url": "http://github.com/kriskowal/q/issues"
|
||||
},
|
||||
"license": {
|
||||
"type": "MIT",
|
||||
"url": "http://github.com/kriskowal/q/raw/master/LICENSE"
|
||||
},
|
||||
"main": "q.js",
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"q.js",
|
||||
"queue.js"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/kriskowal/q.git"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.6.0",
|
||||
"teleport": ">=0.2.0"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"cover": "*",
|
||||
"grunt": "~0.4.1",
|
||||
"grunt-cli": "~0.1.9",
|
||||
"grunt-contrib-uglify": "~0.9.1",
|
||||
"jasmine-node": "1.11.0",
|
||||
"jshint": "~2.1.9",
|
||||
"matcha": "~0.2.0",
|
||||
"opener": "*",
|
||||
"promises-aplus-tests": "1.x"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "jasmine-node spec && promises-aplus-tests spec/aplus-adapter",
|
||||
"test-browser": "opener spec/q-spec.html",
|
||||
"benchmark": "matcha",
|
||||
"lint": "jshint q.js",
|
||||
"cover": "cover run jasmine-node spec && cover report html && opener cover_html/index.html",
|
||||
"minify": "grunt",
|
||||
"prepublish": "grunt"
|
||||
},
|
||||
"overlay": {
|
||||
"teleport": {
|
||||
"dependencies": {
|
||||
"system": ">=0.0.4"
|
||||
}
|
||||
}
|
||||
},
|
||||
"directories": {
|
||||
"test": "./spec"
|
||||
},
|
||||
"gitHead": "d373079d3620152e3d60e82f27265a09ee0e81bd",
|
||||
"_id": "q@1.4.1",
|
||||
"_shasum": "55705bcd93c5f3673530c2c2cbc0c2b3addc286e",
|
||||
"_from": "q@1.4.1",
|
||||
"_npmVersion": "2.8.3",
|
||||
"_nodeVersion": "1.8.1",
|
||||
"_npmUser": {
|
||||
"name": "kriskowal",
|
||||
"email": "kris.kowal@cixar.com"
|
||||
},
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "kriskowal",
|
||||
"email": "kris.kowal@cixar.com"
|
||||
},
|
||||
{
|
||||
"name": "domenic",
|
||||
"email": "domenic@domenicdenicola.com"
|
||||
}
|
||||
],
|
||||
"dist": {
|
||||
"shasum": "55705bcd93c5f3673530c2c2cbc0c2b3addc286e",
|
||||
"tarball": "http://registry.npmjs.org/q/-/q-1.4.1.tgz"
|
||||
},
|
||||
"_resolved": "https://registry.npmjs.org/q/-/q-1.4.1.tgz",
|
||||
"readme": "ERROR: No README data found!"
|
||||
}
|
||||
+2048
File diff suppressed because it is too large
Load Diff
+35
@@ -0,0 +1,35 @@
|
||||
|
||||
var Q = require("./q");
|
||||
|
||||
module.exports = Queue;
|
||||
function Queue() {
|
||||
var ends = Q.defer();
|
||||
var closed = Q.defer();
|
||||
return {
|
||||
put: function (value) {
|
||||
var next = Q.defer();
|
||||
ends.resolve({
|
||||
head: value,
|
||||
tail: next.promise
|
||||
});
|
||||
ends.resolve = next.resolve;
|
||||
},
|
||||
get: function () {
|
||||
var result = ends.promise.get("head");
|
||||
ends.promise = ends.promise.get("tail");
|
||||
return result.fail(function (error) {
|
||||
closed.resolve(error);
|
||||
throw error;
|
||||
});
|
||||
},
|
||||
closed: closed.promise,
|
||||
close: function (error) {
|
||||
error = error || new Error("Can't get value from closed queue");
|
||||
var end = {head: Q.reject(error)};
|
||||
end.tail = end;
|
||||
ends.resolve(end);
|
||||
return closed.promise;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "ShellJS",
|
||||
"twitter": [
|
||||
"r2r"
|
||||
]
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"loopfunc": true,
|
||||
"sub": true,
|
||||
"undef": true,
|
||||
"unused": true,
|
||||
"node": true
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
test/
|
||||
tmp/
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- "0.10"
|
||||
- "0.11"
|
||||
- "0.12"
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
Copyright (c) 2012, Artur Adib <aadib@mozilla.com>
|
||||
All rights reserved.
|
||||
|
||||
You may use this project under the terms of the New BSD license as follows:
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of Artur Adib nor the
|
||||
names of the contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
ARE DISCLAIMED. IN NO EVENT SHALL ARTUR ADIB BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
+579
@@ -0,0 +1,579 @@
|
||||
# ShellJS - Unix shell commands for Node.js [](http://travis-ci.org/arturadib/shelljs)
|
||||
|
||||
ShellJS is a portable **(Windows/Linux/OS X)** implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!
|
||||
|
||||
The project is [unit-tested](http://travis-ci.org/arturadib/shelljs) and battled-tested in projects like:
|
||||
|
||||
+ [PDF.js](http://github.com/mozilla/pdf.js) - Firefox's next-gen PDF reader
|
||||
+ [Firebug](http://getfirebug.com/) - Firefox's infamous debugger
|
||||
+ [JSHint](http://jshint.com) - Most popular JavaScript linter
|
||||
+ [Zepto](http://zeptojs.com) - jQuery-compatible JavaScript library for modern browsers
|
||||
+ [Yeoman](http://yeoman.io/) - Web application stack and development tool
|
||||
+ [Deployd.com](http://deployd.com) - Open source PaaS for quick API backend generation
|
||||
|
||||
and [many more](https://npmjs.org/browse/depended/shelljs).
|
||||
|
||||
Connect with [@r2r](http://twitter.com/r2r) on Twitter for questions, suggestions, etc.
|
||||
|
||||
## Installing
|
||||
|
||||
Via npm:
|
||||
|
||||
```bash
|
||||
$ npm install [-g] shelljs
|
||||
```
|
||||
|
||||
If the global option `-g` is specified, the binary `shjs` will be installed. This makes it possible to
|
||||
run ShellJS scripts much like any shell script from the command line, i.e. without requiring a `node_modules` folder:
|
||||
|
||||
```bash
|
||||
$ shjs my_script
|
||||
```
|
||||
|
||||
You can also just copy `shell.js` into your project's directory, and `require()` accordingly.
|
||||
|
||||
|
||||
## Examples
|
||||
|
||||
### JavaScript
|
||||
|
||||
```javascript
|
||||
require('shelljs/global');
|
||||
|
||||
if (!which('git')) {
|
||||
echo('Sorry, this script requires git');
|
||||
exit(1);
|
||||
}
|
||||
|
||||
// Copy files to release dir
|
||||
mkdir('-p', 'out/Release');
|
||||
cp('-R', 'stuff/*', 'out/Release');
|
||||
|
||||
// Replace macros in each .js file
|
||||
cd('lib');
|
||||
ls('*.js').forEach(function(file) {
|
||||
sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
|
||||
sed('-i', /.*REMOVE_THIS_LINE.*\n/, '', file);
|
||||
sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, cat('macro.js'), file);
|
||||
});
|
||||
cd('..');
|
||||
|
||||
// Run external tool synchronously
|
||||
if (exec('git commit -am "Auto-commit"').code !== 0) {
|
||||
echo('Error: Git commit failed');
|
||||
exit(1);
|
||||
}
|
||||
```
|
||||
|
||||
### CoffeeScript
|
||||
|
||||
```coffeescript
|
||||
require 'shelljs/global'
|
||||
|
||||
if not which 'git'
|
||||
echo 'Sorry, this script requires git'
|
||||
exit 1
|
||||
|
||||
# Copy files to release dir
|
||||
mkdir '-p', 'out/Release'
|
||||
cp '-R', 'stuff/*', 'out/Release'
|
||||
|
||||
# Replace macros in each .js file
|
||||
cd 'lib'
|
||||
for file in ls '*.js'
|
||||
sed '-i', 'BUILD_VERSION', 'v0.1.2', file
|
||||
sed '-i', /.*REMOVE_THIS_LINE.*\n/, '', file
|
||||
sed '-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, cat 'macro.js', file
|
||||
cd '..'
|
||||
|
||||
# Run external tool synchronously
|
||||
if (exec 'git commit -am "Auto-commit"').code != 0
|
||||
echo 'Error: Git commit failed'
|
||||
exit 1
|
||||
```
|
||||
|
||||
## Global vs. Local
|
||||
|
||||
The example above uses the convenience script `shelljs/global` to reduce verbosity. If polluting your global namespace is not desirable, simply require `shelljs`.
|
||||
|
||||
Example:
|
||||
|
||||
```javascript
|
||||
var shell = require('shelljs');
|
||||
shell.echo('hello world');
|
||||
```
|
||||
|
||||
## Make tool
|
||||
|
||||
A convenience script `shelljs/make` is also provided to mimic the behavior of a Unix Makefile. In this case all shell objects are global, and command line arguments will cause the script to execute only the corresponding function in the global `target` object. To avoid redundant calls, target functions are executed only once per script.
|
||||
|
||||
Example (CoffeeScript):
|
||||
|
||||
```coffeescript
|
||||
require 'shelljs/make'
|
||||
|
||||
target.all = ->
|
||||
target.bundle()
|
||||
target.docs()
|
||||
|
||||
target.bundle = ->
|
||||
cd __dirname
|
||||
mkdir 'build'
|
||||
cd 'lib'
|
||||
(cat '*.js').to '../build/output.js'
|
||||
|
||||
target.docs = ->
|
||||
cd __dirname
|
||||
mkdir 'docs'
|
||||
cd 'lib'
|
||||
for file in ls '*.js'
|
||||
text = grep '//@', file # extract special comments
|
||||
text.replace '//@', '' # remove comment tags
|
||||
text.to 'docs/my_docs.md'
|
||||
```
|
||||
|
||||
To run the target `all`, call the above script without arguments: `$ node make`. To run the target `docs`: `$ node make docs`.
|
||||
|
||||
You can also pass arguments to your targets by using the `--` separator. For example, to pass `arg1` and `arg2` to a target `bundle`, do `$ node make bundle -- arg1 arg2`:
|
||||
|
||||
```javascript
|
||||
require('shelljs/make');
|
||||
|
||||
target.bundle = function(argsArray) {
|
||||
// argsArray = ['arg1', 'arg2']
|
||||
/* ... */
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
<!-- DO NOT MODIFY BEYOND THIS POINT - IT'S AUTOMATICALLY GENERATED -->
|
||||
|
||||
|
||||
## Command reference
|
||||
|
||||
|
||||
All commands run synchronously, unless otherwise stated.
|
||||
|
||||
|
||||
### cd('dir')
|
||||
Changes to directory `dir` for the duration of the script
|
||||
|
||||
|
||||
### pwd()
|
||||
Returns the current directory.
|
||||
|
||||
|
||||
### ls([options ,] path [,path ...])
|
||||
### ls([options ,] path_array)
|
||||
Available options:
|
||||
|
||||
+ `-R`: recursive
|
||||
+ `-A`: all files (include files beginning with `.`, except for `.` and `..`)
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
ls('projs/*.js');
|
||||
ls('-R', '/users/me', '/tmp');
|
||||
ls('-R', ['/users/me', '/tmp']); // same as above
|
||||
```
|
||||
|
||||
Returns array of files in the given path, or in current directory if no path provided.
|
||||
|
||||
|
||||
### find(path [,path ...])
|
||||
### find(path_array)
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
find('src', 'lib');
|
||||
find(['src', 'lib']); // same as above
|
||||
find('.').filter(function(file) { return file.match(/\.js$/); });
|
||||
```
|
||||
|
||||
Returns array of all files (however deep) in the given paths.
|
||||
|
||||
The main difference from `ls('-R', path)` is that the resulting file names
|
||||
include the base directories, e.g. `lib/resources/file1` instead of just `file1`.
|
||||
|
||||
|
||||
### cp([options ,] source [,source ...], dest)
|
||||
### cp([options ,] source_array, dest)
|
||||
Available options:
|
||||
|
||||
+ `-f`: force
|
||||
+ `-r, -R`: recursive
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
cp('file1', 'dir1');
|
||||
cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp');
|
||||
cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above
|
||||
```
|
||||
|
||||
Copies files. The wildcard `*` is accepted.
|
||||
|
||||
|
||||
### rm([options ,] file [, file ...])
|
||||
### rm([options ,] file_array)
|
||||
Available options:
|
||||
|
||||
+ `-f`: force
|
||||
+ `-r, -R`: recursive
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
rm('-rf', '/tmp/*');
|
||||
rm('some_file.txt', 'another_file.txt');
|
||||
rm(['some_file.txt', 'another_file.txt']); // same as above
|
||||
```
|
||||
|
||||
Removes files. The wildcard `*` is accepted.
|
||||
|
||||
|
||||
### mv(source [, source ...], dest')
|
||||
### mv(source_array, dest')
|
||||
Available options:
|
||||
|
||||
+ `f`: force
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
mv('-f', 'file', 'dir/');
|
||||
mv('file1', 'file2', 'dir/');
|
||||
mv(['file1', 'file2'], 'dir/'); // same as above
|
||||
```
|
||||
|
||||
Moves files. The wildcard `*` is accepted.
|
||||
|
||||
|
||||
### mkdir([options ,] dir [, dir ...])
|
||||
### mkdir([options ,] dir_array)
|
||||
Available options:
|
||||
|
||||
+ `p`: full path (will create intermediate dirs if necessary)
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g');
|
||||
mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above
|
||||
```
|
||||
|
||||
Creates directories.
|
||||
|
||||
|
||||
### test(expression)
|
||||
Available expression primaries:
|
||||
|
||||
+ `'-b', 'path'`: true if path is a block device
|
||||
+ `'-c', 'path'`: true if path is a character device
|
||||
+ `'-d', 'path'`: true if path is a directory
|
||||
+ `'-e', 'path'`: true if path exists
|
||||
+ `'-f', 'path'`: true if path is a regular file
|
||||
+ `'-L', 'path'`: true if path is a symbolic link
|
||||
+ `'-p', 'path'`: true if path is a pipe (FIFO)
|
||||
+ `'-S', 'path'`: true if path is a socket
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
if (test('-d', path)) { /* do something with dir */ };
|
||||
if (!test('-f', path)) continue; // skip if it's a regular file
|
||||
```
|
||||
|
||||
Evaluates expression using the available primaries and returns corresponding value.
|
||||
|
||||
|
||||
### cat(file [, file ...])
|
||||
### cat(file_array)
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
var str = cat('file*.txt');
|
||||
var str = cat('file1', 'file2');
|
||||
var str = cat(['file1', 'file2']); // same as above
|
||||
```
|
||||
|
||||
Returns a string containing the given file, or a concatenated string
|
||||
containing the files if more than one file is given (a new line character is
|
||||
introduced between each file). Wildcard `*` accepted.
|
||||
|
||||
|
||||
### 'string'.to(file)
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
cat('input.txt').to('output.txt');
|
||||
```
|
||||
|
||||
Analogous to the redirection operator `>` in Unix, but works with JavaScript strings (such as
|
||||
those returned by `cat`, `grep`, etc). _Like Unix redirections, `to()` will overwrite any existing file!_
|
||||
|
||||
|
||||
### 'string'.toEnd(file)
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
cat('input.txt').toEnd('output.txt');
|
||||
```
|
||||
|
||||
Analogous to the redirect-and-append operator `>>` in Unix, but works with JavaScript strings (such as
|
||||
those returned by `cat`, `grep`, etc).
|
||||
|
||||
|
||||
### sed([options ,] search_regex, replacement, file)
|
||||
Available options:
|
||||
|
||||
+ `-i`: Replace contents of 'file' in-place. _Note that no backups will be created!_
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js');
|
||||
sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js');
|
||||
```
|
||||
|
||||
Reads an input string from `file` and performs a JavaScript `replace()` on the input
|
||||
using the given search regex and replacement string or function. Returns the new string after replacement.
|
||||
|
||||
|
||||
### grep([options ,] regex_filter, file [, file ...])
|
||||
### grep([options ,] regex_filter, file_array)
|
||||
Available options:
|
||||
|
||||
+ `-v`: Inverse the sense of the regex and print the lines not matching the criteria.
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
grep('-v', 'GLOBAL_VARIABLE', '*.js');
|
||||
grep('GLOBAL_VARIABLE', '*.js');
|
||||
```
|
||||
|
||||
Reads input string from given files and returns a string containing all lines of the
|
||||
file that match the given `regex_filter`. Wildcard `*` accepted.
|
||||
|
||||
|
||||
### which(command)
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
var nodeExec = which('node');
|
||||
```
|
||||
|
||||
Searches for `command` in the system's PATH. On Windows looks for `.exe`, `.cmd`, and `.bat` extensions.
|
||||
Returns string containing the absolute path to the command.
|
||||
|
||||
|
||||
### echo(string [,string ...])
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
echo('hello world');
|
||||
var str = echo('hello world');
|
||||
```
|
||||
|
||||
Prints string to stdout, and returns string with additional utility methods
|
||||
like `.to()`.
|
||||
|
||||
|
||||
### pushd([options,] [dir | '-N' | '+N'])
|
||||
|
||||
Available options:
|
||||
|
||||
+ `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated.
|
||||
|
||||
Arguments:
|
||||
|
||||
+ `dir`: Makes the current working directory be the top of the stack, and then executes the equivalent of `cd dir`.
|
||||
+ `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack.
|
||||
+ `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack.
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
// process.cwd() === '/usr'
|
||||
pushd('/etc'); // Returns /etc /usr
|
||||
pushd('+1'); // Returns /usr /etc
|
||||
```
|
||||
|
||||
Save the current directory on the top of the directory stack and then cd to `dir`. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack.
|
||||
|
||||
### popd([options,] ['-N' | '+N'])
|
||||
|
||||
Available options:
|
||||
|
||||
+ `-n`: Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated.
|
||||
|
||||
Arguments:
|
||||
|
||||
+ `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero.
|
||||
+ `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero.
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
echo(process.cwd()); // '/usr'
|
||||
pushd('/etc'); // '/etc /usr'
|
||||
echo(process.cwd()); // '/etc'
|
||||
popd(); // '/usr'
|
||||
echo(process.cwd()); // '/usr'
|
||||
```
|
||||
|
||||
When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack.
|
||||
|
||||
### dirs([options | '+N' | '-N'])
|
||||
|
||||
Available options:
|
||||
|
||||
+ `-c`: Clears the directory stack by deleting all of the elements.
|
||||
|
||||
Arguments:
|
||||
|
||||
+ `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero.
|
||||
+ `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero.
|
||||
|
||||
Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified.
|
||||
|
||||
See also: pushd, popd
|
||||
|
||||
|
||||
### ln(options, source, dest)
|
||||
### ln(source, dest)
|
||||
Available options:
|
||||
|
||||
+ `s`: symlink
|
||||
+ `f`: force
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
ln('file', 'newlink');
|
||||
ln('-sf', 'file', 'existing');
|
||||
```
|
||||
|
||||
Links source to dest. Use -f to force the link, should dest already exist.
|
||||
|
||||
|
||||
### exit(code)
|
||||
Exits the current process with the given exit code.
|
||||
|
||||
### env['VAR_NAME']
|
||||
Object containing environment variables (both getter and setter). Shortcut to process.env.
|
||||
|
||||
### exec(command [, options] [, callback])
|
||||
Available options (all `false` by default):
|
||||
|
||||
+ `async`: Asynchronous execution. Defaults to true if a callback is provided.
|
||||
+ `silent`: Do not echo program output to console.
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
var version = exec('node --version', {silent:true}).output;
|
||||
|
||||
var child = exec('some_long_running_process', {async:true});
|
||||
child.stdout.on('data', function(data) {
|
||||
/* ... do something with data ... */
|
||||
});
|
||||
|
||||
exec('some_long_running_process', function(code, output) {
|
||||
console.log('Exit code:', code);
|
||||
console.log('Program output:', output);
|
||||
});
|
||||
```
|
||||
|
||||
Executes the given `command` _synchronously_, unless otherwise specified.
|
||||
When in synchronous mode returns the object `{ code:..., output:... }`, containing the program's
|
||||
`output` (stdout + stderr) and its exit `code`. Otherwise returns the child process object, and
|
||||
the `callback` gets the arguments `(code, output)`.
|
||||
|
||||
**Note:** For long-lived processes, it's best to run `exec()` asynchronously as
|
||||
the current synchronous implementation uses a lot of CPU. This should be getting
|
||||
fixed soon.
|
||||
|
||||
|
||||
### chmod(octal_mode || octal_string, file)
|
||||
### chmod(symbolic_mode, file)
|
||||
|
||||
Available options:
|
||||
|
||||
+ `-v`: output a diagnostic for every file processed
|
||||
+ `-c`: like verbose but report only when a change is made
|
||||
+ `-R`: change files and directories recursively
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
chmod(755, '/Users/brandon');
|
||||
chmod('755', '/Users/brandon'); // same as above
|
||||
chmod('u+x', '/Users/brandon');
|
||||
```
|
||||
|
||||
Alters the permissions of a file or directory by either specifying the
|
||||
absolute permissions in octal form or expressing the changes in symbols.
|
||||
This command tries to mimic the POSIX behavior as much as possible.
|
||||
Notable exceptions:
|
||||
|
||||
+ In symbolic modes, 'a-r' and '-r' are identical. No consideration is
|
||||
given to the umask.
|
||||
+ There is no "quiet" option since default behavior is to run silent.
|
||||
|
||||
|
||||
## Non-Unix commands
|
||||
|
||||
|
||||
### tempdir()
|
||||
|
||||
Examples:
|
||||
|
||||
```javascript
|
||||
var tmp = tempdir(); // "/tmp" for most *nix platforms
|
||||
```
|
||||
|
||||
Searches and returns string containing a writeable, platform-dependent temporary directory.
|
||||
Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir).
|
||||
|
||||
|
||||
### error()
|
||||
Tests if error occurred in the last command. Returns `null` if no error occurred,
|
||||
otherwise returns string explaining the error
|
||||
|
||||
|
||||
## Configuration
|
||||
|
||||
|
||||
### config.silent
|
||||
Example:
|
||||
|
||||
```javascript
|
||||
var sh = require('shelljs');
|
||||
var silentState = sh.config.silent; // save old silent state
|
||||
sh.config.silent = true;
|
||||
/* ... */
|
||||
sh.config.silent = silentState; // restore old silent state
|
||||
```
|
||||
|
||||
Suppresses all command output if `true`, except for `echo()` calls.
|
||||
Default is `false`.
|
||||
|
||||
### config.fatal
|
||||
Example:
|
||||
|
||||
```javascript
|
||||
require('shelljs/global');
|
||||
config.fatal = true;
|
||||
cp('this_file_does_not_exist', '/dev/null'); // dies here
|
||||
/* more commands... */
|
||||
```
|
||||
|
||||
If `true` the script will die on errors. Default is `false`.
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
# Release steps
|
||||
|
||||
* Ensure master passes CI tests
|
||||
* Bump version in package.json. Any breaking change or new feature should bump minor (or even major). Non-breaking changes or fixes can just bump patch.
|
||||
* Update README manually if the changes are not documented in-code. If so, run `scripts/generate-docs.js`
|
||||
* Commit
|
||||
* `$ git tag <version>` (see `git tag -l` for latest)
|
||||
* `$ git push origin master --tags`
|
||||
* `$ npm publish .`
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env node
|
||||
require('../global');
|
||||
|
||||
if (process.argv.length < 3) {
|
||||
console.log('ShellJS: missing argument (script name)');
|
||||
console.log();
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
var args,
|
||||
scriptName = process.argv[2];
|
||||
env['NODE_PATH'] = __dirname + '/../..';
|
||||
|
||||
if (!scriptName.match(/\.js/) && !scriptName.match(/\.coffee/)) {
|
||||
if (test('-f', scriptName + '.js'))
|
||||
scriptName += '.js';
|
||||
if (test('-f', scriptName + '.coffee'))
|
||||
scriptName += '.coffee';
|
||||
}
|
||||
|
||||
if (!test('-f', scriptName)) {
|
||||
console.log('ShellJS: script not found ('+scriptName+')');
|
||||
console.log();
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
args = process.argv.slice(3);
|
||||
|
||||
for (var i = 0, l = args.length; i < l; i++) {
|
||||
if (args[i][0] !== "-"){
|
||||
args[i] = '"' + args[i] + '"'; // fixes arguments with multiple words
|
||||
}
|
||||
}
|
||||
|
||||
if (scriptName.match(/\.coffee$/)) {
|
||||
//
|
||||
// CoffeeScript
|
||||
//
|
||||
if (which('coffee')) {
|
||||
exec('coffee ' + scriptName + ' ' + args.join(' '), { async: true });
|
||||
} else {
|
||||
console.log('ShellJS: CoffeeScript interpreter not found');
|
||||
console.log();
|
||||
process.exit(1);
|
||||
}
|
||||
} else {
|
||||
//
|
||||
// JavaScript
|
||||
//
|
||||
exec('node ' + scriptName + ' ' + args.join(' '), { async: true });
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
var shell = require('./shell.js');
|
||||
for (var cmd in shell)
|
||||
global[cmd] = shell[cmd];
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
require('./global');
|
||||
|
||||
global.config.fatal = true;
|
||||
global.target = {};
|
||||
|
||||
var args = process.argv.slice(2),
|
||||
targetArgs,
|
||||
dashesLoc = args.indexOf('--');
|
||||
|
||||
// split args, everything after -- if only for targets
|
||||
if (dashesLoc > -1) {
|
||||
targetArgs = args.slice(dashesLoc + 1, args.length);
|
||||
args = args.slice(0, dashesLoc);
|
||||
}
|
||||
|
||||
// This ensures we only execute the script targets after the entire script has
|
||||
// been evaluated
|
||||
setTimeout(function() {
|
||||
var t;
|
||||
|
||||
if (args.length === 1 && args[0] === '--help') {
|
||||
console.log('Available targets:');
|
||||
for (t in global.target)
|
||||
console.log(' ' + t);
|
||||
return;
|
||||
}
|
||||
|
||||
// Wrap targets to prevent duplicate execution
|
||||
for (t in global.target) {
|
||||
(function(t, oldTarget){
|
||||
|
||||
// Wrap it
|
||||
global.target[t] = function() {
|
||||
if (oldTarget.done)
|
||||
return;
|
||||
oldTarget.done = true;
|
||||
return oldTarget.apply(oldTarget, arguments);
|
||||
};
|
||||
|
||||
})(t, global.target[t]);
|
||||
}
|
||||
|
||||
// Execute desired targets
|
||||
if (args.length > 0) {
|
||||
args.forEach(function(arg) {
|
||||
if (arg in global.target)
|
||||
global.target[arg](targetArgs);
|
||||
else {
|
||||
console.log('no such target: ' + arg);
|
||||
}
|
||||
});
|
||||
} else if ('all' in global.target) {
|
||||
global.target.all(targetArgs);
|
||||
}
|
||||
|
||||
}, 0);
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"name": "shelljs",
|
||||
"version": "0.5.3",
|
||||
"author": {
|
||||
"name": "Artur Adib",
|
||||
"email": "arturadib@gmail.com"
|
||||
},
|
||||
"description": "Portable Unix shell commands for Node.js",
|
||||
"keywords": [
|
||||
"unix",
|
||||
"shell",
|
||||
"makefile",
|
||||
"make",
|
||||
"jake",
|
||||
"synchronous"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/arturadib/shelljs.git"
|
||||
},
|
||||
"license": "BSD*",
|
||||
"homepage": "http://github.com/arturadib/shelljs",
|
||||
"main": "./shell.js",
|
||||
"scripts": {
|
||||
"test": "node scripts/run-tests"
|
||||
},
|
||||
"bin": {
|
||||
"shjs": "./bin/shjs"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"jshint": "~2.1.11"
|
||||
},
|
||||
"optionalDependencies": {},
|
||||
"engines": {
|
||||
"node": ">=0.8.0"
|
||||
},
|
||||
"gitHead": "22d0975040b9b8234755dc6e692d6869436e8485",
|
||||
"bugs": {
|
||||
"url": "https://github.com/arturadib/shelljs/issues"
|
||||
},
|
||||
"_id": "shelljs@0.5.3",
|
||||
"_shasum": "c54982b996c76ef0c1e6b59fbdc5825f5b713113",
|
||||
"_from": "shelljs@0.5.3",
|
||||
"_npmVersion": "2.5.1",
|
||||
"_nodeVersion": "1.2.0",
|
||||
"_npmUser": {
|
||||
"name": "artur",
|
||||
"email": "arturadib@gmail.com"
|
||||
},
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "artur",
|
||||
"email": "arturadib@gmail.com"
|
||||
}
|
||||
],
|
||||
"dist": {
|
||||
"shasum": "c54982b996c76ef0c1e6b59fbdc5825f5b713113",
|
||||
"tarball": "http://registry.npmjs.org/shelljs/-/shelljs-0.5.3.tgz"
|
||||
},
|
||||
"directories": {},
|
||||
"_resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.5.3.tgz",
|
||||
"readme": "ERROR: No README data found!"
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env node
|
||||
require('../global');
|
||||
|
||||
echo('Appending docs to README.md');
|
||||
|
||||
cd(__dirname + '/..');
|
||||
|
||||
// Extract docs from shell.js
|
||||
var docs = grep('//@', 'shell.js');
|
||||
|
||||
docs = docs.replace(/\/\/\@include (.+)/g, function(match, path) {
|
||||
var file = path.match('.js$') ? path : path+'.js';
|
||||
return grep('//@', file);
|
||||
});
|
||||
|
||||
// Remove '//@'
|
||||
docs = docs.replace(/\/\/\@ ?/g, '');
|
||||
// Append docs to README
|
||||
sed('-i', /## Command reference(.|\n)*/, '## Command reference\n\n' + docs, 'README.md');
|
||||
|
||||
echo('All done.');
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env node
|
||||
require('../global');
|
||||
|
||||
var path = require('path');
|
||||
|
||||
var failed = false;
|
||||
|
||||
//
|
||||
// Lint
|
||||
//
|
||||
JSHINT_BIN = './node_modules/jshint/bin/jshint';
|
||||
cd(__dirname + '/..');
|
||||
|
||||
if (!test('-f', JSHINT_BIN)) {
|
||||
echo('JSHint not found. Run `npm install` in the root dir first.');
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (exec(JSHINT_BIN + ' *.js test/*.js').code !== 0) {
|
||||
failed = true;
|
||||
echo('*** JSHINT FAILED! (return code != 0)');
|
||||
echo();
|
||||
} else {
|
||||
echo('All JSHint tests passed');
|
||||
echo();
|
||||
}
|
||||
|
||||
//
|
||||
// Unit tests
|
||||
//
|
||||
cd(__dirname + '/../test');
|
||||
ls('*.js').forEach(function(file) {
|
||||
echo('Running test:', file);
|
||||
if (exec('node ' + file).code !== 123) { // 123 avoids false positives (e.g. premature exit)
|
||||
failed = true;
|
||||
echo('*** TEST FAILED! (missing exit code "123")');
|
||||
echo();
|
||||
}
|
||||
});
|
||||
|
||||
if (failed) {
|
||||
echo();
|
||||
echo('*******************************************************');
|
||||
echo('WARNING: Some tests did not pass!');
|
||||
echo('*******************************************************');
|
||||
exit(1);
|
||||
} else {
|
||||
echo();
|
||||
echo('All tests passed.');
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
//
|
||||
// ShellJS
|
||||
// Unix shell commands on top of Node's API
|
||||
//
|
||||
// Copyright (c) 2012 Artur Adib
|
||||
// http://github.com/arturadib/shelljs
|
||||
//
|
||||
|
||||
var common = require('./src/common');
|
||||
|
||||
|
||||
//@
|
||||
//@ All commands run synchronously, unless otherwise stated.
|
||||
//@
|
||||
|
||||
//@include ./src/cd
|
||||
var _cd = require('./src/cd');
|
||||
exports.cd = common.wrap('cd', _cd);
|
||||
|
||||
//@include ./src/pwd
|
||||
var _pwd = require('./src/pwd');
|
||||
exports.pwd = common.wrap('pwd', _pwd);
|
||||
|
||||
//@include ./src/ls
|
||||
var _ls = require('./src/ls');
|
||||
exports.ls = common.wrap('ls', _ls);
|
||||
|
||||
//@include ./src/find
|
||||
var _find = require('./src/find');
|
||||
exports.find = common.wrap('find', _find);
|
||||
|
||||
//@include ./src/cp
|
||||
var _cp = require('./src/cp');
|
||||
exports.cp = common.wrap('cp', _cp);
|
||||
|
||||
//@include ./src/rm
|
||||
var _rm = require('./src/rm');
|
||||
exports.rm = common.wrap('rm', _rm);
|
||||
|
||||
//@include ./src/mv
|
||||
var _mv = require('./src/mv');
|
||||
exports.mv = common.wrap('mv', _mv);
|
||||
|
||||
//@include ./src/mkdir
|
||||
var _mkdir = require('./src/mkdir');
|
||||
exports.mkdir = common.wrap('mkdir', _mkdir);
|
||||
|
||||
//@include ./src/test
|
||||
var _test = require('./src/test');
|
||||
exports.test = common.wrap('test', _test);
|
||||
|
||||
//@include ./src/cat
|
||||
var _cat = require('./src/cat');
|
||||
exports.cat = common.wrap('cat', _cat);
|
||||
|
||||
//@include ./src/to
|
||||
var _to = require('./src/to');
|
||||
String.prototype.to = common.wrap('to', _to);
|
||||
|
||||
//@include ./src/toEnd
|
||||
var _toEnd = require('./src/toEnd');
|
||||
String.prototype.toEnd = common.wrap('toEnd', _toEnd);
|
||||
|
||||
//@include ./src/sed
|
||||
var _sed = require('./src/sed');
|
||||
exports.sed = common.wrap('sed', _sed);
|
||||
|
||||
//@include ./src/grep
|
||||
var _grep = require('./src/grep');
|
||||
exports.grep = common.wrap('grep', _grep);
|
||||
|
||||
//@include ./src/which
|
||||
var _which = require('./src/which');
|
||||
exports.which = common.wrap('which', _which);
|
||||
|
||||
//@include ./src/echo
|
||||
var _echo = require('./src/echo');
|
||||
exports.echo = _echo; // don't common.wrap() as it could parse '-options'
|
||||
|
||||
//@include ./src/dirs
|
||||
var _dirs = require('./src/dirs').dirs;
|
||||
exports.dirs = common.wrap("dirs", _dirs);
|
||||
var _pushd = require('./src/dirs').pushd;
|
||||
exports.pushd = common.wrap('pushd', _pushd);
|
||||
var _popd = require('./src/dirs').popd;
|
||||
exports.popd = common.wrap("popd", _popd);
|
||||
|
||||
//@include ./src/ln
|
||||
var _ln = require('./src/ln');
|
||||
exports.ln = common.wrap('ln', _ln);
|
||||
|
||||
//@
|
||||
//@ ### exit(code)
|
||||
//@ Exits the current process with the given exit code.
|
||||
exports.exit = process.exit;
|
||||
|
||||
//@
|
||||
//@ ### env['VAR_NAME']
|
||||
//@ Object containing environment variables (both getter and setter). Shortcut to process.env.
|
||||
exports.env = process.env;
|
||||
|
||||
//@include ./src/exec
|
||||
var _exec = require('./src/exec');
|
||||
exports.exec = common.wrap('exec', _exec, {notUnix:true});
|
||||
|
||||
//@include ./src/chmod
|
||||
var _chmod = require('./src/chmod');
|
||||
exports.chmod = common.wrap('chmod', _chmod);
|
||||
|
||||
|
||||
|
||||
//@
|
||||
//@ ## Non-Unix commands
|
||||
//@
|
||||
|
||||
//@include ./src/tempdir
|
||||
var _tempDir = require('./src/tempdir');
|
||||
exports.tempdir = common.wrap('tempdir', _tempDir);
|
||||
|
||||
|
||||
//@include ./src/error
|
||||
var _error = require('./src/error');
|
||||
exports.error = _error;
|
||||
|
||||
|
||||
|
||||
//@
|
||||
//@ ## Configuration
|
||||
//@
|
||||
|
||||
exports.config = common.config;
|
||||
|
||||
//@
|
||||
//@ ### config.silent
|
||||
//@ Example:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ var sh = require('shelljs');
|
||||
//@ var silentState = sh.config.silent; // save old silent state
|
||||
//@ sh.config.silent = true;
|
||||
//@ /* ... */
|
||||
//@ sh.config.silent = silentState; // restore old silent state
|
||||
//@ ```
|
||||
//@
|
||||
//@ Suppresses all command output if `true`, except for `echo()` calls.
|
||||
//@ Default is `false`.
|
||||
|
||||
//@
|
||||
//@ ### config.fatal
|
||||
//@ Example:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ require('shelljs/global');
|
||||
//@ config.fatal = true;
|
||||
//@ cp('this_file_does_not_exist', '/dev/null'); // dies here
|
||||
//@ /* more commands... */
|
||||
//@ ```
|
||||
//@
|
||||
//@ If `true` the script will die on errors. Default is `false`.
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
var common = require('./common');
|
||||
var fs = require('fs');
|
||||
|
||||
//@
|
||||
//@ ### cat(file [, file ...])
|
||||
//@ ### cat(file_array)
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ var str = cat('file*.txt');
|
||||
//@ var str = cat('file1', 'file2');
|
||||
//@ var str = cat(['file1', 'file2']); // same as above
|
||||
//@ ```
|
||||
//@
|
||||
//@ Returns a string containing the given file, or a concatenated string
|
||||
//@ containing the files if more than one file is given (a new line character is
|
||||
//@ introduced between each file). Wildcard `*` accepted.
|
||||
function _cat(options, files) {
|
||||
var cat = '';
|
||||
|
||||
if (!files)
|
||||
common.error('no paths given');
|
||||
|
||||
if (typeof files === 'string')
|
||||
files = [].slice.call(arguments, 1);
|
||||
// if it's array leave it as it is
|
||||
|
||||
files = common.expand(files);
|
||||
|
||||
files.forEach(function(file) {
|
||||
if (!fs.existsSync(file))
|
||||
common.error('no such file or directory: ' + file);
|
||||
|
||||
cat += fs.readFileSync(file, 'utf8') + '\n';
|
||||
});
|
||||
|
||||
if (cat[cat.length-1] === '\n')
|
||||
cat = cat.substring(0, cat.length-1);
|
||||
|
||||
return common.ShellString(cat);
|
||||
}
|
||||
module.exports = _cat;
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
var fs = require('fs');
|
||||
var common = require('./common');
|
||||
|
||||
//@
|
||||
//@ ### cd('dir')
|
||||
//@ Changes to directory `dir` for the duration of the script
|
||||
function _cd(options, dir) {
|
||||
if (!dir)
|
||||
common.error('directory not specified');
|
||||
|
||||
if (!fs.existsSync(dir))
|
||||
common.error('no such file or directory: ' + dir);
|
||||
|
||||
if (!fs.statSync(dir).isDirectory())
|
||||
common.error('not a directory: ' + dir);
|
||||
|
||||
process.chdir(dir);
|
||||
}
|
||||
module.exports = _cd;
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
var common = require('./common');
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
|
||||
var PERMS = (function (base) {
|
||||
return {
|
||||
OTHER_EXEC : base.EXEC,
|
||||
OTHER_WRITE : base.WRITE,
|
||||
OTHER_READ : base.READ,
|
||||
|
||||
GROUP_EXEC : base.EXEC << 3,
|
||||
GROUP_WRITE : base.WRITE << 3,
|
||||
GROUP_READ : base.READ << 3,
|
||||
|
||||
OWNER_EXEC : base.EXEC << 6,
|
||||
OWNER_WRITE : base.WRITE << 6,
|
||||
OWNER_READ : base.READ << 6,
|
||||
|
||||
// Literal octal numbers are apparently not allowed in "strict" javascript. Using parseInt is
|
||||
// the preferred way, else a jshint warning is thrown.
|
||||
STICKY : parseInt('01000', 8),
|
||||
SETGID : parseInt('02000', 8),
|
||||
SETUID : parseInt('04000', 8),
|
||||
|
||||
TYPE_MASK : parseInt('0770000', 8)
|
||||
};
|
||||
})({
|
||||
EXEC : 1,
|
||||
WRITE : 2,
|
||||
READ : 4
|
||||
});
|
||||
|
||||
//@
|
||||
//@ ### chmod(octal_mode || octal_string, file)
|
||||
//@ ### chmod(symbolic_mode, file)
|
||||
//@
|
||||
//@ Available options:
|
||||
//@
|
||||
//@ + `-v`: output a diagnostic for every file processed//@
|
||||
//@ + `-c`: like verbose but report only when a change is made//@
|
||||
//@ + `-R`: change files and directories recursively//@
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ chmod(755, '/Users/brandon');
|
||||
//@ chmod('755', '/Users/brandon'); // same as above
|
||||
//@ chmod('u+x', '/Users/brandon');
|
||||
//@ ```
|
||||
//@
|
||||
//@ Alters the permissions of a file or directory by either specifying the
|
||||
//@ absolute permissions in octal form or expressing the changes in symbols.
|
||||
//@ This command tries to mimic the POSIX behavior as much as possible.
|
||||
//@ Notable exceptions:
|
||||
//@
|
||||
//@ + In symbolic modes, 'a-r' and '-r' are identical. No consideration is
|
||||
//@ given to the umask.
|
||||
//@ + There is no "quiet" option since default behavior is to run silent.
|
||||
function _chmod(options, mode, filePattern) {
|
||||
if (!filePattern) {
|
||||
if (options.length > 0 && options.charAt(0) === '-') {
|
||||
// Special case where the specified file permissions started with - to subtract perms, which
|
||||
// get picked up by the option parser as command flags.
|
||||
// If we are down by one argument and options starts with -, shift everything over.
|
||||
filePattern = mode;
|
||||
mode = options;
|
||||
options = '';
|
||||
}
|
||||
else {
|
||||
common.error('You must specify a file.');
|
||||
}
|
||||
}
|
||||
|
||||
options = common.parseOptions(options, {
|
||||
'R': 'recursive',
|
||||
'c': 'changes',
|
||||
'v': 'verbose'
|
||||
});
|
||||
|
||||
if (typeof filePattern === 'string') {
|
||||
filePattern = [ filePattern ];
|
||||
}
|
||||
|
||||
var files;
|
||||
|
||||
if (options.recursive) {
|
||||
files = [];
|
||||
common.expand(filePattern).forEach(function addFile(expandedFile) {
|
||||
var stat = fs.lstatSync(expandedFile);
|
||||
|
||||
if (!stat.isSymbolicLink()) {
|
||||
files.push(expandedFile);
|
||||
|
||||
if (stat.isDirectory()) { // intentionally does not follow symlinks.
|
||||
fs.readdirSync(expandedFile).forEach(function (child) {
|
||||
addFile(expandedFile + '/' + child);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
else {
|
||||
files = common.expand(filePattern);
|
||||
}
|
||||
|
||||
files.forEach(function innerChmod(file) {
|
||||
file = path.resolve(file);
|
||||
if (!fs.existsSync(file)) {
|
||||
common.error('File not found: ' + file);
|
||||
}
|
||||
|
||||
// When recursing, don't follow symlinks.
|
||||
if (options.recursive && fs.lstatSync(file).isSymbolicLink()) {
|
||||
return;
|
||||
}
|
||||
|
||||
var perms = fs.statSync(file).mode;
|
||||
var type = perms & PERMS.TYPE_MASK;
|
||||
|
||||
var newPerms = perms;
|
||||
|
||||
if (isNaN(parseInt(mode, 8))) {
|
||||
// parse options
|
||||
mode.split(',').forEach(function (symbolicMode) {
|
||||
/*jshint regexdash:true */
|
||||
var pattern = /([ugoa]*)([=\+-])([rwxXst]*)/i;
|
||||
var matches = pattern.exec(symbolicMode);
|
||||
|
||||
if (matches) {
|
||||
var applyTo = matches[1];
|
||||
var operator = matches[2];
|
||||
var change = matches[3];
|
||||
|
||||
var changeOwner = applyTo.indexOf('u') != -1 || applyTo === 'a' || applyTo === '';
|
||||
var changeGroup = applyTo.indexOf('g') != -1 || applyTo === 'a' || applyTo === '';
|
||||
var changeOther = applyTo.indexOf('o') != -1 || applyTo === 'a' || applyTo === '';
|
||||
|
||||
var changeRead = change.indexOf('r') != -1;
|
||||
var changeWrite = change.indexOf('w') != -1;
|
||||
var changeExec = change.indexOf('x') != -1;
|
||||
var changeSticky = change.indexOf('t') != -1;
|
||||
var changeSetuid = change.indexOf('s') != -1;
|
||||
|
||||
var mask = 0;
|
||||
if (changeOwner) {
|
||||
mask |= (changeRead ? PERMS.OWNER_READ : 0) + (changeWrite ? PERMS.OWNER_WRITE : 0) + (changeExec ? PERMS.OWNER_EXEC : 0) + (changeSetuid ? PERMS.SETUID : 0);
|
||||
}
|
||||
if (changeGroup) {
|
||||
mask |= (changeRead ? PERMS.GROUP_READ : 0) + (changeWrite ? PERMS.GROUP_WRITE : 0) + (changeExec ? PERMS.GROUP_EXEC : 0) + (changeSetuid ? PERMS.SETGID : 0);
|
||||
}
|
||||
if (changeOther) {
|
||||
mask |= (changeRead ? PERMS.OTHER_READ : 0) + (changeWrite ? PERMS.OTHER_WRITE : 0) + (changeExec ? PERMS.OTHER_EXEC : 0);
|
||||
}
|
||||
|
||||
// Sticky bit is special - it's not tied to user, group or other.
|
||||
if (changeSticky) {
|
||||
mask |= PERMS.STICKY;
|
||||
}
|
||||
|
||||
switch (operator) {
|
||||
case '+':
|
||||
newPerms |= mask;
|
||||
break;
|
||||
|
||||
case '-':
|
||||
newPerms &= ~mask;
|
||||
break;
|
||||
|
||||
case '=':
|
||||
newPerms = type + mask;
|
||||
|
||||
// According to POSIX, when using = to explicitly set the permissions, setuid and setgid can never be cleared.
|
||||
if (fs.statSync(file).isDirectory()) {
|
||||
newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (options.verbose) {
|
||||
log(file + ' -> ' + newPerms.toString(8));
|
||||
}
|
||||
|
||||
if (perms != newPerms) {
|
||||
if (!options.verbose && options.changes) {
|
||||
log(file + ' -> ' + newPerms.toString(8));
|
||||
}
|
||||
fs.chmodSync(file, newPerms);
|
||||
}
|
||||
}
|
||||
else {
|
||||
common.error('Invalid symbolic mode change: ' + symbolicMode);
|
||||
}
|
||||
});
|
||||
}
|
||||
else {
|
||||
// they gave us a full number
|
||||
newPerms = type + parseInt(mode, 8);
|
||||
|
||||
// POSIX rules are that setuid and setgid can only be added using numeric form, but not cleared.
|
||||
if (fs.statSync(file).isDirectory()) {
|
||||
newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms;
|
||||
}
|
||||
|
||||
fs.chmodSync(file, newPerms);
|
||||
}
|
||||
});
|
||||
}
|
||||
module.exports = _chmod;
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
var os = require('os');
|
||||
var fs = require('fs');
|
||||
var _ls = require('./ls');
|
||||
|
||||
// Module globals
|
||||
var config = {
|
||||
silent: false,
|
||||
fatal: false
|
||||
};
|
||||
exports.config = config;
|
||||
|
||||
var state = {
|
||||
error: null,
|
||||
currentCmd: 'shell.js',
|
||||
tempDir: null
|
||||
};
|
||||
exports.state = state;
|
||||
|
||||
var platform = os.type().match(/^Win/) ? 'win' : 'unix';
|
||||
exports.platform = platform;
|
||||
|
||||
function log() {
|
||||
if (!config.silent)
|
||||
console.log.apply(this, arguments);
|
||||
}
|
||||
exports.log = log;
|
||||
|
||||
// Shows error message. Throws unless _continue or config.fatal are true
|
||||
function error(msg, _continue) {
|
||||
if (state.error === null)
|
||||
state.error = '';
|
||||
state.error += state.currentCmd + ': ' + msg + '\n';
|
||||
|
||||
if (msg.length > 0)
|
||||
log(state.error);
|
||||
|
||||
if (config.fatal)
|
||||
process.exit(1);
|
||||
|
||||
if (!_continue)
|
||||
throw '';
|
||||
}
|
||||
exports.error = error;
|
||||
|
||||
// In the future, when Proxies are default, we can add methods like `.to()` to primitive strings.
|
||||
// For now, this is a dummy function to bookmark places we need such strings
|
||||
function ShellString(str) {
|
||||
return str;
|
||||
}
|
||||
exports.ShellString = ShellString;
|
||||
|
||||
// Returns {'alice': true, 'bob': false} when passed a dictionary, e.g.:
|
||||
// parseOptions('-a', {'a':'alice', 'b':'bob'});
|
||||
function parseOptions(str, map) {
|
||||
if (!map)
|
||||
error('parseOptions() internal error: no map given');
|
||||
|
||||
// All options are false by default
|
||||
var options = {};
|
||||
for (var letter in map)
|
||||
options[map[letter]] = false;
|
||||
|
||||
if (!str)
|
||||
return options; // defaults
|
||||
|
||||
if (typeof str !== 'string')
|
||||
error('parseOptions() internal error: wrong str');
|
||||
|
||||
// e.g. match[1] = 'Rf' for str = '-Rf'
|
||||
var match = str.match(/^\-(.+)/);
|
||||
if (!match)
|
||||
return options;
|
||||
|
||||
// e.g. chars = ['R', 'f']
|
||||
var chars = match[1].split('');
|
||||
|
||||
chars.forEach(function(c) {
|
||||
if (c in map)
|
||||
options[map[c]] = true;
|
||||
else
|
||||
error('option not recognized: '+c);
|
||||
});
|
||||
|
||||
return options;
|
||||
}
|
||||
exports.parseOptions = parseOptions;
|
||||
|
||||
// Expands wildcards with matching (ie. existing) file names.
|
||||
// For example:
|
||||
// expand(['file*.js']) = ['file1.js', 'file2.js', ...]
|
||||
// (if the files 'file1.js', 'file2.js', etc, exist in the current dir)
|
||||
function expand(list) {
|
||||
var expanded = [];
|
||||
list.forEach(function(listEl) {
|
||||
// Wildcard present on directory names ?
|
||||
if(listEl.search(/\*[^\/]*\//) > -1 || listEl.search(/\*\*[^\/]*\//) > -1) {
|
||||
var match = listEl.match(/^([^*]+\/|)(.*)/);
|
||||
var root = match[1];
|
||||
var rest = match[2];
|
||||
var restRegex = rest.replace(/\*\*/g, ".*").replace(/\*/g, "[^\\/]*");
|
||||
restRegex = new RegExp(restRegex);
|
||||
|
||||
_ls('-R', root).filter(function (e) {
|
||||
return restRegex.test(e);
|
||||
}).forEach(function(file) {
|
||||
expanded.push(file);
|
||||
});
|
||||
}
|
||||
// Wildcard present on file names ?
|
||||
else if (listEl.search(/\*/) > -1) {
|
||||
_ls('', listEl).forEach(function(file) {
|
||||
expanded.push(file);
|
||||
});
|
||||
} else {
|
||||
expanded.push(listEl);
|
||||
}
|
||||
});
|
||||
return expanded;
|
||||
}
|
||||
exports.expand = expand;
|
||||
|
||||
// Normalizes _unlinkSync() across platforms to match Unix behavior, i.e.
|
||||
// file can be unlinked even if it's read-only, see https://github.com/joyent/node/issues/3006
|
||||
function unlinkSync(file) {
|
||||
try {
|
||||
fs.unlinkSync(file);
|
||||
} catch(e) {
|
||||
// Try to override file permission
|
||||
if (e.code === 'EPERM') {
|
||||
fs.chmodSync(file, '0666');
|
||||
fs.unlinkSync(file);
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.unlinkSync = unlinkSync;
|
||||
|
||||
// e.g. 'shelljs_a5f185d0443ca...'
|
||||
function randomFileName() {
|
||||
function randomHash(count) {
|
||||
if (count === 1)
|
||||
return parseInt(16*Math.random(), 10).toString(16);
|
||||
else {
|
||||
var hash = '';
|
||||
for (var i=0; i<count; i++)
|
||||
hash += randomHash(1);
|
||||
return hash;
|
||||
}
|
||||
}
|
||||
|
||||
return 'shelljs_'+randomHash(20);
|
||||
}
|
||||
exports.randomFileName = randomFileName;
|
||||
|
||||
// extend(target_obj, source_obj1 [, source_obj2 ...])
|
||||
// Shallow extend, e.g.:
|
||||
// extend({A:1}, {b:2}, {c:3}) returns {A:1, b:2, c:3}
|
||||
function extend(target) {
|
||||
var sources = [].slice.call(arguments, 1);
|
||||
sources.forEach(function(source) {
|
||||
for (var key in source)
|
||||
target[key] = source[key];
|
||||
});
|
||||
|
||||
return target;
|
||||
}
|
||||
exports.extend = extend;
|
||||
|
||||
// Common wrapper for all Unix-like commands
|
||||
function wrap(cmd, fn, options) {
|
||||
return function() {
|
||||
var retValue = null;
|
||||
|
||||
state.currentCmd = cmd;
|
||||
state.error = null;
|
||||
|
||||
try {
|
||||
var args = [].slice.call(arguments, 0);
|
||||
|
||||
if (options && options.notUnix) {
|
||||
retValue = fn.apply(this, args);
|
||||
} else {
|
||||
if (args.length === 0 || typeof args[0] !== 'string' || args[0][0] !== '-')
|
||||
args.unshift(''); // only add dummy option if '-option' not already present
|
||||
retValue = fn.apply(this, args);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!state.error) {
|
||||
// If state.error hasn't been set it's an error thrown by Node, not us - probably a bug...
|
||||
console.log('shell.js: internal error');
|
||||
console.log(e.stack || e);
|
||||
process.exit(1);
|
||||
}
|
||||
if (config.fatal)
|
||||
throw e;
|
||||
}
|
||||
|
||||
state.currentCmd = 'shell.js';
|
||||
return retValue;
|
||||
};
|
||||
} // wrap
|
||||
exports.wrap = wrap;
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
var common = require('./common');
|
||||
var os = require('os');
|
||||
|
||||
// Buffered file copy, synchronous
|
||||
// (Using readFileSync() + writeFileSync() could easily cause a memory overflow
|
||||
// with large files)
|
||||
function copyFileSync(srcFile, destFile) {
|
||||
if (!fs.existsSync(srcFile))
|
||||
common.error('copyFileSync: no such file or directory: ' + srcFile);
|
||||
|
||||
var BUF_LENGTH = 64*1024,
|
||||
buf = new Buffer(BUF_LENGTH),
|
||||
bytesRead = BUF_LENGTH,
|
||||
pos = 0,
|
||||
fdr = null,
|
||||
fdw = null;
|
||||
|
||||
try {
|
||||
fdr = fs.openSync(srcFile, 'r');
|
||||
} catch(e) {
|
||||
common.error('copyFileSync: could not read src file ('+srcFile+')');
|
||||
}
|
||||
|
||||
try {
|
||||
fdw = fs.openSync(destFile, 'w');
|
||||
} catch(e) {
|
||||
common.error('copyFileSync: could not write to dest file (code='+e.code+'):'+destFile);
|
||||
}
|
||||
|
||||
while (bytesRead === BUF_LENGTH) {
|
||||
bytesRead = fs.readSync(fdr, buf, 0, BUF_LENGTH, pos);
|
||||
fs.writeSync(fdw, buf, 0, bytesRead);
|
||||
pos += bytesRead;
|
||||
}
|
||||
|
||||
fs.closeSync(fdr);
|
||||
fs.closeSync(fdw);
|
||||
|
||||
fs.chmodSync(destFile, fs.statSync(srcFile).mode);
|
||||
}
|
||||
|
||||
// Recursively copies 'sourceDir' into 'destDir'
|
||||
// Adapted from https://github.com/ryanmcgrath/wrench-js
|
||||
//
|
||||
// Copyright (c) 2010 Ryan McGrath
|
||||
// Copyright (c) 2012 Artur Adib
|
||||
//
|
||||
// Licensed under the MIT License
|
||||
// http://www.opensource.org/licenses/mit-license.php
|
||||
function cpdirSyncRecursive(sourceDir, destDir, opts) {
|
||||
if (!opts) opts = {};
|
||||
|
||||
/* Create the directory where all our junk is moving to; read the mode of the source directory and mirror it */
|
||||
var checkDir = fs.statSync(sourceDir);
|
||||
try {
|
||||
fs.mkdirSync(destDir, checkDir.mode);
|
||||
} catch (e) {
|
||||
//if the directory already exists, that's okay
|
||||
if (e.code !== 'EEXIST') throw e;
|
||||
}
|
||||
|
||||
var files = fs.readdirSync(sourceDir);
|
||||
|
||||
for (var i = 0; i < files.length; i++) {
|
||||
var srcFile = sourceDir + "/" + files[i];
|
||||
var destFile = destDir + "/" + files[i];
|
||||
var srcFileStat = fs.lstatSync(srcFile);
|
||||
|
||||
if (srcFileStat.isDirectory()) {
|
||||
/* recursion this thing right on back. */
|
||||
cpdirSyncRecursive(srcFile, destFile, opts);
|
||||
} else if (srcFileStat.isSymbolicLink()) {
|
||||
var symlinkFull = fs.readlinkSync(srcFile);
|
||||
fs.symlinkSync(symlinkFull, destFile, os.platform() === "win32" ? "junction" : null);
|
||||
} else {
|
||||
/* At this point, we've hit a file actually worth copying... so copy it on over. */
|
||||
if (fs.existsSync(destFile) && !opts.force) {
|
||||
common.log('skipping existing file: ' + files[i]);
|
||||
} else {
|
||||
copyFileSync(srcFile, destFile);
|
||||
}
|
||||
}
|
||||
|
||||
} // for files
|
||||
} // cpdirSyncRecursive
|
||||
|
||||
|
||||
//@
|
||||
//@ ### cp([options ,] source [,source ...], dest)
|
||||
//@ ### cp([options ,] source_array, dest)
|
||||
//@ Available options:
|
||||
//@
|
||||
//@ + `-f`: force
|
||||
//@ + `-r, -R`: recursive
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ cp('file1', 'dir1');
|
||||
//@ cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp');
|
||||
//@ cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above
|
||||
//@ ```
|
||||
//@
|
||||
//@ Copies files. The wildcard `*` is accepted.
|
||||
function _cp(options, sources, dest) {
|
||||
options = common.parseOptions(options, {
|
||||
'f': 'force',
|
||||
'R': 'recursive',
|
||||
'r': 'recursive'
|
||||
});
|
||||
|
||||
// Get sources, dest
|
||||
if (arguments.length < 3) {
|
||||
common.error('missing <source> and/or <dest>');
|
||||
} else if (arguments.length > 3) {
|
||||
sources = [].slice.call(arguments, 1, arguments.length - 1);
|
||||
dest = arguments[arguments.length - 1];
|
||||
} else if (typeof sources === 'string') {
|
||||
sources = [sources];
|
||||
} else if ('length' in sources) {
|
||||
sources = sources; // no-op for array
|
||||
} else {
|
||||
common.error('invalid arguments');
|
||||
}
|
||||
|
||||
var exists = fs.existsSync(dest),
|
||||
stats = exists && fs.statSync(dest);
|
||||
|
||||
// Dest is not existing dir, but multiple sources given
|
||||
if ((!exists || !stats.isDirectory()) && sources.length > 1)
|
||||
common.error('dest is not a directory (too many sources)');
|
||||
|
||||
// Dest is an existing file, but no -f given
|
||||
if (exists && stats.isFile() && !options.force)
|
||||
common.error('dest file already exists: ' + dest);
|
||||
|
||||
if (options.recursive) {
|
||||
// Recursive allows the shortcut syntax "sourcedir/" for "sourcedir/*"
|
||||
// (see Github issue #15)
|
||||
sources.forEach(function(src, i) {
|
||||
if (src[src.length - 1] === '/')
|
||||
sources[i] += '*';
|
||||
});
|
||||
|
||||
// Create dest
|
||||
try {
|
||||
fs.mkdirSync(dest, parseInt('0777', 8));
|
||||
} catch (e) {
|
||||
// like Unix's cp, keep going even if we can't create dest dir
|
||||
}
|
||||
}
|
||||
|
||||
sources = common.expand(sources);
|
||||
|
||||
sources.forEach(function(src) {
|
||||
if (!fs.existsSync(src)) {
|
||||
common.error('no such file or directory: '+src, true);
|
||||
return; // skip file
|
||||
}
|
||||
|
||||
// If here, src exists
|
||||
if (fs.statSync(src).isDirectory()) {
|
||||
if (!options.recursive) {
|
||||
// Non-Recursive
|
||||
common.log(src + ' is a directory (not copied)');
|
||||
} else {
|
||||
// Recursive
|
||||
// 'cp /a/source dest' should create 'source' in 'dest'
|
||||
var newDest = path.join(dest, path.basename(src)),
|
||||
checkDir = fs.statSync(src);
|
||||
try {
|
||||
fs.mkdirSync(newDest, checkDir.mode);
|
||||
} catch (e) {
|
||||
//if the directory already exists, that's okay
|
||||
if (e.code !== 'EEXIST') {
|
||||
common.error('dest file no such file or directory: ' + newDest, true);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
cpdirSyncRecursive(src, newDest, {force: options.force});
|
||||
}
|
||||
return; // done with dir
|
||||
}
|
||||
|
||||
// If here, src is a file
|
||||
|
||||
// When copying to '/path/dir':
|
||||
// thisDest = '/path/dir/file1'
|
||||
var thisDest = dest;
|
||||
if (fs.existsSync(dest) && fs.statSync(dest).isDirectory())
|
||||
thisDest = path.normalize(dest + '/' + path.basename(src));
|
||||
|
||||
if (fs.existsSync(thisDest) && !options.force) {
|
||||
common.error('dest file already exists: ' + thisDest, true);
|
||||
return; // skip file
|
||||
}
|
||||
|
||||
copyFileSync(src, thisDest);
|
||||
}); // forEach(src)
|
||||
}
|
||||
module.exports = _cp;
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
var common = require('./common');
|
||||
var _cd = require('./cd');
|
||||
var path = require('path');
|
||||
|
||||
// Pushd/popd/dirs internals
|
||||
var _dirStack = [];
|
||||
|
||||
function _isStackIndex(index) {
|
||||
return (/^[\-+]\d+$/).test(index);
|
||||
}
|
||||
|
||||
function _parseStackIndex(index) {
|
||||
if (_isStackIndex(index)) {
|
||||
if (Math.abs(index) < _dirStack.length + 1) { // +1 for pwd
|
||||
return (/^-/).test(index) ? Number(index) - 1 : Number(index);
|
||||
} else {
|
||||
common.error(index + ': directory stack index out of range');
|
||||
}
|
||||
} else {
|
||||
common.error(index + ': invalid number');
|
||||
}
|
||||
}
|
||||
|
||||
function _actualDirStack() {
|
||||
return [process.cwd()].concat(_dirStack);
|
||||
}
|
||||
|
||||
//@
|
||||
//@ ### pushd([options,] [dir | '-N' | '+N'])
|
||||
//@
|
||||
//@ Available options:
|
||||
//@
|
||||
//@ + `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated.
|
||||
//@
|
||||
//@ Arguments:
|
||||
//@
|
||||
//@ + `dir`: Makes the current working directory be the top of the stack, and then executes the equivalent of `cd dir`.
|
||||
//@ + `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack.
|
||||
//@ + `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack.
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ // process.cwd() === '/usr'
|
||||
//@ pushd('/etc'); // Returns /etc /usr
|
||||
//@ pushd('+1'); // Returns /usr /etc
|
||||
//@ ```
|
||||
//@
|
||||
//@ Save the current directory on the top of the directory stack and then cd to `dir`. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack.
|
||||
function _pushd(options, dir) {
|
||||
if (_isStackIndex(options)) {
|
||||
dir = options;
|
||||
options = '';
|
||||
}
|
||||
|
||||
options = common.parseOptions(options, {
|
||||
'n' : 'no-cd'
|
||||
});
|
||||
|
||||
var dirs = _actualDirStack();
|
||||
|
||||
if (dir === '+0') {
|
||||
return dirs; // +0 is a noop
|
||||
} else if (!dir) {
|
||||
if (dirs.length > 1) {
|
||||
dirs = dirs.splice(1, 1).concat(dirs);
|
||||
} else {
|
||||
return common.error('no other directory');
|
||||
}
|
||||
} else if (_isStackIndex(dir)) {
|
||||
var n = _parseStackIndex(dir);
|
||||
dirs = dirs.slice(n).concat(dirs.slice(0, n));
|
||||
} else {
|
||||
if (options['no-cd']) {
|
||||
dirs.splice(1, 0, dir);
|
||||
} else {
|
||||
dirs.unshift(dir);
|
||||
}
|
||||
}
|
||||
|
||||
if (options['no-cd']) {
|
||||
dirs = dirs.slice(1);
|
||||
} else {
|
||||
dir = path.resolve(dirs.shift());
|
||||
_cd('', dir);
|
||||
}
|
||||
|
||||
_dirStack = dirs;
|
||||
return _dirs('');
|
||||
}
|
||||
exports.pushd = _pushd;
|
||||
|
||||
//@
|
||||
//@ ### popd([options,] ['-N' | '+N'])
|
||||
//@
|
||||
//@ Available options:
|
||||
//@
|
||||
//@ + `-n`: Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated.
|
||||
//@
|
||||
//@ Arguments:
|
||||
//@
|
||||
//@ + `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero.
|
||||
//@ + `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero.
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ echo(process.cwd()); // '/usr'
|
||||
//@ pushd('/etc'); // '/etc /usr'
|
||||
//@ echo(process.cwd()); // '/etc'
|
||||
//@ popd(); // '/usr'
|
||||
//@ echo(process.cwd()); // '/usr'
|
||||
//@ ```
|
||||
//@
|
||||
//@ When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack.
|
||||
function _popd(options, index) {
|
||||
if (_isStackIndex(options)) {
|
||||
index = options;
|
||||
options = '';
|
||||
}
|
||||
|
||||
options = common.parseOptions(options, {
|
||||
'n' : 'no-cd'
|
||||
});
|
||||
|
||||
if (!_dirStack.length) {
|
||||
return common.error('directory stack empty');
|
||||
}
|
||||
|
||||
index = _parseStackIndex(index || '+0');
|
||||
|
||||
if (options['no-cd'] || index > 0 || _dirStack.length + index === 0) {
|
||||
index = index > 0 ? index - 1 : index;
|
||||
_dirStack.splice(index, 1);
|
||||
} else {
|
||||
var dir = path.resolve(_dirStack.shift());
|
||||
_cd('', dir);
|
||||
}
|
||||
|
||||
return _dirs('');
|
||||
}
|
||||
exports.popd = _popd;
|
||||
|
||||
//@
|
||||
//@ ### dirs([options | '+N' | '-N'])
|
||||
//@
|
||||
//@ Available options:
|
||||
//@
|
||||
//@ + `-c`: Clears the directory stack by deleting all of the elements.
|
||||
//@
|
||||
//@ Arguments:
|
||||
//@
|
||||
//@ + `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero.
|
||||
//@ + `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero.
|
||||
//@
|
||||
//@ Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified.
|
||||
//@
|
||||
//@ See also: pushd, popd
|
||||
function _dirs(options, index) {
|
||||
if (_isStackIndex(options)) {
|
||||
index = options;
|
||||
options = '';
|
||||
}
|
||||
|
||||
options = common.parseOptions(options, {
|
||||
'c' : 'clear'
|
||||
});
|
||||
|
||||
if (options['clear']) {
|
||||
_dirStack = [];
|
||||
return _dirStack;
|
||||
}
|
||||
|
||||
var stack = _actualDirStack();
|
||||
|
||||
if (index) {
|
||||
index = _parseStackIndex(index);
|
||||
|
||||
if (index < 0) {
|
||||
index = stack.length + index;
|
||||
}
|
||||
|
||||
common.log(stack[index]);
|
||||
return stack[index];
|
||||
}
|
||||
|
||||
common.log(stack.join(' '));
|
||||
|
||||
return stack;
|
||||
}
|
||||
exports.dirs = _dirs;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
var common = require('./common');
|
||||
|
||||
//@
|
||||
//@ ### echo(string [,string ...])
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ echo('hello world');
|
||||
//@ var str = echo('hello world');
|
||||
//@ ```
|
||||
//@
|
||||
//@ Prints string to stdout, and returns string with additional utility methods
|
||||
//@ like `.to()`.
|
||||
function _echo() {
|
||||
var messages = [].slice.call(arguments, 0);
|
||||
console.log.apply(this, messages);
|
||||
return common.ShellString(messages.join(' '));
|
||||
}
|
||||
module.exports = _echo;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
var common = require('./common');
|
||||
|
||||
//@
|
||||
//@ ### error()
|
||||
//@ Tests if error occurred in the last command. Returns `null` if no error occurred,
|
||||
//@ otherwise returns string explaining the error
|
||||
function error() {
|
||||
return common.state.error;
|
||||
};
|
||||
module.exports = error;
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
var common = require('./common');
|
||||
var _tempDir = require('./tempdir');
|
||||
var _pwd = require('./pwd');
|
||||
var path = require('path');
|
||||
var fs = require('fs');
|
||||
var child = require('child_process');
|
||||
|
||||
// Hack to run child_process.exec() synchronously (sync avoids callback hell)
|
||||
// Uses a custom wait loop that checks for a flag file, created when the child process is done.
|
||||
// (Can't do a wait loop that checks for internal Node variables/messages as
|
||||
// Node is single-threaded; callbacks and other internal state changes are done in the
|
||||
// event loop).
|
||||
function execSync(cmd, opts) {
|
||||
var tempDir = _tempDir();
|
||||
var stdoutFile = path.resolve(tempDir+'/'+common.randomFileName()),
|
||||
codeFile = path.resolve(tempDir+'/'+common.randomFileName()),
|
||||
scriptFile = path.resolve(tempDir+'/'+common.randomFileName()),
|
||||
sleepFile = path.resolve(tempDir+'/'+common.randomFileName());
|
||||
|
||||
var options = common.extend({
|
||||
silent: common.config.silent
|
||||
}, opts);
|
||||
|
||||
var previousStdoutContent = '';
|
||||
// Echoes stdout changes from running process, if not silent
|
||||
function updateStdout() {
|
||||
if (options.silent || !fs.existsSync(stdoutFile))
|
||||
return;
|
||||
|
||||
var stdoutContent = fs.readFileSync(stdoutFile, 'utf8');
|
||||
// No changes since last time?
|
||||
if (stdoutContent.length <= previousStdoutContent.length)
|
||||
return;
|
||||
|
||||
process.stdout.write(stdoutContent.substr(previousStdoutContent.length));
|
||||
previousStdoutContent = stdoutContent;
|
||||
}
|
||||
|
||||
function escape(str) {
|
||||
return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
|
||||
}
|
||||
|
||||
if (fs.existsSync(scriptFile)) common.unlinkSync(scriptFile);
|
||||
if (fs.existsSync(stdoutFile)) common.unlinkSync(stdoutFile);
|
||||
if (fs.existsSync(codeFile)) common.unlinkSync(codeFile);
|
||||
|
||||
var execCommand = '"'+process.execPath+'" '+scriptFile;
|
||||
var execOptions = {
|
||||
env: process.env,
|
||||
cwd: _pwd(),
|
||||
maxBuffer: 20*1024*1024
|
||||
};
|
||||
|
||||
if (typeof child.execSync === 'function') {
|
||||
var script = [
|
||||
"var child = require('child_process')",
|
||||
" , fs = require('fs');",
|
||||
"var childProcess = child.exec('"+escape(cmd)+"', {env: process.env, maxBuffer: 20*1024*1024}, function(err) {",
|
||||
" fs.writeFileSync('"+escape(codeFile)+"', err ? err.code.toString() : '0');",
|
||||
"});",
|
||||
"var stdoutStream = fs.createWriteStream('"+escape(stdoutFile)+"');",
|
||||
"childProcess.stdout.pipe(stdoutStream, {end: false});",
|
||||
"childProcess.stderr.pipe(stdoutStream, {end: false});",
|
||||
"childProcess.stdout.pipe(process.stdout);",
|
||||
"childProcess.stderr.pipe(process.stderr);",
|
||||
"var stdoutEnded = false, stderrEnded = false;",
|
||||
"function tryClosing(){ if(stdoutEnded && stderrEnded){ stdoutStream.end(); } }",
|
||||
"childProcess.stdout.on('end', function(){ stdoutEnded = true; tryClosing(); });",
|
||||
"childProcess.stderr.on('end', function(){ stderrEnded = true; tryClosing(); });"
|
||||
].join('\n');
|
||||
|
||||
fs.writeFileSync(scriptFile, script);
|
||||
|
||||
if (options.silent) {
|
||||
execOptions.stdio = 'ignore';
|
||||
} else {
|
||||
execOptions.stdio = [0, 1, 2];
|
||||
}
|
||||
|
||||
// Welcome to the future
|
||||
child.execSync(execCommand, execOptions);
|
||||
} else {
|
||||
cmd += ' > '+stdoutFile+' 2>&1'; // works on both win/unix
|
||||
|
||||
var script = [
|
||||
"var child = require('child_process')",
|
||||
" , fs = require('fs');",
|
||||
"var childProcess = child.exec('"+escape(cmd)+"', {env: process.env, maxBuffer: 20*1024*1024}, function(err) {",
|
||||
" fs.writeFileSync('"+escape(codeFile)+"', err ? err.code.toString() : '0');",
|
||||
"});"
|
||||
].join('\n');
|
||||
|
||||
fs.writeFileSync(scriptFile, script);
|
||||
|
||||
child.exec(execCommand, execOptions);
|
||||
|
||||
// The wait loop
|
||||
// sleepFile is used as a dummy I/O op to mitigate unnecessary CPU usage
|
||||
// (tried many I/O sync ops, writeFileSync() seems to be only one that is effective in reducing
|
||||
// CPU usage, though apparently not so much on Windows)
|
||||
while (!fs.existsSync(codeFile)) { updateStdout(); fs.writeFileSync(sleepFile, 'a'); }
|
||||
while (!fs.existsSync(stdoutFile)) { updateStdout(); fs.writeFileSync(sleepFile, 'a'); }
|
||||
}
|
||||
|
||||
// At this point codeFile exists, but it's not necessarily flushed yet.
|
||||
// Keep reading it until it is.
|
||||
var code = parseInt('', 10);
|
||||
while (isNaN(code)) {
|
||||
code = parseInt(fs.readFileSync(codeFile, 'utf8'), 10);
|
||||
}
|
||||
|
||||
var stdout = fs.readFileSync(stdoutFile, 'utf8');
|
||||
|
||||
// No biggie if we can't erase the files now -- they're in a temp dir anyway
|
||||
try { common.unlinkSync(scriptFile); } catch(e) {}
|
||||
try { common.unlinkSync(stdoutFile); } catch(e) {}
|
||||
try { common.unlinkSync(codeFile); } catch(e) {}
|
||||
try { common.unlinkSync(sleepFile); } catch(e) {}
|
||||
|
||||
// some shell return codes are defined as errors, per http://tldp.org/LDP/abs/html/exitcodes.html
|
||||
if (code === 1 || code === 2 || code >= 126) {
|
||||
common.error('', true); // unix/shell doesn't really give an error message after non-zero exit codes
|
||||
}
|
||||
// True if successful, false if not
|
||||
var obj = {
|
||||
code: code,
|
||||
output: stdout
|
||||
};
|
||||
return obj;
|
||||
} // execSync()
|
||||
|
||||
// Wrapper around exec() to enable echoing output to console in real time
|
||||
function execAsync(cmd, opts, callback) {
|
||||
var output = '';
|
||||
|
||||
var options = common.extend({
|
||||
silent: common.config.silent
|
||||
}, opts);
|
||||
|
||||
var c = child.exec(cmd, {env: process.env, maxBuffer: 20*1024*1024}, function(err) {
|
||||
if (callback)
|
||||
callback(err ? err.code : 0, output);
|
||||
});
|
||||
|
||||
c.stdout.on('data', function(data) {
|
||||
output += data;
|
||||
if (!options.silent)
|
||||
process.stdout.write(data);
|
||||
});
|
||||
|
||||
c.stderr.on('data', function(data) {
|
||||
output += data;
|
||||
if (!options.silent)
|
||||
process.stdout.write(data);
|
||||
});
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
//@
|
||||
//@ ### exec(command [, options] [, callback])
|
||||
//@ Available options (all `false` by default):
|
||||
//@
|
||||
//@ + `async`: Asynchronous execution. Defaults to true if a callback is provided.
|
||||
//@ + `silent`: Do not echo program output to console.
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ var version = exec('node --version', {silent:true}).output;
|
||||
//@
|
||||
//@ var child = exec('some_long_running_process', {async:true});
|
||||
//@ child.stdout.on('data', function(data) {
|
||||
//@ /* ... do something with data ... */
|
||||
//@ });
|
||||
//@
|
||||
//@ exec('some_long_running_process', function(code, output) {
|
||||
//@ console.log('Exit code:', code);
|
||||
//@ console.log('Program output:', output);
|
||||
//@ });
|
||||
//@ ```
|
||||
//@
|
||||
//@ Executes the given `command` _synchronously_, unless otherwise specified.
|
||||
//@ When in synchronous mode returns the object `{ code:..., output:... }`, containing the program's
|
||||
//@ `output` (stdout + stderr) and its exit `code`. Otherwise returns the child process object, and
|
||||
//@ the `callback` gets the arguments `(code, output)`.
|
||||
//@
|
||||
//@ **Note:** For long-lived processes, it's best to run `exec()` asynchronously as
|
||||
//@ the current synchronous implementation uses a lot of CPU. This should be getting
|
||||
//@ fixed soon.
|
||||
function _exec(command, options, callback) {
|
||||
if (!command)
|
||||
common.error('must specify command');
|
||||
|
||||
// Callback is defined instead of options.
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = { async: true };
|
||||
}
|
||||
|
||||
// Callback is defined with options.
|
||||
if (typeof options === 'object' && typeof callback === 'function') {
|
||||
options.async = true;
|
||||
}
|
||||
|
||||
options = common.extend({
|
||||
silent: common.config.silent,
|
||||
async: false
|
||||
}, options);
|
||||
|
||||
if (options.async)
|
||||
return execAsync(command, options, callback);
|
||||
else
|
||||
return execSync(command, options);
|
||||
}
|
||||
module.exports = _exec;
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
var fs = require('fs');
|
||||
var common = require('./common');
|
||||
var _ls = require('./ls');
|
||||
|
||||
//@
|
||||
//@ ### find(path [,path ...])
|
||||
//@ ### find(path_array)
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ find('src', 'lib');
|
||||
//@ find(['src', 'lib']); // same as above
|
||||
//@ find('.').filter(function(file) { return file.match(/\.js$/); });
|
||||
//@ ```
|
||||
//@
|
||||
//@ Returns array of all files (however deep) in the given paths.
|
||||
//@
|
||||
//@ The main difference from `ls('-R', path)` is that the resulting file names
|
||||
//@ include the base directories, e.g. `lib/resources/file1` instead of just `file1`.
|
||||
function _find(options, paths) {
|
||||
if (!paths)
|
||||
common.error('no path specified');
|
||||
else if (typeof paths === 'object')
|
||||
paths = paths; // assume array
|
||||
else if (typeof paths === 'string')
|
||||
paths = [].slice.call(arguments, 1);
|
||||
|
||||
var list = [];
|
||||
|
||||
function pushFile(file) {
|
||||
if (common.platform === 'win')
|
||||
file = file.replace(/\\/g, '/');
|
||||
list.push(file);
|
||||
}
|
||||
|
||||
// why not simply do ls('-R', paths)? because the output wouldn't give the base dirs
|
||||
// to get the base dir in the output, we need instead ls('-R', 'dir/*') for every directory
|
||||
|
||||
paths.forEach(function(file) {
|
||||
pushFile(file);
|
||||
|
||||
if (fs.statSync(file).isDirectory()) {
|
||||
_ls('-RA', file+'/*').forEach(function(subfile) {
|
||||
pushFile(subfile);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return list;
|
||||
}
|
||||
module.exports = _find;
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
var common = require('./common');
|
||||
var fs = require('fs');
|
||||
|
||||
//@
|
||||
//@ ### grep([options ,] regex_filter, file [, file ...])
|
||||
//@ ### grep([options ,] regex_filter, file_array)
|
||||
//@ Available options:
|
||||
//@
|
||||
//@ + `-v`: Inverse the sense of the regex and print the lines not matching the criteria.
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ grep('-v', 'GLOBAL_VARIABLE', '*.js');
|
||||
//@ grep('GLOBAL_VARIABLE', '*.js');
|
||||
//@ ```
|
||||
//@
|
||||
//@ Reads input string from given files and returns a string containing all lines of the
|
||||
//@ file that match the given `regex_filter`. Wildcard `*` accepted.
|
||||
function _grep(options, regex, files) {
|
||||
options = common.parseOptions(options, {
|
||||
'v': 'inverse'
|
||||
});
|
||||
|
||||
if (!files)
|
||||
common.error('no paths given');
|
||||
|
||||
if (typeof files === 'string')
|
||||
files = [].slice.call(arguments, 2);
|
||||
// if it's array leave it as it is
|
||||
|
||||
files = common.expand(files);
|
||||
|
||||
var grep = '';
|
||||
files.forEach(function(file) {
|
||||
if (!fs.existsSync(file)) {
|
||||
common.error('no such file or directory: ' + file, true);
|
||||
return;
|
||||
}
|
||||
|
||||
var contents = fs.readFileSync(file, 'utf8'),
|
||||
lines = contents.split(/\r*\n/);
|
||||
lines.forEach(function(line) {
|
||||
var matched = line.match(regex);
|
||||
if ((options.inverse && !matched) || (!options.inverse && matched))
|
||||
grep += line + '\n';
|
||||
});
|
||||
});
|
||||
|
||||
return common.ShellString(grep);
|
||||
}
|
||||
module.exports = _grep;
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
var common = require('./common');
|
||||
var os = require('os');
|
||||
|
||||
//@
|
||||
//@ ### ln(options, source, dest)
|
||||
//@ ### ln(source, dest)
|
||||
//@ Available options:
|
||||
//@
|
||||
//@ + `s`: symlink
|
||||
//@ + `f`: force
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ ln('file', 'newlink');
|
||||
//@ ln('-sf', 'file', 'existing');
|
||||
//@ ```
|
||||
//@
|
||||
//@ Links source to dest. Use -f to force the link, should dest already exist.
|
||||
function _ln(options, source, dest) {
|
||||
options = common.parseOptions(options, {
|
||||
's': 'symlink',
|
||||
'f': 'force'
|
||||
});
|
||||
|
||||
if (!source || !dest) {
|
||||
common.error('Missing <source> and/or <dest>');
|
||||
}
|
||||
|
||||
source = path.resolve(process.cwd(), String(source));
|
||||
dest = path.resolve(process.cwd(), String(dest));
|
||||
|
||||
if (!fs.existsSync(source)) {
|
||||
common.error('Source file does not exist', true);
|
||||
}
|
||||
|
||||
if (fs.existsSync(dest)) {
|
||||
if (!options.force) {
|
||||
common.error('Destination file exists', true);
|
||||
}
|
||||
|
||||
fs.unlinkSync(dest);
|
||||
}
|
||||
|
||||
if (options.symlink) {
|
||||
fs.symlinkSync(source, dest, os.platform() === "win32" ? "junction" : null);
|
||||
} else {
|
||||
fs.linkSync(source, dest, os.platform() === "win32" ? "junction" : null);
|
||||
}
|
||||
}
|
||||
module.exports = _ln;
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
var path = require('path');
|
||||
var fs = require('fs');
|
||||
var common = require('./common');
|
||||
var _cd = require('./cd');
|
||||
var _pwd = require('./pwd');
|
||||
|
||||
//@
|
||||
//@ ### ls([options ,] path [,path ...])
|
||||
//@ ### ls([options ,] path_array)
|
||||
//@ Available options:
|
||||
//@
|
||||
//@ + `-R`: recursive
|
||||
//@ + `-A`: all files (include files beginning with `.`, except for `.` and `..`)
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ ls('projs/*.js');
|
||||
//@ ls('-R', '/users/me', '/tmp');
|
||||
//@ ls('-R', ['/users/me', '/tmp']); // same as above
|
||||
//@ ```
|
||||
//@
|
||||
//@ Returns array of files in the given path, or in current directory if no path provided.
|
||||
function _ls(options, paths) {
|
||||
options = common.parseOptions(options, {
|
||||
'R': 'recursive',
|
||||
'A': 'all',
|
||||
'a': 'all_deprecated'
|
||||
});
|
||||
|
||||
if (options.all_deprecated) {
|
||||
// We won't support the -a option as it's hard to image why it's useful
|
||||
// (it includes '.' and '..' in addition to '.*' files)
|
||||
// For backwards compatibility we'll dump a deprecated message and proceed as before
|
||||
common.log('ls: Option -a is deprecated. Use -A instead');
|
||||
options.all = true;
|
||||
}
|
||||
|
||||
if (!paths)
|
||||
paths = ['.'];
|
||||
else if (typeof paths === 'object')
|
||||
paths = paths; // assume array
|
||||
else if (typeof paths === 'string')
|
||||
paths = [].slice.call(arguments, 1);
|
||||
|
||||
var list = [];
|
||||
|
||||
// Conditionally pushes file to list - returns true if pushed, false otherwise
|
||||
// (e.g. prevents hidden files to be included unless explicitly told so)
|
||||
function pushFile(file, query) {
|
||||
// hidden file?
|
||||
if (path.basename(file)[0] === '.') {
|
||||
// not explicitly asking for hidden files?
|
||||
if (!options.all && !(path.basename(query)[0] === '.' && path.basename(query).length > 1))
|
||||
return false;
|
||||
}
|
||||
|
||||
if (common.platform === 'win')
|
||||
file = file.replace(/\\/g, '/');
|
||||
|
||||
list.push(file);
|
||||
return true;
|
||||
}
|
||||
|
||||
paths.forEach(function(p) {
|
||||
if (fs.existsSync(p)) {
|
||||
var stats = fs.statSync(p);
|
||||
// Simple file?
|
||||
if (stats.isFile()) {
|
||||
pushFile(p, p);
|
||||
return; // continue
|
||||
}
|
||||
|
||||
// Simple dir?
|
||||
if (stats.isDirectory()) {
|
||||
// Iterate over p contents
|
||||
fs.readdirSync(p).forEach(function(file) {
|
||||
if (!pushFile(file, p))
|
||||
return;
|
||||
|
||||
// Recursive?
|
||||
if (options.recursive) {
|
||||
var oldDir = _pwd();
|
||||
_cd('', p);
|
||||
if (fs.statSync(file).isDirectory())
|
||||
list = list.concat(_ls('-R'+(options.all?'A':''), file+'/*'));
|
||||
_cd('', oldDir);
|
||||
}
|
||||
});
|
||||
return; // continue
|
||||
}
|
||||
}
|
||||
|
||||
// p does not exist - possible wildcard present
|
||||
|
||||
var basename = path.basename(p);
|
||||
var dirname = path.dirname(p);
|
||||
// Wildcard present on an existing dir? (e.g. '/tmp/*.js')
|
||||
if (basename.search(/\*/) > -1 && fs.existsSync(dirname) && fs.statSync(dirname).isDirectory) {
|
||||
// Escape special regular expression chars
|
||||
var regexp = basename.replace(/(\^|\$|\(|\)|<|>|\[|\]|\{|\}|\.|\+|\?)/g, '\\$1');
|
||||
// Translates wildcard into regex
|
||||
regexp = '^' + regexp.replace(/\*/g, '.*') + '$';
|
||||
// Iterate over directory contents
|
||||
fs.readdirSync(dirname).forEach(function(file) {
|
||||
if (file.match(new RegExp(regexp))) {
|
||||
if (!pushFile(path.normalize(dirname+'/'+file), basename))
|
||||
return;
|
||||
|
||||
// Recursive?
|
||||
if (options.recursive) {
|
||||
var pp = dirname + '/' + file;
|
||||
if (fs.lstatSync(pp).isDirectory())
|
||||
list = list.concat(_ls('-R'+(options.all?'A':''), pp+'/*'));
|
||||
} // recursive
|
||||
} // if file matches
|
||||
}); // forEach
|
||||
return;
|
||||
}
|
||||
|
||||
common.error('no such file or directory: ' + p, true);
|
||||
});
|
||||
|
||||
return list;
|
||||
}
|
||||
module.exports = _ls;
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
var common = require('./common');
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
|
||||
// Recursively creates 'dir'
|
||||
function mkdirSyncRecursive(dir) {
|
||||
var baseDir = path.dirname(dir);
|
||||
|
||||
// Base dir exists, no recursion necessary
|
||||
if (fs.existsSync(baseDir)) {
|
||||
fs.mkdirSync(dir, parseInt('0777', 8));
|
||||
return;
|
||||
}
|
||||
|
||||
// Base dir does not exist, go recursive
|
||||
mkdirSyncRecursive(baseDir);
|
||||
|
||||
// Base dir created, can create dir
|
||||
fs.mkdirSync(dir, parseInt('0777', 8));
|
||||
}
|
||||
|
||||
//@
|
||||
//@ ### mkdir([options ,] dir [, dir ...])
|
||||
//@ ### mkdir([options ,] dir_array)
|
||||
//@ Available options:
|
||||
//@
|
||||
//@ + `p`: full path (will create intermediate dirs if necessary)
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g');
|
||||
//@ mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above
|
||||
//@ ```
|
||||
//@
|
||||
//@ Creates directories.
|
||||
function _mkdir(options, dirs) {
|
||||
options = common.parseOptions(options, {
|
||||
'p': 'fullpath'
|
||||
});
|
||||
if (!dirs)
|
||||
common.error('no paths given');
|
||||
|
||||
if (typeof dirs === 'string')
|
||||
dirs = [].slice.call(arguments, 1);
|
||||
// if it's array leave it as it is
|
||||
|
||||
dirs.forEach(function(dir) {
|
||||
if (fs.existsSync(dir)) {
|
||||
if (!options.fullpath)
|
||||
common.error('path already exists: ' + dir, true);
|
||||
return; // skip dir
|
||||
}
|
||||
|
||||
// Base dir does not exist, and no -p option given
|
||||
var baseDir = path.dirname(dir);
|
||||
if (!fs.existsSync(baseDir) && !options.fullpath) {
|
||||
common.error('no such file or directory: ' + baseDir, true);
|
||||
return; // skip dir
|
||||
}
|
||||
|
||||
if (options.fullpath)
|
||||
mkdirSyncRecursive(dir);
|
||||
else
|
||||
fs.mkdirSync(dir, parseInt('0777', 8));
|
||||
});
|
||||
} // mkdir
|
||||
module.exports = _mkdir;
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
var common = require('./common');
|
||||
|
||||
//@
|
||||
//@ ### mv(source [, source ...], dest')
|
||||
//@ ### mv(source_array, dest')
|
||||
//@ Available options:
|
||||
//@
|
||||
//@ + `f`: force
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ mv('-f', 'file', 'dir/');
|
||||
//@ mv('file1', 'file2', 'dir/');
|
||||
//@ mv(['file1', 'file2'], 'dir/'); // same as above
|
||||
//@ ```
|
||||
//@
|
||||
//@ Moves files. The wildcard `*` is accepted.
|
||||
function _mv(options, sources, dest) {
|
||||
options = common.parseOptions(options, {
|
||||
'f': 'force'
|
||||
});
|
||||
|
||||
// Get sources, dest
|
||||
if (arguments.length < 3) {
|
||||
common.error('missing <source> and/or <dest>');
|
||||
} else if (arguments.length > 3) {
|
||||
sources = [].slice.call(arguments, 1, arguments.length - 1);
|
||||
dest = arguments[arguments.length - 1];
|
||||
} else if (typeof sources === 'string') {
|
||||
sources = [sources];
|
||||
} else if ('length' in sources) {
|
||||
sources = sources; // no-op for array
|
||||
} else {
|
||||
common.error('invalid arguments');
|
||||
}
|
||||
|
||||
sources = common.expand(sources);
|
||||
|
||||
var exists = fs.existsSync(dest),
|
||||
stats = exists && fs.statSync(dest);
|
||||
|
||||
// Dest is not existing dir, but multiple sources given
|
||||
if ((!exists || !stats.isDirectory()) && sources.length > 1)
|
||||
common.error('dest is not a directory (too many sources)');
|
||||
|
||||
// Dest is an existing file, but no -f given
|
||||
if (exists && stats.isFile() && !options.force)
|
||||
common.error('dest file already exists: ' + dest);
|
||||
|
||||
sources.forEach(function(src) {
|
||||
if (!fs.existsSync(src)) {
|
||||
common.error('no such file or directory: '+src, true);
|
||||
return; // skip file
|
||||
}
|
||||
|
||||
// If here, src exists
|
||||
|
||||
// When copying to '/path/dir':
|
||||
// thisDest = '/path/dir/file1'
|
||||
var thisDest = dest;
|
||||
if (fs.existsSync(dest) && fs.statSync(dest).isDirectory())
|
||||
thisDest = path.normalize(dest + '/' + path.basename(src));
|
||||
|
||||
if (fs.existsSync(thisDest) && !options.force) {
|
||||
common.error('dest file already exists: ' + thisDest, true);
|
||||
return; // skip file
|
||||
}
|
||||
|
||||
if (path.resolve(src) === path.dirname(path.resolve(thisDest))) {
|
||||
common.error('cannot move to self: '+src, true);
|
||||
return; // skip file
|
||||
}
|
||||
|
||||
fs.renameSync(src, thisDest);
|
||||
}); // forEach(src)
|
||||
} // mv
|
||||
module.exports = _mv;
|
||||
+1
@@ -0,0 +1 @@
|
||||
// see dirs.js
|
||||
+1
@@ -0,0 +1 @@
|
||||
// see dirs.js
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
var path = require('path');
|
||||
var common = require('./common');
|
||||
|
||||
//@
|
||||
//@ ### pwd()
|
||||
//@ Returns the current directory.
|
||||
function _pwd(options) {
|
||||
var pwd = path.resolve(process.cwd());
|
||||
return common.ShellString(pwd);
|
||||
}
|
||||
module.exports = _pwd;
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
var common = require('./common');
|
||||
var fs = require('fs');
|
||||
|
||||
// Recursively removes 'dir'
|
||||
// Adapted from https://github.com/ryanmcgrath/wrench-js
|
||||
//
|
||||
// Copyright (c) 2010 Ryan McGrath
|
||||
// Copyright (c) 2012 Artur Adib
|
||||
//
|
||||
// Licensed under the MIT License
|
||||
// http://www.opensource.org/licenses/mit-license.php
|
||||
function rmdirSyncRecursive(dir, force) {
|
||||
var files;
|
||||
|
||||
files = fs.readdirSync(dir);
|
||||
|
||||
// Loop through and delete everything in the sub-tree after checking it
|
||||
for(var i = 0; i < files.length; i++) {
|
||||
var file = dir + "/" + files[i],
|
||||
currFile = fs.lstatSync(file);
|
||||
|
||||
if(currFile.isDirectory()) { // Recursive function back to the beginning
|
||||
rmdirSyncRecursive(file, force);
|
||||
}
|
||||
|
||||
else if(currFile.isSymbolicLink()) { // Unlink symlinks
|
||||
if (force || isWriteable(file)) {
|
||||
try {
|
||||
common.unlinkSync(file);
|
||||
} catch (e) {
|
||||
common.error('could not remove file (code '+e.code+'): ' + file, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
else // Assume it's a file - perhaps a try/catch belongs here?
|
||||
if (force || isWriteable(file)) {
|
||||
try {
|
||||
common.unlinkSync(file);
|
||||
} catch (e) {
|
||||
common.error('could not remove file (code '+e.code+'): ' + file, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Now that we know everything in the sub-tree has been deleted, we can delete the main directory.
|
||||
// Huzzah for the shopkeep.
|
||||
|
||||
var result;
|
||||
try {
|
||||
// Retry on windows, sometimes it takes a little time before all the files in the directory are gone
|
||||
var start = Date.now();
|
||||
while (true) {
|
||||
try {
|
||||
result = fs.rmdirSync(dir);
|
||||
if (fs.existsSync(dir)) throw { code: "EAGAIN" }
|
||||
break;
|
||||
} catch(er) {
|
||||
// In addition to error codes, also check if the directory still exists and loop again if true
|
||||
if (process.platform === "win32" && (er.code === "ENOTEMPTY" || er.code === "EBUSY" || er.code === "EPERM" || er.code === "EAGAIN")) {
|
||||
if (Date.now() - start > 1000) throw er;
|
||||
} else if (er.code === "ENOENT") {
|
||||
// Directory did not exist, deletion was successful
|
||||
break;
|
||||
} else {
|
||||
throw er;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch(e) {
|
||||
common.error('could not remove directory (code '+e.code+'): ' + dir, true);
|
||||
}
|
||||
|
||||
return result;
|
||||
} // rmdirSyncRecursive
|
||||
|
||||
// Hack to determine if file has write permissions for current user
|
||||
// Avoids having to check user, group, etc, but it's probably slow
|
||||
function isWriteable(file) {
|
||||
var writePermission = true;
|
||||
try {
|
||||
var __fd = fs.openSync(file, 'a');
|
||||
fs.closeSync(__fd);
|
||||
} catch(e) {
|
||||
writePermission = false;
|
||||
}
|
||||
|
||||
return writePermission;
|
||||
}
|
||||
|
||||
//@
|
||||
//@ ### rm([options ,] file [, file ...])
|
||||
//@ ### rm([options ,] file_array)
|
||||
//@ Available options:
|
||||
//@
|
||||
//@ + `-f`: force
|
||||
//@ + `-r, -R`: recursive
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ rm('-rf', '/tmp/*');
|
||||
//@ rm('some_file.txt', 'another_file.txt');
|
||||
//@ rm(['some_file.txt', 'another_file.txt']); // same as above
|
||||
//@ ```
|
||||
//@
|
||||
//@ Removes files. The wildcard `*` is accepted.
|
||||
function _rm(options, files) {
|
||||
options = common.parseOptions(options, {
|
||||
'f': 'force',
|
||||
'r': 'recursive',
|
||||
'R': 'recursive'
|
||||
});
|
||||
if (!files)
|
||||
common.error('no paths given');
|
||||
|
||||
if (typeof files === 'string')
|
||||
files = [].slice.call(arguments, 1);
|
||||
// if it's array leave it as it is
|
||||
|
||||
files = common.expand(files);
|
||||
|
||||
files.forEach(function(file) {
|
||||
if (!fs.existsSync(file)) {
|
||||
// Path does not exist, no force flag given
|
||||
if (!options.force)
|
||||
common.error('no such file or directory: '+file, true);
|
||||
|
||||
return; // skip file
|
||||
}
|
||||
|
||||
// If here, path exists
|
||||
|
||||
var stats = fs.lstatSync(file);
|
||||
if (stats.isFile() || stats.isSymbolicLink()) {
|
||||
|
||||
// Do not check for file writing permissions
|
||||
if (options.force) {
|
||||
common.unlinkSync(file);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isWriteable(file))
|
||||
common.unlinkSync(file);
|
||||
else
|
||||
common.error('permission denied: '+file, true);
|
||||
|
||||
return;
|
||||
} // simple file
|
||||
|
||||
// Path is an existing directory, but no -r flag given
|
||||
if (stats.isDirectory() && !options.recursive) {
|
||||
common.error('path is a directory', true);
|
||||
return; // skip path
|
||||
}
|
||||
|
||||
// Recursively remove existing directory
|
||||
if (stats.isDirectory() && options.recursive) {
|
||||
rmdirSyncRecursive(file, options.force);
|
||||
}
|
||||
}); // forEach(file)
|
||||
} // rm
|
||||
module.exports = _rm;
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
var common = require('./common');
|
||||
var fs = require('fs');
|
||||
|
||||
//@
|
||||
//@ ### sed([options ,] search_regex, replacement, file)
|
||||
//@ Available options:
|
||||
//@
|
||||
//@ + `-i`: Replace contents of 'file' in-place. _Note that no backups will be created!_
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js');
|
||||
//@ sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js');
|
||||
//@ ```
|
||||
//@
|
||||
//@ Reads an input string from `file` and performs a JavaScript `replace()` on the input
|
||||
//@ using the given search regex and replacement string or function. Returns the new string after replacement.
|
||||
function _sed(options, regex, replacement, file) {
|
||||
options = common.parseOptions(options, {
|
||||
'i': 'inplace'
|
||||
});
|
||||
|
||||
if (typeof replacement === 'string' || typeof replacement === 'function')
|
||||
replacement = replacement; // no-op
|
||||
else if (typeof replacement === 'number')
|
||||
replacement = replacement.toString(); // fallback
|
||||
else
|
||||
common.error('invalid replacement string');
|
||||
|
||||
if (!file)
|
||||
common.error('no file given');
|
||||
|
||||
if (!fs.existsSync(file))
|
||||
common.error('no such file or directory: ' + file);
|
||||
|
||||
var result = fs.readFileSync(file, 'utf8').replace(regex, replacement);
|
||||
if (options.inplace)
|
||||
fs.writeFileSync(file, result, 'utf8');
|
||||
|
||||
return common.ShellString(result);
|
||||
}
|
||||
module.exports = _sed;
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
var common = require('./common');
|
||||
var os = require('os');
|
||||
var fs = require('fs');
|
||||
|
||||
// Returns false if 'dir' is not a writeable directory, 'dir' otherwise
|
||||
function writeableDir(dir) {
|
||||
if (!dir || !fs.existsSync(dir))
|
||||
return false;
|
||||
|
||||
if (!fs.statSync(dir).isDirectory())
|
||||
return false;
|
||||
|
||||
var testFile = dir+'/'+common.randomFileName();
|
||||
try {
|
||||
fs.writeFileSync(testFile, ' ');
|
||||
common.unlinkSync(testFile);
|
||||
return dir;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//@
|
||||
//@ ### tempdir()
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ var tmp = tempdir(); // "/tmp" for most *nix platforms
|
||||
//@ ```
|
||||
//@
|
||||
//@ Searches and returns string containing a writeable, platform-dependent temporary directory.
|
||||
//@ Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir).
|
||||
function _tempDir() {
|
||||
var state = common.state;
|
||||
if (state.tempDir)
|
||||
return state.tempDir; // from cache
|
||||
|
||||
state.tempDir = writeableDir(os.tempDir && os.tempDir()) || // node 0.8+
|
||||
writeableDir(process.env['TMPDIR']) ||
|
||||
writeableDir(process.env['TEMP']) ||
|
||||
writeableDir(process.env['TMP']) ||
|
||||
writeableDir(process.env['Wimp$ScrapDir']) || // RiscOS
|
||||
writeableDir('C:\\TEMP') || // Windows
|
||||
writeableDir('C:\\TMP') || // Windows
|
||||
writeableDir('\\TEMP') || // Windows
|
||||
writeableDir('\\TMP') || // Windows
|
||||
writeableDir('/tmp') ||
|
||||
writeableDir('/var/tmp') ||
|
||||
writeableDir('/usr/tmp') ||
|
||||
writeableDir('.'); // last resort
|
||||
|
||||
return state.tempDir;
|
||||
}
|
||||
module.exports = _tempDir;
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
var common = require('./common');
|
||||
var fs = require('fs');
|
||||
|
||||
//@
|
||||
//@ ### test(expression)
|
||||
//@ Available expression primaries:
|
||||
//@
|
||||
//@ + `'-b', 'path'`: true if path is a block device
|
||||
//@ + `'-c', 'path'`: true if path is a character device
|
||||
//@ + `'-d', 'path'`: true if path is a directory
|
||||
//@ + `'-e', 'path'`: true if path exists
|
||||
//@ + `'-f', 'path'`: true if path is a regular file
|
||||
//@ + `'-L', 'path'`: true if path is a symboilc link
|
||||
//@ + `'-p', 'path'`: true if path is a pipe (FIFO)
|
||||
//@ + `'-S', 'path'`: true if path is a socket
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ if (test('-d', path)) { /* do something with dir */ };
|
||||
//@ if (!test('-f', path)) continue; // skip if it's a regular file
|
||||
//@ ```
|
||||
//@
|
||||
//@ Evaluates expression using the available primaries and returns corresponding value.
|
||||
function _test(options, path) {
|
||||
if (!path)
|
||||
common.error('no path given');
|
||||
|
||||
// hack - only works with unary primaries
|
||||
options = common.parseOptions(options, {
|
||||
'b': 'block',
|
||||
'c': 'character',
|
||||
'd': 'directory',
|
||||
'e': 'exists',
|
||||
'f': 'file',
|
||||
'L': 'link',
|
||||
'p': 'pipe',
|
||||
'S': 'socket'
|
||||
});
|
||||
|
||||
var canInterpret = false;
|
||||
for (var key in options)
|
||||
if (options[key] === true) {
|
||||
canInterpret = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!canInterpret)
|
||||
common.error('could not interpret expression');
|
||||
|
||||
if (options.link) {
|
||||
try {
|
||||
return fs.lstatSync(path).isSymbolicLink();
|
||||
} catch(e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!fs.existsSync(path))
|
||||
return false;
|
||||
|
||||
if (options.exists)
|
||||
return true;
|
||||
|
||||
var stats = fs.statSync(path);
|
||||
|
||||
if (options.block)
|
||||
return stats.isBlockDevice();
|
||||
|
||||
if (options.character)
|
||||
return stats.isCharacterDevice();
|
||||
|
||||
if (options.directory)
|
||||
return stats.isDirectory();
|
||||
|
||||
if (options.file)
|
||||
return stats.isFile();
|
||||
|
||||
if (options.pipe)
|
||||
return stats.isFIFO();
|
||||
|
||||
if (options.socket)
|
||||
return stats.isSocket();
|
||||
} // test
|
||||
module.exports = _test;
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
var common = require('./common');
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
|
||||
//@
|
||||
//@ ### 'string'.to(file)
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ cat('input.txt').to('output.txt');
|
||||
//@ ```
|
||||
//@
|
||||
//@ Analogous to the redirection operator `>` in Unix, but works with JavaScript strings (such as
|
||||
//@ those returned by `cat`, `grep`, etc). _Like Unix redirections, `to()` will overwrite any existing file!_
|
||||
function _to(options, file) {
|
||||
if (!file)
|
||||
common.error('wrong arguments');
|
||||
|
||||
if (!fs.existsSync( path.dirname(file) ))
|
||||
common.error('no such file or directory: ' + path.dirname(file));
|
||||
|
||||
try {
|
||||
fs.writeFileSync(file, this.toString(), 'utf8');
|
||||
} catch(e) {
|
||||
common.error('could not write to file (code '+e.code+'): '+file, true);
|
||||
}
|
||||
}
|
||||
module.exports = _to;
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
var common = require('./common');
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
|
||||
//@
|
||||
//@ ### 'string'.toEnd(file)
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ cat('input.txt').toEnd('output.txt');
|
||||
//@ ```
|
||||
//@
|
||||
//@ Analogous to the redirect-and-append operator `>>` in Unix, but works with JavaScript strings (such as
|
||||
//@ those returned by `cat`, `grep`, etc).
|
||||
function _toEnd(options, file) {
|
||||
if (!file)
|
||||
common.error('wrong arguments');
|
||||
|
||||
if (!fs.existsSync( path.dirname(file) ))
|
||||
common.error('no such file or directory: ' + path.dirname(file));
|
||||
|
||||
try {
|
||||
fs.appendFileSync(file, this.toString(), 'utf8');
|
||||
} catch(e) {
|
||||
common.error('could not append to file (code '+e.code+'): '+file, true);
|
||||
}
|
||||
}
|
||||
module.exports = _toEnd;
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
var common = require('./common');
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
|
||||
// Cross-platform method for splitting environment PATH variables
|
||||
function splitPath(p) {
|
||||
for (i=1;i<2;i++) {}
|
||||
|
||||
if (!p)
|
||||
return [];
|
||||
|
||||
if (common.platform === 'win')
|
||||
return p.split(';');
|
||||
else
|
||||
return p.split(':');
|
||||
}
|
||||
|
||||
function checkPath(path) {
|
||||
return fs.existsSync(path) && fs.statSync(path).isDirectory() == false;
|
||||
}
|
||||
|
||||
//@
|
||||
//@ ### which(command)
|
||||
//@
|
||||
//@ Examples:
|
||||
//@
|
||||
//@ ```javascript
|
||||
//@ var nodeExec = which('node');
|
||||
//@ ```
|
||||
//@
|
||||
//@ Searches for `command` in the system's PATH. On Windows looks for `.exe`, `.cmd`, and `.bat` extensions.
|
||||
//@ Returns string containing the absolute path to the command.
|
||||
function _which(options, cmd) {
|
||||
if (!cmd)
|
||||
common.error('must specify command');
|
||||
|
||||
var pathEnv = process.env.path || process.env.Path || process.env.PATH,
|
||||
pathArray = splitPath(pathEnv),
|
||||
where = null;
|
||||
|
||||
// No relative/absolute paths provided?
|
||||
if (cmd.search(/\//) === -1) {
|
||||
// Search for command in PATH
|
||||
pathArray.forEach(function(dir) {
|
||||
if (where)
|
||||
return; // already found it
|
||||
|
||||
var attempt = path.resolve(dir + '/' + cmd);
|
||||
if (checkPath(attempt)) {
|
||||
where = attempt;
|
||||
return;
|
||||
}
|
||||
|
||||
if (common.platform === 'win') {
|
||||
var baseAttempt = attempt;
|
||||
attempt = baseAttempt + '.exe';
|
||||
if (checkPath(attempt)) {
|
||||
where = attempt;
|
||||
return;
|
||||
}
|
||||
attempt = baseAttempt + '.cmd';
|
||||
if (checkPath(attempt)) {
|
||||
where = attempt;
|
||||
return;
|
||||
}
|
||||
attempt = baseAttempt + '.bat';
|
||||
if (checkPath(attempt)) {
|
||||
where = attempt;
|
||||
return;
|
||||
}
|
||||
} // if 'win'
|
||||
});
|
||||
}
|
||||
|
||||
// Command not found anywhere?
|
||||
if (!checkPath(cmd) && !where)
|
||||
return null;
|
||||
|
||||
where = where || path.resolve(cmd);
|
||||
|
||||
return common.ShellString(where);
|
||||
}
|
||||
module.exports = _which;
|
||||
Reference in New Issue
Block a user