Exemple #1
0
def gen(basepath, destpath, changelogpath, tixurl, confrepl=None, confpath=None, changelogtmpl=None):
    """Generate sphinx docs with all bells and whistles.

    basepath: The base sphinx source path.
    destpath: The final path of html files
    changelogpath: The path to the changelog file to insert in changelog.rst.
    tixurl: The URL (with one formattable argument for the tix number) to the ticket system.
    confrepl: Dictionary containing replacements that have to be made in conf.py. {name: replacement}
    """
    if confrepl is None:
        confrepl = {}
    if confpath is None:
        confpath = op.join(basepath, 'conf.tmpl')
    if changelogtmpl is None:
        changelogtmpl = op.join(basepath, 'changelog.tmpl')
    changelog = read_changelog_file(changelogpath)
    tix = tixgen(tixurl)
    rendered_logs = []
    for log in changelog:
        description = tix(log['description'])
        # The format of the changelog descriptions is in markdown, but since we only use bulled list
        # and links, it's not worth depending on the markdown package. A simple regexp suffice.
        description = re.sub(r'\[(.*?)\]\((.*?)\)', '`\\1 <\\2>`__', description)
        rendered = CHANGELOG_FORMAT.format(version=log['version'], date=log['date_str'],
            description=description)
        rendered_logs.append(rendered)
    confrepl['version'] = changelog[0]['version']
    changelog_out = op.join(basepath, 'changelog.rst')
    filereplace(changelogtmpl, changelog_out, changelog='\n'.join(rendered_logs))
    if op.exists(confpath):
        conf_out = op.join(basepath, 'conf.py')
        filereplace(confpath, conf_out, **confrepl)
    if LooseVersion(get_distribution("sphinx").version) >= LooseVersion("1.7.0"):
        from sphinx.cmd.build import build_main as sphinx_build
        # Call the sphinx_build function, which is the same as doing sphinx-build from cli
        try:
            sphinx_build([basepath, destpath])
        except SystemExit:
            print("Sphinx called sys.exit(), but we're cancelling it because we don't actually want to exit")
    else:
        # We used to call sphinx-build with print_and_do(), but the problem was that the virtualenv
        # of the calling python wasn't correctly considered and caused problems with documentation
        # relying on autodoc (which tries to import the module to auto-document, but fail because of
        # missing dependencies which are in the virtualenv). Here, we do exactly what is done when
        # calling the command from bash.
        cmd = load_entry_point('Sphinx', 'console_scripts', 'sphinx-build')
        try:
            cmd(['sphinx-build', basepath, destpath])
        except SystemExit:
            print("Sphinx called sys.exit(), but we're cancelling it because we don't actually want to exit")
def build(args):
    sourcedir = Path('.')  # TODO: parse SOURCEDIR from args
    if sourcedir.exists():
        print('calling sphinx with args', args)
        return sphinx_build(args)
    else:
        print('simulated call to flit')
Exemple #3
0
def build(build_args=None, docs_dir=None, build_dir=None, fmt=None, open_url=False):
    """Use sphinx-build to build the documentation."""
    status = sphinx_build(build_args)
    if status:
        sys.exit(status)
    if open_url and fmt == 'html':
        webbrowser.open(str(build_dir / 'index.html'))
Exemple #4
0
def gen(
    basepath,
    destpath,
    changelogpath,
    tixurl,
    confrepl=None,
    confpath=None,
    changelogtmpl=None,
):
    """Generate sphinx docs with all bells and whistles.

    basepath: The base sphinx source path.
    destpath: The final path of html files
    changelogpath: The path to the changelog file to insert in changelog.rst.
    tixurl: The URL (with one formattable argument for the tix number) to the ticket system.
    confrepl: Dictionary containing replacements that have to be made in conf.py. {name: replacement}
    """
    if confrepl is None:
        confrepl = {}
    if confpath is None:
        confpath = Path(basepath, "conf.tmpl")
    if changelogtmpl is None:
        changelogtmpl = Path(basepath, "changelog.tmpl")
    changelog = read_changelog_file(changelogpath)
    tix = tixgen(tixurl)
    rendered_logs = []
    for log in changelog:
        description = tix(log["description"])
        # The format of the changelog descriptions is in markdown, but since we only use bulled list
        # and links, it's not worth depending on the markdown package. A simple regexp suffice.
        description = re.sub(r"\[(.*?)\]\((.*?)\)", "`\\1 <\\2>`__", description)
        rendered = CHANGELOG_FORMAT.format(version=log["version"], date=log["date_str"], description=description)
        rendered_logs.append(rendered)
    confrepl["version"] = changelog[0]["version"]
    changelog_out = Path(basepath, "changelog.rst")
    filereplace(changelogtmpl, changelog_out, changelog="\n".join(rendered_logs))
    if Path(confpath).exists():
        conf_out = Path(basepath, "conf.py")
        filereplace(confpath, conf_out, **confrepl)
    # Call the sphinx_build function, which is the same as doing sphinx-build from cli
    try:
        sphinx_build([str(basepath), str(destpath)])
    except SystemExit:
        print("Sphinx called sys.exit(), but we're cancelling it because we don't actually want to exit")
