Beispiel #1
0
def main(argv):
    if not color_terminal():
        # Windows' poor cmd box doesn't understand ANSI sequences
        nocolor()

    try:
        opts, args = getopt.getopt(argv[1:], "ab:t:d:c:CD:A:nNEqQWw:PThvj:", ["help", "version"])
        allopts = set(opt[0] for opt in opts)
        if "-h" in allopts or "--help" in allopts:
            usage(argv)
            print >> sys.stderr
            print >> sys.stderr, "For more information, see " "<http://sphinx-doc.org/>."
            return 0
        if "--version" in allopts:
            print "Sphinx (sphinx-build) %s" % __version__
            return 0
        srcdir = confdir = abspath(args[0])
        if not path.isdir(srcdir):
            print >> sys.stderr, "Error: Cannot find source directory `%s'." % (srcdir,)
            return 1
        if not path.isfile(path.join(srcdir, "conf.py")) and "-c" not in allopts and "-C" not in allopts:
            print >> sys.stderr, ("Error: Source directory doesn't " "contain conf.py file.")
            return 1
        outdir = abspath(args[1])
    except getopt.error, err:
        usage(argv, "Error: %s" % err)
        return 1
Beispiel #2
0
def main(argv):
    if not color_terminal():
        # Windows' poor cmd box doesn't understand ANSI sequences
        nocolor()

    try:
        opts, args = getopt.getopt(argv[1:], 'ab:t:d:c:CD:A:ng:NEqQWw:PThv',
                                   ['help', 'version'])
        allopts = set(opt[0] for opt in opts)
        if '-h' in allopts or '--help' in allopts:
            usage(argv)
            return 0
        if '--version' in allopts:
            print 'Sphinx (sphinx-build) %s' %  __version__
            return 0
        srcdir = confdir = abspath(args[0])
        if not path.isdir(srcdir):
            print >>sys.stderr, 'Error: Cannot find source directory `%s\'.' % (
                                srcdir,)
            return 1
        if not path.isfile(path.join(srcdir, 'conf.py')) and \
               '-c' not in allopts and '-C' not in allopts:
            print >>sys.stderr, ('Error: Source directory doesn\'t '
                                 'contain conf.py file.')
            return 1
        outdir = abspath(args[1])
        if not path.isdir(outdir):
            print >>sys.stderr, 'Making output directory...'
            os.makedirs(outdir)
    except getopt.error, err:
        usage(argv, 'Error: %s' % err)
        return 1
    def run(self):
        if not color_terminal():
            # Windows' poor cmd box doesn't understand ANSI sequences
            nocolor()
        if not self.verbose:
            status_stream = StringIO()
        else:
            status_stream = sys.stdout
        confoverrides = {}
        if self.project:
             confoverrides['project'] = self.project
        if self.version:
             confoverrides['version'] = self.version
        if self.release:
             confoverrides['release'] = self.release
        if self.today:
             confoverrides['today'] = self.today
        app = Sphinx(self.source_dir, self.config_dir,
                     self.builder_target_dir, self.doctree_dir,
                     self.builder, confoverrides, status_stream,
                     freshenv=self.fresh_env)

        try:
            app.build(force_all=self.all_files)
        except Exception, err:
            from docutils.utils import SystemMessage
            if isinstance(err, SystemMessage):
                print >>sys.stderr, darkred('reST markup error:')
                print >>sys.stderr, err.args[0].encode('ascii',
                                                       'backslashreplace')
            else:
                raise
Beispiel #4
0
    def run(self):
        if not sys.stdout.isatty() or sys.platform == 'win32':
            # Windows' poor cmd box doesn't understand ANSI sequences
            nocolor()
        if not self.verbose:
            status_stream = StringIO()
        else:
            status_stream = sys.stdout
        app = Sphinx(self.source_dir, self.source_dir,
                     self.builder_target_dir, self.doctree_dir,
                     self.builder, {}, status_stream,
                     freshenv=self.fresh_env)

        try:
            if self.all_files:
                app.builder.build_all()
            else:
                app.builder.build_update()
        except Exception, err:
            from docutils.utils import SystemMessage
            if isinstance(err, SystemMessage):
                sys.stderr, darkred('reST markup error:')
                print >>sys.stderr, err.args[0].encode('ascii', 'backslashreplace')
            else:
                raise
Beispiel #5
0
    def build_help(self):
        # type: () -> None
        if not color_terminal():
            nocolor()

        print(bold("Sphinx v%s" % sphinx.__display_version__))
        print("Please use `make %s' where %s is one of" % ((blue('target'),) * 2))  # type: ignore  # NOQA
        for osname, bname, description in BUILDERS:
            if not osname or os.name == osname:
                print('  %s  %s' % (blue(bname.ljust(10)), description))
Beispiel #6
0
def setup_logger(verbose=1, color=True):
    """
    Sets up and returns a Python Logger instance for the Sage
    documentation builder.  The optional argument sets logger's level
    and message format.
    """
    # Set up colors. Adapted from sphinx.cmdline.
    import sphinx.util.console as c

    if not color or not sys.stdout.isatty() or not c.color_terminal():
        c.nocolor()

    # Available colors: black, darkgray, (dark)red, dark(green),
    # brown, yellow, (dark)blue, purple, fuchsia, turquoise, teal,
    # lightgray, white.  Available styles: reset, bold, faint,
    # standout, underline, blink.

    # Set up log record formats.
    format_std = "%(message)s"
    formatter = logging.Formatter(format_std)

    # format_debug = "%(module)s #%(lineno)s %(funcName)s() %(message)s"
    fields = ["%(module)s", "#%(lineno)s", "%(funcName)s()", "%(message)s"]
    colors = ["darkblue", "darkred", "brown", "reset"]
    styles = ["reset", "reset", "reset", "reset"]
    format_debug = ""
    for i in xrange(len(fields)):
        format_debug += c.colorize(styles[i], c.colorize(colors[i], fields[i]))
        if i != len(fields):
            format_debug += " "

    # Documentation:  http://docs.python.org/library/logging.html
    logger = logging.getLogger("doc.common.builder")

    # Note: There's also Handler.setLevel().  The argument is the
    # lowest severity message that the respective logger or handler
    # will pass on.  The default levels are DEBUG, INFO, WARNING,
    # ERROR, and CRITICAL.  We use "WARNING" for normal verbosity and
    # "ERROR" for quiet operation.  It's possible to define custom
    # levels.  See the documentation for details.
    if verbose == 0:
        logger.setLevel(logging.ERROR)
    if verbose == 1:
        logger.setLevel(logging.WARNING)
    if verbose == 2:
        logger.setLevel(logging.INFO)
    if verbose == 3:
        logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter(format_debug)

    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger
Beispiel #7
0
def main(argv):
    if not color_terminal():
        # Windows' poor cmd box doesn't understand ANSI sequences
        nocolor()

    # parse options
    try:
        opts, args = getopt.getopt(argv[1:], 'ab:t:d:c:CD:A:nNEqQWw:PThvj:',
                                   ['help', 'version'])
    except getopt.error, err:
        usage(argv, 'Error: %s' % err)
        return 1
Beispiel #8
0
    def run(self):
        if is_sphinx_installed():
            from sphinx.application import Sphinx
            from sphinx.util.console import nocolor

            # Windows' poor cmd box doesn't understand ANSI sequences
            if not sys.stdout.isatty() or sys.platform == 'win32':
                nocolor()

            # Check to see if version information is provided in setup.py
            # If it is, it will override version information in conf.py.
            conf_overrides = {}
            version = self.distribution.get_version()
            if version != "0.0.0":
                conf_overrides['version'] = version
                conf_overrides['release'] = version

            for i in range(len(self.source_dirs)):
                for format in self.formats:
                    try:
                        builder_target = os.path.join(self.target_dir, format,
                            self.projects[i])
                        doctree_dir = os.path.join(builder_target, '.doctrees')

                        self.mkpath(doctree_dir)

                        # The sphinx interface requires 7 arguments: sourcedir,
                        # confdir, outdir, doctreedir, buildername,
                        # confoverrides, and status
                        app = Sphinx(self.source_dirs[i], self.source_dirs[i],
                            builder_target, doctree_dir, format, conf_overrides,
                            self.status_stream
                            )
                        app.builder.build_update()
                        if self.pdf_build and format == 'latex':
                            try:
                                os.chdir(builder_target)
                                subprocess.call(["make", "all-pdf"])
                                log.info("PDF doc created in %s."
                                    % builder_target)
                            except Exception, e:
                                log.error(e)

                    except IOError, e:
                        log.warn(e)

                    except Exception, e:
                        log.error('Unable to generate %s docs.' % format)
                        if format == 'html' and len(self.formats) == 1:
                            log.info("Installing %s html documentation from zip"
                                     " file.\n" % self.distribution.get_name())
                            unzip_html_docs(HTML_ZIP, TARGET_DIR)
Beispiel #9
0
def ablog_start(**kwargs):
    if not color_terminal():
        nocolor()

    d = CONF_DEFAULTS

    try:
        ask_user(d)
    except (KeyboardInterrupt, EOFError):
        print('')
        print('[Interrupted.]')
        return

    generate(d)
Beispiel #10
0
    def run(self):
        if not color_terminal():
            nocolor()
        if not self.verbose:
            status_stream = StringIO()
        else:
            status_stream = sys.stdout
        confoverrides = {}
        if self.project:
            confoverrides['project'] = self.project
        if self.version:
            confoverrides['version'] = self.version
        if self.release:
            confoverrides['release'] = self.release
        if self.today:
            confoverrides['today'] = self.today
        if self.copyright:
            confoverrides['copyright'] = self.copyright
        app = Sphinx(self.source_dir, self.config_dir,
                     self.builder_target_dir, self.doctree_dir,
                     self.builder, confoverrides, status_stream,
                     freshenv=self.fresh_env,
                     warningiserror=self.warning_is_error)

        try:
            app.build(force_all=self.all_files)
            if app.statuscode:
                raise DistutilsExecError(
                    'caused by %s builder.' % app.builder.name)
        except Exception as err:
            if self.pdb:
                import pdb
                print(darkred('Exception occurred while building, starting debugger:'),
                      file=sys.stderr)
                traceback.print_exc()
                pdb.post_mortem(sys.exc_info()[2])
            else:
                from docutils.utils import SystemMessage
                if isinstance(err, SystemMessage):
                    print(darkred('reST markup error:'), file=sys.stderr)
                    print(err.args[0].encode('ascii', 'backslashreplace'),
                          file=sys.stderr)
                else:
                    raise

        if self.link_index:
            src = app.config.master_doc + app.builder.out_suffix
            dst = app.builder.get_outfilename('index')
            os.symlink(src, dst)
    def run(self):
        # type: () -> None
        if not color_terminal():
            nocolor()
        if not self.verbose:  # type: ignore
            status_stream = StringIO()
        else:
            status_stream = sys.stdout  # type: ignore
        confoverrides = {}  # type: Dict[str, Any]
        if self.project:
            confoverrides['project'] = self.project
        if self.version:
            confoverrides['version'] = self.version
        if self.release:
            confoverrides['release'] = self.release
        if self.today:
            confoverrides['today'] = self.today
        if self.copyright:
            confoverrides['copyright'] = self.copyright
        if self.nitpicky:
            confoverrides['nitpicky'] = self.nitpicky

        for builder, builder_target_dir in self.builder_target_dirs:
            app = None

            try:
                confdir = self.config_dir or self.source_dir
                with patch_docutils(confdir), docutils_namespace():
                    app = Sphinx(self.source_dir, self.config_dir,
                                 builder_target_dir, self.doctree_dir,
                                 builder, confoverrides, status_stream,
                                 freshenv=self.fresh_env,
                                 warningiserror=self.warning_is_error)
                    app.build(force_all=self.all_files)
                    if app.statuscode:
                        raise DistutilsExecError(
                            'caused by %s builder.' % app.builder.name)
            except Exception as exc:
                handle_exception(app, self, exc, sys.stderr)
                if not self.pdb:
                    raise SystemExit(1)

            if not self.link_index:
                continue

            src = app.config.master_doc + app.builder.out_suffix  # type: ignore
            dst = app.builder.get_outfilename('index')  # type: ignore
            os.symlink(src, dst)
