<commit_before>/*
 * grunt-contrib-copy
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 Chris Talkington, contributors
 * Licensed under the MIT license.
 * https://github.com/gruntjs/grunt-contrib-copy/blob/master/LICENSE-MIT
 */

module.exports = function(grunt) {
  'use strict';

  // TODO: ditch this when grunt v0.4 is released
  grunt.util = grunt.util || grunt.utils;

  var path = require('path');

  // TODO: remove if/when we officially drop node <= 0.7.9
  path.sep = path.sep || path.normalize('/');

  grunt.registerMultiTask('copy', 'Copy files.', function() {
    var kindOf = grunt.util.kindOf;
    var helpers = require('grunt-lib-contrib').init(grunt);

    var options = helpers.options(this, {
      basePath: false,
      flatten: false,
      processName: false,
      processContent: false,
      processContentExclude: [],
      minimatch: {}
    });

    // TODO: ditch this when grunt v0.4 is released
    this.files = this.files || helpers.normalizeMultiTaskFiles(this.data, this.target);

    var copyOptions = {
      process: options.processContent,
      noProcess: options.processContentExclude
    };

    grunt.verbose.writeflags(options, 'Options');

    var srcFiles;
    var destType;

    var basePath;
    var filename;
    var relative;
    var destFile;
    var srcFile;

    this.files.forEach(function(file) {
      file.dest = path.normalize(file.dest);
      srcFiles = grunt.file.expandFiles(options.minimatch, file.src);

      if (srcFiles.length === 0) {
        grunt.fail.warn('Unable to copy; no valid source files were found.');
      }

      destType = detectDestType(file.dest);

      if (destType === 'file') {
        if (srcFiles.length === 1) {
          srcFile = path.normalize(srcFiles[0]);

          grunt.verbose.or.write('Copying file' + ' to ' + file.dest.cyan + '...');
          grunt.file.copy(srcFile, file.dest);

          grunt.verbose.or.ok();
        } else {
          grunt.fail.warn('Unable to copy multiple files to the same destination filename, did you forget a trailing slash?');
        }
      } else if (destType === 'directory') {
        basePath = helpers.findBasePath(srcFiles, options.basePath);

        grunt.verbose.writeln('Base Path: ' + basePath.cyan);
        grunt.verbose.or.write('Copying files' + ' to ' + file.dest.cyan + '...');

        srcFiles.forEach(function(srcFile) {
          srcFile = path.normalize(srcFile);
          filename = path.basename(srcFile);
          relative = path.dirname(srcFile);

          if (options.flatten) {
            relative = '';
          } else if (basePath && basePath.length >= 1) {
            relative = grunt.util._(relative).strRight(basePath).trim(path.sep);
          }

          if (options.processName && kindOf(options.processName) === 'function') {
            filename = options.processName(filename);
          }

          // make paths outside grunts working dir relative
          relative = relative.replace(/\.\.(\/|\\)/g, '');

          destFile = path.join(file.dest, relative, filename);

          grunt.file.copy(srcFile, destFile, copyOptions);
        });

        grunt.verbose.or.ok();
      }
    });
  });

  var detectDestType = function(dest) {
    if (grunt.util._.endsWith(dest, path.sep)) {
      return 'directory';
    } else {
      return 'file';
    }
  };
};<commit_msg>copyOptions is passed to a single file copy now<commit_after>/*
 * grunt-contrib-copy
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 Chris Talkington, contributors
 * Licensed under the MIT license.
 * https://github.com/gruntjs/grunt-contrib-copy/blob/master/LICENSE-MIT
 */

module.exports = function(grunt) {
  'use strict';

  // TODO: ditch this when grunt v0.4 is released
  grunt.util = grunt.util || grunt.utils;

  var path = require('path');

  // TODO: remove if/when we officially drop node <= 0.7.9
  path.sep = path.sep || path.normalize('/');

  grunt.registerMultiTask('copy', 'Copy files.', function() {
    var kindOf = grunt.util.kindOf;
    var helpers = require('grunt-lib-contrib').init(grunt);

    var options = helpers.options(this, {
      basePath: false,
      flatten: false,
      processName: false,
      processContent: false,
      processContentExclude: [],
      minimatch: {}
    });

    // TODO: ditch this when grunt v0.4 is released
    this.files = this.files || helpers.normalizeMultiTaskFiles(this.data, this.target);

    var copyOptions = {
      process: options.processContent,
      noProcess: options.processContentExclude
    };

    grunt.verbose.writeflags(options, 'Options');

    var srcFiles;
    var destType;

    var basePath;
    var filename;
    var relative;
    var destFile;
    var srcFile;

    this.files.forEach(function(file) {
      file.dest = path.normalize(file.dest);
      srcFiles = grunt.file.expandFiles(options.minimatch, file.src);

      if (srcFiles.length === 0) {
        grunt.fail.warn('Unable to copy; no valid source files were found.');
      }

      destType = detectDestType(file.dest);

      if (destType === 'file') {
        if (srcFiles.length === 1) {
          srcFile = path.normalize(srcFiles[0]);

          grunt.verbose.or.write('Copying file' + ' to ' + file.dest.cyan + '...');
          grunt.file.copy(srcFile, file.dest, copyOptions);

          grunt.verbose.or.ok();
        } else {
          grunt.fail.warn('Unable to copy multiple files to the same destination filename, did you forget a trailing slash?');
        }
      } else if (destType === 'directory') {
        basePath = helpers.findBasePath(srcFiles, options.basePath);

        grunt.verbose.writeln('Base Path: ' + basePath.cyan);
        grunt.verbose.or.write('Copying files' + ' to ' + file.dest.cyan + '...');

        srcFiles.forEach(function(srcFile) {
          srcFile = path.normalize(srcFile);
          filename = path.basename(srcFile);
          relative = path.dirname(srcFile);

          if (options.flatten) {
            relative = '';
          } else if (basePath && basePath.length >= 1) {
            relative = grunt.util._(relative).strRight(basePath).trim(path.sep);
          }

          if (options.processName && kindOf(options.processName) === 'function') {
            filename = options.processName(filename);
          }

          // make paths outside grunts working dir relative
          relative = relative.replace(/\.\.(\/|\\)/g, '');

          destFile = path.join(file.dest, relative, filename);

          grunt.file.copy(srcFile, destFile, copyOptions);
        });

        grunt.verbose.or.ok();
      }
    });
  });

  var detectDestType = function(dest) {
    if (grunt.util._.endsWith(dest, path.sep)) {
      return 'directory';
    } else {
      return 'file';
    }
  };
};<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
/* globals __webpack_hash__ */
if (module.hot) {
	var lastHash;
	var upToDate = function upToDate() {
		return lastHash.indexOf(__webpack_hash__) >= 0;
	};
	var log = require("./log");
	var check = function check() {
		module.hot
			.check(true)
			.then(function (updatedModules) {
				if (!updatedModules) {
					log(
						"warning",
						"[HMR] Cannot find update. " + typeof window !== "undefined"
							? "Need to do a full reload!"
							: "Please reload manually!"
					);
					log(
						"warning",
						"[HMR] (Probably because of restarting the webpack-dev-server)"
					);
					if (typeof window !== "undefined") {
						window.location.reload();
					}
					return;
				}

				if (!upToDate()) {
					check();
				}

				require("./log-apply-result")(updatedModules, updatedModules);

				if (upToDate()) {
					log("info", "[HMR] App is up to date.");
				}
			})
			.catch(function (err) {
				var status = module.hot.status();
				if (["abort", "fail"].indexOf(status) >= 0) {
					log(
						"warning",
						"[HMR] Cannot apply update. " + typeof window !== "undefined"
							? "Need to do a full reload!"
							: "Please reload manually!"
					);
					log("warning", "[HMR] " + log.formatError(err));
					if (typeof window !== "undefined") {
						window.location.reload();
					}
				} else {
					log("warning", "[HMR] Update failed: " + log.formatError(err));
				}
			});
	};
	var hotEmitter = require("./emitter");
	hotEmitter.on("webpackHotUpdate", function (currentHash) {
		lastHash = currentHash;
		if (!upToDate() && module.hot.status() === "idle") {
			log("info", "[HMR] Checking for updates on the server...");
			check();
		}
	});
	log("info", "[HMR] Waiting for update signal from WDS...");
} else {
	throw new Error("[HMR] Hot Module Replacement is disabled.");
}
<commit_msg>fix parentheses, lint<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
/* globals __webpack_hash__ */
if (module.hot) {
	var lastHash;
	var upToDate = function upToDate() {
		return lastHash.indexOf(__webpack_hash__) >= 0;
	};
	var log = require("./log");
	var check = function check() {
		module.hot
			.check(true)
			.then(function (updatedModules) {
				if (!updatedModules) {
					log(
						"warning",
						"[HMR] Cannot find update. " +
							(typeof window !== "undefined"
								? "Need to do a full reload!"
								: "Please reload manually!")
					);
					log(
						"warning",
						"[HMR] (Probably because of restarting the webpack-dev-server)"
					);
					if (typeof window !== "undefined") {
						window.location.reload();
					}
					return;
				}

				if (!upToDate()) {
					check();
				}

				require("./log-apply-result")(updatedModules, updatedModules);

				if (upToDate()) {
					log("info", "[HMR] App is up to date.");
				}
			})
			.catch(function (err) {
				var status = module.hot.status();
				if (["abort", "fail"].indexOf(status) >= 0) {
					log(
						"warning",
						"[HMR] Cannot apply update. " +
							(typeof window !== "undefined"
								? "Need to do a full reload!"
								: "Please reload manually!")
					);
					log("warning", "[HMR] " + log.formatError(err));
					if (typeof window !== "undefined") {
						window.location.reload();
					}
				} else {
					log("warning", "[HMR] Update failed: " + log.formatError(err));
				}
			});
	};
	var hotEmitter = require("./emitter");
	hotEmitter.on("webpackHotUpdate", function (currentHash) {
		lastHash = currentHash;
		if (!upToDate() && module.hot.status() === "idle") {
			log("info", "[HMR] Checking for updates on the server...");
			check();
		}
	});
	log("info", "[HMR] Waiting for update signal from WDS...");
} else {
	throw new Error("[HMR] Hot Module Replacement is disabled.");
}
<|endoftext|>


