prepare files & folders for grunt:plato & coverage
341762
function (baseData, isFile) {
    var fs = require('fs');

    ['/lib/commands/marionette/', '/lib/commands/webdriver/'].forEach(function (folder) {
      fs.readdirSync(__dirname + folder).forEach(function (file) {
        var platoFolder = 'files/' + folder.substring(1).replace(/\//g, '_') + file.replace('.js', '_js');
        if (isFile === true) {
          baseData.push(platoFolder + '/report.history.json');
        } else {
          baseData.push('report/complexity/' + platoFolder);
        }
      });
    });

    return baseData;
  }
632419
def prepare_files(self, finder, force_root_egg_info=False, bundle=False):
        """"""
        unnamed = list(self.unnamed_requirements)
        reqs = list(self.requirements.values())
        while reqs or unnamed:
            if unnamed:
                req_to_install = unnamed.pop(0)
            else:
                req_to_install = reqs.pop(0)
            req_version = None
            install = True
            best_installed = False
            if not self.ignore_installed and not req_to_install.editable:
                req_to_install.check_if_exists()
                if req_to_install.satisfied_by:
                    if self.upgrade:
                        if not self.force_reinstall:
                            try:
                                url, req_version = finder.find_requirement(
                                    req_to_install, self.upgrade)
                            except BestVersionAlreadyInstalled:
                                best_installed = True
                                install = False
                            else:
                                # Avoid the need to call find_requirement again
                                req_to_install.url = url.url

                        if not best_installed:
                            req_to_install.conflicts_with = req_to_install.satisfied_by
                            req_to_install.satisfied_by = None
                    else:
                        install = False
                if req_to_install.satisfied_by:
                    if best_installed:
                        logger.notify('Requirement already up-to-date: %s'
                                      % req_to_install)
                    else:
                        logger.notify('Requirement already satisfied '
                                      '(use --upgrade to upgrade): %s'
                                      % req_to_install)
            if req_to_install.editable:
                logger.notify('Obtaining %s' % req_to_install)
            elif install:
                if req_to_install.url and req_to_install.url.lower().startswith('file:'):
                    logger.notify('Unpacking %s' % display_path(url_to_path(req_to_install.url)))
                else:
                    logger.notify('Downloading/unpacking %s' % req_to_install)
            logger.indent += 2
            try:
                is_bundle = False
                if req_to_install.editable:
                    if req_to_install.source_dir is None:
                        location = req_to_install.build_location(self.src_dir)
                        req_to_install.source_dir = location
                    else:
                        location = req_to_install.source_dir
                    if not os.path.exists(self.build_dir):
                        _make_build_dir(self.build_dir)
                    req_to_install.update_editable(not self.is_download)
                    if self.is_download:
                        req_to_install.run_egg_info()
                        req_to_install.archive(self.download_dir)
                    else:
                        req_to_install.run_egg_info()
                elif install:
                    ##@@ if filesystem packages are not marked
                    ##editable in a req, a non deterministic error
                    ##occurs when the script attempts to unpack the
                    ##build directory

                    location = req_to_install.build_location(self.build_dir, not self.is_download)
                    ## FIXME: is the existance of the checkout good enough to use it?  I don't think so.
                    unpack = True
                    if not os.path.exists(os.path.join(location, 'setup.py')):
                        ## FIXME: this won't upgrade when there's an existing package unpacked in `location`
                        if req_to_install.url is None:
                            url, req_version = finder.find_requirement(req_to_install, upgrade=self.upgrade)
                        else:
                            ## FIXME: should req_to_install.url already be a link?
                            url = Link(req_to_install.url)
                            assert url
                        if url:
                            try:
                                self.unpack_url(req_to_install, req_version, url, location, self.is_download)
                            except HTTPError:
                                e = sys.exc_info()[1]
                                logger.fatal('Could not install requirement %s because of error %s'
                                             % (req_to_install, e))
                                raise InstallationError(
                                    'Could not install requirement %s because of HTTP error %s for URL %s'
                                    % (req_to_install, e, url))
                        else:
                            unpack = False
                    if unpack:
                        is_bundle = req_to_install.is_bundle
                        url = None
                        if is_bundle:
                            req_to_install.move_bundle_files(self.build_dir, self.src_dir)
                            for subreq in req_to_install.bundle_requirements():
                                reqs.append(subreq)
                                self.add_requirement(subreq)
                        elif self.is_download:
                            req_to_install.source_dir = location
                            if url and url.scheme in vcs.all_schemes:
                                req_to_install.run_egg_info()
                                req_to_install.archive(self.download_dir)
                        else:
                            req_to_install.source_dir = location
                            req_to_install.run_egg_info()
                            if force_root_egg_info:
                                # We need to run this to make sure that the .egg-info/
                                # directory is created for packing in the bundle
                                req_to_install.run_egg_info(force_root_egg_info=True)
                            req_to_install.assert_source_matches_version()
                            #@@ sketchy way of identifying packages not grabbed from an index
                            if bundle and req_to_install.url:
                                self.copy_to_build_dir(req_to_install)
                                install = False
                        # req_to_install.req is only avail after unpack for URL pkgs
                        # repeat check_if_exists to uninstall-on-upgrade (#14)
                        req_to_install.check_if_exists()
                        if req_to_install.satisfied_by:
                            if self.upgrade or self.ignore_installed:
                                req_to_install.conflicts_with = req_to_install.satisfied_by
                                req_to_install.satisfied_by = None
                            else:
                                install = False
                if not is_bundle and not self.is_download:
                    ## FIXME: shouldn't be globally added:
                    finder.add_dependency_links(req_to_install.dependency_links)
                    if (req_to_install.extras):
                        logger.notify("Installing extra requirements: %r" % ','.join(req_to_install.extras))
                    if not self.ignore_dependencies:
                        for req in req_to_install.requirements(req_to_install.extras):
                            try:
                                name = pkg_resources.Requirement.parse(req).project_name
                            except ValueError:
                                e = sys.exc_info()[1]
                                ## FIXME: proper warning
                                logger.error('Invalid requirement: %r (%s) in requirement %s' % (req, e, req_to_install))
                                continue
                            if self.has_requirement(name):
                                ## FIXME: check for conflict
                                continue
                            subreq = InstallRequirement(req, req_to_install)
                            reqs.append(subreq)
                            self.add_requirement(subreq)
                    if req_to_install.name not in self.requirements:
                        self.requirements[req_to_install.name] = req_to_install
                else:
                    self.reqs_to_cleanup.append(req_to_install)
                if install:
                    self.successfully_downloaded.append(req_to_install)
                    if bundle and (req_to_install.url and req_to_install.url.startswith('file:///')):
                        self.copy_to_build_dir(req_to_install)
            finally:
                logger.indent -= 2
665269
function getComponentMapping( name, files ) {
		grunt.verbose.writeln( 'BowerMap::getComponentMapping - ' + name );


		//first get list of all files
		var fileList = [];
		if ( shim[ name ] !== undefined ) {
			grunt.verbose.writeln( '    using shim value' );
			//use shim value
			fileList = fileList.concat( shim[ name ] );
		}
		else {
			grunt.verbose.writeln( '    using result value - ' + files );
			//make sure files is an array
			if (typeof files === 'string'){
				files = [files];
			}
			//we just need the path relative to the module directory
			files.forEach( function( file ){
				file = path.fix( file );
				fileList.push( file.replace( path.fix( path.join( bowerPath, name ) ) , "" ) );
			});
		}

		//expand list
		var expandedList = [];
		fileList.forEach( function( file ){
			grunt.verbose.writeln( '      globbing - ' + path.join( name, file ) );
			glob.sync( path.join( name, file ), { cwd: bowerPath, dot: true } ).forEach( function( filename ) {
				var src = path.fix( path.join( bowerPath, filename ) );
				grunt.verbose.writeln( 'src      ' + src );
				expandedList.push( src );
			});
		});

		//filter filetypes
		expandedList = expandedList.filter( function( file ){
			var ext = path.extname( file ).substr(1);
			if ( extensions ){
				return extensions.indexOf( ext ) >= 0;
			}
			else{
				return true;
			}
		});


		//get common path for building destination
		var commonPath = maintainCommonPaths ? "" : getCommonPathBase( expandedList );
		grunt.verbose.writeln( '   common path: ' + commonPath );


		//build default mapping
		var componentMap = {};
		grunt.verbose.writeln( '   mapping files:' );
		expandedList.forEach( function( file ){

			if ( expandedMap[ file ] !== undefined ) {
				//use user configured mapping if set
				componentMap[ file ] = expandedMap[ file ];
				grunt.log.writeln( '  * '+file+' -> '+ expandedMap[ file ] );
			}
			else {
				var newFilename = commonPath === "" ? file : file.replace( commonPath, "" );
				//console.log('      newfileName:',newFilename);
				var dest = path.join( destPath, newFilename );
				//console.log('      dest:',dest);

				if ( useNamespace === true || ( useNamespace === undefined && expandedList.length > 1 ) ){
					dest = dest.replace( destPath, path.join( destPath, name ) );
				}
				componentMap[ file ] = dest;
				grunt.log.writeln( '    '+file+' -> '+ dest );

			}

		});

		return componentMap;

	}
714800
function grunt(gruntInst, verbose, patch) {
		var mw = (patch || core.base());
		mw.enabled = true;
		if (verbose) {
			mw.writeln = function (line) {
				if (mw.enabled) {
					gruntInst.verbose.writeln(line);
				}
			};
		}
		else {
			mw.writeln = function (line) {
				if (mw.enabled) {
					gruntInst.log.writeln(line);
				}
			};
		}
		if (!patch) {
			mw.toString = function () {
				return '<miniwrite-grunt>';
			};
		}
		return mw;
	}
1096565
function prepareRevision(revision) {
  console.log(`🍳  Preparing ${revision}...`);

  if (revision === LOCAL) {
    return babelBuild(LOCAL_DIR());
  } else {
    if (!fs.existsSync(TEMP_DIR())) {
      fs.mkdirSync(TEMP_DIR());
    }

    const hash = hashForRevision(revision);
    const dir = TEMP_DIR(hash);

    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir);
      execSync(`git archive "${hash}" | tar -xC "${dir}"`);
      execSync('yarn install', { cwd: dir });
    }
    for (const file of findFiles(LOCAL_DIR('src'), '*/__tests__/*')) {
      const from = LOCAL_DIR('src', file);
      const to = path.join(dir, 'src', file);
      fs.copyFileSync(from, to);
    }
    execSync(
      `cp -R "${LOCAL_DIR()}/src/__fixtures__/" "${dir}/src/__fixtures__/"`
    );

    return babelBuild(dir);
  }
}
721686
function fileCategoryMap() {

        // Go over every file lookup function we export.
        var exports = module.exports(grunt);
        // This list of categories must contain all non-overlapping file categories.
        var categories = ['extLibFiles', 'extLibMapFiles', 'extCssFiles', 'extFontFiles', 'fontFiles',
            'appIndexFiles', 'testIndexFiles', 'configFiles', 'libFiles', 'modelFiles', 'srcDataFiles',
            'codeFiles', 'otherJsFiles', 'otherNonJsFiles', 'taskFiles', 'cssFiles', 'picFiles', 'soundFiles', 'unitTestFiles',
            'commonJsFiles', 'commonOtherFiles', 'ignoredFiles', 'distUncompressedFiles',
            'distLibFiles', 'distIndexFiles', 'distJsFiles', 'distCssFiles',
            'toolsShellFiles', 'unitTestDataFiles', 'picSrcFiles', 'soundSrcFiles',
            'htmlTemplateFiles', 'generatedJsFiles', 'otherMediaFiles', 'unitTestHelperFiles',
            'pythonFiles', 'compiledPythonFiles', 'localizationDataFiles', 'developmentOtherDataFiles', 'developmentTextDataFiles'];

        // Construct the map by calling each function defined above.
        var map = {};
        for (var i = 0; i < categories.length; i++) {
            var files = flatten(exports[categories[i]]());
            for (var j = 0; j < files.length; j++) {
                if (map[files[j]]) {
                    grunt.fail.warn("A file '" + files[j] + "' maps to category '" + categories[i] + "' in addition to '" + map[files[j]] + "' category.");
                } else {
                    map[files[j]] = categories[i];
                }
            }
        }
        return map;
    }
