def value_(self, ctx, name, value): if name == "key" or name == self.keyName: self._key = value elif name == "cumulate": self._adding = literals.parseBooleanLiteral(value) elif name == "content_": if self._key is attrdef.Undefined: raise common.StructureError( "Content '%s' has no %s attribute" % (value, self.keyName)) self.addPair(self._key, self.parseValue(value)) self._reset() else: raise common.StructureError("No %s attributes on mappings" % name) return self
def getAttribute(self, name): """Returns an attribute instance from name. This function will raise a StructureError if no matching attribute definition is found. """ if name in self.managedAttrs: return self.managedAttrs[name] if name == "content_": raise common.StructureError( "%s elements must not have character data" " content." % (self.name_)) raise common.StructureError( "%s elements have no %s attributes or children." % (self.name_, name))
def validate(self): for val in set(self.managedAttrs.itervalues()): if getattr(self, val.name_) is attrdef.Undefined: raise common.StructureError("You must set %s on %s elements" % (val.name_, self.name_)) if hasattr(val, "validate"): val.validate(self) self._validateNext(Structure)
def _feedToAtom(self, type, name, value): if type == 'start': raise common.StructureError("%s elements cannot have %s children" % (self.next, name)) elif type == 'value' or type == "parsedvalue": self.curParser.feedEvent(self.ctx, 'value', self.next, value) elif type == 'end': self.next = None
def feedEvent(self, ctx, evType, name, value): """dispatches an event to the root structure. Do not call this yourself unless you know what you're doing. The method to feed "real" events to is feed. """ if name != self.rootStruct.name_: raise common.StructureError("Expected root element %s, found %s" % (self.rootStruct.name_, name)) if evType == "start": if isinstance(self.rootStruct, type): self.result = self.rootStruct(None) else: self.result = self.rootStruct self.result.idmap = ctx.idmap return self.result else: raise common.StructureError("Bad document structure")
def __init__(self, content="", format="plain"): self.initArgs = content, format MetaMixin.__init__(self) if format not in self.knownFormats: raise common.StructureError( "Unknown meta format '%s'; allowed are %s." % (format, ", ".join(self.knownFormats))) self.content = content self.format = format self._preprocessContent()
def feedObject(self, instance, original, ctx=None): if not instance._pristine: raise common.StructureError( "Original must be applied before modifying" " the destination structure.", hint="You should normally use" " original only as attribute. If you insist on having it as" " an element, it must be the first one and all other structure" " members must be set through elements, too") instance._originalObject = original instance.feedFrom(original, ctx)
def assertType(id, ob, forceType): """raises a StructureError if forceType is not None and ob is not of type forceType, returns ob otherwise. """ if forceType: if not isinstance(ob, forceType): raise common.StructureError( "Reference to '%s' yielded object of type" " %s, expected %s" % (id, ob.__class__.__name__, forceType.__name__)) return ob
def _setupReplay(self, ctx): sources = [s for s in [self.source, self.events] if s] if len(sources) != 1: raise common.StructureError("Need exactly one of source and events" " on %s elements" % self.name_) stream = sources[0].events_ def replayer(): self.replay(stream, self.parent, ctx) self._replayer = replayer
def _getRowIterator(self): rowIterators = [ ri for ri in [ self._makeRowIteratorFromListItems(), self._makeRowIteratorFromCSV(), self._makeRowIteratorFromCode() ] if ri ] if len(rowIterators) != 1: raise common.StructureError("Must give exactly one data source in" " LOOP") return rowIterators[0]
def _doAddMeta(self): content = self.attrs.pop("content_", "") if not self.attrs: # content only, parse this as a meta stream parseMetaStream(self.container, content) else: try: content = utils.fixIndentation(content, "", 1).rstrip() except common.Error, ex: raise utils.logOldExc( common.StructureError("Bad text in meta value" " (%s)" % ex)) if not "name" in self.attrs: raise common.StructureError("meta elements must have a" " name attribute") metaKey = self.attrs.pop("name") self.container.addMeta(metaKey, content, **self.attrs) # meta elements can have children; add these, properly fudging # their keys for key, content, kwargs in self.children: fullKey = "%s.%s" % (metaKey, key) self.container.addMeta(fullKey, content, **kwargs)
def __init__(self, parent, **kwargs): self.parent = parent # set defaults for val in self.attrSeq: try: if not hasattr(self, val.name_): # don't clobber properties # set up by attributes. setattr(self, val.name_, val.default_) except AttributeError: # default on property given raise utils.logOldExc( common.StructureError( "%s attributes on %s have builtin defaults only." % (val.name_, self.name_))) # set keyword arguments for name, val in kwargs.iteritems(): if name in self.managedAttrs: if not hasattr(self.managedAttrs[name], "computed_"): self.managedAttrs[name].feedObject(self, val) else: raise common.StructureError("%s objects have no attribute %s" % (self.__class__.__name__, name))
def value_(self, ctx, name, value): # value event: If it's a content_, it's a reference, else it's an # attribute on a child of ours. if name == "content_": if self.child: raise common.StructureError( "Content received on ReferenceParser" " although a child is already there.", hint="You should" " not see this. Complain fiercely.") self.refAttr.feed(ctx, self.parent, value) self.child = None return self else: self._ensureChild() return self.child.feedEvent(ctx, "value", name, value)
def getAttributes(self, attDefsFrom=None): """returns a dict of the current attributes, suitable for making a shallow copy of self. Struct attributes will not be reparented, so there are limits to what you can do with such shallow copies. """ if attDefsFrom is None: attrs = set(self.managedAttrs.values()) else: attrs = set(attDefsFrom.managedAttrs.itervalues()) try: return dict([(att.name_, getattr(self, att.name_)) for att in attrs]) except AttributeError, msg: raise common.logOldExc( common.StructureError( "Attempt to copy from invalid source: %s" % unicode(msg)))
def resolveId(ctx, id, instance=None, forceType=None): """tries to resolve id in context. ctx is some object having a getById method; this could be an RD or a parse context. The rules for id are as follows: (#) if id has a # in it, split it and take the first part to be an RD id, the second and id built according to the rest of this spec. (#) if id has a dot in it, split at the first dot to get a pair of id and name. Iterate over the element with id, and look for something with a "name" attribute valued name. If this fails, raise a NotFoundError. (#) if instance is not None and has a resolveName method or has a parent, and that parent has a resolveName method, pass id to it. If it does not raise a NotFoundError, return the result. This is for parents with a rscdef.NamePathAttribute. (#) ask the ParseContext ctx's getById method to resolve id, not catching the NotFoundError this will raise if the id is not known. """ if "#" in id: return resolveCrossId(id, forceType) if ctx is None: raise common.StructureError( "Cannot intra-reference when parsing without" " a context") if "." in id: return resolveComplexId(ctx, id, forceType) srcOb = None if instance: try: srcOb = _resolveOnNamepath(ctx, id, instance) except common.NotFoundError: # no such named element, try element with id pass if srcOb is None and ctx is not None: srcOb = ctx.getById(id, forceType) return assertType(id, srcOb, forceType)
def _makeChild(self, name, parent): """returns a new element of the appropriate type. This method raises a StructureError if that type is not known. Within ReferenceAttribute, the type is given by forceType. """ if self.forceType is None: raise common.StructureError( "Only references allowed for %s, but" " an immediate object was found" % self.name_, hint="This means that" " you tried to replace a reference to an element with" " the element itself. This is only allowed if the reference" " forces a type, which is not the case here.") child = self._getForceType(parent)(parent) # leave a sentinel in the child that will later let us # iterEvents not the id but the struct itself. child._RefAttrImmediate = True return child
def __init__(self, name, **kwargs): if kwargs.get("default") is not None: raise common.StructureError("ReferenceListAttributes cannot have" " defaults") kwargs["default"] = attrdef.Computed ReferenceAttribute.__init__(self, name, **kwargs)
def start_(self, ctx, name, value): raise common.StructureError("No %s elements in mappings" % name)