<commit_before>/**
 * grunt-defs
 * https://github.com/EE/grunt-defs
 *
 * Author Michał Gołębiowski <michal.golebiowski@laboratorium.ee>
 * Copyright (c) 2013 Laboratorium EE
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

    var fs = require('fs'),
        defs = require('defs');

    grunt.registerMultiTask('defs',
        'Static scope analysis and transpilation of ES6 block scoped const and let variables, to ES3.',

        function () {
            var filesNum = 0,
                validRun = true,
            // Merge task-specific and/or target-specific options with these defaults.
                options = this.options();

            // Iterate over all specified file groups.
            this.files.forEach(function (mapping) {
                var tmpFilePath = mapping.dest; // use the destination file as a temporary source one

                if (options.defsConfigURL) {
                    options.defsOptions = grunt.file.readJSON(options.defsConfigURL);
                    delete options.defsConfigURL;
                }

                if (mapping.dest) {
                    // If destination file provided, concatenate all source files to a temporary one.
                    // In such a case options transformDest & outputFileSuffix are ignored.

                    grunt.file.write(
                        tmpFilePath,
                        mapping.src.map(function (file) {
                            return grunt.file.read(file);
                        }).join('\n')
                    );

                    if (!runDefs(tmpFilePath, tmpFilePath, options.defsOptions)) {
                        validRun = false;
                    }
                } else {
                    // Otherwise each file will have its own defs output.

                    // Transform the destination path.
                    if (!options.transformDest) {
                        // By default, append options.outputFileSuffix to the file name.
                        options.transformDest = function transformDest(path) {
                            return path + (options.outputFileSuffix || '');
                        };
                    }

                    mapping.src.map(function (path) {
                        if (!runDefs(path, options.transformDest(path), options.defsOptions)) {
                            validRun = false;
                        }
                    });
                }
            });

            function runDefs(srcPath, destPath, defsOptions) {
                filesNum++;

                var defsOutput = defs(grunt.file.read(srcPath), defsOptions);

                // Write the destination file.
                if (defsOutput.errors) {
                    grunt.log.write('Generating "' + destPath + '" from "' + srcPath + '"...');
                    grunt.log.error();
                    defsOutput.errors.forEach(function (error) {
                        grunt.log.error(error);
                    });
                    return false;
                }

                // Remove the temporary destination file if existed.
                if (fs.existsSync(destPath)) {
                    fs.unlinkSync(destPath);
                }

                // Write defs output to the target file.
                grunt.file.write(destPath, defsOutput.src);

                return true;
            }

            if (validRun) {
                if (filesNum < 1) {
                    grunt.log.ok('No files provided to the defs task.');
                } else {
                    grunt.log.ok(filesNum + (filesNum === 1 ? ' file' : ' files') + ' successfully generated.');
                }
            }
            return validRun;
        });

};
<commit_msg>Use grunt file methods instead of node’s fs ones.<commit_after>/**
 * grunt-defs
 * https://github.com/EE/grunt-defs
 *
 * Author Michał Gołębiowski <michal.golebiowski@laboratorium.ee>
 * Copyright (c) 2013 Laboratorium EE
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

    var defs = require('defs');

    grunt.registerMultiTask('defs',
        'Static scope analysis and transpilation of ES6 block scoped const and let variables, to ES3.',

        function () {
            var filesNum = 0,
                validRun = true,
            // Merge task-specific and/or target-specific options with these defaults.
                options = this.options();

            // Iterate over all specified file groups.
            this.files.forEach(function (mapping) {
                var tmpFilePath = mapping.dest; // use the destination file as a temporary source one

                if (options.defsConfigURL) {
                    options.defsOptions = grunt.file.readJSON(options.defsConfigURL);
                    delete options.defsConfigURL;
                }

                if (mapping.dest) {
                    // If destination file provided, concatenate all source files to a temporary one.
                    // In such a case options transformDest & outputFileSuffix are ignored.

                    grunt.file.write(
                        tmpFilePath,
                        mapping.src.map(function (file) {
                            return grunt.file.read(file);
                        }).join('\n')
                    );

                    if (!runDefs(tmpFilePath, tmpFilePath, options.defsOptions)) {
                        validRun = false;
                    }
                } else {
                    // Otherwise each file will have its own defs output.

                    // Transform the destination path.
                    if (!options.transformDest) {
                        // By default, append options.outputFileSuffix to the file name.
                        options.transformDest = function transformDest(path) {
                            return path + (options.outputFileSuffix || '');
                        };
                    }

                    mapping.src.map(function (path) {
                        if (!runDefs(path, options.transformDest(path), options.defsOptions)) {
                            validRun = false;
                        }
                    });
                }
            });

            function runDefs(srcPath, destPath, defsOptions) {
                filesNum++;

                var defsOutput = defs(grunt.file.read(srcPath), defsOptions);

                // Write the destination file.
                if (defsOutput.errors) {
                    grunt.log.write('Generating "' + destPath + '" from "' + srcPath + '"...');
                    grunt.log.error();
                    defsOutput.errors.forEach(function (error) {
                        grunt.log.error(error);
                    });
                    return false;
                }

                // Remove the temporary destination file if existed.
                if (grunt.file.exists(destPath)) {
                    grunt.file.delete(destPath);
                }

                // Write defs output to the target file.
                grunt.file.write(destPath, defsOutput.src);

                return true;
            }

            if (validRun) {
                if (filesNum < 1) {
                    grunt.log.ok('No files provided to the defs task.');
                } else {
                    grunt.log.ok(filesNum + (filesNum === 1 ? ' file' : ' files') + ' successfully generated.');
                }
            }
            return validRun;
        });

};
<|endoftext|>


<commit_before>/*
 * grunt-dojo
 * https://github.com/phated/grunt-dojo
 *
 * Copyright (c) 2013 Blaine Bublitz
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {

  'use strict';

  grunt.registerMultiTask('dojo', 'build dojo by spawning a child process', function(){

    var done = this.async();

    var options = this.options({
      dojo: null,
      load: 'build',
      profile: null,
      package: null,
      packages: null,
      require: null,
      requires: null,
      releaseDir: null,
      cwd: null,
      dojoConfig: null
    });

    grunt.log.subhead('Building Dojo...');

    var args = [];
    /*
     * Add parameter(s) to the argument list and log them, if in verbose mode.
     */
    var addParam = function() {
        grunt.verbose.write("\t");
        grunt.util._.forEach(arguments, function(param) {
            args.push(param);
            grunt.verbose.write(param +" ");
        });
        grunt.verbose.write("\n");
    };

    if(options.dojo){
      grunt.verbose.writeln("Dojo build parameters:");
      addParam(options.dojo);
      addParam('load=' + options.load);

      if(options.dojoConfig){
       addParam('--dojoConfig', options.dojoConfig);
      }

      if(options.profile){
        addParam('--profile', options.profile);
      }

      /*
       * Support both the singular and plural form of the 'package' and 'require' parameters
       */
      ['package', 'require'].forEach(function(dojoParam){
          if(!Array.isArray(options[dojoParam+'s'])) {
            options[dojoParam+'s'] = [];
          }
          if(options[dojoParam]){
            options[dojoParam+'s'].push(options[dojoParam]);
          }
          options[dojoParam+'s'].forEach(function(paramValue){
           addParam('--'+dojoParam, paramValue);
          });
      });

      if(options.releaseDir){
       addParam('--releaseDir', options.releaseDir);
      }
    } else {
      grunt.log.error('No dojo specified');
      done(false);
    }

    var opts = {};
    if(options.cwd){
      opts.cwd = options.cwd;
    }

    var child = grunt.util.spawn({
      cmd: 'node',
      args: args,
      opts: opts
    }, function(err, result){
      if(err){
        grunt.log.error(err);
        return done(false);
      }

      grunt.log.success('Dojo Successfully Built...');

      done();
    });

      if(!!grunt.option('verbose')) {
          child.stdout.on('data', function (data) {
              grunt.log.write(data);
          });
          child.stderr.on('data', function (data) {
              grunt.log.error(data);
          });
      }
  });

};
<commit_msg>Add the command line options in the order the user defined them.<commit_after>/*
 * grunt-dojo
 * https://github.com/phated/grunt-dojo
 *
 * Copyright (c) 2013 Blaine Bublitz
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {

  'use strict';

  grunt.registerMultiTask('dojo', 'build dojo by spawning a child process', function(){

    var done = this.async();

    var userOptions = this.options(),
      options = {},
      defaults = {
        dojo: null,
        load: 'build',
        profile: null,
        package: null,
        packages: null,
        require: null,
        requires: null,
        releaseDir: null,
        cwd: null,
        dojoConfig: null,
        basePath: null
      };

    /* Copy properties from user configuration first and then
     * copy the non-specified defaults over. This preserves
     * the order in which the user defined the properties.
     */
    grunt.util._.forEach(userOptions, function(value, key){
      options[key] = userOptions[key];
      delete defaults[key];
    });
    grunt.util._.extend(options, defaults);

    grunt.log.subhead('Building Dojo...');

    var args = [];
    /*
     * Add parameter(s) to the argument list and log them, if in verbose mode.
     */
    var addParam = function() {
        grunt.verbose.write("\t");
        grunt.util._.forEach(arguments, function(param) {
            args.push(param);
            grunt.verbose.write(param +" ");
        });
        grunt.verbose.write("\n");
    };

    if(options.dojo){
      grunt.verbose.writeln("Dojo build parameters:");
      addParam(options.dojo);
      addParam('load=' + options.load);

      // Add command line parameters in the order in which they were defined
      grunt.util._.forEach(options, function(value, key){
        var match;
        if(value == null){
          return;
        }
        if(/^dojoConfig|profile|releaseDir|basePath$/.test(key)){
          addParam('--' + key, value);
        }
        else if((match = key.match(/^(package|require)s?$/))){
          /*
           * Support both the singular and plural form of the 'package' and 'require' parameters
           */
          if(!Array.isArray(value)){
            value = [value];
          }
          value.forEach(function(value){
            addParam('--' + match[1], value);
          });
        }
      });

    } else {
      grunt.log.error('No dojo specified');
      done(false);
    }

    var opts = {};
    if(options.cwd){
      opts.cwd = options.cwd;
    }

    var child = grunt.util.spawn({
      cmd: 'node',
      args: args,
      opts: opts
    }, function(err, result){
      if(err){
        grunt.log.error(err);
        return done(false);
      }

      grunt.log.success('Dojo Successfully Built...');

      done();
    });

      if(!!grunt.option('verbose')) {
          child.stdout.on('data', function (data) {
              grunt.log.write(data);
          });
          child.stderr.on('data', function (data) {
              grunt.log.error(data);
          });
      }
  });

};
<|endoftext|>