52809
function (srcFiles, destPath) {
    // Iterate over all specified file groups.
    srcFiles.map(grunt.file.read).forEach(function (fileContent, i) {
        var abspath = srcFiles[i];
        var results = fileContent.match(applyminGlobal.beginminPattern_global);
        if (results) {
            var beginminInfo = {};
            for (var index in results) {
                var result = results[index].match(applyminGlobal.beginminPattern);
                var beginEndMinBlock = result[0];
                var targetUrlPath = result[1];
                var staticBlock = result[2];  // static block, maybe css/js
                var targetFilePath = targetUrlPath.match(new RegExp(destPath + '/' + '\\S+\\.(css|js)', 'i'));
                if (!targetFilePath) {
                    grunt.warn('In the file: ' + abspath + ', the target filename in ' + targetUrlPath + ' should start with ' + destPath + '/' + ' and end with .css or .js');
                }
                targetFilePath = targetFilePath[0];
                _handleStaticBlock(abspath, targetFilePath, staticBlock);
                if (targetFilePath in beginminInfo) {
                    grunt.warn('In the file: ' + abspath + ', the target filename ' + targetFilePath + ' should not be duplicated.');
                }
                beginminInfo[targetFilePath] = {targetUrlPath:targetUrlPath, beginEndMinBlock:beginEndMinBlock};
            }
            // Store results for the applymin later.
            applyminGlobal.beginminInfos[abspath] = beginminInfo;
        }
    });
  }
