kerneldoc.py 6.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# coding=utf-8
#
# Copyright © 2016 Intel Corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# Authors:
#    Jani Nikula <jani.nikula@intel.com>
26 27 28
#
# Please make sure this works on both python2 and python3.
#
29

30
import codecs
31 32 33
import os
import subprocess
import sys
34
import re
35
import glob
36 37

from docutils import nodes, statemachine
38
from docutils.statemachine import ViewList
39
from docutils.parsers.rst import directives, Directive
40 41 42 43 44 45 46 47 48 49 50

#
# AutodocReporter is only good up to Sphinx 1.7
#
import sphinx

Use_SSI = sphinx.__version__[:3] >= '1.7'
if Use_SSI:
    from sphinx.util.docutils import switch_source_input
else:
    from sphinx.ext.autodoc import AutodocReporter
51

52 53
import kernellog

54 55
__version__  = '1.0'

56 57 58 59 60 61
class KernelDocDirective(Directive):
    """Extract kernel-doc comments from the specified file"""
    required_argument = 1
    optional_arguments = 4
    option_spec = {
        'doc': directives.unchanged_required,
62
        'functions': directives.unchanged,
63 64
        'export': directives.unchanged,
        'internal': directives.unchanged,
65 66 67 68 69
    }
    has_content = False

    def run(self):
        env = self.state.document.settings.env
70
        cmd = [env.config.kerneldoc_bin, '-rst', '-enable-lineno']
71 72

        filename = env.config.kerneldoc_srctree + '/' + self.arguments[0]
73
        export_file_patterns = []
74 75 76 77 78 79 80 81 82

        # Tell sphinx of the dependency
        env.note_dependency(os.path.abspath(filename))

        tab_width = self.options.get('tab-width', self.state.document.settings.tab_width)

        # FIXME: make this nicer and more robust against errors
        if 'export' in self.options:
            cmd += ['-export']
83
            export_file_patterns = str(self.options.get('export')).split()
84 85
        elif 'internal' in self.options:
            cmd += ['-internal']
86
            export_file_patterns = str(self.options.get('internal')).split()
87 88 89
        elif 'doc' in self.options:
            cmd += ['-function', str(self.options.get('doc'))]
        elif 'functions' in self.options:
90 91 92 93 94 95
            functions = self.options.get('functions').split()
            if functions:
                for f in functions:
                    cmd += ['-function', f]
            else:
                cmd += ['-no-doc-sections']
96

97 98 99 100 101
        for pattern in export_file_patterns:
            for f in glob.glob(env.config.kerneldoc_srctree + '/' + pattern):
                env.note_dependency(os.path.abspath(f))
                cmd += ['-export-file', f]

102 103 104
        cmd += [filename]

        try:
105 106
            kernellog.verbose(env.app,
                              'calling kernel-doc \'%s\'' % (" ".join(cmd)))
107

108
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
109 110
            out, err = p.communicate()

111
            out, err = codecs.decode(out, 'utf-8'), codecs.decode(err, 'utf-8')
112 113 114 115

            if p.returncode != 0:
                sys.stderr.write(err)

116 117
                kernellog.warn(env.app,
                               'kernel-doc \'%s\' failed with return code %d' % (" ".join(cmd), p.returncode))
118 119 120 121 122
                return [nodes.error(None, nodes.paragraph(text = "kernel-doc missing"))]
            elif env.config.kerneldoc_verbosity > 0:
                sys.stderr.write(err)

            lines = statemachine.string2lines(out, tab_width, convert_whitespace=True)
123 124 125 126 127 128 129 130 131 132 133
            result = ViewList()

            lineoffset = 0;
            line_regex = re.compile("^#define LINENO ([0-9]+)$")
            for line in lines:
                match = line_regex.search(line)
                if match:
                    # sphinx counts lines from 0
                    lineoffset = int(match.group(1)) - 1
                    # we must eat our comments since the upset the markup
                else:
134
                    result.append(line, filename, lineoffset)
135
                    lineoffset += 1
136 137

            node = nodes.section()
138
            self.do_parse(result, node)
139 140 141

            return node.children

142
        except Exception as e:  # pylint: disable=W0703
143 144
            kernellog.warn(env.app, 'kernel-doc \'%s\' processing failed with: %s' %
                           (" ".join(cmd), str(e)))
145 146
            return [nodes.error(None, nodes.paragraph(text = "kernel-doc missing"))]

147 148 149 150 151 152 153 154 155 156 157 158 159 160
    def do_parse(self, result, node):
        if Use_SSI:
            with switch_source_input(self.state, result):
                self.state.nested_parse(result, 0, node, match_titles=1)
        else:
            save = self.state.memo.title_styles, self.state.memo.section_level, self.state.memo.reporter
            self.state.memo.reporter = AutodocReporter(result, self.state.memo.reporter)
            self.state.memo.title_styles, self.state.memo.section_level = [], 0
            try:
                self.state.nested_parse(result, 0, node, match_titles=1)
            finally:
                self.state.memo.title_styles, self.state.memo.section_level, self.state.memo.reporter = save


161 162 163 164 165 166
def setup(app):
    app.add_config_value('kerneldoc_bin', None, 'env')
    app.add_config_value('kerneldoc_srctree', None, 'env')
    app.add_config_value('kerneldoc_verbosity', 1, 'env')

    app.add_directive('kernel-doc', KernelDocDirective)
167 168 169 170 171 172

    return dict(
        version = __version__,
        parallel_read_safe = True,
        parallel_write_safe = True
    )