Better debug output.
[zeroinstall.git] / zeroinstall / injector / model.py
blob10fe3af694cae1e31597a41cf192965ec7d3f733
1 """In-memory representation of interfaces and other data structures.
3 The objects in this module are used to build a representation of an XML interface
4 file in memory.
6 @see: L{reader} constructs these data-structures.
8 @var defaults: Default values for the 'default' attribute for <environment> bindings of
9 well-known variables.
10 """
12 # Copyright (C) 2006, Thomas Leonard
13 # See the README file for details, or visit http://0install.net.
15 import os, re
16 from logging import warn, info, debug
17 from zeroinstall import SafeException, version
18 from zeroinstall.injector.namespaces import XMLNS_IFACE
20 # Element names for bindings in feed files
21 binding_names = frozenset(['environment'])
23 network_offline = 'off-line'
24 network_minimal = 'minimal'
25 network_full = 'full'
26 network_levels = (network_offline, network_minimal, network_full)
28 stability_levels = {} # Name -> Stability
30 defaults = {
31 'PATH': '/bin:/usr/bin',
32 'XDG_CONFIG_DIRS': '/etc/xdg',
33 'XDG_DATA_DIRS': '/usr/local/share:/usr/share',
36 class InvalidInterface(SafeException):
37 """Raised when parsing an invalid feed."""
38 def __init__(self, message, ex = None):
39 if ex:
40 message += "\n\n(exact error: %s)" % ex
41 SafeException.__init__(self, message)
43 def _split_arch(arch):
44 """Split an arch into an (os, machine) tuple. Either or both parts may be None."""
45 if not arch:
46 return None, None
47 elif '-' not in arch:
48 raise SafeException("Malformed arch '%s'" % arch)
49 else:
50 os, machine = arch.split('-', 1)
51 if os == '*': os = None
52 if machine == '*': machine = None
53 return os, machine
55 def _join_arch(os, machine):
56 if os == machine == None: return None
57 return "%s-%s" % (os or '*', machine or '*')
59 class Stability(object):
60 """A stability rating. Each implementation has an upstream stability rating and,
61 optionally, a user-set rating."""
62 __slots__ = ['level', 'name', 'description']
63 def __init__(self, level, name, description):
64 self.level = level
65 self.name = name
66 self.description = description
67 assert name not in stability_levels
68 stability_levels[name] = self
70 def __cmp__(self, other):
71 return cmp(self.level, other.level)
73 def __str__(self):
74 return self.name
76 def __repr__(self):
77 return "<Stability: " + self.description + ">"
79 def process_binding(e):
80 """Internal"""
81 if e.name == 'environment':
82 mode = {
83 None: EnvironmentBinding.PREPEND,
84 'prepend': EnvironmentBinding.PREPEND,
85 'append': EnvironmentBinding.APPEND,
86 'replace': EnvironmentBinding.REPLACE,
87 }[e.getAttribute('mode')]
89 binding = EnvironmentBinding(e.getAttribute('name'),
90 insert = e.getAttribute('insert'),
91 default = e.getAttribute('default'),
92 mode = mode)
93 if not binding.name: raise InvalidInterface("Missing 'name' in binding")
94 if binding.insert is None: raise InvalidInterface("Missing 'insert' in binding")
95 return binding
96 else:
97 raise Exception("Unknown binding type '%s'" % e.name)
99 def process_depends(item):
100 """Internal"""
101 # Note: also called from selections
102 dep_iface = item.getAttribute('interface')
103 if not dep_iface:
104 raise InvalidInterface("Missing 'interface' on <requires>")
105 dependency = InterfaceDependency(dep_iface, metadata = item.attrs)
107 for e in item.childNodes:
108 if e.uri != XMLNS_IFACE: continue
109 if e.name in binding_names:
110 dependency.bindings.append(process_binding(e))
111 elif e.name == 'version':
112 dependency.restrictions.append(
113 Restriction(not_before = parse_version(e.getAttribute('not-before')),
114 before = parse_version(e.getAttribute('before'))))
115 return dependency
118 insecure = Stability(0, 'insecure', 'This is a security risk')
119 buggy = Stability(5, 'buggy', 'Known to have serious bugs')
120 developer = Stability(10, 'developer', 'Work-in-progress - bugs likely')
121 testing = Stability(20, 'testing', 'Stability unknown - please test!')
122 stable = Stability(30, 'stable', 'Tested - no serious problems found')
123 packaged = Stability(35, 'packaged', 'Supplied by the local package manager')
124 preferred = Stability(40, 'preferred', 'Best of all - must be set manually')
126 class Restriction(object):
127 """A Restriction limits the allowed implementations of an Interface."""
128 __slots__ = ['before', 'not_before']
129 def __init__(self, before, not_before):
130 self.before = before
131 self.not_before = not_before
133 def meets_restriction(self, impl):
134 if self.not_before and impl.version < self.not_before:
135 return False
136 if self.before and impl.version >= self.before:
137 return False
138 return True
140 def __str__(self):
141 if self.not_before is not None or self.before is not None:
142 range = ''
143 if self.not_before is not None:
144 range += format_version(self.not_before) + ' <= '
145 range += 'version'
146 if self.before is not None:
147 range += ' < ' + format_version(self.before)
148 else:
149 range = 'none'
150 return "(restriction: %s)" % range
152 class Binding(object):
153 """Information about how the choice of a Dependency is made known
154 to the application being run."""
156 class EnvironmentBinding(Binding):
157 """Indicate the chosen implementation using an environment variable."""
158 __slots__ = ['name', 'insert', 'default', 'mode']
160 PREPEND = 'prepend'
161 APPEND = 'append'
162 REPLACE = 'replace'
164 def __init__(self, name, insert, default = None, mode = PREPEND):
165 """mode argument added in version 0.28"""
166 self.name = name
167 self.insert = insert
168 self.default = default
169 self.mode = mode
171 def __str__(self):
172 return "<environ %s %s %s>" % (self.name, self.mode, self.insert)
174 __repr__ = __str__
176 def get_value(self, path, old_value):
177 """Calculate the new value of the environment variable after applying this binding.
178 @param path: the path to the selected implementation
179 @param old_value: the current value of the environment variable
180 @return: the new value for the environment variable"""
181 extra = os.path.join(path, self.insert)
183 if self.mode == EnvironmentBinding.REPLACE:
184 return extra
186 if old_value is None:
187 old_value = self.default or defaults.get(self.name, None)
188 if old_value is None:
189 return extra
190 if self.mode == EnvironmentBinding.PREPEND:
191 return extra + ':' + old_value
192 else:
193 return old_value + ':' + extra
195 def _toxml(self, doc):
196 """Create a DOM element for this binding.
197 @param doc: document to use to create the element
198 @return: the new element
200 env_elem = doc.createElementNS(XMLNS_IFACE, 'environment')
201 env_elem.setAttributeNS(None, 'name', self.name)
202 env_elem.setAttributeNS(None, 'insert', self.insert)
203 if self.default:
204 env_elem.setAttributeNS(None, 'default', self.default)
205 return env_elem
207 class Feed(object):
208 """An interface's feeds are other interfaces whose implementations can also be
209 used as implementations of this interface."""
210 __slots__ = ['uri', 'os', 'machine', 'user_override', 'langs']
211 def __init__(self, uri, arch, user_override, langs = None):
212 self.uri = uri
213 # This indicates whether the feed comes from the user's overrides
214 # file. If true, writer.py will write it when saving.
215 self.user_override = user_override
216 self.os, self.machine = _split_arch(arch)
217 self.langs = langs
219 def __str__(self):
220 return "<Feed from %s>" % self.uri
221 __repr__ = __str__
223 arch = property(lambda self: _join_arch(self.os, self.machine))
225 class Dependency(object):
226 """A Dependency indicates that an Implementation requires some additional
227 code to function. This is an abstract base class.
228 @ivar metadata: any extra attributes from the XML element
229 @type metadata: {str: str}
231 __slots__ = ['metadata']
233 def __init__(self, metadata):
234 if metadata is None:
235 metadata = {}
236 else:
237 assert not isinstance(metadata, basestring) # Use InterfaceDependency instead!
238 self.metadata = metadata
240 class InterfaceDependency(Dependency):
241 """A Dependency on a Zero Install interface.
242 @ivar interface: the interface required by this dependency
243 @type interface: str
244 @ivar restrictions: a list of constraints on acceptable implementations
245 @type restrictions: [L{Restriction}]
246 @ivar bindings: how to make the choice of implementation known
247 @type bindings: [L{Binding}]
248 @since: 0.28
250 __slots__ = ['interface', 'restrictions', 'bindings', 'metadata']
252 def __init__(self, interface, restrictions = None, metadata = None):
253 Dependency.__init__(self, metadata)
254 assert isinstance(interface, (str, unicode))
255 assert interface
256 self.interface = interface
257 if restrictions is None:
258 self.restrictions = []
259 else:
260 self.restrictions = restrictions
261 self.bindings = []
263 def __str__(self):
264 return "<Dependency on %s; bindings: %s%s>" % (self.interface, self.bindings, self.restrictions)
266 class RetrievalMethod(object):
267 """A RetrievalMethod provides a way to fetch an implementation."""
268 __slots__ = []
270 class DownloadSource(RetrievalMethod):
271 """A DownloadSource provides a way to fetch an implementation."""
272 __slots__ = ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
274 def __init__(self, implementation, url, size, extract, start_offset = 0, type = None):
275 assert url.startswith('http:') or url.startswith('ftp:') or url.startswith('/')
276 self.implementation = implementation
277 self.url = url
278 self.size = size
279 self.extract = extract
280 self.start_offset = start_offset
281 self.type = type # MIME type - see unpack.py
283 class Recipe(RetrievalMethod):
284 """Get an implementation by following a series of steps.
285 @ivar size: the combined download sizes from all the steps
286 @type size: int
287 @ivar steps: the sequence of steps which must be performed
288 @type steps: [L{RetrievalMethod}]"""
289 __slots__ = ['steps']
291 def __init__(self):
292 self.steps = []
294 size = property(lambda self: sum([x.size for x in self.steps]))
296 class Implementation(object):
297 """An Implementation is a package which implements an Interface.
298 @ivar download_sources: list of methods of getting this implementation
299 @type download_sources: [L{RetrievalMethod}]
300 @ivar feed: the feed owning this implementation (since 0.32)
301 @type feed: [L{ZeroInstallFeed}]
302 @ivar bindings: how to tell this component where it itself is located (since 0.31)
303 @type bindings: [Binding]
306 # Note: user_stability shouldn't really be here
308 __slots__ = ['upstream_stability', 'user_stability', 'langs',
309 'requires', 'main', 'metadata', 'download_sources',
310 'id', 'feed', 'version', 'released', 'bindings']
312 def __init__(self, feed, id):
313 assert id
314 self.feed = feed
315 self.id = id
316 self.main = None
317 self.user_stability = None
318 self.upstream_stability = None
319 self.metadata = {} # [URI + " "] + localName -> value
320 self.requires = []
321 self.version = None
322 self.released = None
323 self.download_sources = []
324 self.langs = None
325 self.bindings = []
327 def get_stability(self):
328 return self.user_stability or self.upstream_stability or testing
330 def __str__(self):
331 return self.id
333 def __repr__(self):
334 return "v%s (%s)" % (self.get_version(), self.id)
336 def __cmp__(self, other):
337 """Newer versions come first"""
338 return cmp(other.version, self.version)
340 def get_version(self):
341 """Return the version as a string.
342 @see: L{format_version}
344 return format_version(self.version)
346 arch = property(lambda self: _join_arch(self.os, self.machine))
348 os = machine = None
350 class DistributionImplementation(Implementation):
351 """An implementation provided by the distribution. Information such as the version
352 comes from the package manager.
353 @since: 0.28"""
354 __slots__ = ['installed']
356 def __init__(self, feed, id):
357 assert id.startswith('package:')
358 Implementation.__init__(self, feed, id)
359 self.installed = True
361 class ZeroInstallImplementation(Implementation):
362 """An implementation where all the information comes from Zero Install.
363 @since: 0.28"""
364 __slots__ = ['os', 'machine', 'upstream_stability', 'user_stability',
365 'size', 'requires', 'main', 'id']
367 def __init__(self, feed, id):
368 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
369 Implementation.__init__(self, feed, id)
370 self.size = None
371 self.os = None
372 self.machine = None
374 # Deprecated
375 dependencies = property(lambda self: dict([(x.interface, x) for x in self.requires
376 if isinstance(x, InterfaceDependency)]))
378 def add_download_source(self, url, size, extract, start_offset = 0, type = None):
379 """Add a download source."""
380 self.download_sources.append(DownloadSource(self, url, size, extract, start_offset, type))
382 def set_arch(self, arch):
383 self.os, self.machine = _split_arch(arch)
384 arch = property(lambda self: _join_arch(self.os, self.machine), set_arch)
386 class Interface(object):
387 """An Interface represents some contract of behaviour.
388 @ivar uri: the URI for this interface.
389 @ivar stability_policy: user's configured policy.
390 Implementations at this level or higher are preferred.
391 Lower levels are used only if there is no other choice.
393 __slots__ = ['uri', 'stability_policy', '_main_feed', 'extra_feeds']
395 implementations = property(lambda self: self._main_feed.implementations)
396 name = property(lambda self: self._main_feed.name)
397 description = property(lambda self: self._main_feed.description)
398 summary = property(lambda self: self._main_feed.summary)
399 last_modified = property(lambda self: self._main_feed.last_modified)
400 feeds = property(lambda self: self.extra_feeds + self._main_feed.feeds)
401 metadata = property(lambda self: self._main_feed.metadata)
403 last_checked = property(lambda self: self._main_feed.last_checked)
405 def __init__(self, uri):
406 assert uri
407 if uri.startswith('http:') or uri.startswith('/'):
408 self.uri = uri
409 else:
410 raise SafeException("Interface name '%s' doesn't start "
411 "with 'http:'" % uri)
412 self.reset()
414 def _get_feed_for(self):
415 retval = {}
416 for key in self._main_feed.feed_for:
417 retval[key] = True
418 return retval
419 feed_for = property(_get_feed_for) # Deprecated (used by 0publish)
421 def reset(self):
422 self.extra_feeds = []
423 self._main_feed = _dummy_feed
424 self.stability_policy = None
426 def get_name(self):
427 if self._main_feed is not _dummy_feed:
428 return self._main_feed.get_name()
429 return '(' + os.path.basename(self.uri) + ')'
431 def __repr__(self):
432 return "<Interface %s>" % self.uri
434 def set_stability_policy(self, new):
435 assert new is None or isinstance(new, Stability)
436 self.stability_policy = new
438 def get_feed(self, url):
439 for x in self.extra_feeds:
440 if x.uri == url:
441 return x
442 return self._main_feed.get_feed(url)
444 def get_metadata(self, uri, name):
445 return self._main_feed.get_metadata(uri, name)
447 def _merge_attrs(attrs, item):
448 """Add each attribute of item to a copy of attrs and return the copy.
449 @type attrs: {str: str}
450 @type item: L{qdom.Element}
451 @rtype: {str: str}
453 new = attrs.copy()
454 for a in item.attrs:
455 new[str(a)] = item.attrs[a]
456 return new
458 def _get_long(elem, attr_name):
459 val = elem.getAttribute(attr_name)
460 if val is not None:
461 try:
462 val = long(val)
463 except ValueError, ex:
464 raise SafeException("Invalid value for integer attribute '%s': %s" % (attr_name, val))
465 return val
467 class ZeroInstallFeed(object):
468 """A feed lists available implementations of an interface.
469 @ivar url: the URL for this feed
470 @ivar implementations: Implementations in this feed, indexed by ID
471 @type implementations: {str: L{Implementation}}
472 @ivar name: human-friendly name
473 @ivar summary: short textual description
474 @ivar description: long textual description
475 @ivar last_modified: timestamp on signature
476 @ivar last_checked: time feed was last successfully downloaded and updated
477 @ivar feeds: list of <feed> elements in this feed
478 @type feeds: [L{Feed}]
479 @ivar feed_for: interfaces for which this could be a feed
480 @type feed_for: set(str)
481 @ivar metadata: extra elements we didn't understand
483 # _main is deprecated
484 __slots__ = ['url', 'implementations', 'name', 'description', 'summary',
485 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
487 def __init__(self, feed_element, local_path = None, distro = None):
488 """Create a feed object from a DOM.
489 @param feed_element: the root element of a feed file
490 @type feed_element: L{qdom.Element}
491 @param interface: temporary hack for restructuring. will go away.
492 @param local_name: the pathname of this local feed, or None for remote feeds
493 @param distro: used to resolve distribution package references
494 @type distro: L{distro.Distribution} or None"""
495 assert feed_element
496 self.implementations = {}
497 self.name = None
498 self.summary = None
499 self.description = ""
500 self.last_modified = None
501 self.feeds = []
502 self.feed_for = set()
503 self.metadata = []
504 self.last_checked = None
506 assert feed_element.name in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
507 assert feed_element.uri == XMLNS_IFACE, "Wrong namespace on root element: %s" % feed_element.uri
509 main = feed_element.getAttribute('main')
510 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
512 if local_path:
513 self.url = local_path
514 local_dir = os.path.dirname(local_path)
515 else:
516 self.url = feed_element.getAttribute('uri')
517 if not self.url:
518 raise InvalidInterface("<interface> uri attribute missing")
519 local_dir = None # Can't have relative paths
521 min_injector_version = feed_element.getAttribute('min-injector-version')
522 if min_injector_version:
523 if parse_version(min_injector_version) > parse_version(version):
524 raise InvalidInterface("This feed requires version %s or later of "
525 "Zero Install, but I am only version %s. "
526 "You can get a newer version from http://0install.net" %
527 (min_injector_version, version))
529 for x in feed_element.childNodes:
530 if x.uri != XMLNS_IFACE:
531 self.metadata.append(x)
532 continue
533 if x.name == 'name':
534 self.name = x.content
535 elif x.name == 'description':
536 self.description = x.content
537 elif x.name == 'summary':
538 self.summary = x.content
539 elif x.name == 'feed-for':
540 feed_iface = x.getAttribute('interface')
541 if not feed_iface:
542 raise InvalidInterface('Missing "interface" attribute in <feed-for>')
543 self.feed_for.add(feed_iface)
544 # Bug report from a Debian/stable user that --feed gets the wrong value.
545 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
546 # in case it happens again.
547 debug("Is feed-for %s", feed_iface)
548 elif x.name == 'feed':
549 feed_src = x.getAttribute('src')
550 if not feed_src:
551 raise InvalidInterface('Missing "src" attribute in <feed>')
552 if feed_src.startswith('http:') or local_path:
553 self.feeds.append(Feed(feed_src, x.getAttribute('arch'), False, langs = x.getAttribute('langs')))
554 else:
555 raise InvalidInterface("Invalid feed URL '%s'" % feed_src)
556 else:
557 self.metadata.append(x)
559 if not self.name:
560 raise InvalidInterface("Missing <name> in feed")
561 if not self.summary:
562 raise InvalidInterface("Missing <summary> in feed")
564 def process_group(group, group_attrs, base_depends, base_bindings):
565 for item in group.childNodes:
566 if item.uri != XMLNS_IFACE: continue
568 if item.name not in ('group', 'implementation', 'package-implementation'):
569 continue
571 depends = base_depends[:]
572 bindings = base_bindings[:]
574 item_attrs = _merge_attrs(group_attrs, item)
576 # We've found a group or implementation. Scan for dependencies
577 # and bindings. Doing this here means that:
578 # - We can share the code for groups and implementations here.
579 # - The order doesn't matter, because these get processed first.
580 # A side-effect is that the document root cannot contain
581 # these.
582 for child in item.childNodes:
583 if child.uri != XMLNS_IFACE: continue
584 if child.name == 'requires':
585 dep = process_depends(child)
586 depends.append(dep)
587 elif child.name in binding_names:
588 bindings.append(process_binding(child))
590 if item.name == 'group':
591 process_group(item, item_attrs, depends, bindings)
592 elif item.name == 'implementation':
593 process_impl(item, item_attrs, depends, bindings)
594 elif item.name == 'package-implementation':
595 process_native_impl(item, item_attrs, depends)
596 else:
597 assert 0
599 def process_impl(item, item_attrs, depends, bindings):
600 id = item.getAttribute('id')
601 if id is None:
602 raise InvalidInterface("Missing 'id' attribute on %s" % item)
603 if local_dir and (id.startswith('/') or id.startswith('.')):
604 impl = self._get_impl(os.path.abspath(os.path.join(local_dir, id)))
605 else:
606 if '=' not in id:
607 raise InvalidInterface('Invalid "id"; form is "alg=value" (got "%s")' % id)
608 alg, sha1 = id.split('=')
609 try:
610 long(sha1, 16)
611 except Exception, ex:
612 raise InvalidInterface('Bad SHA1 attribute: %s' % ex)
613 impl = self._get_impl(id)
615 impl.metadata = item_attrs
616 try:
617 version = item_attrs['version']
618 version_mod = item_attrs.get('version-modifier', None)
619 if version_mod: version += version_mod
620 except KeyError:
621 raise InvalidInterface("Missing version attribute")
622 impl.version = parse_version(version)
624 item_main = item_attrs.get('main', None)
625 if item_main and item_main.startswith('/'):
626 raise InvalidInterface("'main' attribute must be relative, but '%s' starts with '/'!" %
627 item_main)
628 impl.main = item_main
630 impl.released = item_attrs.get('released', None)
631 impl.langs = item_attrs.get('langs', None)
633 size = item.getAttribute('size')
634 if size:
635 impl.size = long(size)
636 impl.arch = item_attrs.get('arch', None)
637 try:
638 stability = stability_levels[str(item_attrs['stability'])]
639 except KeyError:
640 stab = str(item_attrs['stability'])
641 if stab != stab.lower():
642 raise InvalidInterface('Stability "%s" invalid - use lower case!' % item_attrs.stability)
643 raise InvalidInterface('Stability "%s" invalid' % item_attrs['stability'])
644 if stability >= preferred:
645 raise InvalidInterface("Upstream can't set stability to preferred!")
646 impl.upstream_stability = stability
648 impl.bindings = bindings
649 impl.requires = depends
651 for elem in item.childNodes:
652 if elem.uri != XMLNS_IFACE: continue
653 if elem.name == 'archive':
654 url = elem.getAttribute('href')
655 if not url:
656 raise InvalidInterface("Missing href attribute on <archive>")
657 size = elem.getAttribute('size')
658 if not size:
659 raise InvalidInterface("Missing size attribute on <archive>")
660 impl.add_download_source(url = url, size = long(size),
661 extract = elem.getAttribute('extract'),
662 start_offset = _get_long(elem, 'start-offset'),
663 type = elem.getAttribute('type'))
664 elif elem.name == 'recipe':
665 recipe = Recipe()
666 for recipe_step in elem.childNodes:
667 if recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'archive':
668 url = recipe_step.getAttribute('href')
669 if not url:
670 raise InvalidInterface("Missing href attribute on <archive>")
671 size = recipe_step.getAttribute('size')
672 if not size:
673 raise InvalidInterface("Missing size attribute on <archive>")
674 recipe.steps.append(DownloadSource(None, url = url, size = long(size),
675 extract = recipe_step.getAttribute('extract'),
676 start_offset = _get_long(recipe_step, 'start-offset'),
677 type = recipe_step.getAttribute('type')))
678 else:
679 info("Unknown step '%s' in recipe; skipping recipe", recipe_step.name)
680 break
681 else:
682 impl.download_sources.append(recipe)
684 def process_native_impl(item, item_attrs, depends):
685 package = item_attrs.get('package', None)
686 if package is None:
687 raise InvalidInterface("Missing 'package' attribute on %s" % item)
689 def factory(id):
690 assert id.startswith('package:')
691 impl = self._get_impl(id)
693 impl.metadata = item_attrs
695 item_main = item_attrs.get('main', None)
696 if item_main and not item_main.startswith('/'):
697 raise InvalidInterface("'main' attribute must be absolute, but '%s' doesn't start with '/'!" %
698 item_main)
699 impl.main = item_main
700 impl.upstream_stability = packaged
701 impl.requires = depends
703 return impl
705 distro.get_package_info(package, factory)
707 process_group(feed_element,
708 {'stability': 'testing',
709 'main' : main,
711 [], [])
713 def get_name(self):
714 return self.name or '(' + os.path.basename(self.url) + ')'
716 def __repr__(self):
717 return "<Feed %s>" % self.url
719 def _get_impl(self, id):
720 if id not in self.implementations:
721 if id.startswith('package:'):
722 impl = DistributionImplementation(self, id)
723 else:
724 impl = ZeroInstallImplementation(self, id)
725 self.implementations[id] = impl
726 return self.implementations[id]
728 def set_stability_policy(self, new):
729 assert new is None or isinstance(new, Stability)
730 self.stability_policy = new
732 def get_feed(self, url):
733 for x in self.feeds:
734 if x.uri == url:
735 return x
736 return None
738 def add_metadata(self, elem):
739 self.metadata.append(elem)
741 def get_metadata(self, uri, name):
742 """Return a list of interface metadata elements with this name and namespace URI."""
743 return [m for m in self.metadata if m.name == name and m.uri == uri]
745 class DummyFeed(object):
746 last_modified = None
747 name = '-'
748 last_checked = property(lambda self: None)
749 implementations = property(lambda self: {})
750 feeds = property(lambda self: [])
751 summary = property(lambda self: '-')
752 description = property(lambda self: '')
753 def get_name(self): return self.name
754 def get_feed(self, url): return None
755 def get_metadata(self, uri, name): return []
756 _dummy_feed = DummyFeed()
758 def unescape(uri):
759 """Convert each %20 to a space, etc.
760 @rtype: str"""
761 uri = uri.replace('#', '/')
762 if '%' not in uri: return uri
763 return re.sub('%[0-9a-fA-F][0-9a-fA-F]',
764 lambda match: chr(int(match.group(0)[1:], 16)),
765 uri).decode('utf-8')
767 def escape(uri):
768 """Convert each space to %20, etc
769 @rtype: str"""
770 return re.sub('[^-_.a-zA-Z0-9]',
771 lambda match: '%%%02x' % ord(match.group(0)),
772 uri.encode('utf-8'))
774 def _pretty_escape(uri):
775 """Convert each space to %20, etc
776 : is preserved and / becomes #. This makes for nicer strings,
777 and may replace L{escape} everywhere in future.
778 @rtype: str"""
779 return re.sub('[^-_.a-zA-Z0-9:/]',
780 lambda match: '%%%02x' % ord(match.group(0)),
781 uri.encode('utf-8')).replace('/', '#')
783 def canonical_iface_uri(uri):
784 """If uri is a relative path, convert to an absolute one.
785 Otherwise, return it unmodified.
786 @rtype: str
787 @raise SafeException: if uri isn't valid
789 if uri.startswith('http:'):
790 return uri
791 else:
792 iface_uri = os.path.realpath(uri)
793 if os.path.isfile(iface_uri):
794 return iface_uri
795 raise SafeException("Bad interface name '%s'.\n"
796 "(doesn't start with 'http:', and "
797 "doesn't exist as a local file '%s' either)" %
798 (uri, iface_uri))
800 _version_mod_to_value = {
801 'pre': -2,
802 'rc': -1,
803 '': 0,
804 'post': 1,
807 # Reverse mapping
808 _version_value_to_mod = {}
809 for x in _version_mod_to_value: _version_value_to_mod[_version_mod_to_value[x]] = x
810 del x
812 _version_re = re.compile('-([a-z]*)')
814 def parse_version(version_string):
815 """Convert a version string to an internal representation.
816 The parsed format can be compared quickly using the standard Python functions.
817 - Version := DottedList ("-" Mod DottedList?)*
818 - DottedList := (Integer ("." Integer)*)
819 @rtype: tuple (opaque)
820 @raise SafeException: if the string isn't a valid version
821 @since: 0.24 (moved from L{reader}, from where it is still available):"""
822 if version_string is None: return None
823 parts = _version_re.split(version_string)
824 if parts[-1] == '':
825 del parts[-1] # Ends with a modifier
826 else:
827 parts.append('')
828 if not parts:
829 raise SafeException("Empty version string!")
830 l = len(parts)
831 try:
832 for x in range(0, l, 2):
833 part = parts[x]
834 if part:
835 parts[x] = map(int, parts[x].split('.'))
836 else:
837 parts[x] = [] # (because ''.split('.') == [''], not [])
838 for x in range(1, l, 2):
839 parts[x] = _version_mod_to_value[parts[x]]
840 return parts
841 except ValueError, ex:
842 raise SafeException("Invalid version format in '%s': %s" % (version_string, ex))
843 except KeyError, ex:
844 raise SafeException("Invalid version modifier in '%s': %s" % (version_string, ex))
846 def format_version(version):
847 """Format a parsed version for display. Undoes the effect of L{parse_version}.
848 @see: L{Implementation.get_version}
849 @rtype: str
850 @since: 0.24"""
851 version = version[:]
852 l = len(version)
853 for x in range(0, l, 2):
854 version[x] = '.'.join(map(str, version[x]))
855 for x in range(1, l, 2):
856 version[x] = '-' + _version_value_to_mod[version[x]]
857 if version[-1] == '-': del version[-1]
858 return ''.join(version)