Template in place plugin.

@param {Object} files
@param {Metalsmith} metalsmith
@param {Function} done
557016
function renderTemplateFiles (skipInterpolation) {
  skipInterpolation = typeof skipInterpolation === 'string'
    ? [skipInterpolation]
    : skipInterpolation;
  return (files, metalsmith, done) => {
    const keys = Object.keys(files);
    const metalsmithMetadata = metalsmith.metadata();
    async.each(keys, (file, next) => {
      // skipping files with skipInterpolation option
      if (skipInterpolation && multimatch([file], skipInterpolation, { dot: true }).length) {
        return next();
      }
      const rawFileName = file;
      const rawBuffer = files[file];
      const contents = rawBuffer.contents.toString();
      // do not attempt to render files that do not have mustaches
      if (!/{{([^{}]+)}}/g.test(contents) && !/{{([^{}]+)}}/g.test(file)) {
        return next();
      }

      // first replace filename
      render(file, metalsmithMetadata, (err, res) => {
        if (err) {
          err.message = `[${file}] ${err.message}`;
          return next(err);
        }
        file = res;
        // second replace file contents
        render(contents, metalsmithMetadata, (err, res) => {
          if (err) {
            err.message = `[${file}] ${err.message}`;
            return next(err);
          }
          files[file] = rawBuffer;
          files[file].contents = new Buffer(res);

          // delete old buffer
          if (rawFileName !== file) {
            files[rawFileName] = null;
            delete files[rawFileName];
          }
          next();
        });
      });
    }, done);
  };
}
838532
function mochaStandard (done) {
  var standard = require(mochaStandard.module)

  var files = this.files || []
  var options = this.options || {}

  standard.lintFiles(files, options, function (err, res) {
    if (err) return done(err)
    if (res.errorCount === 0 && res.warningCount === 0) return done()
    done(errorify(res))
  })
}
387989
function plugin() {
	return function (files, metalsmith, done) {
		Object.keys(files).forEach(function (file) {
			setImmediate(done);

			var pathslash = process.platform === 'win32' ? '\\' : '/';
			var rootPath = '';

			var levels = needles(file, pathslash);
			for (var i = 0; i < levels; i++) {
				rootPath += '../';
			}
			files[file].rootPath = rootPath;
		});
	};
}
868470
function do_load(file, name) {
		var name = name || file;
		if(!file) throw new Error("file not defined");
		var c = do_compile(file, name);
		dust.loadSource(c);
		if(_debug) console.log("[dustfs] [" + name + "] Template loaded: " + file);
		return c;
	}
164258
function generateUtilityFiles(next) {
    fs.copy(path.join(getConfig('template.folder'), 'index.js'), path.join(getConfig('output.folder'), 'index.js'), function (err) {
        if (err) { next(err); return; }
        if (getConfig('output.log')) { logger.info('(Created) Index file: ' + path.resolve(path.join(getConfig('output.folder'), 'index.js'))); }
        fs.copy(path.join(getConfig('template.folder'), '..', 'utils.js'), path.join(getConfig('output.folder'), 'utils.js'), function (err) {
            if (err) { next(err); return; }
            next(null);
        });
    });
    try {
        overriddenAliases = require(path.join(process.cwd(), getConfig('output.folder'), 'alias.json'));
    } catch (ignore) {}
}
178331
function cover( done ) {
	gulp.src( [ './src/**/*.js' ] )
		.pipe( istanbul() )
		.pipe( istanbul.hookRequire() )
		.on( 'finish', function() {
			done( runSpecs() );
		} );
}
1287221
function processFile(sourcePath, templates, customPartialName, files) {
  return (file, callback) => {
    const layout = templates.layouts[file.meta.layout];
    const fns = wrapFunctions(templates.fns, file, files);
    const context = Object.assign({}, file.meta, fns);
    async.waterfall([
      cb => getPartials(file, sourcePath, templates, customPartialName, cb),
      (partials, cb) => render(file, layout, context, partials, cb),
    ], (error, result) => {
      const data = result;
      async.nextTick(callback, error, Object.assign({}, file, { data }));
    });
  };
}
1321194
function View_preloadTemplates(dir) {
            var list, name;
            if (this.isDir(dir)) {
                list = this.readDir(dir);
                while (true) {
                    name = list.shift();
                    if (!name) {
                        break;
                    }
                    this.preloadTemplates(di.normalizePath(dir + '/' + name));
                }

            } else if (this.isFile(dir) && this.suffix.test(dir)) {
                process.nextTick(function compileTemplateAsync() {
                    this.setPreloaded(dir, this.swig.compileFile(dir));
                }.bind(this));
            }
        }
