Skip to content

Commit

Permalink
add capability to create local html documentation from ecbuild macros. (
Browse files Browse the repository at this point in the history
#4)

* add capability to create local html documentation from ecbuild macros.

Change-Id: Ibd5012764eba17eba99ee03ca07974d31d811bd1

* minor cleanup

Change-Id: If243caa6e57c39667793f3c513f3d8ca3f67a35e

* address reviewer comments

Change-Id: I41831decb7b703d5ec68b4ba52f2cd2c72e07fca
  • Loading branch information
aerorahul authored Jun 17, 2019
1 parent b189b47 commit 335377a
Show file tree
Hide file tree
Showing 6 changed files with 352 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
CMakeLists.txt.user*
*.log
*.swp
build*/
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ configure_file( cmake/ecbuild_version.h.in ${CMAKE_BINARY_DIR}/ecbuild_version.h

ecbuild_add_option( FEATURE INSTALL
DEFAULT OFF
DESCRIPTION "Wether to install ecbuild files" )
DESCRIPTION "Whether to install ecbuild files" )
# contents

ecbuild_add_resources( TARGET ${PROJECT_NAME}_description_files
Expand Down
14 changes: 14 additions & 0 deletions cmake/contrib/FindSphinx.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
find_program(SPHINX_EXECUTABLE
NAMES sphinx-build
HINTS $ENV{SPHINX_DIR} ENV PATH
PATH_SUFFIXES bin
DOC "Sphinx documentation generator"
)

include(FindPackageHandleStandardArgs)

find_package_handle_standard_args(Sphinx DEFAULT_MSG
SPHINX_EXECUTABLE
)

mark_as_advanced(SPHINX_EXECUTABLE)
42 changes: 42 additions & 0 deletions doc/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
# nor does it submit to any jurisdiction.

find_package( PythonInterp )
find_package( Sphinx )

if( PYTHONINTERP_FOUND )

Expand All @@ -19,4 +20,45 @@ if( PYTHONINTERP_FOUND )
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
COMMENT "Uploading documentation" )

if( SPHINX_FOUND )

# configured documentation tools and intermediate build results
set(SPHINX_BUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/sphinx_build")

# Sphinx cache with pickled ReST documents
set(SPHINX_CACHE_DIR "${CMAKE_CURRENT_BINARY_DIR}/sphinx_doctrees")

# Sphinx source with pickled ReST documents
set(SPHINX_SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/sphinx_source")

# HTML output directory
set(SPHINX_HTML_DIR "${CMAKE_CURRENT_BINARY_DIR}/html")

add_custom_target( create_docs COMMENT "Creating Sphinx RST documentation" )
add_custom_command( TARGET create_docs POST_BUILD
COMMAND ${PYTHON_EXECUTABLE} create.py
--source ${SPHINX_SOURCE_DIR} ${ECBUILD_MODULE}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
COMMENT "Creating Sphinx RST documentation" )

configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/conf.py.in"
"${SPHINX_BUILD_DIR}/conf.py"
@ONLY)

add_custom_target(html_docs ALL
${SPHINX_EXECUTABLE}
-q
-b html
-c "${SPHINX_BUILD_DIR}"
-d "${SPHINX_CACHE_DIR}"
"${SPHINX_SOURCE_DIR}"
"${SPHINX_HTML_DIR}"
DEPENDS create_docs
COMMENT "Building ecBuild HTML documentation with Sphinx")

install( DIRECTORY ${SPHINX_HTML_DIR} DESTINATION ${INSTALL_DATA_DIR} )

endif()

endif()
179 changes: 179 additions & 0 deletions doc/conf.py.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
# ecBuild documentation configuration file, created by
# sphinx-quickstart of the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config

# -- 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 sys
# sys.path.insert(0, os.path.abspath('.'))


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

project = 'ecBuild'
copyright = '2011-, ECMWF'
author = 'ECMWF'

# The short X.Y version
version = '@ECBUILD_VERSION@'
# The full version, including alpha/beta/rc tags
#release = '1'


# -- 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 = []

# 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 master toctree document.
master_doc = 'index'

# 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

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

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


# -- 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 = 'default'

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

# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
html_sidebars = {
'**': [
'relations.html', # needs 'show_related': True theme option to display
'searchbox.html',
]
}


# -- Options for HTMLHelp output ---------------------------------------------

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


# -- 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, 'ecBuild.tex', 'ecBuild Documentation',
'ECMWF', 'manual'),
]


# -- 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, 'ecbuild', 'ecBuild Documentation',
[author], 1)
]


# -- 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, 'ecBuild', 'ecBuild Documentation',
author, 'ecBuild', 'CMake-based Build System from ECMWF.',
'Miscellaneous'),
]


# -- Options for Epub output -------------------------------------------------

# Bibliographic Dublin Core info.
epub_title = project

# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''

# A unique identification for the text.
#
# epub_uid = ''

# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
115 changes: 115 additions & 0 deletions doc/create.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
#!/usr/bin/env python

"""
Extract rst documentation for a given list of ecBuild macros for use with Sphinx.
"""

from __future__ import print_function
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from os import environ, path, makedirs


def writeRST(rst, directory):
"Write rST documentation to ``fname``.rst"

if not path.exists(directory):
makedirs(directory)

for key, value in rst.items():
fh = open('%s/%s.rst' % (directory, key), 'w')
fh.write(value)
fh.close()

return


def extract(fname):
"Extract rST documentation from CMake module ``fname``."
with open(fname) as f:
rst = False
lines = []
for line in f:
line = line.strip()
# Only consider comments
if not line.startswith('#'):
rst = False
continue
# Lines with the magic cooke '.rst:' start an rST block
if line.endswith('.rst:'):
rst = True
continue
# Only add lines in an rST block
if rst:
line = line.lstrip('#')
# Blank lines are syntactically relevant
lines.append(line[1:] if line else line)
return lines


def indexRST():

strings = []

strings.append('#####################\n')
strings.append('ecBuild Documentation\n')
strings.append('#####################\n')
strings.append('\n')
strings.append('.. toctree::\n')
strings.append('\t:maxdepth: 2\n')
strings.append('\n')
strings.append('\tmacros/index.rst\n')
strings.append('\n')
strings.append('##################\n')
strings.append('Indices and tables\n')
strings.append('##################\n')
strings.append('\n')
#strings.append('* :ref:`genindex`\n')
strings.append('* :ref:`search`\n')

return ''.join(strings)


def macrosRST(macros):

strings = []

strings.append('##############\n')
strings.append('ecBuild macros\n')
strings.append('##############\n')
strings.append('.. toctree::\n')
strings.append('\t:maxdepth: 1\n')
strings.append('\n')

for m in sorted(macros):
mname, _ = path.splitext(m)
strings.append('\t'+mname+'.rst\n')

return ''.join(strings)


def main():
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('--source', default='./_source',
help='Path to stage Sphinx .rst files')
parser.add_argument('macro', nargs='+',
help='list of paths to ecBuild macros')
args = parser.parse_args()

print('====== Start creating rst for Sphinx documentation ======')

rst = {}
for m in args.macro:
mname, _ = path.splitext(m)
mname = path.basename(mname)
rst[mname] = '\n'.join(extract(m))

writeRST(rst, path.join(args.source, 'macros'))

writeRST({'index': indexRST()}, args.source)
writeRST({'index': macrosRST(rst.keys())}, path.join(args.source, 'macros'))

print('====== Finished creating rst for Sphinx documentation ======')

if __name__ == '__main__':
main()

0 comments on commit 335377a

Please sign in to comment.