Attachment 'jyant.py'

Download

   1 # -*- coding: iso-8859-1 -*-
   2 """
   3     Jyant - Extensions to Ant
   4 
   5     @copyright: 2005 by J├╝rgen Hermann <jhermann@users.sourceforge.net>
   6     @license: GNU GPL.
   7 """
   8 
   9 import __builtin__ # for accessing them from the PropMapper
  10 
  11 class PropMapper:
  12     """ Map the properties in Ant's "project" object to Python names.
  13 
  14         @cvar _DEBUG: set to 1 to get some debugging output.
  15         @cvar TYPEMAP:
  16             mapping from Jython type objects to the
  17             corresponding conversion functions.
  18     """
  19     _DEBUG = 0
  20 
  21     TYPEMAP = {
  22         type(1): int,
  23         type(''): str,
  24     }
  25 
  26     def __init__(self, project, name=None):
  27         """ Init typemapper with the properties in "project".
  28 
  29             If "name" is None, the created object is propulated with
  30             the root namespace, the values in that namespace are
  31             other Portmapper objects with the name prefix of the
  32             properties they contain. By overloading the usual __magic__
  33             methods a mapper can behave as a simple value (__str__,
  34             __int__) AND as a dictionary (__getitem__) or an attribute
  35             container (__getattr__). This is important to mimic Ant's
  36             ability to assign value to names that are prefixes for
  37             other names.
  38 
  39             @param project: Reference to Ant project.
  40             @param name: Property name/prefix or None for the root namespace.
  41         """
  42         self.__root = name is None
  43         self.__name = name or '<PROPS>' # give magic name to root namespace
  44         self.__props = {}
  45         self.__project = project
  46 
  47         # if we're not the root, nothing more to do
  48         if name is not None: return
  49 
  50         # populate namespace
  51         for key in project.getProperties():
  52             names = key.split('.')
  53             vals = self
  54             
  55             # iterate over name parts
  56             for idx, name in zip(range(len(names)), names):
  57                 # if we don't have a container yet for this prefix...
  58                 if not vals.__props.has_key(name):
  59                     # create one, and anchor it in its parent
  60                     vals.__props[name] = PropMapper(
  61                         project, '.'.join(names[:idx+1]))
  62                 # set parent for deeper level
  63                 vals = vals.__props[name]
  64 
  65     def __getitem__(self, name):
  66         """ Behave as a dictionary, this implements the basic value access
  67             and the root namespace (we pass it into eval as "locals", which
  68             must adhere to the dict protocol).
  69 
  70             The root namespace also allows access to all builtins.
  71         """
  72         if PropMapper._DEBUG:
  73             print "getting item %s from %r" % (name or "<VALUE>", self)
  74 
  75         # get value in this namespace
  76         result = self.__props.get(name, None)
  77         if result is None:
  78             # DUH, no luck, try other possible places...
  79             if self.__root:
  80                 # try to find a builtin with this name
  81                 result = vars(__builtin__).get(name, None)
  82             else:
  83                 # see if it's a method call
  84                 result = getattr(str(self), name, None)
  85         if result is None:
  86             # OK, let's give up...
  87             raise KeyError, "%r.%s" % (self, name)
  88 
  89         # return value found
  90         return result
  91 
  92     def __getattr__(self, name):
  93         """ Attribute access, delegated to __getitem__.
  94         """
  95         return self[name]
  96 
  97     def __int__(self):
  98         """ Integer value access.
  99         """
 100         if PropMapper._DEBUG:
 101             print "getting int value from %r" % (self)
 102         # delegate to __str__, then convert
 103         return int(str(self))
 104 
 105     def __str__(self):
 106         """ Access string value of this mapper's prefix.
 107         """
 108         if PropMapper._DEBUG:
 109             print "getting str value from %r" % (self)
 110         return str(self.__project.getProperty(repr(self)))
 111 
 112     def __coerce__(self, other):
 113         """ Coerce this mapper's value to the type of the "other" operand.
 114         """
 115         if PropMapper._DEBUG:
 116             print "coercing value for %r" % (self)
 117 
 118         # get mapping operator
 119         target = type(other)
 120         target = self.TYPEMAP.get(target, target)
 121 
 122         # map own value
 123         return (target(str(self)), other)
 124 
 125     def __repr__(self):
 126         """ Return name prefix of this mapper.
 127             Note that this is used internally, so do not change the
 128             return value semantics.
 129         """
 130         return self.__name
 131 
 132 
 133 class Task:
 134     """ Base class for all task implementations. Stores Ant's environment
 135         and offers evaluation of expressions with Jython syntax that are
 136         able to access all Ant properties.
 137     """
 138 
 139     def __init__(self, ant, this):
 140         """ Store environment and create some convenience attributes.
 141         """
 142         self.ant = ant
 143         self.this = this
 144         self.project = self.ant['project']
 145         self.bsf = self.ant['bsf']
 146         self.attributes= self.ant['attributes']
 147         self.elements = self.ant['elements']
 148 
 149     def evalExpression(self, expr):
 150         """ Evaluate Jython expression using current Ant properties.
 151         
 152             @param expr: expression to evaluate
 153             @type expr: str
 154             @rtype: type of the expression result
 155             @return: evaluated "expr"
 156         """
 157         glob = globals()
 158         mapper = PropMapper(self.project)
 159         return eval(expr, glob, mapper)
 160 
 161 
 162 class Eval(Task):
 163     """ Implementation of <eval>.
 164     """
 165     def execute(self):
 166         # simply set the given "property" to the value of "expression"
 167         self.project.setProperty(self.attributes['property'],
 168             str(self.evalExpression(self.attributes['expression']))
 169         )
 170 
 171 
 172 class EvalCond(Task):
 173     """ Implementation of <evalcond>.
 174     """
 175     def execute(self):
 176         # evaluate "expression" attribute to bool value
 177         boolval = 0 != int(self.evalExpression(self.attributes['expression']))
 178 
 179         # get "value" or "else" attribute value, with appropriate defaults
 180         if boolval:
 181             val = self.attributes.get('value') or "true"
 182         else:
 183             val = self.attributes.get('else') or None
 184 
 185         # set "property" if we got a value for it
 186         if val is not None:
 187             self.project.setProperty(self.attributes['property'], val)
 188 
 189 class IfThenElse(Task):
 190     """ Implementation of <if>.
 191     """
 192     def execute(self):
 193         # evaluate "condition" attribute to bool value
 194         boolval = 0 != int(eval(self.attributes['condition']))
 195 
 196         # make sure there is at most one <then> and <else>
 197         for elemname in ['then', 'else']:
 198             assert len(self.elements.get(elemname) or []) <= 1, (
 199                 "Only one child element <%s> allowed!" % elemname
 200             )
 201 
 202         # execute the selected child element's task, if it exists
 203         elemname = ('else', 'then')[boolval]
 204         tasks = self.elements.get(elemname) or None
 205         if tasks is not None and tasks:
 206             tasks[0].execute()
 207 
 208 
 209 def info(ant, this):
 210     """ Print some Jython scripting values.
 211     """
 212     import sys
 213 
 214     attrs = ant['attributes']
 215     if attrs['echo'] != "true": return
 216 
 217     print "name = %r" % __name__
 218     print "ant env = %r" % ant
 219     print "modules = %r" % sys.modules
 220     print "tag name = %r" % this.getTag()
 221     print "echo = %r" % attrs['echo']
 222 
 223 def dispatch(ant):
 224     """ Dispatch to task implementation based on the tag name.
 225     """
 226     # get tag name of this task
 227     from java.lang import Thread
 228     cur_thread = Thread.currentThread()
 229     project = ant['project']
 230     this = project.getThreadTask(cur_thread)
 231 
 232     # map from tag name to implementation
 233     taskmap = {
 234         'jyant-info': info,
 235         'eval': Eval,
 236         'evalcond': EvalCond,
 237         'if': IfThenElse,
 238     }
 239 
 240     # call implementation, which is either a function
 241     # implementing the task directly or a Task factory
 242     task = taskmap[this.getTag()](ant, this)
 243 
 244     # if implementation is a "Task" object, execute it
 245     if isinstance(task, Task):
 246         task.execute()
 247 
 248 if __name__ == "main":
 249     # dispatch task
 250     dispatch(globals())

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.

You are not allowed to attach a file to this page.