Build extensions in build directory, then copy if --inplace
165388
def run(self):
        """"""
        old_inplace, self.inplace = self.inplace, 0
        _build_ext.run(self)
        self.inplace = old_inplace
        if old_inplace:
            self.copy_extensions_to_source()
1116085
def build_paste(uid, shortid, type, nick, time, fmt, code, filename, mime):
        ""
        return locals()
1155491
function copyReadmeFiles() {

    const resolvedSrcReadmePaths = path.resolve(rootDir, srcReadmePaths);

    dryRun ? console.log(`In ${destDir}, this script would...`) : console.log(`In ${destDir}...`);

    fs.readdir('packages', (err, files) => {
        totalDocsCount = files.length;
    });

    createDirectory(destDir);
    glob(resolvedSrcReadmePaths, {realpath:true}, function(error, srcFiles) {
        
        srcFiles.forEach((srcReadmePath) => {    
            createDestReadme(srcReadmePath);
            const srcDirPath = path.dirname(srcReadmePath);
            const lastSrcDir = srcDirPath.split(path.sep).pop();
            sidebarEntries.push(`en/packages/${lastSrcDir}/index`);
        });

        console.log(chalk.green(`${updatedDocsCount} of ${totalDocsCount} package readme.md files updated`));
        updateSidebar();
       
    });

}
595483
function constructIncludedDirectory(data) {
  var defaults, opt, files, splitDirPath, tmp, included,
    src, ext, filename, relfilename, key, work, basepath, fullpath;

  basepath = yamlinc.getBasePath();

  work = {};
  opt = {};
  defaults = {
    whitelist: [],
    blacklist: [],
    allowEmpty: false,
    recursive: true,
    extensions: ['.yaml', '.yml'],
    lowerKeys: false,
    variableIndicator: '~',
    variablePrefix: '{',
    variableSuffix: '}',
    ignoreIndicator: '_',
    ignoreTopLevelDir: true,
    excludeTopLevelDirSeparator: false,
    pathSeparator: '/'
  };

  if (Array.isArray(data[0])) {
    files = data[0];
  } else {
    fullpath = p.join(basepath, data[0]);
    debug('reading %s', fullpath);
    files = recursiveReadSync(fullpath);
    files = files.map(function(filepath) {
      return filepath.replace(basepath + p.sep, '');
    });
    debug('files ', files);
  }

  // sort the by length of filepath
  files.sort(function(a, b) {
    return a.length - b.length;
  });

  if (!data[1]) {
    data[1] = {};
  }

  merge(opt, defaults, data[1]);

  debug('resolved options %j', opt);

  var keepFile = function(filepath) {
    ext = p.extname(filepath);
    if (opt.extensions.indexOf(ext) === -1) {
      debug('skipping disallowed file extension %s: %s', ext, filepath);
      return false;
    }

    filename = p.basename(filepath, ext);

    // check whitelist for filepath and file name
    if (opt.whitelist.indexOf(filepath) !== -1 ||
      opt.whitelist.indexOf(filename) !== -1 ||
      opt.whitelist.indexOf(filename + ext) !== -1) {
      debug('whitelisting %s', filepath);
      return true;
    }

    // if ANY part of the path has an ignorePrefix,
    // skip it
    if (filepath.indexOf('/' + opt.ignoreIndicator) !== -1) {
      debug('ignoring %s', filepath);
      return false;
    }

    // check blacklist for filepath and file name
    if (opt.blacklist.indexOf(filepath) !== -1 ||
      opt.blacklist.indexOf(filename) !== -1 ||
      opt.blacklist.indexOf(filename + ext) !== -1) {
      debug('blacklisting %s', filepath);
      return false;
    }

    // guess we're keeping it!
    debug('keepFile: keeping ' + filepath);
    return true;
  };

  files.forEach(function(filepath) {
    debug('looking at %s', filepath);
    if (!keepFile(filepath)) {
      return;
    }

    splitDirPath = filepath.split('/');
    splitDirPath.pop();

    // we generally don't want the top dir.
    if (opt.ignoreTopLevelDir) {
      splitDirPath.shift();
    }

    if (opt.lowerKeys) {
      filename = filename.toLowerCase();
    }

    // parameterize key
    if (opt.variableIndicator) {
      splitDirPath.forEach(function(element, i, a) {
        if (element.charAt(0) === opt.variableIndicator) {
          a[i] = opt.variablePrefix + element.substr(1) + opt.variableSuffix;
        }
      });
    }

    // get the source at last
    included = {};
    src = fs.readFileSync(p.join(basepath, filepath), 'utf8');
    if (src.length > 0) {
      yamlinc.YAML_VISITED_FILES.push(filepath);
      included = yaml.load(src, {
        schema: yamlinc.YAML_INCLUDE_SCHEMA,
        filename: filepath
      });
    }

    tmp = {};
    if (opt.recursive) {

      key = opt.excludeTopLevelDirSeparator ? '' : opt.pathSeparator;
      key += splitDirPath.join(opt.pathSeparator);
      if (opt.allowEmpty) {
        tmp[key] = {};
        tmp[key][filename] = included;
      } else {
        if (Object.getOwnPropertyNames(included).length > 0) {
          if (key.length > 0) {
            tmp[key] = {};
            tmp[key][filename] = included;
          } else {
            // this implements the opt.excludeTopLevelDirSeparator option when at the top level
            tmp[filename] = included;
          }
        }
      }
    } else {
      if (opt.allowEmpty) {
        tmp[filename] = included;
      } else {
        if (Object.getOwnPropertyNames(included).length > 0) {
          tmp[filename] = included;
        }
      }
    }

    work = merge(work, tmp);
  });
  return new IncludedDirectory(work);
}
1089540
function copyFilesToPack(grunt, buildPath, filesToPack) {
	return function(callback) {
		grunt.util.async.forEach(filesToPack, function(fileConfig, callback) {
			try {
				var filepathDest;
				if (detectDestType(grunt, fileConfig.dest) === 'directory') {
					var dest = (fileConfig.orig.expand) ? fileConfig.dest : path.join(fileConfig.dest, fileConfig.src);
					filepathDest = path.join(buildPath, dest);
				} else {
					filepathDest = path.join(buildPath, fileConfig.dest);
				}

				if (grunt.file.isDir(fileConfig.src)) {
					if (fileConfig.directory) {
						// Copy a whole folder to the destination directory.
						grunt.verbose.writeln('Copying folder "' + fileConfig.src + '" to "' + filepathDest + '"');
						fs.copyRecursive(fileConfig.src, filepathDest, callback);
					} else {
						// Create a folder inside the destination directory.
						grunt.verbose.writeln('Creating folder "' + filepathDest + '"');
						fs.mkdirs(filepathDest, callback);
					}
				} else {
					// Copy a file to the destination directory inside the tmp folder.
					if (fileConfig.link) {
						grunt.verbose.writeln('Copying symlink "' + fileConfig.src + '->' + fileConfig.link + '" to "' + filepathDest + '"');
						//ensure the parent directory exists when making symlinks
						fs.mkdirs(getDirName(filepathDest), function(err) {
							if (err) throw err;
							_fs.symlink(fileConfig.link, filepathDest, 'file', callback);
						});
						
					}
					else {
						grunt.verbose.writeln('Copying file "' + fileConfig.src + '" to "' + filepathDest + '"');
						grunt.file.copy(fileConfig.src, filepathDest);
						fs.lstat(fileConfig.src, function(err, stat) {
							if (err) throw err;
							_fs.chmod(filepathDest, stat.mode, callback);
						});
					}
				}
				
			} catch(e) {
				callback(e);
			}
		}, callback);
	};
}
1117149
def copy_artifacts(app):
    """"""
    dest_path = app.builder.outdir + '/error'
    source_path = app.builder.srcdir + '/build_version_doc/artifacts'
    _run_cmd('cd ' + app.builder.srcdir)
    _run_cmd('rm -rf ' + dest_path)
    _run_cmd('mkdir -p ' + dest_path)
    _run_cmd('cp ' + source_path + '/404.html ' + dest_path)
    _run_cmd('cp ' + source_path + '/api.html ' + dest_path)
    dest_path = app.builder.outdir + '/_static'
    _run_cmd('rm -rf ' + dest_path)
    _run_cmd('mkdir -p ' + dest_path)
    _run_cmd('cp ' + app.builder.srcdir + '/_static/mxnet.css ' + dest_path)
