Python docutils.parsers.rst 模块,Directive() 实例源码

我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用docutils.parsers.rst.Directive()

项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1
项目:AshsSDK    作者:thehappydinoa    | 项目源码 | 文件源码
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1
项目:bolero    作者:rock-learning    | 项目源码 | 文件源码
def __init__(self, root_data_object, renderer_factory_creator_constructor, finder_factory,
                 project_info_factory, filter_factory, target_handler_factory, parser_factory, *args):
        rst.Directive.__init__(self, *args)
        self.directive_args = list(args)  # Convert tuple to list to allow modification.

        self.root_data_object = root_data_object
        self.renderer_factory_creator_constructor = renderer_factory_creator_constructor
        self.finder_factory = finder_factory
        self.project_info_factory = project_info_factory
        self.filter_factory = filter_factory
        self.target_handler_factory = target_handler_factory
        self.parser_factory = parser_factory
项目:chalktalk_docs    作者:loremIpsum1771    | 项目源码 | 文件源码
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1
项目:blackmamba    作者:zrzka    | 项目源码 | 文件源码
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1
项目:symbolator    作者:kevinpt    | 项目源码 | 文件源码
def figure_wrapper(directive, node, caption):
    # type: (Directive, nodes.Node, unicode) -> nodes.figure
    figure_node = nodes.figure('', node)
    if 'align' in node:
        figure_node['align'] = node.attributes.pop('align')

    parsed = nodes.Element()
    directive.state.nested_parse(ViewList([caption], source=''),
                                 directive.content_offset, parsed)
    caption_node = nodes.caption(parsed[0].rawsource, '',
                                 *parsed[0].children)
    caption_node.source = parsed[0].source
    caption_node.line = parsed[0].line
    figure_node += caption_node
    return figure_node
项目:pyimgui    作者:swistakm    | 项目源码 | 文件源码
def flag(argument):
    """Reimplement directives.flag to return True instead of None
    Check for a valid flag option (no argument) and return ``None``.
    (Directive option conversion function.)

    Raise ``ValueError`` if an argument is found.
    """
    if argument and argument.strip():
        raise ValueError('no argument is allowed; "%s" supplied' % argument)
    else:
        return True
项目:RST-vscode    作者:tht13    | 项目源码 | 文件源码
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1
项目:tf_aws_ecs_instance_draining_on_scale_in    作者:terraform-community-modules    | 项目源码 | 文件源码
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError, detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish
        directive_instance = directive(
            type_name, arguments, options, content, lineno,
            content_offset, block_text, self, self.state_machine)
        try:
            result = directive_instance.run()
        except docutils.parsers.rst.DirectiveError, error:
            msg_node = self.reporter.system_message(error.level, error.msg,
                                                    line=lineno)
            msg_node += nodes.literal_block(block_text, block_text)
            result = [msg_node]
        assert isinstance(result, list), \
               'Directive "%s" must return a list of nodes.' % type_name
        for i in range(len(result)):
            assert isinstance(result[i], nodes.Node), \
                   ('Directive "%s" returned non-Node object (index %s): %r'
                    % (type_name, i, result[i]))
        return (result,
                blank_finish or self.state_machine.is_next_line_blank())
项目:AshsSDK    作者:thehappydinoa    | 项目源码 | 文件源码
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError, detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish
        directive_instance = directive(
            type_name, arguments, options, content, lineno,
            content_offset, block_text, self, self.state_machine)
        try:
            result = directive_instance.run()
        except docutils.parsers.rst.DirectiveError, error:
            msg_node = self.reporter.system_message(error.level, error.msg,
                                                    line=lineno)
            msg_node += nodes.literal_block(block_text, block_text)
            result = [msg_node]
        assert isinstance(result, list), \
               'Directive "%s" must return a list of nodes.' % type_name
        for i in range(len(result)):
            assert isinstance(result[i], nodes.Node), \
                   ('Directive "%s" returned non-Node object (index %s): %r'
                    % (type_name, i, result[i]))
        return (result,
                blank_finish or self.state_machine.is_next_line_blank())
