コード例 #1
0
ファイル: attrdef.py プロジェクト: GMBarra/Docker
	def parse(self, value):
		try:
			return int(value)
		except ValueError:
			raise utils.logOldExc(
				LiteralParseError(self.name_, value, hint="Value must be an"
				" integer literal."))
コード例 #2
0
def doMetaOverride(container, metaKey, metaValue, extraArgs={}):
    """creates the representation of metaKey/metaValue in container.

	If metaKey does not need any special action, this returns None.

	This gets called from one central point in MetaMixin.addMeta, and 
	essentially all magic involved should be concentrated here.
	"""
    if metaKey in META_CLASSES_FOR_KEYS and not isinstance(
            metaValue, MetaValue):
        try:
            container.addMeta(
                metaKey, META_CLASSES_FOR_KEYS[metaKey](metaValue,
                                                        **extraArgs))
            return True
        except TypeError:
            raise utils.logOldExc(
                MetaError(
                    "Invalid arguments for %s meta items: %s" %
                    (metaKey, utils.safe_str(extraArgs)), None))

    # let's see if there's some way to rationalise this kind of thing
    # later.
    if metaKey == "creator":
        return _doCreatorMetaOverride(container, metaValue)
コード例 #3
0
ファイル: attrdef.py プロジェクト: GMBarra/Docker
	def parse(self, value):
		try:
			return float(value)
		except ValueError:
			raise utils.logOldExc(
				LiteralParseError(self.name_, value, hint="value must be a float"
					" literal"))
コード例 #4
0
ファイル: literals.py プロジェクト: GMBarra/Docker
 def parseSexaColon(soup):
     timeangleRE = r"(?:\d+:)?(?:\d+:)?\d+(?:\.\d*)?"
     dmsRE = "[+-]?\s*(?:\d+:)?(?:\d+:)?\d+(?:\.\d*)?"
     mat = re.match("(%s)\s*[\s,/]?\s*(%s)$" % (timeangleRE, dmsRE), soup)
     if mat:
         try:
             return (utils.hmsToDeg(mat.group(1), sepChar=":"),
                     utils.dmsToDeg(mat.group(2), sepChar=":"))
         except utils.Error, msg:
             raise utils.logOldExc(ValueError(str(msg)))
コード例 #5
0
ファイル: attrdef.py プロジェクト: GMBarra/Docker
	def parse(self, val):
		if val is None:
			return None
		try:
			return dict((k.strip(), v.strip()) 
				for k,v in (p.split(":") for p in val.split(",")))
		except ValueError:
			raise utils.logOldExc(LiteralParseError(self.name_, val, 
				hint="A key-value enumeration of the format k:v {,k:v}"
				" is expected here"))
コード例 #6
0
ファイル: macros.py プロジェクト: GMBarra/Docker
 def execMacro(self, macName, args):
     fun = self.__findMacro(macName)
     try:
         return fun(*args)
     except TypeError:
         raise utils.logOldExc(
             MacroError("Invalid macro arguments to \\%s: %s" %
                        (macName, args),
                        macName,
                        hint="You supplied too few or too many arguments"))
コード例 #7
0
 def parse(self, value):
     try:
         return literals.parseBooleanLiteral(value)
     except ValueError:
         raise utils.logOldExc(
             LiteralParseError(
                 self.name_,
                 value,
                 hint=
                 "A boolean literal (e.g., True, False, yes, no) is expected here."
             ))
コード例 #8
0
 def bind(symName, nodeClass):
     try:
         if getattr(nodeClass, "collapsible", False):
             syms[symName].addParseAction(
                 lambda s, pos, toks: nodes.autocollapse(nodeClass, toks))
         else:
             syms[symName].addParseAction(
                 lambda s, pos, toks: nodeClass.fromParseResult(toks))
     except KeyError:
         raise utils.logOldExc(
             KeyError("%s asks for non-existing symbol %s" %
                      (nodeClass.__name__, symName)))
コード例 #9
0
	def getArgs(self):
		"""returns a dictionary suitable as keyword arguments to psycopg2's
		connect.
		"""
		res = {}
		for key in ["database", "user", "password", "host", "port", "sslmode"]:
			if getattr(self, key):
				res[key] = getattr(self, key)
		if res.keys()==["sslmode"]:
			raise utils.logOldExc(utils.StructureError("Insufficient information"
			" to connect to the database in profile '%s'."%(
				self.profileName)))
		return res
