Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 768b87c

Browse files
committed
Fix how example files are added to the build. Saves about 1MB in html output.
svn path=/branches/v0_98_5_maint/; revision=6672
1 parent fdda0fd commit 768b87c

5 files changed

Lines changed: 196 additions & 8 deletions

File tree

doc/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
3030
extensions = ['mathmpl', 'math_symbol_table', 'sphinx.ext.autodoc',
3131
'only_directives', 'plot_directive', 'inheritance_diagram',
32-
'gen_gallery']
32+
'gen_gallery', 'gen_rst']
3333

3434
# Add any paths that contain templates here, relative to this directory.
3535
templates_path = ['_templates']

doc/make.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,12 @@ def examples():
3434

3535
def html():
3636
check_build()
37-
if not os.path.exists('examples/index.rst'):
38-
examples()
3937
shutil.copy('../lib/matplotlib/mpl-data/matplotlibrc', '_static/matplotlibrc')
40-
#figs()
4138
if small_docs:
4239
options = "-D plot_formats=\"['png']\""
4340
else:
4441
options = ''
45-
if os.system('sphinx-build %s -b html -d build/doctrees . build/html' % options):
42+
if os.system('sphinx-build %s -P -b html -d build/doctrees . build/html' % options):
4643
raise SystemExit("Building HTML failed.")
4744

4845
figures_dest_path = 'build/html/pyplots'

doc/sphinxext/gen_rst.py

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
"""
2+
generate the rst files for the examples by iterating over the pylab examples
3+
"""
4+
import os, glob
5+
6+
import os
7+
import re
8+
import sys
9+
fileList = []
10+
11+
def out_of_date(original, derived):
12+
"""
13+
Returns True if derivative is out-of-date wrt original,
14+
both of which are full file paths.
15+
16+
TODO: this check isn't adequate in some cases. Eg, if we discover
17+
a bug when building the examples, the original and derived will be
18+
unchanged but we still want to force a rebuild.
19+
"""
20+
return (not os.path.exists(derived) or
21+
os.stat(derived).st_mtime < os.stat(original).st_mtime)
22+
23+
noplot_regex = re.compile(r"#\s*-\*-\s*noplot\s*-\*-")
24+
25+
def generate_example_rst(app):
26+
rootdir = os.path.join(app.builder.srcdir, 'mpl_examples')
27+
exampledir = os.path.join(app.builder.srcdir, 'examples')
28+
if not os.path.exists(exampledir):
29+
os.makedirs(exampledir)
30+
31+
datad = {}
32+
for root, subFolders, files in os.walk(rootdir):
33+
for fname in files:
34+
if ( fname.startswith('.') or fname.startswith('#') or fname.startswith('_') or
35+
fname.find('.svn')>=0 or not fname.endswith('.py') ):
36+
continue
37+
38+
fullpath = os.path.join(root,fname)
39+
contents = file(fullpath).read()
40+
# indent
41+
relpath = os.path.split(root)[-1]
42+
datad.setdefault(relpath, []).append((fullpath, fname, contents))
43+
44+
subdirs = datad.keys()
45+
subdirs.sort()
46+
47+
fhindex = file(os.path.join(exampledir, 'index.rst'), 'w')
48+
fhindex.write("""\
49+
.. _examples-index:
50+
51+
####################
52+
Matplotlib Examples
53+
####################
54+
55+
.. htmlonly::
56+
57+
:Release: |version|
58+
:Date: |today|
59+
60+
.. toctree::
61+
:maxdepth: 2
62+
63+
""")
64+
65+
for subdir in subdirs:
66+
rstdir = os.path.join(exampledir, subdir)
67+
if not os.path.exists(rstdir):
68+
os.makedirs(rstdir)
69+
70+
outputdir = os.path.join(app.builder.outdir, 'examples')
71+
if not os.path.exists(outputdir):
72+
os.makedirs(outputdir)
73+
74+
outputdir = os.path.join(outputdir, subdir)
75+
if not os.path.exists(outputdir):
76+
os.makedirs(outputdir)
77+
78+
subdirIndexFile = os.path.join(rstdir, 'index.rst')
79+
fhsubdirIndex = file(subdirIndexFile, 'w')
80+
fhindex.write(' %s/index.rst\n\n'%subdir)
81+
82+
fhsubdirIndex.write("""\
83+
.. _%s-examples-index:
84+
85+
##############################################
86+
%s Examples
87+
##############################################
88+
89+
.. htmlonly::
90+
91+
:Release: |version|
92+
:Date: |today|
93+
94+
.. toctree::
95+
:maxdepth: 1
96+
97+
"""%(subdir, subdir))
98+
99+
print subdir
100+
101+
data = datad[subdir]
102+
data.sort()
103+
104+
for fullpath, fname, contents in data:
105+
basename, ext = os.path.splitext(fname)
106+
outputfile = os.path.join(outputdir, fname)
107+
#thumbfile = os.path.join(thumb_dir, '%s.png'%basename)
108+
#print ' static_dir=%s, basename=%s, fullpath=%s, fname=%s, thumb_dir=%s, thumbfile=%s'%(static_dir, basename, fullpath, fname, thumb_dir, thumbfile)
109+
110+
rstfile = '%s.rst'%basename
111+
outrstfile = os.path.join(rstdir, rstfile)
112+
113+
fhsubdirIndex.write(' %s\n'%rstfile)
114+
115+
if (not out_of_date(fullpath, outputfile) and
116+
not out_of_date(fullpath, outrstfile)):
117+
continue
118+
119+
print ' %s'%fname
120+
121+
fh = file(outrstfile, 'w')
122+
fh.write('.. _%s-%s:\n\n'%(subdir, basename))
123+
title = '%s example code: %s'%(subdir, fname)
124+
#title = '<img src=%s> %s example code: %s'%(thumbfile, subdir, fname)
125+
126+
127+
fh.write(title + '\n')
128+
fh.write('='*len(title) + '\n\n')
129+
130+
do_plot = (subdir in ('api',
131+
'pylab_examples',
132+
'units') and
133+
not noplot_regex.search(contents))
134+
135+
if do_plot:
136+
fh.write("\n\n.. plot:: %s\n\n::\n\n" % fullpath)
137+
else:
138+
fh.write("[`source code <%s>`_]\n\n::\n\n" % fname)
139+
fhstatic = file(outputfile, 'w')
140+
fhstatic.write(contents)
141+
fhstatic.close()
142+
143+
# indent the contents
144+
contents = '\n'.join([' %s'%row.rstrip() for row in contents.split('\n')])
145+
fh.write(contents)
146+
147+
fh.write('\n\nKeywords: python, matplotlib, pylab, example, codex (see :ref:`how-to-search-examples`)')
148+
fh.close()
149+
150+
fhsubdirIndex.close()
151+
152+
fhindex.close()
153+
154+
def setup(app):
155+
app.connect('builder-inited', generate_example_rst)

