File: ext.py

package info (click to toggle)
buildbot 4.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 21,080 kB
  • sloc: python: 174,183; sh: 1,204; makefile: 332; javascript: 119; xml: 16
file content (430 lines) | stat: -rw-r--r-- 15,154 bytes parent folder | download | duplicates (2)
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# This file is part of Buildbot.  Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members

from docutils import nodes
from docutils.parsers.rst import Directive
from sphinx import addnodes
from sphinx.domains import Domain
from sphinx.domains import Index
from sphinx.domains import ObjType
from sphinx.roles import XRefRole
from sphinx.util import logging
from sphinx.util import ws_re
from sphinx.util.docfields import DocFieldTransformer
from sphinx.util.docfields import Field
from sphinx.util.docfields import TypedField
from sphinx.util.nodes import make_refnode

logger = logging.getLogger(__name__)


class BBRefTargetDirective(Directive):
    """
    A directive that can be a target for references.  Attributes:

    @cvar ref_type: same as directive name
    @cvar indextemplates: templates for main index entries, if any
    """

    has_content = False
    name_annotation = None
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = True
    option_spec = {}
    domain = 'bb'
    doc_field_types = []

    def get_field_type_map(self):
        # This is the same as DocFieldTransformer.preprocess_fieldtype which got removed in
        # Sphinx 4.0
        typemap = {}
        for fieldtype in self.doc_field_types:
            for name in fieldtype.names:
                typemap[name] = fieldtype, False
            if fieldtype.is_typed:
                for name in fieldtype.typenames:
                    typemap[name] = fieldtype, True
        return typemap

    def run(self):
        self.env = env = self.state.document.settings.env
        # normalize whitespace in fullname like XRefRole does
        fullname = ws_re.sub(' ', self.arguments[0].strip())
        targetname = f'{self.ref_type}-{fullname}'

        # keep the target; this may be used to generate a BBIndex later
        targets = env.domaindata['bb']['targets'].setdefault(self.ref_type, {})
        targets[fullname] = env.docname, targetname

        # make up the descriptor: a target and potentially an index descriptor
        node = nodes.target('', '', ids=[targetname])
        ret = [node]

        # add the target to the document
        self.state.document.note_explicit_target(node)

        # append the index node if necessary
        entries = []
        for tpl in self.indextemplates:
            colon = tpl.find(':')
            if colon != -1:
                indextype = tpl[:colon].strip()
                indexentry = tpl[colon + 1 :].strip() % (fullname,)
            else:
                indextype = 'single'
                indexentry = tpl % (fullname,)
            entries.append((indextype, indexentry, targetname, targetname, None))

        if entries:
            inode = addnodes.index(entries=entries)
            ret.insert(0, inode)

        # if the node has content, set up a signature and parse the content
        if self.has_content:
            descnode = addnodes.desc()
            descnode['domain'] = 'bb'
            descnode['objtype'] = self.ref_type
            descnode['noindex'] = True
            signode = addnodes.desc_signature(fullname, '')

            if self.name_annotation:
                annotation = f"{self.name_annotation} "
                signode += addnodes.desc_annotation(annotation, annotation)
            signode += addnodes.desc_name(fullname, fullname)
            descnode += signode

            contentnode = addnodes.desc_content()
            self.state.nested_parse(self.content, 0, contentnode)
            DocFieldTransformer(self).transform_all(contentnode)
            descnode += contentnode

            ret.append(descnode)

        return ret

    @classmethod
    def resolve_ref(cls, domain, env, fromdocname, builder, typ, target, node, contnode):
        """
        Resolve a reference to a directive of this class
        """
        targets = domain.data['targets'].get(cls.ref_type, {})
        try:
            todocname, targetname = targets[target]
        except KeyError:
            logger.warning(
                f"{fromdocname}:{node.line}: Missing BB reference: bb:{cls.ref_type}:{target}"
            )
            return None

        return make_refnode(builder, fromdocname, todocname, targetname, contnode, target)


def make_ref_target_directive(ref_type, indextemplates=None, **kwargs):
    """
    Create and return a L{BBRefTargetDirective} subclass.
    """
    class_vars = dict(ref_type=ref_type, indextemplates=indextemplates)
    class_vars.update(kwargs)
    return type(f"BB{ref_type.capitalize()}RefTargetDirective", (BBRefTargetDirective,), class_vars)


