Ejemplo n.º 1
0
def test_template_configuration_file_base():
    with TemporaryDirectory() as tmpdir:
        dir = Path(tmpdir)
        with (dir / 'a.rtt').open('w') as a:
            a.write(CONFIGURATION_A)
        with (dir / 'b.rtt').open('w') as b:
            b.write(CONFIGURATION_B)
        conf = TemplateConfigurationFile(b.name)
    assert conf.template == MyDocumentTemplate
    header_text = conf.get_variable(PageTemplate, 'header_text',
                                    Var('my_header_text'))
    expected_header_text = SingleStyledText('Configuration B Header')
    assert header_text == expected_header_text
    doc = create_document(conf)
    assert doc.get_option('a') is True
    assert doc.get_option('b') is False
    assert doc.get_option('c') is False
    part_template, = doc.part_templates
    part = part_template.document_part(doc, 'number')
    assert part.template_name == 'contents'
    page = part.new_page(1, new_chapter=False)
    assert page.template_name == 'contents_page'
    assert page.get_config_value('columns', doc) == 1
    assert page.get_config_value('column_spacing', doc) == 1 * PT
    # the retrieved config values have a parent (Header/Footer), so we can't
    # use == but compare their repr (which doesn't include the parent)
    assert (repr(page.get_config_value('header_text',
                                       doc)) == repr(expected_header_text))
    assert (repr(page.get_config_value(
        'footer_text',
        doc)) == repr(Field(PAGE_NUMBER) + ' / ' + Field(NUMBER_OF_PAGES)))
Ejemplo n.º 2
0
def render_rst_file(rst_path, out_filename, reference_path):
    reader = ReStructuredTextReader()
    doctree = reader.parse(rst_path)
    kwargs = {}
    stylesheet_path = rst_path.with_suffix('.rts')
    if stylesheet_path.exists():
        kwargs['stylesheet'] = str(stylesheet_path)
    templconf_path = rst_path.with_suffix('.rtt')
    if templconf_path.exists():
        config = TemplateConfigurationFile(str(templconf_path))
    else:
        config = TemplateConfiguration('rst', template=MinimalTemplate, **kwargs)
        config.variables['paper_size'] = 'a5'
    render_doctree(doctree, out_filename, reference_path, config)
Ejemplo n.º 3
0
def _render_rst(rst_path, doctree, out_filename, reference_path, warnings=[]):
    kwargs = {}
    stylesheet_path = rst_path.with_suffix('.rts')
    if stylesheet_path.exists():
        kwargs['stylesheet'] = str(stylesheet_path)
    templconf_path = rst_path.with_suffix('.rtt')
    if templconf_path.exists():
        config = TemplateConfigurationFile(str(templconf_path))
    else:
        config = TemplateConfiguration('rst',
                                       template=MinimalTemplate,
                                       **kwargs)
        config.variables['paper_size'] = 'a5'
    render_doctree(doctree, out_filename, reference_path, config, warnings)
Ejemplo n.º 4
0
def test_rstdemo(tmpdir):
    config = TemplateConfigurationFile(os.path.join(TEST_DIR, 'rstdemo.rtt'))

    parser = ReStructuredTextReader()
    flowables = parser.parse(os.path.join(TEST_DIR, 'demo.txt'))
    document = config.document(flowables)
    with in_directory(tmpdir.strpath):
        document.render('demo')
        _, _, _, badlinks, _, _ = check_pdf_links('demo.pdf')
        pytest.assume(badlinks == ['table-of-contents'])
        if not diff_pdf(os.path.join(TEST_DIR, 'reference/demo.pdf'),
                        'demo.pdf'):
            pytest.fail('The generated PDF is different from the reference '
                        'PDF.\nGenerated files can be found in {}'
                        .format(tmpdir.strpath))
Ejemplo n.º 5
0
    def template_from_config(self, logger):
        config = self.config
        template_cfg = {}
        if isinstance(config.rinoh_template, str):
            tmpl_path = path.join(self.confdir, config.rinoh_template)
            if path.isfile(tmpl_path):
                base = TemplateConfigurationFile(config.rinoh_template,
                                                 source=self)
                template_cfg['base'] = base
                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

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

        sphinx_config = template_cls.Configuration('Sphinx conf.py options',
                                                   **template_cfg)
        return sphinx_config