1027442
function done(err, template) {

    // cache
    if (options && options.cache && template) {
      cache.set(filename, template);
    }

    if (isAsync) {
      callback(err, template);
    }

    return template;
  }
218508
function(props) {
        var files = {};
        // Include all template files by default.
        helpers.expand({filter: 'isFile', dot: true}, [pathPrefix + '**']).forEach(function(obj) {
          // Get the source filepath relative to the template root.
          var src = obj.rel.slice(pathPrefix.length);
          // Get the destination filepath.
          var dest = init.renames[src];
          // Create a property for this file, but use src if dest evaulates
          // to false
          var processed = (dest) ? grunt.template.process(dest, {data: props, delimiters: 'init'}) : false;
          processed = (processed === 'false' || processed === '') ? false : processed;
          files[(processed) ? processed : src] = obj.rel;
        });
        // Exclude files with a value of false in rename.json.
        var exclusions = Object.keys(init.renames).filter(function(key) {
          var processed = (init.renames[key]) ? 
            grunt.template.process(init.renames[key], {data: props, delimiters: 'init'}) : false;
          processed = (processed === 'false' || processed === '') ? false : processed;
          return (processed === false);
        }).map(function(key) {
          return pathPrefix + key;
        });
        // Exclude all exclusion files by deleting them from the files object.
        if (exclusions.length > 0) {
          helpers.expand({filter: 'isFile', dot: true}, exclusions).forEach(function(obj) {
            // Get the source filepath relative to the template root.
            var src = obj.rel.slice(pathPrefix.length);
            // And remove that file from the files list.
            delete files[src];
          });
        }
        return files;
      }
9605
function generateDemoHtml(done) {
			if (!o.htmlDemo) {
				done();
				return;
			}

			var context = prepareHtmlTemplateContext();

			// Generate HTML
			var demoTemplate = readTemplate(o.htmlDemoTemplate, 'demo', '.html');
			var demo = renderTemplate(demoTemplate, context);

			mkdirp(getDemoPath(), function(err) {
				if (err) {
					logger.log(err);
					return;
				}
				// Save file
				fs.writeFileSync(getDemoFilePath(), demo);
				done();
			});

		}
364696
function(files, metalsmith, done){
            var yuiDocsData = require('../docs/data.json');

            var makeUrl = function(docClass, method){
                var out = '/docs/classes/' + docClass + '.html';
                if(method){
                    out += '#method_' + method;
                }
                return out;
            };

            for(var key in files){
                var file = files[key];
                if(file.docs_class){
                    file.yui_class_data = yuiDocsData.classes[file.docs_class];
                    if(file.docs_method){
                        file.yui_method_url = makeUrl(file.docs_class) + '#method_' + file.docs_class;
                    }
                }
                var relatedDocs = file.related_methods;
                var relatedDocsFormatted = [];
                if(relatedDocs){
                    relatedDocs.forEach(function(doc){
                        if(doc.indexOf('.') !== -1){
                            var arr = doc.split('.');
                            relatedDocsFormatted.push({
                                name: arr[0] + '.prototype.' + arr[1] + '()',
                                class: arr[0],
                                method: arr[1],
                                url: makeUrl(arr[0], arr[1])
                            });
                        } else {
                            relatedDocsFormatted.push({
                                name: doc + '()',
                                class: doc,
                                url: makeUrl(doc)
                            });
                        }
                    });
                    file.related_docs = relatedDocsFormatted;
                }
            }
            done();
        }
