Returns the jslint test config.

@function
@memberof! GruntTaskHelper
@private
@param {Object} buildConfig - The grunt buildConfig data
@param {Object} config - The JSLint config used for non test files
@returns {Object} The JSLint config
977688
function (buildConfig, config) {
        var testConfig = extend(true, {}, config || {}, {
            nomen: true,
            unparam: true,
            predef: [
                'it',
                'describe'
            ]
        });

        if (!buildConfig.nodeProject) {
            testConfig.predef.push('angular');
        }

        return testConfig;
    }
669164
function checkConfig(config) {
	if (config.code.compatibility) {
		warnings.push('Browserslist configuration has to be placed in `package.json`');
	}
	if (warnings.length) {
		console.warn('-------------------------------------------------------');
		console.warn('Attention:');
		warnings.forEach((string) => console.warn(`- ${string}`));
		console.warn('-------------------------------------------------------');
	}
}
179221
function getTools(config) {
      var tools = {};

      config.openRequests = config.openRequests || {};

      tools.noop = Function();
      tools.id = function(d) { return d; }

      tools.argArray = function(args) {
        return Array.prototype.slice.call(args, 0);
      }

      tools.join = function() {
        var query = '',
            arr = tools.argArray(arguments).map(function(d) {
              var d = typeof d == 'object' ? '?' + tools.serialize(d) : d,
                  s;

              s = (d && String(d) || '').split('?');
              if (s.length == 1) return d;
              if (query) query += '&';
              query += s[1];
              return s[0];
            }).filter(tools.id);

        return arr.join('/').replace(/\/+/g, '/') + (query ? '?' + query : '')
                  .replace(/&&/g, '&').replace(/&$/, '');
      }

      tools.serialize = function(obj, prefix) {
        var str = [], p, k;
        for (p in obj) {
          if (obj.hasOwnProperty(p)) {
            k = prefix ? prefix + '[' + p + ']' : p, v = obj[p];
            if (v instanceof Date) v = JSON.stringify(v);
            str.push(typeof v == 'object'
                      ? tools.serialize(v, k)
                      : encodeURIComponent(k) + '=' + encodeURIComponent(v));
          }
        }
        return str.join('&');
      }

      tools.merge = function(a, b) {
        for (var k in b) a[k] = b[k];
        return a;
      }

      tools.xhrargs = function(d, cb) {
        if (typeof (d) === 'function') return { data: {}, cb: d };
        else return { data: d || {}, cb: cb };
      }

      tools.uuid = function() {
        function s4() {
          return Math.floor((1 + Math.random()) * 0x10000)
                     .toString(16)
                     .substring(1);
        };

        return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
               s4() + '-' + s4() + s4() + s4();
      };

      tools.request = function(method, url, data, cb, context) {
        var req = typeof (XMLHttpRequest) != 'undefined'
                    ? new XMLHttpRequest()
                    : new ActiveXObject('Microsoft.XMLHTTP'),
            isjson = typeof (FormData) === 'undefined' ||
                          !(data instanceof FormData),
            reqId = tools.uuid();

        config.openRequests[reqId] = true;

        // If is blocking and blocked, silently go away
        if (context.isBlocking && config.blockers[context.path]) return;

        // Else block the next guy
        else if (context.isBlocking) config.blockers[context.path] = true;

        if (config.credentials) req.withCredentials = true;
        req.open(method, url, true);

        if (isjson) req.setRequestHeader('Content-type', 'application/json');
        req.onreadystatechange = function() {
          var status, data, error, meta;

          // Unlblock in config.blockingDelay time if isBlocking
          if (context.isBlocking) {
            setTimeout(function() {
              config.blockers[context.path] = false;
            }, config.blockingDelay);
          };

          if (req.readyState == 4) {  // done
            status = req.status;
            if (status >= 200 && status < 300) {
              try {
                data = JSON.parse(req.responseText || '{}');
                error = config.getError(data);
                if (!req.responseText) error = 'Empty response';
                meta = config.getMetadata(data);
                data = config.getData(data);
              } catch (e) { error = 'invalid json response' };
            } else {
              error = { code: status, message: 'invalid status code' };
            }

            if (config.openRequests[reqId]) {
              delete config.openRequests[reqId];
              return cb && cb(error, data, meta);
            }
          }
        }
        if (!isjson) req.send(data);
        else if (data) req.send(JSON.stringify(data));
        else req.send();
      };

      tools.forEach = function(obj, fn) {
        var k;

        if (obj instanceof Array) {
          obj.forEach(fn);
        } else for (k in obj) fn(obj[k], k);
      };

      tools.defineProperty = function(obj, key, val) {
        if (!(obj instanceof Object)) return;
        try {
          Object.defineProperty(obj, key, {
            enumerable: false,
            value: val
          });
        } catch (e) {  // fallback
          obj[key] = val;
        }
      };

      return tools;
    }
