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