1# Copyright 2015-2016 The Meson development team
2
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6
7#     http://www.apache.org/licenses/LICENSE-2.0
8
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import sys, os
16import subprocess
17import shutil
18import argparse
19from ..mesonlib import MesonException, Popen_safe, is_windows, is_cygwin, split_args
20from . import destdir_join
21
22parser = argparse.ArgumentParser()
23
24parser.add_argument('--sourcedir', dest='sourcedir')
25parser.add_argument('--builddir', dest='builddir')
26parser.add_argument('--subdir', dest='subdir')
27parser.add_argument('--headerdirs', dest='headerdirs')
28parser.add_argument('--mainfile', dest='mainfile')
29parser.add_argument('--modulename', dest='modulename')
30parser.add_argument('--moduleversion', dest='moduleversion')
31parser.add_argument('--htmlargs', dest='htmlargs', default='')
32parser.add_argument('--scanargs', dest='scanargs', default='')
33parser.add_argument('--scanobjsargs', dest='scanobjsargs', default='')
34parser.add_argument('--gobjects-types-file', dest='gobject_typesfile', default='')
35parser.add_argument('--fixxrefargs', dest='fixxrefargs', default='')
36parser.add_argument('--mkdbargs', dest='mkdbargs', default='')
37parser.add_argument('--ld', dest='ld', default='')
38parser.add_argument('--cc', dest='cc', default='')
39parser.add_argument('--ldflags', dest='ldflags', default='')
40parser.add_argument('--cflags', dest='cflags', default='')
41parser.add_argument('--content-files', dest='content_files', default='')
42parser.add_argument('--expand-content-files', dest='expand_content_files', default='')
43parser.add_argument('--html-assets', dest='html_assets', default='')
44parser.add_argument('--ignore-headers', dest='ignore_headers', default='')
45parser.add_argument('--namespace', dest='namespace', default='')
46parser.add_argument('--mode', dest='mode', default='')
47parser.add_argument('--installdir', dest='install_dir')
48parser.add_argument('--run', dest='run', default='')
49for tool in ['scan', 'scangobj', 'mkdb', 'mkhtml', 'fixxref']:
50    program_name = 'gtkdoc-' + tool
51    parser.add_argument('--' + program_name, dest=program_name.replace('-', '_'))
52
53def gtkdoc_run_check(cmd, cwd, library_paths=None):
54    if library_paths is None:
55        library_paths = []
56
57    env = dict(os.environ)
58    if is_windows() or is_cygwin():
59        if 'PATH' in env:
60            library_paths.extend(env['PATH'].split(os.pathsep))
61        env['PATH'] = os.pathsep.join(library_paths)
62    else:
63        if 'LD_LIBRARY_PATH' in env:
64            library_paths.extend(env['LD_LIBRARY_PATH'].split(os.pathsep))
65        env['LD_LIBRARY_PATH'] = os.pathsep.join(library_paths)
66
67    if is_windows():
68        cmd.insert(0, sys.executable)
69
70    # Put stderr into stdout since we want to print it out anyway.
71    # This preserves the order of messages.
72    p, out = Popen_safe(cmd, cwd=cwd, env=env, stderr=subprocess.STDOUT)[0:2]
73    if p.returncode != 0:
74        err_msg = ["{!r} failed with status {:d}".format(cmd, p.returncode)]
75        if out:
76            err_msg.append(out)
77        raise MesonException('\n'.join(err_msg))
78    elif out:
79        # Unfortunately Windows cmd.exe consoles may be using a codepage
80        # that might choke print() with a UnicodeEncodeError, so let's
81        # ignore such errors for now, as a compromise as we are outputting
82        # console output here...
83        try:
84            print(out)
85        except UnicodeEncodeError:
86            pass
87
88def build_gtkdoc(source_root, build_root, doc_subdir, src_subdirs,
89                 main_file, module, module_version,
90                 html_args, scan_args, fixxref_args, mkdb_args,
91                 gobject_typesfile, scanobjs_args, run, ld, cc, ldflags, cflags,
92                 html_assets, content_files, ignore_headers, namespace,
93                 expand_content_files, mode, options):
94    print("Building documentation for %s" % module)
95
96    src_dir_args = []
97    for src_dir in src_subdirs:
98        if not os.path.isabs(src_dir):
99            dirs = [os.path.join(source_root, src_dir),
100                    os.path.join(build_root, src_dir)]
101        else:
102            dirs = [src_dir]
103        src_dir_args += ['--source-dir=' + d for d in dirs]
104
105    doc_src = os.path.join(source_root, doc_subdir)
106    abs_out = os.path.join(build_root, doc_subdir)
107    htmldir = os.path.join(abs_out, 'html')
108
109    content_files += [main_file]
110    sections = os.path.join(doc_src, module + "-sections.txt")
111    if os.path.exists(sections):
112        content_files.append(sections)
113
114    overrides = os.path.join(doc_src, module + "-overrides.txt")
115    if os.path.exists(overrides):
116        content_files.append(overrides)
117
118    # Copy files to build directory
119    for f in content_files:
120        # FIXME: Use mesonlib.File objects so we don't need to do this
121        if not os.path.isabs(f):
122            f = os.path.join(doc_src, f)
123        elif os.path.commonpath([f, build_root]) == build_root:
124            continue
125        shutil.copyfile(f, os.path.join(abs_out, os.path.basename(f)))
126
127    shutil.rmtree(htmldir, ignore_errors=True)
128    try:
129        os.mkdir(htmldir)
130    except Exception:
131        pass
132
133    for f in html_assets:
134        f_abs = os.path.join(doc_src, f)
135        shutil.copyfile(f_abs, os.path.join(htmldir, os.path.basename(f_abs)))
136
137    scan_cmd = [options.gtkdoc_scan, '--module=' + module] + src_dir_args
138    if ignore_headers:
139        scan_cmd.append('--ignore-headers=' + ' '.join(ignore_headers))
140    # Add user-specified arguments
141    scan_cmd += scan_args
142    gtkdoc_run_check(scan_cmd, abs_out)
143
144    # Use the generated types file when available, otherwise gobject_typesfile
145    # would often be a path to source dir instead of build dir.
146    if '--rebuild-types' in scan_args:
147        gobject_typesfile = os.path.join(abs_out, module + '.types')
148
149    if gobject_typesfile:
150        scanobjs_cmd = [options.gtkdoc_scangobj] + scanobjs_args
151        scanobjs_cmd += ['--types=' + gobject_typesfile,
152                         '--module=' + module,
153                         '--run=' + run,
154                         '--cflags=' + cflags,
155                         '--ldflags=' + ldflags,
156                         '--cc=' + cc,
157                         '--ld=' + ld,
158                         '--output-dir=' + abs_out]
159
160        library_paths = []
161        for ldflag in split_args(ldflags):
162            if ldflag.startswith('-Wl,-rpath,'):
163                library_paths.append(ldflag[11:])
164
165        gtkdoc_run_check(scanobjs_cmd, build_root, library_paths)
166
167    # Make docbook files
168    if mode == 'auto':
169        # Guessing is probably a poor idea but these keeps compat
170        # with previous behavior
171        if main_file.endswith('sgml'):
172            modeflag = '--sgml-mode'
173        else:
174            modeflag = '--xml-mode'
175    elif mode == 'xml':
176        modeflag = '--xml-mode'
177    elif mode == 'sgml':
178        modeflag = '--sgml-mode'
179    else: # none
180        modeflag = None
181
182    mkdb_cmd = [options.gtkdoc_mkdb,
183                '--module=' + module,
184                '--output-format=xml',
185                '--expand-content-files=' + ' '.join(expand_content_files),
186                ] + src_dir_args
187    if namespace:
188        mkdb_cmd.append('--name-space=' + namespace)
189    if modeflag:
190        mkdb_cmd.append(modeflag)
191    if main_file:
192        # Yes, this is the flag even if the file is in xml.
193        mkdb_cmd.append('--main-sgml-file=' + main_file)
194    # Add user-specified arguments
195    mkdb_cmd += mkdb_args
196    gtkdoc_run_check(mkdb_cmd, abs_out)
197
198    # Make HTML documentation
199    mkhtml_cmd = [options.gtkdoc_mkhtml,
200                  '--path=' + ':'.join((doc_src, abs_out)),
201                  module,
202                  ] + html_args
203    if main_file:
204        mkhtml_cmd.append('../' + main_file)
205    else:
206        mkhtml_cmd.append('%s-docs.xml' % module)
207    # html gen must be run in the HTML dir
208    gtkdoc_run_check(mkhtml_cmd, htmldir)
209
210    # Fix cross-references in HTML files
211    fixref_cmd = [options.gtkdoc_fixxref,
212                  '--module=' + module,
213                  '--module-dir=html'] + fixxref_args
214    gtkdoc_run_check(fixref_cmd, abs_out)
215
216    if module_version:
217        shutil.move(os.path.join(htmldir, '{}.devhelp2'.format(module)),
218                    os.path.join(htmldir, '{}-{}.devhelp2'.format(module, module_version)))
219
220def install_gtkdoc(build_root, doc_subdir, install_prefix, datadir, module):
221    source = os.path.join(build_root, doc_subdir, 'html')
222    final_destination = os.path.join(install_prefix, datadir, module)
223    shutil.rmtree(final_destination, ignore_errors=True)
224    shutil.copytree(source, final_destination)
225
226def run(args):
227    options = parser.parse_args(args)
228    if options.htmlargs:
229        htmlargs = options.htmlargs.split('@@')
230    else:
231        htmlargs = []
232    if options.scanargs:
233        scanargs = options.scanargs.split('@@')
234    else:
235        scanargs = []
236    if options.scanobjsargs:
237        scanobjsargs = options.scanobjsargs.split('@@')
238    else:
239        scanobjsargs = []
240    if options.fixxrefargs:
241        fixxrefargs = options.fixxrefargs.split('@@')
242    else:
243        fixxrefargs = []
244    if options.mkdbargs:
245        mkdbargs = options.mkdbargs.split('@@')
246    else:
247        mkdbargs = []
248    build_gtkdoc(
249        options.sourcedir,
250        options.builddir,
251        options.subdir,
252        options.headerdirs.split('@@'),
253        options.mainfile,
254        options.modulename,
255        options.moduleversion,
256        htmlargs,
257        scanargs,
258        fixxrefargs,
259        mkdbargs,
260        options.gobject_typesfile,
261        scanobjsargs,
262        options.run,
263        options.ld,
264        options.cc,
265        options.ldflags,
266        options.cflags,
267        options.html_assets.split('@@') if options.html_assets else [],
268        options.content_files.split('@@') if options.content_files else [],
269        options.ignore_headers.split('@@') if options.ignore_headers else [],
270        options.namespace,
271        options.expand_content_files.split('@@') if options.expand_content_files else [],
272        options.mode,
273        options)
274
275    if 'MESON_INSTALL_PREFIX' in os.environ:
276        destdir = os.environ.get('DESTDIR', '')
277        install_prefix = destdir_join(destdir, os.environ['MESON_INSTALL_PREFIX'])
278        if options.install_dir:
279            install_dir = options.install_dir
280        else:
281            install_dir = options.modulename
282            if options.moduleversion:
283                install_dir += '-' + options.moduleversion
284        if os.path.isabs(install_dir):
285            install_dir = destdir_join(destdir, install_dir)
286        install_gtkdoc(options.builddir,
287                       options.subdir,
288                       install_prefix,
289                       'share/gtk-doc/html',
290                       install_dir)
291    return 0
292
293if __name__ == '__main__':
294    sys.exit(run(sys.argv[1:]))
295