File: check_spelling.py

package info (click to toggle)
blender-doc 4.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 253,604 kB
  • sloc: python: 13,030; javascript: 322; makefile: 113; sh: 107
file content (555 lines) | stat: -rw-r--r-- 15,591 bytes parent folder | download
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
#!/usr/bin/env python3
# Apache License, Version 2.0

"""
Check spelling for all RST files in the repository.

- TODO: more comprehensive docs.
- TODO: some words get extracted that shouldn't.
"""

import docutils.parsers.rst
from docutils.parsers.rst import directives, roles
import docutils
from check_spelling_config import (
    dict_custom,
    dict_ignore,
)
import os
import sys
import re


# for spelling
import enchant
dict_spelling = enchant.Dict("en_US")


USE_ONCE = True
once_words = set()
bad_words = set()


def find_vcs_root(test, dirs=(".svn", ".git", ".hg"), default=None):
    import os
    prev, test = None, os.path.abspath(test)
    while prev != test:
        if any(os.path.isdir(os.path.join(test, d)) for d in dirs):
            return test
        prev, test = test, os.path.abspath(os.path.join(test, os.pardir))
    return default


def check_word(w):
    if not w:
        return True
    w_lower = w.lower()
    if w_lower in dict_custom or w_lower in dict_ignore:
        return True
    return dict_spelling.check(w)


def regex_key_raise(x):
    raise Exception("Unknown role! " + "".join(x.groups()))


# A table of regex and their replacement functions.
#
# This is used to clean up text from `docutils.nodes.NodeVisitor.visit_Text` which doesn't remove inline markup.
# Note that in some cases the order matters, especially with include/excluding roles.

RE_TEXT_REPLACE_ROLES_INCLUDE = ("menuselection", "guilabel")
RE_TEXT_REPLACE_ROLES_EXCLUDE = ("kbd", "ref", "doc", "abbr")

RE_TEXT_REPLACE_TABLE = (
    # Match HTML link: `Text <url>`__
    # A URL may span multiple lines.
    (
        re.compile(r"(`)([^`<]+)(<[^`>]+>)(`)(__)", re.MULTILINE),
        lambda x: x.groups()[1].strip(),
    ),
    # Roles with plain-text: :some_role:`Text <ref>`
    (
        re.compile(r"(:[A-Za-z_]+:)(`)([^`<]+)(<[^`>]+>)(`)", flags=re.MULTILINE),
        lambda x: x.groups()[2].strip(),
    ),
    # Roles to always include.
    (
        re.compile(r"(:(" + ("|".join(RE_TEXT_REPLACE_ROLES_INCLUDE)) + r"):)(`)([^`]+)(`)", flags=re.MULTILINE),
        lambda x: x.groups()[3].strip(),
    ),
    # Roles to always exclude.
    (
        re.compile(r"(:(" + ("|".join(RE_TEXT_REPLACE_ROLES_EXCLUDE)) + r"):)(`)([^`]+)(`)", flags=re.MULTILINE),
        lambda _: " ",
    ),
    # Ensure all roles are handled.
    (
        re.compile(r"(:[A-Za-z_]+:)(`)([^`]+)(`)", flags=re.MULTILINE),
        regex_key_raise,
    ),
    # Match substitution for removal: `|identifier|`
    (
        re.compile(r"\|[a-zA-Z0-9_]+\|"),
        lambda _: " ",
    ),
)

RE_WORDS = re.compile(
    r"\b("
    # Capital words, with optional '-' and "'".
    r"[A-Z]+[\-'A-Z]*[A-Z]|"
    # Lowercase words, with optional '-' and "'".
    r"[A-Za-z][\-'a-z]*[a-z]+"
    r")\b"
)


