Example #1
0
    def prepareSphinx(src_dir, out_dir, doctree_dir, config=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
        """
        # 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 not color_terminal():
            nocolor()

        sts = ConfluenceTestUtil.default_sphinx_status
        conf = dict(config) if config else None
        conf_dir = src_dir if not conf else None
        warnerr = not relax

        with docutils_namespace():
            app = Sphinx(
                src_dir,  # output for document sources
                conf_dir,  # ignore configuration directory
                out_dir,  # output for generated documents
                doctree_dir,  # output for doctree files
                ConfluenceBuilder.name,  # use this extension's builder
                confoverrides=conf,  # load provided configuration (volatile)
                status=sts,  # status output
                warning=sys.stderr,  # warnings output
                warningiserror=warnerr)  # treat warnings as errors

            yield app
Example #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: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
Example #3
0
    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
        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
Example #4
0
    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.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
Example #5
0
    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
        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
    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
Example #7
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
Example #8
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
Example #9
0
    def run(self) -> None:
        warnings.warn('setup.py build_sphinx is deprecated.',
                      RemovedInSphinx70Warning,
                      stacklevel=2)

        if not color_terminal():
            nocolor()
        if not self.verbose:  # type: ignore
            status_stream = StringIO()
        else:
            status_stream = sys.stdout  # type: ignore
        confoverrides: 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,
                                 verbosity=self.verbosity,
                                 keep_going=self.keep_going)
                    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) from exc

            if not self.link_index:
                continue

            src = app.config.root_doc + app.builder.out_suffix  # type: ignore
            dst = app.builder.get_outfilename('index')  # type: ignore
            os.symlink(src, dst)
Example #10
0
    def build_help(self) -> 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))
        for osname, bname, description in BUILDERS:
            if not osname or os.name == osname:
                print('  %s  %s' % (blue(bname.ljust(10)), description))
Example #11
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))
Example #12
0
def prepareSphinx(src_dir,
                  out_dir,
                  doctree_dir,
                  config=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
    """
    # 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 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'

    with docutils_namespace():
        app = Sphinx(
            src_dir,  # output for document sources
            conf_dir,  # configuration directory
            out_dir,  # output for generated documents
            doctree_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
Example #13
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
Example #14
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
Example #15
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)

        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)
Example #16
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
Example #17
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
Example #18
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)
Example #19
0
File: start.py Project: tg-m/ablog
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)
Example #20
0
    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 = {}
        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

        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)
Example #21
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)
Example #22
0
    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)
Example #23
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)
Example #24
0
def main():
    parser = argparse.ArgumentParser(
        prog='sphinx-build-confluence',
        add_help=False,
        description='Sphinx extension to output Atlassian Confluence content.',
    )

    parser.add_argument('action', nargs='?')
    parser.add_argument('--color',
                        default='auto',
                        action='store_const',
                        const='yes')
    parser.add_argument('--help', '-h', action='store_true')
    parser.add_argument('--no-color',
                        '-N',
                        dest='color',
                        action='store_const',
                        const='no')
    parser.add_argument('--verbose', '-V', action='count', default=0)
    parser.add_argument('--version',
                        action='version',
                        version='%(prog)s ' + version)
    parser.add_argument('--work-dir')

    args, _ = parser.parse_known_args()
    if args.help:
        print(usage())
        sys.exit(0)

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

    # pre-load logging support if sphinx is not loaded (to prevent blank lines)
    logger.initialize(preload=True)

    # invoke a desired command mainline
    if args.action == 'report':
        rv = report_main(parser)
    elif args.action == 'wipe':
        rv = wipe_main(parser)
    else:
        rv = build_main(parser)

    return rv
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)
Example #26
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)
Example #27
0
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}

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

    ## Supporting .rst as the default suffix
    d.setdefault('suffix', '.rst')
    d.setdefault('master', 'index')

    ## specifying kernels
    kernel_obj = {'python3': False, 'python2': False, 'julia-1.1': False}
    d.setdefault('kernels', kernel_obj)

    try:
        ask_user(d)
    except (KeyboardInterrupt, EOFError):
        print()
        print('[Interrupted.]')
        return 130  # 128 + SIGINT

    generate(d, overwrite=False)
    return 0
Example #28
0
    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 as err:
            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)