コード例 #10
0
def resolveNameBased(container, id, forceType=None):
    """Tries to find a thing with name id within container.

	If container defines a method getElementForName, it will be called; it
	must either return some element with this name or raise a NotFoundError.

	If no such method exists, the function iterates over container until
	it finds an element with el.name==id.  If no such element exists,
	it again raises a NotFoundError.

	The function raises a NotFoundError when no such thing exists.
	"""
    if hasattr(container, "getElementForName"):
        return container.getElementForName(id)

    ob = None
    try:
        for ob in container:
            if hasattr(ob, "name") and ob.name == id:
                return assertType(id, ob, forceType)
    except TypeError:
        if ob is None:
            raise utils.logOldExc(
                common.NotFoundError(
                    id,
                    "Element with name",
                    "container %s" % repr(container),
                    hint="The container, %s, is not iterable" %
                    repr(container)))
        else:
            raise utils.logOldExc(
                common.NotFoundError(
                    id,
                    "Element with name",
                    "container %s" % repr(container),
                    hint="Element %s is of type %s and thus unsuitable"
                    " for name path" % (ob.name, type(ob))))
    raise common.NotFoundError(id, "Element with name",
                               "container %s" % container.id)
コード例 #11
0
def resolveComplexId(ctx, id, forceType=None):
    """resolves a dotted id.

	See resolveId.
	"""
    try:
        pId, name = id.split(".")
    except ValueError:
        raise utils.logOldExc(
            common.LiteralParseError(
                "id",
                id,
                hint="A complex reference (parent.name) is expected here"))
    container = ctx.getById(pId)
    return resolveNameBased(container, name, forceType)
コード例 #12
0
 def _createJob(self, query, lang, userParams):
     params = {"REQUEST": "doQuery", "LANG": lang, "QUERY": query}
     for k, v in userParams.iteritems():
         params[k] = str(v)
     response = request(self.destHost,
                        self.destPath,
                        params,
                        method="POST",
                        expectedStatus=303,
                        timeout=self.timeout)
     # The last part of headers[location] now contains the job id
     try:
         self.jobId = urlparse.urlsplit(response.getheader(
             "location", "")).path.split("/")[-1]
     except ValueError:
         raise utils.logOldExc(
             ProtocolError("Job creation returned invalid job id"))
コード例 #13
0
 def _build(self, constructors, metaContainer, macroPackage):
     result = []
     for item in constructors:
         if isinstance(item, basestring):
             result.append(item)
         else:
             try:
                 result.extend(
                     self._getItemsForConstructor(metaContainer,
                                                  macroPackage, *item))
             except utils.Error:
                 raise
             except:
                 raise utils.logOldExc(
                     utils.ReportableError(
                         "Invalid constructor func in %s, meta container active %s"
                         % (repr(item), repr(metaContainer))))
     return result
コード例 #14
0
    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))
コード例 #15
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)
コード例 #16
0
ファイル: config.py プロジェクト: GMBarra/Docker
 def _raiseError(self, msg):
     raise utils.logOldExc(
         ProfileParseError(self.parser.error_leader() + msg))
コード例 #17
0
                base.ui.notifyWarning("Ignoring dependent %s of %s (%s)" %
                                      (dependentId, dd.id, unicode(msg)))

    for dd in dds:
        gatherDependents(dd)

    if parseOptions.buildDependencies:
        parseOptions = parseOptions.change(buildDependencies=False)

    try:
        buildSequence = utils.topoSort(edges)
    except ValueError, ex:
        raise utils.logOldExc(
            base.ReportableError(
                "Could not sort"
                " dependent DDs topologically (use  --hints to learn more).",
                hint="This is most likely because there's a cyclic dependency."
                " Please check your dependency structure.  The original message"
                " is: %s" % utils.safe_str(ex)))

    # note that the original DD is the first item in the build sequence,
    # and we don't want to re-make it here
    if parseOptions.metaOnly:
        if len(buildSequence) > 1:
            base.ui.notifyWarning(
                "Only importing metadata, not rebulding"
                " dependencies.  Depending on your changes, it may be"
                " necessary to manually re-make one of these: %s" %
                ", ".join(dd.id for dd in buildSequence[1:]))
    else:
        for dd in buildSequence[1:]:
コード例 #18
0
ファイル: unitconv.py プロジェクト: GMBarra/Docker
def parseUnit(unitStr, unitGrammar=getUnitGrammar()):
    try:
        return utils.pyparseString(unitGrammar, unitStr, parseAll=True)[0]
    except pyparsing.ParseException, msg:
        raise utils.logOldExc(
            BadUnit("%s at col. %d" % (repr(unitStr), msg.column)))