class BBIndex(Index):
    """
    A Buildbot-specific index.

    @cvar name: same name as the directive and xref role
    @cvar localname: name of the index document
    """

    def generate(self, docnames=None):
        content = {}
        idx_targets = self.domain.data['targets'].get(self.name, {})
        for name, (docname, targetname) in idx_targets.items():
            letter = name[0].upper()
            content.setdefault(letter, []).append((name, 0, docname, targetname, '', '', ''))
        content = [
            (l, sorted(content[l], key=lambda tup: tup[0].lower())) for l in sorted(content.keys())
        ]
        return (content, False)

    @classmethod
    def resolve_ref(cls, domain, env, fromdocname, builder, typ, target, node, contnode):
        """
        Resolve a reference to an index to the document containing the index,
        using the index's C{localname} as the content of the link.
        """
        # indexes appear to be automatically generated at doc DOMAIN-NAME
        todocname = f"bb-{target}"

        node = nodes.reference('', '', internal=True)
        node['refuri'] = builder.get_relative_uri(fromdocname, todocname)
        node['reftitle'] = cls.localname
        node.append(nodes.emphasis(cls.localname, cls.localname))
        return node


def make_index(name, localname):
    """
    Create and return a L{BBIndex} subclass, for use in the domain's C{indices}
    """
    return type(f"BB{name.capitalize()}Index", (BBIndex,), dict(name=name, localname=localname))


