summaryrefslogtreecommitdiff
path: root/sphinx/cmdline.py
blob: 6e7ab3267915e27dd9579ef646e9ec7dffd1584f (plain)
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
# -*- coding: utf-8 -*-
"""
    sphinx.cmdline
    ~~~~~~~~~~~~~~

    sphinx-build command-line handling.

    :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""
from __future__ import print_function

import os
import sys
import getopt
import traceback
from os import path

from six import text_type, binary_type
from docutils.utils import SystemMessage

from sphinx import __version__
from sphinx.errors import SphinxError
from sphinx.application import Sphinx
from sphinx.util import Tee, format_exception_cut_frames, save_traceback
from sphinx.util.console import red, nocolor, color_terminal
from sphinx.util.osutil import abspath, fs_encoding
from sphinx.util.pycompat import terminal_safe


def usage(argv, msg=None):
    if msg:
        print(msg, file=sys.stderr)
        print(file=sys.stderr)
    print("""\
Sphinx v%s
Usage: %s [options] sourcedir outdir [filenames...]

General options
^^^^^^^^^^^^^^^
-b <builder>  builder to use; default is html
-a            write all files; default is to only write new and changed files
-E            don't use a saved environment, always read all files
-d <path>     path for the cached environment and doctree files
                (default: outdir/.doctrees)
-j <N>        build in parallel with N processes where possible
-M <builder>  "make" mode -- used by Makefile, like "sphinx-build -M html"

Build configuration options
^^^^^^^^^^^^^^^^^^^^^^^^^^^
-c <path>           path where configuration file (conf.py) is located
                      (default: same as sourcedir)
-C                  use no config file at all, only -D options
-D <setting=value>  override a setting in configuration file
-t <tag>            define tag: include "only" blocks with <tag>
-A <name=value>     pass a value into the templates, for HTML builder
-n                  nit-picky mode, warn about all missing references

Console output options
^^^^^^^^^^^^^^^^^^^^^^
-v         increase verbosity (can be repeated)
-q         no output on stdout, just warnings on stderr
-Q         no output at all, not even warnings
-w <file>  write warnings (and errors) to given file
-W         turn warnings into errors
-T         show full traceback on exception
-N         do not emit colored output
-P         run Pdb on exception

Filename arguments
^^^^^^^^^^^^^^^^^^
* without -a and without filenames, write new and changed files.
* with -a, write all files.
* with filenames, write these.

