Exemplo n.º 1
0
 def test_gen_tasks(self):
     hw = HelloWorld()
     hw.site = MockObject()
     hw.site.config = {}
     for i in hw.gen_tasks():
         self.assertEqual(i['basename'], 'hello_world')
         self.assertEqual(i['uptodate'], [False])
         try:
             self.assertIsInstance(i['actions'][0][1][0], bool)
         except AttributeError:
             LOGGER.warning('Python 2.6 is missing assertIsInstance()')
Exemplo n.º 2
0
 def test_gen_tasks(self):
     hw = HelloWorld()
     hw.site = MockObject()
     hw.site.config = {}
     for i in hw.gen_tasks():
         self.assertEqual(i['basename'], 'hello_world')
         self.assertEqual(i['uptodate'], [False])
         try:
             self.assertIsInstance(i['actions'][0][1][0], bool)
         except AttributeError:
             LOGGER.warning('Python 2.6 is missing assertIsInstance()')
Exemplo n.º 3
0
    def run(self):
        if 'alt' in self.options and self.ignore_alt:
            LOGGER.warning("Graphviz: the :alt: option is ignored, it's better to set the title of your graph.")
        if self.arguments:
            if self.content:
                LOGGER.warning("Graphviz: this directive can't have both content and a filename argument. Ignoring content.")
            f_name = self.arguments[0]
            # TODO: be smart about where exactly that file is located
            with open(f_name, 'rb') as inf:
                data = inf.read().decode('utf-8')
        else:
            data = '\n'.join(self.content)
        node_list = []
        try:
            p = Popen([self.dot_path, '-Tsvg'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
            svg_data, errors = p.communicate(input=data.encode('utf8'))
            code = p.wait()
            if code:  # Some error
                document = self.state.document
                return [document.reporter.error(
                        'Error processing graph: {0}'.format(errors), line=self.lineno)]
            if self.embed_graph:  # SVG embedded in the HTML
                if 'inline' in self.options:
                    svg_data = '<span class="graphviz">{0}</span>'.format(svg_data)
                else:
                    svg_data = '<p class="graphviz">{0}</p>'.format(svg_data)

            else:  # External SVG file
                # TODO: there is no reason why this branch needs to be a raw
                # directive. It could generate regular docutils nodes and
                # be useful for any writer.
                makedirs(self.output_folder)
                f_name = hashlib.md5(svg_data).hexdigest() + '.svg'
                img_path = self.graph_path + f_name
                f_path = os.path.join(self.output_folder, f_name)
                alt = self.options.get('alt', '')
                with open(f_path, 'wb+') as outf:
                    outf.write(svg_data)
                    self.state.document.settings.record_dependencies.add(f_path)
                if 'inline' in self.options:
                    svg_data = '<span class="graphviz"><img src="{0}" alt="{1}"></span>'.format(img_path, alt)
                else:
                    svg_data = '<p class="graphviz"><img src="{0}" alt="{1}"></p>'.format(img_path, alt)

            node_list.append(nodes.raw('', svg_data, format='html'))
            if 'caption' in self.options and 'inline' not in self.options:
                node_list.append(
                    nodes.raw('', '<p class="caption">{0}</p>'.format(self.options['caption']),
                              format='html'))
            return node_list
        except OSError:
            LOGGER.error("Can't execute 'dot'")
            raise
Exemplo n.º 4
0
    def run(self):
        if 'alt' in self.options and self.ignore_alt:
            LOGGER.warning("Graphviz: the :alt: option is ignored, it's better to set the title of your graph.")
        if self.arguments:
            if self.content:
                LOGGER.warning("Graphviz: this directive can't have both content and a filename argument. Ignoring content.")
            f_name = self.arguments[0]
            # TODO: be smart about where exactly that file is located
            with open(f_name, 'rb') as inf:
                data = inf.read().decode('utf-8')
        else:
            data = '\n'.join(self.content)
        node_list = []
        try:
            p = Popen([self.dot_path, '-Tsvg'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
            svg_data, errors = p.communicate(input=data.encode('utf8'))
            code = p.wait()
            if code:  # Some error
                document = self.state.document
                return [document.reporter.error(
                        'Error processing graph: {0}'.format(errors), line=self.lineno)]
            if self.embed_graph:  # SVG embedded in the HTML
                if 'inline' in self.options:
                    svg_data = '<span class="graphviz">{0}</span>'.format(svg_data.decode('utf8'))
                else:
                    svg_data = '<p class="graphviz">{0}</p>'.format(svg_data.decode('utf8'))

            else:  # External SVG file
                # TODO: there is no reason why this branch needs to be a raw
                # directive. It could generate regular docutils nodes and
                # be useful for any writer.
                makedirs(self.output_folder)
                f_name = hashlib.md5(svg_data).hexdigest() + '.svg'
                img_path = self.graph_path + f_name
                f_path = os.path.join(self.output_folder, f_name)
                alt = self.options.get('alt', '')
                with open(f_path, 'wb+') as outf:
                    outf.write(svg_data)
                    self.state.document.settings.record_dependencies.add(f_path)
                if 'inline' in self.options:
                    svg_data = '<span class="graphviz"><img src="{0}" alt="{1}"></span>'.format(img_path, alt)
                else:
                    svg_data = '<p class="graphviz"><img src="{0}" alt="{1}"></p>'.format(img_path, alt)

            node_list.append(nodes.raw('', svg_data, format='html'))
            if 'caption' in self.options and 'inline' not in self.options:
                node_list.append(
                    nodes.raw('', '<p class="caption">{0}</p>'.format(self.options['caption']),
                              format='html'))
            return node_list
        except OSError:
            LOGGER.error("Can't execute 'dot'")
            raise
Exemplo n.º 5
0
Arquivo: doc.py Projeto: tbm/nikola
def doc_shortcode(*args, **kwargs):
    """Implement the doc shortcode."""
    text = kwargs['data']
    success, twin_slugs, title, permalink, slug = _doc_link(text, text, LOGGER)
    if success:
        if twin_slugs:
            LOGGER.warning(
                'More than one post with the same slug. Using "{0}" for doc shortcode'.format(permalink))
        return '<a href="{0}">{1}</a>'.format(permalink, title)
    else:
        LOGGER.error(
            '"{0}" slug doesn\'t exist.'.format(slug))
        return '<span class="error text-error" style="color: red;">Invalid link: {0}</span>'.format(text)
Exemplo n.º 6
0
Arquivo: doc.py Projeto: tbm/nikola
def doc_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    """Handle the doc role."""
    success, twin_slugs, title, permalink, slug = _doc_link(rawtext, text, options, content)
    if success:
        if twin_slugs:
            inliner.reporter.warning(
                'More than one post with the same slug. Using "{0}"'.format(permalink))
            LOGGER.warning(
                'More than one post with the same slug. Using "{0}" for doc role'.format(permalink))
        node = make_link_node(rawtext, title, permalink, options)
        return [node], []
    else:
        msg = inliner.reporter.error(
            '"{0}" slug doesn\'t exist.'.format(slug),
            line=lineno)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]
Exemplo n.º 7
0
    def read_files(self):
        self.rows = []
        cnt = 0
        for fname in get_entries(os.path.join(base_path, "../examples")):
            LOGGER.info("processing " + fname)
            try:
                # data = load_json(fname)
                data = {}
                data["path"] = fname
                data["path_image"] = fname[:-3] + ".png"
                data["name"] = os.path.basename(os.path.dirname(fname))
                data["url"] = "https://github.com/undertherain/pycontextfree/blob/master/examples/" + data["name"] + "/" + os.path.basename(fname)
                data["id"] = cnt
                name_image = os.path.basename(fname)[:-3] + ".png"

                data["image"] = "/gallery/" + name_image
                cnt += 1
                self.rows.append(data)
            except Exception as e:
                LOGGER.warning("error processing " + fname + str(e))
Exemplo n.º 8
0
    def handler(self, title=None, site=None, data=None, lang=None):
        """Create an inter-site link

        Args:
         title: optional argument to specify a different title from the post

        Returns:
         output HTML to replace the shortcode
        """
        success, twin_slugs, title, permalink, slug = lancelot_link(
            site, data, title)
        if success:
            if twin_slugs:
                LOGGER.warning('More than one post with the same slug. '
                               f'Using "{permalink}" for lancelot shortcode')
            output = f'<a href="{permalink}">{title}</a>'
        else:
            LOGGER.error(f'"{slug}" slug doesn\'t exist.')
            output = ('<span class="error text-error" style="color: red;">'
                      f'Invalid link: {data}</span>')
        return output, []
Exemplo n.º 9
0
    def compile_html(self, source, dest, is_two_file=True):
        """Compile reSt into HTML."""

        if not has_docutils:
            raise Exception('To build this site, you need to install the '
                            '"docutils" package.')
        makedirs(os.path.dirname(dest))
        error_level = 100
        with codecs.open(dest, "w+", "utf8") as out_file:
            with codecs.open(source, "r", "utf8") as in_file:
                data = in_file.read()
                if not is_two_file:
                    data = data.split('\n\n', 1)[-1]
                output, error_level, deps = rst2html(
                    data, settings_overrides={
                        'initial_header_level': 2,
                        'record_dependencies': True,
                        'stylesheet_path': None,
                        'link_stylesheet': True,
                        'syntax_highlight': 'short',
                        'math_output': 'mathjax',
                    })
                out_file.write(output)
            deps_path = dest + '.dep'
            if deps.list:
                with codecs.open(deps_path, "wb+", "utf8") as deps_file:
                    deps_file.write('\n'.join(deps.list))
            else:
                if os.path.isfile(deps_path):
                    os.unlink(deps_path)
        if error_level == 2:
            LOGGER.warning('Docutils reports warnings on {0}'.format(source))
        if error_level < 3:
            return True
        else:
            return False