예제 #1
0
def template_from_config(config, confdir, warn):
    template_cfg = {}
    if isinstance(config.rinoh_template, str):
        tmpl_path = path.join(confdir, config.rinoh_template)
        if path.isfile(tmpl_path):
            template_cfg['base'] = TemplateConfigurationFile(tmpl_path)
            template_cls = template_cfg['base'].template
        else:
            template_cls = DocumentTemplate.from_string(config.rinoh_template)
    elif isinstance(config.rinoh_template, TemplateConfiguration):
        template_cfg['base'] = config.rinoh_template
        template_cls = config.rinoh_template.template
    else:
        template_cls = config.rinoh_template
    if isinstance(config.rinoh_stylesheet, str):
        stylesheet_path = path.join(confdir, config.rinoh_stylesheet)
        stylesheet = StyleSheet.from_string(stylesheet_path if path.isfile(
            stylesheet_path) else config.rinoh_stylesheet)
    else:
        stylesheet = config.rinoh_stylesheet
    if config.pygments_style is not None:
        if stylesheet is not None:
            base = stylesheet
        elif 'base' in template_cfg:
            base = template_cfg['base']['stylesheet']
        else:
            base = template_cls.stylesheet.default_value
        stylesheet = pygments_style_to_stylesheet(config.pygments_style, base)
    if stylesheet is not None:
        template_cfg['stylesheet'] = stylesheet

    language = config.language
    if language:
        try:
            template_cfg['language'] = Language.from_string(language)
        except KeyError:
            warn('The language "{}" is not supported by rinohtype.'.format(
                language))

    variables = {}
    if config.rinoh_paper_size:
        variables['paper_size'] = config.rinoh_paper_size

    sphinx_config = template_cls.Configuration('Sphinx conf.py options',
                                               **template_cfg)
    sphinx_config.variables.update(variables)
    return sphinx_config
예제 #2
0
def template_from_config(config, confdir, warn):
    template_cfg = {}
    if isinstance(config.rinoh_template, str):
        tmpl_path = path.join(confdir, config.rinoh_template)
        if path.isfile(tmpl_path):
            template_cfg['base'] = TemplateConfigurationFile(tmpl_path)
            template_cls = template_cfg['base'].template
        else:
           template_cls = DocumentTemplate.from_string(config.rinoh_template)
    elif isinstance(config.rinoh_template, TemplateConfiguration):
        template_cfg['base'] = config.rinoh_template
        template_cls = config.rinoh_template.template
    else:
        template_cls = config.rinoh_template
    if isinstance(config.rinoh_stylesheet, str):
        stylesheet_path = path.join(confdir, config.rinoh_stylesheet)
        stylesheet = StyleSheet.from_string(stylesheet_path
                                            if path.isfile(stylesheet_path)
                                            else config.rinoh_stylesheet)
    else:
        stylesheet = config.rinoh_stylesheet
    if config.pygments_style is not None:
        if stylesheet is not None:
            base = stylesheet
        elif 'base' in template_cfg:
            base = template_cfg['base']['stylesheet']
        else:
            base = template_cls.stylesheet.default_value
        stylesheet = pygments_style_to_stylesheet(config.pygments_style, base)
    if stylesheet is not None:
        template_cfg['stylesheet'] = stylesheet

    language = config.language
    if language:
        try:
            template_cfg['language'] = Language.from_string(language)
        except KeyError:
            warn('The language "{}" is not supported by rinohtype.')

    variables = {}
    if config.rinoh_paper_size:
        variables['paper_size'] = config.rinoh_paper_size

    sphinx_config = template_cls.Configuration('Sphinx conf.py options',
                                               **template_cfg)
    sphinx_config.variables.update(variables)
    return sphinx_config
예제 #3
0
 def write_doc(self, docname, doctree, docnames, targetname):
     config = self.config
     suffix, = config.source_suffix
     source_path = os.path.join(self.srcdir, docname + suffix)
     parser = ReStructuredTextReader()
     rinoh_tree = parser.from_doctree(source_path, doctree)
     rinoh_document_template = config.rinoh_document_template
     template = (DocumentTemplate.from_string(rinoh_document_template)
                 if isinstance(rinoh_document_template, str) else
                 rinoh_document_template)
     if isinstance(self.config.rinoh_stylesheet, str):
         stylesheet = StyleSheet.from_string(self.config.rinoh_stylesheet)
     elif self.config.rinoh_stylesheet is None:
         stylesheet = template.Configuration.stylesheet.default_value
     else:
         stylesheet = self.config.rinoh_stylesheet
     if config.pygments_style is not None:
         stylesheet = pygments_style_to_stylesheet(config.pygments_style,
                                                   stylesheet)
     paper_size = config.rinoh_paper_size
     base_config = template.Configuration(paper_size=paper_size,
                                          stylesheet=stylesheet)
     if config.rinoh_template_configuration is not None:
         template_configuration = config.rinoh_template_configuration
         if template_configuration.base is None:
             template_configuration.base = base_config
     else:
         template_configuration = base_config
     rinoh_document = template(rinoh_tree,
                               configuration=template_configuration,
                               backend=pdf)
     extra_indices = StaticGroupedFlowables(self.generate_indices(docnames))
     rinoh_document.insert('indices', extra_indices, 0)
     rinoh_logo = config.rinoh_logo
     if rinoh_logo:
         rinoh_document.metadata['logo'] = rinoh_logo
     rinoh_document.metadata['title'] = doctree.settings.title
     rinoh_document.metadata['subtitle'] = ('Release {}'.format(
         config.release))
     rinoh_document.metadata['author'] = doctree.settings.author
     outfilename = path.join(self.outdir, os_path(targetname))
     ensuredir(path.dirname(outfilename))
     rinoh_document.render(outfilename)