<commit_before>/*
 * grunt-gulp
 * https://github.com/shama/grunt-gulp
 *
 * Copyright (c) 2016 Kyle Robinson Young
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  var gulp = require('gulp');
  var concat = require('gulp-concat');
  var path = require('path');

  grunt.registerMultiTask('gulp', 'Run gulp tasks through grunt', function() {
    var done = this.async();
    var grunttask = this;
    var options = this.options({ tasks: null });

    if (typeof this.data === 'function') {
      gulp.task('default', this.data);
      gulp.start('default', done);
    } else {
      gulp.task('default', function() {
        var count = grunttask.files.length;
        var errcount = 0;
        function isdone() {
          count--;
          if (count < 1) {
            done(errcount === 0);
          }
        }
        grunttask.files.forEach(function(file) {
          var dirname = path.dirname(file.dest);
          var filename = path.relative(dirname, file.dest);

          var s = gulp.src(file.src);
          if (typeof options.tasks === 'function') {
            s = options.tasks.call(s, s);
          }

          var dest = gulp.dest(dirname);
          dest.on('end', function() {
            grunt.log.ok('Created ' + file.dest);
            isdone();
          });
          dest.on('error', function(err) {
            grunt.log.error(err);
            errcount++;
            isdone();
          });
          return s.pipe(concat(filename)).pipe(dest);
        });
      });
      gulp.start();
    }
  });

};
<commit_msg>Have the Grunt task error when the Gulp task returns a rejected promise<commit_after>/*
 * grunt-gulp
 * https://github.com/shama/grunt-gulp
 *
 * Copyright (c) 2016 Kyle Robinson Young
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  var gulp = require('gulp');
  var concat = require('gulp-concat');
  var path = require('path');

  grunt.registerMultiTask('gulp', 'Run gulp tasks through grunt', function() {
    var done = this.async();
    var grunttask = this;
    var options = this.options({ tasks: null });

    if (typeof this.data === 'function') {
      gulp.task('default', this.data);
      gulp.start('default', function(err) {
        if(err) done(false);  // `false` to error out the grunt task
        else done();
      } );
    } else {
      gulp.task('default', function() {
        var count = grunttask.files.length;
        var errcount = 0;
        function isdone() {
          count--;
          if (count < 1) {
            done(errcount === 0);
          }
        }
        grunttask.files.forEach(function(file) {
          var dirname = path.dirname(file.dest);
          var filename = path.relative(dirname, file.dest);

          var s = gulp.src(file.src);
          if (typeof options.tasks === 'function') {
            s = options.tasks.call(s, s);
          }

          var dest = gulp.dest(dirname);
          dest.on('end', function() {
            grunt.log.ok('Created ' + file.dest);
            isdone();
          });
          dest.on('error', function(err) {
            grunt.log.error(err);
            errcount++;
            isdone();
          });
          return s.pipe(concat(filename)).pipe(dest);
        });
      });
      gulp.start();
    }
  });

};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var Promise = require( "bluebird" );
var fs     	= Promise.promisifyAll( require("fs") );
var path	= require('path');
var exec	= require( "child_process" ).exec;

var platformName 	= "";

var Installer		= require( "/opt/openrov/cockpit/src/lib/Installer.js" );

fs.readFileAsync( "/opt/openrov/system/config/platform.conf" )
.then( function( data )
{
	// Parse platform info from configuration file
	var platInfo 	= JSON.parse( data );
	platformName 	= platInfo.platform;

	if( platformName == "" )
	{
		throw "No platform specified";
	}

	return platformName;
} )
.then( function()
{
	var installDir = path.join( "/opt/openrov/cockpit/src/system-plugins/platform-manager/platforms", platformName, "install" );

	// Install board files
	return Installer.Install( installDir );
} )
.catch( function( err )
{
	console.log( "Error: " + err.message );
	process.exit( 1 );
})
.then( function()
{
	console.log( "Install complete." );
	process.exit( 0 );
});
<commit_msg>Updated Install.js to install shared stage<commit_after>#!/usr/bin/env node

var Promise = require( "bluebird" );
var fs     	= Promise.promisifyAll( require("fs") );
var path	= require('path');
var exec	= require( "child_process" ).exec;

var platformName 	= "";

var Installer		= require( "/opt/openrov/cockpit/src/lib/Installer.js" );

fs.readFileAsync( "/opt/openrov/system/config/platform.conf" )
.then( function( data )
{
	// Parse platform info from configuration file
	var platInfo 	= JSON.parse( data );
	platformName 	= platInfo.platform;

	if( platformName == "" )
	{
		throw "No platform specified";
	}

	return platformName;
} )
.then( function()
{
	// Install shared stage
	var installDir = "/opt/openrov/cockpit/src/system-plugins/platform-manager/install";

	// Install board files
	return Installer.Install( installDir );
} )
.then( function()
{
	// Install platform specific stage
	var installDir = path.join( "/opt/openrov/cockpit/src/system-plugins/platform-manager/platforms", platformName, "install" );

	// Install board files
	return Installer.Install( installDir );
} )
.catch( function( err )
{
	console.log( "Error: " + err.message );
	process.exit( 1 );
})
.then( function()
{
	console.log( "Install complete." );
	process.exit( 0 );
});
<|endoftext|>


<commit_before>const gulp = require('gulp');
const gutil = require('gulp-util');
const pkg = require('../package.json');

gulp.task('help', () => {

    gutil.log('');
    gutil.log(gutil.colors.white('blender-gulp v' + pkg.version));
    gutil.log('');
    gutil.log(gutil.colors.black.bgCyan('Build tasks'));
    gutil.log(gutil.colors.green('gulp'), gutil.colors.yellow('[--production]'), ' compile [& minify] assets 📦');
    gutil.log(gutil.colors.green('gulp watch'), '          compile & watch for changes 👀');
    gutil.log(gutil.colors.green('gulp hot'), '            compile & assets from a hot reload server 🔥');
    gutil.log('');
    gutil.log(gutil.colors.black.bgCyan('Utilities'));
    gutil.log(gutil.colors.green('gulp favicon'), '        standalone utility for favicon generation 🌐');
    gutil.log('');
});
<commit_msg>Lint help<commit_after>const gulp = require('gulp');
const gutil = require('gulp-util');
const pkg = require('../package.json');

gulp.task('help', () => {

    gutil.log('');
    gutil.log(gutil.colors.white('blender-gulp v' + pkg.version));
    gutil.log('');
    gutil.log(gutil.colors.black.bgCyan('Build tasks'));
    gutil.log(gutil.colors.green('gulp'), gutil.colors.yellow('[--production]'), ' compile [& minify] assets 📦');
    gutil.log(gutil.colors.green('gulp watch'), '          compile & watch for changes 👀');
    gutil.log(gutil.colors.green('gulp hot'), '            compile & assets from a hot reload server 🔥');
    gutil.log('');
    gutil.log(gutil.colors.black.bgCyan('Utilities'));
    gutil.log(gutil.colors.green('gulp favicon'), '        standalone utility for favicon generation 🌐');
    gutil.log('');
    gutil.log(gutil.colors.black.bgCyan('Linting'));
    gutil.log(gutil.colors.green('gulp lint:js'), '        lint your project\'s js files 🎀');
    gutil.log(gutil.colors.green('gulp lint:sass'), '      lint your project\'s sass files 🎀');
    gutil.log('');
});
<|endoftext|>


<commit_before>/*
 * grunt-inky
 * https://github.com/Miw0/grunt-inky
 *                         ___
 *                      .-'   `'.
 *                     /         \
 *                     |         ;
 *                     |         |           ___.--,
 *            _.._     |0) ~ (0) |    _.---'`__.-( (_.
 *     __.--'`_.. '.__.\    '--. \_.-' ,.--'`     `""`
 *    ( ,.--'`   ',__ /./;   ;, '.__.'`    __
 *    _`) )  .---.__.' / |   |\   \__..--""  """--.,_
 *   `---' .'.''-._.-'`_./  /\ '.  \ _.-~~~````~~~-._`-.__.'
 *         | |  .' _.-' |  |  \  \  '.               `~---`
 *          \ \/ .'     \  \   '. '-._)
 *           \/ /        \  \    `=.__`~-.
 *           / /\         `) )    / / `"".`\
 *     , _.-'.'\ \        / /    ( (     / /
 *      `--~`   ) )    .-'.'      '.'.  | (
 *             (/`    ( (`          ) )  '-;
 *              `      '-;         (-'
 *
 * Copyright (c) 2016 Michael 'Miw0' Worm
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

    grunt.registerMultiTask('inky', 'A grunt plugin for ZURB Inky. https://github.com/zurb/inky', function () {

        var done = this.async(),
            path = require('path'),
            fs = require('fs'),
            chalk = require('chalk'),
            max = this.filesSrc.length,
            index = 0,
            isFinished = function () {
                index++;

                if (index === max) {
                    done();
                }
            },
            unixifyPath = function (filepath) {
                if (process.platform === 'win32') {
                    return filepath.replace(/\\/g, '/');
                } else {
                    return filepath;
                }
            },
            detectDestType = function (dest) {
                if (grunt.util._.endsWith(dest, '/')) {
                    return 'directory';
                } else {
                    return 'file';
                }
            },
            options = this.options({
                columnCount: 12,
                components: {
                    button: 'button',
                    row: 'row',
                    columns: 'columns',
                    container: 'container',
                    inky: 'inky',
                    blockGrid: 'block-grid',
                    menu: 'menu',
                    menuItem: 'item'
                }
            });

        // Iterate over all specified file groups.
        this.files.forEach(function (filePair) {
            var isExpandedPair = filePair.orig.expand || false,
                destination = unixifyPath(filePair.dest),
                fullHtml = '';

            filePair.src.forEach(function (file) {
                file = unixifyPath(file);

                if (detectDestType(destination) === 'directory') {
                    destination = isExpandedPair ? destination : path.join(destination, file);
                }

                // Load plugins
                var Inky = require('inky').Inky,
                    cheerio = require('cheerio');

                // Actual Inky processing
                var i = new Inky(options),
                    input = grunt.file.read(file),
                    html = cheerio.load(input),
                    convertedHtml = i.releaseTheKraken(html);

                fullHtml += convertedHtml;

                grunt.log.writeln('File ' + chalk.cyan(file) + ' has been released by the ' + chalk.magenta('kraken') + ' ...');
            });

            // Create folder if not exists
            grunt.file.mkdir(path.dirname(destination));

            // Write the destination file.
            fs.writeFile(destination, fullHtml, function () {
                grunt.log.writeln('Successfully wrote ' + chalk.green(destination) + '.');
                isFinished();
            });
        });
    });

};
<commit_msg>Enable pass thru of options to cheerio<commit_after>/*
 * grunt-inky
 * https://github.com/Miw0/grunt-inky
 *                         ___
 *                      .-'   `'.
 *                     /         \
 *                     |         ;
 *                     |         |           ___.--,
 *            _.._     |0) ~ (0) |    _.---'`__.-( (_.
 *     __.--'`_.. '.__.\    '--. \_.-' ,.--'`     `""`
 *    ( ,.--'`   ',__ /./;   ;, '.__.'`    __
 *    _`) )  .---.__.' / |   |\   \__..--""  """--.,_
 *   `---' .'.''-._.-'`_./  /\ '.  \ _.-~~~````~~~-._`-.__.'
 *         | |  .' _.-' |  |  \  \  '.               `~---`
 *          \ \/ .'     \  \   '. '-._)
 *           \/ /        \  \    `=.__`~-.
 *           / /\         `) )    / / `"".`\
 *     , _.-'.'\ \        / /    ( (     / /
 *      `--~`   ) )    .-'.'      '.'.  | (
 *             (/`    ( (`          ) )  '-;
 *              `      '-;         (-'
 *
 * Copyright (c) 2016 Michael 'Miw0' Worm
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

    grunt.registerMultiTask('inky', 'A grunt plugin for ZURB Inky. https://github.com/zurb/inky', function () {

        var done = this.async(),
            path = require('path'),
            fs = require('fs'),
            chalk = require('chalk'),
            max = this.filesSrc.length,
            index = 0,
            isFinished = function () {
                index++;

                if (index === max) {
                    done();
                }
            },
            unixifyPath = function (filepath) {
                if (process.platform === 'win32') {
                    return filepath.replace(/\\/g, '/');
                } else {
                    return filepath;
                }
            },
            detectDestType = function (dest) {
                if (grunt.util._.endsWith(dest, '/')) {
                    return 'directory';
                } else {
                    return 'file';
                }
            },
            options = this.options({
                columnCount: 12,
                components: {
                    button: 'button',
                    row: 'row',
                    columns: 'columns',
                    container: 'container',
                    inky: 'inky',
                    blockGrid: 'block-grid',
                    menu: 'menu',
                    menuItem: 'item'
                }
            });

        // Iterate over all specified file groups.
        this.files.forEach(function (filePair) {
            var isExpandedPair = filePair.orig.expand || false,
                destination = unixifyPath(filePair.dest),
                fullHtml = '';

            filePair.src.forEach(function (file) {
                file = unixifyPath(file);

                if (detectDestType(destination) === 'directory') {
                    destination = isExpandedPair ? destination : path.join(destination, file);
                }

                // Load plugins
                var Inky = require('inky').Inky,
                    cheerio = require('cheerio');

                // Actual Inky processing
                var i = new Inky(options),
                    input = grunt.file.read(file),
                    html = cheerio.load(input, options),
                    convertedHtml = i.releaseTheKraken(html);

                fullHtml += convertedHtml;

                grunt.log.writeln('File ' + chalk.cyan(file) + ' has been released by the ' + chalk.magenta('kraken') + ' ...');
            });

            // Create folder if not exists
            grunt.file.mkdir(path.dirname(destination));

            // Write the destination file.
            fs.writeFile(destination, fullHtml, function () {
                grunt.log.writeln('Successfully wrote ' + chalk.green(destination) + '.');
                isFinished();
            });
        });
    });

};
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// @flow
import * as React from 'react';
import { Provider } from 'react-redux';

import { render } from 'firefox-profiler/test/fixtures/testing-library';
import { getProfileFromTextSamples } from '../fixtures/profiles/processed-profile';
import { storeWithProfile } from '../fixtures/stores';
import { changeSelectedCallNode } from '../../actions/profile-view';
import { FlameGraph } from '../../components/flame-graph';
import { selectedThreadSelectors } from 'firefox-profiler/selectors';
import { ensureExists } from '../../utils/flow';
import { fireFullKeyPress } from '../fixtures/utils';
import { ProfileCallTreeView } from '../../components/calltree/ProfileCallTreeView';
import type {
  Transform,
  CallNodePath,
  IndexIntoFuncTable,
  IndexIntoResourceTable,
} from 'firefox-profiler/types';

type KeyPressOptions = { key: string, ... };

type TestSetup = {|
  getTransform: () => null | Transform,
  pressKey: (options: KeyPressOptions) => void,
  expectedCallNodePath: CallNodePath,
  // This should be expectedCallNodePath[expectedCallNodePath.length - 1], but this simplifies tests a bit.
  expectedFuncIndex: IndexIntoFuncTable,
  expectedResourceIndex: IndexIntoResourceTable,
|};

function testTransformKeyboardShortcuts(setup: () => TestSetup) {
  it('handles focus subtree', () => {
    const { pressKey, getTransform, expectedCallNodePath } = setup();
    pressKey({ key: 'F' });
    expect(getTransform()).toMatchObject({
      type: 'focus-subtree',
      callNodePath: expectedCallNodePath,
    });
  });

  it('handles focus-function', () => {
    const { pressKey, getTransform, expectedFuncIndex } = setup();
    pressKey({ key: 'f' });
    expect(getTransform()).toEqual({
      type: 'focus-function',
      funcIndex: expectedFuncIndex,
    });
  });

  it('handles merge call node', () => {
    const { pressKey, getTransform, expectedCallNodePath } = setup();
    pressKey({ key: 'M' });
    expect(getTransform()).toMatchObject({
      type: 'merge-call-node',
      callNodePath: expectedCallNodePath,
    });
  });

  it('handles merge function', () => {
    const { pressKey, getTransform, expectedFuncIndex } = setup();
    pressKey({ key: 'm' });
    const transform = getTransform();
    expect(transform).toEqual({
      type: 'merge-function',
      funcIndex: expectedFuncIndex,
    });
  });

  it('handles drop function', () => {
    const { pressKey, getTransform, expectedFuncIndex } = setup();
    pressKey({ key: 'd' });
    expect(getTransform()).toEqual({
      type: 'drop-function',
      funcIndex: expectedFuncIndex,
    });
  });

  it('handles collapse resource', () => {
    const { pressKey, getTransform, expectedResourceIndex } = setup();
    pressKey({ key: 'C' });
    expect(getTransform()).toMatchObject({
      type: 'collapse-resource',
      resourceIndex: expectedResourceIndex,
    });
  });

  it('handles collapse direct recursion', () => {
    const { pressKey, getTransform, expectedFuncIndex } = setup();
    pressKey({ key: 'r' });
    expect(getTransform()).toMatchObject({
      type: 'collapse-direct-recursion',
      funcIndex: expectedFuncIndex,
    });
  });

  it('handles collapse function subtree', () => {
    const { pressKey, getTransform, expectedFuncIndex } = setup();
    pressKey({ key: 'c' });
    expect(getTransform()).toEqual({
      type: 'collapse-function-subtree',
      funcIndex: expectedFuncIndex,
    });
  });

  it('ignores shortcuts with modifiers', () => {
    const { pressKey, getTransform } = setup();
    pressKey({ key: 'c', ctrlKey: true });
    pressKey({ key: 'c', metaKey: true });
    expect(getTransform()).toEqual(null);
  });
}

// This is a generic setup that's used in all of our testcases.
function setupStore(childrenToRender) {
  const {
    profile,
    funcNamesDictPerThread: [funcNames],
  } = getProfileFromTextSamples(`
    A               A               A
    B[lib:XUL]  B[lib:XUL]  B[lib:XUL]
    B[lib:XUL]  B[lib:XUL]  B[lib:XUL]
    B[lib:XUL]  B[lib:XUL]  B[lib:XUL]
    C               C               H
    D               F               I
    E               E
  `);
  const store = storeWithProfile(profile);
  const { getState } = store;

  render(<Provider store={store}>{childrenToRender}</Provider>);

  return {
    ...store,
    funcNames,
    getTransform: () => {
      const stack = selectedThreadSelectors.getTransformStack(getState());
      switch (stack.length) {
        case 0:
          return null;
        case 1:
          return stack[0];
        default:
          throw new Error('This test assumes there is only one transform.');
      }
    },
  };
}

// This returns a function that makes it easy to simulate a keypress on a
// specific element identified by a class name.
const pressKeyBuilder = className => (options: KeyPressOptions) => {
  const div = ensureExists(
    document.querySelector('.' + className),
    `Couldn't find the content div with selector .${className}`
  );
  fireFullKeyPress(div, options);
};

describe('flame graph transform shortcuts', () => {
  testTransformKeyboardShortcuts(() => {
    const {
      dispatch,
      funcNames: { A, B },
      getTransform,
    } = setupStore(<FlameGraph />);

    dispatch(changeSelectedCallNode(0, [A, B]));

    return {
      getTransform,
      // take either a key as a string, or a full event if we need more
      // information like modifier keys.
      pressKey: pressKeyBuilder('flameGraphContent'),
      expectedCallNodePath: [A, B],
      expectedFuncIndex: B,
      expectedResourceIndex: 0,
    };
  });
});

describe('CallTree transform shortcuts', () => {
  testTransformKeyboardShortcuts(() => {
    const {
      dispatch,
      funcNames: { A, B },
      getTransform,
    } = setupStore(<ProfileCallTreeView />);

    dispatch(changeSelectedCallNode(0, [A, B]));

    return {
      getTransform,
      // take either a key as a string, or a full event if we need more
      // information like modifier keys.
      pressKey: pressKeyBuilder('treeViewBody'),
      expectedCallNodePath: [A, B],
      expectedFuncIndex: B,
      expectedResourceIndex: 0,
    };
  });
});
<commit_msg>Add a test for the stack chart<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// @flow
import * as React from 'react';
import { Provider } from 'react-redux';

import { render } from 'firefox-profiler/test/fixtures/testing-library';
import { getProfileFromTextSamples } from '../fixtures/profiles/processed-profile';
import { storeWithProfile } from '../fixtures/stores';
import { changeSelectedCallNode } from '../../actions/profile-view';
import { FlameGraph } from '../../components/flame-graph';
import { selectedThreadSelectors } from 'firefox-profiler/selectors';
import { ensureExists } from '../../utils/flow';
import { fireFullKeyPress } from '../fixtures/utils';
import { ProfileCallTreeView } from '../../components/calltree/ProfileCallTreeView';
import { StackChart } from 'firefox-profiler/components/stack-chart';
import type {
  Transform,
  CallNodePath,
  IndexIntoFuncTable,
  IndexIntoResourceTable,
} from 'firefox-profiler/types';

type KeyPressOptions = { key: string, ... };

type TestSetup = {|
  getTransform: () => null | Transform,
  pressKey: (options: KeyPressOptions) => void,
  expectedCallNodePath: CallNodePath,
  // This should be expectedCallNodePath[expectedCallNodePath.length - 1], but this simplifies tests a bit.
  expectedFuncIndex: IndexIntoFuncTable,
  expectedResourceIndex: IndexIntoResourceTable,
|};

function testTransformKeyboardShortcuts(setup: () => TestSetup) {
  it('handles focus subtree', () => {
    const { pressKey, getTransform, expectedCallNodePath } = setup();
    pressKey({ key: 'F' });
    expect(getTransform()).toMatchObject({
      type: 'focus-subtree',
      callNodePath: expectedCallNodePath,
    });
  });

  it('handles focus-function', () => {
    const { pressKey, getTransform, expectedFuncIndex } = setup();
    pressKey({ key: 'f' });
    expect(getTransform()).toEqual({
      type: 'focus-function',
      funcIndex: expectedFuncIndex,
    });
  });

  it('handles merge call node', () => {
    const { pressKey, getTransform, expectedCallNodePath } = setup();
    pressKey({ key: 'M' });
    expect(getTransform()).toMatchObject({
      type: 'merge-call-node',
      callNodePath: expectedCallNodePath,
    });
  });

  it('handles merge function', () => {
    const { pressKey, getTransform, expectedFuncIndex } = setup();
    pressKey({ key: 'm' });
    const transform = getTransform();
    expect(transform).toEqual({
      type: 'merge-function',
      funcIndex: expectedFuncIndex,
    });
  });

  it('handles drop function', () => {
    const { pressKey, getTransform, expectedFuncIndex } = setup();
    pressKey({ key: 'd' });
    expect(getTransform()).toEqual({
      type: 'drop-function',
      funcIndex: expectedFuncIndex,
    });
  });

  it('handles collapse resource', () => {
    const { pressKey, getTransform, expectedResourceIndex } = setup();
    pressKey({ key: 'C' });
    expect(getTransform()).toMatchObject({
      type: 'collapse-resource',
      resourceIndex: expectedResourceIndex,
    });
  });

  it('handles collapse direct recursion', () => {
    const { pressKey, getTransform, expectedFuncIndex } = setup();
    pressKey({ key: 'r' });
    expect(getTransform()).toMatchObject({
      type: 'collapse-direct-recursion',
      funcIndex: expectedFuncIndex,
    });
  });

  it('handles collapse function subtree', () => {
    const { pressKey, getTransform, expectedFuncIndex } = setup();
    pressKey({ key: 'c' });
    expect(getTransform()).toEqual({
      type: 'collapse-function-subtree',
      funcIndex: expectedFuncIndex,
    });
  });

  it('ignores shortcuts with modifiers', () => {
    const { pressKey, getTransform } = setup();
    pressKey({ key: 'c', ctrlKey: true });
    pressKey({ key: 'c', metaKey: true });
    expect(getTransform()).toEqual(null);
  });
}

// This is a generic setup that's used in all of our testcases.
function setupStore(childrenToRender) {
  const {
    profile,
    funcNamesDictPerThread: [funcNames],
  } = getProfileFromTextSamples(`
    A               A               A
    B[lib:XUL]  B[lib:XUL]  B[lib:XUL]
    B[lib:XUL]  B[lib:XUL]  B[lib:XUL]
    B[lib:XUL]  B[lib:XUL]  B[lib:XUL]
    C               C               H
    D               F               I
    E               E
  `);
  const store = storeWithProfile(profile);
  const { getState } = store;

  render(<Provider store={store}>{childrenToRender}</Provider>);

  return {
    ...store,
    funcNames,
    getTransform: () => {
      const stack = selectedThreadSelectors.getTransformStack(getState());
      switch (stack.length) {
        case 0:
          return null;
        case 1:
          return stack[0];
        default:
          throw new Error('This test assumes there is only one transform.');
      }
    },
  };
}

// This returns a function that makes it easy to simulate a keypress on a
// specific element identified by a class name.
const pressKeyBuilder = className => (options: KeyPressOptions) => {
  const div = ensureExists(
    document.querySelector('.' + className),
    `Couldn't find the content div with selector .${className}`
  );
  fireFullKeyPress(div, options);
};

describe('flame graph transform shortcuts', () => {
  testTransformKeyboardShortcuts(() => {
    const {
      dispatch,
      funcNames: { A, B },
      getTransform,
    } = setupStore(<FlameGraph />);

    dispatch(changeSelectedCallNode(0, [A, B]));

    return {
      getTransform,
      // take either a key as a string, or a full event if we need more
      // information like modifier keys.
      pressKey: pressKeyBuilder('flameGraphContent'),
      expectedCallNodePath: [A, B],
      expectedFuncIndex: B,
      expectedResourceIndex: 0,
    };
  });
});

describe('CallTree transform shortcuts', () => {
  testTransformKeyboardShortcuts(() => {
    const {
      dispatch,
      funcNames: { A, B },
      getTransform,
    } = setupStore(<ProfileCallTreeView />);

    dispatch(changeSelectedCallNode(0, [A, B]));

    return {
      getTransform,
      // take either a key as a string, or a full event if we need more
      // information like modifier keys.
      pressKey: pressKeyBuilder('treeViewBody'),
      expectedCallNodePath: [A, B],
      expectedFuncIndex: B,
      expectedResourceIndex: 0,
    };
  });
});

describe('stack chart transform shortcuts', () => {
  testTransformKeyboardShortcuts(() => {
    const {
      dispatch,
      funcNames: { A, B },
      getTransform,
    } = setupStore(<StackChart />);

    dispatch(changeSelectedCallNode(0, [A, B]));

    return {
      getTransform,
      // take either a key as a string, or a full event if we need more
      // information like modifier keys.
      pressKey: pressKeyBuilder('stackChartContent'),
      expectedCallNodePath: [A, B],
      expectedFuncIndex: B,
      expectedResourceIndex: 0,
    };
  });
});
<|endoftext|>


<commit_before>/*
 * grunt-contrib-jade
 * http://gruntjs.com/
 *
 * Copyright (c) 2015 Eric Woroshow, contributors
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {
  var lib = require('./lib/jade');
  var chalk = require('chalk');

  // content conversion for templates
  var defaultProcessContent = function(content) { return content; };

  // filename conversion for templates
  var defaultProcessName = function(name) { return name.replace('.jade', ''); };

  grunt.registerMultiTask('jade', 'Compile jade templates.', function() {
    var options = this.options({
      namespace: 'JST',
      separator: grunt.util.linefeed + grunt.util.linefeed,
      amd: false
    });

    var data = options.data;
    delete options.data;

    var nsInfo;

    if (options.namespace !== false) {
      nsInfo = lib.getNamespaceDeclaration(options.namespace);
    }

    // assign transformation functions
    var processContent = options.processContent || defaultProcessContent;
    var processName = options.processName || defaultProcessName;

    this.files.forEach(function(f) {
      var templates = [];

      f.src.filter(function(filepath) {
        // warn on and remove invalid source files (if nonull was set)
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      })
      .forEach(function(filepath) {
        var src = processContent(grunt.file.read(filepath), filepath);
        var compiled, filename;
        filename = processName(filepath);

        options.filename = filepath;

        try {
          var jade = f.orig.jade = require('jade');
          if (typeof data === 'function') {
            // if data is function, bind to f.orig, passing f.dest and f.src
            f.orig.data = data.call(f.orig, f.dest, f.src);
          } else {
            f.orig.data = data;
          }
          if (options.filters) {
            Object.keys(options.filters).forEach(function(filter) {
              jade.filters[filter] = options.filters[filter].bind(f.orig);
            });
          }
          // if in client mode, return function source
          if (options.client) {
            compiled = jade.compileClient(src, options).toString();
          } else {
            compiled = jade.compile(src, options)(f.orig.data);
          }

          // if configured for AMD and the namespace has been explicitly set
          // to false, the Jade template will be directly returned
          if (options.client && options.amd && options.namespace === false) {
            compiled = 'return ' + compiled;
          }
        } catch (e) {
          grunt.log.error(e);
          grunt.fail.warn('Jade failed to compile "' + filepath + '".');
          return false;
        }

        if (options.client && options.namespace !== false) {
          templates.push(nsInfo.namespace + '[' + JSON.stringify(filename) + '] = ' + compiled + ';');
        } else {
          templates.push(compiled);
        }
      });

      var output = templates;
      if (output.length < 1) {
        grunt.log.warn('Destination not written because compiled files were empty.');
      } else {
        if (options.client && options.namespace !== false) {
          output.unshift(nsInfo.declaration);

          if (options.node) {
            output.unshift('var jade = jade || require(\'jade\').runtime;');

            var nodeExport = 'if (typeof exports === \'object\' && exports) {';
            nodeExport += 'module.exports = ' + nsInfo.namespace + ';}';

            output.push(nodeExport);
          }
        }

        if (options.amd) {
          // wrap the file in an AMD define function
          output.unshift('define([\'jade\'], function(jade) { if(jade && jade[\'runtime\'] !== undefined) { jade = jade.runtime; }');
          if (options.namespace !== false) {
            // namespace has not been explicitly set to false;
            // the AMD wrapper will return the object containing the template
            output.push('return ' + nsInfo.namespace + ';');
          }
          output.push('});');
        }

        grunt.file.write(f.dest, output.join(grunt.util.normalizelf(options.separator)));
        grunt.verbose.writeln('File ' + chalk.cyan(f.dest) + ' created.');
      }
    });

    grunt.log.ok(this.files.length + ' ' + grunt.util.pluralize(this.files.length, 'file/files') + ' created.');

  });

};
<commit_msg>Require jade runtime in a recommended way<commit_after>/*
 * grunt-contrib-jade
 * http://gruntjs.com/
 *
 * Copyright (c) 2015 Eric Woroshow, contributors
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {
  var lib = require('./lib/jade');
  var chalk = require('chalk');

  // content conversion for templates
  var defaultProcessContent = function(content) { return content; };

  // filename conversion for templates
  var defaultProcessName = function(name) { return name.replace('.jade', ''); };

  grunt.registerMultiTask('jade', 'Compile jade templates.', function() {
    var options = this.options({
      namespace: 'JST',
      separator: grunt.util.linefeed + grunt.util.linefeed,
      amd: false
    });

    var data = options.data;
    delete options.data;

    var nsInfo;

    if (options.namespace !== false) {
      nsInfo = lib.getNamespaceDeclaration(options.namespace);
    }

    // assign transformation functions
    var processContent = options.processContent || defaultProcessContent;
    var processName = options.processName || defaultProcessName;

    this.files.forEach(function(f) {
      var templates = [];

      f.src.filter(function(filepath) {
        // warn on and remove invalid source files (if nonull was set)
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      })
      .forEach(function(filepath) {
        var src = processContent(grunt.file.read(filepath), filepath);
        var compiled, filename;
        filename = processName(filepath);

        options.filename = filepath;

        try {
          var jade = f.orig.jade = require('jade');
          if (typeof data === 'function') {
            // if data is function, bind to f.orig, passing f.dest and f.src
            f.orig.data = data.call(f.orig, f.dest, f.src);
          } else {
            f.orig.data = data;
          }
          if (options.filters) {
            Object.keys(options.filters).forEach(function(filter) {
              jade.filters[filter] = options.filters[filter].bind(f.orig);
            });
          }
          // if in client mode, return function source
          if (options.client) {
            compiled = jade.compileClient(src, options).toString();
          } else {
            compiled = jade.compile(src, options)(f.orig.data);
          }

          // if configured for AMD and the namespace has been explicitly set
          // to false, the Jade template will be directly returned
          if (options.client && options.amd && options.namespace === false) {
            compiled = 'return ' + compiled;
          }
        } catch (e) {
          grunt.log.error(e);
          grunt.fail.warn('Jade failed to compile "' + filepath + '".');
          return false;
        }

        if (options.client && options.namespace !== false) {
          templates.push(nsInfo.namespace + '[' + JSON.stringify(filename) + '] = ' + compiled + ';');
        } else {
          templates.push(compiled);
        }
      });

      var output = templates;
      if (output.length < 1) {
        grunt.log.warn('Destination not written because compiled files were empty.');
      } else {
        if (options.client && options.namespace !== false) {
          output.unshift(nsInfo.declaration);

          if (options.node) {
            output.unshift('var jade = jade || require(\'jade/lib/runtime\');');

            var nodeExport = 'if (typeof exports === \'object\' && exports) {';
            nodeExport += 'module.exports = ' + nsInfo.namespace + ';}';

            output.push(nodeExport);
          }
        }

        if (options.amd) {
          // wrap the file in an AMD define function
          output.unshift('define([\'jade\'], function(jade) { if(jade && jade[\'runtime\'] !== undefined) { jade = jade.runtime; }');
          if (options.namespace !== false) {
            // namespace has not been explicitly set to false;
            // the AMD wrapper will return the object containing the template
            output.push('return ' + nsInfo.namespace + ';');
          }
          output.push('});');
        }

        grunt.file.write(f.dest, output.join(grunt.util.normalizelf(options.separator)));
        grunt.verbose.writeln('File ' + chalk.cyan(f.dest) + ' created.');
      }
    });

    grunt.log.ok(this.files.length + ' ' + grunt.util.pluralize(this.files.length, 'file/files') + ' created.');

  });

};
<|endoftext|>


<commit_before>'use strict';

var git = require('git-rev');

module.exports = function(grunt) {
    var classPathSep = (process.platform === "win32") ? ';' : ':',
        gitHash = '',
        pkg = grunt.file.readJSON('package.json');

    grunt.initConfig({
        watch: {
            options: {
                livereload: 35729
            },
            js: {
                files: ['public/**/*.js', '!public/lib/**', '!public/dist/**'],
                tasks: ['shell','copy:mainjs']
            },
            html: {
                files: ['public/**/*.html'],
                tasks: ['copy:dist']
            },
            css: {
                files: ['public/**/*.css'],
                tasks: ['copy:dist']
            },
            image: {
                files: ['public/**/*.{ico,gif,png}'],
                tasks: ['copy:dist']
            }
        },
        jshint: {
            all: {
                src: ['gruntfile.js', 'package.json', 'server.js', 'server/**/*.js', 'public/**/*.js', '!public/lib/**', '!public/dist/**'],
                options: {
                    jshintrc: true
                }
            }
        },
        concurrent: {
            tasks: ['watch','proxitserver'],
            options: {
                logConcurrentOutput: true
            }
        },
        jsbeautifier: {
            'default': {
                src: ['<%= jshint.all.src %>', 'bower.json'],
                options: {
                    js: {
                        preserveNewlines: true,
                        maxPreserveNewlines: 2
                    }
                }
            },
            'build': {
                src: '<%= jsbeautifier.default.src %>',
                options: {
                    mode: 'VERIFY_ONLY',
                    js: '<%= jsbeautifier.default.options.js%>'
                }
            }
        },
        bower: {
            install: {
                options: {
                    verbose: true
                }
            }
        },
        dist: 'public/js/app.min.js',
        modules: grunt.file.expand(
            'public/js/app.js',
            'public/js/routes.js',
            'public/modules/**/*Module.js',
            'public/modules/**/*.js',
            'public/js/init.js'
        ).join(' '),
        shell: {
            min: {
                command: 'java ' +
                    '-cp dist/lib/closure-compiler/compiler.jar' + classPathSep +
                    'dist/lib/ng-closure-runner/ngcompiler.jar ' +
                    'org.angularjs.closurerunner.NgClosureRunner ' +
                    '--compilation_level SIMPLE_OPTIMIZATIONS ' +
                    //'--formatting PRETTY_PRINT ' +
                    '--language_in ECMASCRIPT5_STRICT ' +
                    '--angular_pass ' +
                    '--manage_closure_dependencies ' +
                    '--js <%= modules %> ' +
                    '--js_output_file <%= dist %>'
            }
        },
        devUpdate: {
            main: {
                options: {
                    updateType: 'force'
                }
            }
        },
        compress: {
            release: {
                options: {
                    archive: function() {
                        return [pkg.name, pkg.version, gitHash].join('_') + '.tgz';
                    }
                },
                src: ['node_modules/**', 'package.json', 'server.js', 'server/**', 'public/**', '!public/js/**', '!public/modules/**/*.js']
            }
        },
        copy: {
        	dist: {
        		expand: true,
        	    cwd: 'public/',
        	    src: '**',
        	    dest: 'dist',
        	 },
        	 mainjs:{
        		expand: true,
    		    cwd: 'public/',
    		    src: 'js/*.js',
    		    dest: 'dist/js/',
    		    flatten: true,
    		    filter: 'isFile'
        	 }
        },
        clean: ['dist'],
        proxit: {
            dev: {
                options: {
                	"port": 9000,
                    "verbose": true,
                    "hosts": [{
                        "hostnames": ["*"],
                        "routes": {
                            "/": "dist",
                            "/api":"http://162.249.6.39:21000/api"
                        }
                    }
                   ]
                }
            }
        }
    });

    require('load-grunt-tasks')(grunt);
    grunt.registerTask('default', ['devUpdate', 'bower', 'jshint', 'jsbeautifier:default']);

    grunt.registerTask('server', ['jshint','build','bower','minify','copy:mainjs','concurrent']);

    grunt.registerTask('minify', 'Minify the all js', function() {
        var done = this.async();
        grunt.file.mkdir('public/dist');
        grunt.task.run(['shell:min']);
        done();
    });
    grunt.loadNpmTasks('proxit');
    grunt.registerTask('proxitserver', 'Proxit', function() {
    	var done = this.async();
        grunt.task.run(['proxit:dev']);
        done();
    });
    grunt.registerTask('build','Build DGI',function(){
    	grunt.task.run(['clean']);
    	 grunt.task.run(['copy:dist']);
    });
    grunt.registerTask('release', 'Create release package', function() {
        var done = this.async();
        git.short(function(str) {
            gitHash = str;
            grunt.task.run(['minify', 'compress:release']);
            done();
        });
    });
};
<commit_msg>Updated proxit port number to 3010<commit_after>'use strict';