447476
function getConfig(config) {
    // Read a RESTBase configuration from a (optional) path argument, an (optional) CONFIG
    // env var, or from /etc/restbase/config.yaml
    var conf;

    if (config) {
        conf = config;
    } else if (process.env.CONFIG) {
        conf = process.env.CONFIG;
    } else {
        conf = '/etc/restbase/config.yaml';
    }

    var confObj = yaml.safeLoad(fs.readFileSync(conf));
    return confObj.default_project['x-modules'][0].options.table;
}
637363
function lintConfig(config) {
  if (!config.path) return logger.halt('null config.path')
  if (!config.path.root) return logger.halt('null config.path.root')
  if (!config.path.client) return logger.halt('null config.path.client')
  if (!config.path.static) return logger.halt('null config.path.static')
  if (!config.path.vendor) return logger.halt('null config.path.vendor')
  config.path.client = config.path.client.replace(/\/$/, '')
  var staticDir = path.join(config.path.root, config.path.static)
  config.$path = {
    source: {
      client: path.join(config.path.root, config.path.client),
      vendor: path.join(config.path.root, config.path.vendor)
    },
    target: {
      static: staticDir,
      client: path.join(staticDir, config.path.client),
      vendor: path.join(staticDir, config.path.vendor)
    }
  }
  return config
}
258923
function builder (config, configPath, callback) {
	var inc = new Include(config)
	inc
		.on('drain', function () {
			// All files and their dependencies loaded, root files (files with no parent file) built
			inc.build(function () {

				var output = path.resolve( configPath, config.output.path )
				var outputFiles = []

				debug('Include DONE: %d roots found output=%s', inc.roots.length, output)
				async.forEach(
					inc.roots
				, function (file, cb) {
						var relfile = path.join( output, path.relative(configPath, file.id) )

						outputFiles.push(relfile)

						debug('Include WRITING: file=%s', relfile)
						var w = fstream
							.Writer({
								path: relfile
							, mode: config.output.mode
							})
							w
							.on('close', cb)

							if (file.content)
								w.end(file.content)
							else
								fs.createReadStream(file.id).pipe(w)
				  }
				, function (err) {
						if (err) return callback(err)
						debug('%d files written out to %s', inc.roots.length, output)
						callback(
							null
						, outputFiles
						, inc.sourceFiles
						, inc.roots.map(function(root) {
								return root.id
							})
						)
					}
				)
			})
		})

	debug( path.resolve( configPath, config.input.include || '*.js' ) )
	debug( config.input.include || '*.js' )
	debug( config.input.exclude || '' )
	fileset(
		config.input.include || '*.js'
	, config.input.exclude || ''
	, { cwd: configPath }
	, function (err, files) {
			if (err) throw err

			debug('files', files)
			files
				.forEach(function (file) {
					inc.add( path.resolve( configPath, file) )
				})
		}
	)
}
1134143
function getSlackbotConfig (config) {
  return _.defaults(config.botkit, {debug: !!config.debug}, botkitDefaults)
}
1296796
function buildBuildList() {
  const buildList = {
    'build/tests.js': allPackages.map(pkg => `packages/${pkg}/test/*.js`)
  };
  allPackages.forEach(pkg => {
    buildList[`packages/${pkg}/dist/${pkg}.js`] = [`packages/${pkg}/globals.js`];
  });
  buildList['packages/demos/dist/demos.js'] = ['packages/demos/src/*.js'];
  return buildList;
}
1131720
function(configPath, configNames, config) {
	var configsUsed = [];

	config = config || projectConfig;

	// work with the raw configuration object
	if (config && config.root) {
		config = config.root();
	}

	config = convict(config);
	configPath = path.resolve(appPath, configPath);
	configNames = configNames || [];

	configNames.forEach(function(configName) {
		var file;

		// Ignore local config in production mode
		if (configName == 'local' && nodeEnv === 'production') { return; }

		file = path.join(configPath, 'config-'+configName);
		file += configName === 'default' ? '.js' : '.json';

		if (fs.existsSync(file)) {

			if (configName === 'default') {
				config = convict( require(file) );
				config.load(dynamicDefaults);
			}
			else {
				config.loadFile( file );
			}

			// logging
			configName === 'default' ? configsUsed.push('xtc defaults') : configsUsed.push(configName);
		}
	});

	// be informative
	!process.env.testRun
		&& configsUsed.push('env', 'args')
		&& console.log('configuration:', configsUsed.join(' < '));

	return config;
}
955628
function (fileName, fileContents, config, onLifecycleName, pluginCollector) {
            /*jslint evil: true */
            var foundIndex = -1, startIndex = 0, lineEndIndex, conditionLine,
                matches, type, marker, condition, isTrue, endRegExp, endMatches,
                endMarkerIndex, shouldInclude, startLength, lifecycleHas, deps,
                i, dep, moduleName, collectorMod,
                lifecyclePragmas, pragmas = config.pragmas, hasConfig = config.has,
                //Legacy arg defined to help in dojo conversion script. Remove later
                //when dojo no longer needs conversion:
                kwArgs = pragmas;

            //Mix in a specific lifecycle scoped object, to allow targeting
            //some pragmas/has tests to only when files are saved, or at different
            //lifecycle events. Do not bother with kwArgs in this section, since
            //the old dojo kwArgs were for all points in the build lifecycle.
            if (onLifecycleName) {
                lifecyclePragmas = config['pragmas' + onLifecycleName];
                lifecycleHas = config['has' + onLifecycleName];

                if (lifecyclePragmas) {
                    pragmas = create(pragmas || {}, lifecyclePragmas);
                }

                if (lifecycleHas) {
                    hasConfig = create(hasConfig || {}, lifecycleHas);
                }
            }

            //Replace has references if desired
            if (hasConfig) {
                fileContents = fileContents.replace(pragma.hasRegExp, function (match, test) {
                    if (hasConfig.hasOwnProperty(test)) {
                        return !!hasConfig[test];
                    }
                    return match;
                });
            }

            if (!config.skipPragmas) {

                while ((foundIndex = fileContents.indexOf("//>>", startIndex)) !== -1) {
                    //Found a conditional. Get the conditional line.
                    lineEndIndex = fileContents.indexOf("\n", foundIndex);
                    if (lineEndIndex === -1) {
                        lineEndIndex = fileContents.length - 1;
                    }

                    //Increment startIndex past the line so the next conditional search can be done.
                    startIndex = lineEndIndex + 1;

                    //Break apart the conditional.
                    conditionLine = fileContents.substring(foundIndex, lineEndIndex + 1);
                    matches = conditionLine.match(pragma.conditionalRegExp);
                    if (matches) {
                        type = matches[1];
                        marker = matches[2];
                        condition = matches[3];
                        isTrue = false;
                        //See if the condition is true.
                        try {
                            isTrue = !!eval("(" + condition + ")");
                        } catch (e) {
                            throw "Error in file: " +
                                   fileName +
                                   ". Conditional comment: " +
                                   conditionLine +
                                   " failed with this error: " + e;
                        }

                        //Find the endpoint marker.
                        endRegExp = new RegExp('\\/\\/\\>\\>\\s*' + type + 'End\\(\\s*[\'"]' + marker + '[\'"]\\s*\\)', "g");
                        endMatches = endRegExp.exec(fileContents.substring(startIndex, fileContents.length));
                        if (endMatches) {
                            endMarkerIndex = startIndex + endRegExp.lastIndex - endMatches[0].length;

                            //Find the next line return based on the match position.
                            lineEndIndex = fileContents.indexOf("\n", endMarkerIndex);
                            if (lineEndIndex === -1) {
                                lineEndIndex = fileContents.length - 1;
                            }

                            //Should we include the segment?
                            shouldInclude = ((type === "exclude" && !isTrue) || (type === "include" && isTrue));

                            //Remove the conditional comments, and optionally remove the content inside
                            //the conditional comments.
                            startLength = startIndex - foundIndex;
                            fileContents = fileContents.substring(0, foundIndex) +
                                (shouldInclude ? fileContents.substring(startIndex, endMarkerIndex) : "") +
                                fileContents.substring(lineEndIndex + 1, fileContents.length);

                            //Move startIndex to foundIndex, since that is the new position in the file
                            //where we need to look for more conditionals in the next while loop pass.
                            startIndex = foundIndex;
                        } else {
                            throw "Error in file: " +
                                  fileName +
                                  ". Cannot find end marker for conditional comment: " +
                                  conditionLine;

                        }
                    }
                }
            }

            //If need to find all plugin resources to optimize, do that now,
            //before namespacing, since the namespacing will change the API
            //names.
            //If there is a plugin collector, scan the file for plugin resources.
            if (config.optimizeAllPluginResources && pluginCollector) {
                try {
                    deps = parse.findDependencies(fileName, fileContents);
                    if (deps.length) {
                        for (i = 0; i < deps.length; i++) {
                            dep = deps[i];
                            if (dep.indexOf('!') !== -1) {
                                moduleName = dep.split('!')[0];
                                collectorMod = pluginCollector[moduleName];
                                if (!collectorMod) {
                                 collectorMod = pluginCollector[moduleName] = [];
                                }
                                collectorMod.push(dep);
                            }
                        }
                    }
                } catch (eDep) {
                    logger.error('Parse error looking for plugin resources in ' +
                                 fileName + ', skipping.');
                }
            }

            //Strip amdefine use for node-shared modules.
            fileContents = fileContents.replace(pragma.amdefineRegExp, '');

            //Do namespacing
            if (onLifecycleName === 'OnSave' && config.namespace) {
                fileContents = pragma.namespace(fileContents, config.namespace, onLifecycleName);
            }


            return pragma.removeStrict(fileContents, config);
        }