774824
def run_build_lib(folder):
    """"""
    try:
        retcode = subprocess.call("cd %s; make" % folder, shell=True)
        retcode = subprocess.call("rm -rf _build/html/doxygen", shell=True)
        retcode = subprocess.call("mkdir _build", shell=True)
        retcode = subprocess.call("mkdir _build/html", shell=True)
        retcode = subprocess.call("cp -rf doxygen/html _build/html/doxygen", shell=True)
        if retcode < 0:
            sys.stderr.write("build terminated by signal %s" % (-retcode))
    except OSError as e:
        sys.stderr.write("build execution failed: %s" % e)
523700
def find_build_dir(path, build="_build"):
    """"""
    path = os.path.abspath(os.path.expanduser(path))
    contents = os.listdir(path)
    filtered_contents = [directory for directory in contents
                            if os.path.isdir(os.path.join(path, directory))]

    if build in filtered_contents:
        return os.path.join(path, build)
    else:
        if path == os.path.realpath("/"):
            return None
        else:
            return find_build_dir("{0}/..".format(path), build)
747666
function Buildit(opts) {
	opts = opts || {};

	this.cwd = opts.baseUrl || process.cwd();
	this.name = opts.name;
	this.locals = {};
	this.externals = [];

	if (opts.define) {
		this.define = opts.define;
	}

	if (opts.exports) {
		this.exports = opts.exports;
	}

	if (opts.extensions) {
		this.extensions = opts.extensions;
	}
}
754293
def extension
      copy_file 'extension/gitignore', File.join(name, '.gitignore') unless options[:'skip-git']
      template 'extension/Rakefile', File.join(name, 'Rakefile')
      template 'extension/gemspec', File.join(name, "#{name}.gemspec")
      template 'extension/Gemfile', File.join(name, 'Gemfile')
      template 'extension/lib/lib.rb', File.join(name, 'lib', "#{name}.rb")
      template 'extension/lib/lib/extension.rb', File.join(name, 'lib', name, 'extension.rb')
      template 'extension/features/support/env.rb', File.join(name, 'features', 'support', 'env.rb')
      empty_directory File.join(name, 'fixtures')
    end