Beispiel #12
0
def main(argv=sys.argv):
    if not color_terminal():
        nocolor()

    d = {}
    if len(argv) > 3:
        print 'Usage: sphinx-quickstart [root]'
        sys.exit(1)
    elif len(argv) == 2:
        d['path'] = argv[1]
    try:
        ask_user(d)
    except (KeyboardInterrupt, EOFError):
        print
        print '[Interrupted.]'
        return
    generate(d)
Beispiel #13
0
    def run(self):
        if not color_terminal():
            nocolor()
        if not self.verbose:
            status_stream = StringIO()
        else:
            status_stream = sys.stdout
        confoverrides = {}
        if self.project:
            confoverrides["project"] = self.project
        if self.version:
            confoverrides["version"] = self.version
        if self.release:
            confoverrides["release"] = self.release
        if self.today:
            confoverrides["today"] = self.today
        if self.copyright:
            confoverrides["copyright"] = self.copyright

        try:
            with docutils_namespace():
                app = Sphinx(
                    self.source_dir,
                    self.config_dir,
                    self.builder_target_dir,
                    self.doctree_dir,
                    self.builder,
                    confoverrides,
                    status_stream,
                    freshenv=self.fresh_env,
                    warningiserror=self.warning_is_error,
                )
                app.build(force_all=self.all_files)
                if app.statuscode:
                    raise DistutilsExecError("caused by %s builder." % app.builder.name)
        except Exception as exc:
            handle_exception(app, self, exc, sys.stderr)
            if not self.pdb:
                raise SystemExit(1)

        if self.link_index:
            src = app.config.master_doc + app.builder.out_suffix
            dst = app.builder.get_outfilename("index")
            os.symlink(src, dst)
Beispiel #14
0
def main(argv=sys.argv):
    # delay-import these to be able to get sphinx.__version__ from setup.py
    # even without docutils installed
    from sphinx.application import Sphinx, SphinxError
    from docutils.utils import SystemMessage

    if not sys.stdout.isatty() or sys.platform == 'win32':
        # Windows' poor cmd box doesn't understand ANSI sequences
        nocolor()

    try:
        opts, args = getopt.getopt(argv[1:], 'ab:d:c:D:NEqP')
        srcdir = confdir = path.abspath(args[0])
        if not path.isdir(srcdir):
            print >>sys.stderr, 'Error: Cannot find source directory.'
            return 1
        if not path.isfile(path.join(srcdir, 'conf.py')) and \
               '-c' not in (opt[0] for opt in opts):
            print >>sys.stderr, 'Error: Source directory doesn\'t contain conf.py file.'
            return 1
        outdir = path.abspath(args[1])
        if not path.isdir(outdir):
            print >>sys.stderr, 'Error: Cannot find output directory.'
            return 1
    except (IndexError, getopt.error):
        usage(argv)
        return 1

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

    buildername = all_files = None
    freshenv = use_pdb = False
    status = sys.stdout
    confoverrides = {}
    doctreedir = path.join(outdir, '.doctrees')
    for opt, val in opts:
        if opt == '-b':
            buildername = val
        elif opt == '-a':
            if filenames:
                usage(argv, 'Cannot combine -a option and filenames.')
                return 1
            all_files = True
        elif opt == '-d':
            doctreedir = path.abspath(val)
        elif opt == '-c':
            confdir = path.abspath(val)
            if not path.isfile(path.join(confdir, 'conf.py')):
                print >>sys.stderr, \
                      'Error: Configuration directory doesn\'t contain conf.py file.'
                return 1
        elif opt == '-D':
            key, val = val.split('=')
            try:
                val = int(val)
            except ValueError:
                pass
            confoverrides[key] = val
        elif opt == '-N':
            nocolor()
        elif opt == '-E':
            freshenv = True
        elif opt == '-q':
            status = StringIO()
        elif opt == '-P':
            use_pdb = True

    try:
        app = Sphinx(srcdir, confdir, outdir, doctreedir, buildername,
                     confoverrides, status, sys.stderr, freshenv)
        app.build(all_files, filenames)
    except KeyboardInterrupt:
        if use_pdb:
            import pdb
            print >>sys.stderr, darkred('Interrupted while building, starting debugger:')
            traceback.print_exc()
            pdb.post_mortem(sys.exc_info()[2])
        return 1
    except Exception, err:
        if use_pdb:
            import pdb
            print >>sys.stderr, darkred('Exception occurred while building, '
                                        'starting debugger:')
            traceback.print_exc()
            pdb.post_mortem(sys.exc_info()[2])
        else:
            if isinstance(err, SystemMessage):
                print >>sys.stderr, darkred('reST markup error:')
                print >>sys.stderr, err.args[0].encode('ascii', 'backslashreplace')
            elif isinstance(err, SphinxError):
                print >>sys.stderr, darkred('%s:' % err.category)
                print >>sys.stderr, err
            else:
                print >>sys.stderr, darkred('Exception occurred:')
                print >>sys.stderr, format_exception_cut_frames().rstrip()
                tbpath = save_traceback()
                print >>sys.stderr, darkred('The full traceback has been saved '
                                            'in %s, if you want to report the '
                                            'issue to the author.' % tbpath)
                print >>sys.stderr, ('Please also report this if it was a user '
                                     'error, so that a better error message '
                                     'can be provided next time.')
                print >>sys.stderr, ('Send reports to [email protected]. '
                                     'Thanks!')
            return 1
Beispiel #15
0
def build_main(argv: List[str] = sys.argv[1:]) -> int:
    """Sphinx build "main" command-line entry."""

    parser = get_parser()
    args = parser.parse_args(argv)

    if args.noconfig:
        args.confdir = None
    elif not args.confdir:
        args.confdir = args.sourcedir

    if not args.doctreedir:
        args.doctreedir = os.path.join(args.outputdir, '.doctrees')

    # handle remaining filename arguments
    filenames = args.filenames
    missing_files = []
    for filename in filenames:
        if not os.path.isfile(filename):
            missing_files.append(filename)
    if missing_files:
        parser.error(__('cannot find files %r') % missing_files)

    if args.force_all and filenames:
        parser.error(__('cannot combine -a option and filenames'))

    if args.color == 'no' or (args.color == 'auto' and not color_terminal()):
        nocolor()

    status = sys.stdout
    warning = sys.stderr
    error = sys.stderr

    if args.quiet:
        status = None

    if args.really_quiet:
        status = warning = None

    if warning and args.warnfile:
        try:
            warnfp = open(args.warnfile, 'w')
        except Exception as exc:
            parser.error(
                __('cannot open warning file %r: %s') % (args.warnfile, exc))
        warning = Tee(warning, warnfp)  # type: ignore
        error = warning

    confoverrides = {}
    for val in args.define:
        try:
            key, val = val.split('=', 1)
        except ValueError:
            parser.error(
                __('-D option argument must be in the form name=value'))
        confoverrides[key] = val

    for val in args.htmldefine:
        try:
            key, val = val.split('=')
        except ValueError:
            parser.error(
                __('-A option argument must be in the form name=value'))
        try:
            val = int(val)
        except ValueError:
            pass
        confoverrides['html_context.%s' % key] = val

    if args.nitpicky:
        confoverrides['nitpicky'] = True

    app = None
    try:
        confdir = args.confdir or args.sourcedir
        with patch_docutils(confdir), docutils_namespace():
            app = Sphinx(args.sourcedir, args.confdir, args.outputdir,
                         args.doctreedir, args.builder, confoverrides, status,
                         warning, args.freshenv, args.warningiserror,
                         args.tags, args.verbosity, args.jobs, args.keep_going)
            app.build(args.force_all, filenames)
            return app.statuscode
    except (Exception, KeyboardInterrupt) as exc:
        handle_exception(app, args, exc, error)
        return 2
Beispiel #16
0
def main(argv=sys.argv[1:]):
    # type: (List[str]) -> int
    locale.setlocale(locale.LC_ALL, '')
    sphinx.locale.init_console(os.path.join(package_dir, 'locale'), 'sphinx')

    if not color_terminal():
        nocolor()

    # parse options
    parser = get_parser()
    try:
        args = parser.parse_args(argv)
    except SystemExit as err:
        return err.code

    d = vars(args)
    # delete None or False value
    d = dict((k, v) for k, v in d.items() if not (v is None or v is False))

    try:
        if 'quiet' in d:
            if not set(['project', 'author']).issubset(d):
                print(__('''"quiet" is specified, but any of "project" or \
"author" is not specified.'''))
                return 1

        if set(['quiet', 'project', 'author']).issubset(d):
            # quiet mode with all required params satisfied, use default
            d.setdefault('version', '')
            d.setdefault('release', d['version'])
            d2 = DEFAULTS.copy()
            d2.update(d)
            d = d2

            if not valid_dir(d):
                print()
                print(bold(__('Error: specified path is not a directory, or sphinx'
                              ' files already exist.')))
                print(__('sphinx-quickstart only generate into a empty directory.'
                         ' Please specify a new root path.'))
                return 1
        else:
            ask_user(d)
    except (KeyboardInterrupt, EOFError):
        print()
        print('[Interrupted.]')
        return 130  # 128 + SIGINT

    # decode values in d if value is a Python string literal
    for key, value in d.items():
        if isinstance(value, binary_type):
            d[key] = term_decode(value)

    # handle use of CSV-style extension values
    d.setdefault('extensions', [])
    for ext in d['extensions'][:]:
        if ',' in ext:
            d['extensions'].remove(ext)
            d['extensions'].extend(ext.split(','))

    for variable in d.get('variables', []):
        try:
            name, value = variable.split('=')
            d[name] = value
        except ValueError:
            print(__('Invalid template variable: %s') % variable)

    generate(d, templatedir=args.templatedir)
    return 0
