Skip to content

Instantly share code, notes, and snippets.

@mreis1
Last active August 23, 2016 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mreis1/217bc4919eda095aa7be9f51aca56fb8 to your computer and use it in GitHub Desktop.
Save mreis1/217bc4919eda095aa7be9f51aca56fb8 to your computer and use it in GitHub Desktop.
grunt-flag-parser
var _ = require('lodash');
/***
*
* parser used to work with http://gruntjs.com/api/grunt.option
*
*
* Author marcio.reis@outlook.com
*
* - supports boolean params
* example: grunt build --ios
* will return { ios: true }
* - automatically parses values to float/int from arguments.
* if you want a numeric value to stay a string just use quotes when you provide the value
* example:
* --flag=1.1 this will be parsed as float number { flag: 1.1 }
* --flag="1.1" this will stay as it was { flag: "1.1" }
*
*/
/*
Parser function which takes the output of `grunt.option.flags()` and transform it in a object<key,value<
@param arr {array}
@return object<key,value>
*/
function parser(arr){
var params = {};
_.each(arr, function(valueLv1, keyLv1){
valueLv1 = valueLv1.split('--');
_.each(valueLv1, function(valueLv2, keyLv2){
valueLv2 = valueLv2.split('=');
if (valueLv2.length == 1){
if (valueLv2[0]){
params[valueLv2[0]] = true;
}
} else {
if (!valueLv2[1]){
params[valueLv2[0]] = true;
} else {
params[valueLv2[0]] = parseIntIsNum(valueLv2[1]);
}
}
})
});
return params;
}
var regexNum = new RegExp("^([\\d]+)?(?:(.[\\d]+))$","g");
function parseIntIsNum(value){
var isQuoted = false; //nums can be forced to stay as strings
if (value){
value = value.trim();
var startsWidthQuote = false;
var firstQuoteType = "";
var endsWithQuote = false;
if (value[0] === "\"" || value[0] === "\'"){
startsWidthQuote = true;
firstQuoteType = value[0];
}
if (startsWidthQuote){
endsWithQuote = value[value.length - 1] == firstQuoteType;
}
if (startsWidthQuote && endsWithQuote){
isQuoted = true;
}
}
if (isQuoted){
return value = value.slice(1,value.length-1);
} else {
return value ? (regexNum.test(value) ? parseFloat(value) : value) : false;
}
}
module.exports = parser;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment