Debian Codegraph @

doc/spec/build-spec.py

raw
1 #!/usr/bin/env python3
2 ############################################################################
3 # Copyright (C) Intel Corporation
4 #
5 # SPDX-License-Identifier: MIT
6 ############################################################################
7 """
8 Build specification.
9 """
10 # pylint: disable=invalid-name,consider-using-f-string
11
12 # Main script to build the specification. Derived from:
13 # github.com/oneapi-src/oneAPI-spec/blob/main/scripts/oneapi.py
14
15 import argparse
16 import glob
17 import os
18 import os.path
19 import sys
20 import shutil
21 import subprocess # nosec B404
22 from functools import wraps
23 from os.path import join
24
25 sphinx_build = 'sphinx-build'
26 source_dir = 'source'
27 build_dir = 'build'
28 doxygen_dir = 'doxygen'
29 doxygen_xml = join(doxygen_dir, 'xml', 'index.xml')
30
31 indent = 0
32 cl_args = []
33
34
35 def action(func):
36 """Execute and log action"""
37 @wraps(func)
38 def wrapped(*args, **kwargs):
39 global indent # pylint: disable=W0603
40 log('%s: %s' % (
41 args[1] if len(args) > 1 and args[1] else wrapped.__name__,
42 args[0],
43 ))
44 indent += 2
45 x = func(*args, **kwargs)
46 indent -= 2
47 return x
48
49 return wrapped
50
51
52 class cd:
53 """Context manager for changing the current working directory"""
54 def __init__(self, newPath):
55 self.savedPath = ""
56 self.newPath = os.path.expanduser(newPath)
57
58 def __enter__(self):
59 self.savedPath = os.getcwd()
60 log('cd ' + self.newPath)
61 os.chdir(self.newPath)
62
63 def __exit__(self, etype, value, traceback):
64 os.chdir(self.savedPath)
65
66
67 def log(*args, **kwargs):
68 """Log message"""
69 print(indent * ' ' + ' '.join(map(str, args)), flush=True, **kwargs)
70
71
72 def shell(c):
73 """Execute shell command"""
74 log(c)
75 if cl_args.dry_run:
76 return
77 subprocess.check_call(c, shell=True) # nosec B602
78
79
80 def copy(src, dst):
81 """Execute copy command"""
82 log('cp', src, dst)
83 if cl_args.dry_run:
84 return
85 shutil.copy(src, dst)
86
87
88 def makedirs(path):
89 """Execute mkdir command"""
90 log('mkdir -p', path)
91 if cl_args.dry_run:
92 return
93 os.makedirs(path)
94
95
96 def sphinx(root, target):
97 """Execute sphinx build"""
98 if not cl_args.verbose:
99 os.environ['LATEXMKOPTS'] = '--silent'
100 os.environ['LATEXOPTS'] = '-interaction=nonstopmode -halt-on-error'
101 sphinx_args = '-N'
102 if not cl_args.verbose:
103 sphinx_args += ' -q'
104 if not cl_args.serial:
105 sphinx_args += ' -j auto'
106 if cl_args.a:
107 sphinx_args += ' -a'
108 if cl_args.n:
109 sphinx_args += ' -n'
110 if cl_args.W:
111 sphinx_args += ' -W'
112
113 shell('%s -M %s %s %s %s' % (
114 sphinx_build,
115 target,
116 join(root, source_dir),
117 join(root, build_dir),
118 sphinx_args,
119 ))
120
121
122 def get_env(var):
123 """Get environment variable"""
124 return os.environ[var] if var in os.environ else ''
125
126
127 def root_only(root):
128 """Check if in root dir"""
129 if root != '.':
130 sys.exit('Error: Only works from root')
131
132
133 @action
134 def dockerbuild(root, _target=None):
135 """Build image"""
136 cd(root)
137 copy(join(root, 'requirements.txt'), join(root, 'docker'))
138 copy(join(root, 'ubuntu-packages.txt'), join(root, 'docker'))
139 copy(join(root, 'install.sh'), join(root, 'docker'))
140 shell('docker build'
141 ' -f ./doc/spec/docker/Dockerfile.build'
142 ' --build-arg http_proxy=%s'
143 ' --build-arg https_proxy=%s'
144 ' --build-arg no_proxy=%s'
145 ' --tag vpl-spec %s' %
146 (get_env('http_proxy'), get_env('https_proxy'), get_env('no_proxy'),
147 join(root, 'docker')))
148
149
150 @action
151 def dockerrun(_root, _target=None):
152 """Run image"""
153 shell('docker run --rm -it'
154 ' -e http_proxy=%s'
155 ' -e https_proxy=%s'
156 ' -e no_proxy=%s'
157 ' --user %s:%s'
158 ' --volume=%s:/build'
159 ' --workdir=/build'
160 ' vpl-spec' % (
161 get_env('http_proxy'),
162 get_env('https_proxy'),
163 get_env('no_proxy'),
164 os.getuid(), # pylint: disable=no-member
165 os.getgid(), # pylint: disable=no-member
166 os.getcwd(),
167 ))
168
169
170 @action
171 def clean(root, _target=None):
172 """Execute sphinx clean"""
173 apply_dirs(root, 'clean')
174 sphinx(root, 'clean')
175
176
177 def command(root, target):
178 """Execute command list"""
179 commands[target](root, target)
180
181
182 def apply_dirs(root, target):
183 """Execute command list"""
184 elements = join(root, 'doc', 'spec')
185 if os.path.exists(elements):
186 for curr_dir in dirs:
187 command(join(elements, curr_dir), target)
188
189
190 def up_to_date(target, deps):
191 """Check if up to date"""
192 if not os.path.exists(target):
193 return False
194 for dep in deps:
195 if os.path.getmtime(target) < os.path.getmtime(dep):
196 return False
197 return True
198
199
200 def doxygen_files(root):
201 """Get doxyfile"""
202 return [join(root, 'Doxyfile')] + glob.glob(join('api', 'vpl', '**'),
203 recursive=True)
204
205
206 def doxygen(root, _target=None):
207 """Execute doxygen build"""
208 with cd(root):
209 doxyfile = 'Doxyfile'
210 if not os.path.exists(doxyfile) or up_to_date(join(root, doxygen_xml),
211 doxygen_files(root)):
212 return
213 shell('doxygen %s' % doxyfile)
214
215
216 @action
217 def prep(root='.', _target=None):
218 """Prepare doxygen build"""
219 apply_dirs(root, 'prep')
220 doxygen(root)
221
222
223 @action
224 def build(root, target):
225 """Build sphinx"""
226 prep(root)
227 sphinx(root, target)
228
229
230 def remove_elements(li, elements):
231 """Remove elements"""
232 for e in elements:
233 if e in li:
234 li.remove(e)
235 return li
236
237
238 @action
239 def sort_words(_root, _target=None):
240 """Sort words in spell check"""
241 with open(join('source', 'spelling_wordlist.txt'),
242 encoding="utf-8") as fin:
243 lines = fin.readlines()
244 with open(join('source', 'spelling_wordlist.txt'), 'w',
245 encoding="utf-8") as fout:
246 for li in sorted(list(set(lines))):
247 fout.write(li)
248
249
250 commands = {
251 'clean': clean,
252 'dockerbuild': dockerbuild,
253 'dockerrun': dockerrun,
254 'html': build,
255 'latexpdf': build,
256 'spelling': build,
257 'singlehtml': build,
258 'prep': prep,
259 'sort-words': sort_words,
260 }
261
262 dirs = [
263 'vpl',
264 ]
265
266
267 def main():
268 """Main specification build"""
269 global cl_args # pylint: disable=W0603
270 parser = argparse.ArgumentParser(
271 description='Build IntelĀ® Video Processing Library spec.')
272 parser.add_argument('action',
273 choices=commands.keys(),
274 default='html',
275 nargs='?')
276 parser.add_argument('root', nargs='?', default=join('doc', 'spec'))
277 parser.add_argument('--branch')
278 parser.add_argument('--verbose', action='store_true')
279 parser.add_argument('--dry-run', action='store_true')
280 parser.add_argument('--serial', action='store_true')
281 parser.add_argument('-W', action='store_true')
282 parser.add_argument('-a',
283 action='store_true',
284 help='sphinx -a (build all files)')
285 parser.add_argument('-n',
286 action='store_true',
287 help='sphinx -n (nitpicky mode)')
288 cl_args = parser.parse_args()
289
290 commands[cl_args.action](cl_args.root, cl_args.action)
291
292
293 main()