forked from robotframework/robotframework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathug2html.py
executable file
·301 lines (237 loc) · 9.76 KB
/
ug2html.py
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
#!/usr/bin/env python3
"""ug2html.py -- Creates HTML version of Robot Framework User Guide
Usage: ug2html.py [ cr(eate) | dist | zip ]
create .. Creates the user guide so that it has relative links to images,
library docs, etc. Mainly used to test how changes look in HTML.
dist .... Creates the user guide under 'robotframework-userguide-<version>'
directory and also copies all needed images and other link targets
there. The created output directory can thus be distributed
independently.
Note: Before running this command, you must generate documents at
project root, for example, with: invoke library-docs all
zip ..... Uses 'dist' to create a stand-alone distribution and then packages
it into 'robotframework-userguide-<version>.zip'
Version number to use is got automatically from 'src/robot/version.py' file.
"""
import os
import sys
import shutil
# First part of this file is Pygments configuration and actual
# documentation generation follows it.
#
#
# Pygments configuration
# ----------------------
#
# This code is from 'external/rst-directive.py' file included in Pygments 0.9
# distribution. For more details see http://pygments.org/docs/rstdirective/
#
"""
The Pygments MoinMoin Parser
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This fragment is a Docutils_ 0.4 directive that renders source code
(to HTML only, currently) via Pygments.
To use it, adjust the options below and copy the code into a module
that you import on initialization. The code then automatically
registers a ``sourcecode`` directive that you can use instead of
normal code blocks like this::
.. sourcecode:: python
My code goes here.
If you want to have different code styles, e.g. one with line numbers
and one without, add formatters with their names in the VARIANTS dict
below. You can invoke them instead of the DEFAULT one by using a
directive option::
.. sourcecode:: python
:linenos:
My code goes here.
Look at the `directive documentation`_ to get all the gory details.
.. _Docutils: http://docutils.sf.net/
.. _directive documentation:
http://docutils.sourceforge.net/docs/howto/rst-directives.html
:copyright: 2007 by Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
# Options
# ~~~~~~~
# Set to True if you want inline CSS styles instead of classes
INLINESTYLES = False
from pygments.formatters import HtmlFormatter
# The default formatter
DEFAULT = HtmlFormatter(noclasses=INLINESTYLES)
# Add name -> formatter pairs for every variant you want to use
VARIANTS = {
# 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),
}
from docutils import nodes
from docutils.parsers.rst import directives
from pygments import highlight, __version__ as pygments_version
from pygments.lexers import get_lexer_by_name
# Use latest version, not version bundled with Pygments
import robotframeworklexer
def too_old(version_string, minimum):
version = tuple(int(v) for v in version_string.split('.')[:2])
return version < minimum
if too_old(getattr(robotframeworklexer, '__version__', '1.0'), (1, 1)):
sys.exit('robotframeworklexer >= 1.1 is required.')
if too_old(pygments_version, (2, 1)):
sys.exit('Pygments >= 2.1 is required.')
def pygments_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
try:
if arguments[0] == 'robotframework':
lexer = robotframeworklexer.RobotFrameworkLexer()
else:
lexer = get_lexer_by_name(arguments[0])
except ValueError as err:
raise ValueError(f'Invalid syntax highlighting language "{arguments[0]}".')
# take an arbitrary option if more than one is given
formatter = options and VARIANTS[options.keys()[0]] or DEFAULT
# possibility to read the content from an external file
filtered = [ line for line in content if line.strip() ]
if len(filtered) == 1:
path = filtered[0].replace('/', os.sep)
if os.path.isfile(path):
content = open(path, encoding="utf-8").read().splitlines()
parsed = highlight(u'\n'.join(content), lexer, formatter)
return [nodes.raw('', parsed, format='html')]
pygments_directive.arguments = (1, 0, 1)
pygments_directive.content = 1
pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS])
directives.register_directive('sourcecode', pygments_directive)
#
# Create the user guide using docutils
#
# This code is based on rst2html.py distributed with docutils
#
CURDIR = os.path.dirname(os.path.abspath(__file__))
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except ImportError:
pass
def create_userguide():
from docutils.core import publish_cmdline
print('Creating user guide ...')
version, version_file = _update_version()
install_file = _copy_installation_instructions()
description = 'HTML generator for Robot Framework User Guide.'
arguments = ['--time',
'--stylesheet-path', ['src/userguide.css'],
'src/RobotFrameworkUserGuide.rst',
'RobotFrameworkUserGuide.html']
os.chdir(CURDIR)
publish_cmdline(writer_name='html', description=description, argv=arguments)
os.unlink(version_file)
os.unlink(install_file)
ugpath = os.path.abspath(arguments[-1])
print(ugpath)
return ugpath, version
def _update_version():
version = _get_version()
print(f'Version: {version}')
with open(os.path.join(CURDIR, 'src', 'version.rst'), 'w',
encoding="utf-8") as vfile:
vfile.write(f'.. |version| replace:: {version}\n')
return version, vfile.name
def _get_version():
namespace = {}
versionfile = os.path.join(CURDIR, '..', '..', 'src', 'robot', 'version.py')
with open(versionfile, encoding="utf-8") as f:
code = compile(f.read(), versionfile, 'exec')
exec(code, namespace)
return namespace['get_version']()
def _copy_installation_instructions():
source = os.path.join(CURDIR, '..', '..', 'INSTALL.rst')
target = os.path.join(CURDIR, 'src', 'GettingStarted', 'INSTALL.rst')
include = True
with open(source, encoding="utf-8") as source_file:
with open(target, 'w', encoding="utf-8") as target_file:
for line in source_file:
if 'START USER GUIDE IGNORE' in line:
include = False
if include:
target_file.write(line)
if 'END USER GUIDE IGNORE' in line:
include = True
return target
#
# Create user guide distribution directory
#
def create_distribution():
import re
from urllib.parse import urlparse
dist = os.path.normpath(os.path.join(CURDIR, '..', '..', 'dist'))
ugpath, version = create_userguide() # we are in doc/userguide after this
outdir = os.path.join(dist, f'robotframework-userguide-{version}')
libraries = os.path.join(outdir, 'libraries')
images = os.path.join(outdir, 'images')
print('Creating distribution directory ...')
if os.path.exists(outdir):
print('Removing previous user guide distribution')
shutil.rmtree(outdir)
elif not os.path.exists(dist):
os.mkdir(dist)
for dirname in [outdir, libraries, images]:
print(f'Creating output directory {dirname!r}')
os.mkdir(dirname)
def replace_links(res):
if not res.group(5):
return res.group(0)
scheme, _, path, _, _, fragment = urlparse(res.group(5))
if scheme or (fragment and not path):
return res.group(0)
replaced_link = f'{res.group(1)} {res.group(4)}="%s/{os.path.basename(path)}"'
if path.startswith('../libraries'):
copy(path, libraries)
replaced_link = replaced_link % 'libraries'
elif path.startswith('src/'):
copy(path, images)
replaced_link = replaced_link % 'images'
else:
raise ValueError(f'Invalid link target: {path} ('
f'context: {res.group(0)})')
print(f'Modified link {res.group(0)!r} -> {replaced_link!r}')
return replaced_link
def copy(source, dest):
print(f'Copying {source!r} -> {dest!r}')
shutil.copy(source, dest)
link_regexp = re.compile('''
(<(a|img)\s+.*?)
(\s+(href|src)="(.*?)"|>)
''', re.VERBOSE | re.DOTALL | re.IGNORECASE)
with open(ugpath, encoding="utf-8") as infile:
content = link_regexp.sub(replace_links, infile.read())
with open(os.path.join(outdir, os.path.basename(ugpath)), 'w',
encoding="utf-8") as outfile:
outfile.write(content)
print(os.path.abspath(outfile.name))
return outdir
#
# Create a zip distribution package
#
def create_zip():
ugdir = create_distribution()
print('Creating zip package ...')
zip_path = zip_distribution(ugdir)
print(f'Removing distribution directory {ugdir!r}')
shutil.rmtree(ugdir)
print(zip_path)
def zip_distribution(dirpath):
from zipfile import ZipFile, ZIP_DEFLATED
zippath = os.path.normpath(dirpath) + '.zip'
arcroot = os.path.dirname(dirpath)
with ZipFile(zippath, 'w', compression=ZIP_DEFLATED) as zipfile:
for root, _, files in os.walk(dirpath):
for name in files:
path = os.path.join(root, name)
arcpath = os.path.relpath(path, arcroot)
print(f'Adding {arcpath!r}')
zipfile.write(path, arcpath)
return os.path.abspath(zippath)
if __name__ == '__main__':
actions = { 'create': create_userguide, 'cr': create_userguide,
'dist': create_distribution, 'zip': create_zip }
try:
actions[sys.argv[1]](*sys.argv[2:])
except (KeyError, IndexError, TypeError):
print(__doc__)