337900
function compile( $compiled_template_filename = '' )
		{
			if (empty($this->template))
			{
				return;
			}
			/* Quick hack to allow subtemplates */
			if(eregi("<!-- INCLUDE", $this->template))
			{
				while ($this->count_subtemplates() > 0)
				{
					preg_match_all('/<!-- INCLUDE ([a-zA-Z0-9_.]+) -->/', $this->template, $tvar);
					foreach($tvar[1] as $subfile)
					{
						if(file_exists($this->template_dir . "/$subfile"))
						{
							$subst = implode('',file($this->template_dir . "/$subfile"));
						}
						else
						{
							$subst = 'SmartTemplate Parser Error: Subtemplate not found: \''.$subfile.'\'';
						}
						$this->template = str_replace("<!-- INCLUDE $subfile -->", $subst, $this->template);
					}
				}
			}
			//	END, ELSE Blocks
			$page  =  preg_replace("/<!-- ENDIF.+?-->/",  "<?php\n}\n?>",  $this->template);
			$page  =  preg_replace("/<!-- END[ a-zA-Z0-9_.]* -->/",  "<?php\n}\n\$_obj=\$_stack[--\$_stack_cnt];}\n?>",  $page);
			$page  =  str_replace("<!-- ELSE -->",  "<?php\n} else {\n?>",  $page);

			//	'BEGIN - END' Blocks
			if (preg_match_all('/<!-- BEGIN ([a-zA-Z0-9_.]+) -->/', $page, $var))
			{
				foreach ($var[1] as $tag)
				{
					list($parent, $block)  =  $this->var_name($tag);
					$code  =  "<?php\n"
							. "if (!empty(\$$parent"."['$block'])){\n"
							. "if (!is_array(\$$parent"."['$block']))\n"
							. "\$$parent"."['$block']=array(array('$block'=>\$$parent"."['$block']));\n"
							. "\$_tmp_arr_keys=array_keys(\$$parent"."['$block']);\n"
							. "if (\$_tmp_arr_keys[0]!='0')\n"
							. "\$$parent"."['$block']=array(0=>\$$parent"."['$block']);\n"
							. "\$_stack[\$_stack_cnt++]=\$_obj;\n"
							. "foreach (\$$parent"."['$block'] as \$rowcnt=>\$$block) {\n"
							. "\$$block"."['ROWCNT']=\$rowcnt;\n"
							. "\$$block"."['ALTROW']=\$rowcnt%2;\n"
							. "\$$block"."['ROWBIT']=\$rowcnt%2;\n"
							. "\$_obj=&\$$block;\n?>";
					$page  =  str_replace("<!-- BEGIN $tag -->",  $code,  $page);
				}
			}

			//	'IF nnn=mmm' Blocks
			if (preg_match_all('/<!-- (ELSE)?IF ([a-zA-Z0-9_.]+)[ ]*([!=<>]+)[ ]*(["]?[^"]*["]?) -->/', $page, $var))
			{
				foreach ($var[2] as $cnt => $tag)
				{
					list($parent, $block)  =  $this->var_name($tag);
					$cmp   =  $var[3][$cnt];
					$val   =  $var[4][$cnt];
					$else  =  ($var[1][$cnt] == 'ELSE') ? '} else' : '';
					if ($cmp == '=')
					{
						$cmp  =  '==';
					}
					
					if (preg_match('/"([^"]*)"/',$val,$matches))
					{
						$code  =  "<?php\n$else"."if (\$$parent"."['$block'] $cmp \"".$matches[1]."\"){\n?>";
					}
					elseif (preg_match('/([^"]*)/',$val,$matches))
					{
						list($parent_right, $block_right)  =  $this->var_name($matches[1]);
						$code  =  "<?php\n$else"."if (\$$parent"."['$block'] $cmp \$$parent_right"."['$block_right']){\n?>";
					}
					
					$page  =  str_replace($var[0][$cnt],  $code,  $page);
				}
			}

			//	'IF nnn' Blocks
			if (preg_match_all('/<!-- (ELSE)?IF ([a-zA-Z0-9_.]+) -->/', $page, $var))
			{
				foreach ($var[2] as $cnt => $tag)
				{
					$else  =  ($var[1][$cnt] == 'ELSE') ? '} else' : '';
					list($parent, $block)  =  $this->var_name($tag);
					$code  =  "<?php\n$else"."if (!empty(\$$parent"."['$block'])){\n?>";
					$page  =  str_replace($var[0][$cnt],  $code,  $page);
				}
			}

			//	Replace Scalars
			if (preg_match_all('/{([a-zA-Z0-9_. >]+)}/', $page, $var))
			{
				foreach ($var[1] as $fulltag)
				{
					//	Determin Command (echo / $obj[n]=)
					list($cmd, $tag)  =  $this->cmd_name($fulltag);

					list($block, $skalar)  =  $this->var_name($tag);
					$code  =  "<?php\n$cmd \$$block"."['$skalar'];\n?>\n";
					$page  =  str_replace('{'.$fulltag.'}',  $code,  $page);
				}
			}


			//	ROSI Special: Replace Translations
			if (preg_match_all('/<"([a-zA-Z0-9_.]+)">/', $page, $var))
			{
				foreach ($var[1] as $tag)
				{
					list($block, $skalar)  =  $this->var_name($tag);
					$code  =  "<?php\necho gettext('$skalar');\n?>\n";
					$page  =  str_replace('<"'.$tag.'">',  $code,  $page);
				}
			}


			//	Include Extensions
			$header = '';
			if (preg_match_all('/{([a-zA-Z0-9_]+):([^}]*)}/', $page, $var))
			{
				foreach ($var[2] as $cnt => $tag)
				{
					//	Determin Command (echo / $obj[n]=)
					list($cmd, $tag)  =  $this->cmd_name($tag);

					$extension  =  $var[1][$cnt];
					if (!isset($this->extension_tagged[$extension]))
					{
						$header  .=  "include_once \"smarttemplate_extensions/smarttemplate_extension_$extension.php\";\n";
						$this->extension_tagged[$extension]  =  true;
					}
					if (!strlen($tag))
					{
						$code  =  "<?php\n$cmd smarttemplate_extension_$extension();\n?>\n";
					}
					elseif (substr($tag, 0, 1) == '"')
					{
						$code  =  "<?php\n$cmd smarttemplate_extension_$extension($tag);\n?>\n";
					}
					elseif (strpos($tag, ','))
					{
						list($tag, $addparam)  =  explode(',', $tag, 2);
						list($block, $skalar)  =  $this->var_name($tag);
						if (preg_match('/^([a-zA-Z_]+)/', $addparam, $match))
						{
							$nexttag   =  $match[1];
							list($nextblock, $nextskalar)  =  $this->var_name($nexttag);
							$addparam  =  substr($addparam, strlen($nexttag));
							$code  =  "<?php\n$cmd smarttemplate_extension_$extension(\$$block"."['$skalar'],\$$nextblock"."['$nextskalar']"."$addparam);\n?>\n";
						}
						else
						{
							$code  =  "<?php\n$cmd smarttemplate_extension_$extension(\$$block"."['$skalar'],$addparam);\n?>\n";
						}
					}
					else
					{
						list($block, $skalar)  =  $this->var_name($tag);
						$code  =  "<?php\n$cmd smarttemplate_extension_$extension(\$$block"."['$skalar']);\n?>\n";
					}
					$page  =  str_replace($var[0][$cnt],  $code,  $page);
				}
			}

			//	Add Include Header
			if (isset($header) && !empty($header))
			{
				$page  =  "<?php\n$header\n?>$page";
			}

			//	Store Code to Temp Dir
			if (strlen($compiled_template_filename))
			{
		        if ($hd  =  fopen($compiled_template_filename,  "w"))
		        {
			        fwrite($hd,  $page);
			        fclose($hd);
			        return true;
			    }
			    else
			    {
			    	$this->error  =  "Could not write compiled file.";
			        return false;
			    }
			}
			else
			{
				return $page;
			}
		}
