Don't abort if a local feed is missing
[zeroinstall.git] / zeroinstall / injector / model.py
blob31028ffa500843414750840436d8414910525ae7
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, locale
18 from logging import info, debug, warn
19 from zeroinstall import SafeException, version
20 from zeroinstall.injector.namespaces import XMLNS_IFACE
21 from zeroinstall.injector import qdom
23 # Element names for bindings in feed files
24 binding_names = frozenset(['environment', 'overlay'])
26 network_offline = 'off-line'
27 network_minimal = 'minimal'
28 network_full = 'full'
29 network_levels = (network_offline, network_minimal, network_full)
31 stability_levels = {} # Name -> Stability
33 defaults = {
34 'PATH': '/bin:/usr/bin',
35 'XDG_CONFIG_DIRS': '/etc/xdg',
36 'XDG_DATA_DIRS': '/usr/local/share:/usr/share',
39 class InvalidInterface(SafeException):
40 """Raised when parsing an invalid feed."""
41 feed_url = None
43 def __init__(self, message, ex = None):
44 if ex:
45 try:
46 message += "\n\n(exact error: %s)" % ex
47 except:
48 # Some Python messages have type str but contain UTF-8 sequences.
49 # (e.g. IOException). Adding these to a Unicode 'message' (e.g.
50 # after gettext translation) will cause an error.
51 import codecs
52 decoder = codecs.lookup('utf-8')
53 decex = decoder.decode(str(ex), errors = 'replace')[0]
54 message += "\n\n(exact error: %s)" % decex
56 SafeException.__init__(self, message)
58 def __unicode__(self):
59 if hasattr(SafeException, '__unicode__'):
60 # Python >= 2.6
61 if self.feed_url:
62 return _('%s [%s]') % (SafeException.__unicode__(self), self.feed_url)
63 return SafeException.__unicode__(self)
64 else:
65 return unicode(SafeException.__str__(self))
67 def _split_arch(arch):
68 """Split an arch into an (os, machine) tuple. Either or both parts may be None."""
69 if not arch:
70 return None, None
71 elif '-' not in arch:
72 raise SafeException(_("Malformed arch '%s'") % arch)
73 else:
74 osys, machine = arch.split('-', 1)
75 if osys == '*': osys = None
76 if machine == '*': machine = None
77 return osys, machine
79 def _join_arch(osys, machine):
80 if osys == machine == None: return None
81 return "%s-%s" % (osys or '*', machine or '*')
83 def _best_language_match(options):
84 (language, encoding) = locale.getlocale()
86 if language:
87 # xml:lang uses '-', while LANG uses '_'
88 language = language.replace('_', '-')
89 else:
90 language = 'en-US'
92 return (options.get(language, None) or # Exact match (language+region)
93 options.get(language.split('-', 1)[0], None) or # Matching language
94 options.get('en', None)) # English
96 class Stability(object):
97 """A stability rating. Each implementation has an upstream stability rating and,
98 optionally, a user-set rating."""
99 __slots__ = ['level', 'name', 'description']
100 def __init__(self, level, name, description):
101 self.level = level
102 self.name = name
103 self.description = description
104 assert name not in stability_levels
105 stability_levels[name] = self
107 def __cmp__(self, other):
108 return cmp(self.level, other.level)
110 def __str__(self):
111 return self.name
113 def __repr__(self):
114 return _("<Stability: %s>") % self.description
116 def process_binding(e):
117 """Internal"""
118 if e.name == 'environment':
119 mode = {
120 None: EnvironmentBinding.PREPEND,
121 'prepend': EnvironmentBinding.PREPEND,
122 'append': EnvironmentBinding.APPEND,
123 'replace': EnvironmentBinding.REPLACE,
124 }[e.getAttribute('mode')]
126 binding = EnvironmentBinding(e.getAttribute('name'),
127 insert = e.getAttribute('insert'),
128 default = e.getAttribute('default'),
129 value = e.getAttribute('value'),
130 mode = mode)
131 if not binding.name: raise InvalidInterface(_("Missing 'name' in binding"))
132 if binding.insert is None and binding.value is None:
133 raise InvalidInterface(_("Missing 'insert' or 'value' in binding"))
134 if binding.insert is not None and binding.value is not None:
135 raise InvalidInterface(_("Binding contains both 'insert' and 'value'"))
136 return binding
137 elif e.name == 'overlay':
138 return OverlayBinding(e.getAttribute('src'), e.getAttribute('mount-point'))
139 else:
140 raise Exception(_("Unknown binding type '%s'") % e.name)
142 def process_depends(item, local_feed_dir):
143 """Internal"""
144 # Note: also called from selections
145 attrs = item.attrs
146 dep_iface = item.getAttribute('interface')
147 if not dep_iface:
148 raise InvalidInterface(_("Missing 'interface' on <%s>") % item.name)
149 if dep_iface.startswith('./'):
150 if local_feed_dir:
151 dep_iface = os.path.abspath(os.path.join(local_feed_dir, dep_iface))
152 # (updates the element too, in case we write it out again)
153 attrs['interface'] = dep_iface
154 else:
155 raise InvalidInterface(_('Relative interface URI "%s" in non-local feed') % dep_iface)
156 dependency = InterfaceDependency(dep_iface, element = item)
158 for e in item.childNodes:
159 if e.uri != XMLNS_IFACE: continue
160 if e.name in binding_names:
161 dependency.bindings.append(process_binding(e))
162 elif e.name == 'version':
163 dependency.restrictions.append(
164 VersionRangeRestriction(not_before = parse_version(e.getAttribute('not-before')),
165 before = parse_version(e.getAttribute('before'))))
166 return dependency
168 def N_(message): return message
170 insecure = Stability(0, N_('insecure'), _('This is a security risk'))
171 buggy = Stability(5, N_('buggy'), _('Known to have serious bugs'))
172 developer = Stability(10, N_('developer'), _('Work-in-progress - bugs likely'))
173 testing = Stability(20, N_('testing'), _('Stability unknown - please test!'))
174 stable = Stability(30, N_('stable'), _('Tested - no serious problems found'))
175 packaged = Stability(35, N_('packaged'), _('Supplied by the local package manager'))
176 preferred = Stability(40, N_('preferred'), _('Best of all - must be set manually'))
178 del N_
180 class Restriction(object):
181 """A Restriction limits the allowed implementations of an Interface."""
182 __slots__ = []
184 def meets_restriction(self, impl):
185 """Called by the L{solver.Solver} to check whether a particular implementation is acceptable.
186 @return: False if this implementation is not a possibility
187 @rtype: bool
189 raise NotImplementedError(_("Abstract"))
191 class VersionRestriction(Restriction):
192 """Only select implementations with a particular version number.
193 @since: 0.40"""
195 def __init__(self, version):
196 """@param version: the required version number
197 @see: L{parse_version}; use this to pre-process the version number
199 self.version = version
201 def meets_restriction(self, impl):
202 return impl.version == self.version
204 def __str__(self):
205 return _("(restriction: version = %s)") % format_version(self.version)
207 class VersionRangeRestriction(Restriction):
208 """Only versions within the given range are acceptable"""
209 __slots__ = ['before', 'not_before']
211 def __init__(self, before, not_before):
212 """@param before: chosen versions must be earlier than this
213 @param not_before: versions must be at least this high
214 @see: L{parse_version}; use this to pre-process the versions
216 self.before = before
217 self.not_before = not_before
219 def meets_restriction(self, impl):
220 if self.not_before and impl.version < self.not_before:
221 return False
222 if self.before and impl.version >= self.before:
223 return False
224 return True
226 def __str__(self):
227 if self.not_before is not None or self.before is not None:
228 range = ''
229 if self.not_before is not None:
230 range += format_version(self.not_before) + ' <= '
231 range += 'version'
232 if self.before is not None:
233 range += ' < ' + format_version(self.before)
234 else:
235 range = 'none'
236 return _("(restriction: %s)") % range
238 class Binding(object):
239 """Information about how the choice of a Dependency is made known
240 to the application being run."""
242 class EnvironmentBinding(Binding):
243 """Indicate the chosen implementation using an environment variable."""
244 __slots__ = ['name', 'insert', 'default', 'mode', 'value']
246 PREPEND = 'prepend'
247 APPEND = 'append'
248 REPLACE = 'replace'
250 def __init__(self, name, insert, default = None, mode = PREPEND, value=None):
252 mode argument added in version 0.28
253 value argument added in version 0.52
255 self.name = name
256 self.insert = insert
257 self.default = default
258 self.mode = mode
259 self.value = value
261 def __str__(self):
262 return _("<environ %(name)s %(mode)s %(insert)s %(value)s>") % {'name': self.name,'mode': self.mode, 'insert': self.insert, 'value': self.value}
264 __repr__ = __str__
266 def get_value(self, path, old_value):
267 """Calculate the new value of the environment variable after applying this binding.
268 @param path: the path to the selected implementation
269 @param old_value: the current value of the environment variable
270 @return: the new value for the environment variable"""
272 if self.insert is not None:
273 extra = os.path.join(path, self.insert)
274 else:
275 assert self.value is not None
276 extra = self.value
278 if self.mode == EnvironmentBinding.REPLACE:
279 return extra
281 if old_value is None:
282 old_value = self.default or defaults.get(self.name, None)
283 if old_value is None:
284 return extra
285 if self.mode == EnvironmentBinding.PREPEND:
286 return extra + os.pathsep + old_value
287 else:
288 return old_value + os.pathsep + extra
290 def _toxml(self, doc):
291 """Create a DOM element for this binding.
292 @param doc: document to use to create the element
293 @return: the new element
295 env_elem = doc.createElementNS(XMLNS_IFACE, 'environment')
296 env_elem.setAttributeNS(None, 'name', self.name)
297 if self.insert is not None:
298 env_elem.setAttributeNS(None, 'insert', self.insert)
299 else:
300 env_elem.setAttributeNS(None, 'value', self.value)
301 if self.default:
302 env_elem.setAttributeNS(None, 'default', self.default)
303 return env_elem
305 class OverlayBinding(Binding):
306 """Make the chosen implementation available by overlaying it onto another part of the file-system.
307 This is to support legacy programs which use hard-coded paths."""
308 __slots__ = ['src', 'mount_point']
310 def __init__(self, src, mount_point):
311 self.src = src
312 self.mount_point = mount_point
314 def __str__(self):
315 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self.src or '.', 'mount_point': self.mount_point or '/'}
317 __repr__ = __str__
319 def _toxml(self, doc):
320 """Create a DOM element for this binding.
321 @param doc: document to use to create the element
322 @return: the new element
324 env_elem = doc.createElementNS(XMLNS_IFACE, 'overlay')
325 if self.src is not None:
326 env_elem.setAttributeNS(None, 'src', self.src)
327 if self.mount_point is not None:
328 env_elem.setAttributeNS(None, 'mount-point', self.mount_point)
329 return env_elem
331 class Feed(object):
332 """An interface's feeds are other interfaces whose implementations can also be
333 used as implementations of this interface."""
334 __slots__ = ['uri', 'os', 'machine', 'user_override', 'langs']
335 def __init__(self, uri, arch, user_override, langs = None):
336 self.uri = uri
337 # This indicates whether the feed comes from the user's overrides
338 # file. If true, writer.py will write it when saving.
339 self.user_override = user_override
340 self.os, self.machine = _split_arch(arch)
341 self.langs = langs
343 def __str__(self):
344 return "<Feed from %s>" % self.uri
345 __repr__ = __str__
347 arch = property(lambda self: _join_arch(self.os, self.machine))
349 class Dependency(object):
350 """A Dependency indicates that an Implementation requires some additional
351 code to function. This is an abstract base class.
352 @ivar qdom: the XML element for this Dependency (since 0launch 0.51)
353 @type qdom: L{qdom.Element}
354 @ivar metadata: any extra attributes from the XML element
355 @type metadata: {str: str}
357 __slots__ = ['qdom']
359 def __init__(self, element):
360 assert isinstance(element, qdom.Element), type(element) # Use InterfaceDependency instead!
361 self.qdom = element
363 @property
364 def metadata(self):
365 return self.qdom.attrs
367 class InterfaceDependency(Dependency):
368 """A Dependency on a Zero Install interface.
369 @ivar interface: the interface required by this dependency
370 @type interface: str
371 @ivar restrictions: a list of constraints on acceptable implementations
372 @type restrictions: [L{Restriction}]
373 @ivar bindings: how to make the choice of implementation known
374 @type bindings: [L{Binding}]
375 @since: 0.28
377 __slots__ = ['interface', 'restrictions', 'bindings']
379 def __init__(self, interface, restrictions = None, element = None):
380 Dependency.__init__(self, element)
381 assert isinstance(interface, (str, unicode))
382 assert interface
383 self.interface = interface
384 if restrictions is None:
385 self.restrictions = []
386 else:
387 self.restrictions = restrictions
388 self.bindings = []
390 def __str__(self):
391 return _("<Dependency on %(interface)s; bindings: %(bindings)s%(restrictions)s>") % {'interface': self.interface, 'bindings': self.bindings, 'restrictions': self.restrictions}
393 class RetrievalMethod(object):
394 """A RetrievalMethod provides a way to fetch an implementation."""
395 __slots__ = []
397 class DownloadSource(RetrievalMethod):
398 """A DownloadSource provides a way to fetch an implementation."""
399 __slots__ = ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
401 def __init__(self, implementation, url, size, extract, start_offset = 0, type = None):
402 self.implementation = implementation
403 self.url = url
404 self.size = size
405 self.extract = extract
406 self.start_offset = start_offset
407 self.type = type # MIME type - see unpack.py
409 class Recipe(RetrievalMethod):
410 """Get an implementation by following a series of steps.
411 @ivar size: the combined download sizes from all the steps
412 @type size: int
413 @ivar steps: the sequence of steps which must be performed
414 @type steps: [L{RetrievalMethod}]"""
415 __slots__ = ['steps']
417 def __init__(self):
418 self.steps = []
420 size = property(lambda self: sum([x.size for x in self.steps]))
422 class DistributionSource(RetrievalMethod):
423 """A package that is installed using the distribution's tools (including PackageKit).
424 @ivar install: a function to call to install this package
425 @type install: (L{handler.Handler}) -> L{tasks.Blocker}
426 @ivar package_id: the package name, in a form recognised by the distribution's tools
427 @type package_id: str
428 @ivar size: the download size in bytes
429 @type size: int
430 @ivar needs_confirmation: whether the user should be asked to confirm before calling install()
431 @type needs_confirmation: bool"""
433 __slots__ = ['package_id', 'size', 'install', 'needs_confirmation']
435 def __init__(self, package_id, size, install, needs_confirmation = True):
436 RetrievalMethod.__init__(self)
437 self.package_id = package_id
438 self.size = size
439 self.install = install
440 self.needs_confirmation = needs_confirmation
442 class Command(object):
443 """A Command is a way of running an Implementation as a program."""
445 __slots__ = ['qdom', '_depends', '_local_dir', '_runner']
447 def __init__(self, qdom, local_dir):
448 """@param qdom: the <command> element
449 @param local_dir: the directory containing the feed (for relative dependencies), or None if not local
451 assert qdom.name == 'command', 'not <command>: %s' % qdom
452 self.qdom = qdom
453 self._local_dir = local_dir
454 self._depends = None
456 path = property(lambda self: self.qdom.attrs.get("path", None))
458 def _toxml(self, doc, prefixes):
459 return self.qdom.toDOM(doc, prefixes)
461 @property
462 def requires(self):
463 if self._depends is None:
464 self._runner = None
465 depends = []
466 for child in self.qdom.childNodes:
467 if child.name == 'requires':
468 dep = process_depends(child, self._local_dir)
469 depends.append(dep)
470 elif child.name == 'runner':
471 if self._runner:
472 raise InvalidInterface(_("Multiple <runner>s in <command>!"))
473 dep = process_depends(child, self._local_dir)
474 depends.append(dep)
475 self._runner = dep
476 self._depends = depends
477 return self._depends
479 def get_runner(self):
480 self.requires # (sets _runner)
481 return self._runner
483 class Implementation(object):
484 """An Implementation is a package which implements an Interface.
485 @ivar download_sources: list of methods of getting this implementation
486 @type download_sources: [L{RetrievalMethod}]
487 @ivar feed: the feed owning this implementation (since 0.32)
488 @type feed: [L{ZeroInstallFeed}]
489 @ivar bindings: how to tell this component where it itself is located (since 0.31)
490 @type bindings: [Binding]
491 @ivar upstream_stability: the stability reported by the packager
492 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged]
493 @ivar user_stability: the stability as set by the user
494 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred]
495 @ivar langs: natural languages supported by this package
496 @type langs: str
497 @ivar requires: interfaces this package depends on
498 @type requires: [L{Dependency}]
499 @ivar commands: ways to execute as a program
500 @type commands: {str: Command}
501 @ivar metadata: extra metadata from the feed
502 @type metadata: {"[URI ]localName": str}
503 @ivar id: a unique identifier for this Implementation
504 @ivar version: a parsed version number
505 @ivar released: release date
506 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path)
507 @type local_path: str | None
508 @ivar requires_root_install: whether the user will need admin rights to use this
509 @type requires_root_install: bool
512 # Note: user_stability shouldn't really be here
514 __slots__ = ['upstream_stability', 'user_stability', 'langs',
515 'requires', 'metadata', 'download_sources', 'commands',
516 'id', 'feed', 'version', 'released', 'bindings', 'machine']
518 def __init__(self, feed, id):
519 assert id
520 self.feed = feed
521 self.id = id
522 self.user_stability = None
523 self.upstream_stability = None
524 self.metadata = {} # [URI + " "] + localName -> value
525 self.requires = []
526 self.version = None
527 self.released = None
528 self.download_sources = []
529 self.langs = ""
530 self.machine = None
531 self.bindings = []
532 self.commands = {}
534 def get_stability(self):
535 return self.user_stability or self.upstream_stability or testing
537 def __str__(self):
538 return self.id
540 def __repr__(self):
541 return "v%s (%s)" % (self.get_version(), self.id)
543 def __cmp__(self, other):
544 """Newer versions come first"""
545 d = cmp(other.version, self.version)
546 if d: return d
547 # If the version number is the same, just give a stable sort order, and
548 # ensure that two different implementations don't compare equal.
549 d = cmp(other.feed.url, self.feed.url)
550 if d: return d
551 return cmp(other.id, self.id)
553 def get_version(self):
554 """Return the version as a string.
555 @see: L{format_version}
557 return format_version(self.version)
559 arch = property(lambda self: _join_arch(self.os, self.machine))
561 os = None
562 local_path = None
563 digests = None
564 requires_root_install = False
566 def _get_main(self):
567 """"@deprecated: use commands["run"] instead"""
568 main = self.commands.get("run", None)
569 if main is not None:
570 return main.path
571 return None
572 def _set_main(self, path):
573 """"@deprecated: use commands["run"] instead"""
574 if path is None:
575 if "run" in self.commands:
576 del self.commands["run"]
577 else:
578 self.commands["run"] = Command(qdom.Element(XMLNS_IFACE, 'command', {'path': path}), None)
579 main = property(_get_main, _set_main)
581 def is_available(self, stores):
582 """Is this Implementation available locally?
583 (a local implementation, an installed distribution package, or a cached ZeroInstallImplementation)
584 @rtype: bool
585 @since: 0.53
587 raise NotImplementedError("abstract")
589 class DistributionImplementation(Implementation):
590 """An implementation provided by the distribution. Information such as the version
591 comes from the package manager.
592 @since: 0.28"""
593 __slots__ = ['distro', 'installed']
595 def __init__(self, feed, id, distro):
596 assert id.startswith('package:')
597 Implementation.__init__(self, feed, id)
598 self.distro = distro
599 self.installed = False
601 @property
602 def requires_root_install(self):
603 return not self.installed
605 def is_available(self, stores):
606 return self.installed
608 class ZeroInstallImplementation(Implementation):
609 """An implementation where all the information comes from Zero Install.
610 @ivar digests: a list of "algorith=value" strings (since 0.45)
611 @type digests: [str]
612 @since: 0.28"""
613 __slots__ = ['os', 'size', 'digests', 'local_path']
615 def __init__(self, feed, id, local_path):
616 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
617 assert not id.startswith('package:'), id
618 Implementation.__init__(self, feed, id)
619 self.size = None
620 self.os = None
621 self.digests = []
622 self.local_path = local_path
624 # Deprecated
625 dependencies = property(lambda self: dict([(x.interface, x) for x in self.requires
626 if isinstance(x, InterfaceDependency)]))
628 def add_download_source(self, url, size, extract, start_offset = 0, type = None):
629 """Add a download source."""
630 self.download_sources.append(DownloadSource(self, url, size, extract, start_offset, type))
632 def set_arch(self, arch):
633 self.os, self.machine = _split_arch(arch)
634 arch = property(lambda self: _join_arch(self.os, self.machine), set_arch)
636 def is_available(self, stores):
637 if self.local_path is not None:
638 return os.path.exists(self.local_path)
639 if self.digests:
640 path = stores.lookup_maybe(self.digests)
641 return path is not None
642 return False # (0compile creates fake entries with no digests)
644 class Interface(object):
645 """An Interface represents some contract of behaviour.
646 @ivar uri: the URI for this interface.
647 @ivar stability_policy: user's configured policy.
648 Implementations at this level or higher are preferred.
649 Lower levels are used only if there is no other choice.
651 __slots__ = ['uri', 'stability_policy', 'extra_feeds']
653 implementations = property(lambda self: self._main_feed.implementations)
654 name = property(lambda self: self._main_feed.name)
655 description = property(lambda self: self._main_feed.description)
656 summary = property(lambda self: self._main_feed.summary)
657 last_modified = property(lambda self: self._main_feed.last_modified)
658 feeds = property(lambda self: self.extra_feeds + self._main_feed.feeds)
659 metadata = property(lambda self: self._main_feed.metadata)
661 last_checked = property(lambda self: self._main_feed.last_checked)
663 def __init__(self, uri):
664 assert uri
665 if uri.startswith('http:') or uri.startswith('https:') or os.path.isabs(uri):
666 self.uri = uri
667 else:
668 raise SafeException(_("Interface name '%s' doesn't start "
669 "with 'http:' or 'https:'") % uri)
670 self.reset()
672 def _get_feed_for(self):
673 retval = {}
674 for key in self._main_feed.feed_for:
675 retval[key] = True
676 return retval
677 feed_for = property(_get_feed_for) # Deprecated (used by 0publish)
679 def reset(self):
680 self.extra_feeds = []
681 self.stability_policy = None
683 def get_name(self):
684 from zeroinstall.injector.iface_cache import iface_cache
685 feed = iface_cache.get_feed(self.uri)
686 if feed:
687 return feed.get_name()
688 return '(' + os.path.basename(self.uri) + ')'
690 def __repr__(self):
691 return _("<Interface %s>") % self.uri
693 def set_stability_policy(self, new):
694 assert new is None or isinstance(new, Stability)
695 self.stability_policy = new
697 def get_feed(self, url):
698 #import warnings
699 #warnings.warn("use iface_cache.get_feed instead", DeprecationWarning, 2)
700 for x in self.extra_feeds:
701 if x.uri == url:
702 return x
703 #return self._main_feed.get_feed(url)
704 return None
706 def get_metadata(self, uri, name):
707 return self._main_feed.get_metadata(uri, name)
709 @property
710 def _main_feed(self):
711 #import warnings
712 #warnings.warn("use the feed instead", DeprecationWarning, 3)
713 from zeroinstall.injector import policy
714 iface_cache = policy.get_deprecated_singleton_config().iface_cache
715 feed = iface_cache.get_feed(self.uri)
716 if feed is None:
717 return _dummy_feed
718 return feed
720 def _merge_attrs(attrs, item):
721 """Add each attribute of item to a copy of attrs and return the copy.
722 @type attrs: {str: str}
723 @type item: L{qdom.Element}
724 @rtype: {str: str}
726 new = attrs.copy()
727 for a in item.attrs:
728 new[str(a)] = item.attrs[a]
729 return new
731 def _get_long(elem, attr_name):
732 val = elem.getAttribute(attr_name)
733 if val is not None:
734 try:
735 val = int(val)
736 except ValueError:
737 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name, 'value': val})
738 return val
740 class ZeroInstallFeed(object):
741 """A feed lists available implementations of an interface.
742 @ivar url: the URL for this feed
743 @ivar implementations: Implementations in this feed, indexed by ID
744 @type implementations: {str: L{Implementation}}
745 @ivar name: human-friendly name
746 @ivar summaries: short textual description (in various languages, since 0.49)
747 @type summaries: {str: str}
748 @ivar descriptions: long textual description (in various languages, since 0.49)
749 @type descriptions: {str: str}
750 @ivar last_modified: timestamp on signature
751 @ivar last_checked: time feed was last successfully downloaded and updated
752 @ivar feeds: list of <feed> elements in this feed
753 @type feeds: [L{Feed}]
754 @ivar feed_for: interfaces for which this could be a feed
755 @type feed_for: set(str)
756 @ivar metadata: extra elements we didn't understand
758 # _main is deprecated
759 __slots__ = ['url', 'implementations', 'name', 'descriptions', 'first_description', 'summaries', 'first_summary', '_package_implementations',
760 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
762 def __init__(self, feed_element, local_path = None, distro = None):
763 """Create a feed object from a DOM.
764 @param feed_element: the root element of a feed file
765 @type feed_element: L{qdom.Element}
766 @param local_path: the pathname of this local feed, or None for remote feeds"""
767 self.implementations = {}
768 self.name = None
769 self.summaries = {} # { lang: str }
770 self.first_summary = None
771 self.descriptions = {} # { lang: str }
772 self.first_description = None
773 self.last_modified = None
774 self.feeds = []
775 self.feed_for = set()
776 self.metadata = []
777 self.last_checked = None
778 self._package_implementations = []
780 if distro is not None:
781 import warnings
782 warnings.warn("distro argument is now ignored", DeprecationWarning, 2)
784 if feed_element is None:
785 return # XXX subclass?
787 assert feed_element.name in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
788 assert feed_element.uri == XMLNS_IFACE, "Wrong namespace on root element: %s" % feed_element.uri
790 main = feed_element.getAttribute('main')
791 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
793 if local_path:
794 self.url = local_path
795 local_dir = os.path.dirname(local_path)
796 else:
797 self.url = feed_element.getAttribute('uri')
798 if not self.url:
799 raise InvalidInterface(_("<interface> uri attribute missing"))
800 local_dir = None # Can't have relative paths
802 min_injector_version = feed_element.getAttribute('min-injector-version')
803 if min_injector_version:
804 if parse_version(min_injector_version) > parse_version(version):
805 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
806 "Zero Install, but I am only version %(version)s. "
807 "You can get a newer version from http://0install.net") %
808 {'min_version': min_injector_version, 'version': version})
810 for x in feed_element.childNodes:
811 if x.uri != XMLNS_IFACE:
812 self.metadata.append(x)
813 continue
814 if x.name == 'name':
815 self.name = x.content
816 elif x.name == 'description':
817 if self.first_description == None:
818 self.first_description = x.content
819 self.descriptions[x.attrs.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x.content
820 elif x.name == 'summary':
821 if self.first_summary == None:
822 self.first_summary = x.content
823 self.summaries[x.attrs.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x.content
824 elif x.name == 'feed-for':
825 feed_iface = x.getAttribute('interface')
826 if not feed_iface:
827 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
828 self.feed_for.add(feed_iface)
829 # Bug report from a Debian/stable user that --feed gets the wrong value.
830 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
831 # in case it happens again.
832 debug(_("Is feed-for %s"), feed_iface)
833 elif x.name == 'feed':
834 feed_src = x.getAttribute('src')
835 if not feed_src:
836 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
837 if feed_src.startswith('http:') or feed_src.startswith('https:') or local_path:
838 langs = x.getAttribute('langs')
839 if langs: langs = langs.replace('_', '-')
840 self.feeds.append(Feed(feed_src, x.getAttribute('arch'), False, langs = langs))
841 else:
842 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src)
843 else:
844 self.metadata.append(x)
846 if not self.name:
847 raise InvalidInterface(_("Missing <name> in feed"))
848 if not self.summary:
849 raise InvalidInterface(_("Missing <summary> in feed"))
851 def process_group(group, group_attrs, base_depends, base_bindings, base_commands):
852 for item in group.childNodes:
853 if item.uri != XMLNS_IFACE: continue
855 if item.name not in ('group', 'implementation', 'package-implementation'):
856 continue
858 # We've found a group or implementation. Scan for dependencies,
859 # bindings and commands. Doing this here means that:
860 # - We can share the code for groups and implementations here.
861 # - The order doesn't matter, because these get processed first.
862 # A side-effect is that the document root cannot contain
863 # these.
865 depends = base_depends[:]
866 bindings = base_bindings[:]
867 commands = base_commands.copy()
869 for attr, command in [('main', 'run'),
870 ('self-test', 'test')]:
871 value = item.attrs.get(attr, None)
872 if value is not None:
873 commands[command] = Command(qdom.Element(XMLNS_IFACE, 'command', {'path': value}), None)
875 for child in item.childNodes:
876 if child.uri != XMLNS_IFACE: continue
877 if child.name == 'requires':
878 dep = process_depends(child, local_dir)
879 depends.append(dep)
880 elif child.name == 'command':
881 command_name = child.attrs.get('name', None)
882 if not command_name:
883 raise InvalidInterface('Missing name for <command>')
884 commands[command_name] = Command(child, local_dir)
885 elif child.name in binding_names:
886 bindings.append(process_binding(child))
888 compile_command = item.attrs.get('http://zero-install.sourceforge.net/2006/namespaces/0compile command')
889 if compile_command is not None:
890 commands['compile'] = Command(qdom.Element(XMLNS_IFACE, 'command', {'shell-command': compile_command}), None)
892 item_attrs = _merge_attrs(group_attrs, item)
894 if item.name == 'group':
895 process_group(item, item_attrs, depends, bindings, commands)
896 elif item.name == 'implementation':
897 process_impl(item, item_attrs, depends, bindings, commands)
898 elif item.name == 'package-implementation':
899 if depends:
900 warn("A <package-implementation> with dependencies in %s!", self.url)
901 self._package_implementations.append((item, item_attrs))
902 else:
903 assert 0
905 def process_impl(item, item_attrs, depends, bindings, commands):
906 id = item.getAttribute('id')
907 if id is None:
908 raise InvalidInterface(_("Missing 'id' attribute on %s") % item)
909 local_path = item_attrs.get('local-path')
910 if local_dir and local_path:
911 abs_local_path = os.path.abspath(os.path.join(local_dir, local_path))
912 impl = ZeroInstallImplementation(self, id, abs_local_path)
913 elif local_dir and (id.startswith('/') or id.startswith('.')):
914 # For old feeds
915 id = os.path.abspath(os.path.join(local_dir, id))
916 impl = ZeroInstallImplementation(self, id, id)
917 else:
918 impl = ZeroInstallImplementation(self, id, None)
919 if '=' in id:
920 # In older feeds, the ID was the (single) digest
921 impl.digests.append(id)
922 if id in self.implementations:
923 warn(_("Duplicate ID '%(id)s' in feed '%(feed)s'"), {'id': id, 'feed': self})
924 self.implementations[id] = impl
926 impl.metadata = item_attrs
927 try:
928 version_mod = item_attrs.get('version-modifier', None)
929 if version_mod:
930 item_attrs['version'] += version_mod
931 del item_attrs['version-modifier']
932 version = item_attrs['version']
933 except KeyError:
934 raise InvalidInterface(_("Missing version attribute"))
935 impl.version = parse_version(version)
937 impl.commands = commands
939 impl.released = item_attrs.get('released', None)
940 impl.langs = item_attrs.get('langs', '').replace('_', '-')
942 size = item.getAttribute('size')
943 if size:
944 impl.size = int(size)
945 impl.arch = item_attrs.get('arch', None)
946 try:
947 stability = stability_levels[str(item_attrs['stability'])]
948 except KeyError:
949 stab = str(item_attrs['stability'])
950 if stab != stab.lower():
951 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs.stability)
952 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs['stability'])
953 if stability >= preferred:
954 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
955 impl.upstream_stability = stability
957 impl.bindings = bindings
958 impl.requires = depends
960 for elem in item.childNodes:
961 if elem.uri != XMLNS_IFACE: continue
962 if elem.name == 'archive':
963 url = elem.getAttribute('href')
964 if not url:
965 raise InvalidInterface(_("Missing href attribute on <archive>"))
966 size = elem.getAttribute('size')
967 if not size:
968 raise InvalidInterface(_("Missing size attribute on <archive>"))
969 impl.add_download_source(url = url, size = int(size),
970 extract = elem.getAttribute('extract'),
971 start_offset = _get_long(elem, 'start-offset'),
972 type = elem.getAttribute('type'))
973 elif elem.name == 'manifest-digest':
974 for aname, avalue in elem.attrs.iteritems():
975 if ' ' not in aname:
976 impl.digests.append('%s=%s' % (aname, avalue))
977 elif elem.name == 'recipe':
978 recipe = Recipe()
979 for recipe_step in elem.childNodes:
980 if recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'archive':
981 url = recipe_step.getAttribute('href')
982 if not url:
983 raise InvalidInterface(_("Missing href attribute on <archive>"))
984 size = recipe_step.getAttribute('size')
985 if not size:
986 raise InvalidInterface(_("Missing size attribute on <archive>"))
987 recipe.steps.append(DownloadSource(None, url = url, size = int(size),
988 extract = recipe_step.getAttribute('extract'),
989 start_offset = _get_long(recipe_step, 'start-offset'),
990 type = recipe_step.getAttribute('type')))
991 else:
992 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step.name)
993 break
994 else:
995 impl.download_sources.append(recipe)
997 root_attrs = {'stability': 'testing'}
998 root_commands = {}
999 if main:
1000 info("Note: @main on document element is deprecated in %s", self)
1001 root_commands['run'] = Command(qdom.Element(XMLNS_IFACE, 'command', {'path': main}), None)
1002 process_group(feed_element, root_attrs, [], [], root_commands)
1004 def get_distro_feed(self):
1005 """Does this feed contain any <pacakge-implementation> elements?
1006 i.e. is it worth asking the package manager for more information?
1007 @return: the URL of the virtual feed, or None
1008 @since: 0.49"""
1009 if self._package_implementations:
1010 return "distribution:" + self.url
1011 return None
1013 def get_package_impls(self, distro):
1014 """Find the best <pacakge-implementation> element(s) for the given distribution.
1015 @param distro: the distribution to use to rate them
1016 @type distro: L{distro.Distribution}
1017 @return: a list of tuples for the best ranked elements
1018 @rtype: [str]
1019 @since: 0.49"""
1020 best_score = 0
1021 best_impls = []
1023 for item, item_attrs in self._package_implementations:
1024 distro_names = item_attrs.get('distributions', '')
1025 for distro_name in distro_names.split(' '):
1026 score = distro.get_score(distro_name)
1027 if score > best_score:
1028 best_score = score
1029 best_impls = []
1030 if score == best_score:
1031 best_impls.append((item, item_attrs))
1032 return best_impls
1034 def get_name(self):
1035 return self.name or '(' + os.path.basename(self.url) + ')'
1037 def __repr__(self):
1038 return _("<Feed %s>") % self.url
1040 def set_stability_policy(self, new):
1041 assert new is None or isinstance(new, Stability)
1042 self.stability_policy = new
1044 def get_feed(self, url):
1045 for x in self.feeds:
1046 if x.uri == url:
1047 return x
1048 return None
1050 def add_metadata(self, elem):
1051 self.metadata.append(elem)
1053 def get_metadata(self, uri, name):
1054 """Return a list of interface metadata elements with this name and namespace URI."""
1055 return [m for m in self.metadata if m.name == name and m.uri == uri]
1057 @property
1058 def summary(self):
1059 return _best_language_match(self.summaries) or self.first_summary
1061 @property
1062 def description(self):
1063 return _best_language_match(self.descriptions) or self.first_description
1065 class DummyFeed(object):
1066 """Temporary class used during API transition."""
1067 last_modified = None
1068 name = '-'
1069 last_checked = property(lambda self: None)
1070 implementations = property(lambda self: {})
1071 feeds = property(lambda self: [])
1072 summary = property(lambda self: '-')
1073 description = property(lambda self: '')
1074 def get_name(self): return self.name
1075 def get_feed(self, url): return None
1076 def get_metadata(self, uri, name): return []
1077 _dummy_feed = DummyFeed()
1079 def unescape(uri):
1080 """Convert each %20 to a space, etc.
1081 @rtype: str"""
1082 uri = uri.replace('#', '/')
1083 if '%' not in uri: return uri
1084 return re.sub('%[0-9a-fA-F][0-9a-fA-F]',
1085 lambda match: chr(int(match.group(0)[1:], 16)),
1086 uri).decode('utf-8')
1088 def escape(uri):
1089 """Convert each space to %20, etc
1090 @rtype: str"""
1091 return re.sub('[^-_.a-zA-Z0-9]',
1092 lambda match: '%%%02x' % ord(match.group(0)),
1093 uri.encode('utf-8'))
1095 def _pretty_escape(uri):
1096 """Convert each space to %20, etc
1097 : is preserved and / becomes #. This makes for nicer strings,
1098 and may replace L{escape} everywhere in future.
1099 @rtype: str"""
1100 return re.sub('[^-_.a-zA-Z0-9:/]',
1101 lambda match: '%%%02x' % ord(match.group(0)),
1102 uri.encode('utf-8')).replace('/', '#')
1104 def canonical_iface_uri(uri):
1105 """If uri is a relative path, convert to an absolute one.
1106 A "file:///foo" URI is converted to "/foo".
1107 An "alias:prog" URI expands to the URI in the 0alias script
1108 Otherwise, return it unmodified.
1109 @rtype: str
1110 @raise SafeException: if uri isn't valid
1112 if uri.startswith('http://') or uri.startswith('https://'):
1113 if uri.count("/") < 3:
1114 raise SafeException(_("Missing / after hostname in URI '%s'") % uri)
1115 return uri
1116 elif uri.startswith('file:///'):
1117 return uri[7:]
1118 elif uri.startswith('alias:'):
1119 from zeroinstall import alias, support
1120 alias_prog = uri[6:]
1121 if not os.path.isabs(alias_prog):
1122 full_path = support.find_in_path(alias_prog)
1123 if not full_path:
1124 raise alias.NotAnAliasScript("Not found in $PATH: " + alias_prog)
1125 else:
1126 full_path = alias_prog
1127 interface_uri, main = alias.parse_script(full_path)
1128 return interface_uri
1129 else:
1130 iface_uri = os.path.realpath(uri)
1131 if os.path.isfile(iface_uri):
1132 return iface_uri
1133 raise SafeException(_("Bad interface name '%(uri)s'.\n"
1134 "(doesn't start with 'http:', and "
1135 "doesn't exist as a local file '%(interface_uri)s' either)") %
1136 {'uri': uri, 'interface_uri': iface_uri})
1138 _version_mod_to_value = {
1139 'pre': -2,
1140 'rc': -1,
1141 '': 0,
1142 'post': 1,
1145 # Reverse mapping
1146 _version_value_to_mod = {}
1147 for x in _version_mod_to_value: _version_value_to_mod[_version_mod_to_value[x]] = x
1148 del x
1150 _version_re = re.compile('-([a-z]*)')
1152 def parse_version(version_string):
1153 """Convert a version string to an internal representation.
1154 The parsed format can be compared quickly using the standard Python functions.
1155 - Version := DottedList ("-" Mod DottedList?)*
1156 - DottedList := (Integer ("." Integer)*)
1157 @rtype: tuple (opaque)
1158 @raise SafeException: if the string isn't a valid version
1159 @since: 0.24 (moved from L{reader}, from where it is still available):"""
1160 if version_string is None: return None
1161 parts = _version_re.split(version_string)
1162 if parts[-1] == '':
1163 del parts[-1] # Ends with a modifier
1164 else:
1165 parts.append('')
1166 if not parts:
1167 raise SafeException(_("Empty version string!"))
1168 l = len(parts)
1169 try:
1170 for x in range(0, l, 2):
1171 part = parts[x]
1172 if part:
1173 parts[x] = map(int, parts[x].split('.'))
1174 else:
1175 parts[x] = [] # (because ''.split('.') == [''], not [])
1176 for x in range(1, l, 2):
1177 parts[x] = _version_mod_to_value[parts[x]]
1178 return parts
1179 except ValueError, ex:
1180 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1181 except KeyError, ex:
1182 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1184 def format_version(version):
1185 """Format a parsed version for display. Undoes the effect of L{parse_version}.
1186 @see: L{Implementation.get_version}
1187 @rtype: str
1188 @since: 0.24"""
1189 version = version[:]
1190 l = len(version)
1191 for x in range(0, l, 2):
1192 version[x] = '.'.join(map(str, version[x]))
1193 for x in range(1, l, 2):
1194 version[x] = '-' + _version_value_to_mod[version[x]]
1195 if version[-1] == '-': del version[-1]
1196 return ''.join(version)