Giter VIP home page Giter VIP logo

gulp-run's Introduction

gulp-run

Codacy Badge

Use shell commands in your gulp or vinyl pipeline.

Many command line interfaces are built around the idea of piping. Let's take advantage of that in our Gulp pipeline! To use gulp-run, simply tell it the command to process your files; gulp-run accepts any command you could write into your shell, including I/O redirection like python < baz.py | cat foo.txt - bar.txt. Additionally, node_modules/.bin is included on the path, so you can call programs supplied by your installed packages. Supports Unix and Windows.

This plugin is inspired by gulp-shell and gulp-spawn and attempts to improve upon their great work.

Usage

var run = require('gulp-run');

// use gulp-run to start a pipeline
gulp.task('hello-world', function() {
  return run('echo Hello World').exec()    // prints "Hello World\n".
    .pipe(gulp.dest('output'))      // writes "Hello World\n" to output/echo.
  ;
})


// use gulp-run in the middle of a pipeline:
gulp.task('even-lines', function() {
  return gulp
    .src('path/to/input/*')             // get input files.
    .pipe(run('awk "NR % 2 == 0"'))     // use awk to extract the even lines.
    .pipe(gulp.dest('path/to/output'))  // profit.
  ;
});

// use gulp-run without gulp
var cmd = new run.Command('cat');  // create a command object for `cat`.
cmd.exec('hello world');           // call `cat` with 'hello world' on stdin.

API

run(template, [options])

Creates a Vinyl (gulp) stream that transforms its input by piping it to a shell command.

See run.Command for a description of the arguments.

Returns

(stream.Transform in Object Mode): Returns a Transform stream that receives Vinyl files. For each input, a subprocess is started taking the contents of the input on stdin. A new file is pushed downstream containing the process's stdout.

Example

gulp.task('even-lines', function() {
  return gulp
    .src('path/to/input/*')             // get input files.
    .pipe(run('awk "NR % 2 == 0"'))     // use awk to extract the even lines.
    .pipe(gulp.dest('path/to/output'))  // profit.
  ;
})

run(...).exec([stdin], [callback])

Start a gulp pipeline and execute the command immediately, pushing the results downstream.

Arguments

  1. [stdin] (String | Buffer | Vinyl): If given, this will be used as stdin for the command.
  2. [callback] (Function): The callback is called once the command has exited. An Error is passed if the exit status was non-zero. The error will have a status property set to the exit status.

Returns

(Stream.Readable in Object Mode): Returns a Vinyl (gulp) stream which will push downstream the stdout of the command as a Vinyl file. The default path of the Vinyl file is the first word of the template; use gulp-rename for more versatility.

Example

gulp.task('hello-world', function() {
  return run('echo Hello World').exec()  // prints "[echo] Hello World\n".
    .pipe(gulp.dest('output'))           // writes "Hello World\n" to output/echo.
  ;
})

new run.Command(template, [options])

Represents a command to be run in a subshell.

Arguments

  1. template (String): The command to run. It can be a template interpolating the variable file which references the Vinyl file being input. The template need not interpolate anything; a simple shell command will do just fine. The command is passed as an argument to sh -c, so I/O redirection and the like will work as you would expect from a terminal.
  2. options (Object):
    • env (Object): The environmental variables for the child process. Defaults to process.env.
    • cwd (String): The initial working directory for the child process. Defaults to process.cwd().
    • silent (Boolean): If true, do not print the command's output. This is the same as setting verbosity to 1. Defaults to false.
    • verbosity (Number): Sets the verbosity level. Defaults to 2.
      • 0: Do not print anything, ever.
      • 1: Print the command being run and its stderr.
      • 2: Print the command, its stderr, and its stdout.
      • 3: Print the command, its stderr, and its stdout progressivly. Not useful if you have concurrent gulp-run instances, as the outputs may get mixed.
    • usePowerShell (Boolean): Windows only. If true uses the PowerShell instead of cmd.exe for command execution.

run.Command#exec([stdin], [callback])

Spawn a subshell and execute the command.

Arguments

  1. [stdin] (String | Buffer | Vinyl): If given, this will be used as stdin for the command.
  2. [callback] (Function): The callback is called once the command has exited. An Error is passed if the exit status was non-zero. The error will have a status property set to the exit status.