项目:m2r    作者:miyakogi    | 项目源码 | 文件源码
def run(self):
        """Most of this method is from ``docutils.parser.rst.Directive``.

        docutils version: 0.12
        """
        if not self.state.document.settings.file_insertion_enabled:
            raise self.warning('"%s" directive disabled.' % self.name)
        source = self.state_machine.input_lines.source(
            self.lineno - self.state_machine.input_offset - 1)
        source_dir = os.path.dirname(os.path.abspath(source))
        path = rst.directives.path(self.arguments[0])
        path = os.path.normpath(os.path.join(source_dir, path))
        path = utils.relative_path(None, path)
        path = nodes.reprunicode(path)

        # get options (currently not use directive-specific options)
        encoding = self.options.get(
            'encoding', self.state.document.settings.input_encoding)
        e_handler = self.state.document.settings.input_encoding_error_handler
        tab_width = self.options.get(
            'tab-width', self.state.document.settings.tab_width)

        # open the inclding file
        try:
            self.state.document.settings.record_dependencies.add(path)
            include_file = io.FileInput(source_path=path,
                                        encoding=encoding,
                                        error_handler=e_handler)
        except UnicodeEncodeError as error:
            raise self.severe('Problems with "%s" directive path:\n'
                              'Cannot encode input file path "%s" '
                              '(wrong locale?).' %
                              (self.name, SafeString(path)))
        except IOError as error:
            raise self.severe('Problems with "%s" directive path:\n%s.' %
                              (self.name, ErrorString(error)))

        # read from the file
        try:
            rawtext = include_file.read()
        except UnicodeError as error:
            raise self.severe('Problem with "%s" directive:\n%s' %
                              (self.name, ErrorString(error)))

        config = self.state.document.settings.env.config
        converter = M2R(no_underscore_emphasis=config.no_underscore_emphasis)
        include_lines = statemachine.string2lines(converter(rawtext),
                                                  tab_width,
                                                  convert_whitespace=True)
        self.state_machine.insert_input(include_lines, path)
        return []
项目:chalktalk_docs    作者:loremIpsum1771    | 项目源码 | 文件源码
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError, detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish
        directive_instance = directive(
            type_name, arguments, options, content, lineno,
            content_offset, block_text, self, self.state_machine)
        try:
            result = directive_instance.run()
        except docutils.parsers.rst.DirectiveError, error:
            msg_node = self.reporter.system_message(error.level, error.msg,
                                                    line=lineno)
            msg_node += nodes.literal_block(block_text, block_text)
            result = [msg_node]
        assert isinstance(result, list), \
               'Directive "%s" must return a list of nodes.' % type_name
        for i in range(len(result)):
            assert isinstance(result[i], nodes.Node), \
                   ('Directive "%s" returned non-Node object (index %s): %r'
                    % (type_name, i, result[i]))
        return (result,
                blank_finish or self.state_machine.is_next_line_blank())
项目:tensorforce    作者:reinforceio    | 项目源码 | 文件源码
def run(self):
        """Most of this method is from ``docutils.parser.rst.Directive``.

        docutils version: 0.12
        """
        if not self.state.document.settings.file_insertion_enabled:
            raise self.warning('"%s" directive disabled.' % self.name)
        source = self.state_machine.input_lines.source(
            self.lineno - self.state_machine.input_offset - 1)
        source_dir = os.path.dirname(os.path.abspath(source))
        path = rst.directives.path(self.arguments[0])
        path = os.path.normpath(os.path.join(source_dir, path))
        path = utils.relative_path(None, path)
        path = nodes.reprunicode(path)

        # get options (currently not use directive-specific options)
        encoding = self.options.get(
            'encoding', self.state.document.settings.input_encoding)
        e_handler = self.state.document.settings.input_encoding_error_handler
        tab_width = self.options.get(
            'tab-width', self.state.document.settings.tab_width)

        # open the inclding file
        try:
            self.state.document.settings.record_dependencies.add(path)
            include_file = io.FileInput(source_path=path,
                                        encoding=encoding,
                                        error_handler=e_handler)
        except UnicodeEncodeError as error:
            raise self.severe('Problems with "%s" directive path:\n'
                              'Cannot encode input file path "%s" '
                              '(wrong locale?).' %
                              (self.name, SafeString(path)))
        except IOError as error:
            raise self.severe('Problems with "%s" directive path:\n%s.' %
                              (self.name, ErrorString(error)))

        # read from the file
        try:
            rawtext = include_file.read()
        except UnicodeError as error:
            raise self.severe('Problem with "%s" directive:\n%s' %
                              (self.name, ErrorString(error)))

        config = self.state.document.settings.env.config
        converter = M2R(no_underscore_emphasis=config.no_underscore_emphasis)
        include_lines = statemachine.string2lines(converter(rawtext),
                                                  tab_width,
                                                  convert_whitespace=True)
        self.state_machine.insert_input(include_lines, path)
        return []
