API changes: use Feed rather than Interface in many places
[zeroinstall/zeroinstall-afb.git] / zeroinstall / injector / model.py
blobcc995fdd9c0910f5d3fc827d7488701cd8ab9611
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 @type langs: str
398 @ivar requires: interfaces this package depends on
399 @type requires: [L{Dependency}]
400 @ivar main: the default file to execute when running as a program
401 @ivar metadata: extra metadata from the feed
402 @type metadata: {"[URI ]localName": str}
403 @ivar id: a unique identifier for this Implementation
404 @ivar version: a parsed version number
405 @ivar released: release date
406 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path)
407 @type local_path: str | None
408 @ivar requires_root_install: whether the user will need admin rights to use this
409 @type requires_root_install: bool
412 # Note: user_stability shouldn't really be here
414 __slots__ = ['upstream_stability', 'user_stability', 'langs',
415 'requires', 'main', 'metadata', 'download_sources',
416 'id', 'feed', 'version', 'released', 'bindings', 'machine']
418 def __init__(self, feed, id):
419 assert id
420 self.feed = feed
421 self.id = id
422 self.main = None
423 self.user_stability = None
424 self.upstream_stability = None
425 self.metadata = {} # [URI + " "] + localName -> value
426 self.requires = []
427 self.version = None
428 self.released = None
429 self.download_sources = []
430 self.langs = ""
431 self.machine = None
432 self.bindings = []
434 def get_stability(self):
435 return self.user_stability or self.upstream_stability or testing
437 def __str__(self):
438 return self.id
440 def __repr__(self):
441 return "v%s (%s)" % (self.get_version(), self.id)
443 def __cmp__(self, other):
444 """Newer versions come first"""
445 d = cmp(other.version, self.version)
446 if d: return d
447 # If the version number is the same, just give a stable sort order, and
448 # ensure that two different implementations don't compare equal.
449 d = cmp(other.feed.url, self.feed.url)
450 if d: return d
451 return cmp(other.id, self.id)
453 def get_version(self):
454 """Return the version as a string.
455 @see: L{format_version}
457 return format_version(self.version)
459 arch = property(lambda self: _join_arch(self.os, self.machine))
461 os = None
462 local_path = None
463 digests = None
464 requires_root_install = False
466 class DistributionImplementation(Implementation):
467 """An implementation provided by the distribution. Information such as the version
468 comes from the package manager.
469 @since: 0.28"""
471 def __init__(self, feed, id, distro):
472 assert id.startswith('package:')
473 Implementation.__init__(self, feed, id)
474 self.distro = distro
476 @property
477 def requires_root_install(self):
478 return not self.installed
480 @property
481 def installed(self):
482 return self.distro.get_installed(self.id)
484 class ZeroInstallImplementation(Implementation):
485 """An implementation where all the information comes from Zero Install.
486 @ivar digests: a list of "algorith=value" strings (since 0.45)
487 @type digests: [str]
488 @since: 0.28"""
489 __slots__ = ['os', 'size', 'digests', 'local_path']
491 def __init__(self, feed, id, local_path):
492 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
493 assert not id.startswith('package:'), id
494 Implementation.__init__(self, feed, id)
495 self.size = None
496 self.os = None
497 self.digests = []
498 self.local_path = local_path
500 # Deprecated
501 dependencies = property(lambda self: dict([(x.interface, x) for x in self.requires
502 if isinstance(x, InterfaceDependency)]))
504 def add_download_source(self, url, size, extract, start_offset = 0, type = None):
505 """Add a download source."""
506 self.download_sources.append(DownloadSource(self, url, size, extract, start_offset, type))
508 def set_arch(self, arch):
509 self.os, self.machine = _split_arch(arch)
510 arch = property(lambda self: _join_arch(self.os, self.machine), set_arch)
512 class Interface(object):
513 """An Interface represents some contract of behaviour.
514 @ivar uri: the URI for this interface.
515 @ivar stability_policy: user's configured policy.
516 Implementations at this level or higher are preferred.
517 Lower levels are used only if there is no other choice.
519 __slots__ = ['uri', 'stability_policy', 'extra_feeds']
521 implementations = property(lambda self: self._main_feed.implementations)
522 name = property(lambda self: self._main_feed.name)
523 description = property(lambda self: self._main_feed.description)
524 summary = property(lambda self: self._main_feed.summary)
525 last_modified = property(lambda self: self._main_feed.last_modified)
526 feeds = property(lambda self: self.extra_feeds + self._main_feed.feeds)
527 metadata = property(lambda self: self._main_feed.metadata)
529 last_checked = property(lambda self: self._main_feed.last_checked)
531 def __init__(self, uri):
532 assert uri
533 if uri.startswith('http:') or uri.startswith('https:') or uri.startswith('/'):
534 self.uri = uri
535 else:
536 raise SafeException(_("Interface name '%s' doesn't start "
537 "with 'http:' or 'https:'") % uri)
538 self.reset()
540 def _get_feed_for(self):
541 retval = {}
542 for key in self._main_feed.feed_for:
543 retval[key] = True
544 return retval
545 feed_for = property(_get_feed_for) # Deprecated (used by 0publish)
547 def reset(self):
548 self.extra_feeds = []
549 self.stability_policy = None
551 def get_name(self):
552 from zeroinstall.injector.iface_cache import iface_cache
553 feed = iface_cache.get_feed(self.uri)
554 if feed:
555 return feed.get_name()
556 return '(' + os.path.basename(self.uri) + ')'
558 def __repr__(self):
559 return _("<Interface %s>") % self.uri
561 def set_stability_policy(self, new):
562 assert new is None or isinstance(new, Stability)
563 self.stability_policy = new
565 def get_feed(self, url):
566 #import warnings
567 #warnings.warn("use iface_cache.get_feed instead", DeprecationWarning, 2)
568 for x in self.extra_feeds:
569 if x.uri == url:
570 return x
571 #return self._main_feed.get_feed(url)
572 return None
574 def get_metadata(self, uri, name):
575 return self._main_feed.get_metadata(uri, name)
577 @property
578 def _main_feed(self):
579 #import warnings
580 #warnings.warn("use the feed instead", DeprecationWarning, 3)
581 from zeroinstall.injector.iface_cache import iface_cache
582 feed = iface_cache.get_feed(self.uri)
583 if feed is None:
584 return _dummy_feed
585 return feed
587 def _merge_attrs(attrs, item):
588 """Add each attribute of item to a copy of attrs and return the copy.
589 @type attrs: {str: str}
590 @type item: L{qdom.Element}
591 @rtype: {str: str}
593 new = attrs.copy()
594 for a in item.attrs:
595 new[str(a)] = item.attrs[a]
596 return new
598 def _get_long(elem, attr_name):
599 val = elem.getAttribute(attr_name)
600 if val is not None:
601 try:
602 val = long(val)
603 except ValueError, ex:
604 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name, 'value': val})
605 return val
607 class ZeroInstallFeed(object):
608 """A feed lists available implementations of an interface.
609 @ivar url: the URL for this feed
610 @ivar implementations: Implementations in this feed, indexed by ID
611 @type implementations: {str: L{Implementation}}
612 @ivar name: human-friendly name
613 @ivar summary: short textual description
614 @ivar description: long textual description
615 @ivar last_modified: timestamp on signature
616 @ivar last_checked: time feed was last successfully downloaded and updated
617 @ivar feeds: list of <feed> elements in this feed
618 @type feeds: [L{Feed}]
619 @ivar feed_for: interfaces for which this could be a feed
620 @type feed_for: set(str)
621 @ivar metadata: extra elements we didn't understand
623 # _main is deprecated
624 __slots__ = ['url', 'implementations', 'name', 'description', 'summary',
625 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
627 def __init__(self, feed_element, local_path = None, distro = None):
628 """Create a feed object from a DOM.
629 @param feed_element: the root element of a feed file
630 @type feed_element: L{qdom.Element}
631 @param local_path: the pathname of this local feed, or None for remote feeds
632 @param distro: used to resolve distribution package references
633 @type distro: L{distro.Distribution} or None"""
634 assert feed_element
635 self.implementations = {}
636 self.name = None
637 self.summary = None
638 self.description = ""
639 self.last_modified = None
640 self.feeds = []
641 self.feed_for = set()
642 self.metadata = []
643 self.last_checked = None
645 assert feed_element.name in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
646 assert feed_element.uri == XMLNS_IFACE, "Wrong namespace on root element: %s" % feed_element.uri
648 main = feed_element.getAttribute('main')
649 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
651 if local_path:
652 self.url = local_path
653 local_dir = os.path.dirname(local_path)
654 else:
655 self.url = feed_element.getAttribute('uri')
656 if not self.url:
657 raise InvalidInterface(_("<interface> uri attribute missing"))
658 local_dir = None # Can't have relative paths
660 min_injector_version = feed_element.getAttribute('min-injector-version')
661 if min_injector_version:
662 if parse_version(min_injector_version) > parse_version(version):
663 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
664 "Zero Install, but I am only version %(version)s. "
665 "You can get a newer version from http://0install.net") %
666 {'min_version': min_injector_version, 'version': version})
668 for x in feed_element.childNodes:
669 if x.uri != XMLNS_IFACE:
670 self.metadata.append(x)
671 continue
672 if x.name == 'name':
673 self.name = x.content
674 elif x.name == 'description':
675 self.description = x.content
676 elif x.name == 'summary':
677 self.summary = x.content
678 elif x.name == 'feed-for':
679 feed_iface = x.getAttribute('interface')
680 if not feed_iface:
681 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
682 self.feed_for.add(feed_iface)
683 # Bug report from a Debian/stable user that --feed gets the wrong value.
684 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
685 # in case it happens again.
686 debug(_("Is feed-for %s"), feed_iface)
687 elif x.name == 'feed':
688 feed_src = x.getAttribute('src')
689 if not feed_src:
690 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
691 if feed_src.startswith('http:') or feed_src.startswith('https:') or local_path:
692 self.feeds.append(Feed(feed_src, x.getAttribute('arch'), False, langs = x.getAttribute('langs')))
693 else:
694 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src)
695 else:
696 self.metadata.append(x)
698 if not self.name:
699 raise InvalidInterface(_("Missing <name> in feed"))
700 if not self.summary:
701 raise InvalidInterface(_("Missing <summary> in feed"))
703 package_impls = [0, []] # Best score so far and packages with that score
705 def process_group(group, group_attrs, base_depends, base_bindings):
706 for item in group.childNodes:
707 if item.uri != XMLNS_IFACE: continue
709 if item.name not in ('group', 'implementation', 'package-implementation'):
710 continue
712 depends = base_depends[:]
713 bindings = base_bindings[:]
715 item_attrs = _merge_attrs(group_attrs, item)
717 # We've found a group or implementation. Scan for dependencies
718 # and bindings. Doing this here means that:
719 # - We can share the code for groups and implementations here.
720 # - The order doesn't matter, because these get processed first.
721 # A side-effect is that the document root cannot contain
722 # these.
723 for child in item.childNodes:
724 if child.uri != XMLNS_IFACE: continue
725 if child.name == 'requires':
726 dep = process_depends(child)
727 depends.append(dep)
728 elif child.name in binding_names:
729 bindings.append(process_binding(child))
731 if item.name == 'group':
732 process_group(item, item_attrs, depends, bindings)
733 elif item.name == 'implementation':
734 process_impl(item, item_attrs, depends, bindings)
735 elif item.name == 'package-implementation':
736 distro_names = item_attrs.get('distributions', '')
737 for distro_name in distro_names.split(' '):
738 score = distro.get_score(distro_name)
739 if score > package_impls[0]:
740 package_impls[0] = score
741 package_impls[1] = []
742 if score == package_impls[0]:
743 package_impls[1].append((item, item_attrs, depends))
744 else:
745 assert 0
747 def process_impl(item, item_attrs, depends, bindings):
748 id = item.getAttribute('id')
749 if id is None:
750 raise InvalidInterface(_("Missing 'id' attribute on %s") % item)
751 local_path = item_attrs.get('local-path')
752 if local_dir and local_path:
753 abs_local_path = os.path.abspath(os.path.join(local_dir, local_path))
754 impl = ZeroInstallImplementation(self, id, abs_local_path)
755 elif local_dir and (id.startswith('/') or id.startswith('.')):
756 # For old feeds
757 id = os.path.abspath(os.path.join(local_dir, id))
758 impl = ZeroInstallImplementation(self, id, id)
759 else:
760 impl = ZeroInstallImplementation(self, id, None)
761 if '=' in id:
762 # In older feeds, the ID was the (single) digest
763 impl.digests.append(id)
764 if id in self.implementations:
765 warn(_("Duplicate ID '%s' in feed '%s'"), id, self)
766 self.implementations[id] = impl
768 impl.metadata = item_attrs
769 try:
770 version_mod = item_attrs.get('version-modifier', None)
771 if version_mod:
772 item_attrs['version'] += version_mod
773 del item_attrs['version-modifier']
774 version = item_attrs['version']
775 except KeyError:
776 raise InvalidInterface(_("Missing version attribute"))
777 impl.version = parse_version(version)
779 item_main = item_attrs.get('main', None)
780 if item_main and item_main.startswith('/'):
781 raise InvalidInterface(_("'main' attribute must be relative, but '%s' starts with '/'!") %
782 item_main)
783 impl.main = item_main
785 impl.released = item_attrs.get('released', None)
786 impl.langs = item_attrs.get('langs', '')
788 size = item.getAttribute('size')
789 if size:
790 impl.size = long(size)
791 impl.arch = item_attrs.get('arch', None)
792 try:
793 stability = stability_levels[str(item_attrs['stability'])]
794 except KeyError:
795 stab = str(item_attrs['stability'])
796 if stab != stab.lower():
797 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs.stability)
798 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs['stability'])
799 if stability >= preferred:
800 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
801 impl.upstream_stability = stability
803 impl.bindings = bindings
804 impl.requires = depends
806 for elem in item.childNodes:
807 if elem.uri != XMLNS_IFACE: continue
808 if elem.name == 'archive':
809 url = elem.getAttribute('href')
810 if not url:
811 raise InvalidInterface(_("Missing href attribute on <archive>"))
812 size = elem.getAttribute('size')
813 if not size:
814 raise InvalidInterface(_("Missing size attribute on <archive>"))
815 impl.add_download_source(url = url, size = long(size),
816 extract = elem.getAttribute('extract'),
817 start_offset = _get_long(elem, 'start-offset'),
818 type = elem.getAttribute('type'))
819 elif elem.name == 'manifest-digest':
820 for aname, avalue in elem.attrs.iteritems():
821 if ' ' not in aname:
822 impl.digests.append('%s=%s' % (aname, avalue))
823 elif elem.name == 'recipe':
824 recipe = Recipe()
825 for recipe_step in elem.childNodes:
826 if recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'archive':
827 url = recipe_step.getAttribute('href')
828 if not url:
829 raise InvalidInterface(_("Missing href attribute on <archive>"))
830 size = recipe_step.getAttribute('size')
831 if not size:
832 raise InvalidInterface(_("Missing size attribute on <archive>"))
833 recipe.steps.append(DownloadSource(None, url = url, size = long(size),
834 extract = recipe_step.getAttribute('extract'),
835 start_offset = _get_long(recipe_step, 'start-offset'),
836 type = recipe_step.getAttribute('type')))
837 else:
838 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step.name)
839 break
840 else:
841 impl.download_sources.append(recipe)
843 def process_native_impl(item, item_attrs, depends):
844 package = item_attrs.get('package', None)
845 if package is None:
846 raise InvalidInterface(_("Missing 'package' attribute on %s") % item)
848 def factory(id):
849 assert id.startswith('package:')
850 if id in self.implementations:
851 warn(_("Duplicate ID '%s' for DistributionImplementation"), id)
852 impl = DistributionImplementation(self, id, distro)
853 self.implementations[id] = impl
855 impl.metadata = item_attrs
857 item_main = item_attrs.get('main', None)
858 if item_main and not item_main.startswith('/'):
859 raise InvalidInterface(_("'main' attribute must be absolute, but '%s' doesn't start with '/'!") %
860 item_main)
861 impl.main = item_main
862 impl.upstream_stability = packaged
863 impl.requires = depends
865 return impl
867 distro.get_package_info(package, factory)
869 root_attrs = {'stability': 'testing'}
870 if main:
871 root_attrs['main'] = main
872 process_group(feed_element, root_attrs, [], [])
874 for args in package_impls[1]:
875 process_native_impl(*args)
877 def get_name(self):
878 return self.name or '(' + os.path.basename(self.url) + ')'
880 def __repr__(self):
881 return _("<Feed %s>") % self.url
883 """@deprecated"""
884 def _get_impl(self, id):
885 assert id not in self.implementations
887 if id.startswith('.') or id.startswith('/'):
888 id = os.path.abspath(os.path.join(self.url, id))
889 local_path = id
890 impl = ZeroInstallImplementation(self, id, local_path)
891 else:
892 impl = ZeroInstallImplementation(self, id, None)
893 impl.digests.append(id)
895 self.implementations[id] = impl
896 return impl
898 def set_stability_policy(self, new):
899 assert new is None or isinstance(new, Stability)
900 self.stability_policy = new
902 def get_feed(self, url):
903 for x in self.feeds:
904 if x.uri == url:
905 return x
906 return None
908 def add_metadata(self, elem):
909 self.metadata.append(elem)
911 def get_metadata(self, uri, name):
912 """Return a list of interface metadata elements with this name and namespace URI."""
913 return [m for m in self.metadata if m.name == name and m.uri == uri]
915 class DummyFeed(object):
916 """Temporary class used during API transition."""
917 last_modified = None
918 name = '-'
919 last_checked = property(lambda self: None)
920 implementations = property(lambda self: {})
921 feeds = property(lambda self: [])
922 summary = property(lambda self: '-')
923 description = property(lambda self: '')
924 def get_name(self): return self.name
925 def get_feed(self, url): return None
926 def get_metadata(self, uri, name): return []
927 _dummy_feed = DummyFeed()
929 def unescape(uri):
930 """Convert each %20 to a space, etc.
931 @rtype: str"""
932 uri = uri.replace('#', '/')
933 if '%' not in uri: return uri
934 return re.sub('%[0-9a-fA-F][0-9a-fA-F]',
935 lambda match: chr(int(match.group(0)[1:], 16)),
936 uri).decode('utf-8')
938 def escape(uri):
939 """Convert each space to %20, etc
940 @rtype: str"""
941 return re.sub('[^-_.a-zA-Z0-9]',
942 lambda match: '%%%02x' % ord(match.group(0)),
943 uri.encode('utf-8'))
945 def _pretty_escape(uri):
946 """Convert each space to %20, etc
947 : is preserved and / becomes #. This makes for nicer strings,
948 and may replace L{escape} everywhere in future.
949 @rtype: str"""
950 return re.sub('[^-_.a-zA-Z0-9:/]',
951 lambda match: '%%%02x' % ord(match.group(0)),
952 uri.encode('utf-8')).replace('/', '#')
954 def canonical_iface_uri(uri):
955 """If uri is a relative path, convert to an absolute one.
956 A "file:///foo" URI is converted to "/foo".
957 Otherwise, return it unmodified.
958 @rtype: str
959 @raise SafeException: if uri isn't valid
961 if uri.startswith('http://') or uri.startswith('https://'):
962 if uri.count("/") < 3:
963 raise SafeException(_("Missing / after hostname in URI '%s'") % uri)
964 return uri
965 elif uri.startswith('file:///'):
966 return uri[7:]
967 else:
968 iface_uri = os.path.realpath(uri)
969 if os.path.isfile(iface_uri):
970 return iface_uri
971 raise SafeException(_("Bad interface name '%(uri)s'.\n"
972 "(doesn't start with 'http:', and "
973 "doesn't exist as a local file '%(interface_uri)s' either)") %
974 {'uri': uri, 'interface_uri': iface_uri})
976 _version_mod_to_value = {
977 'pre': -2,
978 'rc': -1,
979 '': 0,
980 'post': 1,
983 # Reverse mapping
984 _version_value_to_mod = {}
985 for x in _version_mod_to_value: _version_value_to_mod[_version_mod_to_value[x]] = x
986 del x
988 _version_re = re.compile('-([a-z]*)')
990 def parse_version(version_string):
991 """Convert a version string to an internal representation.
992 The parsed format can be compared quickly using the standard Python functions.
993 - Version := DottedList ("-" Mod DottedList?)*
994 - DottedList := (Integer ("." Integer)*)
995 @rtype: tuple (opaque)
996 @raise SafeException: if the string isn't a valid version
997 @since: 0.24 (moved from L{reader}, from where it is still available):"""
998 if version_string is None: return None
999 parts = _version_re.split(version_string)
1000 if parts[-1] == '':
1001 del parts[-1] # Ends with a modifier
1002 else:
1003 parts.append('')
1004 if not parts:
1005 raise SafeException(_("Empty version string!"))
1006 l = len(parts)
1007 try:
1008 for x in range(0, l, 2):
1009 part = parts[x]
1010 if part:
1011 parts[x] = map(int, parts[x].split('.'))
1012 else:
1013 parts[x] = [] # (because ''.split('.') == [''], not [])
1014 for x in range(1, l, 2):
1015 parts[x] = _version_mod_to_value[parts[x]]
1016 return parts
1017 except ValueError, ex:
1018 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1019 except KeyError, ex:
1020 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1022 def format_version(version):
1023 """Format a parsed version for display. Undoes the effect of L{parse_version}.
1024 @see: L{Implementation.get_version}
1025 @rtype: str
1026 @since: 0.24"""
1027 version = version[:]
1028 l = len(version)
1029 for x in range(0, l, 2):
1030 version[x] = '.'.join(map(str, version[x]))
1031 for x in range(1, l, 2):
1032 version[x] = '-' + _version_value_to_mod[version[x]]
1033 if version[-1] == '-': del version[-1]
1034 return ''.join(version)