Ejemplo n.º 6
0
def test_rstdemo():
    config = TemplateConfigurationFile(TEST_DIR / 'rstdemo.rtt')

    parser = ReStructuredTextReader()
    flowables = parser.parse(TEST_DIR / 'demo.txt')
    document = config.document(flowables)
    out_dir = OUTPUT_DIR / 'rstdemo'
    out_dir.mkdir(parents=True, exist_ok=True)
    pdf_filename = 'demo.pdf'
    _, _, _, _, _, _, ref_outlines = check_pdf_links(TEST_DIR / 'reference'
                                                     / pdf_filename)
    with in_directory(out_dir):
        document.render('demo')
        _, _, _, badlinks, _, _, outlines = check_pdf_links(pdf_filename)
        pytest.assume(badlinks == ['table-of-contents'])
        pytest.assume(ref_outlines == outlines)
        if not diff_pdf(TEST_DIR / 'reference' / 'demo.pdf', 'demo.pdf'):
            pytest.fail('The generated PDF is different from the reference '
                        'PDF.\nGenerated files can be found in {}'
                        .format(out_dir))
Ejemplo n.º 7
0
def test_rstdemo():
    config = TemplateConfigurationFile(TEST_DIR / 'rstdemo.rtt')

    parser = ReStructuredTextReader()
    flowables = parser.parse(TEST_DIR / 'demo.txt')
    document = config.document(flowables)
    out_dir = OUTPUT_DIR / 'rstdemo'
    out_dir.mkdir(parents=True, exist_ok=True)
    pdf_filename = 'demo.pdf'
    _, _, _, _, _, _, ref_outlines = check_pdf_links(TEST_DIR / 'reference' /
                                                     pdf_filename)
    with in_directory(out_dir):
        document.render('demo')
        _, _, _, badlinks, _, _, outlines = check_pdf_links(pdf_filename)
        pytest.assume(badlinks == ['table-of-contents'])
        pytest.assume(ref_outlines == outlines)
        if not diff_pdf(TEST_DIR / 'reference' / 'demo.pdf', 'demo.pdf'):
            pytest.fail(
                'The generated PDF is different from the reference '
                'PDF.\nGenerated files can be found in {}'.format(out_dir))
Ejemplo n.º 8
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
Ejemplo n.º 9
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, 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))
Ejemplo n.º 10
0
from rinoh.frontend.rst import ReStructuredTextReader
from rinoh.strings import Strings
from rinoh.structure import AdmonitionTitles
from rinoh.style import StyleSheet
from rinoh.template import TemplateConfigurationFile


if __name__ == '__main__':
    default_stylesheet = StyleSheet('empty')
    default_stylesheet.write('emtpy')

    strings = Strings(AdmonitionTitles(important='IMPORTANT:',
                                       tip='TIP:'))

    configuration = TemplateConfigurationFile('article.rtt')

    sphinx_stylesheet = configuration['stylesheet'].base
    sphinx_stylesheet.write('sphinx')

    for name in ('demo', 'quickstart', 'FAQ', 'THANKS'):
        parser = ReStructuredTextReader()
        document_tree = parser.parse(name + '.txt')
        document = configuration.document(document_tree)
        document.render(name)
Ejemplo n.º 11
0
from rinoh.frontend.rst import ReStructuredTextReader
from rinoh.strings import Strings
from rinoh.structure import AdmonitionTitles
from rinoh.style import StyleSheet
from rinoh.template import TemplateConfigurationFile

if __name__ == '__main__':
    default_stylesheet = StyleSheet('empty')
    default_stylesheet.write('emtpy')

    strings = Strings(AdmonitionTitles(important='IMPORTANT:', tip='TIP:'))

    configuration = TemplateConfigurationFile('article.rtt')

    sphinx_stylesheet = configuration['stylesheet'].base
    sphinx_stylesheet.write('sphinx')

    for name in ('demo', 'quickstart', 'FAQ', 'THANKS'):
        parser = ReStructuredTextReader()
        document_tree = parser.parse(name + '.txt')
        document = configuration.document(document_tree)
        document.render(name)