var git = require('git-rev');

module.exports = function(grunt) {
    var classPathSep = (process.platform === "win32") ? ';' : ':',
        gitHash = '',
        pkg = grunt.file.readJSON('package.json');

    grunt.initConfig({
        watch: {
            options: {
                livereload: 35729
            },
            js: {
                files: ['public/**/*.js', '!public/lib/**', '!public/dist/**'],
                tasks: ['shell','copy:mainjs']
            },
            html: {
                files: ['public/**/*.html'],
                tasks: ['copy:dist']
            },
            css: {
                files: ['public/**/*.css'],
                tasks: ['copy:dist']
            },
            image: {
                files: ['public/**/*.{ico,gif,png}'],
                tasks: ['copy:dist']
            }
        },
        jshint: {
            all: {
                src: ['gruntfile.js', 'package.json', 'server.js', 'server/**/*.js', 'public/**/*.js', '!public/lib/**', '!public/dist/**'],
                options: {
                    jshintrc: true
                }
            }
        },
        concurrent: {
            tasks: ['watch','proxitserver'],
            options: {
                logConcurrentOutput: true
            }
        },
        jsbeautifier: {
            'default': {
                src: ['<%= jshint.all.src %>', 'bower.json'],
                options: {
                    js: {
                        preserveNewlines: true,
                        maxPreserveNewlines: 2
                    }
                }
            },
            'build': {
                src: '<%= jsbeautifier.default.src %>',
                options: {
                    mode: 'VERIFY_ONLY',
                    js: '<%= jsbeautifier.default.options.js%>'
                }
            }
        },
        bower: {
            install: {
                options: {
                    verbose: true
                }
            }
        },
        dist: 'public/js/app.min.js',
        modules: grunt.file.expand(
            'public/js/app.js',
            'public/js/routes.js',
            'public/modules/**/*Module.js',
            'public/modules/**/*.js',
            'public/js/init.js'
        ).join(' '),
        shell: {
            min: {
                command: 'java ' +
                    '-cp dist/lib/closure-compiler/compiler.jar' + classPathSep +
                    'dist/lib/ng-closure-runner/ngcompiler.jar ' +
                    'org.angularjs.closurerunner.NgClosureRunner ' +
                    '--compilation_level SIMPLE_OPTIMIZATIONS ' +
                    //'--formatting PRETTY_PRINT ' +
                    '--language_in ECMASCRIPT5_STRICT ' +
                    '--angular_pass ' +
                    '--manage_closure_dependencies ' +
                    '--js <%= modules %> ' +
                    '--js_output_file <%= dist %>'
            }
        },
        devUpdate: {
            main: {
                options: {
                    updateType: 'force'
                }
            }
        },
        compress: {
            release: {
                options: {
                    archive: function() {
                        return [pkg.name, pkg.version, gitHash].join('_') + '.tgz';
                    }
                },
                src: ['node_modules/**', 'package.json', 'server.js', 'server/**', 'public/**', '!public/js/**', '!public/modules/**/*.js']
            }
        },
        copy: {
        	dist: {
        		expand: true,
        	    cwd: 'public/',
        	    src: '**',
        	    dest: 'dist',
        	 },
        	 mainjs:{
        		expand: true,
    		    cwd: 'public/',
    		    src: 'js/*.js',
    		    dest: 'dist/js',
        	 }
        },
        clean: ['dist'],
        proxit: {
            dev: {
                options: {
                	'port': 3010,
                    'verbose': true,
                    'hosts': [{
                        'hostnames': ['*'],
                        'routes': {
                            '/': 'dist',
                            '/api':'http://162.249.6.39:21000/api'
                        }
                    }
                   ]
                }
            }
        }
    });

    require('load-grunt-tasks')(grunt);
    grunt.registerTask('default', ['devUpdate', 'bower', 'jshint', 'jsbeautifier:default']);

    grunt.registerTask('server', ['jshint','build','bower','minify','copy:mainjs','concurrent']);

    grunt.registerTask('minify', 'Minify the all js', function() {
        var done = this.async();
        grunt.file.mkdir('public/dist');
        grunt.task.run(['shell:min']);
        done();
    });
    grunt.loadNpmTasks('proxit');
    grunt.registerTask('proxitserver', 'Proxit', function() {
    	var done = this.async();
        grunt.task.run(['proxit:dev']);
        done();
    });
    grunt.registerTask('build','Build DGI',function(){
    	grunt.task.run(['clean']);
    	 grunt.task.run(['copy:dist']);
    });
    grunt.registerTask('release', 'Create release package', function() {
        var done = this.async();
        git.short(function(str) {
            gitHash = str;
            grunt.task.run(['minify', 'compress:release']);
            done();
        });
    });
};
<|endoftext|>