807400
function(files, props, options) {
        options = grunt.utils._.defaults(options || {}, {
          process: function(contents) {
            return grunt.template.process(contents, props, 'init');
          }
        });
        Object.keys(files).forEach(function(destpath) {
          var o = Object.create(options);
          var srcpath = files[destpath];
          // If srcpath is relative, match it against options.noProcess if
          // necessary, then make srcpath absolute.
          var relpath;
          if (srcpath && !grunt.file.isPathAbsolute(srcpath)) {
            if (o.noProcess) {
              relpath = srcpath.slice(pathPrefix.length);
              o.noProcess = grunt.file.isMatch(o.noProcess, relpath);
            }
            srcpath = grunt.task.getFile(srcpath);
          }
          // Copy!
          init.copy(srcpath, destpath, o);
        });
      }
842852
function createFiles (files, argv, templates, cb) {
  if (!templates) {
    const parent = path.resolve(module.parent.filename)
    templates = path.join(parent, '../templates')
  }

  const dir = argv.directory
  parallel(files.map(mapFn), cb)

  function mapFn (file) {
    const tempDir = path.resolve(templates)
    const inFile = path.join(tempDir, file.replace(/^\./, '_.'))
    const outFile = path.resolve(path.join(dir, file))

    return function (done) {
      fs.createReadStream(inFile)
        .pipe(through(transform))
        .pipe(fs.createWriteStream(outFile))
        .on('error', done)
        .on('finish', function () {
          process.stdout.write('write: ' + outFile + '\n')
          done()
        })

      function transform (chunk, enc, cb) {
        const str = chunk.toString()
        const mt = mustache.render(str, argv)
        cb(null, mt)
      }
    }
  }
}
1344158
function remove(file, options, done) {
    if (arguments.length === 2 && 'function' === typeof options) {
        done = options;
        options = {};
    }

    if ('function' !== typeof done) {
        done = function() {};
    }

    function callfile(file, stats, done) {
        fs.unlink(file, done);
    }

    function calldir(dir, stats, files, state, done) {
        if (state === 'end') {
            if (options.empty && dir === file) {
                done();
            } else {
                if (stats.isSymbolicLink()) {
                    fs.unlink(dir, done);
                } else {
                    fs.rmdir(dir, function(er) {
                        if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) {
                            // try in few time, last deletion is not completely ended
                            setTimeout(function() {
                                fs.rmdir(dir, done);
                            }, 10);
                        } else {
                            done(er);
                        }
                    });
                }
            }
        } else {
            done();
        }
    }

    options = Object.assign({
        fs: fs,
        resolve: true,
        followSymlink: false
    }, options);

    _explore(file, callfile, calldir, options, done);
}
151442
function plugin(options){
  options = options || {};
  var keys = options.keys || [];

  return function(files, metalsmith, done){
    setImmediate(done);
    Object.keys(files).forEach(function(file){
      debug('checking file: %s', file);
      if (!isHtml(file)) return;
      var data = files[file];
      var dir = dirname(file);
      var html = basename(file, extname(file)) + '.html';
      if ('.' != dir) html = dir + '/' + html;

      debug('Encoding html entities in file: %s', file);

      var reg = /\`\`\`([\s\S]+?)\`\`\`/gi;
      var rep = function(match, group) {
        if (group) {
          return he.encode(group, {useNamedReferences: true});
        }
        else {
          return "";
        }
      };
      var encoded = data.contents.toString().replace(reg, rep);
      data.contents = new Buffer(encoded);

      keys.forEach(function(key) {
        data[key] = data[key].replace(reg, rep);
      });

      delete files[file];
      files[html] = data;
    });
  };
}