Exemple #5
0
    def generate_sphinx_spell_words(self) -> Set[str]:
        """
        Generates Sphinx spelling dictionary

        Returns:
            spell words
        """
        if os.path.isdir(self._build_dir):
            shutil.rmtree(self._build_dir)
        if os.path.isdir(self._stubs_dir):
            shutil.rmtree(self._stubs_dir)
        if os.path.isdir(self._jupyter_execute_dir):
            shutil.rmtree(self._jupyter_execute_dir)
        try:
            os.mkdir(self._build_dir)
            sphinx_dict_file = os.path.join(
                self._build_dir, SpellDictGenerator._SPHINX_DICT_FILE)
            # create empty dictionary file
            with open(sphinx_dict_file, "w"):
                pass
            sphinx_build([
                "-b",
                "spelling",
                "-D",
                f"spelling_word_list_filename={sphinx_dict_file}",
                self._docs_dir,
                self._build_dir,
            ])
            self._sphinx_words = SpellDictGenerator._get_sphinx_spell_words(
                self._build_dir)
            return self._sphinx_words
        finally:
            if os.path.isdir(self._build_dir):
                shutil.rmtree(self._build_dir)
            if os.path.isdir(self._stubs_dir):
                shutil.rmtree(self._stubs_dir)
            if os.path.isdir(self._jupyter_execute_dir):
                shutil.rmtree(self._jupyter_execute_dir)
Exemple #6
0
def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]
    parser = argparse.ArgumentParser()
    parser.add_argument('-v',
                        '--version',
                        action="store_true",
                        help=u'Displays version')

    parser.add_argument('--ip', help="Drone IP address")

    parser.add_argument('--gendoc',
                        dest="doc_out_directory",
                        help="Generate olympe documentation")

    parser.add_argument('--gendoc_context_path',
                        dest="doc_context",
                        help="Documentation context path")

    ns = parser.parse_args(argv)
    args = vars(ns)

    if args['doc_out_directory']:
        from sphinx.cmd.build import main as sphinx_build
        cmd = ["-b", "html"]
        if args["doc_context"]:
            cmd += [
                "-D", "custom_html_context_path={}".format(args["doc_context"])
            ]
        cmd += ["{}/doc".format(os.path.dirname(olympe.__file__))]
        cmd += [args['doc_out_directory']]
        sys.exit(sphinx_build(cmd))

    if 'version' in args and args['version']:
        print(olympe.__version__)
        sys.exit(0)

    import IPython
    user_ns = dict(olympe=olympe)
    if args["ip"]:
        user_ns["drone"] = olympe.Drone(args["ip"])
    IPython.embed(user_ns=user_ns)
Exemple #7
0
 def build_html(self) -> None:
     if sphinx_build(self.sphinx_args):
         raise SphinxBuildError("BUILD FAILED")
Exemple #8
0
def gen(basepath,
        destpath,
        changelogpath,
        tixurl,
        confrepl=None,
        confpath=None,
        changelogtmpl=None):
    """Generate sphinx docs with all bells and whistles.

    basepath: The base sphinx source path.
    destpath: The final path of html files
    changelogpath: The path to the changelog file to insert in changelog.rst.
    tixurl: The URL (with one formattable argument for the tix number) to the ticket system.
    confrepl: Dictionary containing replacements that have to be made in conf.py. {name: replacement}
    """
    if confrepl is None:
        confrepl = {}
    if confpath is None:
        confpath = op.join(basepath, 'conf.tmpl')
    if changelogtmpl is None:
        changelogtmpl = op.join(basepath, 'changelog.tmpl')
    changelog = read_changelog_file(changelogpath)
    tix = tixgen(tixurl)
    rendered_logs = []
    for log in changelog:
        description = tix(log['description'])
        # The format of the changelog descriptions is in markdown, but since we only use bulled list
        # and links, it's not worth depending on the markdown package. A simple regexp suffice.
        description = re.sub(r'\[(.*?)\]\((.*?)\)', '`\\1 <\\2>`__',
                             description)
        rendered = CHANGELOG_FORMAT.format(version=log['version'],
                                           date=log['date_str'],
                                           description=description)
        rendered_logs.append(rendered)
    confrepl['version'] = changelog[0]['version']
    changelog_out = op.join(basepath, 'changelog.rst')
    filereplace(changelogtmpl,
                changelog_out,
                changelog='\n'.join(rendered_logs))
    if op.exists(confpath):
        conf_out = op.join(basepath, 'conf.py')
        filereplace(confpath, conf_out, **confrepl)
    if LooseVersion(
            get_distribution("sphinx").version) >= LooseVersion("1.7.0"):
        from sphinx.cmd.build import build_main as sphinx_build
        # Call the sphinx_build function, which is the same as doing sphinx-build from cli
        try:
            sphinx_build([basepath, destpath])
        except SystemExit:
            print(
                "Sphinx called sys.exit(), but we're cancelling it because we don't actually want to exit"
            )
    else:
        # We used to call sphinx-build with print_and_do(), but the problem was that the virtualenv
        # of the calling python wasn't correctly considered and caused problems with documentation
        # relying on autodoc (which tries to import the module to auto-document, but fail because of
        # missing dependencies which are in the virtualenv). Here, we do exactly what is done when
        # calling the command from bash.
        cmd = load_entry_point('Sphinx', 'console_scripts', 'sphinx-build')
        try:
            cmd(['sphinx-build', basepath, destpath])
        except SystemExit:
            print(
                "Sphinx called sys.exit(), but we're cancelling it because we don't actually want to exit"
            )