<commit_before>/*
 * grunt-json
 * https://github.com/wilsonpage/grunt-json
 *
 * Copyright (c) 2012 Wilson Page
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  var path = require('path');

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/gruntjs/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask('json', 'Concatenating JSON into JS', function() {
    var files = grunt.file.expandFiles(this.file.src);
    console.log(this);
    var json = grunt.helper('concat-json', files, this.data);
    grunt.file.write(this.file.dest, json);
    grunt.log.write('File "' + this.file.dest + '" created.');
  });

  // ==========================================================================
  // HELPERS
  // ==========================================================================

  grunt.registerHelper('concat-json', function(files, options) {
    var namespace = options && options.namespace || 'myjson';
    var basename;

    return 'var ' + namespace + '={};' + files.map(function(filepath) {
      basename = path.basename(filepath, '.json');
      return '\n' + options.namespace + '["' + basename + '"] = ' + grunt.task.directive(filepath, grunt.file.read) + ';';
    }).join('');
  });
};
<commit_msg>-Remove console.log<commit_after>/*
 * grunt-json
 * https://github.com/wilsonpage/grunt-json
 *
 * Copyright (c) 2012 Wilson Page
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  var path = require('path');

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/gruntjs/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask('json', 'Concatenating JSON into JS', function() {
    var files = grunt.file.expandFiles(this.file.src);
    var json = grunt.helper('concat-json', files, this.data);
    grunt.file.write(this.file.dest, json);
    grunt.log.write('File "' + this.file.dest + '" created.');
  });

  // ==========================================================================
  // HELPERS
  // ==========================================================================

  grunt.registerHelper('concat-json', function(files, options) {
    var namespace = options && options.namespace || 'myjson';
    var basename;

    return 'var ' + namespace + '={};' + files.map(function(filepath) {
      basename = path.basename(filepath, '.json');
      return '\n' + options.namespace + '["' + basename + '"] = ' + grunt.task.directive(filepath, grunt.file.read) + ';';
    }).join('');
  });
};
<|endoftext|>


<commit_before>'use strict';

//////////////////////////////
// Requires
//////////////////////////////
var gutil = require('gulp-util'),
    sass = require('gulp-sass'),
    rename = require('gulp-rename'),
    fs = require('fs-extra'),
    ifElse = require('gulp-if-else'),
    importOnce = require('node-sass-import-once'),
    inline_base64 = require('gulp-css-base64'),
    autoprefixer = require('gulp-autoprefixer'),
    dest = require('../helpers/relative-dest');

//////////////////////////////
// Internal Vars
//////////////////////////////
var toWatch = [
  'patterns/**/*.scss',
  'patterns/**/*.sass',
  'library/sass/**/*.scss',
  'library/sass/**/*.sass'
];