예제 #4
0
파일: __main__.py 프로젝트: wxtim/rinohtype
def main():
    global parser
    args = parser.parse_args()
    do_exit = False
    if args.docs:
        webbrowser.open(DOCS_URL)
        return
    if args.list_templates:
        print('Installed document templates:')
        for name, _ in sorted(DocumentTemplate.installed_resources):
            print('- {}'.format(name))
        do_exit = True
    if args.list_stylesheets:
        print('Installed style sheets:')
        for name, _ in sorted(StyleSheet.installed_resources):
            print('- {}'.format(name))
        do_exit = True
    if args.list_formats:
        print('Supported input file formats:')
        for entry_point, dist in find_entry_points('rinoh.frontends'):
            reader_cls = entry_point.load()
            print('- {} (.{}) [{}]'.format(entry_point.name,
                                           ', .'.join(reader_cls.extensions),
                                           get_distribution_name(dist)))
        do_exit = True
    if args.list_options:
        reader_name, reader_cls = get_reader_by_name(args.list_options)
        if list(reader_cls.supported_attributes):
            print('Options supported by the {} frontend'.format(reader_name))
            for name in reader_cls.supported_attributes:
                attr_def = reader_cls.attribute_definition(name)
                print('- {} ({}): {}. Default: {}'.format(
                    name, attr_def.accepted_type.__name__,
                    attr_def.description, attr_def.default_value))
        else:
            print('The {} frontend takes no options'.format(reader_name))
        do_exit = True
    if args.list_fonts:
        if args.list_fonts is object:
            print('Installed fonts:')
            for typeface, distribution in installed_typefaces():
                print('- {} [{}]'.format(typeface.name, distribution))
                widths = OrderedDict()
                for font in typeface.fonts():
                    widths.setdefault(font.width, []).append(font)
                for width, fonts in widths.items():
                    styles = []
                    for font in fonts:
                        style = FontWeight.to_name(font.weight)
                        if font.slant != FontSlant.UPRIGHT:
                            style = '{}-{}'.format(font.slant, style)
                        styles.append(style)
                    print('   {}: {}'.format(FontWidth.to_name(width),
                                             ', '.join(styles)))
        else:
            display_fonts(args.list_fonts)
        do_exit = True
    if do_exit:
        return

    if args.input is None:
        parser.print_help()
        return

    template_cfg = {}
    variables = {}
    cwd_source = CwdSource()
    if args.stylesheet:
        if os.path.isfile(args.stylesheet):
            stylesheet = StyleSheetFile(args.stylesheet,
                                        matcher=matcher,
                                        source=cwd_source)
        else:
            try:
                stylesheet = StyleSheet.from_string(args.stylesheet)
            except ResourceNotFound as err:
                raise SystemExit("Could not find the Style sheet '{}'. "
                                 "Aborting.\n"
                                 "Run `{} --list-stylesheets` to find out "
                                 "which style sheets are available.".format(
                                     err.resource_name, parser.prog))
        template_cfg['stylesheet'] = stylesheet

    if args.paper:
        try:
            variables['paper_size'] = Paper.from_string(args.paper.lower())
        except ValueError:
            accepted = ', '.join(
                sorted(paper.name for paper in PAPER_BY_NAME.values()))
            raise SystemExit("Unknown paper size '{}'. Must be one of:\n"
                             "   {}".format(args.paper, accepted))

    if not os.path.exists(args.input):
        raise SystemExit('{}: No such file'.format(args.input))
    input_dir, input_filename = os.path.split(args.input)
    input_root, input_ext = os.path.splitext(input_filename)

    if args.output:
        if os.path.isdir(args.output):
            output_path = os.path.join(args.output, input_root)
        else:
            output_path = args.output
    else:
        output_path = input_root

    reader_name, reader_cls = (get_reader_by_name(args.format) if args.format
                               else get_reader_by_extension(input_ext[1:]))
    str_options = dict((part.strip() for part in option.split('=', maxsplit=1))
                       for option, in args.option)
    try:
        options = {}
        for key, str_value in str_options.items():
            attr_def = reader_cls.attribute_definition(key)
            options[key] = attr_def.accepted_type.from_string(str_value)
    except KeyError as e:
        raise SystemExit(
            'The {} frontend does not accept the option {}'.format(
                reader_name, e))
    except ValueError as e:
        raise SystemExit("The value passed to the '{}' option is not valid:\n"
                         '  {}'.format(key, e))
    reader = reader_cls(**options)

    if os.path.isfile(args.template):
        template_cfg['base'] = TemplateConfigurationFile(args.template,
                                                         source=cwd_source)
        template_cls = template_cfg['base'].template
    else:
        template_cls = DocumentTemplate.from_string(args.template)
    configuration = template_cls.Configuration('rinoh command line options',
                                               **template_cfg)
    configuration.variables.update(variables)

    document_tree = reader.parse(args.input)
    document = template_cls(document_tree, configuration=configuration)
    while True:
        try:
            success = document.render(output_path)
            if not success:
                raise SystemExit('Rendering completed with errors')
            break
        except ResourceNotFound as err:
            if args.install_resources:
                print(
                    "Attempting to the install the '{}' {} from PyPI:".format(
                        err.resource_name, err.resource_type.title()))
                success = Typeface.install_from_pypi(err.entry_point_name)
                if not success:
                    raise SystemExit(
                        "No '{}' {} found on PyPI. Aborting.".format(
                            err.resource_name, err.resource_type))
            else:
                raise SystemExit(
                    "{} '{}' not installed. Consider passing the "
                    "--install-resources command line option.".format(
                        err.resource_type.title(), err.resource_name))
