Render and output to a directory given a package specification.
504534
def render_source(output_dir, package_spec):
  
  path, name = package_spec.filepath
  destination_filename = "%s/%s.h" % (output_dir, name)
  py_template = JENV.get_template(MESSAGES_TEMPLATE_NAME)
  with open(destination_filename, 'w') as f:
    f.write(py_template.render(msgs=package_spec.definitions,
                               pkg_name=name,
                               filepath="/".join(package_spec.filepath) + ".yaml",
                               max_msgid_len=package_spec.max_msgid_len,
                               description=package_spec.description,
                               timestamp=package_spec.creation_timestamp,
                               include=extensions(package_spec.includes)))
177758
def render_long_description(self, dirname):
        
        with changedir(dirname):
            self.setuptools.check_valid_package()
            long_description = self.setuptools.get_long_description()
            outfile = abspath('.long-description.html')
            self.docutils.publish_string(long_description, outfile, self.styles)
            return outfile
568993
def print_results(self):
        """"""
        # Updates
        if self.package_data.get('updates'):
            print('\n{}{}Updates:'.format(c.Style.BRIGHT, c.Fore.BLUE))
            for p in self.package_data['updates']:
                print(
                    '{!s:<20}{}{} {!s:<50}'.format(
                        p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, p.get('output')
                    )
                )

        # Packaging
        print('\n{}{}Package:'.format(c.Style.BRIGHT, c.Fore.BLUE))
        for p in self.package_data['package']:
            if isinstance(p.get('output'), list):
                n = 5
                list_data = p.get('output')
                print(
                    '{!s:<20}{}{} {!s:<50}'.format(
                        p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, ', '.join(p.get('output')[:n])
                    )
                )
                del list_data[:n]
                for data in [
                    list_data[i : i + n] for i in range(0, len(list_data), n)  # noqa: E203
                ]:
                    print(
                        '{!s:<20}{}{} {!s:<50}'.format(
                            '', c.Style.BRIGHT, c.Fore.CYAN, ', '.join(data)
                        )
                    )

            else:
                print(
                    '{!s:<20}{}{} {!s:<50}'.format(
                        p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, p.get('output')
                    )
                )

        # Bundle
        if self.package_data.get('bundle'):
            print('\n{}{}Bundle:'.format(c.Style.BRIGHT, c.Fore.BLUE))
            for p in self.package_data['bundle']:
                print(
                    '{!s:<20}{}{} {!s:<50}'.format(
                        p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, p.get('output')
                    )
                )

        # ignore exit code
        if not self.args.ignore_validation:
            print('\n')  # separate errors from normal output
            # print all errors
            for error in self.package_data.get('errors'):
                print('{}{}'.format(c.Fore.RED, error))
                self.exit_code = 1
68392
def main(argv=sys.argv):
    """"""
    parser = setup_parser()

    (opts, args) = parser.parse_args(argv[1:])

    if not args:
        parser.error('A package path is required.')

    rootpath, excludes = args[0], args[1:]
    if not opts.destdir:
        parser.error('An output directory is required.')
    if opts.header is None:
        opts.header = path.normpath(rootpath).split(path.sep)[-1]
    if opts.suffix.startswith('.'):
        opts.suffix = opts.suffix[1:]
    if not path.isdir(rootpath):
        print >>sys.stderr, '%s is not a directory.' % rootpath
        sys.exit(1)
    if not path.isdir(opts.destdir):
        if not opts.dryrun:
            os.makedirs(opts.destdir)
    rootpath = path.normpath(path.abspath(rootpath))
    excludes = normalize_excludes(rootpath, excludes)
    modules = recurse_tree(rootpath, excludes, opts)
    if opts.full:
        from sphinx import quickstart as qs
        modules.sort()
        prev_module = ''
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path = opts.destdir,
            sep  = False,
            dot  = '_',
            project = opts.header,
            author = opts.author or 'Author',
            version = opts.version or '',
            release = opts.release or opts.version or '',
            suffix = '.' + opts.suffix,
            master = 'index',
            epub = True,
            ext_autodoc = True,
            ext_viewcode = True,
            makefile = True,
            batchfile = True,
            mastertocmaxdepth = opts.maxdepth,
            mastertoctree = text,
        )
        if not opts.dryrun:
            qs.generate(d, silent=True, overwrite=opts.force)
    elif not opts.notoc:
        create_modules_toc_file(modules, opts)