Beispiel #17
0
def main(argv):
    if not color_terminal():
        nocolor()

    parser = optparse.OptionParser(USAGE, epilog=EPILOG, formatter=MyFormatter())
    parser.add_option('--version', action='store_true', dest='version',
                      help='show version information and exit')

    group = parser.add_option_group('General options')
    group.add_option('-b', metavar='BUILDER', dest='builder', default='html',
                     help='builder to use; default is html')
    group.add_option('-a', action='store_true', dest='force_all',
                     help='write all files; default is to only write new and '
                     'changed files')
    group.add_option('-E', action='store_true', dest='freshenv',
                     help='don\'t use a saved environment, always read '
                     'all files')
    group.add_option('-d', metavar='PATH', default=None, dest='doctreedir',
                     help='path for the cached environment and doctree files '
                     '(default: outdir/.doctrees)')
    group.add_option('-j', metavar='N', default=1, type='int', dest='jobs',
                     help='build in parallel with N processes where possible')
    # this option never gets through to this point (it is intercepted earlier)
    # group.add_option('-M', metavar='BUILDER', dest='make_mode',
    #                 help='"make" mode -- as used by Makefile, like '
    #                 '"sphinx-build -M html"')

    group = parser.add_option_group('Build configuration options')
    group.add_option('-c', metavar='PATH', dest='confdir',
                     help='path where configuration file (conf.py) is located '
                     '(default: same as sourcedir)')
    group.add_option('-C', action='store_true', dest='noconfig',
                     help='use no config file at all, only -D options')
    group.add_option('-D', metavar='setting=value', action='append',
                     dest='define', default=[],
                     help='override a setting in configuration file')
    group.add_option('-A', metavar='name=value', action='append',
                     dest='htmldefine', default=[],
                     help='pass a value into HTML templates')
    group.add_option('-t', metavar='TAG', action='append',
                     dest='tags', default=[],
                     help='define tag: include "only" blocks with TAG')
    group.add_option('-n', action='store_true', dest='nitpicky',
                     help='nit-picky mode, warn about all missing references')

    group = parser.add_option_group('Console output options')
    group.add_option('-v', action='count', dest='verbosity', default=0,
                     help='increase verbosity (can be repeated)')
    group.add_option('-q', action='store_true', dest='quiet',
                     help='no output on stdout, just warnings on stderr')
    group.add_option('-Q', action='store_true', dest='really_quiet',
                     help='no output at all, not even warnings')
    group.add_option('-N', action='store_true', dest='nocolor',
                     help='do not emit colored output')
    group.add_option('-w', metavar='FILE', dest='warnfile',
                     help='write warnings (and errors) to given file')
    group.add_option('-W', action='store_true', dest='warningiserror',
                     help='turn warnings into errors')
    group.add_option('-T', action='store_true', dest='traceback',
                     help='show full traceback on exception')
    group.add_option('-P', action='store_true', dest='pdb',
                     help='run Pdb on exception')

    # parse options
    try:
        opts, args = parser.parse_args(argv[1:])
    except SystemExit as err:
        return err.code

    # handle basic options
    if opts.version:
        print('Sphinx (sphinx-build) %s' % __version__)
        return 0

    # get paths (first and second positional argument)
    try:
        srcdir = abspath(args[0])
        confdir = abspath(opts.confdir or srcdir)
        if opts.noconfig:
            confdir = None
        if not path.isdir(srcdir):
            print('Error: Cannot find source directory `%s\'.' % srcdir,
                  file=sys.stderr)
            return 1
        if not opts.noconfig and not path.isfile(path.join(confdir, 'conf.py')):
            print('Error: Config 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

    if opts.force_all and filenames:
        print('Error: Cannot combine -a option and filenames.', file=sys.stderr)
        return 1

    if opts.nocolor:
        nocolor()

    doctreedir = abspath(opts.doctreedir or path.join(outdir, '.doctrees'))

    status = sys.stdout
    warning = sys.stderr
    error = sys.stderr

    if opts.quiet:
        status = None
    if opts.really_quiet:
        status = warning = None
    if warning and opts.warnfile:
        try:
            warnfp = open(opts.warnfile, 'w')
        except Exception as exc:
            print('Error: Cannot open warning file %r: %s' %
                  (opts.warnfile, exc), file=sys.stderr)
            sys.exit(1)
        warning = Tee(warning, warnfp)
        error = warning

    confoverrides = {}
    for val in opts.define:
        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

    for val in opts.htmldefine:
        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

    if opts.nitpicky:
        confoverrides['nitpicky'] = True

    app = None
    try:
        app = Sphinx(srcdir, confdir, outdir, doctreedir, opts.builder,
                     confoverrides, status, warning, opts.freshenv,
                     opts.warningiserror, opts.tags, opts.verbosity, opts.jobs)
        app.build(opts.force_all, filenames)
        return app.statuscode
    except (Exception, KeyboardInterrupt) as err:
        if opts.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 opts.verbosity or opts.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
Beispiel #18
0
def main(argv):
    if not color_terminal():
        nocolor()

    parser = optparse.OptionParser(USAGE,
                                   epilog=EPILOG,
                                   formatter=MyFormatter())
    parser.add_option('--version',
                      action='store_true',
                      dest='version',
                      help='show version information and exit')

    group = parser.add_option_group('General options')
    group.add_option('-b',
                     metavar='BUILDER',
                     dest='builder',
                     default='html',
                     help='builder to use; default is html')
    group.add_option('-a',
                     action='store_true',
                     dest='force_all',
                     help='write all files; default is to only write new and '
                     'changed files')
    group.add_option('-E',
                     action='store_true',
                     dest='freshenv',
                     help='don\'t use a saved environment, always read '
                     'all files')
    group.add_option('-d',
                     metavar='PATH',
                     default=None,
                     dest='doctreedir',
                     help='path for the cached environment and doctree files '
                     '(default: outdir/.doctrees)')
    group.add_option('-j',
                     metavar='N',
                     default=1,
                     type='int',
                     dest='jobs',
                     help='build in parallel with N processes where possible')
    # this option never gets through to this point (it is intercepted earlier)
    # group.add_option('-M', metavar='BUILDER', dest='make_mode',
    #                 help='"make" mode -- as used by Makefile, like '
    #                 '"sphinx-build -M html"')

    group = parser.add_option_group('Build configuration options')
    group.add_option('-c',
                     metavar='PATH',
                     dest='confdir',
                     help='path where configuration file (conf.py) is located '
                     '(default: same as sourcedir)')
    group.add_option('-C',
                     action='store_true',
                     dest='noconfig',
                     help='use no config file at all, only -D options')
    group.add_option('-D',
                     metavar='setting=value',
                     action='append',
                     dest='define',
                     default=[],
                     help='override a setting in configuration file')
    group.add_option('-A',
                     metavar='name=value',
                     action='append',
                     dest='htmldefine',
                     default=[],
                     help='pass a value into HTML templates')
    group.add_option('-t',
                     metavar='TAG',
                     action='append',
                     dest='tags',
                     default=[],
                     help='define tag: include "only" blocks with TAG')
    group.add_option('-n',
                     action='store_true',
                     dest='nitpicky',
                     help='nit-picky mode, warn about all missing references')

    group = parser.add_option_group('Console output options')
    group.add_option('-v',
                     action='count',
                     dest='verbosity',
                     default=0,
                     help='increase verbosity (can be repeated)')
    group.add_option('-q',
                     action='store_true',
                     dest='quiet',
                     help='no output on stdout, just warnings on stderr')
    group.add_option('-Q',
                     action='store_true',
                     dest='really_quiet',
                     help='no output at all, not even warnings')
    group.add_option('-N',
                     action='store_true',
                     dest='nocolor',
                     help='do not emit colored output')
    group.add_option('-w',
                     metavar='FILE',
                     dest='warnfile',
                     help='write warnings (and errors) to given file')
    group.add_option('-W',
                     action='store_true',
                     dest='warningiserror',
                     help='turn warnings into errors')
    group.add_option('-T',
                     action='store_true',
                     dest='traceback',
                     help='show full traceback on exception')
    group.add_option('-P',
                     action='store_true',
                     dest='pdb',
                     help='run Pdb on exception')

    # parse options
    try:
        opts, args = parser.parse_args(list(argv[1:]))
    except SystemExit as err:
        return err.code

    # handle basic options
    if opts.version:
        print('Sphinx (sphinx-build) %s' % __display_version__)
        return 0

    # get paths (first and second positional argument)
    try:
        srcdir = abspath(args[0])
        confdir = abspath(opts.confdir or srcdir)
        if opts.noconfig:
            confdir = None
        if not path.isdir(srcdir):
            print('Error: Cannot find source directory `%s\'.' % srcdir,
                  file=sys.stderr)
            return 1
        if not opts.noconfig and not path.isfile(path.join(confdir,
                                                           'conf.py')):
            print('Error: Config directory doesn\'t contain a conf.py file.',
                  file=sys.stderr)
            return 1
        outdir = abspath(args[1])
    except IndexError:
        parser.print_help()
        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

    if opts.force_all and filenames:
        print('Error: Cannot combine -a option and filenames.',
              file=sys.stderr)
        return 1

    if opts.nocolor:
        nocolor()

    doctreedir = abspath(opts.doctreedir or path.join(outdir, '.doctrees'))

    status = sys.stdout
    warning = sys.stderr
    error = sys.stderr

    if opts.quiet:
        status = None
    if opts.really_quiet:
        status = warning = None
    if warning and opts.warnfile:
        try:
            warnfp = open(opts.warnfile, 'w')
        except Exception as exc:
            print('Error: Cannot open warning file %r: %s' %
                  (opts.warnfile, exc),
                  file=sys.stderr)
            sys.exit(1)
        warning = Tee(warning, warnfp)
        error = warning

    confoverrides = {}
    for val in opts.define:
        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

    for val in opts.htmldefine:
        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

    if opts.nitpicky:
        confoverrides['nitpicky'] = True

    app = None
    try:
        app = Sphinx(srcdir, confdir, outdir, doctreedir, opts.builder,
                     confoverrides, status, warning, opts.freshenv,
                     opts.warningiserror, opts.tags, opts.verbosity, opts.jobs)
        app.build(opts.force_all, filenames)
        return app.statuscode
    except (Exception, KeyboardInterrupt) as err:
        if opts.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 opts.verbosity or opts.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://github.com/sphinx-doc/sphinx/issues>. Thanks!',
                    file=error)
            return 1
Beispiel #19
0
def setup_module():
    nocolor()
Beispiel #20
0
def main(argv):
  """
  Based mostly on sphinx.cmdline.main
  """
  if not color_terminal():
    # Windows' poor cmd box doesn't understand ANSI sequences
    nocolor()

  try:
    opts, args = getopt.getopt(argv[1:], 'ab:t:d:c:CD:A:ng:NEqQWw:P')
    allopts = set(opt[0] for opt in opts)
    srcdir = confdir = os.path.abspath(args[0])
    if not os.path.isdir(srcdir):
      print >>sys.stderr, 'Error: Cannot find source directory.'
      return 1
    if not os.path.isfile(os.path.join(srcdir, 'conf.py')) and \
           '-c' not in allopts and '-C' not in allopts:
      print >> sys.stderr, 'Error: Source directory doesn\'t contain conf.py file.'
      return 1
    outdir = os.path.abspath(args[1])
    if not os.path.isdir(outdir):
      print >>sys.stderr, 'Making output directory...'
      os.makedirs(outdir)
  except (IndexError, getopt.error):
    usage(argv)
    return 1

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

  buildername = None
  force_all = freshenv = warningiserror = False
  status = sys.stdout
  warning = sys.stderr
  confoverrides = {}
  tags = []
  doctreedir = os.path.join(outdir, '.doctrees')
  for opt, val in opts:
    if opt == '-b':
        buildername = val
    elif opt == '-a':
        if filenames:
            usage(argv, 'Cannot combine -a option and filenames.')
            return 1
        force_all = True
    elif opt == '-t':
        tags.append(val)
    elif opt == '-d':
        doctreedir = os.path.abspath(val)
    elif opt == '-c':
        confdir = os.path.abspath(val)
        if not os.path.isfile(os.path.join(confdir, 'conf.py')):
            print >> sys.stderr, \
                'Error: Configuration directory doesn\'t contain conf.py file.'
            return 1
    elif opt == '-C':
        confdir = None
    elif opt == '-D':
        try:
            key, val = val.split('=')
        except ValueError:
            print >> sys.stderr, \
                'Error: -D option argument must be in the form name=value.'
            return 1
        try:
            val = int(val)
        except ValueError:
            pass
        confoverrides[key] = val
    elif opt == '-A':
        try:
            key, val = val.split('=')
        except ValueError:
            print >> sys.stderr, \
                'Error: -A option argument must be in the form name=value.'
            return 1
        try:
            val = int(val)
        except ValueError:
            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

  try:
    app = Sphinx(srcdir, confdir, outdir, doctreedir, buildername,
                 confoverrides, status, warning, freshenv,
                 warningiserror, tags)
    app.build(force_all, filenames)
    return app.statuscode
  except KeyboardInterrupt:
    return 1
  except Exception as err:
    print >> sys.stderr
    if isinstance(err, SystemMessage):
      print >> sys.stderr, red('reST markup error:')
      print >> sys.stderr, err.args[0].encode('ascii', 'backslashreplace')
    elif isinstance(err, SphinxError):
      print >> sys.stderr, red('%s:' % err.category)
      print >> sys.stderr, err
    else:
      raise
    return 1
Beispiel #21
0
def main(argv=sys.argv[1:]):
    # type: (List[str]) -> int
    if not color_terminal():
        nocolor()

    # parse options
    parser = get_parser()
    try:
        args = parser.parse_args(argv)
    except SystemExit as err:
        return err.code

    d = vars(args)
    # delete None or False value
    d = dict((k, v) for k, v in d.items() if not (v is None or v is False))

    try:
        if 'quiet' in d:
            if not set(['project', 'author']).issubset(d):
                print('''"quiet" is specified, but any of "project" or \
"author" is not specified.''')
                return 1

        if set(['quiet', 'project', 'author']).issubset(d):
            # quiet mode with all required params satisfied, use default
            d.setdefault('version', '')
            d.setdefault('release', d['version'])
            d2 = DEFAULTS.copy()
            d2.update(d)
            d = d2

            if not valid_dir(d):
                print()
                print(
                    bold('Error: specified path is not a directory, or sphinx'
                         ' files already exist.'))
                print('sphinx-quickstart only generate into a empty directory.'
                      ' Please specify a new root path.')
                return 1
        else:
            ask_user(d)
    except (KeyboardInterrupt, EOFError):
        print()
        print('[Interrupted.]')
        return 130  # 128 + SIGINT

    # decode values in d if value is a Python string literal
    for key, value in d.items():
        if isinstance(value, binary_type):
            d[key] = term_decode(value)

    # handle use of CSV-style extension values
    d.setdefault('extensions', [])
    for ext in d['extensions'][:]:
        if ',' in ext:
            d['extensions'].remove(ext)
            d['extensions'].extend(ext.split(','))

    for variable in d.get('variables', []):
        try:
            name, value = variable.split('=')
            d[name] = value
        except ValueError:
            print('Invalid template variable: %s' % variable)

    generate(d, templatedir=args.templatedir)
    return 0
Beispiel #22
0
    def run(self):
        if not self.distribution.doc_modules:
            return

        ## Make sure that sources are complete in build_lib.
        self.run_command('build_src')
        ## Ditto extensions
        self.run_command('build_ext')

        build = self.get_finalized_command('build')
        buildpy = self.get_finalized_command('build_py')
        target = os.path.abspath(os.path.join(build.build_base, 'http'))
        mkdir(target)
        build_verbose = self.distribution.verbose
        environ = self.distribution.environment

        for dext in self.distribution.doc_modules:
            if self.distribution.verbose:
                print('building documentation "' + dext.name + '" sources')

            doc_dir = os.path.abspath(dext.source_directory)
            extra_dirs = dext.extra_directories
            working_dir = os.path.abspath(os.path.join(self.build_temp,
                                                       dext.source_directory))
            here = os.getcwd()

            reprocess = True
            ref = os.path.join(target, dext.name + '.html')
            root_dir = dext.name
            if os.path.exists(ref) and not self.force:
                reprocess = False
                docbase = os.path.join(doc_dir, 'modules')
                for root, dirnames, filenames in os.walk(docbase):
                    for fn in fnmatch.filter(filenames, '*.rst'):
                        doc = os.path.join(root, fn)
                        if os.path.getmtime(ref) < os.path.getmtime(doc):
                            reprocess = True
                            break
                        src = os.path.join(root_dir, root[len(docbase)+1:],
                                            fn[:-3] + 'py')
                        if os.path.exists(src):
                            if os.path.getmtime(ref) < os.path.getmtime(src):
                                reprocess = True
                                break
            if reprocess:
                src_dirs = []
                for package in buildpy.packages:
                    # Locate package source directory
                    src_dirs.append(os.path.abspath(buildpy.get_package_dir(package)))
                #FIXME rst files in package sources (mutiple packages)
                #src_dir = src_dirs[0]
                src_dir = os.path.abspath('.')
                bld_dir = os.path.abspath(self.build_lib)
                doc_bld_dir = os.path.join(bld_dir,
                                           os.path.relpath(doc_dir, src_dir))
                environ['BUILD_DIR'] = bld_dir
                environ['SOURCE_DIR'] = src_dir
                environ['RELATIVE_SOURCE_DIR'] = os.path.relpath(src_dir,
                                                                 doc_bld_dir)

                copy_tree(doc_dir, working_dir, True,
                          excludes=['.svn', 'CVS', '.git', '.hg*'])
                for d in extra_dirs:
                    subdir = os.path.basename(os.path.normpath(d))
                    copy_tree(d, os.path.join(target, subdir), True,
                              excludes=['.svn', 'CVS', '.git', '.hg*'])

                ## Configure rst files
                configure_files(environ, src_dir, '*.rst', working_dir)

                if os.path.exists(os.path.join(doc_dir, dext.doxygen_cfg)):
                    ## Doxygen + breathe
                    'Config ' + os.path.join(doc_dir, dext.doxygen_cfg)
                    configure_file(environ,
                                   os.path.join(doc_dir, dext.doxygen_cfg),
                                   os.path.join(working_dir, dext.doxygen_cfg),
                                   style=dext.style)
                    for s in dext.doxygen_srcs:
                        configure_file(environ,
                                       os.path.join(doc_dir, s),
                                       os.path.join(working_dir, s),
                                       style=dext.style)
                    try:
                        doxygen_exe = find_program('doxygen')
                    except:
                        sys.stderr.write('ERROR: Doxygen not installed ' +
                                         '(required for documentation).\n')
                        return

                    reprocess = True
                    ref = os.path.join(working_dir, 'html', 'index.html')
                    if os.path.exists(ref) and not self.force:
                        reprocess = False
                        for d in environ['C_SOURCE_DIRS'].split(' '):
                            for orig in glob.glob(os.path.join(d, '*.h*')):
                               if os.path.getmtime(ref) < \
                                        os.path.getmtime(orig):
                                    reprocess = True
                                    break
                    if reprocess:
                        if self.distribution.verbose:
                            out = sys.stdout
                            err = sys.stderr
                        else:
                            out = err = open('doxygen.log', 'w')
                        os.chdir(working_dir)
                        cmd_line = [doxygen_exe, dext.doxygen_cfg]
                        status = subprocess.call(cmd_line,
                                                 stdout=out, stderr=err)
                        if status != 0:
                            raise Exception("Command '" + str(cmd_line) +
                                            "' returned non-zero exit status "
                                            + str(status))

                        if not self.distribution.verbose:
                            out.close()
                        copy_tree('html', os.path.join(target, 'html'), True,
                                  excludes=['.svn', 'CVS', '.git', '.hg*'])
                        os.chdir(here)
                        create_breathe_stylesheet(target)

                for f in dext.extra_docs:
                    shutil.copy(os.path.join(doc_dir, f), target)

                ## Sphinx
                if dext.without_sphinx:
                    return
                if dext.sphinx_config is None:
                    dext.sphinx_config = os.path.join(os.path.dirname(__file__),
                                                      'sphinx_conf.py.in')
                elif os.path.dirname(dext.sphinx_config) == '':
                    dext.sphinx_config =  os.path.join(doc_dir,
                                                       dext.sphinx_config)
                configure_file(environ, dext.sphinx_config,
                               os.path.join(working_dir, 'conf.py'))
                import warnings
                try:
                    import sphinx
                    from sphinx.application import Sphinx
                    if 'windows' in platform.system().lower() or \
                            not build_verbose:
                        from sphinx.util.console import nocolor
                except:
                    sys.stderr.write('ERROR: Sphinx not installed ' +
                                     '(required for documentation).\n')
                    return
                warnings.filterwarnings("ignore",
                                        category=PendingDeprecationWarning)
                warnings.filterwarnings("ignore", category=UserWarning)

                status = sys.stdout
                if not build_verbose:
                    status = open('sphinx.log', 'w')
                if 'windows' in platform.system().lower() or not build_verbose:
                    nocolor()
                try:
                    sphinx_app = Sphinx(working_dir, working_dir, target,
                                        os.path.join(target, '.doctrees'),
                                        'html', None, status)
                    sphinx_app.build(True)
                except Exception:
                    if build_verbose:
                        e = sys.exc_info()[1]
                        print('ERROR: ' + str(e))
                    else:
                        pass
                if not build_verbose:
                    status.close()
                warnings.resetwarnings()
Beispiel #23
0
def setup_module():
    nocolor()
    def run(self):
        if not self.distribution.doc_modules:
            return

        ## Make sure that sources are complete in build_lib.
        self.run_command('build_src')
        ## Ditto extensions
        self.run_command('build_ext')

        build = self.get_finalized_command('build')
        buildpy = self.get_finalized_command('build_py')
        ## packages and files are in build.build_lib (see build_py.py)
        target = os.path.join(os.path.abspath(build.build_base), 'http')
        mkdir(target)
        build_verbose = self.distribution.verbose
        environ = self.distribution.environment

        for dext in self.distribution.doc_modules:
            if self.distribution.verbose:
                print('building documentation "' + dext.name + '" sources')

            doc_dir = os.path.abspath(dext.source_directory)
            extra_dirs = dext.extra_directories
            src_dir = os.path.abspath(dext.name)
            here = os.getcwd()

            reprocess = True
            ref = os.path.join(target, dext.name + '.html')
            root_dir = dext.name
            if os.path.exists(ref) and not self.force:
                reprocess = False
                for root, _, filenames in os.walk(src_dir):
                    for fn in fnmatch.filter(filenames, '*.rst'):
                        doc = os.path.join(root, fn)
                        if os.path.getmtime(ref) < os.path.getmtime(doc):
                            reprocess = True
                            break
                        src = os.path.join(root_dir, root[len(doc_dir)+1:],
                                            fn[:-3] + 'py')
                        if os.path.exists(src):
                            if os.path.getmtime(ref) < os.path.getmtime(src):
                                reprocess = True
                                break
            if reprocess:
                working_dir = os.path.abspath(build.build_lib)
                for package in buildpy.packages:
                    pkgdir = buildpy.get_package_dir(package)
                    pkgsrcdir = os.path.join(os.path.dirname(src_dir), pkgdir)
                    configure_files(environ, pkgsrcdir,
                                    '*.rst', os.path.join(working_dir, pkgdir))

                cfg_dir = os.path.join(working_dir, dext.source_directory)
                environ['BUILD_DIR'] = working_dir

                copy_tree(doc_dir, working_dir, True,
                          excludes=[dext.name, '.svn', 'CVS', '.git', '.hg*'])
                copy_tree(os.path.join(doc_dir, dext.name),
                          os.path.join(cfg_dir, dext.name), True,
                          excludes=['.svn', 'CVS', '.git', '.hg*'])
                for d in extra_dirs:
                    subdir = os.path.basename(os.path.normpath(d))
                    copy_tree(d, os.path.join(target, subdir), True,
                              excludes=['.svn', 'CVS', '.git', '.hg*'])

                if os.path.exists(os.path.join(doc_dir, dext.doxygen_cfg)):
                    ## Doxygen + breathe
                    print('Config ' + os.path.join(doc_dir, dext.doxygen_cfg))
                    configure_file(environ,
                                   os.path.join(doc_dir, dext.doxygen_cfg),
                                   os.path.join(working_dir, dext.doxygen_cfg),
                                   style=dext.style)
                    for s in dext.doxygen_srcs:
                        configure_file(environ,
                                       os.path.join(doc_dir, s),
                                       os.path.join(working_dir, s),
                                       style=dext.style)
                    try:
                        doxygen_exe = find_program('doxygen')
                    except Exception:  # pylint: disable=W0703
                        sys.stderr.write('ERROR: Doxygen not installed ' +
                                         '(required for documentation).\n')
                        return

                    reprocess = True
                    ref = os.path.join(working_dir, 'html', 'index.html')
                    if os.path.exists(ref) and not self.force:
                        reprocess = False
                        for d in environ['C_SOURCE_DIRS'].split(' '):
                            for orig in glob.glob(os.path.join(d, '*.h*')):
                                if os.path.getmtime(ref) < \
                                   os.path.getmtime(orig):
                                    reprocess = True
                                    break
                    if reprocess:
                        if self.distribution.verbose:
                            out = sys.stdout
                            err = sys.stderr
                        else:
                            out = err = open('doxygen.log', 'w')
                        os.chdir(working_dir)
                        cmd_line = [doxygen_exe, dext.doxygen_cfg]
                        status = subprocess.call(cmd_line,
                                                 stdout=out, stderr=err)
                        if status != 0:
                            raise Exception("Command '" + str(cmd_line) +
                                            "' returned non-zero exit status "
                                            + str(status))

                        if not self.distribution.verbose:
                            out.close()
                        copy_tree('html', os.path.join(target, 'html'), True,
                                  excludes=['.svn', 'CVS', '.git', '.hg*'])
                        copy_tree('xml', os.path.join(cfg_dir, 'xml'), True)
                        os.chdir(here)
                        create_breathe_stylesheet(target)

                for f in dext.extra_docs:
                    shutil.copy(os.path.join(doc_dir, f), target)

                ## Sphinx
                if dext.without_sphinx:
                    return
                if dext.sphinx_config is None:
                    level_up = os.path.dirname(os.path.dirname(__file__))
                    dext.sphinx_config = os.path.join(level_up,
                                                      'sphinx_conf.py.in')
                elif os.path.dirname(dext.sphinx_config) == '':
                    dext.sphinx_config =  os.path.join(doc_dir,
                                                       dext.sphinx_config)
                configure_file(environ, dext.sphinx_config,
                               os.path.join(cfg_dir, 'conf.py'))
                import warnings
                try:
                    import sphinx  # pylint: disable=W0612
                except ImportError:
                    configure_package('breathe')  ## requires sphinx
                    sys.path.insert(0, os.path.join(options.target_build_dir,
                                                    options.local_lib_dir))

                from sphinx.application import Sphinx
                if 'windows' in platform.system().lower() or \
                   not build_verbose:
                    from sphinx.util.console import nocolor
                warnings.filterwarnings("ignore",
                                        category=PendingDeprecationWarning)
                warnings.filterwarnings("ignore", category=UserWarning)

                status = sys.stdout
                if not build_verbose:
                    status = open('sphinx.log', 'w')
                if 'windows' in platform.system().lower() or not build_verbose:
                    nocolor()
                try:
                    ## args: srcdir, confdir, outdir, doctreedir, buildername
                    sphinx_app = Sphinx(os.path.join(working_dir, dext.name),
                                        cfg_dir, target,
                                        os.path.join(target, '.doctrees'),
                                        'html', status=status)
                    sphinx_app.build(force_all=True, filenames=None)
                except Exception:  # pylint: disable=W0703
                    if build_verbose:
                        print('ERROR: ' + str(sys.exc_info()[1]))
                    else:
                        pass
                if not build_verbose:
                    status.close()
                warnings.resetwarnings()