class BBDomain(Domain):
    name = 'bb'
    label = 'Buildbot'

    object_types = {
        'cfg': ObjType('cfg', 'cfg'),
        'sched': ObjType('sched', 'sched'),
        'chsrc': ObjType('chsrc', 'chsrc'),
        'step': ObjType('step', 'step'),
        'reportgen': ObjType('reportgen', 'reportgen'),
        'reporter': ObjType('reporter', 'reporter'),
        'configurator': ObjType('configurator', 'configurator'),
        'worker': ObjType('worker', 'worker'),
        'cmdline': ObjType('cmdline', 'cmdline'),
        'msg': ObjType('msg', 'msg'),
        'event': ObjType('event', 'event'),
        'rtype': ObjType('rtype', 'rtype'),
        'rpath': ObjType('rpath', 'rpath'),
        'raction': ObjType('raction', 'raction'),
    }

    directives = {
        'cfg': make_ref_target_directive(
            'cfg',
            indextemplates=[
                'single: Buildmaster Config; %s',
                'single: %s (Buildmaster Config)',
            ],
        ),
        'sched': make_ref_target_directive(
            'sched',
            indextemplates=[
                'single: Schedulers; %s',
                'single: %s Scheduler',
            ],
        ),
        'chsrc': make_ref_target_directive(
            'chsrc',
            indextemplates=[
                'single: Change Sources; %s',
                'single: %s Change Source',
            ],
        ),
        'step': make_ref_target_directive(
            'step',
            indextemplates=[
                'single: Build Steps; %s',
                'single: %s Build Step',
            ],
        ),
        'reportgen': make_ref_target_directive(
            'reportgen',
            indextemplates=[
                'single: Report Generators; %s',
                'single: %s Report Generator',
            ],
        ),
        'reporter': make_ref_target_directive(
            'reporter',
            indextemplates=[
                'single: Reporter Targets; %s',
                'single: %s Reporter Target',
            ],
        ),
        'configurator': make_ref_target_directive(
            'configurator',
            indextemplates=[
                'single: Configurators; %s',
                'single: %s Configurators',
            ],
        ),
        'worker': make_ref_target_directive(
            'worker',
            indextemplates=[
                'single: Build Workers; %s',
                'single: %s Build Worker',
            ],
        ),
        'cmdline': make_ref_target_directive(
            'cmdline',
            indextemplates=[
                'single: Command Line Subcommands; %s',
                'single: %s Command Line Subcommand',
            ],
        ),
        'msg': make_ref_target_directive(
            'msg',
            indextemplates=[
                'single: Message Schema; %s',
            ],
            has_content=True,
            name_annotation='routing key:',
            doc_field_types=[
                TypedField(
                    'key', label='Keys', names=('key',), typenames=('type',), can_collapse=True
                ),
                Field('var', label='Variable', names=('var',)),
            ],
        ),
        'event': make_ref_target_directive(
            'event',
            indextemplates=[
                'single: event; %s',
            ],
            has_content=True,
            name_annotation='event:',
            doc_field_types=[],
        ),
        'rtype': make_ref_target_directive(
            'rtype',
            indextemplates=[
                'single: Resource Type; %s',
            ],
            has_content=True,
            name_annotation='resource type:',
            doc_field_types=[
                TypedField(
                    'attr',
                    label='Attributes',
                    names=('attr',),
                    typenames=('type',),
                    can_collapse=True,
                ),
            ],
        ),
        'rpath': make_ref_target_directive(
            'rpath',
            indextemplates=[
                'single: Resource Path; %s',
            ],
            name_annotation='path:',
            has_content=True,
            doc_field_types=[
                TypedField(
                    'pathkey',
                    label='Path Keys',
                    names=('pathkey',),
                    typenames=('type',),
                    can_collapse=True,
                ),
            ],
        ),
        'raction': make_ref_target_directive(
            'raction',
            indextemplates=[
                'single: Resource Action; %s',
            ],
            name_annotation='POST with method:',
            has_content=True,
            doc_field_types=[
                TypedField(
                    'body',
                    label='Body keys',
                    names=('body',),
                    typenames=('type',),
                    can_collapse=True,
                ),
            ],
        ),
    }

    roles = {
        'cfg': XRefRole(),
        'sched': XRefRole(),
        'chsrc': XRefRole(),
        'step': XRefRole(),
        'reportgen': XRefRole(),
        'reporter': XRefRole(),
        'configurator': XRefRole(),
        'worker': XRefRole(),
        'cmdline': XRefRole(),
        'msg': XRefRole(),
        'event': XRefRole(),
        'rtype': XRefRole(),
        'rpath': XRefRole(),
        'index': XRefRole(),
    }

    initial_data = {
        'targets': {},  # type -> target -> (docname, targetname)
    }

    indices = [
        make_index("cfg", "Buildmaster Configuration Index"),
        make_index("sched", "Scheduler Index"),
        make_index("chsrc", "Change Source Index"),
        make_index("step", "Build Step Index"),
        make_index("reportgen", "Reporter Generator Index"),
        make_index("reporter", "Reporter Target Index"),
        make_index("configurator", "Configurator Target Index"),
        make_index("worker", "Build Worker Index"),
        make_index("cmdline", "Command Line Index"),
        make_index("msg", "MQ Routing Key Index"),
        make_index("event", "Data API Event Index"),
        make_index("rtype", "REST/Data API Resource Type Index"),
        make_index("rpath", "REST/Data API Path Index"),
        make_index("raction", "REST/Data API Actions Index"),
    ]

    def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
        if typ == 'index':
            for idx in self.indices:
                if idx.name == target:
                    break
            else:
                raise KeyError(f"no index named '{target}'")
            return idx.resolve_ref(self, env, fromdocname, builder, typ, target, node, contnode)
        elif typ in self.directives:
            dir = self.directives[typ]
            return dir.resolve_ref(self, env, fromdocname, builder, typ, target, node, contnode)

    def merge_domaindata(self, docnames, otherdata):
        for typ in self.object_types:
            if typ not in otherdata['targets']:
                continue

            if typ not in self.data['targets']:
                self.data['targets'][typ] = otherdata['targets'][typ]
                continue

            self_data = self.data['targets'][typ]
            other_data = otherdata['targets'][typ]

            for target_name, target_data in other_data.items():
                if target_name in self_data:
                    # for some reason we end up with multiple references to the same things in
                    # multiple domains. If both instances point to the same location, ignore it,
                    # otherwise issue a warning.
                    if other_data[target_name] == self_data[target_name]:
                        continue

                    self_path = f'{self.env.doc2path(self_data[target_name][0])}#{self_data[target_name][1]}'

                    other_path = f'{self.env.doc2path(other_data[target_name][0])}#{other_data[target_name][1]}'

                    logger.warning(
                        f'Duplicate index {typ} reference {target_name} in {self_path}, other instance in {other_path}'
                    )
                else:
                    self_data[target_name] = target_data


def setup(app):
    app.add_domain(BBDomain)
    return {'parallel_read_safe': True, 'parallel_write_safe': True}