Example #29
0
def main():
    parser = argparse.ArgumentParser(
        prog='sphinx-build-confluence',
        add_help=False,
        description='Sphinx extension to output Atlassian Confluence content.')

    parser.add_argument('action', nargs='?')
    parser.add_argument('--help', '-h', action='store_true')
    parser.add_argument('--no-color', '-N', dest='color')
    parser.add_argument('--verbose', '-V', action='count', default=0)
    parser.add_argument('--version',
                        action='version',
                        version='%(prog)s ' + version)
    parser.add_argument('--work-dir')

    args, _ = parser.parse_known_args()
    if args.help:
        print(usage())
        sys.exit(0)

    logger.initialize(preload=True)
    if args.color == 'no' or (args.color == 'auto' and not color_terminal()):
        nocolor()
    # disable color (on windows) by default when using virtualenv since it
    # appears to be causing issues
    elif getattr(sys, 'base_prefix', sys.prefix) != sys.prefix:
        if sys.platform == 'win32':
            nocolor()

    # invoke a desired command mainline
    if args.action == 'report':
        rv = report_main(parser)
    elif args.action == 'wipe':
        rv = wipe_main(parser)
    else:
        rv = build_main(parser)

    return rv
Example #30
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)

            # Post process equations if requested
            if os.environ.get('UPDATEHTMLEQS'):
                ival = os.environ.get('UPDATEHTMLEQS')
                ival = ival.strip()
                if ival == 'Y':
                    # Perform post processing of equations here
                    print("Performing post processing of equations.")

                    eqVerbose = ""
                    if os.environ.get('UPDATEHTMLEQSVERBOSE'):
                        eqVerbose = "-v"

                    #@python3 ./postProcessEquations.py -d $(BUILDDIR) -p html -b sphinx -s index.html $(UPDATEHTMLEQSVERBOSE)
                    builddir = os.sep.join(args.outputdir.split('/')[0:-1])
                    projdir = args.outputdir.split('/')[-1]
                    if builddir == projdir:
                        projdir = "."
                    if eqVerbose != "":
                        cmd = [
                            'python3', './postProcessEquations.py', '-d',
                            builddir, '-p', projdir, '-b', 'sphinx', '-s',
                            'index.html', eqVerbose
                        ]
                    else:
                        cmd = [
                            'python3', './postProcessEquations.py', '-d',
                            builddir, '-p', projdir, '-b', 'sphinx', '-s',
                            'index.html'
                        ]
                    print('Running:', cmd)
                    out = check_output(cmd)

            return app.statuscode
    except (Exception, KeyboardInterrupt) as exc:
        handle_exception(app, args, exc, error)
        return 2
Example #31
0
def inner_main(args):
    d = {}

    if not sys.stdout.isatty() or 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. 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)
    do_prompt(
        d, 'ext_intersphinx', 'intersphinx: link between Sphinx documentation '
        'of different projects (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['now'] = time.asctime()
    d['underline'] = len(d['project']) * '='
    d['extensions'] = ', '.join(
        repr('sphinx.ext.' + name)
        for name in ('autodoc', 'doctest', 'intersphinx')
        if d['ext_' + name].upper() in ('Y', 'YES'))
    d['copyright'] = time.strftime('%Y') + ', ' + d['author']
    d['author_texescaped'] = unicode(d['author']).translate(tex_escape_map)
    d['project_doc'] = d['project'] + ' Documentation'
    d['project_doc_texescaped'] = \
        unicode(d['project'] + ' Documentation').translate(tex_escape_map)

    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')
        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'].upper() in ('Y', 'YES'):
        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()

    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).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. 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))
Example #32
0
def main(argv=sys.argv[1:]):  # type: ignore
    # type: (List[unicode]) -> int

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

    # get paths (first and second positional argument)
    try:
        srcdir = abspath(args.sourcedir)
        confdir = abspath(args.confdir or srcdir)
        if args.noconfig:
            confdir = None

        if not path.isdir(srcdir):
            parser.error('cannot find source directory (%s)' % srcdir)
        if not args.noconfig and not path.isfile(path.join(confdir,
                                                           'conf.py')):
            parser.error("config directory doesn't contain a conf.py file "
                         "(%s)" % confdir)

        outdir = abspath(args.outputdir)
        if srcdir == outdir:
            parser.error('source directory and destination directory are same')
    except UnicodeError:
        parser.error('multibyte filename not supported on this filesystem '
                     'encoding (%r)' % fs_encoding)

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

    # 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 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()

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

    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')
        if likely_encoding and isinstance(val, binary_type):
            try:
                val = val.decode(likely_encoding)
            except UnicodeError:
                pass
        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:
            if likely_encoding and isinstance(val, binary_type):
                try:
                    val = val.decode(likely_encoding)
                except UnicodeError:
                    pass
        confoverrides['html_context.%s' % key] = val

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

    app = None
    try:
        with patch_docutils(), docutils_namespace():
            app = Sphinx(srcdir, confdir, outdir, doctreedir, args.builder,
                         confoverrides, status, warning, args.freshenv,
                         args.warningiserror, args.tags, args.verbosity,
                         args.jobs)
            app.build(args.force_all, filenames)
            return app.statuscode
    except (Exception, KeyboardInterrupt) as exc:
        handle_exception(app, args, exc, error)
        return 2