def check_spelling_body(text):

    # Wash text or inline RST.
    for re_expr, re_replace_fn in RE_TEXT_REPLACE_TABLE:
        text = re.sub(re_expr, re_replace_fn, text)

    for re_match in RE_WORDS.finditer(text):
        w = re_match.group(0)

        # Skip entirely uppercase words.
        # These are typically used for acronyms: XYZ, UDIM, API ... etc.
        if w.isupper():
            continue

        w_lower = w.lower()

        if USE_ONCE and w_lower in once_words:
            continue

        if check_word(w):
            pass
        elif "-" in w and all(check_word(w_split) for w_split in w.split("-")):
            pass  # all words split by dash are correct, also pass
        else:
            bad_words.add(w)
            # print(" %r" % w)

            if USE_ONCE:
                once_words.add(w_lower)


CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))
RST_DIR = find_vcs_root(CURRENT_DIR)


def rst_files(path):
    for dirpath, dirnames, filenames in os.walk(path):
        if dirpath.startswith("."):
            continue
        for filename in filenames:
            if filename.startswith("."):
                continue
            ext = os.path.splitext(filename)[1]
            if ext.lower() == ".rst":
                yield os.path.join(dirpath, filename)


def main():
    for fn in rst_files(RST_DIR):
        check_spelling(fn)

    # We could have nicer in-context display,
    # for now just print the words
    words_sorted = list(bad_words)
    words_sorted.sort(key=lambda s: s.lower())
    for w in words_sorted:
        print(w)
        # print(w, "->", " ".join(dict_spelling.suggest(w)))


# -----------------------------------------------------------------------------
# Register dummy directives


def directive_ignore(
        name, arguments, options, content, lineno,
        content_offset, block_text, state, state_machine,
):
    """
    Used to explicitly mark as doctest blocks things that otherwise
    wouldn't look like doctest blocks.

    Note this doesn't ignore child nodes.
    """
    text = '\n'.join(content)
    r'''
    if re.match(r'.*\n\s*\n', block_text):
        warning('doctest-ignore on line %d will not be ignored, '
             'because there is\na blank line between ".. doctest-ignore::"'
             ' and the doctest example.' % lineno)
    '''
    return [docutils.nodes.doctest_block(text, text, codeblock=True)]


directive_ignore.content = True


def directive_ignore_recursive(
        name, arguments, options, content, lineno,
        content_offset, block_text, state, state_machine,
):
    """
    Ignore everything under this directive (use with care!)
    """
    return []


directive_ignore_recursive.content = True


# ones we want to check
directives.register_directive('index', directive_ignore)
directives.register_directive('reference', directive_ignore)
directives.register_directive('seealso', directive_ignore)
directives.register_directive('only', directive_ignore)
directives.register_directive('hlist', directive_ignore)
directives.register_directive('versionchanged', directive_ignore)

# Custom.
directives.register_directive('peertube', directive_ignore)

# directives.register_directive('glossary', directive_ignore)  # wash this data instead
# Custom directives from extensions
directives.register_directive('todo', directive_ignore)

# Recursive ignore, take care!
directives.register_directive('toctree', directive_ignore_recursive)
directives.register_directive('code-block', directive_ignore_recursive)
directives.register_directive('highlight', directive_ignore_recursive)
directives.register_directive('parsed-literal', directive_ignore_recursive)
# Python API reference.
directives.register_directive('autoclass', directive_ignore_recursive)
directives.register_directive('automodule', directive_ignore_recursive)
directives.register_directive('autosummary', directive_ignore_recursive)
directives.register_directive('currentmodule', directive_ignore_recursive)
directives.register_directive('function', directive_ignore_recursive)
# Custom directives from extensions
directives.register_directive('youtube', directive_ignore_recursive)
directives.register_directive('peertube', directive_ignore_recursive)
directives.register_directive('vimeo', directive_ignore_recursive)
directives.register_directive('todolist', directive_ignore_recursive)

# workaround some bug? docutils won't load relative includes!
directives.register_directive('include', directive_ignore_recursive)


# Dummy roles
class RoleIgnore(docutils.nodes.Inline, docutils.nodes.TextElement):
    pass


