source: sasview/docs/sphinx-docs/build_sphinx.py @ f4d571b

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.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since f4d571b was f4d571b, checked in by ajj, 7 years ago

Fixing print statements

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