518485
function preparePackage() {
    var ignoreFiles = ['package.json', 'README.md', 'LICENSE.md', '.gitignore', '.npmignore'];
    var ignoreCopyFiles = [];
    var copyRecursiveSync = function(src, dest) {
        var exists = fs.existsSync(src);
        var stats = exists && fs.statSync(src);
        var isDirectory = exists && stats.isDirectory();
        if (exists && isDirectory) {
            if (!fs.existsSync(dest)) {
                fs.mkdirSync(dest);
            }
            fs.readdirSync(src).forEach(function(filename) {
                copyRecursiveSync(upath.join(src, filename),
                    upath.join(dest, filename));
            });
        } else {
            if (ignoreCopyFiles.indexOf(upath.basename(src)) === -1) {
                fs.linkSync(src, dest);
            }
        }
    };
    var srcPkg = upath.join(process.cwd(), 'src');
    if (fs.existsSync(srcPkg)) {
        fs.readdirSync(process.cwd()).forEach(function(filename) {
            var curPath = upath.join(process.cwd(), filename);
            if (ignoreFiles.indexOf(upath.basename(curPath)) === -1 && fs.statSync(curPath).isFile()) {
                fs.unlinkSync(curPath);
            }
        });
        copyRecursiveSync(srcPkg, process.cwd());
    }
    deleteFolderRecursive(srcPkg);
    deleteFolderRecursive(upath.join(process.cwd(), 'test'));
    deleteFolderRecursive(upath.join(process.cwd(), 'env'));
}
1360624
async function buildSassFiles(files, outputDir, config) {
  const renderedFiles = await Promise.all(files.map(async file => {
    const css = await renderFile(file, config);
    return {file, css};
  }));

  await fs.ensureDir(outputDir);

  return Promise.all(renderedFiles.map(({file, css}) => {
    const outputFile = getOutputFile(file, outputDir);
    return writeFile(outputFile, css);
  }));
}
589861
def _prepare(self):
        """"""
        names = []

        added_directories = set()

        def add_directory(short_path):
            # Do not continue if this directory has already been added
            if short_path in added_directories:
                return

            # Scan for first super-directory that has already been added
            dir_base  = short_path
            dir_parts = []
            while dir_base:
                dir_base, dir_name = os.path.split(dir_base)
                dir_parts.append(dir_name)
                if dir_base in added_directories:
                    break

            # Add missing intermediate directory nodes in the right order
            while dir_parts:
                dir_base = os.path.join(dir_base, dir_parts.pop())

                # Create an empty, fake file to represent the directory
                mock_file = io.StringIO()
                mock_file.write(u'')
                # Add this directory to those that will be sent
                names.append(('files',
                             (dir_base.replace(os.sep, '/'), mock_file, 'application/x-directory')))
                # Remember that this directory has already been sent
                added_directories.add(dir_base)

        def add_file(short_path, full_path):
            try:
                # Always add files in wildcard directories
                names.append(('files', (short_name.replace(os.sep, '/'),
                                        open(full_path, 'rb'),
                                        'application/octet-stream')))
            except OSError:
                # File might have disappeared between `os.walk()` and `open()`
                pass

        def match_short_path(short_path):
            # Remove initial path component so that all files are based in
            # the target directory itself (not one level above)
            if os.sep in short_path:
                path = short_path.split(os.sep, 1)[1]
            else:
                return False

            # Convert all path seperators to POSIX style
            path = path.replace(os.sep, '/')

            # Do the matching and the simplified path
            for pattern in self.patterns:
                if pattern.match(path):
                    return True
            return False

        # Identify the unecessary portion of the relative path
        truncate = os.path.dirname(self.directory)
        # Traverse the filesystem downward from the target directory's uri
        # Errors: `os.walk()` will simply return an empty generator if the
        #         target directory does not exist.
        wildcard_directories = set()
        for curr_dir, _, files in os.walk(self.directory):
            # find the path relative to the directory being added
            if len(truncate) > 0:
                _, _, short_path = curr_dir.partition(truncate)
            else:
                short_path = curr_dir
            # remove leading / or \ if it is present
            if short_path.startswith(os.sep):
                short_path = short_path[1:]

            wildcard_directory = False
            if os.path.split(short_path)[0] in wildcard_directories:
                # Parent directory has matched a pattern, all sub-nodes should
                # be added too
                wildcard_directories.add(short_path)
                wildcard_directory = True
            else:
                # Check if directory path matches one of the patterns
                if match_short_path(short_path):
                    # Directory matched pattern and it should therefor
                    # be added along with all of its contents
                    wildcard_directories.add(short_path)
                    wildcard_directory = True

            # Always add directories within wildcard directories - even if they
            # are empty
            if wildcard_directory:
                add_directory(short_path)

            # Iterate across the files in the current directory
            for filename in files:
                # Find the filename relative to the directory being added
                short_name = os.path.join(short_path, filename)
                filepath = os.path.join(curr_dir, filename)

                if wildcard_directory:
                    # Always add files in wildcard directories
                    add_file(short_name, filepath)
                else:
                    # Add file (and all missing intermediary directories)
                    # if it matches one of the patterns
                    if match_short_path(short_name):
                        add_directory(short_path)
                        add_file(short_name, filepath)
        # Send the request and present the response body to the user
        req = requests.Request("POST", 'http://localhost', files=names)
        prep = req.prepare()
        return prep