def prepare_sphinx(src_dir, config=None, out_dir=None, extra_config=None,
        builder=None, relax=False):
    """
    prepare a sphinx application instance

    Return a prepared Sphinx application instance [1] ready for execution.

    [1]: https://github.com/sphinx-doc/sphinx/blob/master/sphinx/application.py

    Args:
        src_dir: document sources
        config (optional): configuration to use
        out_dir (optional): output for generated documents
        extra_config (optional): additional configuration data to apply
        builder (optional): the builder to use
        relax (optional): do not generate warnings as errors
    """

    # Enable coloring of warning and other messages. Note that this can
    # cause sys.stderr to be mocked which is why we pass the new value
    # explicitly on the call to Sphinx() below.
    if 'MSYSTEM' not in os.environ and not color_terminal():
        nocolor()

    conf = dict(config) if config else {}
    if extra_config:
        conf.update(extra_config)
    conf_dir = src_dir if config is None else None
    warnerr = not relax

    sts = None
    if 'SPHINX_STATUS' in os.environ:
        sts = sys.stdout

    verbosity = 0
    if 'SPHINX_VERBOSITY' in os.environ:
        try:
            verbosity = int(os.environ['SPHINX_VERBOSITY'])
        except ValueError:
            pass

    # default to using this extension's builder
    if not builder:
        builder = 'confluence'

    if not out_dir:
        # 3 = prepare_dirs, this, contextmanager
        out_dir = prepare_dirs(f_back_count=3)

    doctrees_dir = os.path.join(out_dir, '.doctrees')

    # support pre-Sphinx v4.0 installations which do not have `root_doc` by
    # swapping to the obsolete configuration name
    if parse_version(sphinx_version) < parse_version('4.0'):
        if 'root_doc' in conf:
            conf['master_doc'] = conf['root_doc']
            del conf['root_doc']

    with docutils_namespace():
        app = Sphinx(
            src_dir,                 # output for document sources
            conf_dir,                # configuration directory
            out_dir,                 # output for generated documents
            doctrees_dir,            # output for doctree files
            builder,                 # builder to execute
            confoverrides=conf,      # load provided configuration (volatile)
            status=sts,              # status output
            warning=sys.stderr,      # warnings output
            warningiserror=warnerr,  # treat warnings as errors
            verbosity=verbosity)     # verbosity

        yield app
Beispiel #26
0
 def setUp(self):
     nocolor()
Beispiel #27
0
def main(argv):
    # type: (List[unicode]) -> int
    parser = optparse.OptionParser(USAGE,
                                   epilog=EPILOG,
                                   formatter=MyFormatter())
    parser.add_option('--version',
                      action='store_true',
                      dest='version',
                      help='show version information and exit')

    group = parser.add_option_group('General options')
    group.add_option('-b',
                     metavar='BUILDER',
                     dest='builder',
                     default='html',
                     help='builder to use; default is html')
    group.add_option('-a',
                     action='store_true',
                     dest='force_all',
                     help='write all files; default is to only write new and '
                     'changed files')
    group.add_option('-E',
                     action='store_true',
                     dest='freshenv',
                     help='don\'t use a saved environment, always read '
                     'all files')
    group.add_option('-d',
                     metavar='PATH',
                     default=None,
                     dest='doctreedir',
                     help='path for the cached environment and doctree files '
                     '(default: outdir/.doctrees)')
    group.add_option('-j',
                     metavar='N',
                     default=1,
                     type='int',
                     dest='jobs',
                     help='build in parallel with N processes where possible')
    # this option never gets through to this point (it is intercepted earlier)
    # group.add_option('-M', metavar='BUILDER', dest='make_mode',
    #                 help='"make" mode -- as used by Makefile, like '
    #                 '"sphinx-build -M html"')

    group = parser.add_option_group('Build configuration options')
    group.add_option('-c',
                     metavar='PATH',
                     dest='confdir',
                     help='path where configuration file (conf.py) is located '
                     '(default: same as sourcedir)')
    group.add_option('-C',
                     action='store_true',
                     dest='noconfig',
                     help='use no config file at all, only -D options')
    group.add_option('-D',
                     metavar='setting=value',
                     action='append',
                     dest='define',
                     default=[],
                     help='override a setting in configuration file')
    group.add_option('-A',
                     metavar='name=value',
                     action='append',
                     dest='htmldefine',
                     default=[],
                     help='pass a value into HTML templates')
    group.add_option('-t',
                     metavar='TAG',
                     action='append',
                     dest='tags',
                     default=[],
                     help='define tag: include "only" blocks with TAG')
    group.add_option('-n',
                     action='store_true',
                     dest='nitpicky',
                     help='nit-picky mode, warn about all missing references')

    group = parser.add_option_group('Console output options')
    group.add_option('-v',
                     action='count',
                     dest='verbosity',
                     default=0,
                     help='increase verbosity (can be repeated)')
    group.add_option('-q',
                     action='store_true',
                     dest='quiet',
                     help='no output on stdout, just warnings on stderr')
    group.add_option('-Q',
                     action='store_true',
                     dest='really_quiet',
                     help='no output at all, not even warnings')
    group.add_option('--color',
                     dest='color',
                     action='store_const',
                     const='yes',
                     default='auto',
                     help='Do emit colored output (default: auto-detect)')
    group.add_option('-N',
                     '--no-color',
                     dest='color',
                     action='store_const',
                     const='no',
                     help='Do not emit colored output (default: auot-detect)')
    group.add_option('-w',
                     metavar='FILE',
                     dest='warnfile',
                     help='write warnings (and errors) to given file')
    group.add_option('-W',
                     action='store_true',
                     dest='warningiserror',
                     help='turn warnings into errors')
    group.add_option('-T',
                     action='store_true',
                     dest='traceback',
                     help='show full traceback on exception')
    group.add_option('-P',
                     action='store_true',
                     dest='pdb',
                     help='run Pdb on exception')

    # parse options
    try:
        opts, args = parser.parse_args(list(argv[1:]))
    except SystemExit as err:
        return err.code

    # handle basic options
    if opts.version:
        print('Sphinx (sphinx-build) %s' % __display_version__)
        return 0

    # get paths (first and second positional argument)
    try:
        srcdir = abspath(args[0])
        confdir = abspath(opts.confdir or srcdir)
        if opts.noconfig:
            confdir = None
        if not path.isdir(srcdir):
            print('Error: Cannot find source directory `%s\'.' % srcdir,
                  file=sys.stderr)
            return 1
        if not opts.noconfig and not path.isfile(path.join(confdir,
                                                           'conf.py')):
            print('Error: Config directory doesn\'t contain a conf.py file.',
                  file=sys.stderr)
            return 1
        outdir = abspath(args[1])
        if srcdir == outdir:
            print(
                'Error: source directory and destination directory are same.',
                file=sys.stderr)
            return 1
    except IndexError:
        parser.print_help()
        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:]
    errored = False
    for filename in filenames:
        if not path.isfile(filename):
            print('Error: Cannot find file %r.' % filename, file=sys.stderr)
            errored = True
    if errored:
        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

    if opts.force_all and filenames:
        print('Error: Cannot combine -a option and filenames.',
              file=sys.stderr)
        return 1

    if opts.color == 'no' or (opts.color == 'auto' and not color_terminal()):
        nocolor()

    doctreedir = abspath(opts.doctreedir or path.join(outdir, '.doctrees'))

    status = sys.stdout
    warning = sys.stderr
    error = sys.stderr

    if opts.quiet:
        status = None
    if opts.really_quiet:
        status = warning = None
    if warning and opts.warnfile:
        try:
            warnfp = open(opts.warnfile, 'w')
        except Exception as exc:
            print('Error: Cannot open warning file %r: %s' %
                  (opts.warnfile, exc),
                  file=sys.stderr)
            sys.exit(1)
        warning = Tee(warning, warnfp)  # type: ignore
        error = warning

    confoverrides = {}
    for val in opts.define:
        try:
            key, val = val.split('=', 1)
        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

    for val in opts.htmldefine:
        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

    if opts.nitpicky:
        confoverrides['nitpicky'] = True

    app = None
    try:
        with docutils_namespace():
            app = Sphinx(srcdir, confdir, outdir, doctreedir, opts.builder,
                         confoverrides, status, warning, opts.freshenv,
                         opts.warningiserror, opts.tags, opts.verbosity,
                         opts.jobs)
            app.build(opts.force_all, filenames)
            return app.statuscode
    except (Exception, KeyboardInterrupt) as exc:
        handle_exception(app, opts, exc, error)
        return 1
