Example #1
0
config.requires = function() {
  var p = grunt.util.pluralize;
  var props = grunt.util.toArray(arguments).map(config.getPropString);
  var msg = 'Verifying propert' + p(props.length, 'y/ies') +
    ' ' + grunt.log.wordlist(props) + ' exist' + p(props.length, 's') +
    ' in config...';
  grunt.verbose.write(msg);
  var failProps = config.data && props.filter(function(prop) {
    return config.get(prop) == null;
  }).map(function(prop) {
    return '"' + prop + '"';
  });
  if (config.data && failProps.length === 0) {
    grunt.verbose.ok();
    return true;
  } else {
    grunt.verbose.or.write(msg);
    grunt.log.error().error('Unable to process task.');
    if (!config.data) {
      throw grunt.util.error('Unable to load config.');
    } else {
      throw grunt.util.error('Required config propert' +
        p(failProps.length, 'y/ies') + ' ' + failProps.join(', ') + ' missing.');
    }
  }
};
                filePair.src.forEach(function(src) {
                    var dest;

                    if (destIsDirectory(filePair.dest)) {
                        dest = (isExpandedPair) ? filePair.dest : unixifyPath(path.join(filePair.dest, src));
                    } else {
                        dest = filePair.dest;
                    }

                    if (grunt.file.isDir(src)) {
                        grunt.verbose.writeln('Creating ' + chalk.cyan(dest));
                        grunt.file.mkdir(dest);

                        if (options.timestamp) {
                            dirs[dest] = src;
                        }

                        tally.dirs++;
                    } else {
                        grunt.verbose.writeln('Copying ' + chalk.cyan(src) + ' -> ' + chalk.cyan(dest));
                        grunt.file.copy(src, dest, copyOptions);
                        syncTimestamp(src, dest);

                        if (options.mode !== false) {
                            fs.chmodSync(dest, (options.mode === true) ? fs.lstatSync(src).mode : options.mode);
                        }
                        tally.files++;
                    }
                });
Example #3
0
function loadTask(filepath) {
  // In case this was called recursively, save registry for later.
  loadTaskStack.push(registry);
  // Reset registry.
  registry = {tasks: [], untasks: [], meta: {info: lastInfo, filepath: filepath}};
  var filename = path.basename(filepath);
  var msg = 'Loading "' + filename + '" tasks...';
  var regCount = 0;
  var fn;
  try {
    // Load taskfile.
    fn = require(path.resolve(filepath));
    if (typeof fn === 'function') {
      fn.call(grunt, grunt);
    }
    grunt.verbose.write(msg).ok();
    // Log registered/renamed/unregistered tasks.
    ['un', ''].forEach(function(prefix) {
      var list = grunt.util._.chain(registry[prefix + 'tasks']).uniq().sort().value();
      if (list.length > 0) {
        regCount++;
        grunt.verbose.writeln((prefix ? '- ' : '+ ') + grunt.log.wordlist(list));
      }
    });
    if (regCount === 0) {
      grunt.verbose.warn('No tasks were registered or unregistered.');
    }
  } catch (e) {
    // Something went wrong.
    grunt.log.write(msg).error().verbose.error(e.stack).or.error(e);
  }
  // Restore registry.
  registry = loadTaskStack.pop() || {};
}
    function getConfig() {
        var config,
            rcFile = require("rc")("jsbeautifier", {});

        if (options.config || !_.isEqual(rcFile, {})) {
            var baseConfig = options.config ? grunt.file.readJSON(path.resolve(options.config)) : rcFile;
            config = {
                js: {},
                css: {},
                html: {}
            };
            _.extend(config.js, baseConfig);
            _.extend(config.css, baseConfig);
            _.extend(config.html, baseConfig);
            _.extend(config.js, baseConfig.js);
            _.extend(config.css, baseConfig.css);
            _.extend(config.html, baseConfig.html);
            _.extend(config.js, options.js);
            _.extend(config.css, options.css);
            _.extend(config.html, options.html);
        } else {
            config = options;
        }
        config.js.fileTypes = _.union(config.js.fileTypes, [".js", ".json"]);
        config.css.fileTypes = _.union(config.css.fileTypes, [".css"]);
        config.html.fileTypes = _.union(config.html.fileTypes, [".html"]);

        grunt.verbose.writeln("Beautify config before converting camelcase to underscore: " + JSON.stringify(config));

        convertCamelCaseToUnderScore(config);

        grunt.verbose.writeln("Using beautify config: " + JSON.stringify(config));
        return config;
    }
