# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.

import os
import pathlib
import sys

from sphinx.ext import autodoc
from sphinx.util import logging

sys.path.insert(0, os.path.abspath('../'))

logger = logging.getLogger(__name__)


# -- Version detection -------------------------------------------------------

extracted_version = None

if not os.path.exists("../PKG-INFO"):
    # Not building from an SDist, hopefully we're building from git.
    try:
        import setuptools_scm
        extracted_version = setuptools_scm.get_version(root='..')
    except (ModuleNotFoundError, LookupError) as exc:
        logger.warning(exc)

while not extracted_version:
    if not os.path.exists("../PKG-INFO"):
        # Tarball builds have no version information for us.
        break

    # We are building from an SDist (PyPI .tar.gz, Fedora SRPM, etc)
    try:
        # stdlib, py3.8+, preferred method.
        from importlib.metadata import PathDistribution
        extracted_version = PathDistribution(pathlib.Path('../')).version
        print("using importlib.metadata version")
        break
    except ModuleNotFoundError:
        logger.info(
            "importlib.metadata not found; "
            "trying another method to determine version."
        )

    try:
        import pkg_resources  # Included with setuptools
        dist = list(pkg_resources.find_distributions('../'))[0]
        extracted_version = dist.version
        print("using pkg_resources version")
        break
    except ModuleNotFoundError:
        logger.info(
            "pkg_resources not found; "
            "trying another method to determine version."
        )

    try:
        import pkginfo  # Third-party package.
        extracted_version = pkginfo.UnpackedSDist('../').version
        print("using pkginfo version")
        break
    except ModuleNotFoundError:
        logger.info(
            "pkginfo not found; "
            "trying another method to determine version."
        )

    # Out of methods to try, give up.
    break

if not extracted_version:
    logger.warning(
        "Version information not present or determinable.\n"
        "Docs should be built either from git or a PyPI SDist .tar.gz.\n"
        "GitLab tarballs do not include the requisite version info."
    )
    extracted_version = "unknown version"


# -- Project information -----------------------------------------------------

project = 'QEMU Monitor Protocol Library'
copyright = '2009-2022, QEMU Project'
author = 'John Snow'
version = release = extracted_version


# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.viewcode',
    'sphinx.ext.todo',
    'sphinx.ext.intersphinx',
    'sphinx.ext.coverage',
    'sphinx.ext.viewcode',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'en'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# Interpret `this` to be a cross-reference to "anything".
default_role = 'any'

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'

# https://sphinx-rtd-theme.readthedocs.io/en/stable/configuring.html#theme-options
html_theme_options = {
    'collapse_navigation': False,
    'prev_next_buttons_location': 'both',
}

html_context = {
    "display_gitlab": True,
    "gitlab_user": "qemu-project",
    "gitlab_repo": "python-qemu-qmp",
    "gitlab_version": "main",
    "conf_py_path": "/docs/",
}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']


# -- Options for manual page output ------------------------------------------

man_pages = [
    (
        'man/qmp_shell',                            # Index/file
        'qmp-shell',                                # Name
        'An interactive QEMU shell powered by QMP', # Description
        ['The QEMU Project authors'],               # Author(s)
        1,                                          # Section
    ), (
        'man/qmp_shell_wrap',
        'qmp-shell-wrap',
        'QEMU + qmp-shell launcher utility',
        ['The QEMU Project authors'],
        1,
    )
]

man_show_urls = True

# -- Extension configuration -------------------------------------------------

# -- Options for intersphinx extension ---------------------------------------

intersphinx_mapping = {
    'python': ('https://docs.python.org/3', None),
    'qemu': ('https://www.qemu.org/docs/master', None),
}

intersphinx_disabled_reftypes = []

# -- Options for todo extension ----------------------------------------------

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True

# -- Custom extensions -------------------------------------------------------

class FunctionDocstringDocumenter(autodoc.FunctionDocumenter):
    """
    Creates a "docstring-only" directive for functions.

    This is used to pull docstring text from code without Sphinx
    generating function usage information for that object.
    """
    objtype = 'docstring'
    priority = autodoc.FunctionDocumenter.priority - 10
    content_indent = ''
    option_spec = dict(autodoc.FunctionDocumenter.option_spec)
    option_spec['trim-summary'] = autodoc.bool_option
    option_spec['trim-usage'] = autodoc.bool_option
    titles_allowed = True

    def add_directive_header(self, sig):
        return None


def trim_docstring_summary(app, what, name, obj, options, lines):
    """
    Trim the summary line from a docstring.

    If a docstring has a summary line followed by one or more blank
    lines, remove that summary and the subsequent blank lines. This is
    used to eliminate redundant summaries from generated output while
    retaining those lines in source as hints for editors, etc.
    """
    if not options.get('trim-summary'):
        return

    if len(lines) >= 3 and lines[0].strip() and not lines[1].strip():
        lines.pop(0)
        while not lines[0].strip():
            lines.pop(0)


def trim_usage_synopsis(app, what, name, obj, options, lines):
    """
    Remove the "usage: " line from a docstring.

    PEP 257 urges us to use docstrings that include full usage
    information; manpages by convention use a separate "SYNOPSIS"
    section. This callback trims the redundant "usage:" line while
    allowing the text to remain present in source code.

    If a line begins with "usage: ", that line and any following blank
    lines are removed from the docstring.
    """
    if not options.get('trim-usage'):
        return

    for i, line in enumerate(lines):
        if line.lower().startswith('usage: '):
            break
    else:
        return

    lines.pop(i)
    while len(lines) >= i and not lines[i].strip():
        lines.pop(i)


def setup(app):
    app.add_autodocumenter(FunctionDocstringDocumenter)
    autodoc.ModuleDocumenter.option_spec['trim-summary'] = autodoc.bool_option
    autodoc.ModuleDocumenter.option_spec['trim-usage'] = autodoc.bool_option
    app.connect('autodoc-process-docstring', trim_docstring_summary)
    app.connect('autodoc-process-docstring', trim_usage_synopsis)