项目:blackmamba    作者:zrzka    | 项目源码 | 文件源码
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError as detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish
        directive_instance = directive(
            type_name, arguments, options, content, lineno,
            content_offset, block_text, self, self.state_machine)
        try:
            result = directive_instance.run()
        except docutils.parsers.rst.DirectiveError as error:
            msg_node = self.reporter.system_message(error.level, error.msg,
                                                    line=lineno)
            msg_node += nodes.literal_block(block_text, block_text)
            result = [msg_node]
        assert isinstance(result, list), \
               'Directive "%s" must return a list of nodes.' % type_name
        for i in range(len(result)):
            assert isinstance(result[i], nodes.Node), \
                   ('Directive "%s" returned non-Node object (index %s): %r'
                    % (type_name, i, result[i]))
        return (result,
                blank_finish or self.state_machine.is_next_line_blank())
项目:RST-vscode    作者:tht13    | 项目源码 | 文件源码
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError, detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish
        directive_instance = directive(
            type_name, arguments, options, content, lineno,
            content_offset, block_text, self, self.state_machine)
        try:
            result = directive_instance.run()
        except docutils.parsers.rst.DirectiveError, error:
            msg_node = self.reporter.system_message(error.level, error.msg,
                                                    line=lineno)
            msg_node += nodes.literal_block(block_text, block_text)
            result = [msg_node]
        assert isinstance(result, list), \
               'Directive "%s" must return a list of nodes.' % type_name
        for i in range(len(result)):
            assert isinstance(result[i], nodes.Node), \
                   ('Directive "%s" returned non-Node object (index %s): %r'
                    % (type_name, i, result[i]))
        return (result,
                blank_finish or self.state_machine.is_next_line_blank())
项目:pep-drafts    作者:fedora-python    | 项目源码 | 文件源码
def fix_rst_pep(input_lines, outfile, inpath, pepnum):

    class XXXDirective(rst.Directive):
        has_content = True
        def run(self):
            # Raise an error if the directive does not have contents.
            self.assert_has_content()
            text = '\n'.join(self.content)
            # Create the admonition node, to be populated by `nested_parse`.
            admonition_node = nodes.admonition(rawsource=text)
            # Parse the directive contents.
            self.state.nested_parse(self.content, self.content_offset,
                                    admonition_node)
            title = nodes.title('', 'XXX')
            admonition_node.insert(0, title)
            return [admonition_node]
    directives.register_directive('xxx', XXXDirective)

    handle, template_file_name = tempfile.mkstemp(text=True)
    try:
        orig_template_name = pep_html.Writer.default_template_path
        with open(orig_template_name) as inf, open(handle, 'w') as outf:
            content = inf.read()
            content = content.replace('%(pepnum)s.txt', '%(pepnum)s.rst')
            content = content.replace("%(pepindex)s/", "%(pepindex)s")
            outf.write(content)

        output = core.publish_string(
            source=''.join(input_lines),
            source_path=inpath,
            destination_path=outfile.name,
            reader=Reader(),
            parser_name='restructuredtext',
            writer=Writer(pepnum),
            settings=None,
            # Allow Docutils traceback if there's an exception:
            settings_overrides={
                'traceback': 1,
                'template': template_file_name,
            })
        outfile.write(output.decode('utf-8'))
    finally:
        os.unlink(template_file_name)
项目:tf_aws_ecs_instance_draining_on_scale_in    作者:terraform-community-modules    | 项目源码 | 文件源码
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError, detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish
        directive_instance = directive(
            type_name, arguments, options, content, lineno,
            content_offset, block_text, self, self.state_machine)
        try:
            result = directive_instance.run()
        except docutils.parsers.rst.DirectiveError, error:
            msg_node = self.reporter.system_message(error.level, error.msg,
                                                    line=lineno)
            msg_node += nodes.literal_block(block_text, block_text)
            result = [msg_node]
        assert isinstance(result, list), \
               'Directive "%s" must return a list of nodes.' % type_name
        for i in range(len(result)):
            assert isinstance(result[i], nodes.Node), \
                   ('Directive "%s" returned non-Node object (index %s): %r'
                    % (type_name, i, result[i]))
        return (result,
                blank_finish or self.state_machine.is_next_line_blank())