var toSass = process.cwd() + '/library/sass/style.scss';

var sassSettings = {
  'outputStyle': 'compressed',
  'importer': importOnce,
  'importOnce': {
    'index': true,
    'css': false,
    'bower': true
  }
};

//////////////////////////////
// Export
//////////////////////////////
module.exports = function (gulp, sassPaths) {
  //////////////////////////////
  // TERRIBLE HORRIBLE HACK BECAUSE THINGS ARE TERRIBLE AND HORRIBLE WITH LIBSASS RIGHT NOW
  //////////////////////////////
  gulp.task('sass:fix-libsass', function (cb) {
    var files = [
      'bower_components/modular-scale/stylesheets/modular-scale/_sort-list.scss'
    ];

    files.forEach(function (path) {
      var file = fs.readFileSync(path, 'utf-8');
      file = file.replace(/\@elseif/g, '@else if');
      fs.writeFileSync(path, file);
    });

    cb();
  });

  //////////////////////////////
  // Encapsulate task in function to choose path to work on
  //////////////////////////////
  var sassTask = function (path) {
    return gulp.src(path)
      .pipe(sass(sassSettings).on('error', sass.logError))
      .pipe(rename(function (path) {
        path.dirname = '..';
      }))
      .pipe(dest('./www/css/'));
  };

  //////////////////////////////
  // Core Task
  //////////////////////////////
  gulp.task('sass', function () {
    return gulp.src(toSass)
      .pipe(sass(sassSettings))
      .pipe(rename(function (path) {
        path.dirname = '..';
      }))
      .pipe(inline_base64({
        'baseDir': './www',
        'maxWeightResource': 13 * 1024,
        'extensionsAllowed': [
          '.svg',
          '.woff'
        ]
      }))
      .pipe(autoprefixer({
        cascade: false
      }))
      .pipe(dest('./www/css/'));
  });

  //////////////////////////////
  // Server Initialization Task
  //////////////////////////////
  gulp.task('sass:server', function () {
    return sassTask(toSass);
  });

  //////////////////////////////
  // Watch Task
  //////////////////////////////
  gulp.task('sass:watch', function () {
    return gulp.watch(toWatch)
      .on('change', function (event) {
        // Add absolute and relative (to Gulpfile) paths
        event.path = {
          absolute: event.path,
          relative: event.path.replace(__dirname.replace('/tasks', '') + '/', '')
        }

        // Notify user of the change
        gutil.log('File ' + gutil.colors.magenta(event.path.relative) + ' was ' + event.type);

        // Call the task
        return sassTask(toSass);
      });
  });
}
<commit_msg>Prefix on Sass watch<commit_after>'use strict';