Example #5
0
  grunt.registerMultiTask('scrape', 'Extract data from web pages.', function() {

    var config = this.data;

    _.each(config, function(param, key) {
      if (_.isFunction(param)) {
        config[key] = param();
      }
    });

    var done = this.async();

    grunt.verbose.writeln('[log] Scraping data from: ' + config.src + '');
    grunt.verbose.writeln('[log] Scraping data to: ' + config.dest);

    Scraper.scrape(config.src, config)
      .then(function(data) {
        Exporter.export(config.dest, data, config)
          .then(function(filepath) {
            grunt.log.ok('[ok] Successfully scraped data from: ' + config.src);
            grunt.log.ok('[ok] File was writen to: ' + filepath);
            done();
          })
          .catch(function(error) {
            grunt.log.error(error);
          });
      });
  });
Example #6
0
  async.eachLimit(filesToCheck, options.concurrencyCount, function (src, next) {
    var bin;
    var args;

    if (options.bundleExec) {
      bin = 'bundle';
      args = ['exec', 'sass', '--check', src];
    } else {
      bin = 'sass';
      args = ['--check', src];
    }

    grunt.verbose.writeln('Command: ' + bin + ' ' + args.join(' '));

    grunt.verbose.writeln('Checking file ' + chalk.cyan(src) + ' syntax.');
    spawn(bin, args, {stdio: 'inherit'})
      .on('error', grunt.warn)
      .on('close', function (code) {
        if (code > 0) {
          failCount++;
          grunt.log.error('Checking file ' + chalk.cyan(src) + ' - ' + chalk.red('failed') + '.');
        } else {
          grunt.verbose.ok('Checking file ' + chalk.cyan(src) + ' - ' + chalk.green('passed') + '.');
        }

        next();
      });
  }, function () {
 function verboseWrite(chunk) {
   if (onReadyCallback && chunk.toString().indexOf('running on port') != -1) {
     grunt.verbose.writeln('phantomjs STARTED');
     onReadyCallback();
     onReadyCallback = null;
   }
   grunt.verbose.write(chunk);
 }
Example #8
0
Utils.extension = function(filename) {
  grunt.verbose.writeln('extension');
  grunt.verbose.writeln(filename);
  if(grunt.util.kindOf(filename) === 'array' && filename.length > 0) {
    filename = filename[0];
  }
  return _(filename.match(/[^.]*$/)).last();
};
Example #9
0
 stunnel.openTunnel(function(isOpen) {
   if (shouldStayAliveForever && isOpen) {
     grunt.verbose.writeln('Keeping the sauce-tunnel open forever because you used the keepalive flag `' + task.nameArgs + '`');
     return;
   }
   grunt.verbose.writeln('To keep the sauce-tunnel open forever, use the grunt task `' + task.nameArgs + ':keepalive`');
   taskCompletedSuccessfully(isOpen);
 });
function createNonAmdScriptOptions(options, reporters) {
  grunt.verbose.write('Configuring Non-AMD support...');
  var scriptOptions = {
    scripts: toRelativeFiles(jasmineCoreScripts, options.src, mandatoryHelpers, nonAmdExecutor,
                             options.helpers, reporters, options.specs)
  };
  grunt.verbose.ok();
  return scriptOptions;
};
Example #11
0
exports.stop = function (server, phantomjs) {
  if (server) {
    server.kill();
    grunt.verbose.writeln('buster-server stopped');
  }
  if (phantomjs) {
    phantomjs.kill();
    grunt.verbose.writeln('phantomjs stopped');
  }
};
Example #12
0
 grunt.file.expand(val).forEach(function(filepath) {
   var checkForContent = grunt.file.read(filepath);
   if (checkForContent.length === 0 || checkForContent === '') {
     grunt.verbose.warn('Skipping empty path:'.yellow, val);
   } else {
     var parsedData = exports.dataFileReaderFactory(filepath);
     metadata = grunt.config.process(_.extend({}, metadata, parsedData));
     grunt.verbose.ok('metadata:'.yellow, metadata);
   }
 });
function createAmdScriptOptions(options, reporters) {
  grunt.verbose.write('Configuring AMD support...');
  var generatedAmdHelperScript = createAmdHelperScript(options);
  var scriptOptions = {
    scripts: toRelativeFiles(jasmineCoreScripts, mandatoryHelpers, reporters, options.amd.lib,
                             options.amd.main, options.helpers, generatedAmdHelperScript),
  };
  grunt.verbose.ok();
  return scriptOptions;
};
Example #14
0
    success: function(filePath, wasCached) {
        if(!wasCached) {
            grunt.verbose.write("Linting " + this._getFileName(filePath) + "...");  
        } else {
            grunt.verbose.write("Skipped " + this._getFileName(filePath) + "...");
        }

        grunt.verbose.ok();

        this.succeeded = true;
    },
/**
 * Helps to get the right value from optimist object
 * @param argv
 * @returns {*}
 */
function get_environment(argv){
  if( argv["environment"] === true || argv["environment"] == "" ){
    grunt.verbose.writeln("");
    grunt.verbose.writeln("Automatically selected environment dev");
    grunt.verbose.writeln("you can input the environment using,");
    grunt.verbose.writeln("phantomizer --[switch] [project] --environment [environment]");
    grunt.verbose.writeln("");
    return "dev";
  }
  return argv["environment"];
}
Example #16
0
task.init = function(tasks, options) {
  if (!options) { options = {}; }

  // Were only init tasks specified?
  var allInit = tasks.length > 0 && tasks.every(function(name) {
    var obj = task._taskPlusArgs(name).task;
    return obj && obj.init;
  });

  // Get any local Gruntfile or tasks that might exist. Use --gruntfile override
  // if specified, otherwise search the current directory or any parent.
  var gruntfile, msg;
  if (allInit || options.gruntfile === false) {
    gruntfile = null;
  } else {
    gruntfile = grunt.option('gruntfile') ||
      grunt.file.findup('Gruntfile.{js,coffee}', {nocase: true});
    msg = 'Reading "' + (gruntfile ? path.basename(gruntfile) : '???') + '" Gruntfile...';
  }

  if (options.gruntfile === false) {
    // Grunt was run as a lib with {gruntfile: false}.
  } else if (gruntfile && grunt.file.exists(gruntfile)) {
    grunt.verbose.writeln().write(msg).ok();
    // Change working directory so that all paths are relative to the
    // Gruntfile's location (or the --base option, if specified).
    process.chdir(grunt.option('base') || path.dirname(gruntfile));
    // Load local tasks, if the file exists.
    loadTasksMessage('Gruntfile');
    loadTask(gruntfile);
  } else if (options.help || allInit) {
    // Don't complain about missing Gruntfile.
  } else if (grunt.option('gruntfile')) {
    // If --config override was specified and it doesn't exist, complain.
    grunt.log.writeln().write(msg).error();
    grunt.fatal('Unable to find "' + gruntfile + '" Gruntfile.', grunt.fail.code.MISSING_GRUNTFILE);
  } else if (!grunt.option('help')) {
    grunt.verbose.writeln().write(msg).error();
    grunt.log.writelns(
      'A valid Gruntfile could not be found. Please see the getting ' +
      'started guide for more information on how to configure grunt: ' +
      'http://gruntjs.com/getting-started'
    );
    grunt.fatal('Unable to find Gruntfile.', grunt.fail.code.MISSING_GRUNTFILE);
  }

  // Load all user-specified --npm tasks.
  (grunt.option('npm') || []).map(String).forEach(task.loadNpmTasks);
  // Load all user-specified --tasks.
  (grunt.option('tasks') || []).map(String).forEach(task.loadTasks);
};
Example #17
0
    var contents = filespec.src.filter(function(filepath) {
      var fullpath = path.join(filespec.cwd, filepath);

      if (!grunt.file.exists(fullpath) ||
          grunt.file.isDir(fullpath) ||
          grunt.file.isMatch(me.options.partialsGlob, fullpath)) {
        grunt.verbose.writeln(fullpath + " not a valid page");
        return false;
      } else if(validExtensions.indexOf(path.extname(fullpath).substr(1)) === -1) {
        grunt.verbose.writeln(fullpath + ': not a valid extension, skipping');
        return false;  
      } else {
        return true;
      }
    }).map(function(filepath) {
Example #18
0
FileProcessor.prototype.getBlocks = function (configs) {
    var lines = this.file.content.split(/\n/),
        line,
        blocks = [],
        block;

    for (var i = 0; i < lines.length; i++) {
        line = lines[i];

        var start = line.match(startExp);
        if (start) {
            var name = start[2],
                config = findConfig(configs, name);

            block = new Block(name, config);
            block.startAnchor = start[0];
            block.type = start[1];
            //block.template = defaultTemplates[block.type];
            block.indent = (line.match(/^\s*/) || [])[0];

            if (config) {
                block.template = config.template || config.templates[block.type];

                // Custom template fn
                if(typeof config.templatesFn[block.type] === 'function') {
                  block.templateFn = config.templatesFn[block.type];
                }

                block.config = config;
                blocks.push(block);
            } else {
                grunt.verbose.writeln('Found block "' + name + '" that is not defined for this target.');
            }
        }

        if (block) {
            block.lines.push(line);
            var file = getFileName(line, block);
            if (file) {
                block.files.push(file);
            }
        }

        var end = line.match(endExp);
        if (end) {
            if (!block) {
                grunt.warn('Found endfileblock comment without a matching build comment.');
            }

            block.endAnchor = end[0];
            block = null;
        }
    }

    if (block) {
        grunt.warn('Block "' + block.name + '" does not have an endfileblock comment.');
    }

    return blocks;
};
Example #19
0
function Builder (options) {
  this.pages = [];

  if (_.isUndefined(options)) {
    options = {};
  }

  this.options = _.defaultsDeep({}, options, {
    root: process.cwd(),
    paths : {
      build   : 'build',
      data    : 'datas',
      layout  : 'views/layouts',
      source  : 'sources',
      template: 'views/templates',
    },
    customFilters: {}
  });

  grunt.verbose.debug(util.inspect(this.options));

  this.options.paths.build = path.join(this.options.root, this.options.paths.build);
  this.options.paths.data = path.join(this.options.root, this.options.paths.data);
  this.options.paths.layout = path.join(this.options.root, this.options.paths.layout);
  this.options.paths.source = path.join(this.options.root, this.options.paths.source);
  this.options.paths.template = path.join(this.options.root, this.options.paths.template);

  // create Liquid engine
  this.liquidEngine = new Liquid.Engine();
  // permit includes ( see https://github.com/sirlantis/liquid-node/issues/24 )
  this.liquidEngine.registerFileSystem(new Liquid.LocalFileSystem(this.options.paths.template));
}
Example #20
0
 ['un', ''].forEach(function(prefix) {
   var list = grunt.util._.chain(registry[prefix + 'tasks']).uniq().sort().value();
   if (list.length > 0) {
     regCount++;
     grunt.verbose.writeln((prefix ? '- ' : '+ ') + grunt.log.wordlist(list));
   }
 });
Example #21
0
exports.dataFileReaderFactory = function(filepath) {
  var ext = path.extname(filepath);
  var reader = grunt.file.readJSON;
  switch(ext) {
    case '.json':
      grunt.verbose.writeln('>> Reading JSON'.yellow);
      reader = grunt.file.readJSON;
      break;
    case '.yml':
    case '.yaml':
      grunt.verbose.writeln('>> Reading YAML'.yellow);
      reader = grunt.file.readYAML;
      break;
  }
  return reader(filepath);
};
Example #22
0
module.exports = function(){
  var onReadyCallback = this.async();

  var phantomjs = require("phantomjs").path;
  var child_process = require('child_process');
  var config = this.data || {};

  var args = ["--webdriver=" + (config.port || 9515)];
  grunt.verbose.writeln('phantomjs START path:%s args:%s', phantomjs, args);

  var child = child_process.spawn(phantomjs, args);
  process.on('exit', function() {
    child.kill();
  });

  child.on('error', function(error) {
    grunt.verbose.writeln('phantomjs ERROR');
    grunt.fatal(error);
  });
  child.on('exit', function(code) {
    grunt.verbose.writeln('phantomjs END');
    if (code) grunt.fatal('phantomjs FAIL');
  });

  function verboseWrite(chunk) {
    if (onReadyCallback && chunk.toString().indexOf('running on port') != -1) {
      grunt.verbose.writeln('phantomjs STARTED');
      onReadyCallback();
      onReadyCallback = null;
    }
    grunt.verbose.write(chunk);
  }
  child.stdout.on('data', verboseWrite);
  child.stderr.on('data', verboseWrite);
}
task.phantomRunner = function(options, cb) {
  options = grunt.util._.extend({}, defaultOptions, options);

  var phantomReporters = [
      __dirname + '/jasmine/reporters/ConsoleReporter.js',
      __dirname + '/jasmine/reporters/JUnitReporter.js'
    ],
    port = (options.server && options.server.port) || 8888;

  var url = URL.format({
    protocol : 'http',
    hostname : '127.0.0.1',
    port : port + '',
    pathname : path.join(options['runner-dir'], generatedRunnerFilename)
  });

  grunt.verbose.subhead('Testing jasmine specs via phantom').or.writeln('Testing jasmine specs via phantom');
  jasmine.createSpecRunnerPage(options, phantomReporters);
  var server = startServer(baseDir, port);

  runPhantom(url, options, phantomReporters.length, function(err, status) {
    server.close();
    if (typeof cb === 'function') cb(err,status);
  });
};
Example #24
0
var api = function (steps, name, done, fatal) {
    var i = 0;

    grunt.verbose.writeln('Following a workflow with %s steps', chalk.cyan(steps.length));

    async.eachSeries(steps, function (step, next) {

        grunt.verbose.writeln('Executing workflow step %s...', chalk.cyan(++i));

        var r = step.rsync;
        if (r) {
            ssh([ util.format('sudo mkdir -p %s', r.dest) ], name, transfer, fatal);
        } else {
            var commands = _.flatten(step);
            ssh(commands, name, next, fatal);
        }

        function transfer () {
            rsync(name, r, move);
        }

        function move () {
            var parent = path.relative(path.dirname(r.local), r.local);
            var remoteSync = r.remote + '/' + parent;

            ssh([ util.format('sudo cp -r %s/* %s', remoteSync, r.dest) ], name, next, fatal);
        }
    }, done);

};
ExternalVersioner.prototype.doVersion = function () {
  if (this.options.runTask) {
    grunt.verbose.writeln("Tasks triggered: '" + this.surrogateTasks.join(", ") + "'");
    grunt.task.run(this.surrogateTasks);
    this.saveVersionsMap();
  }
};
Example #26
0
module.exports = function(){
  var config = this.data;
  var taskSucceeded = this.async();
  grunt.verbose.write('webdriver remote', JSON.stringify(config.webdriver.remote));
  var browser = wd.promiseChainRemote(config.webdriver.remote);

  browser.on('status', function(info) {
    grunt.verbose.writeln(info);
  });

  browser.on('command', function(meth, path, data) {
    grunt.verbose.writeln(' > ' + meth, path, data || '');
  });

  browser
    .init(config.browser || {})
    .get(config.url)
    .then(function(){return browser;})
    .then(getJSReport)
    .then(config.onComplete && config.onComplete.bind(browser), config.onError && config.onError.bind(browser))
    .fail(grunt.verbose.writeln.bind(grunt.verbose))
    .fin(function(){
      if (grunt.option('webdriver-keep-open')) return;
      grunt.verbose.writeln('Closing the browser window. To keep it open, pass the --webdriver-keep-open flag to grunt.');
      return browser.quit();
    })
    .done(
      taskSucceeded.bind(null,true),
      taskSucceeded.bind(null,false)
    )
  ;
}
    this.writeChildModuleData = function (sBasePath, sModuleName, aNodes) {
        var aChildModulesToWrite = [];
        var sFileData = '';

        for (var i = 0; i < aNodes.length; i++) {
            if (typeof aNodes[i].aChildren !== 'undefined') {
                sFileData += aNodes[i].sStartTokenText;
                aChildModulesToWrite.push(aNodes[i]);
            } else {
                sFileData += aNodes[i];
            }
        }

        // Write the destination file.
        grunt.file.write(sBasePath + sModuleName, sFileData);

        // Print a success message.
        grunt.verbose.writeln('Module "' + sBasePath + sModuleName + '" created.');

        for (i = 0; i < aChildModulesToWrite.length; i++) {
            this.writeChildModuleData(
                sBasePath + sModuleName + '-submodules/',
                aChildModulesToWrite[i].sUniqueModuleName + this.oFileParser.sExtension,
                aChildModulesToWrite[i].aChildren
            );
        }
    };
Example #28
0
 .finally(function(){
   if (grunt.option('webdriver-keep-open')) {
     return;
   }
   grunt.verbose.writeln('Closing the browser window. To keep it open, pass the --webdriver-keep-open flag to grunt.');
   return browser.quit();
 })
Example #29
0
var translations2jsTask = function () {

  var jsonFiles = utils.filterForJson(this.filesSrc);
  grunt.verbose.writeln('Include languages: ' + JSON.stringify(jsonFiles, null, '  '));

  var options = this.options({});

  var languages = jsonFiles.map(function (jsonFile) {
    var locale = path.basename(jsonFile, '.json');
    var data = grunt.file.readJSON(jsonFile);

    var language = {
      locale: locale,
      data: data
    };

    return language;
  });

  grunt.file.copy(options.template, options.out, {
    process: function (contents) {
      return grunt.template.process(contents, {
        data: {
          module: options.module,
          languages: languages
        }
      });
    }
  });
};
 }, function write(result) {
   var out = path.join(options.basePath, options.flatten === true ? path
       .basename(result.name) : result.name);
   grunt.verbose.writeln('instrument to ' + out);
   grunt.file.mkdir(path.dirname(out));
   fs.writeFile(out, result.code, 'utf8', this.async(as(1)));
 }, function end() {