99965
def render_template_directory(deck, arguments):
    """"""
    output_directory = dir_name_from_title(deck.title)

    if os.path.exists(output_directory):
        if sys.stdout.isatty():
            if ask(
                '%s already exists, shall I delete it?' % output_directory,
                arguments.get('--noinput')
            ):
                shutil.rmtree(output_directory)
        else:
            shutil.rmtree(output_directory)

    # copy support files to output directory
    template_directory_path = (
        '%s/templates/%s' %
        (remarkable.__path__[0], deck.presentation_type)
    )
    shutil.copytree(
        template_directory_path,
        output_directory,
    )

    # copy resources
    if os.path.exists('resources'):
        log.info('Copying resources')
        shutil.copytree('resources', '%s/resources' % output_directory)
    else:
        log.info('No resources to copy')

    # render template
    template_filename = '%s/index.html' % deck.presentation_type
    html = render_template(template_filename, deck.json)

    # write index to output directory
    index_filename = '%s/index.html' % output_directory
    write_file(index_filename, html)

    return output_directory
415099
def render_archive(entries):
    """"""
    context = GLOBAL_TEMPLATE_CONTEXT.copy()
    context['entries'] = entries
    _render(context, 'archive_index.html',
            os.path.join(CONFIG['output_to'], 'archive/index.html')),
798264
def render(context, locals)
      @context = context
      @pathname = context.pathname
      @directory = File.dirname(@pathname)

      @header  = data[HEADER_PATTERN, 0] || ""
      @body    = $' || data
      # Ensure body ends in a new line
      @body += "\n" if @body != "" && @body !~ /\n\Z/m

      @included_pathnames = []

      @result = ""
      @result.force_encoding(body.encoding)

      @has_written_body = false

      process_directives
      process_source

      @result
    end
634670
function renderAll(files, data, outputDir) {

  for (var i = 0; i < files.length; i++) {
    render(files[i], data, outputDir)
  }

}
695088
def build(content_directory=None, out_directory=None):
    """"""
    content_directory = content_directory or '.'
    out_directory = os.path.abspath(out_directory or default_out_directory)
    repo = require_repo(content_directory)

    # Prevent user mistakes
    if out_directory == '.':
        raise ValueError('Output directory must be different than the source directory: ' + repr(out_directory))
    if os.path.basename(os.path.relpath(out_directory, content_directory)) == '..':
        raise ValueError('Output directory must not contain the source directory: ' + repr(out_directory))

    # TODO: read config
    # TODO: use virtualenv
    # TODO: init and run plugins
    # TODO: process with active theme

    # Collect and copy static files
    files = presentation_files(repo)
    remove_directory(out_directory)
    copy_files(files, out_directory, repo)

    return out_directory
892824
function generatePackageInformation( &$packageInformation, $package, $http, $step, &$persistentData )
    {
        $cssfile = $persistentData['sitecssfile'];
        if ( $cssfile )
            $cssfile = $persistentData['classescssfile'];

        if ( $cssfile )
        {
            $packageInformation['name'] = $cssfile['basename'];
            $packageInformation['summary'] = $cssfile['basename'] . ' site style';
            $packageInformation['description'] = 'A site style called ' . $cssfile['basename'];
        }
    }
372292
def render_source(output_dir, package_spec):
    
    path, name = package_spec.filepath
    destination_filename = '%s/%s.proto' % (output_dir, name)
    pb_template = JENV.get_template(MESSAGES_TEMPLATE_NAME)
    includes = [include[:-5] if include.endswith('.yaml') else include for include in package_spec.includes]
    if 'types' in includes:
        includes.remove('types')
    with open(destination_filename, 'w') as f:
        f.write(pb_template.render(
            name=name,
            package=package_spec.identifier,
            messages=package_spec.definitions,
            includes=includes,
            description=package_spec.description,
        ))
846104
def compile(self, codepath, destpath=None, package=False, run=False, force=False, show_unchanged=True):
        """"""
        with openfile(codepath, "r") as opened:
            code = readfile(opened)

        if destpath is not None:
            destdir = os.path.dirname(destpath)
            if not os.path.exists(destdir):
                os.makedirs(destdir)
            if package is True:
                self.create_package(destdir)

        foundhash = None if force else self.has_hash_of(destpath, code, package)
        if foundhash:
            if show_unchanged:
                logger.show_tabulated("Left unchanged", showpath(destpath), "(pass --force to override).")
            if self.show:
                print(foundhash)
            if run:
                self.execute_file(destpath)

        else:
            logger.show_tabulated("Compiling", showpath(codepath), "...")

            if package is True:
                compile_method = "parse_package"
            elif package is False:
                compile_method = "parse_file"
            else:
                raise CoconutInternalException("invalid value for package", package)

            def callback(compiled):
                if destpath is None:
                    logger.show_tabulated("Compiled", showpath(codepath), "without writing to file.")
                else:
                    with openfile(destpath, "w") as opened:
                        writefile(opened, compiled)
                    logger.show_tabulated("Compiled to", showpath(destpath), ".")
                if self.show:
                    print(compiled)
                if run:
                    if destpath is None:
                        self.execute(compiled, path=codepath, allow_show=False)
                    else:
                        self.execute_file(destpath)

            self.submit_comp_job(codepath, callback, compile_method, code)