예제 #5
0
def main():
    global parser
    args = parser.parse_args()
    do_exit = False
    if args.docs:
        webbrowser.open(DOCS_URL)
        return
    if args.list_templates:
        print('Installed document templates:')
        for name, _ in sorted(DocumentTemplate.installed_resources):
            print('- {}'.format(name))
        do_exit = True
    if args.list_stylesheets:
        print('Installed style sheets:')
        for name, _ in sorted(StyleSheet.installed_resources):
            print('- {}'.format(name))
        do_exit = True
    if args.list_formats:
        print('Supported input file formats:')
        for entry_point in iter_entry_points('rinoh.frontends'):
            reader_cls = entry_point.load()
            distribution = get_distribution_str(entry_point)
            print('- {} (.{}) [{}]'
                  .format(entry_point.name, ', .'.join(reader_cls.extensions),
                          distribution))
        do_exit = True
    if args.list_options:
        reader_name, reader_cls = get_reader_by_name(args.list_options)
        if list(reader_cls.supported_attributes):
            print('Options supported by the {} frontend'.format(reader_name))
            for name in reader_cls.supported_attributes:
                attr_def = reader_cls.attribute_definition(name)
                print('- {} ({}): {}. Default: {}'
                      .format(name, attr_def.accepted_type.__name__,
                              attr_def.description, attr_def.default_value))
        else:
            print('The {} frontend takes no options'.format(reader_name))
        do_exit = True
    if args.list_fonts:
        if args.list_fonts is object:
            print('Installed fonts:')
            for typeface, distribution in installed_typefaces():
                print('- {} [{}]' .format(typeface.name, distribution))
                widths = OrderedDict()
                for font in typeface.fonts():
                    widths.setdefault(font.width, []).append(font)
                for width, fonts in widths.items():
                    styles = []
                    for font in fonts:
                        style = font.weight.title()
                        if font.slant != FontSlant.UPRIGHT:
                            style = '{}-{}'.format(font.slant.title(), style)
                        styles.append(style)
                    print('   {}: {}'.format(width.title(), ', '.join(styles)))
        else:
            display_fonts(args.list_fonts)
        do_exit = True
    if do_exit:
        return

    if args.input is None:
        parser.print_help()
        return

    template_cfg = {}
    variables = {}
    if args.stylesheet:
        if os.path.isfile(args.stylesheet):
            stylesheet = StyleSheetFile(args.stylesheet, matcher=matcher)
        else:
            try:
                stylesheet = StyleSheet.from_string(args.stylesheet)
            except ResourceNotInstalled as err:
                raise SystemExit("Could not find the Style sheet '{}'. "
                                 "Aborting.\n"
                                 "Run `{} --list-stylesheets` to find out "
                                 "which style sheets are available."
                                 .format(err.resource_name, parser.prog))
        template_cfg['stylesheet'] = stylesheet

    if args.paper:
        try:
            variables['paper_size'] = Paper.from_string(args.paper.lower())
        except ValueError:
            accepted = ', '.join(sorted(paper.name for paper
                                        in PAPER_BY_NAME.values()))
            raise SystemExit("Unknown paper size '{}'. Must be one of:\n"
                             "   {}".format(args.paper, accepted))

    if not os.path.exists(args.input):
        raise SystemExit('{}: No such file'.format(args.input))
    input_dir, input_filename = os.path.split(args.input)
    input_root, input_ext = os.path.splitext(input_filename)
    reader_name, reader_cls = (get_reader_by_name(args.format) if args.format
                               else get_reader_by_extension(input_ext[1:]))
    str_options = dict((part.strip() for part in option.split('=', maxsplit=1))
                       for option, in args.option)
    try:
        options = {}
        for key, str_value in str_options.items():
            attr_def = reader_cls.attribute_definition(key)
            options[key] = attr_def.accepted_type.from_string(str_value)
    except KeyError as e:
        raise SystemExit('The {} frontend does not accept the option {}'
                         .format(reader_name, e))
    except ValueError as e:
        raise SystemExit("The value passed to the '{}' option is not valid:\n"
                         '  {}'.format(key, e))
    reader = reader_cls(**options)

    if os.path.isfile(args.template):
        template_cfg['base'] = TemplateConfigurationFile(args.template)
        template_cls = template_cfg['base'].template
    else:
        template_cls = DocumentTemplate.from_string(args.template)
    configuration = template_cls.Configuration('rinoh command line options',
                                               **template_cfg)
    configuration.variables.update(variables)

    document_tree = reader.parse(args.input)
    document = template_cls(document_tree, configuration=configuration)
    while True:
        try:
            success = document.render(input_root)
            if not success:
                raise SystemExit('Rendering completed with errors')
            break
        except ResourceNotInstalled as err:
            not_installed_msg = ("{} '{}' not installed."
                                 .format(err.resource_type.title(),
                                         err.resource_name))
            if args.install_resources:
                print(not_installed_msg + ' Attempting to install it from '
                                          'PyPI...')
                success = Typeface.install_from_pypi(err.entry_point_name)
                if not success:
                    raise SystemExit("No '{}' {} found on PyPI. Aborting."
                                     .format(err.resource_name,
                                             err.resource_type))
            else:
                raise SystemExit(not_installed_msg + " Consider passing the "
                                 "--install-resources command line option.")
