root/galaxy-central/eggs/PasteScript-1.7.3-py2.6.egg/paste/script/templates.py

リビジョン 3, 9.8 KB (コミッタ: kohda, 14 年 前)

Install Unix tools  http://hannonlab.cshl.edu/galaxy_unix_tools/galaxy.html

行番号 
1# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
2# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
3import sys
4import os
5import inspect
6import copydir
7import command
8
9from paste.util.template import paste_script_template_renderer
10
11class Template(object):
12
13    # Subclasses must define:
14    # _template_dir (or template_dir())
15    # summary
16
17    # Variables this template uses (mostly for documentation now)
18    # a list of instances of var()
19    vars = []
20
21    # Eggs that should be added as plugins:
22    egg_plugins = []
23
24    # Templates that must be applied first:
25    required_templates = []
26
27    # Use Cheetah for substituting templates:
28    use_cheetah = False
29    # If true, then read all the templates to find the variables:
30    read_vars_from_templates = False
31
32    # You can also give this function/method to use something other
33    # than Cheetah or string.Template.  The function should be of the
34    # signature template_renderer(content, vars, filename=filename).
35    # Careful you don't turn this into a method by putting a function
36    # here (without staticmethod)!
37    template_renderer = None
38
39    def __init__(self, name):
40        self.name = name
41        self._read_vars = None
42   
43    def module_dir(self):
44        """Returns the module directory of this template."""
45        mod = sys.modules[self.__class__.__module__]
46        return os.path.dirname(mod.__file__)
47
48    def template_dir(self):
49        assert self._template_dir is not None, (
50            "Template %r didn't set _template_dir" % self)
51        if isinstance( self._template_dir, tuple):
52            return self._template_dir
53        else:
54            return os.path.join(self.module_dir(), self._template_dir)
55
56    def run(self, command, output_dir, vars):
57        self.pre(command, output_dir, vars)
58        self.write_files(command, output_dir, vars)
59        self.post(command, output_dir, vars)
60
61    def check_vars(self, vars, cmd):
62        expect_vars = self.read_vars(cmd)
63        if not expect_vars:
64            # Assume that variables aren't defined
65            return vars
66        converted_vars = {}
67        unused_vars = vars.copy()
68        errors = []
69        for var in expect_vars:
70            if var.name not in unused_vars:
71                if cmd.interactive:
72                    prompt = 'Enter %s' % var.full_description()
73                    response = cmd.challenge(prompt, var.default, var.should_echo)
74                    converted_vars[var.name] = response
75                elif var.default is command.NoDefault:
76                    errors.append('Required variable missing: %s'
77                                  % var.full_description())
78                else:
79                    converted_vars[var.name] = var.default
80            else:
81                converted_vars[var.name] = unused_vars.pop(var.name)
82        if errors:
83            raise command.BadCommand(
84                'Errors in variables:\n%s' % '\n'.join(errors))
85        converted_vars.update(unused_vars)
86        vars.update(converted_vars)
87        return converted_vars
88       
89    def read_vars(self, command=None):
90        if self._read_vars is not None:
91            return self._read_vars
92        assert (not self.read_vars_from_templates
93                or self.use_cheetah), (
94            "You can only read variables from templates if using Cheetah")
95        if not self.read_vars_from_templates:
96            self._read_vars = self.vars
97            return self.vars
98       
99        vars = self.vars[:]
100        var_names = [var.name for var in self.vars]
101        read_vars = find_args_in_dir(
102            self.template_dir(),
103            verbose=command and command.verbose > 1).items()
104        read_vars.sort()
105        for var_name, var in read_vars:
106            if var_name not in var_names:
107                vars.append(var)
108        self._read_vars = vars
109        return vars
110
111    def write_files(self, command, output_dir, vars):
112        template_dir = self.template_dir()
113        if not os.path.exists(output_dir):
114            print "Creating directory %s" % output_dir
115            if not command.simulate:
116                # Don't let copydir create this top-level directory,
117                # since copydir will svn add it sometimes:
118                os.makedirs(output_dir)
119        copydir.copy_dir(template_dir, output_dir,
120                         vars,
121                         verbosity=command.verbose,
122                         simulate=command.options.simulate,
123                         interactive=command.interactive,
124                         overwrite=command.options.overwrite,
125                         indent=1,
126                         use_cheetah=self.use_cheetah,
127                         template_renderer=self.template_renderer)
128
129    def print_vars(self, indent=0):
130        vars = self.read_vars()
131        var.print_vars(vars)
132       
133    def pre(self, command, output_dir, vars):
134        """
135        Called before template is applied.
136        """
137        pass
138
139    def post(self, command, output_dir, vars):
140        """
141        Called after template is applied.
142        """
143        pass
144
145NoDefault = command.NoDefault
146
147class var(object):
148
149    def __init__(self, name, description,
150                 default='', should_echo=True):
151        self.name = name
152        self.description = description
153        self.default = default
154        self.should_echo = should_echo
155
156    def __repr__(self):
157        return '<%s %s default=%r should_echo=%s>' % (
158            self.__class__.__name__,
159            self.name, self.default, self.should_echo)
160
161    def full_description(self):
162        if self.description:
163            return '%s (%s)' % (self.name, self.description)
164        else:
165            return self.name
166
167    def print_vars(cls, vars, indent=0):
168        max_name = max([len(v.name) for v in vars])
169        for var in vars:
170            if var.description:
171                print '%s%s%s  %s' % (
172                    ' '*indent,
173                    var.name,
174                    ' '*(max_name-len(var.name)),
175                    var.description)
176            else:
177                print '  %s' % var.name
178            if var.default is not command.NoDefault:
179                print '      default: %r' % var.default
180            if var.should_echo is True:
181                print '      should_echo: %s' % var.should_echo
182        print
183
184    print_vars = classmethod(print_vars)
185
186class BasicPackage(Template):
187
188    _template_dir = 'paster-templates/basic_package'
189    summary = "A basic setuptools-enabled package"
190    vars = [
191        var('version', 'Version (like 0.1)'),
192        var('description', 'One-line description of the package'),
193        var('long_description', 'Multi-line description (in reST)'),
194        var('keywords', 'Space-separated keywords/tags'),
195        var('author', 'Author name'),
196        var('author_email', 'Author email'),
197        var('url', 'URL of homepage'),
198        var('license_name', 'License name'),
199        var('zip_safe', 'True/False: if the package can be distributed as a .zip file', default=False),
200        ]
201
202    template_renderer = staticmethod(paste_script_template_renderer)
203   
204_skip_variables = ['VFN', 'currentTime', 'self', 'VFFSL', 'dummyTrans',
205                   'getmtime', 'trans']
206
207def find_args_in_template(template):
208    if isinstance(template, (str, unicode)):
209        # Treat as filename:
210        import Cheetah.Template
211        template = Cheetah.Template.Template(file=template)
212    if not hasattr(template, 'body'):
213        # Don't know...
214        return None
215    method = template.body
216    args, varargs, varkw, defaults = inspect.getargspec(method)
217    defaults=list(defaults or [])
218    vars = []
219    while args:
220        if len(args) == len(defaults):
221            default = defaults.pop(0)
222        else:
223            default = command.NoDefault
224        arg = args.pop(0)
225        if arg in _skip_variables:
226            continue
227        # @@: No way to get description yet
228        vars.append(
229            var(arg, description=None,
230                default=default))
231    return vars
232
233def find_args_in_dir(dir, verbose=False):
234    all_vars = {}
235    for fn in os.listdir(dir):
236        if fn.startswith('.') or fn == 'CVS' or fn == '_darcs':
237            continue
238        full = os.path.join(dir, fn)
239        if os.path.isdir(full):
240            inner_vars = find_args_in_dir(full)
241        elif full.endswith('_tmpl'):
242            inner_vars = {}
243            found = find_args_in_template(full)
244            if found is None:
245                # Couldn't read variables
246                if verbose:
247                    print 'Template %s has no parseable variables' % full
248                continue
249            for var in found:
250                inner_vars[var.name] = var
251        else:
252            # Not a template, don't read it
253            continue
254        if verbose:
255            print 'Found variable(s) %s in Template %s' % (
256                ', '.join(inner_vars.keys()), full)
257        for var_name, var in inner_vars.items():
258            # Easy case:
259            if var_name not in all_vars:
260                all_vars[var_name] = var
261                continue
262            # Emit warnings if the variables don't match well:
263            cur_var = all_vars[var_name]
264            if not cur_var.description:
265                cur_var.description = var.description
266            elif (cur_var.description and var.description
267                  and var.description != cur_var.description):
268                print >> sys.stderr, (
269                    "Variable descriptions do not match: %s: %s and %s"
270                    % (var_name, cur_var.description, var.description))
271            if (cur_var.default is not command.NoDefault
272                and var.default is not command.NoDefault
273                and cur_var.default != var.default):
274                print >> sys.stderr, (
275                    "Variable defaults do not match: %s: %r and %r"
276                    % (var_name, cur_var.default, var.default))
277    return all_vars
278
Note: リポジトリブラウザについてのヘルプは TracBrowser を参照してください。