7246
def render_table(output_dir, packages, jenv=JENV):
  
  destination_filename = output_dir + "/com/swiftnav/sbp/client/MessageTable.java"
  with open(destination_filename, 'w+') as f:
      print(destination_filename)
      f.write(jenv.get_template(TEMPLATE_TABLE_NAME).render(packages=packages))
16980
def render_to_response(self, context, *args, **kwargs):
        
        preview_outputs = []
        file_outputs = []
        bast_ctx = context
        added = set()

        for output_group, output_files in context['job_info']['file_groups'].items():
            for output_file_content in output_files:
                if output_group:
                    bast_ctx.update({
                        'job_info': context['job_info'],
                        'output_group': output_group,
                        'output_file_content': output_file_content,
                    })
                    preview = render_to_string('wooey/preview/%s.html' % output_group, bast_ctx)
                    preview_outputs.append(preview)

        for file_info in context['job_info']['all_files']:
            if file_info and file_info.get('name') not in added:
                row_ctx = dict(
                    file=file_info,
                    **context
                )
                table_row = render_to_string('wooey/jobs/results/table_row.html', row_ctx)
                file_outputs.append(table_row)
                added.add(file_info.get('name'))

        return JsonResponse({
            'status': context['job_info']['status'].lower(),
            'command': context['job_info']['job'].command,
            'stdout': context['job_info']['job'].get_stdout(),
            'stderr': context['job_info']['job'].get_stderr(),
            'preview_outputs_html': preview_outputs,
            'file_outputs_html': file_outputs,
        })
488513
def process_templates(input_dir, target_dir, context):
    
    if not target_dir.endswith('/'):
        target_dir = "{}/".format(target_dir)
    if not os.path.exists(target_dir):
        LOGGER.info('Creating: {}'.format(target_dir))
        os.makedirs(target_dir)
    replicate_directory_tree(input_dir, target_dir)
    templates = find_templates(input_dir)
    for templ in templates:
        output_file = templ.replace(input_dir, target_dir)
        output_file = output_file[:-len('.mustache')]
        render_template(templ,  output_file, context)
935226
private static File makeOutputFile(String outputDir, String packageName, String className)
        throws IOException {
        
        // Convert the package name to a path
        Pattern pattern=Pattern.compile("\\.");
        Matcher matcher=pattern.matcher(packageName);
        String sepToUse=File.separator;
        if (sepToUse.equals("\\")) {
            sepToUse="\\\\";
        }

        // Try to create the necessary directories
        String directoryPath=outputDir+File.separator+matcher.replaceAll(sepToUse);
        File directory=new File(directoryPath);
        File outputFile=new File(directory, className+".java");
        
        LOG.debug(String.format("Attempting to create output file at %1$s", outputFile.getAbsolutePath()));
        
        try {
            directory.mkdirs();
            outputFile.createNewFile();
        } catch (SecurityException se) {
            throw new IOException(String.format("Can't write to output file %1$s", outputFile.getAbsoluteFile()), se);
        } catch (IOException ioe) {
            throw new IOException(String.format("Can't write to output file %1$s", outputFile.getAbsoluteFile()), ioe);
        }
        
        return outputFile;
    }
698157
private static void generatePackageDiagrams(RootDoc root, Options opt, String outputFolder)
	    throws IOException {
	Set<String> packages = new HashSet<String>();
	for (ClassDoc classDoc : root.classes()) {
	    PackageDoc packageDoc = classDoc.containingPackage();
	    if(!packages.contains(packageDoc.name())) {
		packages.add(packageDoc.name());
    	    OptionProvider view = new PackageView(outputFolder, packageDoc, root, opt);
    	    UmlGraph.buildGraph(root, view, packageDoc);
    	    runGraphviz(opt.dotExecutable, outputFolder, packageDoc.name(), packageDoc.name(), root);
    	    alterHtmlDocs(opt, outputFolder, packageDoc.name(), packageDoc.name(),
    		    "package-summary.html", Pattern.compile("(</[Hh]2>)|(<h1 title=\"Package\").*"), root);
	    }
	}
    }