//////////////////////////////
// Requires
//////////////////////////////
var gutil = require('gulp-util'),
    sass = require('gulp-sass'),
    rename = require('gulp-rename'),
    fs = require('fs-extra'),
    ifElse = require('gulp-if-else'),
    importOnce = require('node-sass-import-once'),
    inline_base64 = require('gulp-css-base64'),
    autoprefixer = require('gulp-autoprefixer'),
    dest = require('../helpers/relative-dest');

//////////////////////////////
// Internal Vars
//////////////////////////////
var toWatch = [
  'patterns/**/*.scss',
  'patterns/**/*.sass',
  'library/sass/**/*.scss',
  'library/sass/**/*.sass'
];

var toSass = process.cwd() + '/library/sass/style.scss';

var sassSettings = {
  'outputStyle': 'compressed',
  'importer': importOnce,
  'importOnce': {
    'index': true,
    'css': false,
    'bower': true
  }
};

//////////////////////////////
// Export
//////////////////////////////
module.exports = function (gulp, sassPaths) {
  //////////////////////////////
  // TERRIBLE HORRIBLE HACK BECAUSE THINGS ARE TERRIBLE AND HORRIBLE WITH LIBSASS RIGHT NOW
  //////////////////////////////
  gulp.task('sass:fix-libsass', function (cb) {
    var files = [
      'bower_components/modular-scale/stylesheets/modular-scale/_sort-list.scss'
    ];

    files.forEach(function (path) {
      var file = fs.readFileSync(path, 'utf-8');
      file = file.replace(/\@elseif/g, '@else if');
      fs.writeFileSync(path, file);
    });

    cb();
  });

  //////////////////////////////
  // Encapsulate task in function to choose path to work on
  //////////////////////////////
  var sassTask = function (path) {
    return gulp.src(path)
      .pipe(sass(sassSettings).on('error', sass.logError))
      .pipe(rename(function (path) {
        path.dirname = '..';
      }))
      .pipe(autoprefixer({
        cascade: false
      }))
      .pipe(dest('./www/css/'));
  };

  //////////////////////////////
  // Core Task
  //////////////////////////////
  gulp.task('sass', function () {
    return gulp.src(toSass)
      .pipe(sass(sassSettings))
      .pipe(rename(function (path) {
        path.dirname = '..';
      }))
      .pipe(inline_base64({
        'baseDir': './www',
        'maxWeightResource': 13 * 1024,
        'extensionsAllowed': [
          '.svg',
          '.woff'
        ]
      }))
      .pipe(autoprefixer({
        cascade: false
      }))
      .pipe(dest('./www/css/'));
  });

  //////////////////////////////
  // Server Initialization Task
  //////////////////////////////
  gulp.task('sass:server', function () {
    return sassTask(toSass);
  });

  //////////////////////////////
  // Watch Task
  //////////////////////////////
  gulp.task('sass:watch', function () {
    return gulp.watch(toWatch)
      .on('change', function (event) {
        // Add absolute and relative (to Gulpfile) paths
        event.path = {
          absolute: event.path,
          relative: event.path.replace(__dirname.replace('/tasks', '') + '/', '')
        }

        // Notify user of the change
        gutil.log('File ' + gutil.colors.magenta(event.path.relative) + ' was ' + event.type);

        // Call the task
        return sassTask(toSass);
      });
  });
}
<|endoftext|>