Returns

(Vinyl): Returns a Vinyl file wrapping the stdout of the command.

Example

var cmd = new run.Command('cat');  // create a command object for `cat`.
cmd.exec('hello world');           // call `cat` with 'hello world' on stdin.

The ISC License

Copyright (c) 2014 Chris Barrick [email protected] Copyright (c) 2016 Marc Binder [email protected]

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.

gulp-run's People

Contributors

cbarrick avatar kevcenteno avatar leipert avatar lichunqiang avatar mrboolean avatar phazei avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

gulp-run's Issues

maxBuffer isn't handled properly

Found an issue that kept coming up after server was running a few hours. Server has a heartbeat that outputs to stdout every 5 seconds. After a few hours the buffer fills up. Once that happens, the child process crashes. There are two issue with here.

First, when the server crashes, somewhere it's being caught and there's no message or anything. The server just stops, still running. The child process was the only thing left, so it should all die. There's no way to see the error. It took days to discover what was stopping.

Second, there's no setting to increase the maxBuffer. The default size is 200 * 1024 which is really small and there are many long running processes that might need something more customizable.

Is there a way to preserve terminal color output when running a child process?

First off, thank you for the great plugin!

I'm running a child process which has some terminal colors when run on its own, but those colors are lost when running under gulp-run and everything appears as the basic text color.

Is there a way to preserve the colors while running under a child process? I'm running on OS X.

EPIPE error on Travis

Travis reports an EPIPE error on Node v0.11.13 for 07b9f90 and all later commits. See the log here.

I cannot reproduce this with the same Node version.

When verbosity!==0 everything fails

Hello.
In your unit tests put {verbosity:1} in any of them and you will see everything crashes. As the result the current version of gulp-run is unusable.

  1) gulp-run includes `node_modules/.bin` on the PATH:
     TypeError: Object $ echo $PATH # Silenced
 has no method 'indexOf'
      at writeToBuffer (/home/vasyl/code/bt/main/node_modules/gulp-run/lib/line-buffered-stream.js:32:24)
      at Transform._transform (/home/vasyl/code/bt/main/node_modules/gulp-run/lib/line-buffered-stream.js:42:5)
      at Transform._read (_stream_transform.js:179:10)
      at Transform._write (_stream_transform.js:167:12)
      at doWrite (_stream_writable.js:226:10)
      at writeOrBuffer (_stream_writable.js:216:5)
      at Transform.Writable.write (_stream_writable.js:183:11)
      at EventEmitter.Logger.write (/home/vasyl/code/bt/main/node_modules/gulp-run/lib/logger.js:38:15)
      at EventEmitter.Logger.log (/home/vasyl/code/bt/main/node_modules/gulp-run/lib/logger.js:53:7)

Error: No path specified! Can not get relative.

This isn't working :/

gulp.task('hello-world', function () {
  run('echo Hello World').exec()  // prints "Hello World\n".
    .pipe(gulp.dest('output'))    // Writes "Hello World\n" to output/echo.
})

error:

