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