def role_ignore(
        name, rawtext, text, lineno, inliner,
        options={}, content=[],
):
    # Recursively parse the contents of the index term, in case it
    # contains a substitution (like |alpha|).
    nodes, msgs = inliner.parse(text, lineno, memo=inliner, parent=inliner.parent)
    # 'text' instead of 'rawtext' because it doesn't contain the :role:
    return [RoleIgnore(text, '', *nodes, **options)], []


class RoleIgnoreRecursive(docutils.nodes.Inline, docutils.nodes.TextElement):
    pass


def role_ignore_recursive(
        name, rawtext, text, lineno, inliner,
        options={}, content=[],
):
    return [RoleIgnoreRecursive("", '', *(), **{})], []


roles.register_canonical_role('abbr', role_ignore)
roles.register_canonical_role('menuselection', role_ignore)
roles.register_canonical_role('guilabel', role_ignore)

roles.register_canonical_role('class', role_ignore_recursive)
roles.register_canonical_role('doc', role_ignore_recursive)
roles.register_canonical_role('kbd', role_ignore_recursive)
roles.register_canonical_role('mod', role_ignore_recursive)
roles.register_canonical_role('ref', role_ignore_recursive)
roles.register_canonical_role('term', role_ignore_recursive)
# Python API reference.
roles.register_canonical_role('meth', role_ignore_recursive)
# Custom directives from extensions
roles.register_canonical_role('bl-icon', role_ignore_recursive)


# -----------------------------------------------------------------------------
# Special logic to wash filedata
#
# Special Case


def filedata_glossary_wash(filedata):
    """
    Only list body of text.
    """
    lines_src = filedata.splitlines()
    lines_dst = []
    in_glossary = False
    for l in lines_src:
        l_strip = l.lstrip()
        if l_strip.startswith(".. glossary::"):
            in_glossary = True
            continue
        elif in_glossary is False:
            lines_dst.append(l)
            continue
        else:
            indent = len(l) - len(l_strip)
            if indent <= 3 and l_strip:
                continue
            elif indent >= 6 or not l_strip:
                lines_dst.append(l[6:])
    return "\n".join(lines_dst)


# -----------------------------------------------------------------------------


def rst_to_doctree(filedata, filename):
    # filename only used as an ID
    import docutils.parsers.rst
    parser = docutils.parsers.rst.Parser()
    doc = docutils.utils.new_document(filename)
    doc.settings.tab_width = 3
    doc.settings.pep_references = False
    doc.settings.rfc_references = False
    doc.settings.syntax_highlight = False

    doc.settings.raw_enabled = True  # TODO, check how this works!
    doc.settings.file_insertion_enabled = True
    doc.settings.character_level_inline_markup = False  # TODO, whats sphinx do?
    doc.settings.trim_footnote_reference_space = False  # doesn't seem important

    parser.parse(filedata, doc)
    return doc


def check_spelling(filename):
    with open(filename, 'r', encoding='utf-8') as f:
        filedata = f.read()

        # special content handling
        if filename.endswith(os.path.join("glossary", "index.rst")):
            filedata = filedata_glossary_wash(filedata)

        doc = rst_to_doctree(filedata, filename)
        # print(doc)

    visitor = RstSpellingVisitor(doc)
    doc.walkabout(visitor)


RST_CONTEXT_FLAG_LITERAL = 1 << 0
RST_CONTEXT_FLAG_LITERAL_BLOCK = 1 << 1
RST_CONTEXT_FLAG_MATH = 1 << 2
RST_CONTEXT_FLAG_COMMENT = 1 << 3