Example #33
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:]
    err = 0  # type: ignore
    for filename in filenames:
        if not path.isfile(filename):
            print('Error: Cannot find file %r.' % filename, file=sys.stderr)
            err = 1  # type: ignore
    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.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
Example #34
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
Example #35
0
def main(argv=sys.argv):
    if not color_terminal():
        nocolor()

    parser = optparse.OptionParser(USAGE,
                                   epilog=EPILOG,
                                   version='Sphinx v%s' % __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')

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

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

    d = vars(opts)
    for k, v in list(d.items()):
        # delete None or False value
        if v is None or v is False:
            del d[k]

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

        if all(['quiet' in d, 'project' in d, 'author' in d, 'version' in d]):
            # quiet mode with all required params satisfied, use default
            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 path.exists(d['path']) and (not path.isdir(d['path'])
                                           or os.listdir(d['path'])):
                print()
                print(
                    bold('Error: specified path is not a directory, or not a'
                         ' empty directory.'))
                print('sphinx-quickstart only generate into a empty directory.'
                      ' Please specify a new root path.')
                return
        else:
            ask_user(d)
    except (KeyboardInterrupt, EOFError):
        print()
        print('[Interrupted.]')
        return
    generate(d)
Example #36
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
Example #37
0
def main(argv=sys.argv[1:]):  # type: ignore
    # type: (List[unicode]) -> int

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

    # get paths (first and second positional argument)
    try:
        srcdir = abspath(args.sourcedir)
        confdir = abspath(args.confdir or srcdir)
        if args.noconfig:
            confdir = None
        if not path.isdir(srcdir):
            print('Error: Cannot find source directory `%s\'.' % srcdir,
                  file=sys.stderr)
            return 1
        if not args.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.outputdir)
        if srcdir == outdir:
            print('Error: source directory and destination directory are same.',
                  file=sys.stderr)
            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.filenames
    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 args.force_all and filenames:
        print('Error: Cannot combine -a option and filenames.', file=sys.stderr)
        return 1

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

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

    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:
            print('Error: Cannot open warning file %r: %s' %
                  (args.warnfile, exc), file=sys.stderr)
            sys.exit(1)
        warning = Tee(warning, warnfp)  # type: ignore
        error = warning

    confoverrides = {}
    for val in args.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 args.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 args.nitpicky:
        confoverrides['nitpicky'] = True

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

    try:
        opts, args = getopt.getopt(argv[1:], 'ab:d:c:CD:A:NEqP')
        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 = all_files = None
    freshenv = use_pdb = False
    status = sys.stdout
    warning = sys.stderr
    confoverrides = {}
    htmlcontext = {}
    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 == '-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
            htmlcontext[key] = val
        elif opt == '-N':
            nocolor()
        elif opt == '-E':
            freshenv = True
        elif opt == '-q':
            status = None
        elif opt == '-Q':
            status = None
            warning = None
        elif opt == '-P':
            use_pdb = True
    confoverrides['html_context'] = htmlcontext

    try:
        app = Sphinx(srcdir, confdir, outdir, doctreedir, buildername,
                     confoverrides, status, warning, freshenv)
        app.build(all_files, filenames)
        return app.statuscode
    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
Example #39
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)) + '''\
Example #40
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
Example #41
0
def inner_main(args):
    d = {}

    if not sys.stdout.isatty() or 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. 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)
    do_prompt(d, 'ext_intersphinx', 'intersphinx: link between Sphinx documentation '
              'of different projects (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['now'] = time.asctime()
    d['underline'] = len(d['project']) * '='
    d['extensions'] = ', '.join(
        repr('sphinx.ext.' + name) for name in ('autodoc', 'doctest', 'intersphinx')
        if d['ext_' + name].upper() in ('Y', 'YES'))
    d['copyright'] = time.strftime('%Y') + ', ' + d['author']
    d['author_texescaped'] = unicode(d['author']).translate(tex_escape_map)
    d['project_doc'] = d['project'] + ' Documentation'
    d['project_doc_texescaped'] = \
        unicode(d['project'] + ' Documentation').translate(tex_escape_map)

    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')
        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'].upper() in ('Y', 'YES'):
        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()

    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).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. 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))
Example #42
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
Example #43
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
Example #44
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')

    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)

    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)
Example #45
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])
        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:]
    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:
        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
Example #46
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
Example #47
0
"ext_pngmath": true,
"sep": true,
"ext_todo": false,
"ext_coverage": false,
"ext_viewcode": false,
"batchfile": true,
"master": "index",
"epub": false,
"ext_intersphinx": false,
"dot": "_",
"ext_doctest": false
}'''

