Add a PyMOL builder to SCons and generalize PYMOL_PATH setup.
[thesis.git] / site_cons / site_tools / gnuplot.py
1 import os.path
2 import re
3 import SCons.Action
4 import SCons.Scanner
5 import SCons.Script
6 import SCons.Util
7 import doctest
8
9 quoted_string_re = re.compile(r"'([^']*)'", re.M)
10
11 def gnuplot_scan(node, env, path, arg=None):
12     """
13     >>> this_dir = os.path.dirname(__file__)
14     >>> src_dir = os.path.join(this_dir, '..', '..', 'src')
15     >>> class node (object):
16     ...     def __init__(self, path):
17     ...         self.path = path
18     ...         self.abspath = os.path.abspath(self.path)
19     ...         if os.path.isfile(self.path):
20     ...             self.dir = node(os.path.dirname(path))
21     ...     def get_text_contents(self):
22     ...         return open(self.path, 'r').read()
23     ...     def get_contents(self):
24     ...         return self.get_text_contents()
25     ...     def srcnode(self):
26     ...         return self
27     >>> for p in gnuplot_scan(
28     ...         node(os.path.join(src_dir, 'figures', 'order-dep', 'fig.gp')),
29     ...         None, None, None):
30     ...     print p
31     data/order.avg-4
32     data/order.avg-8
33     data/order.avg-12
34     data/order.avg-16
35     data/hist3i.hist
36     data/hist3ii.hist
37     data/hist3iii.hist
38     """
39     try:
40         contents = node.get_text_contents()
41     except AttributeError:
42         contents = node.get_contents() # for older versions of SCons, fall back on binary read
43     ret = []
44     for string in quoted_string_re.findall(contents):
45         p = os.path.join(node.dir.srcnode().abspath, string)
46         if len(string) > 0 and \
47                 ((string not in ret and os.path.exists(p))
48                  or string.endswith('.dat')):
49             ret.append(string)
50     return ret
51
52 GnuplotAction = None
53
54 def generate(env):
55     """Add Builders and construction variables for Gnuplot to an Environment."""
56     global GnuplotAction
57     if GnuplotAction is None:
58         GnuplotAction = SCons.Action.Action('$GNUPLOTCOM', '$GNUPLOTCOMSTR')
59
60     #import pdf
61     #pdf.generate(env)
62
63     env['BUILDERS']['Gnuplot'] = SCons.Script.Builder(
64         action=GnuplotAction, suffix='.pdf', src_suffix = '.gp')
65     env['GNUPLOT'] = 'gnuplot'
66     env['GNUPLOTFLAGS'] = '' #SCons.Util.CLVar('')
67     env['GNUPLOTCOM'] = 'cd ${TARGET.dir} && $GNUPLOT $GNUPLOTFLAGS ${SOURCE.file}'
68     env.Append(SCANNERS=SCons.Scanner.Base(
69             function=gnuplot_scan,
70             name='Gnuplot',
71             skeys=['.gp']))
72
73 def exists(env):
74     return env.Detect('gnuplot')
75
76 if __name__ == '__main__':
77     doctest.testmod()