source: sasview/docs/sphinx-docs/build_sphinx.py @ 0e2d287

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalcmagnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 0e2d287 was 0e2d287, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

docs: lint

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