Giter Site home page Giter Site logo

grunt-exec's Introduction

build status grunt-exec

Grunt plugin for executing shell commands.

NPM NPM

Installation

Install grunt-exec using npm:

$ npm install grunt-exec --save-dev

Then add this line to your project's Gruntfile.js:

grunt.loadNpmTasks('grunt-exec');

Usage

This plugin is a multi task, meaning that grunt will automatically iterate over all exec targets if a target is not specified.

If the exit code generated by the specified shell command is greater than 0, grunt-exec will assume an error has occurred and will abort grunt immediately.

Properties

  • command (alias: cmd): The shell command to be executed. Must be a string or a function that returns a string.
  • stdin: If true, stdin will be redirected from the child process to the current process allowing user interactivity (EXPERIMENTAL)
  • stdout: If true, stdout will be printed. Defaults to true.
  • stderr: If true, stderr will be printed. Defaults to true.
  • cwd: Current working directory of the shell command. Defaults to the directory containing your Gruntfile.
  • exitCode (alias: exitCodes): The expected exit code(s), task will fail if the actual exit code doesn't match. Defaults to 0. Can be an array for multiple allowed exit codes.
  • callback: The callback function passed child_process.exec. Defaults to a noop.
  • callbackArgs: Additional arguments to pass to the callback. Defaults to empty array.
  • sync: Whether to use child_process.spawnSync. Defaults to false.
  • options: Options to provide to child_process.exec. NodeJS Documentation
    • cwd String Current working directory of the child process
    • env Object Environment key-value pairs
    • encoding String (Default: 'utf8')
    • shell String Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.)
    • timeout Number (Default: 0)
    • maxBuffer Number largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed (Default: 200*1024)
    • killSignal String (Default: 'SIGTERM')
    • uid Number Sets the user identity of the process. (See setuid(2).)
    • gid Number Sets the group identity of the process. (See setgid(2).)

If the configuration is instead a simple string, it will be interpreted as a full command itself:

exec: {
  echo_something: 'echo "This is something"'
}

Command Functions

If you plan on doing advanced stuff with grunt-exec, you'll most likely be using functions for the command property of your exec targets. This section details a couple of helpful tips about command functions that could help make your life easier.

Passing arguments from the command line

Command functions can be called with arbitrary arguments. Let's say we have the following exec target that echoes a formatted name:

exec: {
  echo_name: {
    cmd: function(firstName, lastName) {
      var formattedName = [
        lastName.toUpperCase(),
        firstName.toUpperCase()
      ].join(', ');

      return 'echo ' + formattedName;
    }
  }
}

In order to get SIMPSON, HOMER echoed, you'd run grunt exec:echo_name:homer:simpson from the command line.

Accessing grunt object

All command functions are called in the context of the grunt object that they are being ran with. This means you can access the grunt object through this.

Example

The following examples are available in grunt-exec's Gruntfile.

grunt.initConfig({
  exec: {
    remove_logs: {
      command: 'rm -f *.log',
      stdout: false,
      stderr: false
    },
    list_files: {
      cmd: 'ls -l **'
    },
    list_all_files: 'ls -la',
    echo_grunt_version: {
      cmd: function() { return 'echo ' + this.version; }
    },
    echo_name: {
      cmd: function(firstName, lastName) {
        var formattedName = [
          lastName.toUpperCase(),
          firstName.toUpperCase()
        ].join(', ');

        return 'echo ' + formattedName;
      }
    }
  }
});

Testing

$ cd grunt-exec
$ npm test

Issues

Found a bug? Create an issue on GitHub.

https://github.com/jharding/grunt-exec/issues

Versioning

For transparency and insight into the release cycle, releases will be numbered with the follow format:

<major>.<minor>.<patch>

And constructed with the following guidelines:

  • Breaking backwards compatibility bumps the major
  • New additions without breaking backwards compatibility bumps the minor
  • Bug fixes and misc changes bump the patch

For more information on semantic versioning, please visit http://semver.org/.

License

Original Copyright (c) 2012-2014 Jake Harding Copyright (c) 2016 grunt-exec Licensed under the MIT License.

grunt-exec's People

Contributors

almost avatar brian-lim-42 avatar gwicksted avatar jharding avatar joakimbeng avatar kirbysayshi avatar lipsumar avatar mansona avatar peteappleton avatar robloach avatar simoneb avatar spect avatar uc2dabing 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  avatar