279955
def in_builddir(sub='.'):
    
    from functools import wraps

    def wrap_in_builddir(func):
        """Wrap the function for the new build directory."""

        @wraps(func)
        def wrap_in_builddir_func(self, *args, **kwargs):
            """The actual function inside the wrapper for the new builddir."""
            p = local.path(self.builddir) / sub
            if not p.exists():
                LOG.error("%s does not exist.", p)

            if p == local.cwd:
                LOG.debug("CWD already is %s", p)
                return func(self, *args, *kwargs)
            with local.cwd(p):
                return func(self, *args, **kwargs)

        return wrap_in_builddir_func

    return wrap_in_builddir
518464
def build(self, context, variant, build_path, install_path, install=False,
              build_type=BuildType.local):
        
        ret = {}

        if self.write_build_scripts:
            # write out the script that places the user in a build env, where
            # they can run bez directly themselves.
            build_env_script = os.path.join(build_path, "build-env")
            create_forwarding_script(build_env_script,
                                     module=("build_system", "custom"),
                                     func_name="_FWD__spawn_build_shell",
                                     working_dir=self.working_dir,
                                     build_path=build_path,
                                     variant_index=variant.index,
                                     install=install,
                                     install_path=install_path)

            ret["success"] = True
            ret["build_env_script"] = build_env_script
            return ret

        # get build command
        command = self.package.build_command

        # False just means no build command
        if command is False:
            ret["success"] = True
            return ret

        def expand(txt):
            root = self.package.root
            install_ = "install" if install else ''
            return txt.format(root=root, install=install_).strip()

        if isinstance(command, basestring):
            if self.build_args:
                command = command + ' ' + ' '.join(map(quote, self.build_args))

            command = expand(command)
            cmd_str = command
        else:  # list
            command = command + self.build_args
            command = map(expand, command)
            cmd_str = ' '.join(map(quote, command))

        if self.verbose:
            pr = Printer(sys.stdout)
            pr("Running build command: %s" % cmd_str, heading)

        # run the build command
        def _callback(executor):
            self._add_build_actions(executor,
                                    context=context,
                                    package=self.package,
                                    variant=variant,
                                    build_type=build_type,
                                    install=install,
                                    build_path=build_path,
                                    install_path=install_path)

            if self.opts:
                # write args defined in ./parse_build_args.py out as env vars
                extra_args = getattr(self.opts.parser, "_rezbuild_extra_args", [])

                for key, value in vars(self.opts).iteritems():
                    if key in extra_args:
                        varname = "__PARSE_ARG_%s" % key.upper()

                        # do some value conversions
                        if isinstance(value, bool):
                            value = 1 if value else 0
                        elif isinstance(value, (list, tuple)):
                            value = map(str, value)
                            value = map(quote, value)
                            value = ' '.join(value)

                        executor.env[varname] = value

        retcode, _, _ = context.execute_shell(command=command,
                                              block=True,
                                              cwd=build_path,
                                              actions_callback=_callback)
        ret["success"] = (not retcode)
        return ret
