# -*- coding: utf-8 -*-
#
# AllegroGraph Python client documentation build configuration file, created by
# sphinx-quickstart on Wed Nov 16 21:03:22 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

# 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 re
import sys
from datetime import datetime

on_rtd = os.environ.get('READTHEDOCS') == 'True'

# RTD doesn't allow C extensions, so we have to mock pycurl.
# But we only do this on RTD, since running the tutorial
# still requires an actual HTTP client.
if on_rtd:
    # RTD will use Python > 3.3, so no need to add a dependency
    from unittest.mock import MagicMock
    class Mock(MagicMock):
        @classmethod
        def __getattr__(cls, name):
            return MagicMock()
    sys.modules.update((('pycurl', Mock()),))

# Don't ask.
if sys.version_info <= (3,0):
    reload(sys)
    sys.setdefaultencoding('UTF-8')

# Local extensions
sys.path.insert(0, os.path.abspath('lib'))

# Source code
sys.path.insert(0, os.path.abspath('../../src'))

# Support code for doctests
sys.path.insert(0, os.path.abspath('tutorial'))

# We need this to get the version number
import franz

# We also need to ensure that other packages are imported 
# in the right order
import imports

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

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# 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.ifconfig',
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'sphinx.ext.doctest',
    'sphinx.ext.extlinks',
    'sphinx.ext.intersphinx',
    'sphinx.ext.todo',
    'sphinx.ext.mathjax',
    'sphinxcontrib.jupyter',
    'hacks'
]

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

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The encoding of source files.
#
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'AllegroGraph Python client'
copyright = u'%d, Franz Inc.' % datetime.now().year
author = u'Franz Inc.'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version (strip rc and post tags).
version = re.match(r'(?:\d+)(?:\.\d+)*', franz.__version__).group()
# The full version, including alpha/beta/rc tags.
release = franz.__version__

# 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 = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = []

# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#
# add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False

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


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

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

# Use the RTD theme when building on RTD
if on_rtd:
    html_theme = 'default'
else:
    # Allow override with an env var to make testing themes easier.
    html_theme = os.environ.get('theme', 'alabaster')

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []

# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#
# html_title = u'AllegroGraph Python client v6.1.4'

# A shorter title for the navigation bar.  Default is the same as html_title.
#
# html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
html_logo = '_static/logo.png'

# The name of an image file (relative to this directory) to use as a favicon of
# the docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
html_favicon = '_static/favicon.ico'

# 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']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []

# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#
# From http://alabaster.readthedocs.io/en/latest/installation.html
html_sidebars = {
    '**': [
        'about.html',
        'navigation.html',
        'relations.html',
        'searchbox.html',
        'donate.html',
    ]
}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}

# If false, no module index is generated.
#
# html_domain_indices = True

# If false, no index is generated.
#
# html_use_index = True

# If true, the index is split into individual pages for each letter.
#
# html_split_index = False

# If true, links to the reST sources are added to the pages.
#
# html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#
# html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None

# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
#   'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
#   'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'

# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}

# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'

# Output file base name for HTML help builder.
htmlhelp_basename = 'AllegroGraphPythonclientdoc'

# Alabaster theme settings
html_theme_options = {
    'show_related': True,
    'github_button': True,
    'github_user': 'franzinc',
    'github_repo': 'agraph-python',
}

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
     # The paper size ('letterpaper' or 'a4paper').
     #
     # 'papersize': 'letterpaper',

     # The font size ('10pt', '11pt' or '12pt').
     #
     # 'pointsize': '10pt',

     # Additional stuff for the LaTeX preamble.
     #
     # 'preamble': '',

     # Latex figure (float) alignment
     #
     # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, 'AllegroGraphPythonclient.tex', u'AllegroGraph Python client Documentation',
     u'Franz Inc.', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#
# latex_use_parts = False

# If true, show page references after internal links.
#
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
#
# latex_show_urls = False

# Documents to append as an appendix to all manuals.
#
# latex_appendices = []

# It false, will not define \strong, \code, 	itleref, \crossref ... but only
# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
# packages.
#
# latex_keep_old_macro_names = True

# If false, no module index is generated.
#
# latex_domain_indices = True


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

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'allegrographpythonclient', u'AllegroGraph Python client Documentation',
     [author], 1)
]

# If true, show URL addresses after external links.
#
# man_show_urls = False


# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (master_doc, 'AllegroGraphPythonclient', u'AllegroGraph Python client Documentation',
     author, 'AllegroGraphPythonclient', 'One line description of project.',
     'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#
# texinfo_appendices = []

# If false, no module index is generated.
#
# texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False


# Intersphinx (we use static inv files, since Sphinx often
# hangs while retrieving files from the internet).
intersphinx_mapping = {
    'python': ('https://docs.python.org/2.7', 'python-2.7.inv'),
    'python-future': ('http://python-future.org/', 'future.inv')
}
# Simplify external links.
extlinks = {'docs': ('https://franz.com/agraph/support/documentation/current/%s',
                     'AllegroGraph documentation: ')}

# --------------------------------------------
# sphinxcontrib-jupyter Configuration Settings
# --------------------------------------------

# Conversion Mode Settings
# If "all", convert codes and texts into jupyter notebook
# If "code", convert code-blocks only
jupyter_conversion_mode = "all"

jupyter_write_metadata = True

# Location for _static folder
jupyter_static_file_path = ["_static"]

# Configure Jupyter Kernels
jupyter_kernels = {
    "python_rdf": {
        "kernelspec": {
            "display_name": "Python",
            "language": "python3",
            "name": "python3"
            },
        "file_extension": ".py",
    },
}

# Configure Jupyter headers
jupyter_headers = {
    "python_rdf": [
    ],
}

# This must be set, yet seems to be ignored...
jupyter_welcome_block = "jupyter.welcome.block"

# This method must be monkey-patched, otherwise it
# raises an exception and causes the build to fail.
# The code below was copied from sphinxcontrib-jupyter
# and amended.
def depart_list_item(self, node):
    # self.first_line_in_list_item = False

    list_item_start = self.list_item_starts.pop()
    indent = self.indent_char * self.indents[-1]
    br_removed_flag = False

    ###############################################################################
    # CHANGED LINE: The build crashes here without the added checks
    ###############################################################################
    if self.markdown_lines and self.markdown_lines[-1] and self.markdown_lines[-1][-1] == "\n":
        br_removed_flag = True
        self.markdown_lines[-1] = self.markdown_lines[-1][:-1]

    for i in range(list_item_start, len(self.markdown_lines)):
        self.markdown_lines[i] = self.markdown_lines[i].replace(
            "\n", "\n{}".format(indent))

    # add breakline
    if br_removed_flag:
        self.markdown_lines.append("\n")

# Monkey-patch the method defined above.
from sphinxcontrib.jupyter.writers.translate_all import JupyterTranslator
JupyterTranslator.depart_list_item = depart_list_item

# autodoc config

# Do not taker class documentation from the init method.
autoclass_content = 'class'

from sphinx.ext.apidoc import main as apidoc_main

# Text prepended to each document
rst_prolog = """
.. highlight:: python_rdf

.. currentmodule:: franz.openrdf.repository.repositoryconnection.RepositoryConnection
"""

# Text included at the end of each document.
# Note: 'absolute' paths are actually relative to the project directory
#       regardless of the location of the source file in which the include
#       directive appears.
rst_epilog = """
.. include:: /substs.inc
.. include:: /links.inc
.. include:: /images.inc
"""

# Doctest common setup/teardown for all groups
# Note that this code is not displayed anywhere, so it is only suitable for
# things like setup specific to our hosts or boring cleanup that we do not
# want the users to see.

doctest_global_setup="""
# Py2/3 compatibility. We actually display this line in the docs, but we need 
# to repeat it here so it is shared by all documents.
from __future__ import print_function

# Definitions used in multiple tests. The code must be included in the 
# appropriate part of the tutorial, but we need the definitions to be in 
# a global setup block to make them visible in all documents.
""" + open('tutorial/doctest_setup.py').read()

doctest_global_cleanup="""
# Not all examples have to create conn...
# Note that multiple calls to close() are safe.
if 'conn' in vars() and conn is not None:
    conn.close()
"""

import doctest
doctest_default_flags = doctest.DONT_ACCEPT_TRUE_FOR_1 | doctest.ELLIPSIS | doctest.IGNORE_EXCEPTION_DETAIL | doctest.NORMALIZE_WHITESPACE

