Added VersionRangeRestriction subclass of Restriction.
[zeroinstall/zeroinstall-mseaborn.git] / zeroinstall / injector / model.py
blobea761c21b035d9277a70bd9b8ac195af160f46f9
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 VersionRangeRestriction(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__ = []
130 def meets_restriction(self, impl):
131 raise NotImplementedError("Abstract")
133 class VersionRangeRestriction(Restriction):
134 """Only versions within the given range are acceptable"""
135 __slots__ = ['before', 'not_before']
136 def __init__(self, before, not_before):
137 self.before = before
138 self.not_before = not_before
140 def meets_restriction(self, impl):
141 if self.not_before and impl.version < self.not_before:
142 return False
143 if self.before and impl.version >= self.before:
144 return False
145 return True
147 def __str__(self):
148 if self.not_before is not None or self.before is not None:
149 range = ''
150 if self.not_before is not None:
151 range += format_version(self.not_before) + ' <= '
152 range += 'version'
153 if self.before is not None:
154 range += ' < ' + format_version(self.before)
155 else:
156 range = 'none'
157 return "(restriction: %s)" % range
159 class Binding(object):
160 """Information about how the choice of a Dependency is made known
161 to the application being run."""
163 class EnvironmentBinding(Binding):
164 """Indicate the chosen implementation using an environment variable."""
165 __slots__ = ['name', 'insert', 'default', 'mode']
167 PREPEND = 'prepend'
168 APPEND = 'append'
169 REPLACE = 'replace'
171 def __init__(self, name, insert, default = None, mode = PREPEND):
172 """mode argument added in version 0.28"""
173 self.name = name
174 self.insert = insert
175 self.default = default
176 self.mode = mode
178 def __str__(self):
179 return "<environ %s %s %s>" % (self.name, self.mode, self.insert)
181 __repr__ = __str__
183 def get_value(self, path, old_value):
184 """Calculate the new value of the environment variable after applying this binding.
185 @param path: the path to the selected implementation
186 @param old_value: the current value of the environment variable
187 @return: the new value for the environment variable"""
188 extra = os.path.join(path, self.insert)
190 if self.mode == EnvironmentBinding.REPLACE:
191 return extra
193 if old_value is None:
194 old_value = self.default or defaults.get(self.name, None)
195 if old_value is None:
196 return extra
197 if self.mode == EnvironmentBinding.PREPEND:
198 return extra + ':' + old_value
199 else:
200 return old_value + ':' + extra
202 def _toxml(self, doc):
203 """Create a DOM element for this binding.
204 @param doc: document to use to create the element
205 @return: the new element
207 env_elem = doc.createElementNS(XMLNS_IFACE, 'environment')
208 env_elem.setAttributeNS(None, 'name', self.name)
209 env_elem.setAttributeNS(None, 'insert', self.insert)
210 if self.default:
211 env_elem.setAttributeNS(None, 'default', self.default)
212 return env_elem
214 class Feed(object):
215 """An interface's feeds are other interfaces whose implementations can also be
216 used as implementations of this interface."""
217 __slots__ = ['uri', 'os', 'machine', 'user_override', 'langs']
218 def __init__(self, uri, arch, user_override, langs = None):
219 self.uri = uri
220 # This indicates whether the feed comes from the user's overrides
221 # file. If true, writer.py will write it when saving.
222 self.user_override = user_override
223 self.os, self.machine = _split_arch(arch)
224 self.langs = langs
226 def __str__(self):
227 return "<Feed from %s>" % self.uri
228 __repr__ = __str__
230 arch = property(lambda self: _join_arch(self.os, self.machine))
232 class Dependency(object):
233 """A Dependency indicates that an Implementation requires some additional
234 code to function. This is an abstract base class.
235 @ivar metadata: any extra attributes from the XML element
236 @type metadata: {str: str}
238 __slots__ = ['metadata']
240 def __init__(self, metadata):
241 if metadata is None:
242 metadata = {}
243 else:
244 assert not isinstance(metadata, basestring) # Use InterfaceDependency instead!
245 self.metadata = metadata
247 class InterfaceDependency(Dependency):
248 """A Dependency on a Zero Install interface.
249 @ivar interface: the interface required by this dependency
250 @type interface: str
251 @ivar restrictions: a list of constraints on acceptable implementations
252 @type restrictions: [L{Restriction}]
253 @ivar bindings: how to make the choice of implementation known
254 @type bindings: [L{Binding}]
255 @since: 0.28
257 __slots__ = ['interface', 'restrictions', 'bindings', 'metadata']
259 def __init__(self, interface, restrictions = None, metadata = None):
260 Dependency.__init__(self, metadata)
261 assert isinstance(interface, (str, unicode))
262 assert interface
263 self.interface = interface
264 if restrictions is None:
265 self.restrictions = []
266 else:
267 self.restrictions = restrictions
268 self.bindings = []
270 def __str__(self):
271 return "<Dependency on %s; bindings: %s%s>" % (self.interface, self.bindings, self.restrictions)
273 class RetrievalMethod(object):
274 """A RetrievalMethod provides a way to fetch an implementation."""
275 __slots__ = []
277 class DownloadSource(RetrievalMethod):
278 """A DownloadSource provides a way to fetch an implementation."""
279 __slots__ = ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
281 def __init__(self, implementation, url, size, extract, start_offset = 0, type = None):
282 assert url.startswith('http:') or url.startswith('ftp:') or url.startswith('/')
283 self.implementation = implementation
284 self.url = url
285 self.size = size
286 self.extract = extract
287 self.start_offset = start_offset
288 self.type = type # MIME type - see unpack.py
290 class Recipe(RetrievalMethod):
291 """Get an implementation by following a series of steps.
292 @ivar size: the combined download sizes from all the steps
293 @type size: int
294 @ivar steps: the sequence of steps which must be performed
295 @type steps: [L{RetrievalMethod}]"""
296 __slots__ = ['steps']
298 def __init__(self):
299 self.steps = []
301 size = property(lambda self: sum([x.size for x in self.steps]))
303 class Implementation(object):
304 """An Implementation is a package which implements an Interface.
305 @ivar download_sources: list of methods of getting this implementation
306 @type download_sources: [L{RetrievalMethod}]
307 @ivar feed: the feed owning this implementation (since 0.32)
308 @type feed: [L{ZeroInstallFeed}]
309 @ivar bindings: how to tell this component where it itself is located (since 0.31)
310 @type bindings: [Binding]
313 # Note: user_stability shouldn't really be here
315 __slots__ = ['upstream_stability', 'user_stability', 'langs',
316 'requires', 'main', 'metadata', 'download_sources',
317 'id', 'feed', 'version', 'released', 'bindings']
319 def __init__(self, feed, id):
320 assert id
321 self.feed = feed
322 self.id = id
323 self.main = None
324 self.user_stability = None
325 self.upstream_stability = None
326 self.metadata = {} # [URI + " "] + localName -> value
327 self.requires = []
328 self.version = None
329 self.released = None
330 self.download_sources = []
331 self.langs = None
332 self.bindings = []
334 def get_stability(self):
335 return self.user_stability or self.upstream_stability or testing
337 def __str__(self):
338 return self.id
340 def __repr__(self):
341 return "v%s (%s)" % (self.get_version(), self.id)
343 def __cmp__(self, other):
344 """Newer versions come first"""
345 return cmp(other.version, self.version)
347 def get_version(self):
348 """Return the version as a string.
349 @see: L{format_version}
351 return format_version(self.version)
353 arch = property(lambda self: _join_arch(self.os, self.machine))
355 os = machine = None
357 class DistributionImplementation(Implementation):
358 """An implementation provided by the distribution. Information such as the version
359 comes from the package manager.
360 @since: 0.28"""
361 __slots__ = ['installed']
363 def __init__(self, feed, id):
364 assert id.startswith('package:')
365 Implementation.__init__(self, feed, id)
366 self.installed = True
368 class ZeroInstallImplementation(Implementation):
369 """An implementation where all the information comes from Zero Install.
370 @since: 0.28"""
371 __slots__ = ['os', 'machine', 'upstream_stability', 'user_stability',
372 'size', 'requires', 'main', 'id']
374 def __init__(self, feed, id):
375 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
376 Implementation.__init__(self, feed, id)
377 self.size = None
378 self.os = None
379 self.machine = None
381 # Deprecated
382 dependencies = property(lambda self: dict([(x.interface, x) for x in self.requires
383 if isinstance(x, InterfaceDependency)]))
385 def add_download_source(self, url, size, extract, start_offset = 0, type = None):
386 """Add a download source."""
387 self.download_sources.append(DownloadSource(self, url, size, extract, start_offset, type))
389 def set_arch(self, arch):
390 self.os, self.machine = _split_arch(arch)
391 arch = property(lambda self: _join_arch(self.os, self.machine), set_arch)
393 class Interface(object):
394 """An Interface represents some contract of behaviour.
395 @ivar uri: the URI for this interface.
396 @ivar stability_policy: user's configured policy.
397 Implementations at this level or higher are preferred.
398 Lower levels are used only if there is no other choice.
400 __slots__ = ['uri', 'stability_policy', '_main_feed', 'extra_feeds']
402 implementations = property(lambda self: self._main_feed.implementations)
403 name = property(lambda self: self._main_feed.name)
404 description = property(lambda self: self._main_feed.description)
405 summary = property(lambda self: self._main_feed.summary)
406 last_modified = property(lambda self: self._main_feed.last_modified)
407 feeds = property(lambda self: self.extra_feeds + self._main_feed.feeds)
408 metadata = property(lambda self: self._main_feed.metadata)
410 last_checked = property(lambda self: self._main_feed.last_checked)
412 def __init__(self, uri):
413 assert uri
414 if uri.startswith('http:') or uri.startswith('/'):
415 self.uri = uri
416 else:
417 raise SafeException("Interface name '%s' doesn't start "
418 "with 'http:'" % uri)
419 self.reset()
421 def _get_feed_for(self):
422 retval = {}
423 for key in self._main_feed.feed_for:
424 retval[key] = True
425 return retval
426 feed_for = property(_get_feed_for) # Deprecated (used by 0publish)
428 def reset(self):
429 self.extra_feeds = []
430 self._main_feed = _dummy_feed
431 self.stability_policy = None
433 def get_name(self):
434 if self._main_feed is not _dummy_feed:
435 return self._main_feed.get_name()
436 return '(' + os.path.basename(self.uri) + ')'
438 def __repr__(self):
439 return "<Interface %s>" % self.uri
441 def set_stability_policy(self, new):
442 assert new is None or isinstance(new, Stability)
443 self.stability_policy = new
445 def get_feed(self, url):
446 for x in self.extra_feeds:
447 if x.uri == url:
448 return x
449 return self._main_feed.get_feed(url)
451 def get_metadata(self, uri, name):
452 return self._main_feed.get_metadata(uri, name)
454 def _merge_attrs(attrs, item):
455 """Add each attribute of item to a copy of attrs and return the copy.
456 @type attrs: {str: str}
457 @type item: L{qdom.Element}
458 @rtype: {str: str}
460 new = attrs.copy()
461 for a in item.attrs:
462 new[str(a)] = item.attrs[a]
463 return new
465 def _get_long(elem, attr_name):
466 val = elem.getAttribute(attr_name)
467 if val is not None:
468 try:
469 val = long(val)
470 except ValueError, ex:
471 raise SafeException("Invalid value for integer attribute '%s': %s" % (attr_name, val))
472 return val
474 class ZeroInstallFeed(object):
475 """A feed lists available implementations of an interface.
476 @ivar url: the URL for this feed
477 @ivar implementations: Implementations in this feed, indexed by ID
478 @type implementations: {str: L{Implementation}}
479 @ivar name: human-friendly name
480 @ivar summary: short textual description
481 @ivar description: long textual description
482 @ivar last_modified: timestamp on signature
483 @ivar last_checked: time feed was last successfully downloaded and updated
484 @ivar feeds: list of <feed> elements in this feed
485 @type feeds: [L{Feed}]
486 @ivar feed_for: interfaces for which this could be a feed
487 @type feed_for: set(str)
488 @ivar metadata: extra elements we didn't understand
490 # _main is deprecated
491 __slots__ = ['url', 'implementations', 'name', 'description', 'summary',
492 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
494 def __init__(self, feed_element, local_path = None, distro = None):
495 """Create a feed object from a DOM.
496 @param feed_element: the root element of a feed file
497 @type feed_element: L{qdom.Element}
498 @param interface: temporary hack for restructuring. will go away.
499 @param local_name: the pathname of this local feed, or None for remote feeds
500 @param distro: used to resolve distribution package references
501 @type distro: L{distro.Distribution} or None"""
502 assert feed_element
503 self.implementations = {}
504 self.name = None
505 self.summary = None
506 self.description = ""
507 self.last_modified = None
508 self.feeds = []
509 self.feed_for = set()
510 self.metadata = []
511 self.last_checked = None
513 assert feed_element.name in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
514 assert feed_element.uri == XMLNS_IFACE, "Wrong namespace on root element: %s" % feed_element.uri
516 main = feed_element.getAttribute('main')
517 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
519 if local_path:
520 self.url = local_path
521 local_dir = os.path.dirname(local_path)
522 else:
523 self.url = feed_element.getAttribute('uri')
524 if not self.url:
525 raise InvalidInterface("<interface> uri attribute missing")
526 local_dir = None # Can't have relative paths
528 min_injector_version = feed_element.getAttribute('min-injector-version')
529 if min_injector_version:
530 if parse_version(min_injector_version) > parse_version(version):
531 raise InvalidInterface("This feed requires version %s or later of "
532 "Zero Install, but I am only version %s. "
533 "You can get a newer version from http://0install.net" %
534 (min_injector_version, version))
536 for x in feed_element.childNodes:
537 if x.uri != XMLNS_IFACE:
538 self.metadata.append(x)
539 continue
540 if x.name == 'name':
541 self.name = x.content
542 elif x.name == 'description':
543 self.description = x.content
544 elif x.name == 'summary':
545 self.summary = x.content
546 elif x.name == 'feed-for':
547 feed_iface = x.getAttribute('interface')
548 if not feed_iface:
549 raise InvalidInterface('Missing "interface" attribute in <feed-for>')
550 self.feed_for.add(feed_iface)
551 # Bug report from a Debian/stable user that --feed gets the wrong value.
552 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
553 # in case it happens again.
554 debug("Is feed-for %s", feed_iface)
555 elif x.name == 'feed':
556 feed_src = x.getAttribute('src')
557 if not feed_src:
558 raise InvalidInterface('Missing "src" attribute in <feed>')
559 if feed_src.startswith('http:') or local_path:
560 self.feeds.append(Feed(feed_src, x.getAttribute('arch'), False, langs = x.getAttribute('langs')))
561 else:
562 raise InvalidInterface("Invalid feed URL '%s'" % feed_src)
563 else:
564 self.metadata.append(x)
566 if not self.name:
567 raise InvalidInterface("Missing <name> in feed")
568 if not self.summary:
569 raise InvalidInterface("Missing <summary> in feed")
571 def process_group(group, group_attrs, base_depends, base_bindings):
572 for item in group.childNodes:
573 if item.uri != XMLNS_IFACE: continue
575 if item.name not in ('group', 'implementation', 'package-implementation'):
576 continue
578 depends = base_depends[:]
579 bindings = base_bindings[:]
581 item_attrs = _merge_attrs(group_attrs, item)
583 # We've found a group or implementation. Scan for dependencies
584 # and bindings. Doing this here means that:
585 # - We can share the code for groups and implementations here.
586 # - The order doesn't matter, because these get processed first.
587 # A side-effect is that the document root cannot contain
588 # these.
589 for child in item.childNodes:
590 if child.uri != XMLNS_IFACE: continue
591 if child.name == 'requires':
592 dep = process_depends(child)
593 depends.append(dep)
594 elif child.name in binding_names:
595 bindings.append(process_binding(child))
597 if item.name == 'group':
598 process_group(item, item_attrs, depends, bindings)
599 elif item.name == 'implementation':
600 process_impl(item, item_attrs, depends, bindings)
601 elif item.name == 'package-implementation':
602 process_native_impl(item, item_attrs, depends)
603 else:
604 assert 0
606 def process_impl(item, item_attrs, depends, bindings):
607 id = item.getAttribute('id')
608 if id is None:
609 raise InvalidInterface("Missing 'id' attribute on %s" % item)
610 if local_dir and (id.startswith('/') or id.startswith('.')):
611 impl = self._get_impl(os.path.abspath(os.path.join(local_dir, id)))
612 else:
613 if '=' not in id:
614 raise InvalidInterface('Invalid "id"; form is "alg=value" (got "%s")' % id)
615 alg, sha1 = id.split('=')
616 try:
617 long(sha1, 16)
618 except Exception, ex:
619 raise InvalidInterface('Bad SHA1 attribute: %s' % ex)
620 impl = self._get_impl(id)
622 impl.metadata = item_attrs
623 try:
624 version = item_attrs['version']
625 version_mod = item_attrs.get('version-modifier', None)
626 if version_mod: version += version_mod
627 except KeyError:
628 raise InvalidInterface("Missing version attribute")
629 impl.version = parse_version(version)
631 item_main = item_attrs.get('main', None)
632 if item_main and item_main.startswith('/'):
633 raise InvalidInterface("'main' attribute must be relative, but '%s' starts with '/'!" %
634 item_main)
635 impl.main = item_main
637 impl.released = item_attrs.get('released', None)
638 impl.langs = item_attrs.get('langs', None)
640 size = item.getAttribute('size')
641 if size:
642 impl.size = long(size)
643 impl.arch = item_attrs.get('arch', None)
644 try:
645 stability = stability_levels[str(item_attrs['stability'])]
646 except KeyError:
647 stab = str(item_attrs['stability'])
648 if stab != stab.lower():
649 raise InvalidInterface('Stability "%s" invalid - use lower case!' % item_attrs.stability)
650 raise InvalidInterface('Stability "%s" invalid' % item_attrs['stability'])
651 if stability >= preferred:
652 raise InvalidInterface("Upstream can't set stability to preferred!")
653 impl.upstream_stability = stability
655 impl.bindings = bindings
656 impl.requires = depends
658 for elem in item.childNodes:
659 if elem.uri != XMLNS_IFACE: continue
660 if elem.name == 'archive':
661 url = elem.getAttribute('href')
662 if not url:
663 raise InvalidInterface("Missing href attribute on <archive>")
664 size = elem.getAttribute('size')
665 if not size:
666 raise InvalidInterface("Missing size attribute on <archive>")
667 impl.add_download_source(url = url, size = long(size),
668 extract = elem.getAttribute('extract'),
669 start_offset = _get_long(elem, 'start-offset'),
670 type = elem.getAttribute('type'))
671 elif elem.name == 'recipe':
672 recipe = Recipe()
673 for recipe_step in elem.childNodes:
674 if recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'archive':
675 url = recipe_step.getAttribute('href')
676 if not url:
677 raise InvalidInterface("Missing href attribute on <archive>")
678 size = recipe_step.getAttribute('size')
679 if not size:
680 raise InvalidInterface("Missing size attribute on <archive>")
681 recipe.steps.append(DownloadSource(None, url = url, size = long(size),
682 extract = recipe_step.getAttribute('extract'),
683 start_offset = _get_long(recipe_step, 'start-offset'),
684 type = recipe_step.getAttribute('type')))
685 else:
686 info("Unknown step '%s' in recipe; skipping recipe", recipe_step.name)
687 break
688 else:
689 impl.download_sources.append(recipe)
691 def process_native_impl(item, item_attrs, depends):
692 package = item_attrs.get('package', None)
693 if package is None:
694 raise InvalidInterface("Missing 'package' attribute on %s" % item)
696 def factory(id):
697 assert id.startswith('package:')
698 impl = self._get_impl(id)
700 impl.metadata = item_attrs
702 item_main = item_attrs.get('main', None)
703 if item_main and not item_main.startswith('/'):
704 raise InvalidInterface("'main' attribute must be absolute, but '%s' doesn't start with '/'!" %
705 item_main)
706 impl.main = item_main
707 impl.upstream_stability = packaged
708 impl.requires = depends
710 return impl
712 distro.get_package_info(package, factory)
714 process_group(feed_element,
715 {'stability': 'testing',
716 'main' : main,
718 [], [])
720 def get_name(self):
721 return self.name or '(' + os.path.basename(self.url) + ')'
723 def __repr__(self):
724 return "<Feed %s>" % self.url
726 def _get_impl(self, id):
727 if id not in self.implementations:
728 if id.startswith('package:'):
729 impl = DistributionImplementation(self, id)
730 else:
731 impl = ZeroInstallImplementation(self, id)
732 self.implementations[id] = impl
733 return self.implementations[id]
735 def set_stability_policy(self, new):
736 assert new is None or isinstance(new, Stability)
737 self.stability_policy = new
739 def get_feed(self, url):
740 for x in self.feeds:
741 if x.uri == url:
742 return x
743 return None
745 def add_metadata(self, elem):
746 self.metadata.append(elem)
748 def get_metadata(self, uri, name):
749 """Return a list of interface metadata elements with this name and namespace URI."""
750 return [m for m in self.metadata if m.name == name and m.uri == uri]
752 class DummyFeed(object):
753 last_modified = None
754 name = '-'
755 last_checked = property(lambda self: None)
756 implementations = property(lambda self: {})
757 feeds = property(lambda self: [])
758 summary = property(lambda self: '-')
759 description = property(lambda self: '')
760 def get_name(self): return self.name
761 def get_feed(self, url): return None
762 def get_metadata(self, uri, name): return []
763 _dummy_feed = DummyFeed()
765 def unescape(uri):
766 """Convert each %20 to a space, etc.
767 @rtype: str"""
768 uri = uri.replace('#', '/')
769 if '%' not in uri: return uri
770 return re.sub('%[0-9a-fA-F][0-9a-fA-F]',
771 lambda match: chr(int(match.group(0)[1:], 16)),
772 uri).decode('utf-8')
774 def escape(uri):
775 """Convert each space to %20, etc
776 @rtype: str"""
777 return re.sub('[^-_.a-zA-Z0-9]',
778 lambda match: '%%%02x' % ord(match.group(0)),
779 uri.encode('utf-8'))
781 def _pretty_escape(uri):
782 """Convert each space to %20, etc
783 : is preserved and / becomes #. This makes for nicer strings,
784 and may replace L{escape} everywhere in future.
785 @rtype: str"""
786 return re.sub('[^-_.a-zA-Z0-9:/]',
787 lambda match: '%%%02x' % ord(match.group(0)),
788 uri.encode('utf-8')).replace('/', '#')
790 def canonical_iface_uri(uri):
791 """If uri is a relative path, convert to an absolute one.
792 Otherwise, return it unmodified.
793 @rtype: str
794 @raise SafeException: if uri isn't valid
796 if uri.startswith('http:'):
797 return uri
798 else:
799 iface_uri = os.path.realpath(uri)
800 if os.path.isfile(iface_uri):
801 return iface_uri
802 raise SafeException("Bad interface name '%s'.\n"
803 "(doesn't start with 'http:', and "
804 "doesn't exist as a local file '%s' either)" %
805 (uri, iface_uri))
807 _version_mod_to_value = {
808 'pre': -2,
809 'rc': -1,
810 '': 0,
811 'post': 1,
814 # Reverse mapping
815 _version_value_to_mod = {}
816 for x in _version_mod_to_value: _version_value_to_mod[_version_mod_to_value[x]] = x
817 del x
819 _version_re = re.compile('-([a-z]*)')
821 def parse_version(version_string):
822 """Convert a version string to an internal representation.
823 The parsed format can be compared quickly using the standard Python functions.
824 - Version := DottedList ("-" Mod DottedList?)*
825 - DottedList := (Integer ("." Integer)*)
826 @rtype: tuple (opaque)
827 @raise SafeException: if the string isn't a valid version
828 @since: 0.24 (moved from L{reader}, from where it is still available):"""
829 if version_string is None: return None
830 parts = _version_re.split(version_string)
831 if parts[-1] == '':
832 del parts[-1] # Ends with a modifier
833 else:
834 parts.append('')
835 if not parts:
836 raise SafeException("Empty version string!")
837 l = len(parts)
838 try:
839 for x in range(0, l, 2):
840 part = parts[x]
841 if part:
842 parts[x] = map(int, parts[x].split('.'))
843 else:
844 parts[x] = [] # (because ''.split('.') == [''], not [])
845 for x in range(1, l, 2):
846 parts[x] = _version_mod_to_value[parts[x]]
847 return parts
848 except ValueError, ex:
849 raise SafeException("Invalid version format in '%s': %s" % (version_string, ex))
850 except KeyError, ex:
851 raise SafeException("Invalid version modifier in '%s': %s" % (version_string, ex))
853 def format_version(version):
854 """Format a parsed version for display. Undoes the effect of L{parse_version}.
855 @see: L{Implementation.get_version}
856 @rtype: str
857 @since: 0.24"""
858 version = version[:]
859 l = len(version)
860 for x in range(0, l, 2):
861 version[x] = '.'.join(map(str, version[x]))
862 for x in range(1, l, 2):
863 version[x] = '-' + _version_value_to_mod[version[x]]
864 if version[-1] == '-': del version[-1]
865 return ''.join(version)