Beispiel #28
0
def main(argv):
    # type: (List[unicode]) -> int
    parser = optparse.OptionParser(USAGE, epilog=EPILOG, formatter=MyFormatter())
    parser.add_option('--version', action='store_true', dest='version',
                      help='show version information and exit')

    group = parser.add_option_group('General options')
    group.add_option('-b', metavar='BUILDER', dest='builder', default='html',
                     help='builder to use; default is html')
    group.add_option('-a', action='store_true', dest='force_all',
                     help='write all files; default is to only write new and '
                     'changed files')
    group.add_option('-E', action='store_true', dest='freshenv',
                     help='don\'t use a saved environment, always read '
                     'all files')
    group.add_option('-d', metavar='PATH', default=None, dest='doctreedir',
                     help='path for the cached environment and doctree files '
                     '(default: outdir/.doctrees)')
    group.add_option('-j', metavar='N', default=1, type='int', dest='jobs',
                     help='build in parallel with N processes where possible')
    # this option never gets through to this point (it is intercepted earlier)
    # group.add_option('-M', metavar='BUILDER', dest='make_mode',
    #                 help='"make" mode -- as used by Makefile, like '
    #                 '"sphinx-build -M html"')

    group = parser.add_option_group('Build configuration options')
    group.add_option('-c', metavar='PATH', dest='confdir',
                     help='path where configuration file (conf.py) is located '
                     '(default: same as sourcedir)')
    group.add_option('-C', action='store_true', dest='noconfig',
                     help='use no config file at all, only -D options')
    group.add_option('-D', metavar='setting=value', action='append',
                     dest='define', default=[],
                     help='override a setting in configuration file')
    group.add_option('-A', metavar='name=value', action='append',
                     dest='htmldefine', default=[],
                     help='pass a value into HTML templates')
    group.add_option('-t', metavar='TAG', action='append',
                     dest='tags', default=[],
                     help='define tag: include "only" blocks with TAG')
    group.add_option('-n', action='store_true', dest='nitpicky',
                     help='nit-picky mode, warn about all missing references')

    group = parser.add_option_group('Console output options')
    group.add_option('-v', action='count', dest='verbosity', default=0,
                     help='increase verbosity (can be repeated)')
    group.add_option('-q', action='store_true', dest='quiet',
                     help='no output on stdout, just warnings on stderr')
    group.add_option('-Q', action='store_true', dest='really_quiet',
                     help='no output at all, not even warnings')
    group.add_option('--color', dest='color',
                     action='store_const', const='yes', default='auto',
                     help='Do emit colored output (default: auto-detect)')
    group.add_option('-N', '--no-color', dest='color',
                     action='store_const', const='no',
                     help='Do not emit colored output (default: auot-detect)')
    group.add_option('-w', metavar='FILE', dest='warnfile',
                     help='write warnings (and errors) to given file')
    group.add_option('-W', action='store_true', dest='warningiserror',
                     help='turn warnings into errors')
    group.add_option('-T', action='store_true', dest='traceback',
                     help='show full traceback on exception')
    group.add_option('-P', action='store_true', dest='pdb',
                     help='run Pdb on exception')

    # parse options
    try:
        opts, args = parser.parse_args(list(argv[1:]))
    except SystemExit as err:
        return err.code

    # handle basic options
    if opts.version:
        print('Sphinx (sphinx-build) %s' % __display_version__)
        return 0

    # get paths (first and second positional argument)
    try:
        srcdir = abspath(args[0])
        confdir = abspath(opts.confdir or srcdir)
        if opts.noconfig:
            confdir = None
        if not path.isdir(srcdir):
            print('Error: Cannot find source directory `%s\'.' % srcdir,
                  file=sys.stderr)
            return 1
        if not opts.noconfig and not path.isfile(path.join(confdir, 'conf.py')):
            print('Error: Config directory doesn\'t contain a conf.py file.',
                  file=sys.stderr)
            return 1
        outdir = abspath(args[1])
        if srcdir == outdir:
            print('Error: source directory and destination directory are same.',
                  file=sys.stderr)
            return 1
    except IndexError:
        parser.print_help()
        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:]
    errored = False
    for filename in filenames:
        if not path.isfile(filename):
            print('Error: Cannot find file %r.' % filename, file=sys.stderr)
            errored = True
    if errored:
        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

    if opts.force_all and filenames:
        print('Error: Cannot combine -a option and filenames.', file=sys.stderr)
        return 1

    if opts.color == 'no' or (opts.color == 'auto' and not color_terminal()):
        nocolor()

    doctreedir = abspath(opts.doctreedir or path.join(outdir, '.doctrees'))

    status = sys.stdout
    warning = sys.stderr
    error = sys.stderr

    if opts.quiet:
        status = None
    if opts.really_quiet:
        status = warning = None
    if warning and opts.warnfile:
        try:
            warnfp = open(opts.warnfile, 'w')
        except Exception as exc:
            print('Error: Cannot open warning file %r: %s' %
                  (opts.warnfile, exc), file=sys.stderr)
            sys.exit(1)
        warning = Tee(warning, warnfp)  # type: ignore
        error = warning

    confoverrides = {}
    for val in opts.define:
        try:
            key, val = val.split('=', 1)
        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

    for val in opts.htmldefine:
        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

    if opts.nitpicky:
        confoverrides['nitpicky'] = True

    app = None
    try:
        with docutils_namespace():
            app = Sphinx(srcdir, confdir, outdir, doctreedir, opts.builder,
                         confoverrides, status, warning, opts.freshenv,
                         opts.warningiserror, opts.tags, opts.verbosity, opts.jobs)
            app.build(opts.force_all, filenames)
            return app.statuscode
    except (Exception, KeyboardInterrupt) as exc:
        handle_exception(app, opts, exc, error)
        return 1
Beispiel #29
0
def main(argv=sys.argv):
    if not sys.stdout.isatty() or sys.platform == 'win32':
        # Windows' poor cmd box doesn't understand ANSI sequences
        nocolor()

    try:
        opts, args = getopt.getopt(argv[1:], 'ab:d:D:NEqP')
        srcdir = path.abspath(args[0])
        if not path.isdir(srcdir):
            print >>sys.stderr, 'Error: Cannot find source directory.'
            return 1
        if not path.isfile(path.join(srcdir, 'conf.py')):
            print >>sys.stderr, 'Error: Source directory doesn\'t contain conf.py file.'
            return 1
        outdir = path.abspath(args[1])
        if not path.isdir(outdir):
            print >>sys.stderr, 'Error: Cannot find output directory.'
            return 1
    except (IndexError, getopt.error):
        usage(argv)
        return 1

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

    buildername = all_files = None
    freshenv = use_pdb = False
    status = sys.stdout
    confoverrides = {}
    doctreedir = path.join(outdir, '.doctrees')
    for opt, val in opts:
        if opt == '-b':
            buildername = val
        elif opt == '-a':
            if filenames:
                usage(argv, 'Cannot combine -a option and filenames.')
                return 1
            all_files = True
        elif opt == '-d':
            doctreedir = val
        elif opt == '-D':
            key, val = val.split('=')
            try:
                val = int(val)
            except: pass
            confoverrides[key] = val
        elif opt == '-N':
            nocolor()
        elif opt == '-E':
            freshenv = True
        elif opt == '-q':
            status = StringIO()
        elif opt == '-P':
            use_pdb = True

    try:
        app = Sphinx(srcdir, outdir, doctreedir, buildername,
                     confoverrides, status, sys.stderr, freshenv)
        if not app.builder:
            return 1

        if all_files:
            app.builder.build_all()
        elif filenames:
            app.builder.build_specific(filenames)
        else:
            app.builder.build_update()
    except KeyboardInterrupt:
        # catches BaseExceptions in 2.5 -- SystemExit, KeyboardInterrupt
        return 1
    except SystemExit:
        return 0
    except Exception, err:
        if use_pdb:
            import pdb
            print >>sys.stderr, darkred('Exception occurred while building, '
                                        'starting debugger:')
            traceback.print_exc()
            pdb.post_mortem(sys.exc_info()[2])
        else:
            if isinstance(err, SystemMessage):
                print >>sys.stderr, darkred('reST markup error:')
                print >>sys.stderr, str(err)
            else:
                print >>sys.stderr, darkred('Exception occurred:')
                print >>sys.stderr, format_exception_cut_frames().rstrip()
                tbpath = save_traceback()
                print >>sys.stderr, darkred('The full traceback has been saved '
                                            'in %s, if you want to report the '
                                            'issue to the author.' % tbpath)
                print >>sys.stderr, ('Please also report this if it was a user '
                                     'error, so that a better error message '
                                     'can be provided next time.')
                print >>sys.stderr, 'Send reports to [email protected]. Thanks!'
            return 1
Beispiel #30
0
def build_main(argv=sys.argv[1:]):
    # type: (List[str]) -> int
    """Sphinx build "main" command-line entry."""

    parser = get_parser()
    args = parser.parse_args(argv)

    if args.noconfig:
        args.confdir = None
    elif not args.confdir:
        args.confdir = args.sourcedir

    if not args.doctreedir:
        args.doctreedir = os.path.join(args.outputdir, '.doctrees')

    # handle remaining filename arguments
    filenames = args.filenames
    missing_files = []
    for filename in filenames:
        if not os.path.isfile(filename):
            missing_files.append(filename)
    if missing_files:
        parser.error(__('cannot find files %r') % missing_files)

    if args.force_all and filenames:
        parser.error(__('cannot combine -a option and filenames'))

    if args.color == 'no' or (args.color == 'auto' and not color_terminal()):
        nocolor()

    status = sys.stdout
    warning = sys.stderr
    error = sys.stderr

    if args.quiet:
        status = None

    if args.really_quiet:
        status = warning = None

    if warning and args.warnfile:
        try:
            warnfp = open(args.warnfile, 'w')
        except Exception as exc:
            parser.error(__('cannot open warning file %r: %s') % (
                args.warnfile, exc))
        warning = Tee(warning, warnfp)  # type: ignore
        error = warning

    confoverrides = {}
    for val in args.define:
        try:
            key, val = val.split('=', 1)
        except ValueError:
            parser.error(__('-D option argument must be in the form name=value'))
        confoverrides[key] = val

    for val in args.htmldefine:
        try:
            key, val = val.split('=')
        except ValueError:
            parser.error(__('-A option argument must be in the form name=value'))
        try:
            val = int(val)
        except ValueError:
            pass
        confoverrides['html_context.%s' % key] = val

    if args.nitpicky:
        confoverrides['nitpicky'] = True

    app = None
    try:
        confdir = args.confdir or args.sourcedir
        with patch_docutils(confdir), docutils_namespace():
            app = Sphinx(args.sourcedir, args.confdir, args.outputdir,
                         args.doctreedir, args.builder, confoverrides, status,
                         warning, args.freshenv, args.warningiserror,
                         args.tags, args.verbosity, args.jobs, args.keep_going)
            app.build(args.force_all, filenames)
            return app.statuscode
    except (Exception, KeyboardInterrupt) as exc:
        handle_exception(app, args, exc, error)
        return 2
Beispiel #31
0
         print >> sys.stderr, ('Error: -A option argument must be '
                               'in the form name=value.')
         return 1
     try:
         val = int(val)
     except ValueError:
         if likely_encoding and isinstance(val, bytes):
             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
Beispiel #32
0
def inner_main(args):
    d = {}

    if os.name == 'nt' or not sys.stdout.isatty():
        nocolor()

    print bold('Welcome to the Sphinx quickstart utility.')
    print '''
Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).'''

    print '''
Enter the root path for documentation.'''
    do_prompt(d, 'path', 'Root path for the documentation', '.', is_path)
    print '''
You have two options for placing the build directory for Sphinx output.
Either, you use a directory ".build" within the root path, or you separate
"source" and "build" directories within the root path.'''
    do_prompt(d, 'sep', 'Separate source and build directories (y/n)', 'n',
              boolean)
    print '''
Inside the root directory, two more directories will be created; ".templates"
for custom HTML templates and ".static" for custom stylesheets and other
static files. Since the leading dot may be inconvenient for Windows users,
you can enter another prefix (such as "_") to replace the dot.'''
    do_prompt(d, 'dot', 'Name prefix for templates and static dir', '.', ok)

    print '''
The project name will occur in several places in the built documentation.'''
    do_prompt(d, 'project', 'Project name')
    do_prompt(d, 'author', 'Author name(s)')
    print '''
Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1.  If you don't need this dual structure,
just set both to the same value.'''
    do_prompt(d, 'version', 'Project version')
    do_prompt(d, 'release', 'Project release', d['version'])
    print '''
The file name suffix for source files. Commonly, this is either ".txt"
or ".rst".  Only files with this suffix are considered documents.'''
    do_prompt(d, 'suffix', 'Source file suffix', '.rst', suffix)
    print '''
One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.'''
    do_prompt(d, 'master', 'Name of your master document (without suffix)',
              'index')
    print '''
Please indicate if you want to use one of the following Sphinx extensions:'''
    do_prompt(d, 'ext_autodoc', 'autodoc: automatically insert docstrings '
              'from modules (y/n)', 'n', boolean)
    do_prompt(d, 'ext_doctest', 'doctest: automatically test code snippets '
              'in doctest blocks (y/n)', 'n', boolean)
    print '''
If you are under Unix, a Makefile can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.'''
    do_prompt(d, 'makefile', 'Create Makefile? (y/n)',
              os.name == 'posix' and 'y' or 'n', boolean)

    d['project_fn'] = make_filename(d['project'])
    d['year'] = time.strftime('%Y')
    d['now'] = time.asctime()
    d['underline'] = len(d['project']) * '='
    d['extensions'] = ', '.join(
        repr('sphinx.ext.' + name) for name in ('autodoc', 'doctest')
        if d['ext_' + name].upper() in ('Y', 'YES'))

    if not path.isdir(d['path']):
        mkdir_p(d['path'])

    separate = d['sep'].upper() in ('Y', 'YES')
    srcdir = separate and path.join(d['path'], 'source') or d['path']

    mkdir_p(srcdir)
    if separate:
        builddir = path.join(d['path'], 'build')
    else:
        builddir = path.join(srcdir, d['dot'] + 'build')
    mkdir_p(builddir)
    mkdir_p(path.join(srcdir, d['dot'] + 'templates'))
    mkdir_p(path.join(srcdir, d['dot'] + 'static'))

    f = open(path.join(srcdir, 'conf.py'), 'w')
    f.write(QUICKSTART_CONF % d)
    f.close()

    masterfile = path.join(srcdir, d['master'] + d['suffix'])
    f = open(masterfile, 'w')
    f.write(MASTER_FILE % d)
    f.close()

    create_makefile = d['makefile'].upper() in ('Y', 'YES')
    if create_makefile:
        d['rsrcdir'] = separate and 'source' or '.'
        d['rbuilddir'] = separate and 'build' or d['dot'] + 'build'
        f = open(path.join(d['path'], 'Makefile'), 'w')
        f.write(MAKEFILE % d)
        f.close()

    print
    print bold('Finished: An initial directory structure has been created.')
    print '''
You should now populate your master file %s and create other documentation
source files. Use the sphinx-build script to build the docs, like so:
''' % masterfile + (create_makefile and '''
   make <builder>
''' or '''
   sphinx-build -b <builder> %s %s
''' % (srcdir, builddir))
Beispiel #33
0
import re
import os
import sys
import time
import codecs