def get_ag_version():
    # Return the server version as a tuple.
    from franz.openrdf.sail.allegrographserver import AllegroGraphServer

    if 'AGRAPH_VERSION' in os.environ:
        return tuple(int(x) for x in os.environ['AGRAPH_VERSION'].split('.'))
    
    if not any(map(os.environ.get, ('AGRAPH_HOST', 'AGRAPH_PORT'))):
        # We need to choose a version anyway...
        return (6, 3, 1)

    host = os.environ.get('AGRAPH_HOST', '127.0.0.1')
    port = os.environ.get('AGRAPH_PORT', '10035')
    user = os.environ.get('AGRAPH_USER', 'test')
    password = os.environ.get('AGRAPH_PASSWORD', '<PASSWORD>')
    server = AllegroGraphServer(host=host, port=port,
                                user=user, password=password)
    return tuple(int(x) for x in server.version.split('.'))

ag_version = get_ag_version()

def setup(app):
    # Add custom CSS
    app.add_stylesheet('custom.css')
    # Make the version number available to ifconfig
    app.add_config_value('ag_version', ag_version, 'env')
    # Do not generate apidocs for these:
    exclude = ['franz/miniclient', 'franz/openrdf/tests', 
               # These are re-exported in franz.openrdf.model
               'franz/openrdf/model/literal.py', 
               'franz/openrdf/model/statement.py', 
               'franz/openrdf/model/value.py', 
               'franz/openrdf/model/valuefactory.py',
               # More reexported stuff
               'franz/openrdf/vocabulary/owl.py',
               'franz/openrdf/vocabulary/rdf.py',
               'franz/openrdf/vocabulary/rdfs.py',
               'franz/openrdf/vocabulary/xmlschema.py',]
    abs_exclude = [os.path.abspath(os.path.join('../src', path)) 
                   for path in exclude]
    # Generate apidocs
    # Options:
    #  -f = overwrite old files
    #  -o ... = output directory
    # ../src = path to the sources
    # rest = exclusion patterns
    apidoc_main(['-f', '-o', os.path.abspath('src/_gen'), 
                 os.path.abspath('../src')] + abs_exclude)

# -*- coding: utf-8 -*-
#
# AllegroGraph Python client documentation build configuration file, created by
# sphinx-quickstart on Wed Nov 16 21:03:22 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

# 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 re
import sys
from datetime import datetime

on_rtd = os.environ.get('READTHEDOCS') == 'True'

# RTD doesn't allow C extensions, so we have to mock pycurl.
# But we only do this on RTD, since running the tutorial
# still requires an actual HTTP client.
if on_rtd:
    # RTD will use Python > 3.3, so no need to add a dependency
    from unittest.mock import MagicMock
    class Mock(MagicMock):
        @classmethod
        def __getattr__(cls, name):
            return MagicMock()
    sys.modules.update((('pycurl', Mock()),))

# Don't ask.
if sys.version_info <= (3,0):
    reload(sys)
    sys.setdefaultencoding('UTF-8')

# Local extensions
sys.path.insert(0, os.path.abspath('lib'))

# Source code
sys.path.insert(0, os.path.abspath('../../src'))

# Support code for doctests
sys.path.insert(0, os.path.abspath('tutorial'))

# We need this to get the version number
import franz

# We also need to ensure that other packages are imported 
# in the right order
import imports

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

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# 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.ifconfig',
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'sphinx.ext.doctest',
    'sphinx.ext.extlinks',
    'sphinx.ext.intersphinx',
    'sphinx.ext.todo',
    'sphinx.ext.mathjax',
    'sphinxcontrib.jupyter',
    'hacks'
]

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

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The encoding of source files.
#
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'AllegroGraph Python client'
copyright = u'%d, Franz Inc.' % datetime.now().year
author = u'Franz Inc.'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version (strip rc and post tags).
version = re.match(r'(?:\d+)(?:\.\d+)*', franz.__version__).group()
# The full version, including alpha/beta/rc tags.
release = franz.__version__

# 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 = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = []

# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#
# add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False

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


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

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

# Use the RTD theme when building on RTD
if on_rtd:
    html_theme = 'default'
else:
    # Allow override with an env var to make testing themes easier.
    html_theme = os.environ.get('theme', 'alabaster')

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []

# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#
# html_title = u'AllegroGraph Python client v6.1.4'

# A shorter title for the navigation bar.  Default is the same as html_title.
#
# html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
html_logo = '_static/logo.png'

# The name of an image file (relative to this directory) to use as a favicon of
# the docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
html_favicon = '_static/favicon.ico'

# 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']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []

# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#
# From http://alabaster.readthedocs.io/en/latest/installation.html
html_sidebars = {
    '**': [
        'about.html',
        'navigation.html',
        'relations.html',
        'searchbox.html',
        'donate.html',
    ]
}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}

# If false, no module index is generated.
#
# html_domain_indices = True

# If false, no index is generated.
#
# html_use_index = True

# If true, the index is split into individual pages for each letter.
#
# html_split_index = False

# If true, links to the reST sources are added to the pages.
#
# html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#
# html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None

# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
#   'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
#   'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'

# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}

# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'

# Output file base name for HTML help builder.
htmlhelp_basename = 'AllegroGraphPythonclientdoc'

# Alabaster theme settings
html_theme_options = {
    'show_related': True,
    'github_button': True,
    'github_user': 'franzinc',
    'github_repo': 'agraph-python',
}

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
     # The paper size ('letterpaper' or 'a4paper').
     #
     # 'papersize': 'letterpaper',

     # The font size ('10pt', '11pt' or '12pt').
     #
     # 'pointsize': '10pt',

     # Additional stuff for the LaTeX preamble.
     #
     # 'preamble': '',

     # Latex figure (float) alignment
     #
     # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, 'AllegroGraphPythonclient.tex', u'AllegroGraph Python client Documentation',
     u'Franz Inc.', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#
# latex_use_parts = False

# If true, show page references after internal links.
#
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
#
# latex_show_urls = False

# Documents to append as an appendix to all manuals.
#
# latex_appendices = []

# It false, will not define \strong, \code, 	itleref, \crossref ... but only
# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
# packages.
#
# latex_keep_old_macro_names = True

# If false, no module index is generated.
#
# latex_domain_indices = True


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

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'allegrographpythonclient', u'AllegroGraph Python client Documentation',
     [author], 1)
]

# If true, show URL addresses after external links.
#
# man_show_urls = False


# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (master_doc, 'AllegroGraphPythonclient', u'AllegroGraph Python client Documentation',
     author, 'AllegroGraphPythonclient', 'One line description of project.',
     'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#
# texinfo_appendices = []

# If false, no module index is generated.
#
# texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False


# Intersphinx (we use static inv files, since Sphinx often
# hangs while retrieving files from the internet).
intersphinx_mapping = {
    'python': ('https://docs.python.org/2.7', 'python-2.7.inv'),
    'python-future': ('http://python-future.org/', 'future.inv')
}
# Simplify external links.
extlinks = {'docs': ('https://franz.com/agraph/support/documentation/current/%s',
                     'AllegroGraph documentation: ')}

# --------------------------------------------
# sphinxcontrib-jupyter Configuration Settings
# --------------------------------------------

# Conversion Mode Settings
# If "all", convert codes and texts into jupyter notebook
# If "code", convert code-blocks only
jupyter_conversion_mode = "all"

jupyter_write_metadata = True

# Location for _static folder
jupyter_static_file_path = ["_static"]

# Configure Jupyter Kernels
jupyter_kernels = {
    "python_rdf": {
        "kernelspec": {
            "display_name": "Python",
            "language": "python3",
            "name": "python3"
            },
        "file_extension": ".py",
    },
}

# Configure Jupyter headers
jupyter_headers = {
    "python_rdf": [
    ],
}

# This must be set, yet seems to be ignored...
jupyter_welcome_block = "jupyter.welcome.block"

# This method must be monkey-patched, otherwise it
# raises an exception and causes the build to fail.
# The code below was copied from sphinxcontrib-jupyter
# and amended.
def depart_list_item(self, node):
    # self.first_line_in_list_item = False

    list_item_start = self.list_item_starts.pop()
    indent = self.indent_char * self.indents[-1]
    br_removed_flag = False

    ###############################################################################
    # CHANGED LINE: The build crashes here without the added checks
    ###############################################################################
    if self.markdown_lines and self.markdown_lines[-1] and self.markdown_lines[-1][-1] == "\n":
        br_removed_flag = True
        self.markdown_lines[-1] = self.markdown_lines[-1][:-1]

    for i in range(list_item_start, len(self.markdown_lines)):
        self.markdown_lines[i] = self.markdown_lines[i].replace(
            "\n", "\n{}".format(indent))

    # add breakline
    if br_removed_flag:
        self.markdown_lines.append("\n")