855298
function(config){

      opts = xtend(opts, {
        verbose: opts.verbose || config.options.verbose || config.build.options.verbose,
        force: config.build.options.force || false
      });

      var _newArgs = [],
      _bin,
      patsy = this;

      if(patsy.utils.isWin){

        _bin       = "cmd";
        var _cmdName   = 'node_modules\\.bin\\grunt';

        //New args will go to cmd.exe, then we append the args passed in to the list
        //  the /c part tells it to run the command.  Thanks, Windows...
        _newArgs.push('/c');
        _newArgs.push(_cmdName);

        if(opts.verbose){

          util.print('>>'.cyan + ' Loading grunt\nCommand options: ' + String(_bin + ' /c ' + _cmdName + ' --path ' + config.project.environment.abs_path).cyan + '\n');

        }

      } else {

        if(opts.verbose){

          util.print('>>'.cyan + ' Loading grunt\nCommand options: ' + String('node_modules/.bin/grunt --path ' + config.project.environment.abs_path).cyan + '\n');
        }

        _bin        = 'node_modules/.bin/grunt';

      }

      // Append needed arguments for grunt
      _newArgs.push('--path');
      _newArgs.push(config.project.environment.abs_path);
      _newArgs.push('--stack');

      if(opts.verbose){

        _newArgs.push('-v');

      }

      if(opts.force){

        _newArgs.push('--force');

      }

      // Spawn grunt instance
      patsy.grunt     = spawn(_bin, _newArgs, { stdio: 'inherit' });

      patsy.scripture.print('[Patsy]'.yellow + ': The grunt is saddling up!');

      // Can be commented back in again, just testing if this is necessary
      //this.grunt.stderr.pipe(process.stdout);
      var warnings = [];

      /*this.grunt.stdout.on('data',function(data){
        var buff = new Buffer(data);
        console.log("foo: " + buff.toString('utf8'));
      });*/

      /*this.grunt.stdout.on('data',function(data){

        data = String(data).trim();

        // Do not print out empty lines/strings
        if(data !== ''){

          // If opts verbose is set, output is piped directly from grunt
          if(opts.verbose){

            util.puts( data );
          }
          // If not verbose, use scripture or other
          else {

            if(data.indexOf('Done, without errors') !== -1){

              patsy.scripture.print('[Patsy]'.yellow + ': The grunt has finished building without errors!');
            } else if(data.indexOf('Done, but with warnings') !== -1){

              patsy.scripture.print('[Patsy]'.yellow + ': The grunt has finished building, but with warnings!');

              if(warnings.length !== 0){

                util.print(warnings.join('\n'));
                warnings = [];
              }
            } else if(data.indexOf('Waiting..') !== -1){

              patsy.scripture.print('[Grunt]'.green + ': Watching for changes my Liege!'.bold);
            } else if(data.indexOf('changed') !== -1){

              patsy.scripture.print('[Grunt]'.green + ': File changed! Running tasks..'.bold);
            } else if(data.indexOf('not found') !== -1){

              warnings.push(data);
            } else {

              if(warnings.length !== 0){

               // patsy.scripture.print('[Patsy]'.yellow + ': The grunt has finished building, but with warnings!'.yellow);
                util.print(warnings.join('\n'));
                warnings = [];
              }
            }
          }
        }

      });*/

      /*this.grunt.stderr.on('data',function(data){
        try{
          var buff = new Buffer(data);
          data = buff.toString('utf8');
        } catch(e){

        }


        warnings.push(String('Warning: Grunt: ' + data).yellow);

      });
*/
      this.grunt.on('exit',function(code){

        if(opts.verbose){

          patsy.utils.fail('Grunt exception! ' + code.red);

        }

        patsy.scripture.print('[Patsy]'.yellow + ': The grunt has buggered off! ' + code.red + "\n");



        process.exit(1);
      });
    }
