Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpreting grunt command line option as string

As part of a build process, we run a Grunt task like this:

grunt release -r 3.9

The release number passed with the -r option is used to tag various parts of the release.

The trouble arises with releases that end in a zero -- e.g. 3.10. Grunt treats this as a number, drops the trailing zero and thinks that this is release 3.1.

Here's a simple Gruntfile which demonstrates the problem:

module.exports = function(grunt) {
  grunt.registerTask('default', 'Release preparation', function () {
    var rel = grunt.option("r").toString();

    grunt.log.writeln("Release data type:" + typeof rel);
    grunt.log.writeln("release (" + rel + ")");
  });
};

Here's what you get:

$ grunt -r 3.10
Running "default" task
Release data type:string
release (3.1)

Done, without errors.

The toString() converts it to a string appropriately, but the damage has already been done. The trailing zero is gone.

Any way around this?

like image 545
Doug Harris Avatar asked Feb 15 '23 07:02

Doug Harris


1 Answers

Unfortunately, it seems this behavior is by design, as grunt-cli uses nopt module to do its command-line parsing. See the code here, the key line being:

return nopt(exports.known, exports.aliases, process.argv, 2);

This is what nopt has to say about types (emphasis mine):

When parsing unknown fields, "true", "false", and "null" will be interpreted as their JavaScript equivalents, and numeric values will be interpreted as a number.

A couple workarounds might be:

  1. Use something like grunt release -r "v3.10" on the command line and strip off the "v" in your grunt code
  2. Read process.argv again in your grunt code and pass it into the option parser of your choosing
like image 116
explunit Avatar answered Feb 18 '23 03:02

explunit