# Monkey-patch the method defined above.
from sphinxcontrib.jupyter.writers.translate_all import JupyterTranslator
JupyterTranslator.depart_list_item = depart_list_item

# autodoc config

# Do not taker class documentation from the init method.
autoclass_content = 'class'

from sphinx.ext.apidoc import main as apidoc_main

# Text prepended to each document
rst_prolog = """
.. highlight:: python_rdf

.. currentmodule:: franz.openrdf.repository.repositoryconnection.RepositoryConnection
"""

# Text included at the end of each document.
# Note: 'absolute' paths are actually relative to the project directory
#       regardless of the location of the source file in which the include
#       directive appears.
rst_epilog = """
.. include:: /substs.inc
.. include:: /links.inc
.. include:: /images.inc
"""

# Doctest common setup/teardown for all groups
# Note that this code is not displayed anywhere, so it is only suitable for
# things like setup specific to our hosts or boring cleanup that we do not
# want the users to see.

doctest_global_setup="""
# Py2/3 compatibility. We actually display this line in the docs, but we need 
# to repeat it here so it is shared by all documents.
from __future__ import print_function

# Definitions used in multiple tests. The code must be included in the 
# appropriate part of the tutorial, but we need the definitions to be in 
# a global setup block to make them visible in all documents.
""" + open('tutorial/doctest_setup.py').read()

doctest_global_cleanup="""
# Not all examples have to create conn...
# Note that multiple calls to close() are safe.
if 'conn' in vars() and conn is not None:
    conn.close()
"""

import doctest
doctest_default_flags = doctest.DONT_ACCEPT_TRUE_FOR_1 | doctest.ELLIPSIS | doctest.IGNORE_EXCEPTION_DETAIL | doctest.NORMALIZE_WHITESPACE

def get_ag_version():
    # Return the server version as a tuple.
    from franz.openrdf.sail.allegrographserver import AllegroGraphServer

    if 'AGRAPH_VERSION' in os.environ:
        return tuple(int(x) for x in os.environ['AGRAPH_VERSION'].split('.'))
    
    if not any(map(os.environ.get, ('AGRAPH_HOST', 'AGRAPH_PORT'))):
        # We need to choose a version anyway...
        return (6, 3, 1)

    host = os.environ.get('AGRAPH_HOST', '127.0.0.1')
    port = os.environ.get('AGRAPH_PORT', '10035')
    user = os.environ.get('AGRAPH_USER', 'test')
    password = os.environ.get('AGRAPH_PASSWORD', '<PASSWORD>')
    server = AllegroGraphServer(host=host, port=port,
                                user=user, password=password)
    return tuple(int(x) for x in server.version.split('.'))

ag_version = get_ag_version()

def setup(app):
    # Add custom CSS
    app.add_stylesheet('custom.css')
    # Make the version number available to ifconfig
    app.add_config_value('ag_version', ag_version, 'env')
    # Do not generate apidocs for these:
    exclude = ['franz/miniclient', 'franz/openrdf/tests', 
               # These are re-exported in franz.openrdf.model
               'franz/openrdf/model/literal.py', 
               'franz/openrdf/model/statement.py', 
               'franz/openrdf/model/value.py', 
               'franz/openrdf/model/valuefactory.py',
               # More reexported stuff
               'franz/openrdf/vocabulary/owl.py',
               'franz/openrdf/vocabulary/rdf.py',
               'franz/openrdf/vocabulary/rdfs.py',
               'franz/openrdf/vocabulary/xmlschema.py',]
    abs_exclude = [os.path.abspath(os.path.join('../src', path)) 
                   for path in exclude]
    # Generate apidocs
    # Options:
    #  -f = overwrite old files
    #  -o ... = output directory
    # ../src = path to the sources
    # rest = exclusion patterns
    apidoc_main(['-f', '-o', os.path.abspath('src/_gen'), 
                 os.path.abspath('../src')] + abs_exclude)