431348
function getWebpackConfig(config, context) {
  var webpackConfig = {
    module: {
      rules: [
        {
          exclude: /node_modules/,
          loader: assist.resolve('babel-loader'),
          test: /\.(es6|js)$/
        }
      ]
    },
    output: {
      path: config.$path.target.client,
      filename: '[name].js'
    },
    resolve: {
      extensions: ['.js'],
      alias: config.alias || {}
    },
    externals: {}
  }

  var babelConfig = assist.getBabelConfig(context.env)
  var babelLoader = webpackConfig.module.rules
    .find(rule => rule.loader && /babel/.test(rule.loader))
  babelLoader.options = babelConfig

  var processEnv = {
    'process.env': {
      NODE_ENV: JSON.stringify(context.env || 'production'),
      IS_BROWSER: true
    }
  }
  if (context.env === 'development') {
    // development env
    webpackConfig.plugins = [
      new webpack.DefinePlugin(processEnv)
    ]
  } else {
    // production env
    webpackConfig.plugins = [
      new webpack.DefinePlugin(processEnv),
      new webpack.optimize.CommonsChunkPlugin({ name: 'common' }),
      new webpack.optimize.UglifyJsPlugin({ sourceMap: false })
    ]
  }

  return webpackConfig
}
777411
function getPluginConfig(config, pluginName) {
    var pluginsConfig = config.getValues().get('pluginsConfig');
    if (pluginsConfig === undefined) {
        return {};
    }
    var pluginConf = pluginsConfig.get(pluginName);
    if (pluginConf === undefined) {
        return {};
    } else {
        return pluginConf.toJS();
    }
}
1316645
async function build(previousFileSizes) {
  console.log(`${manifest.name}: Creating an optimized production build...`)

  // a project can opt to start
  let webpackConfig = get(manifest, 'skypager.webpack.merge') === false ? {} : config

  if (get(manifest, 'skypager.webpack.build')) {
    console.log(`Using custom wepack config`)
    let configToMerge = require(path.resolve(
      path.dirname(paths.appPackageJson),
      get(manifest, 'skypager.webpack.build')
    ))

    if (typeof configToMerge === 'function') {
      configToMerge = await Promise.resolve(configToMerge(argv.env || 'production', argv, config))
    }

    if (!isArray(configToMerge)) {
      // we won't try and merge webpack config if it is an array
      webpackConfig = configMerge(webpackConfig, configToMerge)
    } else {
      console.log('Using multiple webpack configs')
    }
  }

  const compiler = webpack(webpackConfig)

  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err) {
        return reject(err)
      }

      const messages = formatWebpackMessages(stats.toJson({}, true))
      if (messages.errors.length) {
        // Only keep the first error. Others are often indicative
        // of the same problem, but confuse the reader with noise.
        if (messages.errors.length > 1) {
          messages.errors.length = 1
        }
        console.log(`Build failed in ${manifest.name}`)
        return reject(new Error(messages.errors.join('\n\n')))
      }
      if (
        process.env.CI &&
        (typeof process.env.CI !== 'string' || process.env.CI.toLowerCase() !== 'false') &&
        messages.warnings.length
      ) {
        console.log(
          chalk.yellow(
            '\nTreating warnings as errors because process.env.CI = true.\n' +
              'Most CI servers set it automatically.\n'
          )
        )
        return reject(new Error(messages.warnings.join('\n\n')))
      }
      return resolve({
        stats,
        previousFileSizes,
        warnings: messages.warnings,
      })
    })
  })
}
399629
function ConfigFromPath (superConfig, project, version) {
  ConfigFromPath.super_.call(this, superConfig, project, version);

  var strictNS = simpleWrapNS(this.ns);
  strictNS.env = simpleWrapNS(createNamespace(superConfig.getEnvConfig()));

  var files = superConfig._resolvePaths(project, version);
  var loaded = {};

  var generateLoad = function (f) {
    return function (otherVersion) {
      debug('load(%s) in %s', otherVersion, f);
      var dir = path.dirname(f);
      var otherFile = path.resolve(dir, otherVersion + '.js');
      if (loaded[otherFile]) {
        throw new Error('load(' + version + ') conflict in file ' + f);
      }
      try {
        require(otherFile)(strictNS, generateLoad(otherFile));
      } catch (err) {
        if (err.code === 'MODULE_NOT_FOUND') {
          throw new Error('load(' + version + ') fail in file ' + f);
        } else {
          throw err;
        }
      }
    };
  };
  files.forEach(function (f) {
    debug('load %s', f);
    var init = require(f);
    loaded[f] = true;
    if (typeof init !== 'function') {
      throw new Error('bad config file format, `module.exports` must be a function: ' + f);
    }
    init(strictNS, generateLoad(f));
  });

  var loadedFiles = Object.keys(loaded);
  if (loadedFiles.length < 1) {
    throw new Error('cannot find any config files for ' + project + '.' + version);
  } else {
    loadedFiles.forEach(function (f) {
      delete require.cache[f];
    });
  }

  this._loadFinish();
  debug('done');
}
1326294
function getConfigFromFile(directories, filename) {
	const filepath = tryFile(directories, filename);
	if (!filepath) {
		return {};
	}

	return require(filepath);
}
754740
function getConfigGetter(options) {
	/**
	 * Return a config value.
	 *
	 * @param {string} prop
	 * @param {any} [defaultValue]
	 * @return {any}
	 */
	function config(prop, defaultValue) {
		console.warn(
			'Warning: calling config as a function is deprecated. Use config.values() instead'
		);
		return get(options, prop, defaultValue);
	}

	/**
	 * Return an object with all config values.
	 *
	 * @return {Object}
	 */
	function values() {
		return options;
	}

	/**
	 * Mark config options as required.
	 *
	 * @param {string[]} names...
	 * @return {Object} this
	 */
	function require(...names) {
		const unknown = names.filter(name => !options[name]);
		if (unknown.length > 0) {
			throw new MrmUndefinedOption(`Required config options are missed: ${unknown.join(', ')}.`, {
				unknown,
			});
		}
		return config;
	}

	/**
	 * Set default values.
	 *
	 * @param {Object} defaultOptions
	 * @return {any}
	 */
	function defaults(defaultOptions) {
		options = Object.assign({}, defaultOptions, options);
		return config;
	}

	config.require = require;
	config.defaults = defaults;
	config.values = values;
	return config;
}