class RstSpellingVisitor(docutils.nodes.NodeVisitor):
    __slots__ = (
        "document",
        "skip_context",
    )

    def __init__(self, doc):
        self.document = doc
        self.skip_context = 0

    # -----------------------------
    # Visitors (docutils callbacks)

    def visit_author(self, node):
        print("AUTHOR", node[0])

    # TODO
    def visit_section(self, node):
        pass

    def depart_section(self, node):
        pass

    def visit_title(self, node):
        # print("TITLE", node[0], self.section_level)
        pass

    def depart_title(self, node):
        pass
        # print("/TITLE", node[0])

        '''
        body, body_fmt = self.pop_body()
        align = self.node_align(node)
        elem = BElemText(body, body_fmt, align, self.indent, "style_head%d" % self.section_level)
        self.bdoc.add_elem(elem)
        '''

        # import IPython
        # IPython.embed()

    def visit_list_item(self, node):
        '''
        align = self.node_align(node)
        elem = BElemListItem(align, self.indent, "style_body",
                             self.list_types[-1], self.list_count[-1])
        self.bdoc.add_elem(elem)
        '''
        pass

    def depart_list_item(self, node):
        # self.list_count[-1] += 1
        pass

    def visit_bullet_list(self, node):
        pass
        '''
        self.list_types.append(None)
        self.list_count.append(0)
        '''

    def depart_bullet_list(self, node):
        pass
        '''
        item = self.list_types.pop()
        assert(item == None)
        del self.list_count[-1]
        '''

    def visit_enumerated_list(self, node):
        pass
        '''
        self.list_types.append(node["enumtype"])
        self.list_count.append(0)
        '''

    def depart_enumerated_list(self, node):
        pass
        '''
        item = self.list_types.pop()
        assert(item == node["enumtype"])
        del self.list_count[-1]
        '''

    def visit_paragraph(self, node):
        pass

    def depart_paragraph(self, node):
        pass

        # Just text for now
        # text = node.astext()
        # print(text)
        # check_spelling_body(text)

    def visit_Text(self, node):
        # Visiting text in a sipped context (literal for example).
        if self.skip_context:
            return
        text = node.astext()
        check_spelling_body(text)

    def depart_Text(self, node):
        pass

    def visit_strong(self, node):
        self.is_strong = True

    def depart_strong(self, node):
        self.is_strong = False

    def visit_emphasis(self, node):
        self.is_emphasis = True

    def depart_emphasis(self, node):
        self.is_emphasis = False

    def visit_math(self, node):
        self.skip_context |= RST_CONTEXT_FLAG_MATH
        raise docutils.nodes.SkipNode

    def depart_math(self, node):
        self.skip_context &= ~RST_CONTEXT_FLAG_MATH

    def visit_literal(self, node):
        self.skip_context |= RST_CONTEXT_FLAG_LITERAL
        raise docutils.nodes.SkipNode

    def depart_literal(self, node):
        self.skip_context &= ~RST_CONTEXT_FLAG_LITERAL

    def visit_literal_block(self, node):
        self.skip_context |= RST_CONTEXT_FLAG_LITERAL_BLOCK
        raise docutils.nodes.SkipNode

    def depart_literal_block(self, node):
        self.skip_context &= ~RST_CONTEXT_FLAG_LITERAL_BLOCK
        pass

    def visit_code_block(self, node):
        # No need to flag.
        raise docutils.nodes.SkipNode

    def depart_code_block(self, node):
        pass

    def visit_reference(self, node):
        pass

    def depart_reference(self, node):
        pass

    def visit_title_reference(self, node):
        pass

    def depart_title_reference(self, node):
        pass

    def visit_download_reference(self, node):
        pass

    def depart_download_reference(self, node):
        pass

    def visit_date(self, node):
        # date = datetime.date(*(
        #    map(int, unicode(node[0]).split('-'))))
        # metadata['creation_date'] = date
        pass

    # def visit_document(self, node):
    #    print("TEXT:", node.astext())
    #    # metadata['searchable_text'] = node.astext()

    def visit_comment(self, node):
        self.skip_context |= RST_CONTEXT_FLAG_COMMENT
        raise docutils.nodes.SkipNode

    def depart_comment(self, node):
        self.skip_context &= ~RST_CONTEXT_FLAG_COMMENT

    def visit_raw(self, node):
        raise docutils.nodes.SkipNode

    def depart_raw(self, node):
        pass

    def unknown_visit(self, node):
        pass

    def unknown_departure(self, node):
        pass


if __name__ == "__main__":
    main()