Error: No path specified! Can not get relative.
    at File.Object.defineProperty.get (/Users/thomas/Desktop/play-atomshell/node_modules/gulp-run/node_modules/vinyl/index.js:123:27)
    at DestroyableTransform.saveFile [as _transform] (/Users/thomas/Desktop/play-atomshell/node_modules/gulp/node_modules/vinyl-fs/lib/dest/index.js:37:48)
    at DestroyableTransform.Transform._read (/Users/thomas/Desktop/play-atomshell/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at DestroyableTransform.Transform._write (/Users/thomas/Desktop/play-atomshell/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/Users/thomas/Desktop/play-atomshell/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/Users/thomas/Desktop/play-atomshell/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at DestroyableTransform.Writable.write (/Users/thomas/Desktop/play-atomshell/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at write (_stream_readable.js:601:24)
    at flow (_stream_readable.js:610:7)
    at _stream_readable.js:578:7

Can we run git commands inside gulp task

  • I want to run a command inside gulp task as npm install inside the gulp task
  • So, I used like run.Command('npm install')
  • But the command is not working
  • Can anyone help me
  • I am new to both npm and gulp
const gulp = require('gulp');
const simpleGit = require('simple-git');
var argument=require('yargs').argv;
var run = require('gulp-run');
var build = require('gulp-build');
var process=require ('process');
gulp.task('work',async function(done){
    const git = simpleGit();
  await git.clone('https://gitlab.syncfusion.com/bold-reports/javascript-samples.git', 'new', {'--branch':'hotfix/boldreports_v3.1.31'},(err,res) =>
  {
    if(err)
    {
      console.log(err);
    }
    else
    {
      res="Cloned";
      console.log(res);
    }
  });
  await git.cwd(process.cwd()+'/'+"new");
  await git.pull((err,res) =>
  {
    if(err)
    {
      console.log(err);
    }
    else
    {
      res="Success"
      console.log(res);
    }
  }
);
  
done()
  },run.Command('npm install'),'build');

Confused: cbarrick's version vs. this?

npm install gulp-run gets cbarrick's deprecated version, but npm home gulp-run comes here. If you've taken over, can you publish a new version to true things up?

Possible to write output directly to stdout?

This is on Windows, btw, if that matters.

I'm basically trying to run a console command via gulp, and want to see the output from it printed in the terminal just as if I'd run the command directly. It looks like I can do this by using run.Command but I actually want to do it via gulp. Apologies if this is a basic question, I actually have very little experience with streams outside of gulp boilerplate.

I've tried doing something like

gulp.task('serve', function() {
    return run('polymer serve -o').exec()
        .pipe(process.stdout);
});

But that just throws an error saying "TypeError: Invalid data, chunk must be a string or buffer, not object"

So far, it looks like one solution is to use gulp.dest('path/to/output') and then some more code that reads that output file and outputs it to stdout, but I'm pretty sure that would remove any ANSI color coding that might be included, which is a disadvantage.

So, is there any super-obvious I-should-have-already-seen-this solution to this?

problem running a python file

I am running a python file on shell by the following
python ./tools/make-firefox-meta.py ../adaware.firefox_debug/

but when I put it into gulp-run, with following as a task

gulp.task("python-bsff", ["make-pre-bsff"], function(){
    return run("python ./tools/make-firefox-meta.py ../adaware.firefox_debug/").exec();
}); 

The output is weird

[09:59:03] Error: Command `python ./tools/make-firefox-meta.py ../adaware.firefox_debug/` exited with code 1
    at ChildProcess.handleSubShellExit (C:\Users\alan.saberi\dev\AdAwareAdBlockCore\node_modules\gulp-run\command.js:166:13)
    at ChildProcess.g (events.js:291:16)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
stream.js:74
      throw er; // Unhandled stream error in pipe.
      ^

Error: ENOENT: no such file or directory, stat 'C:\Users\alan.saberi\dev\adaware.firefox_debug\_locales\bg\messages.json'
    at Error (native)

Can you explain to me please, what is wrong with gulp-run and how can I pass this error?

run().exec() cannot continue pipe

Get a "Error: No path specified! Can not get relative."

Simple test task:

gulp.task('test', function () {
  return run("echo hello world", {cwd: './'}).exec()
    .pipe(rename("rest.txt"))
    .pipe(gulp.dest('./'));
});

No callback if command not found

When running a command that doesn't exist, no error callback is generated and the task exits abruptly.

For example,

gulp.task('runme', function(cb) {
    new $.run.Command('nonexistant').exec(functioen (err) {
      console.log('This is where I'm supposed to tell you that I do not exist', err);
      cb(err);
    });
});

Running gulp runme just outputs:

[14:38:48] Using gulpfile ~/myproject/gulpfile.js
[14:38:48] Starting 'runme'...
nfantone@ubuntu-laptop ~/myproject $ echo $?
0

And ends silently with status 0.

It would be useful to inform the user that the command/binary that is to be run is not installed in the system and raise a non-zero error status (like POSIX sh standard, 127).

Maintainer

I am not sure if u are still looking for a new maintainer... In case your deprecation warning is still up-to-date - i am able to handle it...
contact me on a free minute.

Replace deprecated dependency gulp-util

gulp-util has been deprecated recently. Continuing to use this dependency may prevent the use of your library with the latest release of Gulp 4 so it is important to replace gulp-util.

The README.md lists alternatives for all the components so a simple replacement should be enough.

Your package is popular but still relying on gulp-util, it would be good to publish a fixed version to npm as soon as possible.

See:

A relative options.cwd combined with running from node_modules/.bin doesn't work

If options.cwd is specified then it is prepended in front of node_modules/.bin in the path. But this means (if options.cwd is not absolute) when changed to the new working directory the path addition is wrong (it should be just node_modules/.bin).

And when options.cwd is absolute then node_modules/.bin would still be correct. So shouldn't options.cwd not be included in the node_modules/.bin path?

Windows support

Experimental Windows support has landed in master. The only difference is that gulp-run on Windows calls cmd.exe /c <command> instead of sh -c <command>.

Can a Windows user run the tests and report back here? The help would be very much appreciated!

EPIPE Error on node v0.12

Hi,
there is an error, when I run this in node v0.12 or io.js 1.6.

it works, when I run it with node 0.10

events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: write EPIPE
    at exports._errnoException (util.js:746:11)
    at WriteWrap.afterWrite (net.js:766:14)

How to amend the stream contents to the next command?

Look at this example where I am incrementing the version and use the new version number in the git flow release start command:

function bumpAndTag(importance) {

    return gulp.src(['./package.json'])

        // bump the version number according to the given importance
        .pipe(plugins.bump({type: importance}))

        // amend the new version number to that command
        .pipe(plugins.run('git flow release start'))

        // save it back to filesystem
        .pipe(gulp.dest('./'))

        ...
}

That is not working of course because git flow release start requires a version number. Just am trying to explain my issue. How can I make the stream contents in .pipe(plugins.bump({type: importance})) be amended to git flow release start? So that it becomes git flow release start 1.3.19

custom metadata lost

When using gulp-run in a chain, custom metadata of the file is lost because a new vinyl file is returned. Should stdin.clone() be used to create the output file?

Show command output progressively

I'd like to run our test suite using gulp-run in which case it would be useful to see the output as the test runner progresses. Is there a way to achieve this?

Cannot call program with spaces in path on Windows

I have a code like this:

$command = '"C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\Common7\\IDE\\devenv.exe" "..\\MySolution.sln" /run';
run($command).exec();

However, it fails with

'"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe"' is not recognized as an internal or external command, operable program or batch file.

I think the string is quoted correctly in my code, isn't it?

how to do something with stderr?

I'm currently using this plugin to run the binary of libsass (sassc) for testing purposes. What I would really like is a way to capture the stderr to a file. Currently with {verbosity: 1} the stderr is output in the terminal but what I really need for these purposes is to capture it to a file. Is there a way? My setup is as follows. You'll see that I use gulp-plumber to capture 'error' events but the output I'm interested in (they are compiler warnings in fact, not errors) is output to stderr without triggering an actual 'error' event, so this only works for fatal errors at the moment

gulp.task('sassc', function () {
  gulp.src('test.scss', { buffer: false })
    .pipe(plumber(function(err) {
        var errorTxt = err.message +'\n\n'+ err.source;
        gutil.beep();
        gutil.log(gutil.colors.red(errorTxt));
        fs.writeFile('test.log', errorTxt);
    }))
    .pipe(rename(function (path) { path.extname = ".css"; }))
    .pipe(run('/applications/libsass/sassc/bin/sassc -s', {verbosity: 1}))
    .pipe(buffer())
    .pipe(autoprefixer({
        browsers: ['last 5 versions'],
        cascade: false
    }))
    .pipe(gulp.dest('.'))
});

Is it possible to write task taking stdin using `gulp-run`

Hi,
is it possible to write a task taking stdin as input and forwarding it further? Something like

gulp.task('task-taking-stdin', function() {
  var run = require('gulp-run');
  run.exec().pipe(someOtherTask())
});

Could you please guide me if that's something possible to be achieved with gulp-run.

Hoe to take the argument from command-line?

I need to take an argument from the command line and use it in the gulp-file ?
This is my gulpfile.js
var run = require('gulp-run');

   gulp.task('default', function () {
     run('echo Hello user').exec() 
      .pipe(gulp.dest('output'))    
   })

How can I take an argument from Command line and pass it to this file , so that hello argument1 is pprinted instead of hello user?

Cannot get command output

Hi,
I cant get the running command output.
I'm trying to get info from git:
" stream = run('git -C .docs status');

stream.exec();//.on('error', onError);

file = stream.read();
var content= file.contents.read();
console.log(content);"

But the output of 'content' is always null.
And in console i see this:

Starting 'check_git_stats'...
null
On branch gh-pages
Your branch is ahead of 'origin'...............
nothing to commit, working directory clean

So at first it log the 'content' which is always null
and then it actually runs the command and print its output.

But i need to get the output into content variable.

Looks like something is wrong with .exec() command, or maybe i didn't get it?
So how to get command output to variable?

EventEmitter memory leak warning

I'm using gulp-run in conjunction with gulp-tap to pass the paths of files I'm watching on to a theme upload command in shopify_theme Ruby gem. Generally this works but I've started seeing the following warning as the number of files in my project increases. The uploads are still successful, but this is making for some noisy log output.

var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
var run = require('gulp-run');
var tap = require('gulp-tap');

var paths = {
  styles: 'assets/styles/**/*'
};

var upload = function( file ){
  var splitPath = file.path.split('theme/').pop();
  run('theme upload ' + splitPath, { cwd: 'theme' }).exec();
};

gulp.task('sass', function(){
  gulp.src(paths.styles)
    .pipe(sass())
    .pipe(gulp.dest('theme/assets'));
    .pipe(tap(function(file){
      upload(file);
    }));
});

gulp.task('watch', function(){
  gulp.watch(paths.styles, ['sass']);
});

(example gulp-run log output)

$ theme upload assets/timber.scss.liquid
(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace
    at WriteStream.EventEmitter.addListener (events.js:160:15)
    at WriteStream.Readable.on (_stream_readable.js:688:33)
    at WriteStream.EventEmitter.once (events.js:185:8)
    at Duplex.Readable.pipe (_stream_readable.js:540:8)
    at exec (/project/node_modules/gulp-run/gulp-run.js:90:17)
    at Transform.commandStream.exec (/project/node_modules/gulp-run/gulp-run.js:204:12)
    at upload (/project/Gulpfile.js:18:54)
    at /project/Gulpfile.js:39:7
    at Stream.modifyFile (/project/node_modules/gulp-tap/lib/tap.js:66:11)
    at Stream.stream.write (/project/node_modules/gulp-tap/node_modules/event-stream/node_modules/through/index.js:26:11)

Not sure if this is related to gulpjs/gulp#432 but seems to be coming from Transform.commandStream.exec in gulp-run. I'm running 0.10.28.

Running commands in sequence?

I want to run two commands, namely redis-cli flushall and a custom script node gen.js in sequence. This is my current task:

gulp.task('gen', function (done) {
  run('redis-cli flushall').exec('', function () {
    console.log('calling done after redis')
    run('node gen.js').exec('', function () {
      console.log('calling done after gen.js')
      done();
    })
  });
});

However, I see two issues with that code:

  1. If I want to add more commands, this quickly becomes callback hell. I would like something cleaner as in with Promises, with then.
  2. The result I get is this:
λ gulp gen
[18:22:28] Using gulpfile ~\Documents\app\gulpfile.js
[18:22:28] Starting 'gen'...
calling done after redis
$ redis-cli flushall
OK
calling done after gen.js
[18:22:51] Finished 'gen' after 22 s
$ node gen.js
DB dropped.

...but I expected this:

λ gulp gen
[18:22:28] Using gulpfile ~\Documents\app\gulpfile.js
[18:22:28] Starting 'gen'...
$ redis-cli flushall
OK
calling done after redis
$ node gen.js
DB dropped.
calling done after gen.js
[18:22:51] Finished 'gen' after 22 s

Endless loop

I'm trying to automate deploying of my firebase project and when executing the below command it keep deploying over and over again:

gulp.task('deploy_external', function () {
return run('firebase deploy --only hosting', {cwd:"../FirebaseFunctions", verbosity:3}).exec();
});

Am I doing something wrong here?

Console output:

[19:27:34] Starting 'copy_external'...
$ firebase deploy --only hosting <-- this is the first execution

=== Deploying to 'projet-name'...

i deploying hosting
i hosting: preparing public directory for upload...
⚠ Warning: Public directory does not contain index.html

i Progress: [...................................................................................................]

✔ hosting: 54 files uploaded successfully

✔ Deploy complete!

Project Console: https://console.firebase.google.com/project/project-name/overview
Hosting URL: https://project-name.firebaseapp.com
$ firebase deploy --only hosting <-- this is the second unexpected execution which starts immediately after the first one completes

=== Deploying to 'project-name'...

i deploying hosting
i hosting: preparing public directory for upload...
⚠ Warning: Public directory does not contain index.html

And so on...

Error when using merge-stream

I am trying to concatenate the output of gulp-run with files coming from gulp.src. To do this, I use merge-stream and gulp-concat. I get the following error:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: Streaming not supported

If I remove .exec(), I don't have the error but no file is created (I find this logically according to the documentation). If I use gulp-shell instead everything is fine.

Here is my task:

var merge = require('merge-stream');
var concat = require('gulp-concat');

gulp.task('build.js', ['js-files'], function () {
    var jsFiles = fs.readFileSync('/tmp/geo-front3/js-files')
        .toString()
        .replace('\n', ' ');

    var appJs = run('closure-compiler ' +
    jsFiles  +
    '--compilation_level SIMPLE_OPTIMIZATIONS ' +
    '--jscomp_error checkVars ' +
    '--externs externs/ol.js ' +
    '--externs externs/angular.js ' +
    '--externs externs/jquery.js ').exec();

    var libSrc = gulp.src([
        'src/lib/jquery-2.0.3.min.js',
        'src/lib/bootstrap-3.3.1.min.js',
        'src/lib/moment-with-customlocales.min.js',
        'src/lib/typeahead-0.9.3.min.js src/lib/angular.min.js',
        'src/lib/proj4js-compressed.js',
        'src/lib/EPSG*.js',
        'src/lib/ol.js',
        'src/lib/angular-translate.min.js',
        'src/lib/angular-translate-loader-static-files.min.js',
        'src/lib/fastclick.min.js',
        'src/lib/localforage.min.js',
        'src/lib/filesaver.min.js',
    ]);

    merge(libSrc, appJs)
        .pipe(concat('build.js'))
        .pipe(gulp.dest('prd/lib'));
});

pipe to stdout?

How can i pipe the stdout from the child process to the console?

thx in advance ^^;

gulp-run modifies global process.env polluting PATH

On this line in command.js this.options.env is assigned process.env. Immediately afterwards this.options.env.PATH is modified. As process.env wasn't defensively copied when it was assigned this modifies the global process.env.PATH. So if you check process.env.PATH at the end of a gulp run it'll be full of other crap. And because of where this happens this problem applies just by defining your tasks, they don't even need to be run.

When defaulting options.env it should shallow copy process.env.

Consume stdout in chunks?

Is it possible to consume the stdout of the command being run line-by-line, or otherwise chunked? I use gulp-run to kick off a long-running (several minutes) script which occasionally writes its progress to stdout. While having a single callback when the command is done is convenient, it would be nice to be able to log those progress messages locally as they come in, before the entire command finishes.

Unable to npm install the gulp-run

Hi. Any ideas?

157 error Error: Command failed: fatal: ambiguous argument 'v0.x': unknown revision or path not in the working tree.
157 error Use '--' to separate paths from revisions
157 error
157 error     at ChildProcess.exithandler (child_process.js:647:15)
157 error     at ChildProcess.EventEmitter.emit (events.js:98:17)
157 error     at maybeClose (child_process.js:753:16)
157 error     at Socket.<anonymous> (child_process.js:966:11)
157 error     at Socket.EventEmitter.emit (events.js:95:17)
157 error     at Pipe.close (net.js:465:12)
158 error If you need help, you may report this *entire* log,
158 error including the npm and node versions, at:
158 error     <http://github.com/npm/npm/issues>
159 error System Linux 3.8.0-42-generic
160 error command "node" "/usr/bin/npm" "install" "gulp-run" "-g"
161 error cwd /home/vasyl/code/bt/main
162 error node -v v0.10.28
163 error npm -v 1.4.16
164 error code 128

Maintain filename in a gulp pipeline

Currently gulp-run changes the name of files it receives in a pipeline to the default (the name of the command). This quite rude and can make working in pipelines confusing. It should only set the filename for files originating from run(...).exec(...). Files piped into gulp-run should have the same name when they come out.

I am about to push a rewrite of the plugin which fixes this among other things.

Security vulnerability: Sanitize command arguments

By using this package unsanitized input from a command line argument flows into gulp-run, where it is used to build a shell command. Forwarding command-line arguments or file paths from the local environment to a function that executes a system command can change the meaning of the command unexpectedly due to unescaped special characters, which may result in a Indirect Command Injection vulnerability.

run()/run.Command() should accept an array and wrap arguments in double quotes if they contain spaces.

This is easy to fix by ourselves, but Snyk will complain rightfully.

Query / Help: How to create tasks to start and stop appium server

I have a situation in which I want to run the webdriverio tests on Android emulator.
wdio-appium-service is having an issue, because of which the appium server is not getting started on windows.

Basically, I want to launch / start appium server which is can be started from ./node_modules/.bin/appium and the output should be redirected to appium.log file and once my tests are completed , the appium server should be stopped / killed.

gulp.task('start appium' ...
gulp.task('e2e', ['start appium'] ..
gulp.task('stop appium' ...

I am not expert with gulp so finding it bit difficult.

Thanks in advance.

Run after run?

Hi,

I try the following:

gulp.task('npmpack', function () {
    del('myModule-0.1.0.tgz');
    run('npm pack').exec();
    run('npm i myModule-0.1.0.tgz').exec();

But it seems that the 2nd run needs to wait for the 1st run to be completed, as I get the following error:

npm ERR! registry error parsing json
npm ERR! Windows_NT 6.3.9600
... more ERR! below....

Is there a way to solve this through your options?

Thx.

Option to print command only if it has stderr

Hi,

Can you add an option to print the command only if it has an stderr (with the stderr of course)? I am compelled to run a command that takes a long file list as argument and I would like to avoid to see this multiple line command. Verbosity:0 doesn't do the trick since I would like to see the error output if it has one.

Wait for powershell script to finish, callback not working?

Hello,

Great plugin, thanks!. Maybe I'm trying something impossible here, but let's give it a go. I'm using gulp-run to start up a powershell script that executes in a separate powershell window. I thought I could use the callback function to be able to have gulp-run to finish the task, after the powershell script has done it's job.. but can 't get it to work. I'm loading powershell with the 'Start-Process' command.

function deploy(done) {
 // some variable definitly left out (argumentlist)
  return run('Start-Process powershell.exe -ArgumentList ' + argumentList, { usePowerShell: true }).exec(function () {
    done();
  });
}
gulp.task('deploy', deploy);

This is the output, you can see it doesn't wait for completion:

[16:40:18] Starting 'deploy'...                                                                                                                                                                                    
[16:40:18] Finished 'deploy' after 543 ms                                                                                                                                                                          
$ Start-Process powershell.exe -ArgumentList etc....

Any thoughts on this? Thanks!

Received a non-Vinyl object

the example code:

gulp.task('hello-world', function() {
  return run('echo Hello World').exec()    // prints "Hello World\n".
    .pipe(gulp.dest('output'))      // writes "Hello World\n" to output/echo.
  ;
})

currently return error

[15:04:29] Error: Received a non-Vinyl object in dest()
at DestroyableTransform.normalize [as _transform] (/home/set/www/cloudbeds/jarvis/node_modules/vinyl-fs/lib/dest/prepare.js:16:17)
at DestroyableTransform.Transform._read (/home/set/www/cloudbeds/jarvis/node_modules/readable-stream/lib/_stream_transform.js:184:10)
at DestroyableTransform.Transform._write (/home/set/www/cloudbeds/jarvis/node_modules/readable-stream/lib/_stream_transform.js:172:83)
at doWrite (/home/set/www/cloudbeds/jarvis/node_modules/readable-stream/lib/_stream_writable.js:428:64)
at writeOrBuffer (/home/set/www/cloudbeds/jarvis/node_modules/readable-stream/lib/_stream_writable.js:417:5)
at DestroyableTransform.Writable.write (/home/set/www/cloudbeds/jarvis/node_modules/readable-stream/lib/_stream_writable.js:334:11)
at Pumpify.Duplexify._write (/home/set/www/cloudbeds/jarvis/node_modules/duplexify/index.js:208:22)
at doWrite (/home/set/www/cloudbeds/jarvis/node_modules/readable-stream/lib/_stream_writable.js:428:64)
at writeOrBuffer (/home/set/www/cloudbeds/jarvis/node_modules/readable-stream/lib/_stream_writable.js:417:5)
at Pumpify.Writable.write (/home/set/www/cloudbeds/jarvis/node_modules/readable-stream/lib/_stream_writable.js:334:11)

what I need is to write output of running command in file.

run task hangs if output is too large

If a run task outputs too much data to stdout, it seems to hang with no notices or messages or anything.

Originally I thought it was related to maxBuffer, but it seems childProcess.spawn doesn't use that, so it shouldn't have issues itself.

Here is a test case that will replicate it:

Start with running "gulp test"

var
    childProcess = require('child_process'),
    gulp = require('gulp'),
    run = require('gulp-run');

gulp.task('test', function(done){
    var cmd = "gulp test-long";

    //This hangs rather quickly (usually at i=49
    run(cmd,{
        verbosity:3
    }).exec();

    //This never dies
    /*
    var subshell = childProcess.spawn('sh', [
        '-c', cmd
    ], {env: process.env});
    subshell.stdout.pipe(process.stdout);
    subshell.stderr.pipe(process.stderr);
    subshell.stderr.pipe(process.stderr);
    subshell.once('close', function (code) {
        //this is never called
        console.log('PROCESS PROPERLY ENDED');
    });
    //*/
});

gulp.task('test-long', function(done){
    var i = 0;
    setInterval(function() {
        //The longer this is, the sooner it dies.
        console.log("LOTS OF STUFF: " + i++);
        console.log("--------------------------------------------------------------------------------------------------------------------------------");
        console.log("--------------------------------------------------------------------------------------------------------------------------------");
        console.log("--------------------------------------------------------------------------------------------------------------------------------");
        console.log("--------------------------------------------------------------------------------------------------------------------------------");
        console.log("--------------------------------------------------------------------------------------------------------------------------------");
    }, 100);
});

I originally reported it incorrectly in #32

gulp-run doesn't work when child process changes working directory

The problem occurs because the child gulp script requires working directory change:
gulp --gulpfile "<...>\gulpfile.js" build
[13:40:01] Working directory changed to <...>
[13:40:03] Using gulpfile <...>\gulpfile.js
[13:40:03] Starting 'build'...
[13:40:03] Finished 'build' after 6.42 μs

This works:

const cp = require('cp');
gulp.task('gg2', function (done) {
    var gulpfile = path.join(gulpcwd, 'gulpfile.js'); 
    var subShell = cp.spawn('cmd.exe', ['/C', 'gulp', '--gulpfile', gulpfile, '--cwd', gulpcwd, 'build'], {
        env: process.env,
        cwd: process.cwd()
    });

    subShell.stdout.pipe(process.stdout);
    subShell.stderr.pipe(process.stderr);
    subShell.once('exit', function (code) {
            done(code);       
    });
});

This doesn’t work:

const run = require('gulp-run');
gulp.task('gg2', function (done) {
    var gulpfile = path.join(gulpcwd, 'gulpfile.js');
    return run('gulp --gulpfile "' + gulpfile + '" --cwd "' + gulpcwd + '" build', { verbosity: 3 })
        .exec(function (err) {
            done(err);
        }); 
});

In latter case the child process sends a standard gulp error that the gulp file is not found.

Vinyl and template samples

Hi Chris,

I am not familiar with both Vinyl and _.template libraries. I think most people doing deployments are not familiar too.

Would you mind adding examples to the Readme.md? In what way these are useful?

Cheers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.