예제 #6
0
파일: tool.py 프로젝트: calve/rinohtype
def main():
    global parser
    args = parser.parse_args()
    do_exit = False
    if args.list_templates:
        print('Installed document templates:')
        for name in sorted(DocumentTemplate.installed_resources):
            print('- {}'.format(name))
        do_exit = True
    if args.list_stylesheets:
        print('Installed style sheets:')
        for name in sorted(StyleSheet.installed_resources):
            print('- {}'.format(name))
        do_exit = True
    if do_exit:
        return

    try:
        input_dir, input_filename = os.path.split(args.input)
    except AttributeError:
        parser.print_help()
        return

    kwargs = {}
    if args.stylesheet:
        if os.path.exists(args.stylesheet):
            stylesheet = StyleSheetFile(args.stylesheet, matcher=matcher)
        else:
            try:
                stylesheet = StyleSheet.from_string(args.stylesheet)
            except ResourceNotInstalled as err:
                raise SystemExit("Could not find the Style sheet '{}'. "
                                 "Aborting.\n"
                                 "Run `{} --list-stylesheets` to find out "
                                 "which style sheets are available.".format(
                                     err.resource_name, parser.prog))
        kwargs['stylesheet'] = stylesheet

    try:
        kwargs['paper_size'] = getattr(paper, args.paper.upper())
    except AttributeError:
        print("Unknown paper size '{}'. Must be one of:".format(args.paper))
        print('   A0, A1, ..., A10, letter, legal, junior_legal, ledger, '
              'tabloid')
        return

    input_root, input_ext = os.path.splitext(input_filename)
    if input_dir:
        os.chdir(input_dir)

    parser = ReStructuredTextReader()
    with open(input_filename) as input_file:
        document_tree = parser.parse(input_file)

    template = DocumentTemplate.from_string(args.template)
    configuration = template.Configuration(**kwargs)
    document = template(document_tree,
                        configuration=configuration,
                        backend=pdf)

    while True:
        try:
            document.render(input_root)
            break
        except ResourceNotInstalled as err:
            print("Typeface '{}' not installed. Attempting to install it from "
                  "PyPI...".format(err.resource_name))
            # answer = input()
            success = Typeface.install_from_pypi(err.entry_point_name)
            if not success:
                raise SystemExit(
                    "No '{}' typeface found on PyPI. Aborting.".format(
                        err.resource_name))