<commit_before>/* global expect */

define([
	'models/MapFilterModel'
], function (MapFilterModel) {

	describe("MapFilterModel", function () {
		it("resets to the defaults", function () {
			var model = new MapFilterModel();
			var defaults = model.defaults();
			model.reset();
			var test = model.attributes;

			expect(test.state).toBe(defaults.state);
			expect(test.waterBody).toBe(defaults.waterBody);
			expect(test.waterShed).toBe(defaults.waterShed);
			expect(test.dataSeries).toBe(defaults.dataSeries);
			expect(test.groupResultsBy).toBe(defaults.groupResultsBy);
			expect(test.waterSheds.length).toBe(defaults.waterSheds.length);
		});
	});

});<commit_msg>Updated spec a bit for better testing<commit_after>/* global expect */

define([
	'models/MapFilterModel'
], function (MapFilterModel) {

	describe("MapFilterModel", function () {
		it("resets to the defaults", function () {
			var model = new MapFilterModel();
			var defaults = model.defaults();

			model.set('state', ['AK']);
			model.set('waterBody', '...');
			model.set('waterShed', '...');
			model.set('dataSeries', '...');
			model.set('groupResultsBy', '...');
			model.set('waterSheds', [1]);

			var test = model.attributes;
			expect(test.state).not.toBe(defaults.state);
			expect(test.waterBody).not.toBe(defaults.waterBody);
			expect(test.waterShed).not.toBe(defaults.waterShed);
			expect(test.dataSeries).not.toBe(defaults.dataSeries);
			expect(test.groupResultsBy).not.toBe(defaults.groupResultsBy);
			expect(test.waterSheds.length).not.toBe(defaults.waterSheds.length);

			model.reset();
			test = model.attributes;

			expect(test.state).toBe(defaults.state);
			expect(test.waterBody).toBe(defaults.waterBody);
			expect(test.waterShed).toBe(defaults.waterShed);
			expect(test.dataSeries).toBe(defaults.dataSeries);
			expect(test.groupResultsBy).toBe(defaults.groupResultsBy);
			expect(test.waterSheds.length).toBe(defaults.waterSheds.length);
		});
	});

});<|endoftext|>


<commit_before>'use strict'

function validateTopic (topic, message) {
  const end = topic.length - 1
  const endMinus = end - 1
  const slashInPreEnd = endMinus > 0 && topic.charCodeAt(endMinus) !== 47
  if (topic.length === 0) {
    return new Error('impossible to ' + message + ' to an empty topic')
  }
  for (var i = 0; i < topic.length; i++) {
    switch (topic.charCodeAt(i)) {
      case 35: // #
        var notAtTheEnd = i !== end
        if (notAtTheEnd || slashInPreEnd) {
          return new Error('# is only allowed in ' + message + ' in the last position')
        }
        break
      case 43: // +
        var pastChar = i < end - 1 && topic.charCodeAt(i + 1) !== 47
        var preChar = i > 1 && topic.charCodeAt(i - 1) !== 47
        if (pastChar || preChar) {
          return new Error('+ is only allowed in ' + message + ' between /')
        }
        break
    }
  }
}

module.exports = validateTopic
<commit_msg>Add MQTT spec reference in empty topic validation (#439)<commit_after>'use strict'

function validateTopic (topic, message) {
  const end = topic.length - 1
  const endMinus = end - 1
  const slashInPreEnd = endMinus > 0 && topic.charCodeAt(endMinus) !== 47
  if (topic.length === 0) { // [MQTT-3.8.3-3]
    return new Error('impossible to ' + message + ' to an empty topic')
  }
  for (var i = 0; i < topic.length; i++) {
    switch (topic.charCodeAt(i)) {
      case 35: // #
        var notAtTheEnd = i !== end
        if (notAtTheEnd || slashInPreEnd) {
          return new Error('# is only allowed in ' + message + ' in the last position')
        }
        break
      case 43: // +
        var pastChar = i < end - 1 && topic.charCodeAt(i + 1) !== 47
        var preChar = i > 1 && topic.charCodeAt(i - 1) !== 47
        if (pastChar || preChar) {
          return new Error('+ is only allowed in ' + message + ' between /')
        }
        break
    }
  }
}

module.exports = validateTopic
<|endoftext|>


<commit_before>const fs = require('fs')
const azuretestcreds = ['devstoreaccount1', 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==', 'http://127.0.0.1:10000/devstoreaccount1']

class Storage {
  constructor(props) {
    this.backing = props.backing
    if (this.backing === 'azure') {
      const azure = require('azure-storage')
      const creds = props.local ? azuretestcreds : []
      this.blobSvc = azure.createBlobService(...creds)
    } else if (this.backing === 'aws') {
      const AWS = require('aws-sdk')
      this.s3 = new AWS.S3({
        endpoint: props.endpoint,
        region: props.region
      })
    }
  }
  createContainer(container, cb) {
    const createCb = function(error) {
      if (error) {
        console.error(error)
        throw error
      }
      cb()
    }
    if (this.backing === 'azure') {
      this.blobSvc.createContainerIfNotExists(container, createCb)
    } else if (this.backing === 'aws') {
      const params = {
        Bucket: container
      }
      this.s3.createBucket(params, createCb)
    }
  }
  downloadStream(container, file, stream, callback) {
    if (this.backing === 'azure') {
      return this.blobSvc.getBlobToStream(container, file, stream, callback)
    } else if (this.backing === 'aws') {
      const params = {
        Bucket: container,
        Key: file
      }
      return this.s3.getObject(params, callback).createReadStream().pipe(stream)
    }
  }
  uploadFile(container, file, sourcePath, callback) {
    if (this.backing === 'azure') {
      return this.blobSvc.createBlockBlobFromLocalFile(container, file, sourcePath, callback)
    } else if (this.backing === 'aws') {
      const params = {
        Body: fs.createReadStream(sourcePath),
        Bucket: container,
        Key: file
      }
      return this.s3.putObject(params, callback)
    }
  }
}
module.exports = Storage
<commit_msg>Prevent S3 Errors from Crashing App<commit_after>const fs = require('fs')
const azuretestcreds = [
  'devstoreaccount1',
  'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==',
  'http://127.0.0.1:10000/devstoreaccount1',
]

class Storage {
  constructor(props) {
    this.backing = props.backing
    if (this.backing === 'azure') {
      const azure = require('azure-storage')
      const creds = props.local ? azuretestcreds : []
      this.blobSvc = azure.createBlobService(...creds)
    } else if (this.backing === 'aws') {
      const AWS = require('aws-sdk')
      this.s3 = new AWS.S3({
        endpoint: props.endpoint,
        region: props.region,
      })
    }
  }
  createContainer(container, cb) {
    const createCb = function(error) {
      if (error) {
        console.error(error)
        throw error
      }
      cb()
    }
    if (this.backing === 'azure') {
      this.blobSvc.createContainerIfNotExists(container, createCb)
    } else if (this.backing === 'aws') {
      const params = {
        Bucket: container,
      }
      this.s3.createBucket(params, createCb)
    }
  }
  downloadStream(container, file, stream, callback) {
    if (this.backing === 'azure') {
      return this.blobSvc.getBlobToStream(container, file, stream, callback)
    } else if (this.backing === 'aws') {
      const params = {
        Bucket: container,
        Key: file,
      }
      return this.s3
        .getObject(params)
        .createReadStream()
        .on('error', err => {
          if (err.code !== 'NoSuchKey') {
            console.error(err)
          }
          callback(err)
        })
        .on('end', data => callback(null, data)) // do nothing, but this prevents from crashing
        .pipe(stream)
    }
  }
  uploadFile(container, file, sourcePath, callback) {
    if (this.backing === 'azure') {
      return this.blobSvc.createBlockBlobFromLocalFile(
        container,
        file,
        sourcePath,
        callback
      )
    } else if (this.backing === 'aws') {
      const params = {
        Body: fs.createReadStream(sourcePath),
        Bucket: container,
        Key: file,
      }
      return this.s3.putObject(params, callback)
    }
  }
}
module.exports = Storage
<|endoftext|>