source: sasview/docs/sphinx-docs/build_sphinx.py @ 5dd7499

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 5dd7499 was 5dd7499, checked in by ajj, 8 years ago

Fixing sphinx build to assemble documents out of source tree to avoid pollution

  • Property mode set to 100755
File size: 16.4 KB
Line 
1#!/usr/bin/env python
2"""
3Functions for building sphinx docs.
4
5For more information on the invocation of sphinx see:
6http://sphinx-doc.org/invocation.html
7"""
8import subprocess
9import os
10import sys
11import fnmatch
12import shutil
13import imp
14from glob import glob
15
16from distutils.dir_util import copy_tree
17from distutils.util import get_platform
18from shutil import copy
19from os import listdir
20
21platform = '.%s-%s'%(get_platform(),sys.version[:3])
22
23CURRENT_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
24
25run = imp.load_source('run', os.path.join(CURRENT_SCRIPT_DIR, '..', '..', 'run.py'))
26run.prepare()
27
28SASVIEW_SRC = os.path.join(CURRENT_SCRIPT_DIR, "..", "..", "src")
29SASVIEW_BUILD = os.path.abspath(os.path.join(CURRENT_SCRIPT_DIR, "..", "..", "build", "lib"+platform))
30SASVIEW_DOCS = os.path.join(SASVIEW_BUILD, "doc")
31SASVIEW_TEST = os.path.join(SASVIEW_SRC, "..", "sasview", "test", "media")
32SASVIEW_TOC_SOURCE = os.path.join(CURRENT_SCRIPT_DIR, "source")
33
34# Need to slurp in the new sasmodels model definitions to replace the old model_functions.rst
35# We are currently here:
36#/sasview-local-trunk/docs/sphinx-docs/build_sphinx.py
37SASMODELS_SOURCE_PROLOG = os.path.join(CURRENT_SCRIPT_DIR, "..", "..", "..", "sasmodels", "doc")
38SASMODELS_SOURCE_SESANS = os.path.join(CURRENT_SCRIPT_DIR, "..", "..", "..", "sasmodels", "doc", "ref", "sesans")
39SASMODELS_SOURCE_MAGNETISM = os.path.join(CURRENT_SCRIPT_DIR, "..", "..", "..", "sasmodels", "doc", "ref", "magnetism")
40SASMODELS_SOURCE_MAGIMG = os.path.join(CURRENT_SCRIPT_DIR, "..", "..", "..", "sasmodels", "doc", "ref", "magnetism", "mag_img")
41SASMODELS_SOURCE_REF_MODELS = os.path.join(CURRENT_SCRIPT_DIR, "..", "..", "..", "sasmodels", "doc", "ref", "models")
42SASMODELS_SOURCE_MODELS = os.path.join(CURRENT_SCRIPT_DIR, "..", "..", "..", "sasmodels", "doc", "model")
43SASMODELS_SOURCE_IMG = os.path.join(CURRENT_SCRIPT_DIR, "..", "..", "..", "sasmodels", "doc", "model", "img")
44SASMODELS_SOURCE_AUTOIMG = os.path.join(CURRENT_SCRIPT_DIR, "..", "..", "..", "sasmodels", "doc", "_build", "html","_images")
45## Don't do assemble-in-place
46## Assemble the docs in a temporary folder
47SASMODELS_DEST_PROLOG = os.path.join(CURRENT_SCRIPT_DIR, "source-temp")
48SASMODELS_DEST_REF_MODELS = os.path.join(SASMODELS_DEST_PROLOG, "user")
49SASMODELS_DEST_MODELS = os.path.join(SASMODELS_DEST_PROLOG, "user", "models")
50SASMODELS_DEST_IMG = os.path.join(SASMODELS_DEST_PROLOG, "user", "model-imgs", "new-models")
51SASMODELS_DEST_MAGIMG = os.path.join(SASMODELS_DEST_PROLOG, "user", "mag_img")
52SASMODELS_DEST_BUILDIMG = os.path.join(SASMODELS_DEST_PROLOG, "user", "models", "img")
53
54#if os.path.exists(SASMODELS_SOURCE_PROLOG):
55#    print "Found models prolog folder at ", SASMODELS_SOURCE_PROLOG
56#if os.path.exists(SASMODELS_SOURCE_REF_MODELS):
57#    print "Found models ref folder at ", SASMODELS_SOURCE_REF_MODELS
58#if os.path.exists(SASMODELS_SOURCE_MODELS):
59#    print "Found models folder at ", SASMODELS_SOURCE_MODELS
60#if os.path.exists(SASMODELS_SOURCE_IMG):
61#    print "Found img folder at ", SASMODELS_SOURCE_IMG
62#if os.path.exists(SASMODELS_DEST_REF_MODELS):
63#    print "Found models ref folder at ", SASMODELS_DEST_REF_MODELS
64#if os.path.exists(SASMODELS_DEST_MODELS):
65#    print "Found models folder at ", SASMODELS_DEST_MODELS
66#if os.path.exists(SASMODELS_DEST_IMG):
67#    print "Found img folder at ", SASMODELS_DEST_IMG
68#sys.exit()
69
70SPHINX_BUILD = os.path.join(CURRENT_SCRIPT_DIR, "build")
71SPHINX_SOURCE = os.path.join(CURRENT_SCRIPT_DIR, "source-temp")
72SPHINX_SOURCE_API = os.path.join(SPHINX_SOURCE, "dev", "api")
73SPHINX_SOURCE_GUIFRAME = os.path.join(SPHINX_SOURCE, "user", "sasgui", "guiframe")
74SPHINX_SOURCE_MODELS = os.path.join(SPHINX_SOURCE, "user", "models")
75SPHINX_SOURCE_PERSPECTIVES = os.path.join(SPHINX_SOURCE, "user", "sasgui", "perspectives")
76SPHINX_SOURCE_TEST = os.path.join(SPHINX_SOURCE, "test")
77SPHINX_SOURCE_USER = os.path.join(SPHINX_SOURCE, "user")
78
79BUMPS_DOCS = os.path.join(CURRENT_SCRIPT_DIR, "..", "..", "..",
80                          "bumps", "doc", "guide")
81BUMPS_TARGET = os.path.join(SPHINX_SOURCE_PERSPECTIVES, "fitting")
82
83def inplace_change(filename, old_string, new_string):
84# Thanks to http://stackoverflow.com/questions/4128144/replace-string-within-file-contents
85        s=open(filename).read()
86        if old_string in s:
87                print 'Changing "{old_string}" to "{new_string}"'.format(**locals())
88                s=s.replace(old_string, new_string)
89                f=open(filename, 'w')
90                f.write(s)
91                f.flush()
92                f.close()
93        else:
94                print 'No occurences of "{old_string}" found.'.format(**locals())
95
96def _remove_dir(dir_path):
97    """Removes the given directory."""
98    if os.path.isdir(dir_path):
99        print "Removing \"%s\"... " % dir_path
100        shutil.rmtree(dir_path)
101
102def clean():
103    """
104    Clean the sphinx build directory.
105    """
106    print "=== Cleaning Sphinx Build ==="
107    _remove_dir(SASVIEW_DOCS)
108    _remove_dir(SPHINX_BUILD)
109    _remove_dir(SPHINX_SOURCE)
110    #_remove_dir(SPHINX_SOURCE_GUIFRAME)
111    #_remove_dir(SPHINX_SOURCE_MODELS)
112    #_remove_dir(SPHINX_SOURCE_PERSPECTIVES)
113    #_remove_dir(SPHINX_SOURCE_TEST)
114
115def setup_source_temp():
116    """
117    Copy the source toctrees to new folder for assembling the sphinx-docs
118    """
119    print "=== Copying Source toctrees ==="
120    if os.path.exists(SASVIEW_TOC_SOURCE):
121       print "Found docs folder at ", SASVIEW_TOC_SOURCE
122       shutil.copytree(SASVIEW_TOC_SOURCE, SPHINX_SOURCE)
123
124def retrieve_user_docs():
125    """
126    Copies across the contents of any media/ directories in src/, and puts them
127    in an appropriately named directory of docs/sphinx-docs/source/. For
128    example:
129
130        sas/../[MODULE]/media/dir/A.rst
131        sas/../[MODULE]/media/B.rst
132
133    gets copied to a new location:
134
135        docs/sphinx-docs/source/user/[MODULE]/dir/A.rst
136        docs/sphinx-docs/source/user/[MODULE]/B.rst
137
138    so that Sphinx may pick it up when generating the documentation.
139    """
140    print "=== Retrieve User Docs ==="
141
142    # Copy documentation files from their "source" to their "destination".
143    for root, dirnames, _ in os.walk(SASVIEW_SRC):
144        for dirname in fnmatch.filter(dirnames, 'media'):
145
146            docs = os.path.abspath(os.path.join(root, dirname))
147            print "Found docs folder at \"%s\"." % docs
148
149            dest_dir_part = os.path.dirname(os.path.relpath(docs, SASVIEW_SRC))
150            if os.sep in dest_dir_part:
151                dest_dir_part = dest_dir_part[dest_dir_part.index(os.sep) + 1:]
152            dest_dir = os.path.join(SPHINX_SOURCE, "user", dest_dir_part)
153
154            copy_tree(docs, dest_dir)
155
156    # Now pickup testdata_help.rst
157#    print os.path.abspath(SASVIEW_TEST)
158#    print os.path.abspath(SPHINX_SOURCE_TEST)
159    print "=== Including Test Data Docs ==="
160    if os.path.exists(SASVIEW_TEST):
161       print "Found docs folder at ", SASVIEW_TEST
162       shutil.copytree(SASVIEW_TEST, SPHINX_SOURCE_TEST)
163
164    print "=== And the Sasmodels Docs ==="
165    # Make sure we have the relevant images for the new sasmodels documentation
166    # First(!) we'll make a local reference copy for SasView (/new-models will be cleaned each build)
167    if os.path.exists(SASMODELS_SOURCE_IMG):
168        print "Found img  folder SASMODELS_SOURCE_IMG    at ", SASMODELS_SOURCE_IMG
169        if not os.path.exists(SASMODELS_DEST_IMG):
170            print "Missing docs folder SASMODELS_DEST_IMG at ", SASMODELS_DEST_IMG
171            os.makedirs(SASMODELS_DEST_IMG)
172            print "created SASMODELS_DEST_BUILDIMG at ", SASMODELS_DEST_BUILDIMG
173        else: print "Found img  folder SASMODELS_DEST_IMG      at ", SASMODELS_DEST_IMG
174        print "Copying sasmodels model image files..."
175        for files in os.listdir(SASMODELS_SOURCE_IMG):
176            fromhere=os.path.join(SASMODELS_SOURCE_IMG,files)
177            tohere=os.path.join(SASMODELS_DEST_IMG,files)
178            shutil.copy(fromhere,tohere)
179    else: print "cannot find SASMODELS_SOURCE_IMG", SASMODELS_SOURCE_IMG
180
181    if os.path.exists(SASMODELS_SOURCE_AUTOIMG):
182        print "Found img  folder SASMODELS_SOURCE_AUTOIMG    at ", SASMODELS_SOURCE_AUTOIMG
183        if not os.path.exists(SASMODELS_DEST_IMG):
184            print "Missing docs folder SASMODELS_DEST_IMG at ", SASMODELS_DEST_IMG
185            os.makedirs(SASMODELS_DEST_BUILDIMG)
186            print "created SASMODELS_DEST_BUILDIMG at ", SASMODELS_DEST_BUILDIMG
187        print "Copying sasmodels model auto-generated image files..."
188        for files in os.listdir(SASMODELS_SOURCE_AUTOIMG):
189            fromhere=os.path.join(SASMODELS_SOURCE_AUTOIMG,files)
190            tohere=os.path.join(SASMODELS_DEST_IMG,files)
191            shutil.copy(fromhere,tohere)
192        else: print "no source directorty",SASMODELS_SOURCE_AUTOIMG ,"was found"
193
194    # And the rst prolog with the unit substitutions
195    if os.path.exists(SASMODELS_SOURCE_PROLOG):
196        print "Found prolog folder SASMODELS_SOURCE_PROLOG at ", SASMODELS_SOURCE_PROLOG
197        if os.path.exists(SASMODELS_DEST_PROLOG):
198            print "Found docs folder SASMODELS_DEST_PROLOG   at ", SASMODELS_DEST_PROLOG
199            print "Copying sasmodels rst_prolog file..."
200            for files in os.listdir(SASMODELS_SOURCE_PROLOG):
201                if files.startswith("rst"):
202                    fromhere=os.path.join(SASMODELS_SOURCE_PROLOG,files)
203                    tohere=os.path.join(SASMODELS_DEST_PROLOG,files)
204                    shutil.copy(fromhere,tohere)
205
206    if os.path.exists(SASMODELS_SOURCE_SESANS):
207        print "Found docs folder SASMODELS_SOURCE_SESANS at ", SASMODELS_SOURCE_SESANS
208        if os.path.exists(SPHINX_SOURCE_USER):
209            print "Found docs folder SPHINX_SOURCE_USER      at ", SPHINX_SOURCE_USER
210            print "Copying sasmodels sesans files..."
211            for files in os.listdir(SASMODELS_SOURCE_SESANS):
212                if files.endswith(".rst"):
213                    fromhere=os.path.join(SASMODELS_SOURCE_SESANS,files)
214                    tohere=os.path.join(SPHINX_SOURCE_USER,files)
215                    shutil.copy(fromhere,tohere)
216
217    if os.path.exists(SASMODELS_SOURCE_MAGNETISM):
218        print "Found docs folder SASMODELS_SOURCE_MAGNETISM at ", SASMODELS_SOURCE_MAGNETISM
219        if os.path.exists(SASMODELS_DEST_REF_MODELS):
220            print "Found docs folder SASMODELS_DEST_REF_MODELS   at ", SASMODELS_DEST_REF_MODELS
221            print "Copying sasmodels model toctree files..."
222            for files in os.listdir(SASMODELS_SOURCE_MAGNETISM):
223                if files.endswith(".rst"):
224                    fromhere=os.path.join(SASMODELS_SOURCE_MAGNETISM,files)
225                    tohere=os.path.join(SASMODELS_DEST_REF_MODELS,files)
226                    shutil.copy(fromhere,tohere)
227
228    if os.path.exists(SASMODELS_SOURCE_MAGIMG):
229        print "Found img  folder SASMODELS_SOURCE_MAGIMG    at ", SASMODELS_SOURCE_MAGIMG
230        if not os.path.exists(SASMODELS_DEST_MAGIMG):
231            print "Missing docs folder SASMODELS_DEST_MAGIMG at ", SASMODELS_DEST_MAGIMG
232            os.makedirs(SASMODELS_DEST_MAGIMG)
233            print "created SASMODELS_DEST_MAGIMG at ", SASMODELS_DEST_MAGIMG
234        print "Copying sasmodels model auto-generated image files..."
235        for files in os.listdir(SASMODELS_SOURCE_MAGIMG):
236            fromhere=os.path.join(SASMODELS_SOURCE_MAGIMG,files)
237            tohere=os.path.join(SASMODELS_DEST_MAGIMG,files)
238            shutil.copy(fromhere,tohere)
239        else: print "no source directorty",SASMODELS_SOURCE_MAGIMG ,"was found"
240
241    if os.path.exists(SASMODELS_SOURCE_REF_MODELS):
242        print "Found docs folder SASMODELS_SOURCE_REF_MODELS at ", SASMODELS_SOURCE_REF_MODELS
243        if os.path.exists(SASMODELS_DEST_REF_MODELS):
244            print "Found docs folder SASMODELS_DEST_REF_MODELS   at ", SASMODELS_DEST_REF_MODELS
245            print "Copying sasmodels model toctree files..."
246            for files in os.listdir(SASMODELS_SOURCE_REF_MODELS):
247                if files.endswith(".rst"):
248                    fromhere=os.path.join(SASMODELS_SOURCE_REF_MODELS,files)
249                    tohere=os.path.join(SASMODELS_DEST_REF_MODELS,files)
250                    shutil.copy(fromhere,tohere)
251    # But need to change the path to the model docs in the tocs
252    for files in os.listdir(SASMODELS_DEST_REF_MODELS):
253#        print files
254        if files.startswith("shape"):
255            print "Changing toc paths in", files
256            inplace_change(os.path.join(SASMODELS_DEST_REF_MODELS,files), "../../model/", "models/")
257        if files.startswith("sphere"):
258            print "Changing toc paths in", files
259            inplace_change(os.path.join(SASMODELS_DEST_REF_MODELS,files), "../../model/", "models/")
260        if files.startswith("custom"):
261            print "Changing toc paths in", files
262            inplace_change(os.path.join(SASMODELS_DEST_REF_MODELS,files), "../../model/", "models/")
263        if files.startswith("structure"):
264            print "Changing toc paths in", files
265            inplace_change(os.path.join(SASMODELS_DEST_REF_MODELS,files), "../../model/", "models/")
266
267    if os.path.exists(SASMODELS_SOURCE_MODELS):
268        print "Found docs folder SASMODELS_SOURCE_MODELS at ", SASMODELS_SOURCE_MODELS
269        if os.path.exists(SASMODELS_DEST_MODELS):
270            print "Found docs folder SASMODELS_DEST_MODELS   at ", SASMODELS_DEST_MODELS
271            print "Copying sasmodels model files..."
272            for files in os.listdir(SASMODELS_SOURCE_MODELS):
273                if files.endswith(".rst"):
274                    fromhere=os.path.join(SASMODELS_SOURCE_MODELS,files)
275                    tohere=os.path.join(SASMODELS_DEST_MODELS,files)
276                    shutil.copy(fromhere,tohere)
277        else:
278            print "Missing docs folder SASMODELS_DEST_MODELS at ", SASMODELS_DEST_MODELS
279            os.makedirs(SASMODELS_DEST_MODELS)
280            if not os.path.exists(SASMODELS_DEST_BUILDIMG):
281                os.makedirs(SASMODELS_DEST_BUILDIMG)
282            print "Created docs folder SASMODELS_DEST_MODELS at ", SASMODELS_DEST_MODELS
283            print "Copying model files for build..."
284            for files in os.listdir(SASMODELS_SOURCE_MODELS):
285                if files.endswith(".rst"):
286                    fromhere=os.path.join(SASMODELS_SOURCE_MODELS,files)
287                    tohere=os.path.join(SASMODELS_DEST_MODELS,files)
288                    shutil.copy(fromhere,tohere)
289            # No choice but to do this because model files are all coded for images in /models/img
290            print "Copying image files for build..."
291            for files in os.listdir(SASMODELS_DEST_IMG):
292                fromhere=os.path.join(SASMODELS_DEST_IMG,files)
293                tohere=os.path.join(SASMODELS_DEST_BUILDIMG,files)
294                shutil.copy(fromhere,tohere)
295
296
297def retrieve_bumps_docs():
298    """
299    Copies select files from the bumps documentation into fitting perspective
300    """
301    if os.path.exists(BUMPS_DOCS):
302        print "=== Retrieve BUMPS Docs ==="
303        filenames = [os.path.join(BUMPS_DOCS, "optimizer.rst")]
304        filenames += glob(os.path.join(BUMPS_DOCS, "dream-*.png"))
305        filenames += glob(os.path.join(BUMPS_DOCS, "fit-*.png"))
306        for f in filenames:
307            print "Copying file", f
308            shutil.copy(f, BUMPS_TARGET)
309    else:
310        print """
311*** Error *** missing directory %s
312The documentation will not include the optimizer selection section.
313Checkout the bumps source tree and rebuild the docs.
314
315
316""" % BUMPS_DOCS
317
318def apidoc():
319    """
320    Runs sphinx-apidoc to generate .rst files from the docstrings in .py files
321    in the SasView build directory.
322    """
323    print "=== Generate API Rest Files ==="
324
325    # Clean directory before generating a new version.
326    _remove_dir(SPHINX_SOURCE_API)
327
328    subprocess.call(["sphinx-apidoc",
329                     "-o", SPHINX_SOURCE_API, # Output dir.
330                     "-d", "8", # Max depth of TOC.
331                     SASVIEW_BUILD])
332
333def build():
334    """
335    Runs sphinx-build.  Reads in all .rst files and spits out the final html.
336    """
337    print "=== Build HTML Docs from Rest Files ==="
338    subprocess.call(["sphinx-build",
339                     "-b", "html", # Builder name. TODO: accept as arg to setup.py.
340                     "-d", os.path.join(SPHINX_BUILD, "doctrees"),
341                     SPHINX_SOURCE,
342                     os.path.join(SPHINX_BUILD, "html")])
343
344    print "=== Copy HTML Docs to Build Directory ==="
345    html = os.path.join(SPHINX_BUILD, "html")
346    copy_tree(html, SASVIEW_DOCS)
347
348def rebuild():
349    clean()
350    setup_source_temp()
351    retrieve_user_docs()
352    retrieve_bumps_docs()
353    apidoc()
354    build()
355
356    print "=== Done ==="
357
358if __name__ == "__main__":
359    rebuild()
Note: See TracBrowser for help on using the repository browser.