execPromise

@param {string} command
@returns {Promise} stdout or stderr if fails
354828
function execPromise (cmd) {
  if (isTest) {
    return Promise.resolve(cmd)
  }
  return new Promise((resolve, reject) => {
    exec(cmd, (err, stdout, stderr) => {
      if (err || stderr) reject(err || stderr)
      else resolve(stdout)
    })
  })
}
74538
function checkCommand (command, errorCallback) {
    var exec = command
    var args = this.argsExecutable
    var shell = false
    if (this.win) {
      // Arguments have to be manually quoted
      exec = `"${exec}"`
      args = args.map(a => `"${a}"`)
      shell = true
    }

    this.log.verbose(`- executing "${command}" to get executable path`)
    this.run(exec, args, shell, function (err, execPath) {
      // Possible outcomes:
      // - Error: not in PATH, not executable or execution fails
      // - Gibberish: the next command to check version will fail
      // - Absolute path to executable
      if (err) {
        this.addLog(`- "${command}" is not in PATH or produced an error`)
        return errorCallback(err)
      }
      this.addLog(`- executable path is "${execPath}"`)
      this.checkExecPath(execPath, errorCallback)
    }.bind(this))
  }
5660
function execSpawn(command, args, resultMsg, errorMsg) {
    return superspawn.spawn(command, args).then(function(result) {
        return resultMsg + result;
    }, function(error) {
        return errorMsg + error;
    });
}
188776
function (data) {
  var q = _q.defer();
  data = data.replace(/\'/g,"\\\'");
  data = data.replace(/\"/g,'\\\"');
  exec(`echo "${data}" | crontab -`, (err, stdout, stderr) => {
    if (err) q.reject(err);
    if(stdout)q.resolve(stdout);
    else q.resolve(stderr);
  });
  return q.promise;
}
14005
function runCommand(cmd) {
  return exec(cmd).catch(err =>
    Promise.reject(
      err.message && err.message.indexOf('not found') !== -1
        ? new Error(`${cmd.split(' ')[0]} must be installed to upload`)
        : err
    )
  )
}
993173
function run(cmd) {
        return function (callback, options) {
            grunt.verbose.or.ok("Executing " + cmd);
            exec(cmd, options || {}, function (error, stdout, stderr) {
                if (error) {
                    grunt.fatal("'" + cmd + "' failed with :" + stderr);
                } else {
                    grunt.verbose.writeln("Result of " + cmd + ':\n' + stdout);
                    callback();
                }
            });
        };
    }
1198359
function ChildProcessFactory (
    nodeChildProcess,
    Errors,
    Logger,
    assert,
    util,
    Promise,
    Constants,
    _,
    fs,
    path
) {
    var logger = Logger.initialize(ChildProcessFactory);

    /**
     * ChildProcess provides a promise based mechanism to run shell commands
     * in a fairly secure manner.
     * @constructor
     */
    function ChildProcess (command, args, env, code, maxBuffer) {
        var self = this;

        assert.string(command);
        assert.optionalArrayOfNumber(code);

        self.command = command;
        self.file = self._parseCommandPath(self.command);
        self.args = args;
        self.environment = env || {};
        self.exitCode = code || [0];
        self.maxBuffer = maxBuffer || Constants.ChildProcess.MaxBuffer;

        if (!self.file) {
            throw new Error('Unable to locate command file (' + self.command +').');
        }
        if (!_.isEmpty(self.args)) {
            try {
                assert.arrayOfString(self.args, 'ChildProcess command arguments');
            } catch (e) {
                throw new Error('args must be an array of strings');
            }
        }

        self.hasBeenKilled = false;
        self.hasBeenCancelled = false;
        self.spawnInstance = undefined;
    }

    ChildProcess.prototype.createOwnDeferred = function() {
        var self = this;
        self._deferred = new Promise(function(resolve, reject) {
            self._resolve = resolve;
            self._reject = reject;
        });
    };

    ChildProcess.prototype.resolve = function(result) {
        if (!this._deferred.isPending()) {
            logger.error("ChildProcess promise has already been resolved");
            return;
        } else {
            this._resolve(result);
        }
    };

    ChildProcess.prototype.reject = function(error) {
        if (!this._deferred.isPending()) {
            logger.error("ChildProcess promise has already been rejected");
            return;
        } else {
            this._reject(error);
        }
    };

    ChildProcess.prototype.killSafe = function (signal) {
        if (!this.hasBeenKilled && this.spawnInstance && _.isFunction(this.spawnInstance.kill)) {
            this.spawnInstance.kill(signal);
        }
        this.hasBeenCancelled = true;
    };

    /**
     * Runs the given command.
     * @param  {String} command File to run, with path or without.
     * @param  {String[]} args    Arguments to the file.
     * @param  {Object} env     Optional environment variables to provide.
     * @param  {Integer} code   Desired exit code, defaults to 0.
     * @return {Promise}        A promise fulfilled with the stdout, stderr of
     * a successful command.
     */
    ChildProcess.prototype._run = function () {
        var self = this;

        if (self.hasBeenCancelled) {
            self.reject(new Errors.JobKilledError("ChildProcess job has been cancelled", {
                command: self.command,
                argv: self.args
            }));
            return;
        }

        self.hasBeenKilled = false;

        var options = {
            env: self.environment,
            maxBuffer: self.maxBuffer
        };

        self.spawnInstance = nodeChildProcess.execFile(
                self.file, self.args, options, function (error, stdout, stderr) {

            if (error && self.exitCode.indexOf(error.code) === -1) {
                self.hasBeenKilled = true;
                logger.error('Error Running ChildProcess.', {
                    file: self.file,
                    argv: self.args,
                    stdout: stdout,
                    stderr: stderr,
                    error: error
                });
                self.reject(error);
            } else {
                self.hasBeenKilled = true;
                self.resolve({
                    stdout: stdout,
                    stderr: stderr
                });
            }
        })
        .on('close', function(code, signal) {
            if (signal) {
                logger.warning("Child process received closing signal:", {
                    signal: signal,
                    argv: self.args
                });
            }
            self.hasBeenKilled = true;
        })
        .on('error', function(code, signal) {
            logger.error("Child process received closing signal but has " +
                "already been closed!!!", {
                signal: signal,
                argv: self.args
            });
        });
    };

    ChildProcess.prototype._runWithRetries = function(retryCount, delay, retries) {
        var self = this;

        // Max out exponential backoff to 60 seconds.
        delay = delay > 60000 ? 60000 : delay;

        if (!self._deferred) {
            self.createOwnDeferred();
        }

        self._run();

        return self._deferred.catch(function(e) {
            if (e instanceof Errors.JobKilledError) {
                throw e;
            } else if (retryCount < retries) {
                logger.debug("Retrying ChildProcess command.", {
                    file: self.file,
                    args: self.args
                });
                // Create new deferred promise in here instead of above, in case we receive an
                // external cancellation during the below delay, so we don't
                // try to reject using the previous deferred object.
                self.createOwnDeferred();
                return Promise.delay(delay)
                .then(function() {
                    return self._runWithRetries(retryCount + 1, delay * 2, retries);
                });
            } else {
                throw e;
            }
        });
    };

    ChildProcess.prototype.run = function(options) {
        options = options || {};
        options.retries = options.retries || 0;
        if (options.delay !== 0) {
            options.delay = options.delay || 500;
        }

        return this._runWithRetries(0, options.delay, options.retries);
    };

    /**
     * Internal method to identify the path to the command file.  It's essentially
     * unix which in JavaScript.
     * @private
     */
    ChildProcess.prototype._parseCommandPath = function _parseCommandPath (command) {
        var self = this;

        if (self._fileExists(command)) {
            return command;
        } else {
            var found = _.some(self._getPaths(), function (current) {
                var target = path.resolve(current + '/' + command);

                if (self._fileExists(target)) {
                    command = target;

                    return true;
                }
            });

            return found ? command : null;
        }
    };

    /**
     * Internal method to verify a file exists and is not a directory.
     * @private
     */
    ChildProcess.prototype._fileExists = function _fileExists (file) {
        return fs.existsSync(file) && !fs.statSync(file).isDirectory();
    };

    /**
     * Internal method to get an array of directories in the users path.
     * @private
     */
    ChildProcess.prototype._getPaths = function _getPaths () {
        var path = process.env.path || process.env.Path || process.env.PATH;
        return path.split(':');
    };

    return ChildProcess;
}
821505
function execute(/*args*/) {

  const command = prepare_command(arguments);
  ensure_executable(command);
  create_result_file_name(command);

  return platform.execute(command)
  //Handle Results
  .then(() => new Promise((resolve,reject) => {

    const results = get_results(command);
    if (results == null)
      resolve();

    if (is(results, Error))
      reject(Errors.NoResult);

    if (is(results.returned, Error))
      reject(new AfterEffectsError(results.returned.message));
    else
      resolve(results.returned);
  }));
}
370178
function execute(cmd) {
  return new Promise((resolve, reject) => {
    exec(cmd, function(err, stdout) {
      if (err) {
        reject(err);
      } else {
        resolve(stdout);
      }
    });
  });
}
1100885
function createGitCmdPromise(args) {
  return new Promise(function(resolve, reject) {

    //Remove null values from the final git arguments
    args = args.filter(function(arg) {
      /*jshint eqnull:true */
      return arg != null;
    });

    /**
     * @name git#command
     * @event
     * @param {String} String the command issued
     */
    events.emit('command', [gitCmd].concat(args).join(' '));
    var proc = spawn(gitCmd, args);

    var output = Promise.join(readStream(proc.stdout), readStream(proc.stderr), function(stdout, stderr) {
      //Some warnings (like code === 1) are in stdout
      //fatal are in stderr. So try both
      return stdout || stderr;
    }).tap(function(output) {
      /**
       * @name git#result
       * @event
       * @param {String} String the captured output
       */
      events.emit('result', output);
    });

    proc.on('close', function(code) {
      //Some weird behaviours can arise with stdout and stderr values
      //cause writting to then is sync in *nix and async in windows.
      //Also, excessive treatment or long outputs that cause a drain
      //in the stderr & stdout streams, could lead us to having this proc
      //closed (and this callback called), and no complete values captured
      //in an eventual closure variable set then we emit the 'result' event
      //So using promises solves this syncronization
      output.then(function(output) {
        if (code !== 0) {
          var error = new Error('git exited with an error');
          error.code = code;
          error.output = output;
          reject(error);
        } else {
          resolve(output);
        }
      });
    });

    proc.on('error', function(error) {
      reject(new Error(error));
    });
  });
}
860993
function execFile(cmd, args, opts) {
    const deferred = Q.defer();
    childProcess.execFile(cmd, args, opts, function(err, stdout, stderr) {
        if (err) {
            console.error("Error executing " + cmd + " " + args.join(" "));
            console.error(stdout + stderr);
            err.stdout = stdout;
            err.stderr = stderr;
            deferred.reject(err);
        } else {
            deferred.resolve(stdout);
        }
    });
    return deferred.promise;
}
155154
def _exec_command(self, command: str):
        
        stdin, stdout, stderr = self._ssh.exec_command(command)
        # Clearing the buffers
        stdout.read()
        stderr.read()
        stdin.close()
1283826
function doExec(callback, command) {
    let args = Array.prototype.slice.call(arguments);
    args.splice(0, 2);  //remove the first cb and command
    if (!this.isConnected()) {
      return callback(thorin.error('REDIS.NOT_CONNECTED', 'The connection is not active yet.'));
    }
    command = command.toLowerCase();
    if (typeof this[connections].default.connection[command] !== 'function') {
      return callback(thorin.error('REDIS.COMMAND_NOT_FOUND', 'Invalid command issued: ' + command, 500));
    }
    args.push((err, res) => {
      if (err) {
        return callback(thorin.error('REDIS.EXEC', 'Redis command failed to execute.', err));
      }
      if (command === 'hgetall' && typeof res === 'object' && res) {
        // backward compatibility
        if (Object.keys(res).length === 0) {
          res = null;
        }
      }
      callback(null, res);
    });
    this[connections].default.emit('command', command, args);
    this[connections].default.connection[command].apply(this[connections].default.connection, args);
  }
323901
function handlePromise(query, q, model, resultsPerPage) {
  return Promise.all([
    query.exec(),
    model.count(q).exec()
  ]).spread(function(results, count) {
    return [
      results,
      Math.ceil(count / resultsPerPage) || 1,
      count
    ]
  });
}
400902
function start(cmd, { silent = false, env = null } = {}) {
    const parts = cmd.split(' ');
    const command = parts[0][0] === '.' ? path.resolve(parts[0]) : parts[0];
    const handle = {
        process: child_process_1.spawn(command, parts.slice(1), {
            stdio: silent ? 'pipe' : 'inherit',
            env: env || process.env,
            cwd: process.cwd()
        }),
        promise: Promise.resolve()
    };
    handle.promise = new Promise(function (resolve, reject) {
        let resolved = false;
        handle.process.once('error', error => {
            resolved = true;
            reject(error);
        });
        handle.process.once('exit', (code, signal) => {
            if (resolved)
                return;
            if (code === 0) {
                resolve();
            }
            else {
                signal = signal ? `${signal}:` : '';
                reject(new Error(`Child exited with ${signal}${code}`));
            }
        });
    });
    return Promise.resolve(handle);
}
312242
function safeExec(command, options) {
  const result = exec(command, options);
  if (result.code !== 0) {
    exit(result.code);
    return null;
  }
  return result;
}
229360
function (cmd, cwd, callback) {
    var async = typeof callback === 'function';

    var result = exec(
        cmd,
        {cwd: cwd},
        async ? callback : undefined
    );

    return result.code !== 0 && !async ? result.stdout : undefined;
}