ZeroInstallFeed._get_impl always creates a new Implementation
[zeroinstall.git] / zeroinstall / injector / model.py
blobbba01fcf1508f0591eb21829852363df3e6d9491
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
7 @see: U{http://0install.net/interface-spec.html} description of the domain model
9 @var defaults: Default values for the 'default' attribute for <environment> bindings of
10 well-known variables.
11 """
13 # Copyright (C) 2009, Thomas Leonard
14 # See the README file for details, or visit http://0install.net.
16 from zeroinstall import _
17 import os, re
18 from logging import info, debug
19 from zeroinstall import SafeException, version
20 from zeroinstall.injector.namespaces import XMLNS_IFACE
22 # Element names for bindings in feed files
23 binding_names = frozenset(['environment', 'overlay'])
25 network_offline = 'off-line'
26 network_minimal = 'minimal'
27 network_full = 'full'
28 network_levels = (network_offline, network_minimal, network_full)
30 stability_levels = {} # Name -> Stability
32 defaults = {
33 'PATH': '/bin:/usr/bin',
34 'XDG_CONFIG_DIRS': '/etc/xdg',
35 'XDG_DATA_DIRS': '/usr/local/share:/usr/share',
38 class InvalidInterface(SafeException):
39 """Raised when parsing an invalid feed."""
40 def __init__(self, message, ex = None):
41 if ex:
42 message += "\n\n(exact error: %s)" % ex
43 SafeException.__init__(self, message)
45 def _split_arch(arch):
46 """Split an arch into an (os, machine) tuple. Either or both parts may be None."""
47 if not arch:
48 return None, None
49 elif '-' not in arch:
50 raise SafeException(_("Malformed arch '%s'") % arch)
51 else:
52 osys, machine = arch.split('-', 1)
53 if osys == '*': osys = None
54 if machine == '*': machine = None
55 return osys, machine
57 def _join_arch(osys, machine):
58 if osys == machine == None: return None
59 return "%s-%s" % (osys or '*', machine or '*')
61 class Stability(object):
62 """A stability rating. Each implementation has an upstream stability rating and,
63 optionally, a user-set rating."""
64 __slots__ = ['level', 'name', 'description']
65 def __init__(self, level, name, description):
66 self.level = level
67 self.name = name
68 self.description = description
69 assert name not in stability_levels
70 stability_levels[name] = self
72 def __cmp__(self, other):
73 return cmp(self.level, other.level)
75 def __str__(self):
76 return self.name
78 def __repr__(self):
79 return _("<Stability: %s>") % self.description
81 def process_binding(e):
82 """Internal"""
83 if e.name == 'environment':
84 mode = {
85 None: EnvironmentBinding.PREPEND,
86 'prepend': EnvironmentBinding.PREPEND,
87 'append': EnvironmentBinding.APPEND,
88 'replace': EnvironmentBinding.REPLACE,
89 }[e.getAttribute('mode')]
91 binding = EnvironmentBinding(e.getAttribute('name'),
92 insert = e.getAttribute('insert'),
93 default = e.getAttribute('default'),
94 mode = mode)
95 if not binding.name: raise InvalidInterface(_("Missing 'name' in binding"))
96 if binding.insert is None: raise InvalidInterface(_("Missing 'insert' in binding"))
97 return binding
98 elif e.name == 'overlay':
99 return OverlayBinding(e.getAttribute('src'), e.getAttribute('mount-point'))
100 else:
101 raise Exception(_("Unknown binding type '%s'") % e.name)
103 def process_depends(item):
104 """Internal"""
105 # Note: also called from selections
106 dep_iface = item.getAttribute('interface')
107 if not dep_iface:
108 raise InvalidInterface(_("Missing 'interface' on <requires>"))
109 dependency = InterfaceDependency(dep_iface, metadata = item.attrs)
111 for e in item.childNodes:
112 if e.uri != XMLNS_IFACE: continue
113 if e.name in binding_names:
114 dependency.bindings.append(process_binding(e))
115 elif e.name == 'version':
116 dependency.restrictions.append(
117 VersionRangeRestriction(not_before = parse_version(e.getAttribute('not-before')),
118 before = parse_version(e.getAttribute('before'))))
119 return dependency
121 def N_(message): return message
123 insecure = Stability(0, N_('insecure'), _('This is a security risk'))
124 buggy = Stability(5, N_('buggy'), _('Known to have serious bugs'))
125 developer = Stability(10, N_('developer'), _('Work-in-progress - bugs likely'))
126 testing = Stability(20, N_('testing'), _('Stability unknown - please test!'))
127 stable = Stability(30, N_('stable'), _('Tested - no serious problems found'))
128 packaged = Stability(35, N_('packaged'), _('Supplied by the local package manager'))
129 preferred = Stability(40, N_('preferred'), _('Best of all - must be set manually'))
131 del N_
133 class Restriction(object):
134 """A Restriction limits the allowed implementations of an Interface."""
135 __slots__ = []
137 def meets_restriction(self, impl):
138 """Called by the L{Solver} to check whether a particular implementation is acceptable.
139 @return: False if this implementation is not a possibility
140 @rtype: bool
142 raise NotImplementedError(_("Abstract"))
144 class VersionRestriction(Restriction):
145 """Only select implementations with a particular version number.
146 @since: 0.40"""
148 def __init__(self, version):
149 """@param version: the required version number
150 @see: L{parse_version}; use this to pre-process the version number
152 self.version = version
154 def meets_restriction(self, impl):
155 return impl.version == self.version
157 def __str__(self):
158 return _("(restriction: version = %s)") % format_version(self.version)
160 class VersionRangeRestriction(Restriction):
161 """Only versions within the given range are acceptable"""
162 __slots__ = ['before', 'not_before']
164 def __init__(self, before, not_before):
165 """@param before: chosen versions must be earlier than this
166 @param not_before: versions must be at least this high
167 @see: L{parse_version}; use this to pre-process the versions
169 self.before = before
170 self.not_before = not_before
172 def meets_restriction(self, impl):
173 if self.not_before and impl.version < self.not_before:
174 return False
175 if self.before and impl.version >= self.before:
176 return False
177 return True
179 def __str__(self):
180 if self.not_before is not None or self.before is not None:
181 range = ''
182 if self.not_before is not None:
183 range += format_version(self.not_before) + ' <= '
184 range += 'version'
185 if self.before is not None:
186 range += ' < ' + format_version(self.before)
187 else:
188 range = 'none'
189 return _("(restriction: %s)") % range
191 class Binding(object):
192 """Information about how the choice of a Dependency is made known
193 to the application being run."""
195 class EnvironmentBinding(Binding):
196 """Indicate the chosen implementation using an environment variable."""
197 __slots__ = ['name', 'insert', 'default', 'mode']
199 PREPEND = 'prepend'
200 APPEND = 'append'
201 REPLACE = 'replace'
203 def __init__(self, name, insert, default = None, mode = PREPEND):
204 """mode argument added in version 0.28"""
205 self.name = name
206 self.insert = insert
207 self.default = default
208 self.mode = mode
210 def __str__(self):
211 return _("<environ %(name)s %(mode)s %(insert)s>") % {'name': self.name,'mode': self.mode, 'insert': self.insert}
213 __repr__ = __str__
215 def get_value(self, path, old_value):
216 """Calculate the new value of the environment variable after applying this binding.
217 @param path: the path to the selected implementation
218 @param old_value: the current value of the environment variable
219 @return: the new value for the environment variable"""
220 extra = os.path.join(path, self.insert)
222 if self.mode == EnvironmentBinding.REPLACE:
223 return extra
225 if old_value is None:
226 old_value = self.default or defaults.get(self.name, None)
227 if old_value is None:
228 return extra
229 if self.mode == EnvironmentBinding.PREPEND:
230 return extra + ':' + old_value
231 else:
232 return old_value + ':' + extra
234 def _toxml(self, doc):
235 """Create a DOM element for this binding.
236 @param doc: document to use to create the element
237 @return: the new element
239 env_elem = doc.createElementNS(XMLNS_IFACE, 'environment')
240 env_elem.setAttributeNS(None, 'name', self.name)
241 env_elem.setAttributeNS(None, 'insert', self.insert)
242 if self.default:
243 env_elem.setAttributeNS(None, 'default', self.default)
244 return env_elem
246 class OverlayBinding(Binding):
247 """Make the chosen implementation available by overlaying it onto another part of the file-system.
248 This is to support legacy programs which use hard-coded paths."""
249 __slots__ = ['src', 'mount_point']
251 def __init__(self, src, mount_point):
252 self.src = src
253 self.mount_point = mount_point
255 def __str__(self):
256 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self.src or '.', 'mount_point': self.mount_point or '/'}
258 __repr__ = __str__
260 def _toxml(self, doc):
261 """Create a DOM element for this binding.
262 @param doc: document to use to create the element
263 @return: the new element
265 env_elem = doc.createElementNS(XMLNS_IFACE, 'overlay')
266 if self.src is not None:
267 env_elem.setAttributeNS(None, 'src', self.src)
268 if self.mount_point is not None:
269 env_elem.setAttributeNS(None, 'mount-point', self.mount_point)
270 return env_elem
272 class Feed(object):
273 """An interface's feeds are other interfaces whose implementations can also be
274 used as implementations of this interface."""
275 __slots__ = ['uri', 'os', 'machine', 'user_override', 'langs']
276 def __init__(self, uri, arch, user_override, langs = None):
277 self.uri = uri
278 # This indicates whether the feed comes from the user's overrides
279 # file. If true, writer.py will write it when saving.
280 self.user_override = user_override
281 self.os, self.machine = _split_arch(arch)
282 self.langs = langs
284 def __str__(self):
285 return "<Feed from %s>" % self.uri
286 __repr__ = __str__
288 arch = property(lambda self: _join_arch(self.os, self.machine))
290 class Dependency(object):
291 """A Dependency indicates that an Implementation requires some additional
292 code to function. This is an abstract base class.
293 @ivar metadata: any extra attributes from the XML element
294 @type metadata: {str: str}
296 __slots__ = ['metadata']
298 def __init__(self, metadata):
299 if metadata is None:
300 metadata = {}
301 else:
302 assert not isinstance(metadata, basestring) # Use InterfaceDependency instead!
303 self.metadata = metadata
305 class InterfaceDependency(Dependency):
306 """A Dependency on a Zero Install interface.
307 @ivar interface: the interface required by this dependency
308 @type interface: str
309 @ivar restrictions: a list of constraints on acceptable implementations
310 @type restrictions: [L{Restriction}]
311 @ivar bindings: how to make the choice of implementation known
312 @type bindings: [L{Binding}]
313 @since: 0.28
315 __slots__ = ['interface', 'restrictions', 'bindings', 'metadata']
317 def __init__(self, interface, restrictions = None, metadata = None):
318 Dependency.__init__(self, metadata)
319 assert isinstance(interface, (str, unicode))
320 assert interface
321 self.interface = interface
322 if restrictions is None:
323 self.restrictions = []
324 else:
325 self.restrictions = restrictions
326 self.bindings = []
328 def __str__(self):
329 return _("<Dependency on %(interface)s; bindings: %(bindings)s%(restrictions)s>") % {'interface': self.interface, 'bindings': self.bindings, 'restrictions': self.restrictions}
331 class RetrievalMethod(object):
332 """A RetrievalMethod provides a way to fetch an implementation."""
333 __slots__ = []
335 class DownloadSource(RetrievalMethod):
336 """A DownloadSource provides a way to fetch an implementation."""
337 __slots__ = ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
339 def __init__(self, implementation, url, size, extract, start_offset = 0, type = None):
340 self.implementation = implementation
341 self.url = url
342 self.size = size
343 self.extract = extract
344 self.start_offset = start_offset
345 self.type = type # MIME type - see unpack.py
347 class Recipe(RetrievalMethod):
348 """Get an implementation by following a series of steps.
349 @ivar size: the combined download sizes from all the steps
350 @type size: int
351 @ivar steps: the sequence of steps which must be performed
352 @type steps: [L{RetrievalMethod}]"""
353 __slots__ = ['steps']
355 def __init__(self):
356 self.steps = []
358 size = property(lambda self: sum([x.size for x in self.steps]))
360 class Implementation(object):
361 """An Implementation is a package which implements an Interface.
362 @ivar download_sources: list of methods of getting this implementation
363 @type download_sources: [L{RetrievalMethod}]
364 @ivar feed: the feed owning this implementation (since 0.32)
365 @type feed: [L{ZeroInstallFeed}]
366 @ivar bindings: how to tell this component where it itself is located (since 0.31)
367 @type bindings: [Binding]
368 @ivar upstream_stability: the stability reported by the packager
369 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged]
370 @ivar user_stability: the stability as set by the user
371 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred]
372 @ivar langs: natural languages supported by this package
373 @ivar requires: interfaces this package depends on
374 @ivar main: the default file to execute when running as a program
375 @ivar metadata: extra metadata from the feed
376 @type metadata: {"[URI ]localName": str}
377 @ivar id: a unique identifier for this Implementation
378 @ivar version: a parsed version number
379 @ivar released: release date
382 # Note: user_stability shouldn't really be here
384 __slots__ = ['upstream_stability', 'user_stability', 'langs',
385 'requires', 'main', 'metadata', 'download_sources',
386 'id', 'feed', 'version', 'released', 'bindings', 'machine']
388 def __init__(self, feed, id):
389 assert id
390 self.feed = feed
391 self.id = id
392 self.main = None
393 self.user_stability = None
394 self.upstream_stability = None
395 self.metadata = {} # [URI + " "] + localName -> value
396 self.requires = []
397 self.version = None
398 self.released = None
399 self.download_sources = []
400 self.langs = None
401 self.machine = None
402 self.bindings = []
404 def get_stability(self):
405 return self.user_stability or self.upstream_stability or testing
407 def __str__(self):
408 return self.id
410 def __repr__(self):
411 return "v%s (%s)" % (self.get_version(), self.id)
413 def __cmp__(self, other):
414 """Newer versions come first"""
415 return cmp(other.version, self.version)
417 def get_version(self):
418 """Return the version as a string.
419 @see: L{format_version}
421 return format_version(self.version)
423 arch = property(lambda self: _join_arch(self.os, self.machine))
425 os = None
427 class DistributionImplementation(Implementation):
428 """An implementation provided by the distribution. Information such as the version
429 comes from the package manager.
430 @since: 0.28"""
431 __slots__ = ['installed']
433 def __init__(self, feed, id):
434 assert id.startswith('package:')
435 Implementation.__init__(self, feed, id)
436 self.installed = True
438 class ZeroInstallImplementation(Implementation):
439 """An implementation where all the information comes from Zero Install.
440 @since: 0.28"""
441 __slots__ = ['os', 'size']
443 def __init__(self, feed, id):
444 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
445 Implementation.__init__(self, feed, id)
446 self.size = None
447 self.os = None
449 # Deprecated
450 dependencies = property(lambda self: dict([(x.interface, x) for x in self.requires
451 if isinstance(x, InterfaceDependency)]))
453 def add_download_source(self, url, size, extract, start_offset = 0, type = None):
454 """Add a download source."""
455 self.download_sources.append(DownloadSource(self, url, size, extract, start_offset, type))
457 def set_arch(self, arch):
458 self.os, self.machine = _split_arch(arch)
459 arch = property(lambda self: _join_arch(self.os, self.machine), set_arch)
461 class Interface(object):
462 """An Interface represents some contract of behaviour.
463 @ivar uri: the URI for this interface.
464 @ivar stability_policy: user's configured policy.
465 Implementations at this level or higher are preferred.
466 Lower levels are used only if there is no other choice.
468 __slots__ = ['uri', 'stability_policy', '_main_feed', 'extra_feeds']
470 implementations = property(lambda self: self._main_feed.implementations)
471 name = property(lambda self: self._main_feed.name)
472 description = property(lambda self: self._main_feed.description)
473 summary = property(lambda self: self._main_feed.summary)
474 last_modified = property(lambda self: self._main_feed.last_modified)
475 feeds = property(lambda self: self.extra_feeds + self._main_feed.feeds)
476 metadata = property(lambda self: self._main_feed.metadata)
478 last_checked = property(lambda self: self._main_feed.last_checked)
480 def __init__(self, uri):
481 assert uri
482 if uri.startswith('http:') or uri.startswith('https:') or uri.startswith('/'):
483 self.uri = uri
484 else:
485 raise SafeException(_("Interface name '%s' doesn't start "
486 "with 'http:' or 'https:'") % uri)
487 self.reset()
489 def _get_feed_for(self):
490 retval = {}
491 for key in self._main_feed.feed_for:
492 retval[key] = True
493 return retval
494 feed_for = property(_get_feed_for) # Deprecated (used by 0publish)
496 def reset(self):
497 self.extra_feeds = []
498 self._main_feed = _dummy_feed
499 self.stability_policy = None
501 def get_name(self):
502 if self._main_feed is not _dummy_feed:
503 return self._main_feed.get_name()
504 return '(' + os.path.basename(self.uri) + ')'
506 def __repr__(self):
507 return _("<Interface %s>") % self.uri
509 def set_stability_policy(self, new):
510 assert new is None or isinstance(new, Stability)
511 self.stability_policy = new
513 def get_feed(self, url):
514 for x in self.extra_feeds:
515 if x.uri == url:
516 return x
517 return self._main_feed.get_feed(url)
519 def get_metadata(self, uri, name):
520 return self._main_feed.get_metadata(uri, name)
522 def _merge_attrs(attrs, item):
523 """Add each attribute of item to a copy of attrs and return the copy.
524 @type attrs: {str: str}
525 @type item: L{qdom.Element}
526 @rtype: {str: str}
528 new = attrs.copy()
529 for a in item.attrs:
530 new[str(a)] = item.attrs[a]
531 return new
533 def _get_long(elem, attr_name):
534 val = elem.getAttribute(attr_name)
535 if val is not None:
536 try:
537 val = long(val)
538 except ValueError, ex:
539 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name, 'value': val})
540 return val
542 class ZeroInstallFeed(object):
543 """A feed lists available implementations of an interface.
544 @ivar url: the URL for this feed
545 @ivar implementations: Implementations in this feed, indexed by ID
546 @type implementations: {str: L{Implementation}}
547 @ivar name: human-friendly name
548 @ivar summary: short textual description
549 @ivar description: long textual description
550 @ivar last_modified: timestamp on signature
551 @ivar last_checked: time feed was last successfully downloaded and updated
552 @ivar feeds: list of <feed> elements in this feed
553 @type feeds: [L{Feed}]
554 @ivar feed_for: interfaces for which this could be a feed
555 @type feed_for: set(str)
556 @ivar metadata: extra elements we didn't understand
558 # _main is deprecated
559 __slots__ = ['url', 'implementations', 'name', 'description', 'summary',
560 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
562 def __init__(self, feed_element, local_path = None, distro = None):
563 """Create a feed object from a DOM.
564 @param feed_element: the root element of a feed file
565 @type feed_element: L{qdom.Element}
566 @param local_path: the pathname of this local feed, or None for remote feeds
567 @param distro: used to resolve distribution package references
568 @type distro: L{distro.Distribution} or None"""
569 assert feed_element
570 self.implementations = {}
571 self.name = None
572 self.summary = None
573 self.description = ""
574 self.last_modified = None
575 self.feeds = []
576 self.feed_for = set()
577 self.metadata = []
578 self.last_checked = None
580 assert feed_element.name in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
581 assert feed_element.uri == XMLNS_IFACE, "Wrong namespace on root element: %s" % feed_element.uri
583 main = feed_element.getAttribute('main')
584 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
586 if local_path:
587 self.url = local_path
588 local_dir = os.path.dirname(local_path)
589 else:
590 self.url = feed_element.getAttribute('uri')
591 if not self.url:
592 raise InvalidInterface(_("<interface> uri attribute missing"))
593 local_dir = None # Can't have relative paths
595 min_injector_version = feed_element.getAttribute('min-injector-version')
596 if min_injector_version:
597 if parse_version(min_injector_version) > parse_version(version):
598 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
599 "Zero Install, but I am only version %(version)s. "
600 "You can get a newer version from http://0install.net") %
601 {'min_version': min_injector_version, 'version': version})
603 for x in feed_element.childNodes:
604 if x.uri != XMLNS_IFACE:
605 self.metadata.append(x)
606 continue
607 if x.name == 'name':
608 self.name = x.content
609 elif x.name == 'description':
610 self.description = x.content
611 elif x.name == 'summary':
612 self.summary = x.content
613 elif x.name == 'feed-for':
614 feed_iface = x.getAttribute('interface')
615 if not feed_iface:
616 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
617 self.feed_for.add(feed_iface)
618 # Bug report from a Debian/stable user that --feed gets the wrong value.
619 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
620 # in case it happens again.
621 debug(_("Is feed-for %s"), feed_iface)
622 elif x.name == 'feed':
623 feed_src = x.getAttribute('src')
624 if not feed_src:
625 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
626 if feed_src.startswith('http:') or local_path:
627 self.feeds.append(Feed(feed_src, x.getAttribute('arch'), False, langs = x.getAttribute('langs')))
628 else:
629 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src)
630 else:
631 self.metadata.append(x)
633 if not self.name:
634 raise InvalidInterface(_("Missing <name> in feed"))
635 if not self.summary:
636 raise InvalidInterface(_("Missing <summary> in feed"))
638 package_impls = [0, []] # Best score so far and packages with that score
640 def process_group(group, group_attrs, base_depends, base_bindings):
641 for item in group.childNodes:
642 if item.uri != XMLNS_IFACE: continue
644 if item.name not in ('group', 'implementation', 'package-implementation'):
645 continue
647 depends = base_depends[:]
648 bindings = base_bindings[:]
650 item_attrs = _merge_attrs(group_attrs, item)
652 # We've found a group or implementation. Scan for dependencies
653 # and bindings. Doing this here means that:
654 # - We can share the code for groups and implementations here.
655 # - The order doesn't matter, because these get processed first.
656 # A side-effect is that the document root cannot contain
657 # these.
658 for child in item.childNodes:
659 if child.uri != XMLNS_IFACE: continue
660 if child.name == 'requires':
661 dep = process_depends(child)
662 depends.append(dep)
663 elif child.name in binding_names:
664 bindings.append(process_binding(child))
666 if item.name == 'group':
667 process_group(item, item_attrs, depends, bindings)
668 elif item.name == 'implementation':
669 process_impl(item, item_attrs, depends, bindings)
670 elif item.name == 'package-implementation':
671 distro_names = item_attrs.get('distributions', '')
672 for distro_name in distro_names.split(' '):
673 score = distro.get_score(distro_name)
674 if score > package_impls[0]:
675 package_impls[0] = score
676 package_impls[1] = []
677 if score == package_impls[0]:
678 package_impls[1].append((item, item_attrs, depends))
679 else:
680 assert 0
682 def process_impl(item, item_attrs, depends, bindings):
683 id = item.getAttribute('id')
684 if id is None:
685 raise InvalidInterface(_("Missing 'id' attribute on %s") % item)
686 if local_dir and (id.startswith('/') or id.startswith('.')):
687 impl = self._get_impl(os.path.abspath(os.path.join(local_dir, id)))
688 else:
689 if '=' not in id:
690 raise InvalidInterface(_('Invalid "id"; form is "alg=value" (got "%s")') % id)
691 alg, sha1 = id.split('=')
692 try:
693 long(sha1, 16)
694 except Exception, ex:
695 raise InvalidInterface(_('Bad SHA1 attribute: %s') % ex)
696 impl = self._get_impl(id)
698 impl.metadata = item_attrs
699 try:
700 version_mod = item_attrs.get('version-modifier', None)
701 if version_mod:
702 item_attrs['version'] += version_mod
703 del item_attrs['version-modifier']
704 version = item_attrs['version']
705 except KeyError:
706 raise InvalidInterface(_("Missing version attribute"))
707 impl.version = parse_version(version)
709 item_main = item_attrs.get('main', None)
710 if item_main and item_main.startswith('/'):
711 raise InvalidInterface(_("'main' attribute must be relative, but '%s' starts with '/'!") %
712 item_main)
713 impl.main = item_main
715 impl.released = item_attrs.get('released', None)
716 impl.langs = item_attrs.get('langs', None)
718 size = item.getAttribute('size')
719 if size:
720 impl.size = long(size)
721 impl.arch = item_attrs.get('arch', None)
722 try:
723 stability = stability_levels[str(item_attrs['stability'])]
724 except KeyError:
725 stab = str(item_attrs['stability'])
726 if stab != stab.lower():
727 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs.stability)
728 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs['stability'])
729 if stability >= preferred:
730 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
731 impl.upstream_stability = stability
733 impl.bindings = bindings
734 impl.requires = depends
736 for elem in item.childNodes:
737 if elem.uri != XMLNS_IFACE: continue
738 if elem.name == 'archive':
739 url = elem.getAttribute('href')
740 if not url:
741 raise InvalidInterface(_("Missing href attribute on <archive>"))
742 size = elem.getAttribute('size')
743 if not size:
744 raise InvalidInterface(_("Missing size attribute on <archive>"))
745 impl.add_download_source(url = url, size = long(size),
746 extract = elem.getAttribute('extract'),
747 start_offset = _get_long(elem, 'start-offset'),
748 type = elem.getAttribute('type'))
749 elif elem.name == 'recipe':
750 recipe = Recipe()
751 for recipe_step in elem.childNodes:
752 if recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'archive':
753 url = recipe_step.getAttribute('href')
754 if not url:
755 raise InvalidInterface(_("Missing href attribute on <archive>"))
756 size = recipe_step.getAttribute('size')
757 if not size:
758 raise InvalidInterface(_("Missing size attribute on <archive>"))
759 recipe.steps.append(DownloadSource(None, url = url, size = long(size),
760 extract = recipe_step.getAttribute('extract'),
761 start_offset = _get_long(recipe_step, 'start-offset'),
762 type = recipe_step.getAttribute('type')))
763 else:
764 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step.name)
765 break
766 else:
767 impl.download_sources.append(recipe)
769 def process_native_impl(item, item_attrs, depends):
770 package = item_attrs.get('package', None)
771 if package is None:
772 raise InvalidInterface(_("Missing 'package' attribute on %s") % item)
774 def factory(id):
775 assert id.startswith('package:')
776 impl = self._get_impl(id)
778 impl.metadata = item_attrs
780 item_main = item_attrs.get('main', None)
781 if item_main and not item_main.startswith('/'):
782 raise InvalidInterface(_("'main' attribute must be absolute, but '%s' doesn't start with '/'!") %
783 item_main)
784 impl.main = item_main
785 impl.upstream_stability = packaged
786 impl.requires = depends
788 return impl
790 distro.get_package_info(package, factory)
792 root_attrs = {'stability': 'testing'}
793 if main:
794 root_attrs['main'] = main
795 process_group(feed_element, root_attrs, [], [])
797 for args in package_impls[1]:
798 process_native_impl(*args)
800 def get_name(self):
801 return self.name or '(' + os.path.basename(self.url) + ')'
803 def __repr__(self):
804 return _("<Feed %s>") % self.url
806 def _get_impl(self, id):
807 assert id not in self.implementations
808 if id.startswith('package:'):
809 impl = DistributionImplementation(self, id)
810 else:
811 impl = ZeroInstallImplementation(self, id)
812 self.implementations[id] = impl
813 return impl
815 def set_stability_policy(self, new):
816 assert new is None or isinstance(new, Stability)
817 self.stability_policy = new
819 def get_feed(self, url):
820 for x in self.feeds:
821 if x.uri == url:
822 return x
823 return None
825 def add_metadata(self, elem):
826 self.metadata.append(elem)
828 def get_metadata(self, uri, name):
829 """Return a list of interface metadata elements with this name and namespace URI."""
830 return [m for m in self.metadata if m.name == name and m.uri == uri]
832 class DummyFeed(object):
833 """Temporary class used during API transition."""
834 last_modified = None
835 name = '-'
836 last_checked = property(lambda self: None)
837 implementations = property(lambda self: {})
838 feeds = property(lambda self: [])
839 summary = property(lambda self: '-')
840 description = property(lambda self: '')
841 def get_name(self): return self.name
842 def get_feed(self, url): return None
843 def get_metadata(self, uri, name): return []
844 _dummy_feed = DummyFeed()
846 def unescape(uri):
847 """Convert each %20 to a space, etc.
848 @rtype: str"""
849 uri = uri.replace('#', '/')
850 if '%' not in uri: return uri
851 return re.sub('%[0-9a-fA-F][0-9a-fA-F]',
852 lambda match: chr(int(match.group(0)[1:], 16)),
853 uri).decode('utf-8')
855 def escape(uri):
856 """Convert each space to %20, etc
857 @rtype: str"""
858 return re.sub('[^-_.a-zA-Z0-9]',
859 lambda match: '%%%02x' % ord(match.group(0)),
860 uri.encode('utf-8'))
862 def _pretty_escape(uri):
863 """Convert each space to %20, etc
864 : is preserved and / becomes #. This makes for nicer strings,
865 and may replace L{escape} everywhere in future.
866 @rtype: str"""
867 return re.sub('[^-_.a-zA-Z0-9:/]',
868 lambda match: '%%%02x' % ord(match.group(0)),
869 uri.encode('utf-8')).replace('/', '#')
871 def canonical_iface_uri(uri):
872 """If uri is a relative path, convert to an absolute one.
873 A "file:///foo" URI is converted to "/foo".
874 Otherwise, return it unmodified.
875 @rtype: str
876 @raise SafeException: if uri isn't valid
878 if uri.startswith('http://') or uri.startswith('https://'):
879 if uri.count("/") < 3:
880 raise SafeException(_("Missing / after hostname in URI '%s'") % uri)
881 return uri
882 elif uri.startswith('file:///'):
883 return uri[7:]
884 else:
885 iface_uri = os.path.realpath(uri)
886 if os.path.isfile(iface_uri):
887 return iface_uri
888 raise SafeException(_("Bad interface name '%(uri)s'.\n"
889 "(doesn't start with 'http:', and "
890 "doesn't exist as a local file '%(interface_uri)s' either)") %
891 {'uri': uri, 'interface_uri': iface_uri})
893 _version_mod_to_value = {
894 'pre': -2,
895 'rc': -1,
896 '': 0,
897 'post': 1,
900 # Reverse mapping
901 _version_value_to_mod = {}
902 for x in _version_mod_to_value: _version_value_to_mod[_version_mod_to_value[x]] = x
903 del x
905 _version_re = re.compile('-([a-z]*)')
907 def parse_version(version_string):
908 """Convert a version string to an internal representation.
909 The parsed format can be compared quickly using the standard Python functions.
910 - Version := DottedList ("-" Mod DottedList?)*
911 - DottedList := (Integer ("." Integer)*)
912 @rtype: tuple (opaque)
913 @raise SafeException: if the string isn't a valid version
914 @since: 0.24 (moved from L{reader}, from where it is still available):"""
915 if version_string is None: return None
916 parts = _version_re.split(version_string)
917 if parts[-1] == '':
918 del parts[-1] # Ends with a modifier
919 else:
920 parts.append('')
921 if not parts:
922 raise SafeException(_("Empty version string!"))
923 l = len(parts)
924 try:
925 for x in range(0, l, 2):
926 part = parts[x]
927 if part:
928 parts[x] = map(int, parts[x].split('.'))
929 else:
930 parts[x] = [] # (because ''.split('.') == [''], not [])
931 for x in range(1, l, 2):
932 parts[x] = _version_mod_to_value[parts[x]]
933 return parts
934 except ValueError, ex:
935 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
936 except KeyError, ex:
937 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
939 def format_version(version):
940 """Format a parsed version for display. Undoes the effect of L{parse_version}.
941 @see: L{Implementation.get_version}
942 @rtype: str
943 @since: 0.24"""
944 version = version[:]
945 l = len(version)
946 for x in range(0, l, 2):
947 version[x] = '.'.join(map(str, version[x]))
948 for x in range(1, l, 2):
949 version[x] = '-' + _version_value_to_mod[version[x]]
950 if version[-1] == '-': del version[-1]
951 return ''.join(version)