From 0a27f18bfe96469dc17318b9bb174b8a25cfb959 Mon Sep 17 00:00:00 2001 From: Yury Delendik Date: Thu, 7 Mar 2013 10:32:16 -0600 Subject: [PATCH] Updates shell.js to v0.1.2 --- external/shelljs/ChangeLog | 22 - external/shelljs/README.md | 356 +++++++++----- external/shelljs/global.js | 2 +- external/shelljs/make.js | 6 +- external/shelljs/package.json | 5 +- external/shelljs/shell.js | 871 ++++++++++++++++++++++++++-------- 6 files changed, 923 insertions(+), 339 deletions(-) delete mode 100644 external/shelljs/ChangeLog diff --git a/external/shelljs/ChangeLog b/external/shelljs/ChangeLog deleted file mode 100644 index 23ca5d0e0..000000000 --- a/external/shelljs/ChangeLog +++ /dev/null @@ -1,22 +0,0 @@ -2012.03.22, Version 0.0.4 - -* ls() and find() return arrays instead of hashes (Artur Adib) -* exec({silent:...}) overrides global silent() state (Artur Adib) - - -2012.03.21, Version 0.0.3 - -* Wildcard bug fix (Artur Adib) -* execSync() now uses dummy file I/O op to reduce CPU usage (Artur Adib) -* Minor fixes - - -2012.03.15, Version 0.0.2 - -* New methods: find(), test() (Artur Adib) -* Deprecated non-Unix methods: exists(), verbose() - - -2012.03.03, Version 0.0.2pre1 - -* First public release diff --git a/external/shelljs/README.md b/external/shelljs/README.md index af5f05127..02de9ade6 100644 --- a/external/shelljs/README.md +++ b/external/shelljs/README.md @@ -1,18 +1,47 @@ # ShellJS - Unix shell commands for Node.js [![Build Status](https://secure.travis-ci.org/arturadib/shelljs.png)](http://travis-ci.org/arturadib/shelljs) -+ _This project is young and experimental. Use at your own risk._ -+ _Major API change as of v0.0.4: `ls()` and `find()` now return arrays._ +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! -ShellJS is a **portable** (Windows included) 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. +The project is [unit-tested](http://travis-ci.org/arturadib/shelljs) and battled-tested in projects like: -The project is [unit-tested](http://travis-ci.org/arturadib/shelljs) and is being used at Mozilla's [pdf.js](http://github.com/mozilla/pdf.js). ++ [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 ++ [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). + +## 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. -### Example +## 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'); @@ -33,7 +62,34 @@ if (exec('git commit -am "Auto-commit"').code !== 0) { } ``` -### Global vs. Local +### 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`. @@ -44,55 +100,37 @@ var shell = require('shelljs'); shell.echo('hello world'); ``` -### Make tool +## 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: +Example (CoffeeScript): -```javascript -// -// Example file: make.js -// -require('shelljs/make'); +```coffeescript +require 'shelljs/make' -target.all = function() { - target.bundle(); - target.docs(); -} +target.all = -> + target.bundle() + target.docs() -// Bundle JS files -target.bundle = function() { - cd(__dirname); - mkdir('build'); - cd('lib'); - cat('*.js').to('../build/output.js'); -} +target.bundle = -> + cd __dirname + mkdir 'build' + cd 'lib' + (cat '*.js').to '../build/output.js' -// Generate docs -target.docs = function() { - cd(__dirname); - mkdir('docs'); - cd('lib'); - ls('*.js').forEach(function(file){ - var text = grep('//@', file); // extract special comments - text.replace('//@', ''); // remove comment tags - text.to('docs/my_docs.md'); - }); -} +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`, and so on. -### Installing - -Via npm: - -```bash -$ npm install shelljs -``` - -Or simply copy `shell.js` into your project's directory, and `require()` accordingly. -# Command reference +## Command reference All commands run synchronously, unless otherwise stated. -#### cd('dir') +### cd('dir') Changes to directory `dir` for the duration of the script -#### pwd() +### pwd() Returns the current directory. -#### ls([options ,] path [,path ...]) -#### ls([options ,] path_array) +### ls([options ,] path [,path ...]) +### ls([options ,] path_array) Available options: + `-R`: recursive -+ `-a`: all files (include files beginning with `.`) ++ `-A`: all files (include files beginning with `.`, except for `.` and `..`) Examples: @@ -131,8 +169,8 @@ 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) +### find(path [,path ...]) +### find(path_array) Examples: ```javascript @@ -143,11 +181,11 @@ 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 +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') +### cp([options ,] source [,source ...], dest) +### cp([options ,] source_array, dest) Available options: + `-f`: force @@ -163,8 +201,8 @@ cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above Copies files. The wildcard `*` is accepted. -#### rm([options ,] file [, file ...]) -#### rm([options ,] file_array) +### rm([options ,] file [, file ...]) +### rm([options ,] file_array) Available options: + `-f`: force @@ -178,10 +216,10 @@ rm('some_file.txt', 'another_file.txt'); rm(['some_file.txt', 'another_file.txt']); // same as above ``` -Removes files. The wildcard `*` is accepted. +Removes files. The wildcard `*` is accepted. -#### mv(source [, source ...], dest') -#### mv(source_array, dest') +### mv(source [, source ...], dest') +### mv(source_array, dest') Available options: + `f`: force @@ -196,8 +234,8 @@ mv(['file1', 'file2'], 'dir/'); // same as above Moves files. The wildcard `*` is accepted. -#### mkdir([options ,] dir [, dir ...]) -#### mkdir([options ,] dir_array) +### mkdir([options ,] dir [, dir ...]) +### mkdir([options ,] dir_array) Available options: + `p`: full path (will create intermediate dirs if necessary) @@ -211,11 +249,17 @@ mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above Creates directories. -#### test(expression) +### 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: @@ -226,8 +270,8 @@ 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) +### cat(file [, file ...]) +### cat(file_array) Examples: @@ -241,7 +285,7 @@ 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) +### 'string'.to(file) Examples: @@ -252,7 +296,7 @@ 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!_ -#### sed([options ,] search_regex, replace_str, file) +### sed([options ,] search_regex, replace_str, file) Available options: + `-i`: Replace contents of 'file' in-place. _Note that no backups will be created!_ @@ -267,19 +311,23 @@ 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. Returns the new string after replacement. -#### grep(regex_filter, file [, file ...]) -#### grep(regex_filter, file_array) +### 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 +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) +### which(command) Examples: @@ -290,7 +338,7 @@ 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 ...]) +### echo(string [,string ...]) Examples: @@ -302,69 +350,163 @@ var str = echo('hello world'); Prints string to stdout, and returns string with additional utility methods like `.to()`. -#### exit(code) +### 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 + +### 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. + +### exit(code) Exits the current process with the given exit code. -#### env['VAR_NAME'] +### env['VAR_NAME'] Object containing environment variables (both getter and setter). Shortcut to process.env. -#### exec(command [, options] [, callback]) +### exec(command [, options] [, callback]) Available options (all `false` by default): -+ `async`: Asynchronous execution. Needs callback. ++ `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 the `callback` gets the -arguments `(code, 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. -## Non-Unix commands +### 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. + +## Configuration -#### tempdir() -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 - -#### silent([state]) +### config.silent Example: ```javascript -var silentState = silent(); -silent(true); +var silentState = config.silent; // save old silent state +config.silent = true; /* ... */ -silent(silentState); // restore old silent state +config.silent = silentState; // restore old silent state ``` -Suppresses all command output if `state = true`, except for `echo()` calls. -Returns state if no arguments given. +Suppresses all command output if `true`, except for `echo()` calls. +Default is `false`. -## Deprecated +### config.fatal +Example: + +```javascript +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`. + +## Non-Unix commands -#### exists(path [, path ...]) -#### exists(path_array) +### tempdir() +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). -_This function is being deprecated. Use `test()` instead._ - -Returns true if all the given paths exist. - -#### verbose() - -_This function is being deprecated. Use `silent(false) instead.`_ - -Enables all output (default) +### error() +Tests if error occurred in the last command. Returns `null` if no error occurred, +otherwise returns string explaining the error diff --git a/external/shelljs/global.js b/external/shelljs/global.js index 83a27e69a..97f0033cc 100644 --- a/external/shelljs/global.js +++ b/external/shelljs/global.js @@ -1,3 +1,3 @@ var shell = require('./shell.js'); -for (cmd in shell) +for (var cmd in shell) global[cmd] = shell[cmd]; diff --git a/external/shelljs/make.js b/external/shelljs/make.js index c495735bf..b636447e5 100644 --- a/external/shelljs/make.js +++ b/external/shelljs/make.js @@ -1,4 +1,5 @@ require('./global'); +config.fatal = true; global.target = {}; @@ -6,6 +7,7 @@ global.target = {}; // been evaluated var args = process.argv.slice(2); setTimeout(function() { + var t; if (args.length === 1 && args[0] === '--help') { console.log('Available targets:'); @@ -24,7 +26,7 @@ setTimeout(function() { return; oldTarget.done = true; return oldTarget.apply(oldTarget, arguments); - } + }; })(t, target[t]); } @@ -32,7 +34,7 @@ setTimeout(function() { // Execute desired targets if (args.length > 0) { args.forEach(function(arg) { - if (arg in target) + if (arg in target) target[arg](); else { console.log('no such target: ' + arg); diff --git a/external/shelljs/package.json b/external/shelljs/package.json index 4d2830cb9..efc046777 100644 --- a/external/shelljs/package.json +++ b/external/shelljs/package.json @@ -1,6 +1,6 @@ { "name": "shelljs", - "version": "0.0.5pre4", + "version": "0.1.2", "author": "Artur Adib ", "description": "Portable Unix shell commands for Node.js", "keywords": [ @@ -20,6 +20,9 @@ "scripts": { "test": "node scripts/run-tests" }, + "bin": { + "shjs": "./bin/shjs" + }, "dependencies": {}, "devDependencies": {}, "optionalDependencies": {}, diff --git a/external/shelljs/shell.js b/external/shelljs/shell.js index 92c49c54d..f0cd23630 100644 --- a/external/shelljs/shell.js +++ b/external/shelljs/shell.js @@ -16,10 +16,13 @@ var fs = require('fs'), // Node shims for < v0.7 fs.existsSync = fs.existsSync || path.existsSync; +var config = { + silent: false, + fatal: false +}; + var state = { error: null, - fatal: false, - silent: false, currentCmd: 'shell.js', tempDir: null }, @@ -28,11 +31,11 @@ var state = { //@ //@ All commands run synchronously, unless otherwise stated. -//@ +//@ //@ -//@ #### cd('dir') +//@ ### cd('dir') //@ Changes to directory `dir` for the duration of the script function _cd(options, dir) { if (!dir) @@ -45,26 +48,26 @@ function _cd(options, dir) { error('not a directory: ' + dir); process.chdir(dir); -}; +} exports.cd = wrap('cd', _cd); //@ -//@ #### pwd() +//@ ### pwd() //@ Returns the current directory. function _pwd(options) { var pwd = path.resolve(process.cwd()); return ShellString(pwd); -}; +} exports.pwd = wrap('pwd', _pwd); //@ -//@ #### ls([options ,] path [,path ...]) -//@ #### ls([options ,] path_array) +//@ ### ls([options ,] path [,path ...]) +//@ ### ls([options ,] path_array) //@ Available options: //@ //@ + `-R`: recursive -//@ + `-a`: all files (include files beginning with `.`) +//@ + `-A`: all files (include files beginning with `.`, except for `.` and `..`) //@ //@ Examples: //@ @@ -78,9 +81,18 @@ exports.pwd = wrap('pwd', _pwd); function _ls(options, paths) { options = parseOptions(options, { 'R': 'recursive', - 'a': 'all' + '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 + log('ls: Option -a is deprecated. Use -A instead'); + options.all = true; + } + if (!paths) paths = ['.']; else if (typeof paths === 'object') @@ -114,7 +126,7 @@ function _ls(options, paths) { pushFile(p, p); return; // continue } - + // Simple dir? if (fs.statSync(p).isDirectory()) { // Iterate over p contents @@ -127,7 +139,7 @@ function _ls(options, paths) { var oldDir = _pwd(); _cd('', p); if (fs.statSync(file).isDirectory()) - list = list.concat(_ls('-R'+(options.all?'a':''), file+'/*')); + list = list.concat(_ls('-R'+(options.all?'A':''), file+'/*')); _cd('', oldDir); } }); @@ -142,7 +154,7 @@ function _ls(options, paths) { // 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'); + var regexp = basename.replace(/(\^|\$|\(|\)|<|>|\[|\]|\{|\}|\.|\+|\?)/g, '\\$1'); // Translates wildcard into regex regexp = '^' + regexp.replace(/\*/g, '.*') + '$'; // Iterate over directory contents @@ -155,7 +167,7 @@ function _ls(options, paths) { if (options.recursive) { var pp = dirname + '/' + file; if (fs.statSync(pp).isDirectory()) - list = list.concat(_ls('-R'+(options.all?'a':''), pp+'/*')); + list = list.concat(_ls('-R'+(options.all?'A':''), pp+'/*')); } // recursive } // if file matches }); // forEach @@ -166,13 +178,13 @@ function _ls(options, paths) { }); return list; -}; +} exports.ls = wrap('ls', _ls); //@ -//@ #### find(path [,path ...]) -//@ #### find(path_array) +//@ ### find(path [,path ...]) +//@ ### find(path_array) //@ Examples: //@ //@ ```javascript @@ -183,7 +195,7 @@ exports.ls = wrap('ls', _ls); //@ //@ Returns array of all files (however deep) in the given paths. //@ -//@ The main difference from `ls('-R', path)` is that the resulting file names +//@ 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) @@ -208,7 +220,7 @@ function _find(options, paths) { pushFile(file); if (fs.statSync(file).isDirectory()) { - _ls('-Ra', file+'/*').forEach(function(subfile) { + _ls('-RA', file+'/*').forEach(function(subfile) { pushFile(subfile); }); } @@ -220,8 +232,8 @@ exports.find = wrap('find', _find); //@ -//@ #### cp('[options ,] source [,source ...], dest') -//@ #### cp('[options ,] source_array, dest') +//@ ### cp([options ,] source [,source ...], dest) +//@ ### cp([options ,] source_array, dest) //@ Available options: //@ //@ + `-f`: force @@ -265,6 +277,22 @@ function _cp(options, sources, dest) { if (fs.existsSync(dest) && fs.statSync(dest).isFile() && !options.force) 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 = expand(sources); sources.forEach(function(src) { @@ -274,7 +302,6 @@ function _cp(options, sources, dest) { } // If here, src exists - if (fs.statSync(src).isDirectory()) { if (!options.recursive) { // Non-Recursive @@ -282,7 +309,7 @@ function _cp(options, sources, dest) { } else { // Recursive // 'cp /a/source dest' should create 'source' in 'dest' - var newDest = dest+'/'+path.basename(src), + var newDest = path.join(dest, path.basename(src)), checkDir = fs.statSync(src); try { fs.mkdirSync(newDest, checkDir.mode); @@ -290,6 +317,7 @@ function _cp(options, sources, dest) { //if the directory already exists, that's okay if (e.code !== 'EEXIST') throw e; } + cpdirSyncRecursive(src, newDest, {force: options.force}); } return; // done with dir @@ -310,12 +338,12 @@ function _cp(options, sources, dest) { copyFileSync(src, thisDest); }); // forEach(src) -}; // cp +} exports.cp = wrap('cp', _cp); //@ -//@ #### rm([options ,] file [, file ...]) -//@ #### rm([options ,] file_array) +//@ ### rm([options ,] file [, file ...]) +//@ ### rm([options ,] file_array) //@ Available options: //@ //@ + `-f`: force @@ -329,7 +357,7 @@ exports.cp = wrap('cp', _cp); //@ rm(['some_file.txt', 'another_file.txt']); // same as above //@ ``` //@ -//@ Removes files. The wildcard `*` is accepted. +//@ Removes files. The wildcard `*` is accepted. function _rm(options, files) { options = parseOptions(options, { 'f': 'force', @@ -364,7 +392,7 @@ function _rm(options, files) { _unlinkSync(file); return; } - + if (isWriteable(file)) _unlinkSync(file); else @@ -384,12 +412,12 @@ function _rm(options, files) { rmdirSyncRecursive(file, options.force); } }); // forEach(file) -}; // rm +} // rm exports.rm = wrap('rm', _rm); //@ -//@ #### mv(source [, source ...], dest') -//@ #### mv(source_array, dest') +//@ ### mv(source [, source ...], dest') +//@ ### mv(source_array, dest') //@ Available options: //@ //@ + `f`: force @@ -458,12 +486,12 @@ function _mv(options, sources, dest) { fs.renameSync(src, thisDest); }); // forEach(src) -}; // mv +} // mv exports.mv = wrap('mv', _mv); //@ -//@ #### mkdir([options ,] dir [, dir ...]) -//@ #### mkdir([options ,] dir_array) +//@ ### mkdir([options ,] dir [, dir ...]) +//@ ### mkdir([options ,] dir_array) //@ Available options: //@ //@ + `p`: full path (will create intermediate dirs if necessary) @@ -504,17 +532,23 @@ function _mkdir(options, dirs) { if (options.fullpath) mkdirSyncRecursive(dir); else - fs.mkdirSync(dir, 0777); + fs.mkdirSync(dir, parseInt('0777', 8)); }); -}; // mkdir +} // mkdir exports.mkdir = wrap('mkdir', _mkdir); //@ -//@ #### test(expression) +//@ ### 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: //@ @@ -530,24 +564,61 @@ function _test(options, path) { // hack - only works with unary primaries options = parseOptions(options, { + 'b': 'block', + 'c': 'character', 'd': 'directory', - 'f': 'file' + 'e': 'exists', + 'f': 'file', + 'L': 'link', + 'p': 'pipe', + 'S': 'socket' }); - if (!options.directory && !options.file) + + var canInterpret = false; + for (var key in options) + if (options[key] === true) { + canInterpret = true; + break; + } + + if (!canInterpret) error('could not interpret expression'); + if (!fs.existsSync(path)) + return false; + + if (options.exists) + return true; + + if (options.link) + return fs.lstatSync(path).isSymbolicLink(); + + var stats = fs.statSync(path); + + if (options.block) + return stats.isBlockDevice(); + + if (options.character) + return stats.isCharacterDevice(); + if (options.directory) - return fs.existsSync(path) && fs.statSync(path).isDirectory(); + return stats.isDirectory(); if (options.file) - return fs.existsSync(path) && fs.statSync(path).isFile(); -}; // test + return stats.isFile(); + + if (options.pipe) + return stats.isFIFO(); + + if (options.socket) + return stats.isSocket(); +} // test exports.test = wrap('test', _test); //@ -//@ #### cat(file [, file ...]) -//@ #### cat(file_array) +//@ ### cat(file [, file ...]) +//@ ### cat(file_array) //@ //@ Examples: //@ @@ -583,11 +654,11 @@ function _cat(options, files) { cat = cat.substring(0, cat.length-1); return ShellString(cat); -}; +} exports.cat = wrap('cat', _cat); //@ -//@ #### 'string'.to(file) +//@ ### 'string'.to(file) //@ //@ Examples: //@ @@ -609,8 +680,8 @@ function _to(options, file) { } catch(e) { error('could not write to file (code '+e.code+'): '+file, true); } -}; -// In the future, when Proxies are default, we can add methods like `.to()` to primitive strings. +} +// 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; @@ -618,7 +689,7 @@ function ShellString(str) { String.prototype.to = wrap('to', _to); //@ -//@ #### sed([options ,] search_regex, replace_str, file) +//@ ### sed([options ,] search_regex, replace_str, file) //@ Available options: //@ //@ + `-i`: Replace contents of 'file' in-place. _Note that no backups will be created!_ @@ -655,22 +726,30 @@ function _sed(options, regex, replacement, file) { fs.writeFileSync(file, result, 'utf8'); return ShellString(result); -}; +} exports.sed = wrap('sed', _sed); //@ -//@ #### grep(regex_filter, file [, file ...]) -//@ #### grep(regex_filter, file_array) +//@ ### 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 +//@ 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 = parseOptions(options, { + 'v': 'inverse' + }); + if (!files) error('no paths given'); @@ -690,18 +769,19 @@ function _grep(options, regex, files) { var contents = fs.readFileSync(file, 'utf8'), lines = contents.split(/\r*\n/); lines.forEach(function(line) { - if (line.match(regex)) + var matched = line.match(regex); + if ((options.inverse && !matched) || (!options.inverse && matched)) grep += line + '\n'; }); }); return ShellString(grep); -}; +} exports.grep = wrap('grep', _grep); //@ -//@ #### which(command) +//@ ### which(command) //@ //@ Examples: //@ @@ -752,7 +832,7 @@ function _which(options, cmd) { } // if 'win' }); } - + // Command not found anywhere? if (!fs.existsSync(cmd) && !where) return null; @@ -760,11 +840,11 @@ function _which(options, cmd) { where = where || path.resolve(cmd); return ShellString(where); -}; +} exports.which = wrap('which', _which); //@ -//@ #### echo(string [,string ...]) +//@ ### echo(string [,string ...]) //@ //@ Examples: //@ @@ -775,40 +855,237 @@ exports.which = wrap('which', _which); //@ //@ Prints string to stdout, and returns string with additional utility methods //@ like `.to()`. -function _echo(options) { - var messages = [].slice.call(arguments, 1); +function _echo() { + var messages = [].slice.call(arguments, 0); console.log.apply(this, messages); return ShellString(messages.join(' ')); -}; -exports.echo = wrap('echo', _echo); +} +exports.echo = _echo; // don't wrap() as it could parse '-options' + +// 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 { + error(index + ': directory stack index out of range'); + } + } else { + error(index + ': invalid number'); + } +} + +function _actualDirStack() { + return [process.cwd()].concat(_dirStack); +} //@ -//@ #### exit(code) +//@ ### 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 = parseOptions(options, { + 'c' : 'clear' + }); + + if (options['clear']) { + return (_dirStack = []); + } + + var stack = _actualDirStack(); + + if (index) { + index = _parseStackIndex(index); + + if (index < 0) { + index = stack.length + index; + } + + log(stack[index]); + return stack[index]; + } + + log(stack.join(' ')); + + return stack; +} +exports.dirs = wrap("dirs", _dirs); + +//@ +//@ ### 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 = 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 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 = wrap('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 = parseOptions(options, { + 'n' : 'no-cd' + }); + + if (!_dirStack.length) { + return 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 = wrap("popd", _popd); + +//@ +//@ ### exit(code) //@ Exits the current process with the given exit code. exports.exit = process.exit; //@ -//@ #### env['VAR_NAME'] +//@ ### env['VAR_NAME'] //@ Object containing environment variables (both getter and setter). Shortcut to process.env. exports.env = process.env; //@ -//@ #### exec(command [, options] [, callback]) +//@ ### exec(command [, options] [, callback]) //@ Available options (all `false` by default): //@ -//@ + `async`: Asynchronous execution. Needs callback. +//@ + `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 the `callback` gets the -//@ arguments `(code, 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 @@ -819,21 +1096,262 @@ function _exec(command, options, callback) { if (typeof options === 'function') { callback = options; - options = {}; + options = { async: true }; } options = extend({ - silent: state.silent, + silent: config.silent, async: false }, options); if (options.async) - execAsync(command, options, callback); + return execAsync(command, options, callback); else return execSync(command, options); -}; +} exports.exec = wrap('exec', _exec, {notUnix:true}); +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 { + error('You must specify a file.'); + } + } + + options = parseOptions(options, { + 'R': 'recursive', + 'c': 'changes', + 'v': 'verbose' + }); + + if (typeof filePattern === 'string') { + filePattern = [ filePattern ]; + } + + var files; + + if (options.recursive) { + files = []; + 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 = expand(filePattern); + } + + files.forEach(function innerChmod(file) { + file = path.resolve(file); + if (!fs.existsSync(file)) { + 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 { + 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); + } + }); +} +exports.chmod = wrap('chmod', _chmod); + + +//@ +//@ ## Configuration +//@ + + + +exports.config = config; + +//@ +//@ ### config.silent +//@ Example: +//@ +//@ ```javascript +//@ var silentState = config.silent; // save old silent state +//@ config.silent = true; +//@ /* ... */ +//@ config.silent = silentState; // restore old silent state +//@ ``` +//@ +//@ Suppresses all command output if `true`, except for `echo()` calls. +//@ Default is `false`. + +//@ +//@ ### config.fatal +//@ Example: +//@ +//@ ```javascript +//@ 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`. + @@ -847,92 +1365,19 @@ exports.exec = wrap('exec', _exec, {notUnix:true}); //@ -//@ #### tempdir() +//@ ### tempdir() //@ 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). exports.tempdir = wrap('tempdir', tempDir); //@ -//@ #### error() +//@ ### error() //@ Tests if error occurred in the last command. Returns `null` if no error occurred, //@ otherwise returns string explaining the error exports.error = function() { return state.error; -} - -//@ -//@ #### silent([state]) -//@ Example: -//@ -//@ ```javascript -//@ var silentState = silent(); -//@ silent(true); -//@ /* ... */ -//@ silent(silentState); // restore old silent state -//@ ``` -//@ -//@ Suppresses all command output if `state = true`, except for `echo()` calls. -//@ Returns state if no arguments given. -exports.silent = function(_state) { - if (typeof _state !== 'boolean') - return state.silent; - - state.silent = _state; -} - - -//@ -//@ ## Deprecated -//@ - - - - -//@ -//@ #### exists(path [, path ...]) -//@ #### exists(path_array) -//@ -//@ _This function is being deprecated. Use `test()` instead._ -//@ -//@ Returns true if all the given paths exist. -function _exists(options, paths) { - deprecate('exists', 'Use test() instead.'); - - if (!paths) - error('no paths given'); - - if (typeof paths === 'string') - paths = [].slice.call(arguments, 1); - // if it's array leave it as it is - - var exists = true; - paths.forEach(function(p) { - if (!fs.existsSync(p)) - exists = false; - }); - - return exists; }; -exports.exists = wrap('exists', _exists); - - -//@ -//@ #### verbose() -//@ -//@ _This function is being deprecated. Use `silent(false) instead.`_ -//@ -//@ Enables all output (default) -exports.verbose = function() { - deprecate('verbose', 'Use silent(false) instead.'); - - state.silent = false; -} - - - - - @@ -944,7 +1389,7 @@ exports.verbose = function() { // function log() { - if (!state.silent) + if (!config.silent) console.log.apply(this, arguments); } @@ -953,18 +1398,21 @@ function deprecate(what, msg) { } function write(msg) { - if (!state.silent) + if (!config.silent) process.stdout.write(msg); } -// Shows error message. Throws unless '_continue = true'. +// 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'; - + log(state.error); + if (config.fatal) + process.exit(1); + if (!_continue) throw ''; } @@ -977,7 +1425,7 @@ function parseOptions(str, map) { // All options are false by default var options = {}; - for (letter in map) + for (var letter in map) options[map[letter]] = false; if (!str) @@ -1029,13 +1477,13 @@ function wrap(cmd, fn, options) { console.log(e.stack || e); process.exit(1); } - if (state.fatal) + if (config.fatal) throw e; } state.currentCmd = 'shell.js'; return retValue; - } + }; } // wrap // Buffered file copy, synchronous @@ -1115,7 +1563,7 @@ function cpdirSyncRecursive(sourceDir, destDir, opts) { } } // for files -}; // cpdirSyncRecursive +} // cpdirSyncRecursive // Recursively removes 'dir' // Adapted from https://github.com/ryanmcgrath/wrench-js @@ -1140,16 +1588,26 @@ function rmdirSyncRecursive(dir, force) { } else if(currFile.isSymbolicLink()) { // Unlink symlinks - if (force || isWriteable(file)) - _unlinkSync(file); + if (force || isWriteable(file)) { + try { + _unlinkSync(file); + } catch (e) { + 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)) - _unlinkSync(file); + if (force || isWriteable(file)) { + try { + _unlinkSync(file); + } catch (e) { + 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. + // Now that we know everything in the sub-tree has been deleted, we can delete the main directory. // Huzzah for the shopkeep. var result; @@ -1160,7 +1618,7 @@ function rmdirSyncRecursive(dir, force) { } return result; -}; // rmdirSyncRecursive +} // rmdirSyncRecursive // Recursively creates 'dir' function mkdirSyncRecursive(dir) { @@ -1168,7 +1626,7 @@ function mkdirSyncRecursive(dir) { // Base dir exists, no recursion necessary if (fs.existsSync(baseDir)) { - fs.mkdirSync(dir, 0777); + fs.mkdirSync(dir, parseInt('0777', 8)); return; } @@ -1176,14 +1634,14 @@ function mkdirSyncRecursive(dir) { mkdirSyncRecursive(baseDir); // Base dir created, can create dir - fs.mkdirSync(dir, 0777); -}; + fs.mkdirSync(dir, parseInt('0777', 8)); +} // e.g. 'makerjs_a5f185d0443ca...' function randomFileName() { function randomHash(count) { if (count === 1) - return parseInt(16*Math.random()).toString(16); + return parseInt(16*Math.random(), 10).toString(16); else { var hash = ''; for (var i=0; i&1'; // works on both win/unix - var script = - "var child = require('child_process'), \ - fs = require('fs'); \ - child.exec('"+escape(cmd)+"', {env: process.env}, function(err) { \ - fs.writeFileSync('"+escape(codeFile)+"', err ? err.code.toString() : '0'); \ - });"; + var script = + "var child = require('child_process')," + + " fs = require('fs');" + + "child.exec('"+escape(cmd)+"', {env: process.env}, function(err) {" + + " fs.writeFileSync('"+escape(codeFile)+"', err ? err.code.toString() : '0');" + + "});"; if (fs.existsSync(scriptFile)) _unlinkSync(scriptFile); if (fs.existsSync(stdoutFile)) _unlinkSync(stdoutFile); if (fs.existsSync(codeFile)) _unlinkSync(codeFile); fs.writeFileSync(scriptFile, script); - child.exec('node '+scriptFile, { + child.exec('"'+process.execPath+'" '+scriptFile, { env: process.env, cwd: exports.pwd() }); @@ -1321,23 +1779,24 @@ function execSync(cmd, opts) { // 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'); }; + 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(''); - while (isNaN(code)) - code = parseInt(fs.readFileSync(codeFile, 'utf8')); + 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 { _unlinkSync(scriptFile); } catch(e) {}; - try { _unlinkSync(stdoutFile); } catch(e) {}; - try { _unlinkSync(codeFile); } catch(e) {}; - try { _unlinkSync(sleepFile); } catch(e) {}; - + try { _unlinkSync(scriptFile); } catch(e) {} + try { _unlinkSync(stdoutFile); } catch(e) {} + try { _unlinkSync(codeFile); } catch(e) {} + try { _unlinkSync(sleepFile); } catch(e) {} + // True if successful, false if not var obj = { code: code, @@ -1346,14 +1805,15 @@ function execSync(cmd, opts) { return obj; } // execSync() -// Expands wildcards with matching file names. For a given array of file names 'list', returns -// another array containing all file names as per ls(list[i]). -// For example: expand(['file*.js']) = ['file1.js', 'file2.js', ...] -// (if the files 'file1.js', 'file2.js', etc, exist in the current dir) +// Expands wildcards with matching file names. For a given array of file names 'list', returns +// another array containing all file names as per ls(list[i]). +// 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? + // Wildcard present? if (listEl.search(/\*/) > -1) { _ls('', listEl).forEach(function(file) { expanded.push(file); @@ -1361,7 +1821,7 @@ function expand(list) { } else { expanded.push(listEl); } - }); + }); return expanded; } @@ -1378,15 +1838,14 @@ function splitPath(p) { // extend(target_obj, source_obj1 [, source_obj2 ...]) // Shallow extend, e.g.: -// aux.extend({a:1}, {b:2}, {c:3}) -// returns {a:1, b:2, c:3} +// 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 (key in source) + for (var key in source) target[key] = source[key]; }); - + return target; }