# -*- coding: utf-8 -*- # # AllegroGraph Python client documentation build configuration file, created by # sphinx-quickstart on Wed Nov 16 21:03:22 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # 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. # # RTD doesn't allow C extensions, so we have to mock pycurl. # But we only do this on RTD, since running the tutorial # still requires an actual HTTP client. # RTD will use Python > 3.3, so no need to add a dependency # Don't ask. # Local extensions # Source code # Support code for doctests # We need this to get the version number # We also need to ensure that other packages are imported # in the right order # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. # Add any paths that contain templates here, relative to this directory. # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] # The encoding of source files. # # source_encoding = 'utf-8-sig' # The master toctree document. # General information about the project. # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version (strip rc and post tags). # The full version, including alpha/beta/rc tags. # 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. # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # # today = '' # # Else, today_fmt is used as the format for a strftime call. # # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path # The reST default role (used for this markup: `text`) to use for all # documents. # # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # # show_authors = False # The name of the Pygments (syntax highlighting) style to use. # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages.  See the documentation for # a list of builtin themes. # Use the RTD theme when building on RTD # Allow override with an env var to make testing themes easier. # Theme options are theme-specific and customize the look and feel of a theme # further.  For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. # "<project> v<release> documentation" by default. # # html_title = u'AllegroGraph Python client v6.1.4' # A shorter title for the navigation bar.  Default is the same as html_title. # # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # # The name of an image file (relative to this directory) to use as a favicon of # the docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # # 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". # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # # html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. # # html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # # From http://alabaster.readthedocs.io/en/latest/installation.html # Additional templates that should be rendered to pages, maps page names to # template names. # # html_additional_pages = {} # If false, no module index is generated. # # html_domain_indices = True # If false, no index is generated. # # html_use_index = True # If true, the index is split into individual pages for each letter. # # html_split_index = False # If true, links to the reST sources are added to the pages. # # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it.  The value of this option must be the # base URL from which the finished HTML is served. # # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: #   'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' #   'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' # # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. # # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. # Alabaster theme settings # -- Options for LaTeX output --------------------------------------------- # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, #  author, documentclass [howto, manual, or own class]). # The name of an image file (relative to this directory) to place at the top of # the title page. # # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # # latex_use_parts = False # If true, show page references after internal links. # # latex_show_pagerefs = False # If true, show URL addresses after external links. # # latex_show_urls = False # Documents to append as an appendix to all manuals. # # latex_appendices = [] # It false, will not define \strong, \code, 	itleref, \crossref ... but only # \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added # packages. # # latex_keep_old_macro_names = True # If false, no module index is generated. # # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). # If true, show URL addresses after external links. # # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, #  dir menu entry, description, category) # Documents to append as an appendix to all manuals. # # texinfo_appendices = [] # If false, no module index is generated. # # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # # texinfo_no_detailmenu = False # Intersphinx (we use static inv files, since Sphinx often # hangs while retrieving files from the internet). # Simplify external links. # -------------------------------------------- # sphinxcontrib-jupyter Configuration Settings # -------------------------------------------- # Conversion Mode Settings # If "all", convert codes and texts into jupyter notebook # If "code", convert code-blocks only # Location for _static folder # Configure Jupyter Kernels # Configure Jupyter headers # This must be set, yet seems to be ignored... # This method must be monkey-patched, otherwise it # raises an exception and causes the build to fail. # The code below was copied from sphinxcontrib-jupyter # and amended. # self.first_line_in_list_item = False ############################################################################### # CHANGED LINE: The build crashes here without the added checks ############################################################################### # add breakline # Monkey-patch the method defined above. # autodoc config # Do not taker class documentation from the init method. # Text prepended to each document .. highlight:: python_rdf  .. currentmodule:: franz.openrdf.repository.repositoryconnection.RepositoryConnection # Text included at the end of each document. # Note: 'absolute' paths are actually relative to the project directory #       regardless of the location of the source file in which the include #       directive appears. .. include:: /substs.inc .. include:: /links.inc .. include:: /images.inc # Doctest common setup/teardown for all groups # Note that this code is not displayed anywhere, so it is only suitable for # things like setup specific to our hosts or boring cleanup that we do not # want the users to see. # Py2/3 compatibility. We actually display this line in the docs, but we need  # to repeat it here so it is shared by all documents. from __future__ import print_function  # Definitions used in multiple tests. The code must be included in the  # appropriate part of the tutorial, but we need the definitions to be in  # a global setup block to make them visible in all documents. # Not all examples have to create conn... # Note that multiple calls to close() are safe. if 'conn' in vars() and conn is not None:     conn.close() # Return the server version as a tuple. # We need to choose a version anyway... # Add custom CSS # Make the version number available to ifconfig # Do not generate apidocs for these: # These are re-exported in franz.openrdf.model # More reexported stuff # Generate apidocs # Options: #  -f = overwrite old files #  -o ... = output directory # ../src = path to the sources # rest = exclusion patterns