Standard options
^^^^^^^^^^^^^^^^
-h, --help  show this help and exit
--version   show version information and exit
""" % (__version__, argv[0]), file=sys.stderr)


def main(argv):
    if not color_terminal():
        nocolor()

    # parse options
    try:
        opts, args = getopt.getopt(argv[1:], 'ab:t:d:c:CD:A:nNEqQWw:PThvj:',
                                   ['help', 'version'])
    except getopt.error as err:
        usage(argv, 'Error: %s' % err)
        return 1

    # handle basic options
    allopts = set(opt[0] for opt in opts)
    # help and version options
    if '-h' in allopts or '--help' in allopts:
        usage(argv)
        print(file=sys.stderr)
        print('For more information, see <http://sphinx-doc.org/>.',
              file=sys.stderr)
        return 0
    if '--version' in allopts:
        print('Sphinx (sphinx-build) %s' %  __version__)
        return 0

    # get paths (first and second positional argument)
    try:
        srcdir = confdir = abspath(args[0])
        if not path.isdir(srcdir):
            print('Error: Cannot find source directory `%s\'.' % srcdir,
                  file=sys.stderr)
            return 1
        if not path.isfile(path.join(srcdir, 'conf.py')) and \
               '-c' not in allopts and '-C' not in allopts:
            print('Error: Source directory doesn\'t contain a conf.py file.',
                  file=sys.stderr)
            return 1
        outdir = abspath(args[1])
    except IndexError:
        usage(argv, 'Error: Insufficient arguments.')
        return 1
    except UnicodeError:
        print(
            'Error: Multibyte filename not supported on this filesystem '
            'encoding (%r).' % fs_encoding, file=sys.stderr)
        return 1

    # handle remaining filename arguments
    filenames = args[2:]
    err = 0
    for filename in filenames:
        if not path.isfile(filename):
            print('Error: Cannot find file %r.' % filename, file=sys.stderr)
            err = 1
    if err:
        return 1

    # likely encoding used for command-line arguments
    try:
        locale = __import__('locale')  # due to submodule of the same name
        likely_encoding = locale.getpreferredencoding()
    except Exception:
        likely_encoding = None

    buildername = None
    force_all = freshenv = warningiserror = use_pdb = False
    show_traceback = False
    verbosity = 0
    parallel = 0
    status = sys.stdout
    warning = sys.stderr
    error = sys.stderr
    warnfile = None
    confoverrides = {}
    tags = []
    doctreedir = path.join(outdir, '.doctrees')
    for opt, val in opts:
        if opt == '-b':
            buildername = val
        elif opt == '-a':
            if filenames:
                usage(argv, 'Error: Cannot combine -a option and filenames.')
                return 1
            force_all = True
        elif opt == '-t':
            tags.append(val)
        elif opt == '-d':
            doctreedir = abspath(val)
        elif opt == '-c':
            confdir = abspath(val)
            if not path.isfile(path.join(confdir, 'conf.py')):
                print('Error: Configuration directory doesn\'t contain conf.py file.',
                      file=sys.stderr)
                return 1
        elif opt == '-C':
            confdir = None
        elif opt == '-D':
            try:
                key, val = val.split('=')
            except ValueError:
                print('Error: -D option argument must be in the form name=value.',
                      file=sys.stderr)
                return 1
            if likely_encoding and isinstance(val, binary_type):
                try:
                    val = val.decode(likely_encoding)
                except UnicodeError:
                    pass
            confoverrides[key] = val
        elif opt == '-A':
            try:
                key, val = val.split('=')
            except ValueError:
                print('Error: -A option argument must be in the form name=value.',
                      file=sys.stderr)
                return 1
            try:
                val = int(val)
            except ValueError:
                if likely_encoding and isinstance(val, binary_type):
                    try:
                        val = val.decode(likely_encoding)
                    except UnicodeError:
                        pass
            confoverrides['html_context.%s' % key] = val
        elif opt == '-n':
            confoverrides['nitpicky'] = True
        elif opt == '-N':
            nocolor()
        elif opt == '-E':
            freshenv = True
        elif opt == '-q':
            status = None
        elif opt == '-Q':
            status = None
            warning = None
        elif opt == '-W':
            warningiserror = True
        elif opt == '-w':
            warnfile = val
        elif opt == '-P':
            use_pdb = True
        elif opt == '-T':
            show_traceback = True
        elif opt == '-v':
            verbosity += 1
            show_traceback = True
        elif opt == '-j':
            try:
                parallel = int(val)
            except ValueError:
                print('Error: -j option argument must be an integer.',
                      file=sys.stderr)
                return 1

    if warning and warnfile:
        warnfp = open(warnfile, 'w')
        warning = Tee(warning, warnfp)
        error = warning

    if not path.isdir(outdir):
        if status:
            print('Making output directory...', file=status)
        os.makedirs(outdir)

    app = None
    try:
        app = Sphinx(srcdir, confdir, outdir, doctreedir, buildername,
                     confoverrides, status, warning, freshenv,
                     warningiserror, tags, verbosity, parallel)
        app.build(force_all, filenames)
        return app.statuscode
    except (Exception, KeyboardInterrupt) as err:
        if use_pdb:
            import pdb
            print(red('Exception occurred while building, starting debugger:'),
                  file=error)
            traceback.print_exc()
            pdb.post_mortem(sys.exc_info()[2])
        else:
            print(file=error)
            if show_traceback:
                traceback.print_exc(None, error)
                print(file=error)
            if isinstance(err, KeyboardInterrupt):
                print('interrupted!', file=error)
            elif isinstance(err, SystemMessage):
                print(red('reST markup error:'), file=error)
                print(terminal_safe(err.args[0]), file=error)
            elif isinstance(err, SphinxError):
                print(red('%s:' % err.category), file=error)
                print(terminal_safe(text_type(err)), file=error)
            elif isinstance(err, UnicodeError):
                print(red('Encoding error:'), file=error)
                print(terminal_safe(text_type(err)), file=error)
                tbpath = save_traceback(app)
                print(red('The full traceback has been saved in %s, if you want '
                          'to report the issue to the developers.' % tbpath),
                      file=error)
            else:
                print(red('Exception occurred:'), file=error)
                print(format_exception_cut_frames().rstrip(), file=error)
                tbpath = save_traceback(app)
                print(red('The full traceback has been saved in %s, if you '
                          'want to report the issue to the developers.' % tbpath),
                      file=error)
                print('Please also report this if it was a user error, so '
                      'that a better error message can be provided next time.',
                      file=error)
                print('A bug report can be filed in the tracker at '
                      '<https://bitbucket.org/birkenfeld/sphinx/issues/>. Thanks!',
                      file=error)
            return 1