Merge "add version, builddate and copyright in sidebar"
[opnfvdocs.git] / scripts / docs-build.sh
1 #!/bin/bash
2 # SPDX-license-identifier: Apache-2.0
3 ##############################################################################
4 # Copyright (c) 2016 NEC and others.
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
10
11 DOCS_DIR=${DOCS_DIR:-docs}
12 INDEX_RST=${INDEX_RST:-index.rst}
13 BUILD_DIR=${BUILD_DIR:-docs_build}
14 OUTPUT_DIR=${OUTPUT_DIR:-docs_output}
15 SRC_DIR=${SRC_DIR:-$BUILD_DIR/_src}
16 VENV_DIR=${VENV_DIR:-$BUILD_DIR/_venv}
17 OPNFVDOCS_DIR=${OPNFVDOCS_DIR:-$BUILD_DIR/_opnfvdocs}
18 GERRIT_COMMENT=${GERRIT_COMMENT:-}
19
20 get_title_script="
21 import os
22 from docutils import core, nodes
23
24 try:
25     with open('index.rst', 'r') as file:
26         data = file.read()
27     doctree = core.publish_doctree(data,
28         settings_overrides={'report_level': 5,
29                             'halt_level': 5})
30     if isinstance(doctree[0], nodes.title):
31         title = doctree[0]
32     else:
33         for c in doctree.children:
34             if isinstance(c, nodes.section):
35                 title = c[0]
36                 break
37     print title.astext()
38 except:
39     print 'None'"
40 revision="$(git rev-parse --short HEAD)"
41 rev_full="$(git rev-parse HEAD)"
42 version="$(git describe --abbrev=0 2> /dev/null || echo draft) ($revision)"
43 project="$(basename $(git rev-parse --show-toplevel))"
44 html_notes="    Revision: $rev_full\n    Build date: $(date -u +'%Y-%m-%d')"
45 opnfv_logo="$OPNFVDOCS_DIR/etc/opnfv-logo.png"
46 copyright="$(date +%Y), OPNFV"
47
48 function check_rst_doc() {
49     _src="$1"
50
51     # Note: This check may fail in many jobs for building project docs, since
52     #       the old sample has lines more than 120. We ignore failures on this
53     #       check right now, but these have to be fixed before OPNFV B release.
54     _out=$(doc8 --max-line-length 240 --ignore D000 "$_src") || {
55         _msg='Warning: rst validation (doc8) has failed, please fix the following error(s).'
56         _errs=$(echo "$_out" | sed -n -e "/^$_src/s/^/    /p")
57         echo
58         echo -e "$_msg\n$_errs"
59         echo
60         if [ -n "$GERRIT_COMMENT" ]; then
61             echo -e "$_msg\n$_errs" >> "$GERRIT_COMMENT"
62         fi
63     }
64 }
65
66 function add_html_notes() {
67     _src="$1"
68
69     find "$_src" -name '*.rst' | while read file
70     do
71         if grep -q -e ' _sha1_' "$file" ; then
72             # TODO: remove this, once old templates were removed from all repos.
73             echo
74             echo "Warn: '_sha1_' was found in [$file], use the latest document template."
75             echo "      See http://artifacts.opnfv.org/opnfvdocs/docs/how-to-use-docs ."
76             echo
77             sed -i "s/ _sha1_/ $git_sha1/g" "$file"
78         fi
79         sed -i -e "\$a\\\n..\n$html_notes" "$file"
80     done
81 }
82
83 function prepare_src_files() {
84     mkdir -p "$(dirname $SRC_DIR)"
85
86     if [ -e "$SRC_DIR" ]; then
87         rm -rf "$SRC_DIR"
88     fi
89     cp -r "$DOCS_DIR" "$SRC_DIR"
90     add_html_notes "$SRC_DIR"
91 }
92
93 function add_config() {
94     _conf="$1"
95     _param="$2"
96     _val="$3"
97
98     if ! grep -q -e "^$_param = " "$_conf" ; then
99         echo "Adding '$_param' into $_conf ..."
100         echo "$_param = $_val" >> "$_conf"
101     fi
102 }
103
104 # Note: User can customize config for specific document by creating 'conf.py'
105 #       in the taeget document dir (e.g. docs/abc/conf.py). This config file does
106 #       not need to cover all config parameter, as all missing parameter will be
107 #       automatically filled by this function.
108 function prepare_config() {
109     _src="$1"
110     _name="$2"
111     _conf="$_src/conf.py"
112
113     touch "$_conf"
114
115     # default params
116     # Note: If you want to add a new sphinx extention here, you may need python
117     #       package for it (e.g. python package 'sphinxcontrib-httpdomain' is
118     #       required by 'sphinxcontrib.httpdomain'). If you need such python
119     #       package, add the name of the python package into the requirement
120     #       list 'docs/etc/requirements.txt' .
121     add_config "$_conf" 'extensions' \
122     "['sphinxcontrib.httpdomain', 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon']"
123     add_config "$_conf" 'needs_sphinx' "'1.3'"
124     add_config "$_conf" 'numfig' "True"
125     add_config "$_conf" 'master_doc' "'index'"
126     add_config "$_conf" 'pygments_style' "'sphinx'"
127     add_config "$_conf" 'html_use_index' "False"
128     add_config "$_conf" 'html_last_updated_fmt' "'%b %d, %Y'"
129     add_config "$_conf" 'html_logo' "'opnfv-logo.png'"
130     add_config "$_conf" 'latex_domain_indices' "False"
131     add_config "$_conf" 'latex_logo' "'opnfv-logo.png'"
132     add_config "$_conf" 'html_sidebars' \
133                         "{'**': ['globaltoc.html',
134                                  '$(cd $OPNFVDOCS_DIR; pwd)/etc/pagemenu.html',
135                                  'searchbox.html']}"
136
137     # genarated params
138     title=$(cd $_src; python -c "$get_title_script")
139     latex_conf="[('index', '$_name.tex', \"$title\", 'OPNFV', 'manual'),]"
140     add_config "$_conf" 'latex_documents' "$latex_conf"
141     add_config "$_conf" 'release' "u'$version'"
142     add_config "$_conf" 'version' "u'$version'"
143     add_config "$_conf" 'project' "u'$project'"
144     add_config "$_conf" 'copyright' "u'$copyright'"
145     add_config "$_conf" 'rst_epilog' "u'$html_notes'"
146
147     echo "sphinx config to be used:"
148     echo
149     sed -e "s/^/    /" "$_conf"
150     echo
151 }
152
153 function is_top_dir() {
154     [[ "$1" == "$DOCS_DIR" ]]
155 }
156
157 function generate_name_for_top_dir() {
158     for suffix in '' '.top' '.all' '.master' '_' '__' '___'
159     do
160         _name="$(basename $DOCS_DIR)$suffix"
161         [[ -e "$DOCS_DIR/$_name" ]] && continue
162         echo "$_name"
163         return
164     done
165
166     echo "Error: cannot find name for top directory [$DOCS_DIR]"
167     exit 1
168 }
169
170 function generate_name() {
171     _dir=$1
172
173     if is_top_dir "$_dir" ; then
174         _name=$(generate_name_for_top_dir $DOCS_DIR)
175     else
176         _name="${_dir#$DOCS_DIR/}"
177     fi
178     # Replace '/' by '_'
179     echo "${_name////_}"
180 }
181
182
183 if [[ ! -d "$OPNFVDOCS_DIR" ]] ; then
184     echo "Error: $OPNFVDOCS_DIR dir not found."
185     echo "See http://artifacts.opnfv.org/opnfvdocs/docs/how-to-use-docs ."
186     exit 1
187 fi
188
189 if ! which virtualenv > /dev/null ; then
190     echo "Error: 'virtualenv' not found. Exec 'sudo pip install virtualenv' first."
191     exit 1
192 fi
193
194 # workaround for doc8 error in python2.6
195 if [[ $(python -V 2>&1) == Python\ 2.6.* ]] && [ -e /usr/bin/python2.7 ]; then
196     echo "creating venv with Python 2.7 instead of Python 2.6.x ..."
197     virtualenv "$VENV_DIR" --python=/usr/bin/python2.7
198 else
199     virtualenv "$VENV_DIR"
200 fi
201
202 source "$VENV_DIR/bin/activate"
203 pip install -r "$OPNFVDOCS_DIR/etc/requirements.txt"
204
205 check_rst_doc $DOCS_DIR
206
207 prepare_src_files
208
209 if [ -e "$DOCS_DIR/pre-hook.sh" ]; then
210     source "$DOCS_DIR/pre-hook.sh"
211 fi
212
213 find $DOCS_DIR -name $INDEX_RST -printf '%h\n' | while read dir
214 do
215     name=$(generate_name $dir)
216     if is_top_dir "$dir" ; then
217         src="$SRC_DIR"
218     else
219         src="$SRC_DIR/${dir#$DOCS_DIR/}"
220     fi
221     build="$BUILD_DIR/$name"
222     output="$OUTPUT_DIR/$name"
223
224     echo
225     echo "#################${dir//?/#}"
226     echo "Building DOCS in $dir"
227     echo "#################${dir//?/#}"
228     echo
229
230     prepare_config "$src" "$name"
231     cp -f $opnfv_logo "$src/opnfv-logo.png"
232
233     mkdir -p "$output"
234
235     sphinx-build -b html -t html -E "$src" "$output"
236
237     {
238         sphinx-build -b singlehtml -t singlehtml -E "$src" "${output}-single"
239     } || {
240         msg="Error: Single HTML creation for $dir has failed."
241         echo
242         echo "$msg"
243         echo
244         if [ -n "$GERRIT_COMMENT" ]; then
245             echo "$msg" >> "$GERRIT_COMMENT"
246         fi
247     }
248
249     # Note: PDF creation may fail in project doc builds.
250     #       We allow this build job to be marked as succeeded with
251     #       failure in PDF creation, but leave message to fix it.
252     #       Any failure has to be fixed before OPNFV B release.
253     {
254         sphinx-build -b latex -t pdf -E "$src" "$build" && \
255             make -C "$build" LATEXOPTS='--interaction=nonstopmode' all-pdf
256     } && {
257         mv "$build/$name.pdf" "$output"
258     } || {
259         msg="Error: PDF creation for $dir has failed, please fix source rst file(s)."
260         echo
261         echo "$msg"
262         echo
263         if [ -n "$GERRIT_COMMENT" ]; then
264             echo "$msg" >> "$GERRIT_COMMENT"
265         fi
266     }
267
268     # TODO: failures in ODT creation should be handled error and
269     #       cause 'exit 1' before OPNFV B release.
270     tex=$(find $build -name '*.tex' | head -1)
271     odt="${tex%.tex}.odt"
272     if [[ -e $tex ]] && which pandoc > /dev/null ; then
273         (
274             cd $(dirname $tex)
275             pandoc $(basename $tex) -o $(basename $odt)
276         ) && {
277             mv $odt $output/
278         }|| {
279             msg="Error: ODT creation for $dir has failed."
280             echo
281             echo "$msg"
282             echo
283         }
284     else
285         echo "Warn: tex file and/or 'pandoc' are not found, skip ODT creation."
286     fi
287
288     if is_top_dir "$dir" ; then
289         # NOTE: Having top level document (docs/index.rst) is not recommended.
290         #       It may cause conflicts with other docs (mostly with HTML
291         #       folders for contents in top level docs and other document
292         #       folders). But, let's try merge of those contents into the top
293         #       docs directory.
294         (
295             cd $output
296             find . -type d -print | xargs -I d mkdir -p ../d
297             find . -type f -print | xargs -I f mv -b f ../f
298         )
299         rm -rf "$output"
300     fi
301
302 done
303
304 deactivate