533301
function (filepath, content){
        try{
            grunt.file.write(filepath, content);
            grunt.log.writeln('File "' + filepath + '" wrapped and saved.');
        } catch (err){
            grunt.fail.fatal(err);
        }
    }
190286
function(app, options) {
  app.post(WRITE_COVERAGE,
    bodyParser,
    (req, res) => {
      let map = istanbul.libCoverage.createCoverageMap();
      coverageHandler(map, options, req, res);
    },
    logError);
}
551654
def prep_system(run_info_yaml, bcbio_system=None):
    
    work_dir = os.getcwd()
    config, config_file = config_utils.load_system_config(bcbio_system, work_dir)
    dirs = setup_directories(work_dir, os.path.normpath(os.path.dirname(os.path.dirname(run_info_yaml))),
                             config, config_file)
    return [dirs, config, run_info_yaml]
992015
function buildSingleModule (app, mod, conf, args) {
  if (!mod) {
    mod = conf.moduleConf.module;
  }
  conf = getConf(app, mod);
  del.sync(path.join(conf.modulePath, 'dist'));
  var allPromise = taskList.all($, conf.appConf, conf.moduleConf, args);
  var sassPromise = taskList.sass($, conf.appConf, conf.moduleConf, args);
  var lessPromise = taskList.less($, conf.appConf, conf.moduleConf, args);
  var athenaMatePromise = taskList.athena_mate($, conf.appConf, conf.moduleConf, args);
  var stylesAllinonePromise = taskList.allinone($, conf.appConf, conf.moduleConf, args);
  var transImagesPromise = taskList.trans_images($, conf.appConf, conf.moduleConf, args);
  var stylesPromise = taskList.styles($, conf.appConf, conf.moduleConf, args);
  var scriptsPromise = taskList.scripts($, conf.appConf, conf.moduleConf, args);
  var compressPromise = taskList.compress($, conf.appConf, conf.moduleConf, args);
  var fontsPromise = taskList.fonts($, conf.appConf, conf.moduleConf, args);
  var imagesPromise = taskList.images($, conf.appConf, conf.moduleConf, args);
  var revPromise = taskList.rev($, conf.appConf, conf.moduleConf, args);
  var revNoHashPromise = taskList.rev_no_hash($, conf.appConf, conf.moduleConf, args);
  var fetchCommonPromise = taskList.fetch_common($, conf.appConf, conf.moduleConf, args);
  var tempPromise = taskList.temp($, conf.appConf, conf.moduleConf, args);

  $.util.log($.util.colors.green('开始编译模块' + mod + '！'));
  return allPromise(mod, conf.modulePath, conf.appPath)
    .then(sassPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(lessPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(athenaMatePromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(stylesAllinonePromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(transImagesPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(stylesPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(scriptsPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(imagesPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(compressPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(fontsPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(function () {
      // 是否启用md5
      return new Promise(function (resolve, reject) {
        var support = conf.moduleConf.support;
        var useHash = support.useHash ? support.useHash : {
          enable: true
        };
        var enable = useHash.enable === undefined ? true : useHash.enable;
        if (enable) {
          resolve();
        } else {
          reject();
        }
      });
    })
    .then(revPromise.bind(null, mod, conf.modulePath, conf.appPath), revNoHashPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(fetchCommonPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(tempPromise.bind(null, mod, conf.modulePath, conf.appPath))
    .then(function (result) {
      $.util.log($.util.colors.green('结束编译模块' + mod + '！'));
      return Promise.resolve(result);
    }).catch(function (e) {
      if (e) {
        console.log(e.plugin);
        if (e.stack) {
          console.log(e.stack);
        }
      }
    });
}
1323560
function BuildAssetsMiddleware (context)
{
  var grunt = context.grunt
    , options = context.options.assets;

  /**
   * Records which files have been already exported.
   * Prevents duplicate asset exports.
   * It's a map of absolute file names to boolean `true`.
   * @type {Object.<string,boolean>}
   */
  var exportedAssets = {};

  //--------------------------------------------------------------------------------------------------------------------
  // PUBLIC API
  //--------------------------------------------------------------------------------------------------------------------

  this.analyze = function (filesArray)
  {
    /* jshint unused: vars */
    // Do nothing
  };

  this.trace = function (module)
  {
    /* jshint unused: vars */
    // Do nothing.
  };

  this.build = function (targetScript)
  {
    if (!options.enabled) return;
    // Import file paths.
    var stylehseets = grunt.config (context.options.requiredStylesheets.exportToConfigProperty);
    if (!stylehseets) return; // No stylesheet sources are configured.
    var targetPath = path.dirname (targetScript);
    stylehseets.forEach (function (filePath)
    {
      var src = grunt.file.read (filePath);
      scan (path.dirname (filePath), targetPath, src);
    });

  };

  //--------------------------------------------------------------------------------------------------------------------
  // PRIVATE
  //--------------------------------------------------------------------------------------------------------------------

  /**
   * Scans a stylesheet for asset URL references and copies the assets to the build folder.
   * @private
   * @param {string} basePath
   * @param {string} targetPath
   * @param {string} sourceCode
   */
  function scan (basePath, targetPath, sourceCode)
  {
    var match;
    while ((match = MATCH_URLS.exec (sourceCode))) {
      var url = match[2];
      if (!url.match (/^http/i) && url[0] !== '/') { // Skip absolute URLs
        var absSrcPath = path.resolve (basePath, url)
          , absDestPath = path.resolve (targetPath, options.targetDir, url)
          , relDestPath = path.relative (targetPath, absDestPath);
        if (relDestPath[0] === '.')
          return util.warn ('Relative asset url falls outside the build folder: <cyan>%</cyan>%', url, util.NL);
        if (exportedAssets[absDestPath]) // skip already exported asset
          continue;
        else exportedAssets[absDestPath] = true;
        var absTargetFolder = path.dirname (absDestPath);
        grunt.file.mkdir (absTargetFolder);
        if (options.symlink)
          fs.symlinkSync (absSrcPath, absDestPath);
        else grunt.file.copy (absSrcPath, absDestPath);
      }
    }
  }

}
264180
function() {
      var i = 0;
      grunt.log.writeln( 'Ensuring directories:' );

      var ensureDir = function( dir ) {
        grunt.log.ok( options.remoteDir + dir );

        if ( directoriesChecked.indexOf( dir ) > -1 && ((i + 1) < dirs.length) ) {
          directoriesChecked.push( dir );
          i += 1;
          ensureDir( dirs[ i ] );
        } else if ( i >= dirs.length ) {
          uploadFiles();
        } else {
          directoriesChecked.push( dir );
          client
            .raw( 'mkdir -p "' + options.remoteDir + dir + '"' )
            .exec(function( err, res ) {
              if ( err ) {
                grunt.log.error( err );
              }

              if ( (i + 1) < dirs.length ) {
                 i += 1;
                ensureDir( dirs[ i ] );
              } else {
                uploadFiles();
              }
            });
        }
      };

      if ( dirs.length > 0 ) {
        ensureDir( dirs[0] );
      }
    }
1200425
function exports(grunt) {
	'use strict';

	var jsFiles = ['bin/ninejs', '*.js', '**/*.js', '!node_modules/**', '!out/**', '!nineplate/utils/parser/**/commonjs.js', '!nineplate/utils/parser/**/amd.js', '!nineplate/tests/template-generated.js', '!modernizer.js', '!modules/webserver/jsClientUtils/*'],
		testFiles = ['**/tests/**/*.js', '!coverage/**', '!**/tests/**/phantom*.js', '!node_modules/**', '!out/**', '!nineplate/tests/template-generated.js'],
		phantomWatch = ['nineplate/tests/phantomTest.js'],
		stylusFiles = [ '**/*.styl', '!node_modules/**', '!ui/bootstrap/extension.styl' ],
		ncssFiles = ['ui/bootstrap/less/bootstrap.ncss'],
		tsfiles = ['**/*.ts', '!**/*.d.ts', '!node_modules/**/*.ts'],
		Q = require('kew');

	require('load-grunt-tasks')(grunt);
	// Project configuration.
	grunt.initConfig({
		mocha: { //Phantomjs
			index: {
				src: ['nineplate/tests/phantomTest.html']
			}
		},
		mochaTest: {
			normal: {
				src: testFiles,
				options: {
					reporter: 'spec',
					globals: []
				}
			},
			watch: {
				src: testFiles,
				options: {
					reporter: 'spec',
					globals: []
				}
			}
		},
		watch: {
			//jshint : {
			//	files : jsFiles,
			//	tasks : 'jshint'
			//},
			ts: {
				files : tsfiles,
				tasks : 'ts'
			},
			stylus: {
				files: stylusFiles,
				tasks: ['stylus']
			},
			phantom: {
				files: phantomWatch.slice(0).concat(jsFiles),
				tasks: ['mocha']
			}
			//,
			//test: {
			//	files: testFiles.slice(0).concat(jsFiles),
			//	tasks: ['generateParsers', 'mochaTest:watch', 'mocha']
			//}

		},
		stylus:
		{
			files: stylusFiles,
			options:
			{
				urlfunc: 'embedurl', // use embedurl('test.png') in our code to trigger Data URI
				compress: true
			}
		},
		ncss:
		{
			files: ncssFiles,
			options: {}
		},
		exec: {
			less: (process.env.LESS_COMPILER || "node ./node_modules/less/bin/lessc") + " ui/bootstrap/less/bootstrap.less > ui/bootstrap/less/bootstrap.ncss",
			defaultTs : (process.env.TS_COMPILER || "./node_modules/typescript/bin/tsc") + " -p ./tsconfig.json"
		},
		dts_bundle: {
			build: {
				options: {
					name: 'ninejs',
					main: '9js.d.ts',
					exclude: function (n, external) {
						return /*external || (n.indexOf('typings/') >= 0) ||*/ (n.indexOf('node_modules') >= 0);
					},
					prefix: '',
					externals: false,
					referenceExternals: false,
					verbose: false,
					removeSource: false
				}
			}
		},
		globaltsd: {
			options: {
				target: __dirname + '/9js.ts',
				baseDir: __dirname,
				exclude: [
					'ninejs.d.ts',
					'9js.d.ts',
					'typings',
					'node_modules'
				],
				references: [
					'./typings/node/node.d.ts'
				]
			}
		},
		nineplate: {
			html: {
				mode: 'html',
				pattern: '\\.html$',
				src: [
					'ui/css',
					'!ui/tests/logic/FilterBuilder/demo.html',
					'modules'
				]
			},
			css: {
				mode: 'css',
				pattern: '\\.css$',
				extension: 'ncss.js',
				src: [
					'ui',
					'modules'
				]
			}
		}
	});

	grunt.loadNpmTasks('grunt-njs-css');
	grunt.loadNpmTasks('grunt-mocha-test');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.loadNpmTasks('grunt-globaltsd');
	grunt.task.loadTasks('grunt');
	grunt.registerMultiTask('mocha','run Phantomjs tests with Mocha', function() {
		var done = this.async(),
			files = this.filesSrc,
			queues = [],
			command = 'mocha-phantomjs',
			platform = require('os').platform();
		if ((/win/).test(platform)) {
			command += '.cmd';
		}

		files.forEach(function(file) {
			var childProcess = require('child_process'),
				defer = Q.defer();
			queues.push(defer.promise);
			var mochaPhantom = childProcess.spawn(command, [file], { stdio: 'inherit' });
			mochaPhantom.on('exit', function(/*code*/) {
				defer.resolve();
			});
		});
		Q.all(queues).then(function() {
			done();
		});
	});
	grunt.registerTask('tsd','Install TypeScript definitions', function() {
		var done = this.async(),
			command = 'node',
			path = require('path'),
			cliPath = path.resolve(__dirname, 'node_modules', 'tsd', 'build', 'cli.js');

		var childProcess = require('child_process'),
			defer = Q.defer();
		var tsdProcess = childProcess.spawn(command, [cliPath, 'install'], { stdio: 'inherit' });
		tsdProcess.on('exit', function(/*code*/) {
			defer.resolve();
		});
		defer.promise.then(function () {
			done();
		});
	});

	var childProcess = require('child_process'),
			path = require('path');

	grunt.registerMultiTask('nineplate', 'Generates nineplate and css functions', function () {
		console.log('Running nineplate ');
		var done = this.async();
		var files = this.filesSrc;
		var pattern = '';
		var extension = '';
		var data = this.data;
		if (this.data.pattern) {
			pattern = ' --pattern=' + this.data.pattern;
		}
		if (this.data.extension) {
			extension = ' --extension=' + this.data.extension;
		}

		console.log('nineplate ' + files.length + ' files');

		files.forEach(function(file) {
			childProcess.execSync('node ./cli/nineplate.js ' + file + ' --target=amd --mode=' + data.mode + ' --toBase64 --baseUrl=' + path.resolve(process.cwd()) + pattern + extension, {
				stdio: 'inherit'
			});
		});
		done();
	});

	grunt.registerTask('test', ['mochaTest:normal', 'mocha']);
	grunt.registerTask('css', ['less', 'ncss', 'stylus']);
	grunt.registerTask('less', ['exec:less']);
	// Default task.
	grunt.registerTask('default', ['css', 'generateParsers', 'nineplate', 'exec', /*'typedoc', */'test']);

}