grunt-exec's Issues

two red arrows?

What do the two red arrows mean?

remote: Running "exec:verify" (exec) task
remote: >> (these two arrows are red)
remote: HTTP/1.1 200 OK
remote: Server: nginx/1.4.3
remote: Date: Fri, 08 Nov 2013 10:05:21 GMT
remote: Content-Type: text/html
remote: Content-Length: 1161
remote: Last-Modified: Fri, 08 Nov 2013 10:04:37 GMT
remote: Connection: keep-alive
remote: ETag: "527cb735-489"

I'm doing a curl call to the index page after a deploy.

Run command after exit

I have a task that runs a grunt watch, and I would like to execute a command after that watch task has been exited. Is this possible with grunt-exec?

I want grunt-exec to start my MAMP server when my development task is run and then stop it after the watch is exited with Ctrl-C.

Task run but don't do anything

On W7, version "grunt-exec": "~0.4.5"
I'll try the most basic cmd: echo

module.exports = function(grunt) {

require('load-grunt-tasks')(grunt);

// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),

exec: {
update_po: {
cmd: 'echo "hello"'
}
},

});

// Default task(s).
grunt.registerTask( 'default', 'exec' );

};

Result:

c__windows_system32_cmd exe-09-04-2014

What did I missed, something to add somewhere
Grunt and grunt-cli work without any issue ;)

Thanks

syntax error on mkdir command

I am trying to execute the following where target is a sub-directory of where grunt.js is executing:

prepare: {
command: 'mkdir target/templates',
stdout: true
}

I get the following error:

"Command failed: The syntax of the command is incorrect."

If I try this, it works:

prepare: {
command: 'mkdir target2',
stdout: true
}

I'm not sure why I can't make a sub-directory. Of course, if I execute from command line, it works.

Please use grunt.util.spawn

It uses child_process.spawn() which preserves stdout/stderr colors.

If you'd rather use Node's API directly, here's how I'm currently doing it:

var child = child_process.spawn(app, [command], {cwd:cwd, stdio:"inherit"});

child.on("exit", function(code)
{
    this.removeAllListeners();

    callback();
});

Can't interact with commands ran (stdin broken)

When I execute a command, in my case cordova build android --release, that prompts me to enter the password to unlock my signing key, I can enter text but when I hit return I just get a new line and the input doesn't propagate the command in progress, halting the script execution. I've checked the readme and closed issues but can't find anything related to a solution to this?

Thanks

Grunt 0.4 Release

I'm posting this issue to let you know that we will be publishing Grunt 0.4 on Monday, February 18th.

If your plugin is not already Grunt 0.4 compatible, would you please consider updating it? For an overview of what's changed, please see our migration guide.

If you'd like to develop against the final version of Grunt before Monday, please specify "grunt": "0.4.0rc8" as a devDependency in your project. After Monday's release, you'll be able to use "grunt": "~0.4.0" to actually publish your plugin. If you depend on any plugins from the grunt-contrib series, please see our list of release candidates for compatible versions. All of these will be updated to final status when Grunt 0.4 is published.

Also, in an effort to reduce duplication of effort and fragmentation in the developer community, could you review the grunt-contrib series of plugins to see if any of your functionality overlaps significantly with them? Grunt-contrib is community maintained with 40+ contributors—we'd love to discuss any additions you'd like to make.

Finally, we're working on a new task format that doesn't depend on Grunt: it's called node-task. Once this is complete, there will be one more conversion, and then we'll never ask you to upgrade your plugins to support our changes again. Until that happens, thanks for bearing with us!

If you have any questions about how to proceed, please respond here, or join us in #grunt on irc.freenode.net.

Thanks, we really appreciate your work!

Grunt-exec to run a bash script

I try to execute a bash script but it turns error 'cause it interprets also the variables as pure commands and so it exits with error.
If it expects just pure commands also in bash script, really this plugin cannot be used to run more complex scripts with variable. Am I right or not?

Deal with stdout/sterr of executed command

Hello,

I'm using your grunt task and want to work with the stout/sterr of the command. Is there some API, which allows me to get the return value of a command?

Example:
grunt exec:ret_command:whoami

ret_command: {
cmd: function(command) {
var who =
return command;
}
}

