Beispiel #1
0
 def _pytis_help(self, resource_dirs):
     image_dir = os.path.join(config.help_dir, 'img')
     resource_provider = lcg.ResourceProvider(dirs=[image_dir] + resource_dirs)
     def clone(node, node_id):
         # Clone the content node, but force `id' to help URI and `foldable' to True.
         return lcg.ContentNode(node_id, title=node.title(), descr=node.descr(),
                                content=node.content(), hidden=node.hidden(),
                                children=[clone(n, 'help:pytis/'+n.id()) for n in node.children()],
                                resource_provider=resource_provider,
                                foldable=True)
     try:
         node = self._pytis_help_root_node
     except AttributeError:
         directory = os.path.join(config.help_dir, 'src')
         reader = lcg.reader(directory, 'pytis', ext='txt', resource_provider=resource_provider)
         try:
             node = self._pytis_help_root_node = reader.build()
         except IOError as e:
             log(OPERATIONAL, "Unable to read Pytis help files from '%s':" % directory, e)
             node = lcg.ContentNode('pytis:', title=_("Pytis User Guide"),
                                    content=lcg.p(_("Help files not found!")),
                                    hidden=True, resource_provider=resource_provider)
     # We need to clone on every request because set_parent() is called on
     # the result when added to the help tree and set_parent may not be
     # called multiple times.
     return clone(node, 'help:pytis')
Beispiel #2
0
 def _pytis_help_nodes(self):
     def clone(node, id):
         return self.ContentNode(
             id=id,
             title=node.title(),
             descr=node.descr(),
             content=node.content(),
             hidden=node.hidden(),
             children=[clone(n, 'help:pytis/' + n.id()) for n in node.children()],
             resource_provider=self._resource_provider,
             foldable=True,
         )
     directory = os.path.join(pytis.config.help_dir, 'src')
     reader = lcg.reader(directory, 'pytis', ext='txt',
                         resource_provider=self._resource_provider)
     try:
         node = reader.build()
     except IOError as e:
         log(OPERATIONAL, "Unable to read Pytis help files from '%s':" % directory, e)
         node = self.ContentNode('help:pytis', title=_("Pytis User Guide"),
                                 content=lcg.p(_("Help files not found!")),
                                 hidden=True, resource_provider=self._resource_provider)
     else:
         node = clone(node, 'help:pytis')
     return node
Beispiel #3
0
def main(argv, opt, args):
    global _debug
    _debug = opt['debug']
    # Select the output format if options make sense.
    formats = [k for k in (HTML, IMS, HHP, PDF, TEXT, BRAILLE, EPUB,) if opt[k]]
    if not formats:
        output_format = HTML
    elif len(formats) == 1:
        output_format = formats[0]
    else:
        die("Can't use %s together!" % ' and '.join(['--' + f for f in formats]))
    # Find out whether the input is a single file or a directory.
    if len(args) == 1:
        src, dst = args[0], None
    elif len(args) == 2:
        src, dst = args
    else:
        usage(argv)
    if os.path.isfile(src):
        src, filename = os.path.split(src)
        basename, master_ext = os.path.splitext(filename)
        name, lang_ext = os.path.splitext(basename)
        lang = lang_ext[1:] if lang_ext else opt['lang']
        ext = master_ext[1:] if master_ext else None
        recourse = False
    else:
        name = opt['root']
        ext = opt['ext']
        lang = opt['lang']
        recourse = True
    if dst is None:
        if output_format in (PDF, TEXT, BRAILLE, EPUB,):
            # PDF, plain text and Braille script have always just one output
            # file (per each language variant), so there is no harm to write it
            # to the current directory by default.  Other formats generate a
            # file structure, so we require an explicit directory name.
            dst = '.'
        elif output_format == HTML and not recourse:
            opt['inline-styles'] = True
            dst = '.'
        else:
            die("You must specify the destination directory!")
    # Initialize translation and resource directories.
    translations = []
    lcg_dir = os.environ.get('LCGDIR')
    if lcg_dir:
        translations.append(os.path.abspath(os.path.join(lcg_dir, 'translations')))
        lcg.config.default_resource_dir = os.path.normpath(os.path.join(lcg_dir, 'resources'))
    if opt['translations']:
        translations.extend([os.path.abspath(d) for d in opt['translations'].split(':')])
    #######################################################################################
    # Read the source files (first real action after processing options).
    kwargs = {}
    if opt['plain']:
        kwargs['cls'] = lcg.DocFileReader
    reader = lcg.reader(src, name, ext=ext, recourse=recourse, encoding=opt['encoding'], **kwargs)
    try:
        node = reader.build()
    except IOError as e:
        message = unicode(e)
        match = re.match('[[]Errno[^]]*[]] *', message)
        if match:
            message = message[match.end():]
        sys.stderr.write(message)
        sys.stderr.write('\n')
        return
    # Decide which exporter to use.
    kwargs = {}
    export_kwargs = {}
    if output_format == PDF:
        cls = lcg.PDFExporter
        export_kwargs['recursive'] = True
    elif output_format == HHP:
        cls = lcg.HhpExporter
    elif output_format == TEXT:
        cls = lcg.TextExporter
        export_kwargs['recursive'] = True
    elif output_format == BRAILLE:
        cls = lcg.BrailleExporter
        export_kwargs['recursive'] = True
    elif output_format == EPUB:
        cls = lcg.EpubExporter
    else:
        if output_format == IMS:
            cls = lcg.IMSExporter
        else:
            cls = lcg.HtmlStaticExporter
        kwargs = dict(styles=opt['styles'].split(':'), inlinestyles=opt['inline-styles'])
    kwargs['force_lang_ext'] = opt['force-lang-ext']
    # Create the exporter instance.
    exporter = cls(translations=translations, **kwargs)
    # Write the exported content to output file(s).
    if (output_format == PDF and dst.lower().endswith('.pdf') or
        output_format == TEXT and (dst.lower().endswith('.text') or
                                   dst.lower().endswith('.txt')) or
        output_format == BRAILLE and (dst.lower().endswith('.text') or
                                      dst.lower().endswith('.txt'))):
        # TODO: Something similar would make sense for other formats too, at least when generating
        # just one document (no recursion).
        dst, filename = os.path.split(dst)
    elif output_format == EPUB and dst.lower().endswith('.epub'):
        dst, filename = os.path.split(dst)
    else:
        filename = None
    presentation_option = opt['presentation']
    if presentation_option is None:
        presentation = None
    elif presentation_option[-3:] == '.py':
        presentation = read_presentation(presentation_option)
    else:
        presentation = read_style(presentation_option)
    exporter.dump(node, dst, filename=filename, variant=lang, sec_lang=opt['sec-lang'],
                  presentation=presentation, **export_kwargs)
