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
|
"""
sphinx.io
~~~~~~~~~
Input/Output files
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import codecs
from typing import Any
from docutils.core import Publisher
from docutils.io import FileInput, NullOutput
from docutils.parsers.rst import Parser as RSTParser
from docutils.readers import standalone
from docutils.transforms.references import DanglingReferences
from docutils.writers import UnfilteredWriter
from sphinx.transforms import (
AutoIndexUpgrader, DoctreeReadEvent, FigureAligner, SphinxTransformer
)
from sphinx.transforms.i18n import (
PreserveTranslatableMessages, Locale, RemoveTranslatableInline,
)
from sphinx.transforms.references import SphinxDomains
from sphinx.util import logging
from sphinx.util import UnicodeDecodeErrorHandler
from sphinx.util.docutils import LoggingReporter
from sphinx.versioning import UIDTransform
if False:
# For type annotation
from typing import Dict, List, Tuple # NOQA
from typing import Type # for python3.5.1
from docutils import nodes # NOQA
from docutils.frontend import Values # NOQA
from docutils.io import Input # NOQA
from docutils.parsers import Parser # NOQA
from docutils.transforms import Transform # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.environment import BuildEnvironment # NOQA
logger = logging.getLogger(__name__)
class SphinxBaseReader(standalone.Reader):
"""
A base class of readers for Sphinx.
This replaces reporter by Sphinx's on generating document.
"""
transforms = [] # type: List[Type[Transform]]
def __init__(self, app, *args, **kwargs):
# type: (Sphinx, Any, Any) -> None
self.app = app
self.env = app.env
super().__init__(*args, **kwargs)
def get_transforms(self):
# type: () -> List[Type[Transform]]
transforms = super().get_transforms() + self.transforms
# remove transforms which is not needed for Sphinx
unused = [DanglingReferences]
for transform in unused:
if transform in transforms:
transforms.remove(transform)
return transforms
def new_document(self):
# type: () -> nodes.document
"""Creates a new document object which having a special reporter object good
for logging.
"""
document = super().new_document()
# substitute transformer
document.transformer = SphinxTransformer(document)
document.transformer.set_environment(self.env)
# substitute reporter
reporter = document.reporter
document.reporter = LoggingReporter.from_reporter(reporter)
return document
class SphinxStandaloneReader(SphinxBaseReader):
"""
A basic document reader for Sphinx.
"""
def __init__(self, app, *args, **kwargs):
# type: (Sphinx, Any, Any) -> None
self.transforms = self.transforms + app.registry.get_transforms()
super().__init__(app, *args, **kwargs)
def read(self, source, parser, settings):
# type: (Input, Parser, Values) -> nodes.document
self.source = source
if not self.parser:
self.parser = parser
self.settings = settings
self.input = self.read_source()
self.parse()
return self.document
def read_source(self):
# type: () -> str
"""Read content from source and do post-process."""
content = self.source.read()
# emit "source-read" event
arg = [content]
self.app.emit('source-read', self.env.docname, arg)
return arg[0]
class SphinxI18nReader(SphinxBaseReader):
"""
A document reader for i18n.
This returns the source line number of original text as current source line number
to let users know where the error happened.
Because the translated texts are partial and they don't have correct line numbers.
"""
def __init__(self, app, *args, **kwargs):
# type: (Sphinx, Any, Any) -> None
self.transforms = self.transforms + app.registry.get_transforms()
unused = [PreserveTranslatableMessages, Locale, RemoveTranslatableInline,
AutoIndexUpgrader, FigureAligner, SphinxDomains, DoctreeReadEvent,
UIDTransform]
for transform in unused:
if transform in self.transforms:
self.transforms.remove(transform)
super().__init__(app, *args, **kwargs)
class SphinxDummyWriter(UnfilteredWriter):
"""Dummy writer module used for generating doctree."""
supported = ('html',) # needed to keep "meta" nodes
def translate(self):
# type: () -> None
pass
def SphinxDummySourceClass(source, *args, **kwargs):
# type: (Any, Any, Any) -> Any
"""Bypass source object as is to cheat Publisher."""
return source
class SphinxFileInput(FileInput):
"""A basic FileInput for Sphinx."""
def __init__(self, *args, **kwargs):
# type: (Any, Any) -> None
kwargs['error_handler'] = 'sphinx'
super().__init__(*args, **kwargs)
class FiletypeNotFoundError(Exception):
pass
def get_filetype(source_suffix, filename):
# type: (Dict[str, str], str) -> str
for suffix, filetype in source_suffix.items():
if filename.endswith(suffix):
# If default filetype (None), considered as restructuredtext.
return filetype or 'restructuredtext'
else:
raise FiletypeNotFoundError
def read_doc(app, env, filename):
# type: (Sphinx, BuildEnvironment, str) -> nodes.document
"""Parse a document and convert to doctree."""
# set up error_handler for the target document
error_handler = UnicodeDecodeErrorHandler(env.docname)
codecs.register_error('sphinx', error_handler) # type: ignore
reader = SphinxStandaloneReader(app)
filetype = get_filetype(app.config.source_suffix, filename)
parser = app.registry.create_source_parser(app, filetype)
if parser.__class__.__name__ == 'CommonMarkParser' and parser.settings_spec == ():
# a workaround for recommonmark
# If recommonmark.AutoStrictify is enabled, the parser invokes reST parser
# internally. But recommonmark-0.4.0 does not provide settings_spec for reST
# parser. As a workaround, this copies settings_spec for RSTParser to the
# CommonMarkParser.
parser.settings_spec = RSTParser.settings_spec
input_class = app.registry.get_source_input(filetype)
if input_class:
# Sphinx-1.8 style
source = input_class(app, env, source=None, source_path=filename, # type: ignore
encoding=env.config.source_encoding)
pub = Publisher(reader=reader, # type: ignore
parser=parser,
writer=SphinxDummyWriter(),
source_class=SphinxDummySourceClass,
destination=NullOutput())
pub.process_programmatic_settings(None, env.settings, None)
pub.set_source(source, filename)
else:
# Sphinx-2.0 style
pub = Publisher(reader=reader,
parser=parser,
writer=SphinxDummyWriter(),
source_class=SphinxFileInput,
destination=NullOutput())
pub.process_programmatic_settings(None, env.settings, None)
pub.set_source(source_path=filename)
pub.publish()
return pub.document
|