Or if I use
grunt exec:who
who:{
command: 'whoami',
stdout: true,
stderr: true
},
to redirect the stdout or/and sterr to a function, where I can deal with the result of 'whoami'?

BR & THX,
mybecks

Task exec:task not found

Hi,

This is my code:

exec: {
        wp_download: {
            cmd: 'wp core download --locale=<%= wp.download.locale %>  --version=<%= wp.download.version %>'
        }
},

But when I try to run my task, it says Warning: Task "exec:wp_download" not found.

Hope you can help :)

README update

Hey, I wrote a grunt plugin that checks the current node version against engines.node in the project's packages.json and extends grunt-exec tasks by prepending the commands with an nvm use command if necessary. I thought you might want to link to it in your README.

INT signal is trapped away from spawned process

Same as grunt-spawn and grunt-shell (couldn't post the issue there because the author is a bit of a dick).

Steps to reproduce:

git clone [email protected]:MeteorPackaging/summernote.git
cd summernote
git checkout meteor-integration
npm install
grunt meteor-test

This uses grunt-exec (replace "shell" in the source lines) to execute meteor/runtests/sh, which traps the INT signal.

Now press Ctrl+C.

Notice that grunt aborts instantly, without giving runtests.sh a chance to trap the INT signal and do its cleanup.

Is it possible to handle try/catch errors where the error is caused by a shell command?

I'm running a task as follows:

        try {
            grunt.task.run("exec:run_nw");
        } catch(e) {
            grunt.log.writeln("node-webkit not found. Downloading required binaries. Run 'grunt run' once files are downloaded.");
            grunt.task.run("nodewebkit");   
        }

If exec:run_nw fails, I'd like to try and handle the error. In this case, exec:run_nw is trying to run files that don't exist, so instead, I want to retrieve them. However, grunt just fails without utilizing the catch block.

Is there something I'm missing in order to catch errors from the exec module so I can correct them at runtime?

Thank you,

Success after maxBuffer size is reached

Hello!

I am running a compile command that generates a lot of output. As maxBuffer limit is reached, grunt outputs "Done, without errors", and proceeds with the next task, while the compile task continues in the background.

This behaviour is really confusing, there should be a clear error statement.

(running grunt-exec 1.0.0)

Do not execute Multiple cmd

exec: {
echo_something: 'echo "This is something"',
cmd: 'lessc --source-map=main.map less/main.less css/main.css',
cmd: 'lessc --source-map=file2.map less/file2.less css/file2.css'
},
which execute last cmd only

Use a function to set the cwd

The cwd is sometimes not known until execution time. It would be nice to be able to set it from a function. Something like:

grunt.initConfig({
  exec: {
    sample: {
      command: {...},
      cwd: function() {
        return "/my/dynamicpath";
      }
    }
  }
});

Would a pull request for something like that be merged into grunt-exec?

If child is killed, task output should show the kill signal, not 'exited with 0'

For instance when maxBuffer is exceeded (ref #64), the parent process (grunt) will kill the child.
In this case code is null, and the second argument of (signal) is set. However the logic in the task does not check signal, and instead prints (the very confusing) message:

Exited with code: 0.
Warning: Task "exec:dockerNode" failed.� Use --force to continue.

Aborted due to warnings.

https://github.com/jharding/grunt-exec/blob/master/tasks/exec.js#L65

Problem with arguments

Hi,

I'm trying to pass arguments and it works OK but if I define a block of tasks like:

 exec: {
      commit: {
        cmd: function(mensaje) {          
          return 'echo Mensaje: ' + mensaje;
        }
      }
    },

[...]

grunt.registerTask('pre-commit', [
    'clean',
    'jshint',
    'exec'
  ]);

The arguments won't work.

I'm running it like this:

grunt pre-commit:PARAMETRO

and it's showing undefined. Do you know how to do this?

Thanks in advance.

Command working on shell but not with grunt-exec

I am trying to create mysql database using grunt task and following command.

mysql -u "${DB_USER}" -p"${DB_PASSWORD}" -e "CREATE DATABASE IF NOT EXISTS ${DATABASE};"

The database name have dash(-) in it so i have to put "`" before name, escaped with "" which cannot be seen here. This works when I run it on shell directly.

But when running with grunt, i am getting following error:

/bin/sh: 1:
test-db: not found
ERROR
1064 (42000)
at line 1
: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
Exited with code: 1.
Warning: Task "exec:create_database" failed. Use --force to continue.

Execute script that launches a terminal

Hi,

I'm using grunt-contrib-watch task to monitor a folder in which some sh scripts are placed (and removed) on the fly. In those scripts, there's a call to « gnome-terminal ». I would like the terminal to be launched on my graphical interface.

My grunt file is as follows

module.exports = function (grunt) {

  // Project configuration
  grunt.initConfig({

      // Watching project content changes
      // Both sections allow the watch of any file
      // inside both directories, recursively (** means « at any
      // place in the tree »
    watch: {
      options: {
        event: [ 'added' ]
      },
      queued_scripts: {
          files: [ "scripts_tank/**/*" ],
          tasks: [ "exec:execute" ]
      } 
    },
    exec: {
      execute : {
        command: 'sh',
        stdout: true,
        stderr: true
      }
    }
  });

  // Loading plugins. They have to be loaded one at a time
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-exec');

  grunt.registerTask('default', 'watch');
};

The output I get from the grunt watch command :

grunt watch
Running "watch" task
Waiting...OK
>> File "scripts_tank/ddksqj4E3fdjqsgdee4ERS.sh" added.

Running "exec:execute" (exec) task

No new terminal appears and the task never ends.

Is there anything in your plugin that could prevent a terminal to be launched from the process it created ?

Thanks in advance

Can't run remote command that prompts for sudo password

I'm trying to use grunt-exec to execute a script on a remote machine that requires sudo access, and therefore prompts for a password.

I want it to prompt for the password, because I don't want to have to commit the password to source control.

From the command line the following is working correctly:

ssh -t examplehost.com "sudo ls"

However when I run the same command via grunt-exec I get the following:

$ grunt exec:remote_sudo
Running "exec:remote_sudo" (exec) task
>> Pseudo-terminal will not be allocated because stdin is not a terminal.
>> sudo: no tty present and no askpass program specified
>> Sorry, try again.
>> sudo: no tty present and no askpass program specified
>> Sorry, try again.
>> sudo: no tty present and no askpass program specified
>> Sorry, try again.
>> sudo: 3 incorrect password attempts
>> Exited with code: 1.
Warning: Task "exec:remote_sudo" failed. Use --force to continue.

Aborted due to warnings

The answer to this stackoverflow question with a similar error suggests adding an additional -t switch to force the pseudo-terminal tty allocation.

Doing so gets the password prompt to show, but something isn't right, as it shows my password in the clear as I type it (the usual behaviour shows no output as you type), and it hangs forever:

$ grunt exec:remote_sudo
Running "exec:remote_sudo" (exec) task
[sudo] password for tom: not_my_password
# hangs forever here

Is this something grunt-exec should be capable of? Or is it considered beyond the scope of it's use?


Example Gruntfile.js for reference:

module.exports = function(grunt) {

  require('load-grunt-tasks')(grunt);

  grunt.initConfig({
    exec: {
      remote_sudo: 'ssh -t examplehost.com "sudo ls"',
    }
  });
};

"exec:create_temp" not found.

grunt exec:create_temp
Warning: Task "exec:create_temp" not found. Use --force to continue.

Aborted due to warnings.

Here's my definition:

        exec: {
            create_temp: {
                cmd: 'mkdir -p <%= tmp_site_path %>'
            }
        },

Piping to "xargs kill" makes Grunt fail

Successful run
Config:

dist_dev_ks: {
    command: [
        [
            'ps -ef',
            'grep python',
            'grep runserver',
            'grep 9474',
            "awk '{print $2}'",
        ].join(' | '),
    ].join(' && '),
},

Execution:

$ grunt exec:dist_dev_ks
Running "exec:dist_dev_ks" (exec) task
94833
94836
94897

Done, without errors.

Failed run after adding the piping to xargs kill
Config:

dist_dev_ks: {
    command: [
        [
            'ps -ef',
            'grep python',
            'grep runserver',
            'grep 9474',
            "awk '{print $2}'",
            'xargs kill',
        ].join(' | '),
    ].join(' && '),
},

Execution:

$ grunt exec:dist_dev_ks
Running "exec:dist_dev_ks" (exec) task
>> Exited with code: 0.
Warning: Task "exec:dist_dev_ks" failed. Use --force to continue.

Aborted due to warnings.

If I use --verbose:

Expecting exit code 0
>> Exited with code: 0.
Warning: Task "exec:dist_dev_ks" failed. Use --force to continue.

Issue with running the command

Hi,

I get this warning on all commands:
Cannot read property 'orig' of undefined Use --force to continue.

I use the basic setting for list_files in your README

I don't know what the problem is?

exec failed to execute rpmbuild but the commands succeeds if run directly

I've setup exec to run rpmbuild and it did for a while until we changed something in the packaged files then it started failing.

Grungfile.js :
build_rpm:{
cmd: 'rpmbuild -ba <%= rpm_dir %>/SPECS/cdr.spec'
}

Output:
....
....

Exited with code: 0.
Warning: Task "exec:build_rpm" failed. Use --force to continue.

Aborted due to warnings.

Foreach within command

Hi,

I would like to foreach through an array and then fire a command on each iteration:

wp_plugins: {
            cmd: function() {
                var plugins = this.config('wp.plugins');

                plugins.forEach(function(plugin){
                    return 'php wp-cli.phar plugin install ' + plugin + ' --activate --force';
                });
            }
        }

With the code above I get this error:

Running "exec:wp_plugins" (exec) task

Command property must be a string.

Can you help me? Thanks!

Gijs

Register package with Bower

Register Package with Bower

  • There must be a valid manifest JSON in the current working directory.
  • Your package should use semver Git tags.
  • Your package must be available at a Git endpoint (e.g., GitHub); remember to push your Git tags!

bower register grunt-exec git://github.com/jharding/grunt-exec.git

might have to duplicate the package.json to bower.json and change peerDependencies to dependencies or some such small tweaks, but that's it I guess. Up to you guys though :) just noticed it wasn't in there when I ran bower search grunt.

Peace, Tom

Creates only invalid links

absolute (like here) or relative:

symlink:
  bower_components:
    target: 'bower_components'
    link: '/Users/atrapp/development/sentialfive/public/bower_components'

creates only bower_components -> bower_components link which is pretty useless ;)

Option to run a certain subtask when no subtask is specified

I want grunt-exec to behave like make, with the option to default to a certain subtask (e.g., the "all" task), when the grunt user does not specify any particular grunt-exec subtask. This is useful when writing lots of grunt-exec shell commands, so that only a subset of them is run by default.

Looks like this may not be possible at the moment, the way multitasks work:

gruntjs/grunt#815

Would grunt-exec mind adding this option in a different way? I'm not sure grunt multitasks will ever add this feature.

Can't use 'source' to run a bash script

Hi, I'm trying to use this to automate the running of a bash script that sets environment variables in my project. If I just personally run the command 'source ./my_script.sh' then it works just fine. But if I put that same command into grunt-exec, it says that it runs without errors, but the vars aren't actually set.

Any thoughts on what the issue is?

Thanks! - Blake

Colorful output

I use this plugin with watch plugin for autostart tests.
How can I see colroful output from my script under exec:test task ?

can't report error when [Error: stdout maxBuffer exceeded.]

i just try below, but it doesn't work.

    childProcess.on('error', function(error){
      log.error(error);
    })

i test in callback just like below, it works:

    childProcess = cp.exec(command, execOptions, function(error, stdout, stderr){
      if(error !== null){
        log.error(error);
      }
      callback(error, stdout, stderr);
    });

someone has any good idea? and know why?

Thoughts on allowing name: cmd pairs?

In an effort to cut down repetition in gruntfiles, I was thinking about modifying this plugin to allow simple commands to be even more simple:

exec: {
  echo: {
    cmd: 'echo whatwhat'
  }
}

Could become:

exec: {
  echo: 'echo whatwhat'
}

But before I added it, I figured I'd ask here first. I have quite a few grunt files that end up having the same few commands, and the extra lines just add a lot of noise.

support callback?

sometime when we exec a shell, and want to catch the output, filter some keyword then output.

Update Grunt dependency

Currently on ~0.4, should be fixed since this will prevent projects from upgrading to the latest version of Grunt.

Use with `sudo`

Is there any way to use sudo with this task? I have a command that I want to run, but it requires admin permissions.

Grunt Exec Command with subdirectory path not working on windows

I have the following command to execute using grunt (exec):

command: './node_modules/.bin/component install'

The grunt tasks fails with the following error:

image

If i execute the command in cmd (or powershell) it is working.

image

any idea? it doesn't matter if the command uses / oder \

Thanks in advance.

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.