747059
function addOutProperty(out, directory, extensions) {
	out[directory] = {
		extensions: extensions
	};
	Object.defineProperty(
		out[directory],
		'directory',
		{
			get: function () {
				return Config.fileLoaderDirs[directory];
			},
			set: function (value) {
				Config.fileLoaderDirs[directory] = value;
			},
			enumerable: true,
			configurable: false
		}
	);
	out[directory].directory = out[directory].directory || directory;
}
1026686
def copyFunc(dest, source, env):
    """"""

    if os.path.isdir(source):
        if os.path.exists(dest):
            if not os.path.isdir(dest):
                raise SCons.Errors.UserError("cannot overwrite non-directory `%s' with a directory `%s'" % (str(dest), str(source)))
        else:
            parent = os.path.split(dest)[0]
            if not os.path.exists(parent):
                os.makedirs(parent)
        scons_copytree(source, dest)
    else:
        shutil.copy2(source, dest)
        st = os.stat(source)
        os.chmod(dest, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)

    return 0
96745
def build(self, input_path, output_paths):
        """"""
        for output in output_paths:
            shutil.copy(input_path, output_paths)
1327161
def build_files(outdir):
    """"""
    # Make sure there is actually a configuration file
    config_file_dir = os.path.join(cwd, "config.py")
    if not os.path.exists(config_file_dir):
        sys.exit(
            "There dosen't seem to be a configuration file. Have you run the init command?")
    else:
        sys.path.insert(0, cwd)
        try:
            from config import website_name, website_description, website_language, home_page_list
        except:
            sys.exit(
                "ERROR: Some of the crucial configuration values could not be found! Maybe your config.py is too old. Run 'blended init' to fix.")
        try:
            from config import website_description_long, website_license, website_url, author_name, author_bio, plugins, minify_css, minify_js, custom_variables
        except:
            website_description_long = ""
            website_license = ""
            website_url = ""
            author_name = ""
            author_bio = ""
            plugins = []
            custom_variables = {}
            minify_css = False
            minify_js = False
            print("WARNING: Some of the optional configuration values could not be found! Maybe your config.py is too old. Run 'blended init' to fix.\n")

    # Create the build folder
    build_dir = os.path.join(cwd, outdir)
    if "." not in outdir and ".." not in outdir and "..." not in outdir and "...." not in outdir and "....." not in outdir:
        replace_folder(build_dir)

    # Make sure there is actually a header template file
    header_file_dir = os.path.join(cwd, "templates", "header.html")
    if not os.path.exists(header_file_dir):
        sys.exit(
            "There dosen't seem to be a header template file. You need one to generate.")

    # Make sure there is actually a footer template file
    footer_file_dir = os.path.join(cwd, "templates", "footer.html")
    if not os.path.exists(footer_file_dir):
        sys.exit(
            "There dosen't seem to be a footer template file. You need one to generate.")

    # Open the header and footer files for reading
    header_file = open(header_file_dir, "r")
    footer_file = open(footer_file_dir, "r")

    # Create the HTML page listing
    page_list_item_file = os.path.join(cwd, "templates", "page_list_item.html")
    if not os.path.exists(page_list_item_file):
        page_list = '<ul class="page-list">\n'
        for root, dirs, files in os.walk(os.path.join(cwd, "content")):
            for filename in files:
                top = os.path.dirname(os.path.join(root, filename))
                top2 = top.replace(os.path.join(cwd, "content"), "", 1)
                if platform != "win32":
                    subfolder = top2.replace("/", "", 1)
                else:
                    subfolder = top2.replace("\\", "", 1)

                if subfolder == "":
                    subfolder_link = ""
                else:
                    subfolder_link = subfolder + "/"
                file_modified = time.ctime(
                    os.path.getmtime(os.path.join(root, filename)))
                newFilename = get_html_filename(filename)
                newFilename2 = get_html_clear_filename(filename)
                page_list = page_list + '<li class="page-list-item"><a href="' + subfolder_link + newFilename + \
                    '">' + newFilename2 + '</a><span class="page-list-item-time"> - ' + \
                    str(file_modified) + '</span></li>\n'
        page_list = page_list + '</ul>'
    else:
        with open(page_list_item_file, 'r') as f:
            page_list_item = f.read()

        page_list = ""
        for root, dirs, files in os.walk(os.path.join(cwd, "content")):
            dirs[:] = [d for d in dirs if "_" not in d]
            for filename in files:
                p_content = convert_text(os.path.join(root, filename))
                top = os.path.dirname(os.path.join(root, filename))
                top2 = top.replace(os.path.join(cwd, "content"), "", 1)
                if platform != "win32":
                    subfolder = top2.replace("/", "", 1)
                else:
                    subfolder = top2.replace("\\", "", 1)

                if subfolder == "":
                    subfolder_link = ""
                else:
                    subfolder_link = subfolder + "/"
                file_modified = time.ctime(
                    os.path.getmtime(os.path.join(root, filename)))
                file_modified_day = str(datetime.strptime(
                file_modified, "%a %b %d %H:%M:%S %Y"))[8:10]
                file_modified_year = str(datetime.strptime(
                    file_modified, "%a %b %d %H:%M:%S %Y"))[:4]
                file_modified_month = str(datetime.strptime(
                    file_modified, "%a %b %d %H:%M:%S %Y"))[5:7]
                month_name = calendar.month_name[int(file_modified_month)]
                newFilename = get_html_filename(filename)
                newFilename2 = get_html_clear_filename(filename)

                page_list = page_list + page_list_item.replace("{path}", subfolder_link + newFilename).replace("{name}", newFilename2).replace(
                    "{date}", str(file_modified)).replace("{content}", p_content).replace("{content_short}", p_content[:250] + "...").replace("{day}", file_modified_day).replace("{month}", file_modified_month).replace("{month_name}", month_name).replace("{year}", file_modified_year)

    if home_page_list == "yes" or home_page_list:
        # Open the home page file (index.html) for writing
        home_working_file = open(os.path.join(cwd, outdir, "index.html"), "w")

        home_working_file.write(header_file.read())

        # Make sure there is actually a home page template file
        home_templ_dir = os.path.join(cwd, "templates", "home_page.html")
        if os.path.exists(home_templ_dir):
            home_templ_file = open(home_templ_dir, "r")
            home_working_file.write(home_templ_file.read())
        else:
            print("\nNo home page template file found. Writing page list to index.html")
            home_working_file.write(page_list)

        home_working_file.write(footer_file.read())

        home_working_file.close()

    for root, dirs, files in os.walk(os.path.join(cwd, "content")):
        dirs[:] = [d for d in dirs if "_" not in d]
        for filename in files:
            if not filename.startswith("_"):
                header_file = open(header_file_dir, "r")
                footer_file = open(footer_file_dir, "r")
                newFilename = get_html_filename(filename)

                top = os.path.dirname(os.path.join(root, filename))
                top2 = top.replace(os.path.join(cwd, "content"), "", 1)
                if platform != "win32":
                    subfolder = top2.replace("/", "", 1)
                else:
                    subfolder = top2.replace("\\", "", 1)

                if subfolder == "":
                    currents_working_file = open(
                        os.path.join(cwd, outdir, newFilename), "w")
                else:
                    create_folder(os.path.join(cwd, outdir, subfolder))
                    currents_working_file = open(os.path.join(
                        cwd, outdir, subfolder, newFilename), "w")

                # Write the header
                currents_working_file.write(header_file.read())

                text_cont1 = convert_text(os.path.join(root, filename))

                if "+++++" in text_cont1.splitlines()[1]:
                    page_template_file = text_cont1.splitlines()[0]
                    text_cont1 = text_cont1.replace(
                        text_cont1.splitlines()[0], "")
                    text_cont1 = text_cont1.replace(
                        text_cont1.splitlines()[1], "")
                else:
                    page_template_file = "content_page"

                # Write the text content into the content template and onto the
                # build file
                content_templ_dir = os.path.join(
                    cwd, "templates", page_template_file + ".html")
                if os.path.exists(content_templ_dir):
                    content_templ_file = open(content_templ_dir, "r")
                    content_templ_file1 = content_templ_file.read()
                    content_templ_file2 = content_templ_file1.replace(
                        "{page_content}", text_cont1)
                    currents_working_file.write(content_templ_file2)
                else:
                    currents_working_file.write(text_cont1)

                # Write the footer to the build file
                currents_working_file.write("\n" + footer_file.read())

                # Close the build file
                currents_working_file.close()

    # Find all the nav(something) templates in the `templates` folder and
    # Read their content to the dict
    navs = {}

    for file in os.listdir(os.path.join(cwd, "templates")):
        if "nav" in file:
            nav_cont = open(os.path.join(cwd, "templates", file), "r")
            navs[file.replace(".html", "")] = nav_cont.read()
            nav_cont.close()

    forbidden_dirs = set(["assets", "templates"])
    blended_version_message = "Built with Blended v" + \
        str(app_version)
    build_date = str(datetime.now().date())
    build_time = str(datetime.now().time())
    build_datetime = str(datetime.now())

    # Replace global variables such as site name and language
    for root, dirs, files in os.walk(os.path.join(cwd, outdir)):
        dirs[:] = [d for d in dirs if d not in forbidden_dirs]
        for filename in files:
            if filename != "config.pyc" and filename != "config.py":
                newFilename = get_html_clear_filename(filename)
                page_file = filename.replace(".html", "")
                page_folder = os.path.basename(os.path.dirname(os.path.join(
                    root, filename))).replace("-", "").replace("_", "").title()
                page_folder_orig = os.path.basename(
                    os.path.dirname(os.path.join(root, filename)))
                top = os.path.dirname(os.path.join(root, filename))
                top2 = top.replace(os.path.join(cwd, outdir), "", 1)
                if platform != "win32":
                    subfolder = top2.replace("/", "", 1)
                else:
                    subfolder = top2.replace("\\", "", 1)
                if subfolder == "":
                    subfolder_folder = os.path.join(cwd, outdir, filename)
                else:
                    subfolder_folder = os.path.join(
                        cwd, outdir, subfolder, filename)
                file_modified = time.ctime(
                    os.path.getmtime(os.path.join(root, filename)))
                file_modified_day = str(datetime.strptime(
                    file_modified, "%a %b %d %H:%M:%S %Y"))[8:10]
                file_modified_year = str(datetime.strptime(
                    file_modified, "%a %b %d %H:%M:%S %Y"))[:4]
                file_modified_month = str(datetime.strptime(
                file_modified, "%a %b %d %H:%M:%S %Y"))[5:7]
                month_name = calendar.month_name[int(file_modified_month)]

                # The Loop!
                for line in fileinput.input(subfolder_folder, inplace=1):
                    for var in custom_variables:
                        line = line.replace(
                            "{" + var + "}", custom_variables[var])
                    if len(plugins) != 0:
                        for i in range(len(plugins)):
                            if sys.version_info[0] < 2:
                                main = importlib.import_module(plugins[i])
                            elif sys.version_info[0] < 3:
                                main = __import__(plugins[i])
                            content = main.main()
                            line = line.replace(
                                "{" + plugins[i] + "}", content)
                    if "{nav" in line:
                        navname = line.split("{")[1].split("}")[0]
                        line = line.replace(
                            "{" + navname + "}", navs[(line.split("{"))[1].split("}")[0]])
                    line = line.replace(
                        "{website_description}", website_description)
                    line = line.replace(
                        "{website_description_long}", website_description_long)
                    line = line.replace("{website_license}", website_license)
                    line = line.replace("{website_language}", website_language)
                    line = line.replace("{website_url}", website_url)
                    line = line.replace("{author_name}", author_name)
                    line = line.replace("{author_bio}", author_bio)
                    line = line.replace("{random_number}",
                                        str(randint(0, 100000000)))
                    line = line.replace("{build_date}", build_date)
                    line = line.replace("{build_time}", build_time)
                    line = line.replace("{build_datetime}", build_datetime)
                    line = line.replace("{page_list}", page_list)
                    line = line.replace("{page_name}", newFilename)
                    line = line.replace("{page_filename}", page_file)
                    line = line.replace("{page_file}", filename)
                    line = line.replace("{" + filename + "_active}", "active")
                    if page_folder != outdir.title():
                        line = line.replace("{page_folder}", page_folder)
                    else:
                        line = line.replace("{page_folder}", "")
                    if page_folder_orig != outdir:
                        line = line.replace(
                            "{page_folder_orig}", page_folder_orig)
                    else:
                        line = line.replace("{page_folder_orig}", "")
                    line = line.replace("{page_date}", str(file_modified))
                    line = line.replace("{page_day}", str(file_modified_day))
                    line = line.replace("{page_year}", str(file_modified_year))
                    line = line.replace(
                        "{page_month}", str(file_modified_month))
                    line = line.replace(
                        "{page_month_name}", str(month_name))
                    line = line.replace("{blended_version}", str(app_version))
                    line = line.replace(
                        "{blended_version_message}", blended_version_message)
                    line = line.replace("{website_name}", website_name)
                    top = os.path.join(cwd, outdir)
                    startinglevel = top.count(os.sep)
                    relative_path = ""
                    level = root.count(os.sep) - startinglevel
                    for i in range(level):
                        relative_path = relative_path + "../"
                    line = line.replace("{relative_root}", relative_path)
                    print(line.rstrip('\n'))
                fileinput.close()

    # Copy the asset folder to the build folder
    if os.path.exists(os.path.join(cwd, "templates", "assets")):
        if os.path.exists(os.path.join(cwd, outdir, "assets")):
            shutil.rmtree(os.path.join(cwd, outdir, "assets"))
        shutil.copytree(os.path.join(cwd, "templates", "assets"),
                        os.path.join(cwd, outdir, "assets"))

    for root, dirs, files in os.walk(os.path.join(cwd, outdir, "assets")):
        for file in files:
            if not file.startswith("_"):
                if (file.endswith(".sass")) or (file.endswith(".scss")):
                    sass_text = open(os.path.join(root, file)).read()
                    text_file = open(os.path.join(
                        root, file[:-4] + "css"), "w")
                    if sass_text != "":
                        text_file.write(sass.compile(string=sass_text))
                    else:
                        print(file + " is empty! Not compiling Sass.")
                    text_file.close()
                if file.endswith(".less"):
                    less_text = open(os.path.join(root, file)).read()
                    text_file = open(os.path.join(
                        root, file[:-4] + "css"), "w")
                    if less_text != "":
                        text_file.write(lesscpy.compile(StringIO(less_text)))
                    else:
                        print(file + " is empty! Not compiling Less.")
                    text_file.close()
                if file.endswith(".styl"):
                    try:
                        styl_text = open(os.path.join(root, file)).read()
                        text_file = open(os.path.join(
                            root, file[:-4] + "css"), "w")
                        if styl_text != "":
                            text_file.write(Stylus().compile(styl_text))
                        else:
                            print(file + " is empty! Not compiling Styl.")
                        text_file.close()
                    except:
                        print("Not able to build with Stylus! Is it installed?")
                        try:
                            subprocess.call["npm", "install", "-g", "stylus"]
                        except:
                            print("NPM (NodeJS) not working. Is it installed?")
                if file.endswith(".coffee"):
                    coffee_text = open(os.path.join(root, file)).read()
                    text_file = open(os.path.join(root, file[:-6] + "js"), "w")
                    if coffee_text != "":
                        text_file.write(coffeescript.compile(coffee_text))
                    else:
                        print(file + " is empty! Not compiling CoffeeScript.")
                    text_file.close()
                if minify_css:
                    if file.endswith(".css"):
                        css_text = open(os.path.join(root, file)).read()
                        text_file = open(os.path.join(root, file), "w")
                        if css_text != "":
                            text_file.write(cssmin(css_text))
                        text_file.close()
                if minify_js:
                    if file.endswith(".js"):
                        js_text = open(os.path.join(root, file)).read()
                        text_file = open(os.path.join(root, file), "w")
                        if js_text != "":
                            text_file.write(jsmin(js_text))
                        text_file.close()
597063
def TryCompile( self, text, extension):
        
        return self.TryBuild(self.env.Object, text, extension)