from django.conf import settings
from django.contrib import messages

from sphinx import builders
from sphinx.application import Sphinx
from sphinx.util.console import nocolor
from sphinx.builders.html import SerializingHTMLBuilder
from sphinx.util.osutil import ensuredir, os_path

nocolor()

try:
    SETTINGS = settings.MEZE_SETTINGS
except AttributeError:
    SETTINGS = {}

WORKDIR = SETTINGS.get('workdir', settings.PROJECT_ROOT)
IMGEXTS = set(['.gif', '.png', '.jpg'])

try:
    SPHINX_CONF = settings.SPHINX_CONF
except AttributeError:
    SPHINX_CONF = """project = copyright = u''
version = release = '0'
master_doc = 'index'
def main(argv):
    if not color_terminal():
        # Windows' poor cmd box doesn't understand ANSI sequences
        nocolor()

    try:
        opts, args = getopt.getopt(argv[1:], 'ab:t:d:c:CD:A:ng:NEqQWw:P')
        allopts = set(opt[0] for opt in opts)
        srcdir = confdir = path.abspath(args[0])
        if not path.isdir(srcdir):
            print >>sys.stderr, 'Error: Cannot find source directory.'
            return 1
        if not path.isfile(path.join(srcdir, 'conf.py')) and \
               '-c' not in allopts and '-C' not in allopts:
            print >>sys.stderr, ('Error: Source directory doesn\'t '
                                 'contain conf.py file.')
            return 1
        outdir = path.abspath(args[1])
        if not path.isdir(outdir):
            print >>sys.stderr, 'Making output directory...'
            os.makedirs(outdir)
    except (IndexError, getopt.error):
        usage(argv)
        return 1

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

    buildername = None
    force_all = freshenv = warningiserror = use_pdb = False
    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, 'Cannot combine -a option and filenames.')
                return 1
            force_all = True
        elif opt == '-t':
            tags.append(val)
        elif opt == '-d':
            doctreedir = path.abspath(val)
        elif opt == '-c':
            confdir = path.abspath(val)
            if not path.isfile(path.join(confdir, 'conf.py')):
                print >>sys.stderr, ('Error: Configuration directory '
                                     'doesn\'t contain conf.py file.')
                return 1
        elif opt == '-C':
            confdir = None
        elif opt == '-D':
            try:
                key, val = val.split('=')
            except ValueError:
                print >>sys.stderr, ('Error: -D option argument must be '
                                     'in the form name=value.')
                return 1
            try:
                val = int(val)
            except ValueError:
                pass
            confoverrides[key] = val
        elif opt == '-A':
            try:
                key, val = val.split('=')
            except ValueError:
                print >>sys.stderr, ('Error: -A option argument must be '
                                     'in the form name=value.')
                return 1
            try:
                val = int(val)
            except ValueError:
                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

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

    try:
        app = Sphinx(srcdir, confdir, outdir, doctreedir, buildername,
                     confoverrides, status, warning, freshenv,
                     warningiserror, tags)
        app.build(force_all, filenames)
        return app.statuscode
    except KeyboardInterrupt:
        if use_pdb:
            import pdb
            print >>error, red('Interrupted while building, '
                                   'starting debugger:')
            traceback.print_exc()
            pdb.post_mortem(sys.exc_info()[2])
        return 1
    except Exception, err:
        if use_pdb:
            import pdb
            print >>error, red('Exception occurred while building, '
                                   'starting debugger:')
            traceback.print_exc()
            pdb.post_mortem(sys.exc_info()[2])
        else:
            print >>error
            if isinstance(err, SystemMessage):
                print >>error, red('reST markup error:')
                print >>error, err.args[0].encode('ascii', 'backslashreplace')
            elif isinstance(err, SphinxError):
                print >>error, red('%s:' % err.category)
                print >>error, err
            else:
                print >>error, red('Exception occurred:')
                print >>error, format_exception_cut_frames().rstrip()
                tbpath = save_traceback()
                print >>error, red('The full traceback has been saved '
                                   'in %s, if you want to report the '
                                   'issue to the developers.' % tbpath)
                print >>error, ('Please also report this if it was a user '
                                'error, so that a better error message '
                                'can be provided next time.')
                print >>error, (
                    'Either send bugs to the mailing list at '
                    '<http://groups.google.com/group/sphinx-dev/>,\n'
                    'or report them in the tracker at '
                    '<http://bitbucket.org/birkenfeld/sphinx/issues/>. Thanks!')
            return 1
Beispiel #35
0
def inner_main(args):
    d = {}
    texescape.init()

    if not color_terminal():
        nocolor()

    print bold('Welcome to the Sphinx quickstart utility.')
    print '''
Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).'''

    print '''
Enter the root path for documentation.'''
    do_prompt(d, 'path', 'Root path for the documentation', '.', is_path)

    while path.isfile(path.join(d['path'], 'conf.py')) or \
          path.isfile(path.join(d['path'], 'source', 'conf.py')):
        print
        print bold('Error: an existing conf.py has been found in the '
                   'selected root path.')
        print 'sphinx-quickstart will not overwrite existing Sphinx projects.'
        print
        do_prompt(d, 'path', 'Please enter a new root path (or just Enter '
                  'to exit)', '', is_path)
        if not d['path']:
            sys.exit(1)

    print '''
You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.'''
    do_prompt(d, 'sep', 'Separate source and build directories (y/N)', 'n',
              boolean)

    print '''
Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.'''
    do_prompt(d, 'dot', 'Name prefix for templates and static dir', '_', ok)

    print '''
The project name will occur in several places in the built documentation.'''
    do_prompt(d, 'project', 'Project name')
    do_prompt(d, 'author', 'Author name(s)')
    print '''
Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1.  If you don't need this dual structure,
just set both to the same value.'''
    do_prompt(d, 'version', 'Project version')
    do_prompt(d, 'release', 'Project release', d['version'])
    print '''
The file name suffix for source files. Commonly, this is either ".txt"
or ".rst".  Only files with this suffix are considered documents.'''
    do_prompt(d, 'suffix', 'Source file suffix', '.rst', suffix)
    print '''
One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.'''
    do_prompt(d, 'master', 'Name of your master document (without suffix)',
              'index')

    while path.isfile(path.join(d['path'], d['master']+d['suffix'])) or \
          path.isfile(path.join(d['path'], 'source', d['master']+d['suffix'])):
        print
        print bold('Error: the master file %s has already been found in the '
                   'selected root path.' % (d['master']+d['suffix']))
        print 'sphinx-quickstart will not overwrite the existing file.'
        print
        do_prompt(d, 'master', 'Please enter a new file name, or rename the '
                  'existing file and press Enter', d['master'])

    print '''
Please indicate if you want to use one of the following Sphinx extensions:'''
    do_prompt(d, 'ext_autodoc', 'autodoc: automatically insert docstrings '
              'from modules (y/N)', 'n', boolean)
    do_prompt(d, 'ext_doctest', 'doctest: automatically test code snippets '
              'in doctest blocks (y/N)', 'n', boolean)
    do_prompt(d, 'ext_intersphinx', 'intersphinx: link between Sphinx '
              'documentation of different projects (y/N)', 'n', boolean)
    do_prompt(d, 'ext_todo', 'todo: write "todo" entries '
              'that can be shown or hidden on build (y/N)', 'n', boolean)
    do_prompt(d, 'ext_coverage', 'coverage: checks for documentation '
              'coverage (y/N)', 'n', boolean)
    do_prompt(d, 'ext_pngmath', 'pngmath: include math, rendered '
              'as PNG images (y/N)', 'n', boolean)
    do_prompt(d, 'ext_jsmath', 'jsmath: include math, rendered in the '
              'browser by JSMath (y/N)', 'n', boolean)
    if d['ext_pngmath'] and d['ext_jsmath']:
        print '''Note: pngmath and jsmath cannot be enabled at the same time.
pngmath has been deselected.'''
    do_prompt(d, 'ext_ifconfig', 'ifconfig: conditional inclusion of '
              'content based on config values (y/N)', 'n', boolean)
    print '''
A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.'''
    do_prompt(d, 'makefile', 'Create Makefile? (Y/n)', 'y', boolean)
    do_prompt(d, 'batchfile', 'Create Windows command file? (Y/n)',
              'y', boolean)

    d['project_fn'] = make_filename(d['project'])
    d['now'] = time.asctime()
    d['underline'] = len(d['project']) * '='
    d['extensions'] = ', '.join(
        repr('sphinx.ext.' + name)
        for name in ('autodoc', 'doctest', 'intersphinx', 'todo', 'coverage',
                     'pngmath', 'jsmath', 'ifconfig')
        if d['ext_' + name])
    d['copyright'] = time.strftime('%Y') + ', ' + d['author']
    d['author_texescaped'] = unicode(d['author']).\
                             translate(texescape.tex_escape_map)
    d['project_doc'] = d['project'] + ' Documentation'
    d['project_doc_texescaped'] = unicode(d['project'] + ' Documentation').\
                                  translate(texescape.tex_escape_map)

    # escape backslashes and single quotes in strings that are put into
    # a Python string literal
    for key in ('project', 'copyright', 'author_texescaped',
                'project_doc_texescaped', 'version', 'release', 'master'):
        d[key + '_str'] = d[key].replace('\\', '\\\\').replace("'", "\\'")

    if not path.isdir(d['path']):
        mkdir_p(d['path'])

    srcdir = d['sep'] and path.join(d['path'], 'source') or d['path']

    mkdir_p(srcdir)
    if d['sep']:
        builddir = path.join(d['path'], 'build')
        d['exclude_trees'] = ''
    else:
        builddir = path.join(srcdir, d['dot'] + 'build')
        d['exclude_trees'] = repr(d['dot'] + 'build')
    mkdir_p(builddir)
    mkdir_p(path.join(srcdir, d['dot'] + 'templates'))
    mkdir_p(path.join(srcdir, d['dot'] + 'static'))

    conf_text = QUICKSTART_CONF % d
    if d['ext_intersphinx']:
        conf_text += INTERSPHINX_CONFIG

    f = open(path.join(srcdir, 'conf.py'), 'w')
    f.write(conf_text.encode('utf-8'))
    f.close()

    masterfile = path.join(srcdir, d['master'] + d['suffix'])
    f = open(masterfile, 'w')
    f.write((MASTER_FILE % d).encode('utf-8'))
    f.close()

    if d['makefile']:
        d['rsrcdir'] = d['sep'] and 'source' or '.'
        d['rbuilddir'] = d['sep'] and 'build' or d['dot'] + 'build'
        f = open(path.join(d['path'], 'Makefile'), 'w')
        f.write((MAKEFILE % d).encode('utf-8'))
        f.close()

    if d['batchfile']:
        d['rsrcdir'] = d['sep'] and 'source' or '.'
        d['rbuilddir'] = d['sep'] and 'build' or d['dot'] + 'build'
        f = open(path.join(d['path'], 'make.bat'), 'w')
        f.write((BATCHFILE % d).encode('utf-8'))
        f.close()

    print
    print bold('Finished: An initial directory structure has been created.')
    print '''
You should now populate your master file %s and create other documentation
source files. ''' % masterfile + ((d['makefile'] or d['batchfile']) and '''\
Use the Makefile to build the docs, like so:
   make builder
''' or '''\
Use the sphinx-build command to build the docs, like so:
   sphinx-build -b builder %s %s
''' % (srcdir, builddir)) + '''\
Beispiel #36
0
def main(argv):
    if not color_terminal():
        # Windows' poor cmd box doesn't understand ANSI sequences
        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
def main(argv: List[str] = sys.argv[1:]) -> int:
    sphinx.locale.setlocale(locale.LC_ALL, '')
    sphinx.locale.init_console(os.path.join(package_dir, 'locale'), 'sphinx')

    if not color_terminal():
        nocolor()

    # parse options
    parser = get_parser()
    try:
        args = parser.parse_args(argv)
    except SystemExit as err:
        return err.code

    d = vars(args)
    # delete None or False value
    d = {k: v for k, v in d.items() if v is not None}

    # handle use of CSV-style extension values
    d.setdefault('extensions', [])
    for ext in d['extensions'][:]:
        if ',' in ext:
            d['extensions'].remove(ext)
            d['extensions'].extend(ext.split(','))

    try:
        if 'quiet' in d:
            if not {'project', 'author'}.issubset(d):
                print(
                    __('"quiet" is specified, but any of "project" or '
                       '"author" is not specified.'))
                return 1

        if {'quiet', 'project', 'author'}.issubset(d):
            # quiet mode with all required params satisfied, use default
            d.setdefault('version', '')
            d.setdefault('release', d['version'])
            d2 = DEFAULTS.copy()
            d2.update(d)
            d = d2

            if not valid_dir(d):
                print()
                print(
                    bold(
                        __('Error: specified path is not a directory, or sphinx'
                           ' files already exist.')))
                print(
                    __('sphinx-quickstart only generate into a empty directory.'
                       ' Please specify a new root path.'))
                return 1
        else:
            ask_user(d)
    except (KeyboardInterrupt, EOFError):
        print()
        print('[Interrupted.]')
        return 130  # 128 + SIGINT

    for variable in d.get('variables', []):
        try:
            name, value = variable.split('=')
            d[name] = value
        except ValueError:
            print(__('Invalid template variable: %s') % variable)

    generate(d, overwrite=False, templatedir=args.templatedir)
    return 0
Beispiel #38
0
def main(argv=sys.argv):
    # type: (List[str]) -> int
    if not color_terminal():
        nocolor()

    parser = optparse.OptionParser(USAGE, epilog=EPILOG,
                                   version='Sphinx v%s' % __display_version__,
                                   formatter=MyFormatter())
    parser.add_option('-q', '--quiet', action='store_true', dest='quiet',
                      default=False,
                      help='quiet mode')

    group = parser.add_option_group('Structure options')
    group.add_option('--sep', action='store_true', dest='sep',
                     help='if specified, separate source and build dirs')
    group.add_option('--dot', metavar='DOT', dest='dot',
                     help='replacement for dot in _templates etc.')

    group = parser.add_option_group('Project basic options')
    group.add_option('-p', '--project', metavar='PROJECT', dest='project',
                     help='project name')
    group.add_option('-a', '--author', metavar='AUTHOR', dest='author',
                     help='author names')
    group.add_option('-v', metavar='VERSION', dest='version',
                     help='version of project')
    group.add_option('-r', '--release', metavar='RELEASE', dest='release',
                     help='release of project')
    group.add_option('-l', '--language', metavar='LANGUAGE', dest='language',
                     help='document language')
    group.add_option('--suffix', metavar='SUFFIX', dest='suffix',
                     help='source file suffix')
    group.add_option('--master', metavar='MASTER', dest='master',
                     help='master document name')
    group.add_option('--epub', action='store_true', dest='epub',
                     default=False,
                     help='use epub')

    group = parser.add_option_group('Extension options')
    for ext in EXTENSIONS:
        group.add_option('--ext-' + ext, action='store_true',
                         dest='ext_' + ext, default=False,
                         help='enable %s extension' % ext)
    group.add_option('--extensions', metavar='EXTENSIONS', dest='extensions',
                     action='append', help='enable extensions')

    group = parser.add_option_group('Makefile and Batchfile creation')
    group.add_option('--makefile', action='store_true', dest='makefile',
                     default=False,
                     help='create makefile')
    group.add_option('--no-makefile', action='store_true', dest='no_makefile',
                     default=False,
                     help='not create makefile')
    group.add_option('--batchfile', action='store_true', dest='batchfile',
                     default=False,
                     help='create batchfile')
    group.add_option('--no-batchfile', action='store_true', dest='no_batchfile',
                     default=False,
                     help='not create batchfile')
    group.add_option('-M', '--no-use-make-mode', action='store_false', dest='make_mode',
                     help='not use make-mode for Makefile/make.bat')
    group.add_option('-m', '--use-make-mode', action='store_true', dest='make_mode',
                     default=True,
                     help='use make-mode for Makefile/make.bat')

    group = parser.add_option_group('Project templating')
    group.add_option('-t', '--templatedir', metavar='TEMPLATEDIR', dest='templatedir',
                     help='template directory for template files')
    group.add_option('-d', metavar='NAME=VALUE', action='append', dest='variables',
                     help='define a template variable')

    # parse options
    try:
        opts, args = parser.parse_args(argv[1:])
    except SystemExit as err:
        return err.code

    if len(args) > 0:
        opts.ensure_value('path', args[0])

    d = vars(opts)
    # delete None or False value
    d = dict((k, v) for k, v in d.items() if not (v is None or v is False))

    try:
        if 'quiet' in d:
            if not set(['project', 'author']).issubset(d):
                print('''"quiet" is specified, but any of "project" or \
"author" is not specified.''')
                return 1

        if set(['quiet', 'project', 'author']).issubset(d):
            # quiet mode with all required params satisfied, use default
            d.setdefault('version', '')
            d.setdefault('release', d['version'])
            d2 = DEFAULT_VALUE.copy()
            d2.update(dict(("ext_" + ext, False) for ext in EXTENSIONS))
            d2.update(d)
            d = d2
            if 'no_makefile' in d:
                d['makefile'] = False
            if 'no_batchfile' in d:
                d['batchfile'] = False

            if not valid_dir(d):
                print()
                print(bold('Error: specified path is not a directory, or sphinx'
                           ' files already exist.'))
                print('sphinx-quickstart only generate into a empty directory.'
                      ' Please specify a new root path.')
                return 1
        else:
            ask_user(d)
    except (KeyboardInterrupt, EOFError):
        print()
        print('[Interrupted.]')
        return 130  # 128 + SIGINT

    # decode values in d if value is a Python string literal
    for key, value in d.items():
        if isinstance(value, binary_type):
            d[key] = term_decode(value)

    # parse extensions list
    d.setdefault('extensions', [])
    for ext in d['extensions'][:]:
        if ',' in ext:
            d['extensions'].remove(ext)
            for modname in ext.split(','):
                d['extensions'].append(modname)

    for variable in d.get('variables', []):
        try:
            name, value = variable.split('=')
            d[name] = value
        except ValueError:
            print('Invalid template variable: %s' % variable)

    generate(d, templatedir=opts.templatedir)
    return 0
Beispiel #39
0
def main(argv=sys.argv):
    if not color_terminal():
        nocolor()

    parser = optparse.OptionParser(USAGE,
                                   epilog=EPILOG,
                                   version='Sphinx v%s' % __display_version__,
                                   formatter=MyFormatter())
    parser.add_option('-q',
                      '--quiet',
                      action='store_true',
                      dest='quiet',
                      default=False,
                      help='quiet mode')

    group = parser.add_option_group('Structure options')
    group.add_option('--sep',
                     action='store_true',
                     dest='sep',
                     help='if specified, separate source and build dirs')
    group.add_option('--dot',
                     metavar='DOT',
                     dest='dot',
                     help='replacement for dot in _templates etc.')

    group = parser.add_option_group('Project basic options')
    group.add_option('-p',
                     '--project',
                     metavar='PROJECT',
                     dest='project',
                     help='project name')
    group.add_option('-a',
                     '--author',
                     metavar='AUTHOR',
                     dest='author',
                     help='author names')
    group.add_option('-v',
                     metavar='VERSION',
                     dest='version',
                     help='version of project')
    group.add_option('-r',
                     '--release',
                     metavar='RELEASE',
                     dest='release',
                     help='release of project')
    group.add_option('-l',
                     '--language',
                     metavar='LANGUAGE',
                     dest='language',
                     help='document language')
    group.add_option('--suffix',
                     metavar='SUFFIX',
                     dest='suffix',
                     help='source file suffix')
    group.add_option('--master',
                     metavar='MASTER',
                     dest='master',
                     help='master document name')
    group.add_option('--epub',
                     action='store_true',
                     dest='epub',
                     default=False,
                     help='use epub')

    group = parser.add_option_group('Extension options')
    for ext in EXTENSIONS:
        group.add_option('--ext-' + ext,
                         action='store_true',
                         dest='ext_' + ext,
                         default=False,
                         help='enable %s extension' % ext)

    group = parser.add_option_group('Makefile and Batchfile creation')
    group.add_option('--makefile',
                     action='store_true',
                     dest='makefile',
                     default=False,
                     help='create makefile')
    group.add_option('--no-makefile',
                     action='store_true',
                     dest='no_makefile',
                     default=False,
                     help='not create makefile')
    group.add_option('--batchfile',
                     action='store_true',
                     dest='batchfile',
                     default=False,
                     help='create batchfile')
    group.add_option('--no-batchfile',
                     action='store_true',
                     dest='no_batchfile',
                     default=False,
                     help='not create batchfile')
    group.add_option('-M',
                     '--no-use-make-mode',
                     action='store_false',
                     dest='make_mode',
                     help='not use make-mode for Makefile/make.bat')
    group.add_option('-m',
                     '--use-make-mode',
                     action='store_true',
                     dest='make_mode',
                     default=True,
                     help='use make-mode for Makefile/make.bat')

    # parse options
    try:
        opts, args = parser.parse_args(argv[1:])
    except SystemExit as err:
        return err.code

    if len(args) > 0:
        opts.ensure_value('path', args[0])

    d = vars(opts)
    # delete None or False value
    d = dict((k, v) for k, v in d.items() if not (v is None or v is False))

    try:
        if 'quiet' in d:
            if not set(['project', 'author']).issubset(d):
                print('''"quiet" is specified, but any of "project" or \
"author" is not specified.''')
                return 1

        if set(['quiet', 'project', 'author']).issubset(d):
            # quiet mode with all required params satisfied, use default
            d.setdefault('version', '')
            d.setdefault('release', d['version'])
            d2 = DEFAULT_VALUE.copy()
            d2.update(dict(("ext_" + ext, False) for ext in EXTENSIONS))
            d2.update(d)
            d = d2
            if 'no_makefile' in d:
                d['makefile'] = False
            if 'no_batchfile' in d:
                d['batchfile'] = False

            if not valid_dir(d):
                print()
                print(
                    bold('Error: specified path is not a directory, or sphinx'
                         ' files already exist.'))
                print('sphinx-quickstart only generate into a empty directory.'
                      ' Please specify a new root path.')
                return 1
        else:
            ask_user(d)
    except (KeyboardInterrupt, EOFError):
        print()
        print('[Interrupted.]')
        return 130  # 128 + SIGINT

    # decode values in d if value is a Python string literal
    for key, value in d.items():
        if isinstance(value, binary_type):
            d[key] = term_decode(value)

    generate(d)