# Load the options from the json string into a Python dict
options = json.loads(json_conf)

# Everything below is copied from quickstart.py: you need not understand it
# unless noted

if not color_terminal():
    nocolor()

try:
    #Ask the user for the rest of the options
    qs.ask_user(options)
except (KeyboardInterrupt, EOFError):
    print
    print '[Interrupted.]'
    exit()
qs.generate(options)
Example #48
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:P")
        allopts = set(opt[0] for opt in opts)
        srcdir = confdir = path.abspath(args[0])
        if not path.isdir(srcdir):
            print("Error: Cannot find source directory.", 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 conf.py file."), file=sys.stderr)
            return 1
        outdir = path.abspath(args[1])
        if not path.isdir(outdir):
            print("Making output directory...", file=sys.stderr)
            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("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
    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(("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
            try:
                val = int(val)
            except ValueError:
                if likely_encoding and isinstance(val, bytes):
                    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, 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

    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(red("Interrupted while building, starting debugger:"), file=error)
            traceback.print_exc()
            pdb.post_mortem(sys.exc_info()[2])
        return 1
    except Exception 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 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(str(err)), file=error)
            else:
                print(red("Exception occurred:"), file=error)
                print(format_exception_cut_frames().rstrip(), file=error)
                tbpath = save_traceback()
                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(
                    (
                        "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!"
                    ),
                    file=error,
                )
            return 1
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

    # 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
    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:
                if likely_encoding:
                    try:
                        val = val.decode(likely_encoding)
                    except UnicodeError:
                        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:
                if likely_encoding:
                    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

    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, terminal_safe(err.args[0])
            elif isinstance(err, SphinxError):
                print >> error, red('%s:' % err.category)
                print >> error, terminal_safe(unicode(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
Example #50
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' % __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
Example #51
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
Example #52
0
def main(argv):
    if not sys.stdout.isatty() or not color_terminal():
        # Windows' poor cmd box doesn't understand ANSI sequences
        nocolor()

    try:
        opts, args = getopt.getopt(argv[1:], 'ab:d:c:D:A: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, '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 = all_files = None
    freshenv = use_pdb = False
    status = sys.stdout
    warning = sys.stderr
    confoverrides = {}
    htmlcontext = {}
    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':
            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
            htmlcontext[key] = val
        elif opt == '-N':
            nocolor()
        elif opt == '-E':
            freshenv = True
        elif opt == '-q':
            status = None
        elif opt == '-Q':
            status = None
            warning = None
        elif opt == '-P':
            use_pdb = True
    confoverrides['html_context'] = htmlcontext

    try:
        app = Sphinx(srcdir, confdir, outdir, doctreedir, buildername,
                     confoverrides, status, warning, freshenv)
        app.build(all_files, filenames)
        return app.statuscode
    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
Example #53
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: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
Example #54
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)
Example #55
0
def main(argv=sys.argv[1:]):
    # type: (List[str]) -> 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 = dict((k, v) for k, v in d.items() if v is not None)

    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

    # 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, overwrite=False, templatedir=args.templatedir)
    return 0
Example #56
0
def main(argv=sys.argv):
    if not color_terminal():
        nocolor()

    parser = optparse.OptionParser(USAGE, epilog=EPILOG,
                                   version='Sphinx v%s' % __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')

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

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

    d = vars(opts)
    for k, v in list(d.items()):
        # delete None or False value
        if v is None or v is False:
            del d[k]

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

        if all(['quiet' in d, 'project' in d, 'author' in d,
                'version' in d]):
            # quiet mode with all required params satisfied, use default
            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 path.exists(d['path']) and (
                    not path.isdir(d['path']) or os.listdir(d['path'])):
                print()
                print(bold('Error: specified path is not a directory, or not a'
                           ' empty directory.'))
                print('sphinx-quickstart only generate into a empty directory.'
                      ' Please specify a new root path.')
                return
        else:
            ask_user(d)
    except (KeyboardInterrupt, EOFError):
        print()
        print('[Interrupted.]')
        return
    generate(d)
Example #57
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
Example #58
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
            try:
                val = int(val)
            except ValueError:
                if likely_encoding and isinstance(val, bytes):
                    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, 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
        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(str(err)), file=error)
            elif isinstance(err, UnicodeError):
                print(red('Encoding error:'), file=error)
                print(terminal_safe(str(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((
                    'Either send bugs to the mailing list at '
                    '<http://groups.google.com/group/sphinx-users/>,\n'
                    'or report them in the tracker at '
                    '<http://bitbucket.org/birkenfeld/sphinx/issues/>. Thanks!'
                ),
                      file=error)
            return 1