Beispiel #4
0
def main(argv, opt, args):
    global _debug
    _debug = opt['debug']
    # Select the output format if options make sense.
    formats = [
        k for k in (
            HTML,
            IMS,
            HHP,
            PDF,
            TEXT,
            BRAILLE,
            EPUB,
        ) if opt[k]
    ]
    if not formats:
        output_format = HTML
    elif len(formats) == 1:
        output_format = formats[0]
    else:
        die("Can't use %s together!" %
            ' and '.join(['--' + f for f in formats]))
    # Find out whether the input is a single file or a directory.
    if len(args) == 1:
        src, dst = args[0], None
    elif len(args) == 2:
        src, dst = args
    else:
        usage(argv)
    if os.path.isfile(src):
        src, filename = os.path.split(src)
        basename, master_ext = os.path.splitext(filename)
        name, lang_ext = os.path.splitext(basename)
        lang = lang_ext[1:] if lang_ext else opt['lang']
        ext = master_ext[1:] if master_ext else None
        recourse = False
    else:
        name = opt['root']
        ext = opt['ext']
        lang = opt['lang']
        recourse = True
    if dst is None:
        if output_format in (
                PDF,
                TEXT,
                BRAILLE,
                EPUB,
        ):
            # PDF, plain text and Braille script have always just one output
            # file (per each language variant), so there is no harm to write it
            # to the current directory by default.  Other formats generate a
            # file structure, so we require an explicit directory name.
            dst = '.'
        elif output_format == HTML and not recourse:
            opt['inline-styles'] = True
            dst = '.'
        else:
            die("You must specify the destination directory!")
    # Initialize translation and resource directories.
    translations = []
    lcg_dir = os.environ.get('LCGDIR', os.path.join(__file__, '..'))
    if lcg_dir:
        translations.append(
            os.path.abspath(os.path.join(lcg_dir, 'translations')))
    if opt['translations']:
        translations.extend(
            [os.path.abspath(d) for d in opt['translations'].split(':')])
    #######################################################################################
    # Read the source files (first real action after processing options).
    kwargs = {}
    if opt['plain']:
        kwargs['cls'] = lcg.DocFileReader

    reader = lcg.reader(src,
                        name,
                        ext=ext,
                        recourse=recourse,
                        encoding=opt['encoding'],
                        **kwargs)
    try:
        node = reader.build()
    except IOError as e:
        message = unistr(e)
        match = re.match('[[]Errno[^]]*[]] *', message)
        if match:
            message = message[match.end():]
        sys.stderr.write(message)
        sys.stderr.write('\n')
        return
    # Decide which exporter to use.
    kwargs = {}
    export_kwargs = {}
    if output_format == PDF:
        cls = lcg.PDFExporter
        export_kwargs['recursive'] = True
    elif output_format == HHP:
        cls = lcg.HhpExporter
    elif output_format == TEXT:
        cls = lcg.TextExporter
        export_kwargs['recursive'] = True
    elif output_format == BRAILLE:
        cls = lcg.BrailleExporter
        export_kwargs['recursive'] = True
    elif output_format == EPUB:
        cls = lcg.EpubExporter
    else:
        if output_format == IMS:
            cls = lcg.IMSExporter
        else:
            cls = lcg.HtmlStaticExporter
        kwargs = dict(styles=opt['styles'].split(':'),
                      inlinestyles=opt['inline-styles'])
    kwargs['force_lang_ext'] = opt['force-lang-ext']
    # Create the exporter instance.
    exporter = cls(translations=translations, **kwargs)
    # Write the exported content to output file(s).
    if (output_format == PDF and dst.lower().endswith('.pdf')
            or output_format == TEXT and
        (dst.lower().endswith('.text') or dst.lower().endswith('.txt'))
            or output_format == BRAILLE and
        (dst.lower().endswith('.text') or dst.lower().endswith('.txt'))):
        # TODO: Something similar would make sense for other formats too, at least when generating
        # just one document (no recursion).
        dst, filename = os.path.split(dst)
    elif output_format == EPUB and dst.lower().endswith('.epub'):
        dst, filename = os.path.split(dst)
    else:
        filename = None
    presentation_option = opt['presentation']
    if presentation_option is None:
        presentation = None
    elif presentation_option[-3:] == '.py':
        presentation = read_presentation(presentation_option)
    else:
        presentation = read_style(presentation_option)
    exporter.dump(node,
                  dst,
                  filename=filename,
                  variant=lang,
                  sec_lang=opt['sec-lang'],
                  presentation=presentation,
                  **export_kwargs)