If a distribution package is selected, prompt the user to install it
[zeroinstall/solver.git] / zeroinstall / injector / model.py
blob0aa8b8fe1470e7a2f67ae79ddf23641dd0275367
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, warn
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 try:
43 message += "\n\n(exact error: %s)" % ex
44 except:
45 # Some Python messages have type str but contain UTF-8 sequences.
46 # (e.g. IOException). Adding these to a Unicode 'message' (e.g.
47 # after gettext translation) will cause an error.
48 import codecs
49 decoder = codecs.lookup('utf-8')
50 decex = decoder.decode(str(ex), errors = 'replace')[0]
51 message += "\n\n(exact error: %s)" % decex
53 SafeException.__init__(self, message)
55 def _split_arch(arch):
56 """Split an arch into an (os, machine) tuple. Either or both parts may be None."""
57 if not arch:
58 return None, None
59 elif '-' not in arch:
60 raise SafeException(_("Malformed arch '%s'") % arch)
61 else:
62 osys, machine = arch.split('-', 1)
63 if osys == '*': osys = None
64 if machine == '*': machine = None
65 return osys, machine
67 def _join_arch(osys, machine):
68 if osys == machine == None: return None
69 return "%s-%s" % (osys or '*', machine or '*')
71 class Stability(object):
72 """A stability rating. Each implementation has an upstream stability rating and,
73 optionally, a user-set rating."""
74 __slots__ = ['level', 'name', 'description']
75 def __init__(self, level, name, description):
76 self.level = level
77 self.name = name
78 self.description = description
79 assert name not in stability_levels
80 stability_levels[name] = self
82 def __cmp__(self, other):
83 return cmp(self.level, other.level)
85 def __str__(self):
86 return self.name
88 def __repr__(self):
89 return _("<Stability: %s>") % self.description
91 def process_binding(e):
92 """Internal"""
93 if e.name == 'environment':
94 mode = {
95 None: EnvironmentBinding.PREPEND,
96 'prepend': EnvironmentBinding.PREPEND,
97 'append': EnvironmentBinding.APPEND,
98 'replace': EnvironmentBinding.REPLACE,
99 }[e.getAttribute('mode')]
101 binding = EnvironmentBinding(e.getAttribute('name'),
102 insert = e.getAttribute('insert'),
103 default = e.getAttribute('default'),
104 mode = mode)
105 if not binding.name: raise InvalidInterface(_("Missing 'name' in binding"))
106 if binding.insert is None: raise InvalidInterface(_("Missing 'insert' in binding"))
107 return binding
108 elif e.name == 'overlay':
109 return OverlayBinding(e.getAttribute('src'), e.getAttribute('mount-point'))
110 else:
111 raise Exception(_("Unknown binding type '%s'") % e.name)
113 def process_depends(item):
114 """Internal"""
115 # Note: also called from selections
116 dep_iface = item.getAttribute('interface')
117 if not dep_iface:
118 raise InvalidInterface(_("Missing 'interface' on <requires>"))
119 dependency = InterfaceDependency(dep_iface, metadata = item.attrs)
121 for e in item.childNodes:
122 if e.uri != XMLNS_IFACE: continue
123 if e.name in binding_names:
124 dependency.bindings.append(process_binding(e))
125 elif e.name == 'version':
126 dependency.restrictions.append(
127 VersionRangeRestriction(not_before = parse_version(e.getAttribute('not-before')),
128 before = parse_version(e.getAttribute('before'))))
129 return dependency
131 def N_(message): return message
133 insecure = Stability(0, N_('insecure'), _('This is a security risk'))
134 buggy = Stability(5, N_('buggy'), _('Known to have serious bugs'))
135 developer = Stability(10, N_('developer'), _('Work-in-progress - bugs likely'))
136 testing = Stability(20, N_('testing'), _('Stability unknown - please test!'))
137 stable = Stability(30, N_('stable'), _('Tested - no serious problems found'))
138 packaged = Stability(35, N_('packaged'), _('Supplied by the local package manager'))
139 preferred = Stability(40, N_('preferred'), _('Best of all - must be set manually'))
141 del N_
143 class Restriction(object):
144 """A Restriction limits the allowed implementations of an Interface."""
145 __slots__ = []
147 def meets_restriction(self, impl):
148 """Called by the L{Solver} to check whether a particular implementation is acceptable.
149 @return: False if this implementation is not a possibility
150 @rtype: bool
152 raise NotImplementedError(_("Abstract"))
154 class VersionRestriction(Restriction):
155 """Only select implementations with a particular version number.
156 @since: 0.40"""
158 def __init__(self, version):
159 """@param version: the required version number
160 @see: L{parse_version}; use this to pre-process the version number
162 self.version = version
164 def meets_restriction(self, impl):
165 return impl.version == self.version
167 def __str__(self):
168 return _("(restriction: version = %s)") % format_version(self.version)
170 class VersionRangeRestriction(Restriction):
171 """Only versions within the given range are acceptable"""
172 __slots__ = ['before', 'not_before']
174 def __init__(self, before, not_before):
175 """@param before: chosen versions must be earlier than this
176 @param not_before: versions must be at least this high
177 @see: L{parse_version}; use this to pre-process the versions
179 self.before = before
180 self.not_before = not_before
182 def meets_restriction(self, impl):
183 if self.not_before and impl.version < self.not_before:
184 return False
185 if self.before and impl.version >= self.before:
186 return False
187 return True
189 def __str__(self):
190 if self.not_before is not None or self.before is not None:
191 range = ''
192 if self.not_before is not None:
193 range += format_version(self.not_before) + ' <= '
194 range += 'version'
195 if self.before is not None:
196 range += ' < ' + format_version(self.before)
197 else:
198 range = 'none'
199 return _("(restriction: %s)") % range
201 class Binding(object):
202 """Information about how the choice of a Dependency is made known
203 to the application being run."""
205 class EnvironmentBinding(Binding):
206 """Indicate the chosen implementation using an environment variable."""
207 __slots__ = ['name', 'insert', 'default', 'mode']
209 PREPEND = 'prepend'
210 APPEND = 'append'
211 REPLACE = 'replace'
213 def __init__(self, name, insert, default = None, mode = PREPEND):
214 """mode argument added in version 0.28"""
215 self.name = name
216 self.insert = insert
217 self.default = default
218 self.mode = mode
220 def __str__(self):
221 return _("<environ %(name)s %(mode)s %(insert)s>") % {'name': self.name,'mode': self.mode, 'insert': self.insert}
223 __repr__ = __str__
225 def get_value(self, path, old_value):
226 """Calculate the new value of the environment variable after applying this binding.
227 @param path: the path to the selected implementation
228 @param old_value: the current value of the environment variable
229 @return: the new value for the environment variable"""
230 extra = os.path.join(path, self.insert)
232 if self.mode == EnvironmentBinding.REPLACE:
233 return extra
235 if old_value is None:
236 old_value = self.default or defaults.get(self.name, None)
237 if old_value is None:
238 return extra
239 if self.mode == EnvironmentBinding.PREPEND:
240 return extra + ':' + old_value
241 else:
242 return old_value + ':' + extra
244 def _toxml(self, doc):
245 """Create a DOM element for this binding.
246 @param doc: document to use to create the element
247 @return: the new element
249 env_elem = doc.createElementNS(XMLNS_IFACE, 'environment')
250 env_elem.setAttributeNS(None, 'name', self.name)
251 env_elem.setAttributeNS(None, 'insert', self.insert)
252 if self.default:
253 env_elem.setAttributeNS(None, 'default', self.default)
254 return env_elem
256 class OverlayBinding(Binding):
257 """Make the chosen implementation available by overlaying it onto another part of the file-system.
258 This is to support legacy programs which use hard-coded paths."""
259 __slots__ = ['src', 'mount_point']
261 def __init__(self, src, mount_point):
262 self.src = src
263 self.mount_point = mount_point
265 def __str__(self):
266 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self.src or '.', 'mount_point': self.mount_point or '/'}
268 __repr__ = __str__
270 def _toxml(self, doc):
271 """Create a DOM element for this binding.
272 @param doc: document to use to create the element
273 @return: the new element
275 env_elem = doc.createElementNS(XMLNS_IFACE, 'overlay')
276 if self.src is not None:
277 env_elem.setAttributeNS(None, 'src', self.src)
278 if self.mount_point is not None:
279 env_elem.setAttributeNS(None, 'mount-point', self.mount_point)
280 return env_elem
282 class Feed(object):
283 """An interface's feeds are other interfaces whose implementations can also be
284 used as implementations of this interface."""
285 __slots__ = ['uri', 'os', 'machine', 'user_override', 'langs']
286 def __init__(self, uri, arch, user_override, langs = None):
287 self.uri = uri
288 # This indicates whether the feed comes from the user's overrides
289 # file. If true, writer.py will write it when saving.
290 self.user_override = user_override
291 self.os, self.machine = _split_arch(arch)
292 self.langs = langs
294 def __str__(self):
295 return "<Feed from %s>" % self.uri
296 __repr__ = __str__
298 arch = property(lambda self: _join_arch(self.os, self.machine))
300 class Dependency(object):
301 """A Dependency indicates that an Implementation requires some additional
302 code to function. This is an abstract base class.
303 @ivar metadata: any extra attributes from the XML element
304 @type metadata: {str: str}
306 __slots__ = ['metadata']
308 def __init__(self, metadata):
309 if metadata is None:
310 metadata = {}
311 else:
312 assert not isinstance(metadata, basestring) # Use InterfaceDependency instead!
313 self.metadata = metadata
315 class InterfaceDependency(Dependency):
316 """A Dependency on a Zero Install interface.
317 @ivar interface: the interface required by this dependency
318 @type interface: str
319 @ivar restrictions: a list of constraints on acceptable implementations
320 @type restrictions: [L{Restriction}]
321 @ivar bindings: how to make the choice of implementation known
322 @type bindings: [L{Binding}]
323 @since: 0.28
325 __slots__ = ['interface', 'restrictions', 'bindings', 'metadata']
327 def __init__(self, interface, restrictions = None, metadata = None):
328 Dependency.__init__(self, metadata)
329 assert isinstance(interface, (str, unicode))
330 assert interface
331 self.interface = interface
332 if restrictions is None:
333 self.restrictions = []
334 else:
335 self.restrictions = restrictions
336 self.bindings = []
338 def __str__(self):
339 return _("<Dependency on %(interface)s; bindings: %(bindings)s%(restrictions)s>") % {'interface': self.interface, 'bindings': self.bindings, 'restrictions': self.restrictions}
341 class RetrievalMethod(object):
342 """A RetrievalMethod provides a way to fetch an implementation."""
343 __slots__ = []
345 class DownloadSource(RetrievalMethod):
346 """A DownloadSource provides a way to fetch an implementation."""
347 __slots__ = ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
349 def __init__(self, implementation, url, size, extract, start_offset = 0, type = None):
350 self.implementation = implementation
351 self.url = url
352 self.size = size
353 self.extract = extract
354 self.start_offset = start_offset
355 self.type = type # MIME type - see unpack.py
357 class Recipe(RetrievalMethod):
358 """Get an implementation by following a series of steps.
359 @ivar size: the combined download sizes from all the steps
360 @type size: int
361 @ivar steps: the sequence of steps which must be performed
362 @type steps: [L{RetrievalMethod}]"""
363 __slots__ = ['steps']
365 def __init__(self):
366 self.steps = []
368 size = property(lambda self: sum([x.size for x in self.steps]))
370 class DistributionSource(RetrievalMethod):
371 """A package that is installed using the distribution's tools (including PackageKit).
372 @ivar package_id: the package name, in a form recognised by the distribution's tools
373 @type package_id: str
374 @ivar size: the download size in bytes
375 @type size: int"""
377 __slots__ = ['package_id', 'size']
379 def __init__(self, package_id, size):
380 RetrievalMethod.__init__(self)
381 self.package_id = package_id
382 self.size = size
384 class Implementation(object):
385 """An Implementation is a package which implements an Interface.
386 @ivar download_sources: list of methods of getting this implementation
387 @type download_sources: [L{RetrievalMethod}]
388 @ivar feed: the feed owning this implementation (since 0.32)
389 @type feed: [L{ZeroInstallFeed}]
390 @ivar bindings: how to tell this component where it itself is located (since 0.31)
391 @type bindings: [Binding]
392 @ivar upstream_stability: the stability reported by the packager
393 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged]
394 @ivar user_stability: the stability as set by the user
395 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred]
396 @ivar langs: natural languages supported by this package
397 @ivar requires: interfaces this package depends on
398 @type requires: [L{Dependency}]
399 @ivar main: the default file to execute when running as a program
400 @ivar metadata: extra metadata from the feed
401 @type metadata: {"[URI ]localName": str}
402 @ivar id: a unique identifier for this Implementation
403 @ivar version: a parsed version number
404 @ivar released: release date
405 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path)
406 @type local_path: str | None
407 @ivar requires_root_install: whether the user will need admin rights to use this
408 @type requires_root_install: bool
411 # Note: user_stability shouldn't really be here
413 __slots__ = ['upstream_stability', 'user_stability', 'langs',
414 'requires', 'main', 'metadata', 'download_sources',
415 'id', 'feed', 'version', 'released', 'bindings', 'machine']
417 def __init__(self, feed, id):
418 assert id
419 self.feed = feed
420 self.id = id
421 self.main = None
422 self.user_stability = None
423 self.upstream_stability = None
424 self.metadata = {} # [URI + " "] + localName -> value
425 self.requires = []
426 self.version = None
427 self.released = None
428 self.download_sources = []
429 self.langs = None
430 self.machine = None
431 self.bindings = []
433 def get_stability(self):
434 return self.user_stability or self.upstream_stability or testing
436 def __str__(self):
437 return self.id
439 def __repr__(self):
440 return "v%s (%s)" % (self.get_version(), self.id)
442 def __cmp__(self, other):
443 """Newer versions come first"""
444 d = cmp(other.version, self.version)
445 if d: return d
446 # If the version number is the same, just give a stable sort order, and
447 # ensure that two different implementations don't compare equal.
448 d = cmp(other.feed.url, self.feed.url)
449 if d: return d
450 return cmp(other.id, self.id)
452 def get_version(self):
453 """Return the version as a string.
454 @see: L{format_version}
456 return format_version(self.version)
458 arch = property(lambda self: _join_arch(self.os, self.machine))
460 os = None
461 local_path = None
462 digests = None
463 requires_root_install = False
465 class DistributionImplementation(Implementation):
466 """An implementation provided by the distribution. Information such as the version
467 comes from the package manager.
468 @since: 0.28"""
469 __slots__ = ['installed']
471 def __init__(self, feed, id):
472 assert id.startswith('package:')
473 Implementation.__init__(self, feed, id)
474 self.installed = True
476 @property
477 def requires_root_install(self):
478 return not self.installed
480 class ZeroInstallImplementation(Implementation):
481 """An implementation where all the information comes from Zero Install.
482 @ivar digests: a list of "algorith=value" strings (since 0.45)
483 @type digests: [str]
484 @since: 0.28"""
485 __slots__ = ['os', 'size', 'digests', 'local_path']
487 def __init__(self, feed, id, local_path):
488 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
489 assert not id.startswith('package:'), id
490 Implementation.__init__(self, feed, id)
491 self.size = None
492 self.os = None
493 self.digests = []
494 self.local_path = local_path
496 # Deprecated
497 dependencies = property(lambda self: dict([(x.interface, x) for x in self.requires
498 if isinstance(x, InterfaceDependency)]))
500 def add_download_source(self, url, size, extract, start_offset = 0, type = None):
501 """Add a download source."""
502 self.download_sources.append(DownloadSource(self, url, size, extract, start_offset, type))
504 def set_arch(self, arch):
505 self.os, self.machine = _split_arch(arch)
506 arch = property(lambda self: _join_arch(self.os, self.machine), set_arch)
508 class Interface(object):
509 """An Interface represents some contract of behaviour.
510 @ivar uri: the URI for this interface.
511 @ivar stability_policy: user's configured policy.
512 Implementations at this level or higher are preferred.
513 Lower levels are used only if there is no other choice.
515 __slots__ = ['uri', 'stability_policy', '_main_feed', 'extra_feeds']
517 implementations = property(lambda self: self._main_feed.implementations)
518 name = property(lambda self: self._main_feed.name)
519 description = property(lambda self: self._main_feed.description)
520 summary = property(lambda self: self._main_feed.summary)
521 last_modified = property(lambda self: self._main_feed.last_modified)
522 feeds = property(lambda self: self.extra_feeds + self._main_feed.feeds)
523 metadata = property(lambda self: self._main_feed.metadata)
525 last_checked = property(lambda self: self._main_feed.last_checked)
527 def __init__(self, uri):
528 assert uri
529 if uri.startswith('http:') or uri.startswith('https:') or uri.startswith('/'):
530 self.uri = uri
531 else:
532 raise SafeException(_("Interface name '%s' doesn't start "
533 "with 'http:' or 'https:'") % uri)
534 self.reset()
536 def _get_feed_for(self):
537 retval = {}
538 for key in self._main_feed.feed_for:
539 retval[key] = True
540 return retval
541 feed_for = property(_get_feed_for) # Deprecated (used by 0publish)
543 def reset(self):
544 self.extra_feeds = []
545 self._main_feed = _dummy_feed
546 self.stability_policy = None
548 def get_name(self):
549 if self._main_feed is not _dummy_feed:
550 return self._main_feed.get_name()
551 return '(' + os.path.basename(self.uri) + ')'
553 def __repr__(self):
554 return _("<Interface %s>") % self.uri
556 def set_stability_policy(self, new):
557 assert new is None or isinstance(new, Stability)
558 self.stability_policy = new
560 def get_feed(self, url):
561 for x in self.extra_feeds:
562 if x.uri == url:
563 return x
564 return self._main_feed.get_feed(url)
566 def get_metadata(self, uri, name):
567 return self._main_feed.get_metadata(uri, name)
569 def _merge_attrs(attrs, item):
570 """Add each attribute of item to a copy of attrs and return the copy.
571 @type attrs: {str: str}
572 @type item: L{qdom.Element}
573 @rtype: {str: str}
575 new = attrs.copy()
576 for a in item.attrs:
577 new[str(a)] = item.attrs[a]
578 return new
580 def _get_long(elem, attr_name):
581 val = elem.getAttribute(attr_name)
582 if val is not None:
583 try:
584 val = long(val)
585 except ValueError, ex:
586 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name, 'value': val})
587 return val
589 class ZeroInstallFeed(object):
590 """A feed lists available implementations of an interface.
591 @ivar url: the URL for this feed
592 @ivar implementations: Implementations in this feed, indexed by ID
593 @type implementations: {str: L{Implementation}}
594 @ivar name: human-friendly name
595 @ivar summary: short textual description
596 @ivar description: long textual description
597 @ivar last_modified: timestamp on signature
598 @ivar last_checked: time feed was last successfully downloaded and updated
599 @ivar feeds: list of <feed> elements in this feed
600 @type feeds: [L{Feed}]
601 @ivar feed_for: interfaces for which this could be a feed
602 @type feed_for: set(str)
603 @ivar metadata: extra elements we didn't understand
605 # _main is deprecated
606 __slots__ = ['url', 'implementations', 'name', 'description', 'summary',
607 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
609 def __init__(self, feed_element, local_path = None, distro = None):
610 """Create a feed object from a DOM.
611 @param feed_element: the root element of a feed file
612 @type feed_element: L{qdom.Element}
613 @param local_path: the pathname of this local feed, or None for remote feeds
614 @param distro: used to resolve distribution package references
615 @type distro: L{distro.Distribution} or None"""
616 assert feed_element
617 self.implementations = {}
618 self.name = None
619 self.summary = None
620 self.description = ""
621 self.last_modified = None
622 self.feeds = []
623 self.feed_for = set()
624 self.metadata = []
625 self.last_checked = None
627 assert feed_element.name in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
628 assert feed_element.uri == XMLNS_IFACE, "Wrong namespace on root element: %s" % feed_element.uri
630 main = feed_element.getAttribute('main')
631 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
633 if local_path:
634 self.url = local_path
635 local_dir = os.path.dirname(local_path)
636 else:
637 self.url = feed_element.getAttribute('uri')
638 if not self.url:
639 raise InvalidInterface(_("<interface> uri attribute missing"))
640 local_dir = None # Can't have relative paths
642 min_injector_version = feed_element.getAttribute('min-injector-version')
643 if min_injector_version:
644 if parse_version(min_injector_version) > parse_version(version):
645 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
646 "Zero Install, but I am only version %(version)s. "
647 "You can get a newer version from http://0install.net") %
648 {'min_version': min_injector_version, 'version': version})
650 for x in feed_element.childNodes:
651 if x.uri != XMLNS_IFACE:
652 self.metadata.append(x)
653 continue
654 if x.name == 'name':
655 self.name = x.content
656 elif x.name == 'description':
657 self.description = x.content
658 elif x.name == 'summary':
659 self.summary = x.content
660 elif x.name == 'feed-for':
661 feed_iface = x.getAttribute('interface')
662 if not feed_iface:
663 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
664 self.feed_for.add(feed_iface)
665 # Bug report from a Debian/stable user that --feed gets the wrong value.
666 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
667 # in case it happens again.
668 debug(_("Is feed-for %s"), feed_iface)
669 elif x.name == 'feed':
670 feed_src = x.getAttribute('src')
671 if not feed_src:
672 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
673 if feed_src.startswith('http:') or feed_src.startswith('https:') or local_path:
674 self.feeds.append(Feed(feed_src, x.getAttribute('arch'), False, langs = x.getAttribute('langs')))
675 else:
676 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src)
677 else:
678 self.metadata.append(x)
680 if not self.name:
681 raise InvalidInterface(_("Missing <name> in feed"))
682 if not self.summary:
683 raise InvalidInterface(_("Missing <summary> in feed"))
685 package_impls = [0, []] # Best score so far and packages with that score
687 def process_group(group, group_attrs, base_depends, base_bindings):
688 for item in group.childNodes:
689 if item.uri != XMLNS_IFACE: continue
691 if item.name not in ('group', 'implementation', 'package-implementation'):
692 continue
694 depends = base_depends[:]
695 bindings = base_bindings[:]
697 item_attrs = _merge_attrs(group_attrs, item)
699 # We've found a group or implementation. Scan for dependencies
700 # and bindings. Doing this here means that:
701 # - We can share the code for groups and implementations here.
702 # - The order doesn't matter, because these get processed first.
703 # A side-effect is that the document root cannot contain
704 # these.
705 for child in item.childNodes:
706 if child.uri != XMLNS_IFACE: continue
707 if child.name == 'requires':
708 dep = process_depends(child)
709 depends.append(dep)
710 elif child.name in binding_names:
711 bindings.append(process_binding(child))
713 if item.name == 'group':
714 process_group(item, item_attrs, depends, bindings)
715 elif item.name == 'implementation':
716 process_impl(item, item_attrs, depends, bindings)
717 elif item.name == 'package-implementation':
718 distro_names = item_attrs.get('distributions', '')
719 for distro_name in distro_names.split(' '):
720 score = distro.get_score(distro_name)
721 if score > package_impls[0]:
722 package_impls[0] = score
723 package_impls[1] = []
724 if score == package_impls[0]:
725 package_impls[1].append((item, item_attrs, depends))
726 else:
727 assert 0
729 def process_impl(item, item_attrs, depends, bindings):
730 id = item.getAttribute('id')
731 if id is None:
732 raise InvalidInterface(_("Missing 'id' attribute on %s") % item)
733 local_path = item_attrs.get('local-path')
734 if local_dir and local_path:
735 abs_local_path = os.path.abspath(os.path.join(local_dir, local_path))
736 impl = ZeroInstallImplementation(self, id, abs_local_path)
737 elif local_dir and (id.startswith('/') or id.startswith('.')):
738 # For old feeds
739 id = os.path.abspath(os.path.join(local_dir, id))
740 impl = ZeroInstallImplementation(self, id, id)
741 else:
742 impl = ZeroInstallImplementation(self, id, None)
743 if '=' in id:
744 # In older feeds, the ID was the (single) digest
745 impl.digests.append(id)
746 if id in self.implementations:
747 warn(_("Duplicate ID '%s' in feed '%s'"), id, self)
748 self.implementations[id] = impl
750 impl.metadata = item_attrs
751 try:
752 version_mod = item_attrs.get('version-modifier', None)
753 if version_mod:
754 item_attrs['version'] += version_mod
755 del item_attrs['version-modifier']
756 version = item_attrs['version']
757 except KeyError:
758 raise InvalidInterface(_("Missing version attribute"))
759 impl.version = parse_version(version)
761 item_main = item_attrs.get('main', None)
762 if item_main and item_main.startswith('/'):
763 raise InvalidInterface(_("'main' attribute must be relative, but '%s' starts with '/'!") %
764 item_main)
765 impl.main = item_main
767 impl.released = item_attrs.get('released', None)
768 impl.langs = item_attrs.get('langs', None)
770 size = item.getAttribute('size')
771 if size:
772 impl.size = long(size)
773 impl.arch = item_attrs.get('arch', None)
774 try:
775 stability = stability_levels[str(item_attrs['stability'])]
776 except KeyError:
777 stab = str(item_attrs['stability'])
778 if stab != stab.lower():
779 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs.stability)
780 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs['stability'])
781 if stability >= preferred:
782 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
783 impl.upstream_stability = stability
785 impl.bindings = bindings
786 impl.requires = depends
788 for elem in item.childNodes:
789 if elem.uri != XMLNS_IFACE: continue
790 if elem.name == 'archive':
791 url = elem.getAttribute('href')
792 if not url:
793 raise InvalidInterface(_("Missing href attribute on <archive>"))
794 size = elem.getAttribute('size')
795 if not size:
796 raise InvalidInterface(_("Missing size attribute on <archive>"))
797 impl.add_download_source(url = url, size = long(size),
798 extract = elem.getAttribute('extract'),
799 start_offset = _get_long(elem, 'start-offset'),
800 type = elem.getAttribute('type'))
801 elif elem.name == 'manifest-digest':
802 for aname, avalue in elem.attrs.iteritems():
803 if ' ' not in aname:
804 impl.digests.append('%s=%s' % (aname, avalue))
805 elif elem.name == 'recipe':
806 recipe = Recipe()
807 for recipe_step in elem.childNodes:
808 if recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'archive':
809 url = recipe_step.getAttribute('href')
810 if not url:
811 raise InvalidInterface(_("Missing href attribute on <archive>"))
812 size = recipe_step.getAttribute('size')
813 if not size:
814 raise InvalidInterface(_("Missing size attribute on <archive>"))
815 recipe.steps.append(DownloadSource(None, url = url, size = long(size),
816 extract = recipe_step.getAttribute('extract'),
817 start_offset = _get_long(recipe_step, 'start-offset'),
818 type = recipe_step.getAttribute('type')))
819 else:
820 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step.name)
821 break
822 else:
823 impl.download_sources.append(recipe)
825 def process_native_impl(item, item_attrs, depends):
826 package = item_attrs.get('package', None)
827 if package is None:
828 raise InvalidInterface(_("Missing 'package' attribute on %s") % item)
830 def factory(id):
831 assert id.startswith('package:')
832 if id in self.implementations:
833 warn(_("Duplicate ID '%s' for DistributionImplementation"), id)
834 impl = DistributionImplementation(self, id)
835 self.implementations[id] = impl
837 impl.metadata = item_attrs
839 item_main = item_attrs.get('main', None)
840 if item_main and not item_main.startswith('/'):
841 raise InvalidInterface(_("'main' attribute must be absolute, but '%s' doesn't start with '/'!") %
842 item_main)
843 impl.main = item_main
844 impl.upstream_stability = packaged
845 impl.requires = depends
847 return impl
849 distro.get_package_info(package, factory)
851 root_attrs = {'stability': 'testing'}
852 if main:
853 root_attrs['main'] = main
854 process_group(feed_element, root_attrs, [], [])
856 for args in package_impls[1]:
857 process_native_impl(*args)
859 def get_name(self):
860 return self.name or '(' + os.path.basename(self.url) + ')'
862 def __repr__(self):
863 return _("<Feed %s>") % self.url
865 """@deprecated"""
866 def _get_impl(self, id):
867 assert id not in self.implementations
869 if id.startswith('.') or id.startswith('/'):
870 id = os.path.abspath(os.path.join(self.url, id))
871 local_path = id
872 impl = ZeroInstallImplementation(self, id, local_path)
873 else:
874 impl = ZeroInstallImplementation(self, id, None)
875 impl.digests.append(id)
877 self.implementations[id] = impl
878 return impl
880 def set_stability_policy(self, new):
881 assert new is None or isinstance(new, Stability)
882 self.stability_policy = new
884 def get_feed(self, url):
885 for x in self.feeds:
886 if x.uri == url:
887 return x
888 return None
890 def add_metadata(self, elem):
891 self.metadata.append(elem)
893 def get_metadata(self, uri, name):
894 """Return a list of interface metadata elements with this name and namespace URI."""
895 return [m for m in self.metadata if m.name == name and m.uri == uri]
897 class DummyFeed(object):
898 """Temporary class used during API transition."""
899 last_modified = None
900 name = '-'
901 last_checked = property(lambda self: None)
902 implementations = property(lambda self: {})
903 feeds = property(lambda self: [])
904 summary = property(lambda self: '-')
905 description = property(lambda self: '')
906 def get_name(self): return self.name
907 def get_feed(self, url): return None
908 def get_metadata(self, uri, name): return []
909 _dummy_feed = DummyFeed()
911 def unescape(uri):
912 """Convert each %20 to a space, etc.
913 @rtype: str"""
914 uri = uri.replace('#', '/')
915 if '%' not in uri: return uri
916 return re.sub('%[0-9a-fA-F][0-9a-fA-F]',
917 lambda match: chr(int(match.group(0)[1:], 16)),
918 uri).decode('utf-8')
920 def escape(uri):
921 """Convert each space to %20, etc
922 @rtype: str"""
923 return re.sub('[^-_.a-zA-Z0-9]',
924 lambda match: '%%%02x' % ord(match.group(0)),
925 uri.encode('utf-8'))
927 def _pretty_escape(uri):
928 """Convert each space to %20, etc
929 : is preserved and / becomes #. This makes for nicer strings,
930 and may replace L{escape} everywhere in future.
931 @rtype: str"""
932 return re.sub('[^-_.a-zA-Z0-9:/]',
933 lambda match: '%%%02x' % ord(match.group(0)),
934 uri.encode('utf-8')).replace('/', '#')
936 def canonical_iface_uri(uri):
937 """If uri is a relative path, convert to an absolute one.
938 A "file:///foo" URI is converted to "/foo".
939 Otherwise, return it unmodified.
940 @rtype: str
941 @raise SafeException: if uri isn't valid
943 if uri.startswith('http://') or uri.startswith('https://'):
944 if uri.count("/") < 3:
945 raise SafeException(_("Missing / after hostname in URI '%s'") % uri)
946 return uri
947 elif uri.startswith('file:///'):
948 return uri[7:]
949 else:
950 iface_uri = os.path.realpath(uri)
951 if os.path.isfile(iface_uri):
952 return iface_uri
953 raise SafeException(_("Bad interface name '%(uri)s'.\n"
954 "(doesn't start with 'http:', and "
955 "doesn't exist as a local file '%(interface_uri)s' either)") %
956 {'uri': uri, 'interface_uri': iface_uri})
958 _version_mod_to_value = {
959 'pre': -2,
960 'rc': -1,
961 '': 0,
962 'post': 1,
965 # Reverse mapping
966 _version_value_to_mod = {}
967 for x in _version_mod_to_value: _version_value_to_mod[_version_mod_to_value[x]] = x
968 del x
970 _version_re = re.compile('-([a-z]*)')
972 def parse_version(version_string):
973 """Convert a version string to an internal representation.
974 The parsed format can be compared quickly using the standard Python functions.
975 - Version := DottedList ("-" Mod DottedList?)*
976 - DottedList := (Integer ("." Integer)*)
977 @rtype: tuple (opaque)
978 @raise SafeException: if the string isn't a valid version
979 @since: 0.24 (moved from L{reader}, from where it is still available):"""
980 if version_string is None: return None
981 parts = _version_re.split(version_string)
982 if parts[-1] == '':
983 del parts[-1] # Ends with a modifier
984 else:
985 parts.append('')
986 if not parts:
987 raise SafeException(_("Empty version string!"))
988 l = len(parts)
989 try:
990 for x in range(0, l, 2):
991 part = parts[x]
992 if part:
993 parts[x] = map(int, parts[x].split('.'))
994 else:
995 parts[x] = [] # (because ''.split('.') == [''], not [])
996 for x in range(1, l, 2):
997 parts[x] = _version_mod_to_value[parts[x]]
998 return parts
999 except ValueError, ex:
1000 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1001 except KeyError, ex:
1002 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1004 def format_version(version):
1005 """Format a parsed version for display. Undoes the effect of L{parse_version}.
1006 @see: L{Implementation.get_version}
1007 @rtype: str
1008 @since: 0.24"""
1009 version = version[:]
1010 l = len(version)
1011 for x in range(0, l, 2):
1012 version[x] = '.'.join(map(str, version[x]))
1013 for x in range(1, l, 2):
1014 version[x] = '-' + _version_value_to_mod[version[x]]
1015 if version[-1] == '-': del version[-1]
1016 return ''.join(version)