diff options
author | Samy Pessé <samypesse@gmail.com> | 2016-02-26 09:41:26 +0100 |
---|---|---|
committer | Samy Pessé <samypesse@gmail.com> | 2016-02-26 09:41:26 +0100 |
commit | d3d64f636c859f7f01a64f7774cf70bd8ccdc562 (patch) | |
tree | 4f7731f37c3a793d187b0ab1cd77680e69534c6c /lib/utils/command.js | |
parent | 4cb9cbb5ae3aa8f9211ffa3ac5e3d34232c0ca4f (diff) | |
parent | eef072693b17526347c37b66078a5059c71caa31 (diff) | |
download | gitbook-d3d64f636c859f7f01a64f7774cf70bd8ccdc562.zip gitbook-d3d64f636c859f7f01a64f7774cf70bd8ccdc562.tar.gz gitbook-d3d64f636c859f7f01a64f7774cf70bd8ccdc562.tar.bz2 |
Merge pull request #1109 from GitbookIO/3.0.0
Version 3.0.0
Diffstat (limited to 'lib/utils/command.js')
-rw-r--r-- | lib/utils/command.js | 80 |
1 files changed, 80 insertions, 0 deletions
diff --git a/lib/utils/command.js b/lib/utils/command.js new file mode 100644 index 0000000..de240df --- /dev/null +++ b/lib/utils/command.js @@ -0,0 +1,80 @@ +var _ = require('lodash'); +var childProcess = require('child_process'); +var spawn = require("spawn-cmd").spawn; +var Promise = require('./promise'); + +// Execute a command +function exec(command, options) { + var d = Promise.defer(); + + var child = childProcess.exec(command, options, function(err, stdout, stderr) { + if (!err) { + return d.resolve(); + } + + err.message = stdout.toString('utf8') + stderr.toString('utf8'); + d.reject(err); + }); + + child.stdout.on('data', function (data) { + d.notify(data); + }); + + child.stderr.on('data', function (data) { + d.notify(data); + }); + + return d.promise; +} + +// Spawn an executable +function spawnCmd(command, args, options) { + var d = Promise.defer(); + var child = spawn(command, args, options); + + child.on('error', function(error) { + return d.reject(error); + }); + + child.stdout.on('data', function (data) { + d.notify(data); + }); + + child.stderr.on('data', function (data) { + d.notify(data); + }); + + child.on('close', function(code) { + if (code === 0) { + d.resolve(); + } else { + d.reject(new Error('Error with command "'+command+'"')); + } + }); + + return d.promise; +} + +// Transform an option object to a command line string +function escapeShellArg(s) { + s = s.replace(/"/g, '\\"'); + return '"' + s + '"'; +} + +function optionsToShellArgs(options) { + return _.chain(options) + .map(function(value, key) { + if (value === null || value === undefined || value === false) return null; + if (value === true) return key; + return key + '=' + escapeShellArg(value); + }) + .compact() + .value() + .join(' '); +} + +module.exports = { + exec: exec, + spawn: spawnCmd, + optionsToShellArgs: optionsToShellArgs +}; |