doc/sphinxext/plot_directive.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,41 @@
3434
import matplotlib.image as image
3535
from matplotlib import _pylab_helpers
3636

37+
if hasattr(os.path, 'relpath'):
38+
relpath = os.path.relpath
39+
else:
40+
def relpath(target, base=os.curdir):
41+
"""
42+
Return a relative path to the target from either the current dir or an optional base dir.
43+
Base can be a directory specified either as absolute or relative to current dir.
44+
"""
45+
46+
if not os.path.exists(target):
47+
raise OSError, 'Target does not exist: '+target
48+
49+
if not os.path.isdir(base):
50+
raise OSError, 'Base is not a directory or does not exist: '+base
51+
52+
base_list = (os.path.abspath(base)).split(os.sep)
53+
target_list = (os.path.abspath(target)).split(os.sep)
54+
55+
# On the windows platform the target may be on a completely different drive from the base.
56+
if os.name in ['nt','dos','os2'] and base_list[0] <> target_list[0]:
57+
raise OSError, 'Target is on a different drive to base. Target: '+target_list[0].upper()+', base: '+base_list[0].upper()
58+
59+
# Starting from the filepath root, work out how much of the filepath is
60+
# shared by base and target.
61+
for i in range(min(len(base_list), len(target_list))):
62+
if base_list[i] <> target_list[i]: break
63+
else:
64+
# If we broke out of the loop, i is pointing to the first differing path elements.
65+
# If we didn't break out of the loop, i is pointing to identical path elements.
66+
# Increment i so that in all cases it points to the first differing path elements.
67+
i+=1
68+
69+
rel_list = [os.pardir] * (len(base_list)-i) + target_list[i:]
70+
return os.path.join(*rel_list)
71+
3772
def write_char(s):
3873
sys.stdout.write(s)
3974
sys.stdout.flush()
@@ -186,6 +221,7 @@ def plot_directive(name, arguments, options, content, lineno,
186221
reference = directives.uri(arguments[0])
187222
basedir, fname = os.path.split(reference)
188223
basename, ext = os.path.splitext(fname)
224+
basedir = relpath(basedir, setup.app.builder.srcdir)
189225

190226
# Get the directory of the rst file, and determine the relative
191227
# path from the resulting html file to the plot_directive links

lib/matplotlib/pyplot.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1138,9 +1138,9 @@ def thetagrids(*args, **kwargs):
11381138
def plotting():
11391139
"""
11401140
Plotting commands
1141-
============ =================================================
1141+
=============== =========================================================
11421142
Command Description
1143-
========= =================================================
1143+
=============== =========================================================
11441144
axes Create a new axes
11451145
axis Set or return the current axis limits
11461146
bar make a bar chart
@@ -1193,7 +1193,7 @@ def plotting():
11931193
title add a title to the current axes
11941194
xlabel add an xlabel to the current axes
11951195
ylabel add a ylabel to the current axes
1196-
============ =================================================
1196+
=============== =========================================================
11971197
11981198
The following commands will set the default colormap accordingly:
11991199

0 commit comments

Comments
 (0)