Exemple #9
0
    parser = argparse.ArgumentParser()
    parser.add_argument('-v',
                        '--version',
                        action="store_true",
                        help=u'Displays version')

    parser.add_argument('--gendoc',
                        dest="doc_out_directory",
                        help="Generate olympe documentation")

    parser.add_argument('--gendoc_context_path',
                        dest="doc_context",
                        help="Documentation context path")

    ns = parser.parse_args()
    args = vars(ns)

    if args['doc_out_directory']:
        cmd = ["-b", "html"]
        if args["doc_context"]:
            cmd += [
                "-D", "custom_html_context_path={}".format(args["doc_context"])
            ]
        cmd += ["{}/doc".format(os.path.dirname(olympe.__file__))]
        cmd += [args['doc_out_directory']]
        sys.exit(sphinx_build(cmd))

    if 'version' in args and args['version']:
        print(olympe.VERSION_STRING)
        sys.exit(0)
Exemple #10
0
    def from_arguments(
        cls,
        *,
        cli_args: Optional[List[str]] = None,
        sphinx_args: Optional[Dict[str, Any]] = None,
    ) -> Optional["SphinxConfig"]:
        """Return the ``SphinxConfig`` instance that's equivalent to the given arguments.

        .. note::

            Only ``cli_args`` **or** ``sphinx_args`` may be given.

        .. warning::

            This method is unable to determine the value of the
            :obj:`SphinxConfig.make_mode` setting when passing ``sphinx_args``


        Parameters
        ----------
        cli_args
           The cli arguments you would normally pass to ``sphinx-build``

        sphinx_args:
           The arguments you would use to create a ``Sphinx`` application instance.
        """

        make_mode: bool = False
        neither_given = cli_args is None and sphinx_args is None
        both_given = cli_args is not None and sphinx_args is not None
        if neither_given or both_given:
            raise ValueError(
                "You must pass either 'cli_args' or 'sphinx_args'")

        if cli_args is not None:
            # The easiest way to handle this is to just call sphinx-build but with
            # the Sphinx app object patched out - then we just use all the args it
            # was given!
            with mock.patch("sphinx.cmd.build.Sphinx") as m_Sphinx:
                sphinx_build(cli_args)

            if m_Sphinx.call_args is None:
                return None

            signature = inspect.signature(Sphinx)
            keys = signature.parameters.keys()

            values = m_Sphinx.call_args[0]
            sphinx_args = {k: v for k, v in zip(keys, values)}

            # `-M` has to be the first argument passed to `sphinx-build`
            # https://github.com/sphinx-doc/sphinx/blob/1222bed88eb29cde43a81dd208448dc903c53de2/sphinx/cmd/build.py#L287
            make_mode = cli_args[0] == "-M"
            if make_mode and sphinx_args["outdir"].endswith(
                    sphinx_args["buildername"]):
                build_dir = pathlib.Path(sphinx_args["outdir"]).parts[:-1]
                sphinx_args["outdir"] = str(pathlib.Path(*build_dir))

        if sphinx_args is None:
            return None

        return cls(
            confDir=sphinx_args.get("confdir", None),
            configOverrides=sphinx_args.get("confoverrides", {}),
            buildDir=sphinx_args.get("outdir", None),
            builderName=sphinx_args.get("buildername", "html"),
            doctreeDir=sphinx_args.get("doctreedir", None),
            forceFullBuild=sphinx_args.get("freshenv", False),
            keepGoing=sphinx_args.get("keep_going", False),
            makeMode=make_mode,
            numJobs=sphinx_args.get("parallel", 1),
            quiet=sphinx_args.get("status", 1) is None,
            silent=sphinx_args.get("warning", 1) is None,
            srcDir=sphinx_args.get("srcdir", None),
            tags=sphinx_args.get("tags", []),
            verbosity=sphinx_args.get("verbosity", 0),
            warningIsError=sphinx_args.get("warningiserror", False),
        )