Added <executable> binding
[zeroinstall.git] / zeroinstall / injector / model.py
blob042dd3ac83f2d7d0da11aac0faf297a738c901a2
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', 'executable'])
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 separator = e.getAttribute('separator'))
132 if not binding.name: raise InvalidInterface(_("Missing 'name' in binding"))
133 if binding.insert is None and binding.value is None:
134 raise InvalidInterface(_("Missing 'insert' or 'value' in binding"))
135 if binding.insert is not None and binding.value is not None:
136 raise InvalidInterface(_("Binding contains both 'insert' and 'value'"))
137 return binding
138 elif e.name == 'executable':
139 return ExecutableBinding(e)
140 elif e.name == 'overlay':
141 return OverlayBinding(e.getAttribute('src'), e.getAttribute('mount-point'))
142 else:
143 raise Exception(_("Unknown binding type '%s'") % e.name)
145 def process_depends(item, local_feed_dir):
146 """Internal"""
147 # Note: also called from selections
148 attrs = item.attrs
149 dep_iface = item.getAttribute('interface')
150 if not dep_iface:
151 raise InvalidInterface(_("Missing 'interface' on <%s>") % item.name)
152 if dep_iface.startswith('./'):
153 if local_feed_dir:
154 dep_iface = os.path.abspath(os.path.join(local_feed_dir, dep_iface))
155 # (updates the element too, in case we write it out again)
156 attrs['interface'] = dep_iface
157 else:
158 raise InvalidInterface(_('Relative interface URI "%s" in non-local feed') % dep_iface)
159 dependency = InterfaceDependency(dep_iface, element = item)
161 for e in item.childNodes:
162 if e.uri != XMLNS_IFACE: continue
163 if e.name in binding_names:
164 dependency.bindings.append(process_binding(e))
165 elif e.name == 'version':
166 dependency.restrictions.append(
167 VersionRangeRestriction(not_before = parse_version(e.getAttribute('not-before')),
168 before = parse_version(e.getAttribute('before'))))
169 return dependency
171 def N_(message): return message
173 insecure = Stability(0, N_('insecure'), _('This is a security risk'))
174 buggy = Stability(5, N_('buggy'), _('Known to have serious bugs'))
175 developer = Stability(10, N_('developer'), _('Work-in-progress - bugs likely'))
176 testing = Stability(20, N_('testing'), _('Stability unknown - please test!'))
177 stable = Stability(30, N_('stable'), _('Tested - no serious problems found'))
178 packaged = Stability(35, N_('packaged'), _('Supplied by the local package manager'))
179 preferred = Stability(40, N_('preferred'), _('Best of all - must be set manually'))
181 del N_
183 class Restriction(object):
184 """A Restriction limits the allowed implementations of an Interface."""
185 __slots__ = []
187 def meets_restriction(self, impl):
188 """Called by the L{solver.Solver} to check whether a particular implementation is acceptable.
189 @return: False if this implementation is not a possibility
190 @rtype: bool
192 raise NotImplementedError(_("Abstract"))
194 class VersionRestriction(Restriction):
195 """Only select implementations with a particular version number.
196 @since: 0.40"""
198 def __init__(self, version):
199 """@param version: the required version number
200 @see: L{parse_version}; use this to pre-process the version number
202 self.version = version
204 def meets_restriction(self, impl):
205 return impl.version == self.version
207 def __str__(self):
208 return _("(restriction: version = %s)") % format_version(self.version)
210 class VersionRangeRestriction(Restriction):
211 """Only versions within the given range are acceptable"""
212 __slots__ = ['before', 'not_before']
214 def __init__(self, before, not_before):
215 """@param before: chosen versions must be earlier than this
216 @param not_before: versions must be at least this high
217 @see: L{parse_version}; use this to pre-process the versions
219 self.before = before
220 self.not_before = not_before
222 def meets_restriction(self, impl):
223 if self.not_before and impl.version < self.not_before:
224 return False
225 if self.before and impl.version >= self.before:
226 return False
227 return True
229 def __str__(self):
230 if self.not_before is not None or self.before is not None:
231 range = ''
232 if self.not_before is not None:
233 range += format_version(self.not_before) + ' <= '
234 range += 'version'
235 if self.before is not None:
236 range += ' < ' + format_version(self.before)
237 else:
238 range = 'none'
239 return _("(restriction: %s)") % range
241 class Binding(object):
242 """Information about how the choice of a Dependency is made known
243 to the application being run."""
245 class EnvironmentBinding(Binding):
246 """Indicate the chosen implementation using an environment variable."""
247 __slots__ = ['name', 'insert', 'default', 'mode', 'value']
249 PREPEND = 'prepend'
250 APPEND = 'append'
251 REPLACE = 'replace'
253 def __init__(self, name, insert, default = None, mode = PREPEND, value=None, separator=None):
255 mode argument added in version 0.28
256 value argument added in version 0.52
258 self.name = name
259 self.insert = insert
260 self.default = default
261 self.mode = mode
262 self.value = value
263 if separator is None:
264 self.separator = os.pathsep
265 else:
266 self.separator = separator
269 def __str__(self):
270 return _("<environ %(name)s %(mode)s %(insert)s %(value)s>") % {'name': self.name,'mode': self.mode, 'insert': self.insert, 'value': self.value}
272 __repr__ = __str__
274 def get_value(self, path, old_value):
275 """Calculate the new value of the environment variable after applying this binding.
276 @param path: the path to the selected implementation
277 @param old_value: the current value of the environment variable
278 @return: the new value for the environment variable"""
280 if self.insert is not None:
281 extra = os.path.join(path, self.insert)
282 else:
283 assert self.value is not None
284 extra = self.value
286 if self.mode == EnvironmentBinding.REPLACE:
287 return extra
289 if old_value is None:
290 old_value = self.default or defaults.get(self.name, None)
291 if old_value is None:
292 return extra
293 if self.mode == EnvironmentBinding.PREPEND:
294 return extra + self.separator + old_value
295 else:
296 return old_value + self.separator + extra
298 def _toxml(self, doc, prefixes):
299 """Create a DOM element for this binding.
300 @param doc: document to use to create the element
301 @return: the new element
303 env_elem = doc.createElementNS(XMLNS_IFACE, 'environment')
304 env_elem.setAttributeNS(None, 'name', self.name)
305 if self.mode is not None:
306 env_elem.setAttributeNS(None, 'mode', self.mode)
307 if self.insert is not None:
308 env_elem.setAttributeNS(None, 'insert', self.insert)
309 else:
310 env_elem.setAttributeNS(None, 'value', self.value)
311 if self.default:
312 env_elem.setAttributeNS(None, 'default', self.default)
313 if self.separator:
314 env_elem.setAttributeNS(None, 'separator', self.separator)
315 return env_elem
317 class ExecutableBinding(Binding):
318 """Make the chosen command available in $PATH."""
319 __slots__ = ['qdom']
321 def __init__(self, qdom):
322 self.qdom = qdom
324 def __str__(self):
325 return str(self.qdom)
327 __repr__ = __str__
329 def _toxml(self, doc, prefixes):
330 return self.qdom.toDOM(doc, prefixes)
332 @property
333 def name(self):
334 return self.qdom.getAttribute('name')
336 class OverlayBinding(Binding):
337 """Make the chosen implementation available by overlaying it onto another part of the file-system.
338 This is to support legacy programs which use hard-coded paths."""
339 __slots__ = ['src', 'mount_point']
341 def __init__(self, src, mount_point):
342 self.src = src
343 self.mount_point = mount_point
345 def __str__(self):
346 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self.src or '.', 'mount_point': self.mount_point or '/'}
348 __repr__ = __str__
350 def _toxml(self, doc):
351 """Create a DOM element for this binding.
352 @param doc: document to use to create the element
353 @return: the new element
355 env_elem = doc.createElementNS(XMLNS_IFACE, 'overlay')
356 if self.src is not None:
357 env_elem.setAttributeNS(None, 'src', self.src)
358 if self.mount_point is not None:
359 env_elem.setAttributeNS(None, 'mount-point', self.mount_point)
360 return env_elem
362 class Feed(object):
363 """An interface's feeds are other interfaces whose implementations can also be
364 used as implementations of this interface."""
365 __slots__ = ['uri', 'os', 'machine', 'user_override', 'langs']
366 def __init__(self, uri, arch, user_override, langs = None):
367 self.uri = uri
368 # This indicates whether the feed comes from the user's overrides
369 # file. If true, writer.py will write it when saving.
370 self.user_override = user_override
371 self.os, self.machine = _split_arch(arch)
372 self.langs = langs
374 def __str__(self):
375 return "<Feed from %s>" % self.uri
376 __repr__ = __str__
378 arch = property(lambda self: _join_arch(self.os, self.machine))
380 class Dependency(object):
381 """A Dependency indicates that an Implementation requires some additional
382 code to function. This is an abstract base class.
383 @ivar qdom: the XML element for this Dependency (since 0launch 0.51)
384 @type qdom: L{qdom.Element}
385 @ivar metadata: any extra attributes from the XML element
386 @type metadata: {str: str}
388 __slots__ = ['qdom']
390 Essential = "essential"
391 Recommended = "recommended"
393 def __init__(self, element):
394 assert isinstance(element, qdom.Element), type(element) # Use InterfaceDependency instead!
395 self.qdom = element
397 @property
398 def metadata(self):
399 return self.qdom.attrs
401 @property
402 def importance(self):
403 return self.qdom.getAttribute("importance") or Dependency.Essential
405 class InterfaceDependency(Dependency):
406 """A Dependency on a Zero Install interface.
407 @ivar interface: the interface required by this dependency
408 @type interface: str
409 @ivar restrictions: a list of constraints on acceptable implementations
410 @type restrictions: [L{Restriction}]
411 @ivar bindings: how to make the choice of implementation known
412 @type bindings: [L{Binding}]
413 @since: 0.28
415 __slots__ = ['interface', 'restrictions', 'bindings']
417 def __init__(self, interface, restrictions = None, element = None):
418 Dependency.__init__(self, element)
419 assert isinstance(interface, (str, unicode))
420 assert interface
421 self.interface = interface
422 if restrictions is None:
423 self.restrictions = []
424 else:
425 self.restrictions = restrictions
426 self.bindings = []
428 def __str__(self):
429 return _("<Dependency on %(interface)s; bindings: %(bindings)s%(restrictions)s>") % {'interface': self.interface, 'bindings': self.bindings, 'restrictions': self.restrictions}
431 @property
432 def command(self):
433 return self.qdom.getAttribute("command") or ('run' if self.qdom.name == 'runner' else None)
436 class RetrievalMethod(object):
437 """A RetrievalMethod provides a way to fetch an implementation."""
438 __slots__ = []
440 class DownloadSource(RetrievalMethod):
441 """A DownloadSource provides a way to fetch an implementation."""
442 __slots__ = ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
444 def __init__(self, implementation, url, size, extract, start_offset = 0, type = None):
445 self.implementation = implementation
446 self.url = url
447 self.size = size
448 self.extract = extract
449 self.start_offset = start_offset
450 self.type = type # MIME type - see unpack.py
452 class Recipe(RetrievalMethod):
453 """Get an implementation by following a series of steps.
454 @ivar size: the combined download sizes from all the steps
455 @type size: int
456 @ivar steps: the sequence of steps which must be performed
457 @type steps: [L{RetrievalMethod}]"""
458 __slots__ = ['steps']
460 def __init__(self):
461 self.steps = []
463 size = property(lambda self: sum([x.size for x in self.steps]))
465 class DistributionSource(RetrievalMethod):
466 """A package that is installed using the distribution's tools (including PackageKit).
467 @ivar install: a function to call to install this package
468 @type install: (L{handler.Handler}) -> L{tasks.Blocker}
469 @ivar package_id: the package name, in a form recognised by the distribution's tools
470 @type package_id: str
471 @ivar size: the download size in bytes
472 @type size: int
473 @ivar needs_confirmation: whether the user should be asked to confirm before calling install()
474 @type needs_confirmation: bool"""
476 __slots__ = ['package_id', 'size', 'install', 'needs_confirmation']
478 def __init__(self, package_id, size, install, needs_confirmation = True):
479 RetrievalMethod.__init__(self)
480 self.package_id = package_id
481 self.size = size
482 self.install = install
483 self.needs_confirmation = needs_confirmation
485 class Command(object):
486 """A Command is a way of running an Implementation as a program."""
488 __slots__ = ['qdom', '_depends', '_local_dir', '_runner']
490 def __init__(self, qdom, local_dir):
491 """@param qdom: the <command> element
492 @param local_dir: the directory containing the feed (for relative dependencies), or None if not local
494 assert qdom.name == 'command', 'not <command>: %s' % qdom
495 self.qdom = qdom
496 self._local_dir = local_dir
497 self._depends = None
499 path = property(lambda self: self.qdom.attrs.get("path", None))
501 def _toxml(self, doc, prefixes):
502 return self.qdom.toDOM(doc, prefixes)
504 @property
505 def requires(self):
506 if self._depends is None:
507 self._runner = None
508 depends = []
509 for child in self.qdom.childNodes:
510 if child.name == 'requires':
511 dep = process_depends(child, self._local_dir)
512 depends.append(dep)
513 elif child.name == 'runner':
514 if self._runner:
515 raise InvalidInterface(_("Multiple <runner>s in <command>!"))
516 dep = process_depends(child, self._local_dir)
517 depends.append(dep)
518 self._runner = dep
519 self._depends = depends
520 return self._depends
522 def get_runner(self):
523 self.requires # (sets _runner)
524 return self._runner
526 def __str__(self):
527 return str(self.qdom)
529 class Implementation(object):
530 """An Implementation is a package which implements an Interface.
531 @ivar download_sources: list of methods of getting this implementation
532 @type download_sources: [L{RetrievalMethod}]
533 @ivar feed: the feed owning this implementation (since 0.32)
534 @type feed: [L{ZeroInstallFeed}]
535 @ivar bindings: how to tell this component where it itself is located (since 0.31)
536 @type bindings: [Binding]
537 @ivar upstream_stability: the stability reported by the packager
538 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged]
539 @ivar user_stability: the stability as set by the user
540 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred]
541 @ivar langs: natural languages supported by this package
542 @type langs: str
543 @ivar requires: interfaces this package depends on
544 @type requires: [L{Dependency}]
545 @ivar commands: ways to execute as a program
546 @type commands: {str: Command}
547 @ivar metadata: extra metadata from the feed
548 @type metadata: {"[URI ]localName": str}
549 @ivar id: a unique identifier for this Implementation
550 @ivar version: a parsed version number
551 @ivar released: release date
552 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path)
553 @type local_path: str | None
554 @ivar requires_root_install: whether the user will need admin rights to use this
555 @type requires_root_install: bool
558 # Note: user_stability shouldn't really be here
560 __slots__ = ['upstream_stability', 'user_stability', 'langs',
561 'requires', 'metadata', 'download_sources', 'commands',
562 'id', 'feed', 'version', 'released', 'bindings', 'machine']
564 def __init__(self, feed, id):
565 assert id
566 self.feed = feed
567 self.id = id
568 self.user_stability = None
569 self.upstream_stability = None
570 self.metadata = {} # [URI + " "] + localName -> value
571 self.requires = []
572 self.version = None
573 self.released = None
574 self.download_sources = []
575 self.langs = ""
576 self.machine = None
577 self.bindings = []
578 self.commands = {}
580 def get_stability(self):
581 return self.user_stability or self.upstream_stability or testing
583 def __str__(self):
584 return self.id
586 def __repr__(self):
587 return "v%s (%s)" % (self.get_version(), self.id)
589 def __cmp__(self, other):
590 """Newer versions come first"""
591 d = cmp(other.version, self.version)
592 if d: return d
593 # If the version number is the same, just give a stable sort order, and
594 # ensure that two different implementations don't compare equal.
595 d = cmp(other.feed.url, self.feed.url)
596 if d: return d
597 return cmp(other.id, self.id)
599 def get_version(self):
600 """Return the version as a string.
601 @see: L{format_version}
603 return format_version(self.version)
605 arch = property(lambda self: _join_arch(self.os, self.machine))
607 os = None
608 local_path = None
609 digests = None
610 requires_root_install = False
612 def _get_main(self):
613 """"@deprecated: use commands["run"] instead"""
614 main = self.commands.get("run", None)
615 if main is not None:
616 return main.path
617 return None
618 def _set_main(self, path):
619 """"@deprecated: use commands["run"] instead"""
620 if path is None:
621 if "run" in self.commands:
622 del self.commands["run"]
623 else:
624 self.commands["run"] = Command(qdom.Element(XMLNS_IFACE, 'command', {'path': path}), None)
625 main = property(_get_main, _set_main)
627 def is_available(self, stores):
628 """Is this Implementation available locally?
629 (a local implementation, an installed distribution package, or a cached ZeroInstallImplementation)
630 @rtype: bool
631 @since: 0.53
633 raise NotImplementedError("abstract")
635 class DistributionImplementation(Implementation):
636 """An implementation provided by the distribution. Information such as the version
637 comes from the package manager.
638 @since: 0.28"""
639 __slots__ = ['distro', 'installed']
641 def __init__(self, feed, id, distro):
642 assert id.startswith('package:')
643 Implementation.__init__(self, feed, id)
644 self.distro = distro
645 self.installed = False
647 @property
648 def requires_root_install(self):
649 return not self.installed
651 def is_available(self, stores):
652 return self.installed
654 class ZeroInstallImplementation(Implementation):
655 """An implementation where all the information comes from Zero Install.
656 @ivar digests: a list of "algorith=value" strings (since 0.45)
657 @type digests: [str]
658 @since: 0.28"""
659 __slots__ = ['os', 'size', 'digests', 'local_path']
661 def __init__(self, feed, id, local_path):
662 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
663 assert not id.startswith('package:'), id
664 Implementation.__init__(self, feed, id)
665 self.size = None
666 self.os = None
667 self.digests = []
668 self.local_path = local_path
670 # Deprecated
671 dependencies = property(lambda self: dict([(x.interface, x) for x in self.requires
672 if isinstance(x, InterfaceDependency)]))
674 def add_download_source(self, url, size, extract, start_offset = 0, type = None):
675 """Add a download source."""
676 self.download_sources.append(DownloadSource(self, url, size, extract, start_offset, type))
678 def set_arch(self, arch):
679 self.os, self.machine = _split_arch(arch)
680 arch = property(lambda self: _join_arch(self.os, self.machine), set_arch)
682 def is_available(self, stores):
683 if self.local_path is not None:
684 return os.path.exists(self.local_path)
685 if self.digests:
686 path = stores.lookup_maybe(self.digests)
687 return path is not None
688 return False # (0compile creates fake entries with no digests)
690 class Interface(object):
691 """An Interface represents some contract of behaviour.
692 @ivar uri: the URI for this interface.
693 @ivar stability_policy: user's configured policy.
694 Implementations at this level or higher are preferred.
695 Lower levels are used only if there is no other choice.
697 __slots__ = ['uri', 'stability_policy', 'extra_feeds']
699 implementations = property(lambda self: self._main_feed.implementations)
700 name = property(lambda self: self._main_feed.name)
701 description = property(lambda self: self._main_feed.description)
702 summary = property(lambda self: self._main_feed.summary)
703 last_modified = property(lambda self: self._main_feed.last_modified)
704 feeds = property(lambda self: self.extra_feeds + self._main_feed.feeds)
705 metadata = property(lambda self: self._main_feed.metadata)
707 last_checked = property(lambda self: self._main_feed.last_checked)
709 def __init__(self, uri):
710 assert uri
711 if uri.startswith('http:') or uri.startswith('https:') or os.path.isabs(uri):
712 self.uri = uri
713 else:
714 raise SafeException(_("Interface name '%s' doesn't start "
715 "with 'http:' or 'https:'") % uri)
716 self.reset()
718 def _get_feed_for(self):
719 retval = {}
720 for key in self._main_feed.feed_for:
721 retval[key] = True
722 return retval
723 feed_for = property(_get_feed_for) # Deprecated (used by 0publish)
725 def reset(self):
726 self.extra_feeds = []
727 self.stability_policy = None
729 def get_name(self):
730 from zeroinstall.injector.iface_cache import iface_cache
731 feed = iface_cache.get_feed(self.uri)
732 if feed:
733 return feed.get_name()
734 return '(' + os.path.basename(self.uri) + ')'
736 def __repr__(self):
737 return _("<Interface %s>") % self.uri
739 def set_stability_policy(self, new):
740 assert new is None or isinstance(new, Stability)
741 self.stability_policy = new
743 def get_feed(self, url):
744 #import warnings
745 #warnings.warn("use iface_cache.get_feed instead", DeprecationWarning, 2)
746 for x in self.extra_feeds:
747 if x.uri == url:
748 return x
749 #return self._main_feed.get_feed(url)
750 return None
752 def get_metadata(self, uri, name):
753 return self._main_feed.get_metadata(uri, name)
755 @property
756 def _main_feed(self):
757 #import warnings
758 #warnings.warn("use the feed instead", DeprecationWarning, 3)
759 from zeroinstall.injector import policy
760 iface_cache = policy.get_deprecated_singleton_config().iface_cache
761 feed = iface_cache.get_feed(self.uri)
762 if feed is None:
763 return _dummy_feed
764 return feed
766 def _merge_attrs(attrs, item):
767 """Add each attribute of item to a copy of attrs and return the copy.
768 @type attrs: {str: str}
769 @type item: L{qdom.Element}
770 @rtype: {str: str}
772 new = attrs.copy()
773 for a in item.attrs:
774 new[str(a)] = item.attrs[a]
775 return new
777 def _get_long(elem, attr_name):
778 val = elem.getAttribute(attr_name)
779 if val is not None:
780 try:
781 val = int(val)
782 except ValueError:
783 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name, 'value': val})
784 return val
786 class ZeroInstallFeed(object):
787 """A feed lists available implementations of an interface.
788 @ivar url: the URL for this feed
789 @ivar implementations: Implementations in this feed, indexed by ID
790 @type implementations: {str: L{Implementation}}
791 @ivar name: human-friendly name
792 @ivar summaries: short textual description (in various languages, since 0.49)
793 @type summaries: {str: str}
794 @ivar descriptions: long textual description (in various languages, since 0.49)
795 @type descriptions: {str: str}
796 @ivar last_modified: timestamp on signature
797 @ivar last_checked: time feed was last successfully downloaded and updated
798 @ivar feeds: list of <feed> elements in this feed
799 @type feeds: [L{Feed}]
800 @ivar feed_for: interfaces for which this could be a feed
801 @type feed_for: set(str)
802 @ivar metadata: extra elements we didn't understand
804 # _main is deprecated
805 __slots__ = ['url', 'implementations', 'name', 'descriptions', 'first_description', 'summaries', 'first_summary', '_package_implementations',
806 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
808 def __init__(self, feed_element, local_path = None, distro = None):
809 """Create a feed object from a DOM.
810 @param feed_element: the root element of a feed file
811 @type feed_element: L{qdom.Element}
812 @param local_path: the pathname of this local feed, or None for remote feeds"""
813 self.implementations = {}
814 self.name = None
815 self.summaries = {} # { lang: str }
816 self.first_summary = None
817 self.descriptions = {} # { lang: str }
818 self.first_description = None
819 self.last_modified = None
820 self.feeds = []
821 self.feed_for = set()
822 self.metadata = []
823 self.last_checked = None
824 self._package_implementations = []
826 if distro is not None:
827 import warnings
828 warnings.warn("distro argument is now ignored", DeprecationWarning, 2)
830 if feed_element is None:
831 return # XXX subclass?
833 assert feed_element.name in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
834 assert feed_element.uri == XMLNS_IFACE, "Wrong namespace on root element: %s" % feed_element.uri
836 main = feed_element.getAttribute('main')
837 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
839 if local_path:
840 self.url = local_path
841 local_dir = os.path.dirname(local_path)
842 else:
843 self.url = feed_element.getAttribute('uri')
844 if not self.url:
845 raise InvalidInterface(_("<interface> uri attribute missing"))
846 local_dir = None # Can't have relative paths
848 min_injector_version = feed_element.getAttribute('min-injector-version')
849 if min_injector_version:
850 if parse_version(min_injector_version) > parse_version(version):
851 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
852 "Zero Install, but I am only version %(version)s. "
853 "You can get a newer version from http://0install.net") %
854 {'min_version': min_injector_version, 'version': version})
856 for x in feed_element.childNodes:
857 if x.uri != XMLNS_IFACE:
858 self.metadata.append(x)
859 continue
860 if x.name == 'name':
861 self.name = x.content
862 elif x.name == 'description':
863 if self.first_description == None:
864 self.first_description = x.content
865 self.descriptions[x.attrs.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x.content
866 elif x.name == 'summary':
867 if self.first_summary == None:
868 self.first_summary = x.content
869 self.summaries[x.attrs.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x.content
870 elif x.name == 'feed-for':
871 feed_iface = x.getAttribute('interface')
872 if not feed_iface:
873 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
874 self.feed_for.add(feed_iface)
875 # Bug report from a Debian/stable user that --feed gets the wrong value.
876 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
877 # in case it happens again.
878 debug(_("Is feed-for %s"), feed_iface)
879 elif x.name == 'feed':
880 feed_src = x.getAttribute('src')
881 if not feed_src:
882 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
883 if feed_src.startswith('http:') or feed_src.startswith('https:') or local_path:
884 langs = x.getAttribute('langs')
885 if langs: langs = langs.replace('_', '-')
886 self.feeds.append(Feed(feed_src, x.getAttribute('arch'), False, langs = langs))
887 else:
888 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src)
889 else:
890 self.metadata.append(x)
892 if not self.name:
893 raise InvalidInterface(_("Missing <name> in feed"))
894 if not self.summary:
895 raise InvalidInterface(_("Missing <summary> in feed"))
897 def process_group(group, group_attrs, base_depends, base_bindings, base_commands):
898 for item in group.childNodes:
899 if item.uri != XMLNS_IFACE: continue
901 if item.name not in ('group', 'implementation', 'package-implementation'):
902 continue
904 # We've found a group or implementation. Scan for dependencies,
905 # bindings and commands. Doing this here means that:
906 # - We can share the code for groups and implementations here.
907 # - The order doesn't matter, because these get processed first.
908 # A side-effect is that the document root cannot contain
909 # these.
911 depends = base_depends[:]
912 bindings = base_bindings[:]
913 commands = base_commands.copy()
915 for attr, command in [('main', 'run'),
916 ('self-test', 'test')]:
917 value = item.attrs.get(attr, None)
918 if value is not None:
919 commands[command] = Command(qdom.Element(XMLNS_IFACE, 'command', {'name': command, 'path': value}), None)
921 for child in item.childNodes:
922 if child.uri != XMLNS_IFACE: continue
923 if child.name == 'requires':
924 dep = process_depends(child, local_dir)
925 depends.append(dep)
926 elif child.name == 'command':
927 command_name = child.attrs.get('name', None)
928 if not command_name:
929 raise InvalidInterface('Missing name for <command>')
930 commands[command_name] = Command(child, local_dir)
931 elif child.name in binding_names:
932 bindings.append(process_binding(child))
934 compile_command = item.attrs.get('http://zero-install.sourceforge.net/2006/namespaces/0compile command')
935 if compile_command is not None:
936 commands['compile'] = Command(qdom.Element(XMLNS_IFACE, 'command', {'name': 'compile', 'shell-command': compile_command}), None)
938 item_attrs = _merge_attrs(group_attrs, item)
940 if item.name == 'group':
941 process_group(item, item_attrs, depends, bindings, commands)
942 elif item.name == 'implementation':
943 process_impl(item, item_attrs, depends, bindings, commands)
944 elif item.name == 'package-implementation':
945 if depends:
946 warn("A <package-implementation> with dependencies in %s!", self.url)
947 self._package_implementations.append((item, item_attrs))
948 else:
949 assert 0
951 def process_impl(item, item_attrs, depends, bindings, commands):
952 id = item.getAttribute('id')
953 if id is None:
954 raise InvalidInterface(_("Missing 'id' attribute on %s") % item)
955 local_path = item_attrs.get('local-path')
956 if local_dir and local_path:
957 abs_local_path = os.path.abspath(os.path.join(local_dir, local_path))
958 impl = ZeroInstallImplementation(self, id, abs_local_path)
959 elif local_dir and (id.startswith('/') or id.startswith('.')):
960 # For old feeds
961 id = os.path.abspath(os.path.join(local_dir, id))
962 impl = ZeroInstallImplementation(self, id, id)
963 else:
964 impl = ZeroInstallImplementation(self, id, None)
965 if '=' in id:
966 # In older feeds, the ID was the (single) digest
967 impl.digests.append(id)
968 if id in self.implementations:
969 warn(_("Duplicate ID '%(id)s' in feed '%(feed)s'"), {'id': id, 'feed': self})
970 self.implementations[id] = impl
972 impl.metadata = item_attrs
973 try:
974 version_mod = item_attrs.get('version-modifier', None)
975 if version_mod:
976 item_attrs['version'] += version_mod
977 del item_attrs['version-modifier']
978 version = item_attrs['version']
979 except KeyError:
980 raise InvalidInterface(_("Missing version attribute"))
981 impl.version = parse_version(version)
983 impl.commands = commands
985 impl.released = item_attrs.get('released', None)
986 impl.langs = item_attrs.get('langs', '').replace('_', '-')
988 size = item.getAttribute('size')
989 if size:
990 impl.size = int(size)
991 impl.arch = item_attrs.get('arch', None)
992 try:
993 stability = stability_levels[str(item_attrs['stability'])]
994 except KeyError:
995 stab = str(item_attrs['stability'])
996 if stab != stab.lower():
997 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs.stability)
998 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs['stability'])
999 if stability >= preferred:
1000 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
1001 impl.upstream_stability = stability
1003 impl.bindings = bindings
1004 impl.requires = depends
1006 for elem in item.childNodes:
1007 if elem.uri != XMLNS_IFACE: continue
1008 if elem.name == 'archive':
1009 url = elem.getAttribute('href')
1010 if not url:
1011 raise InvalidInterface(_("Missing href attribute on <archive>"))
1012 size = elem.getAttribute('size')
1013 if not size:
1014 raise InvalidInterface(_("Missing size attribute on <archive>"))
1015 impl.add_download_source(url = url, size = int(size),
1016 extract = elem.getAttribute('extract'),
1017 start_offset = _get_long(elem, 'start-offset'),
1018 type = elem.getAttribute('type'))
1019 elif elem.name == 'manifest-digest':
1020 for aname, avalue in elem.attrs.iteritems():
1021 if ' ' not in aname:
1022 impl.digests.append('%s=%s' % (aname, avalue))
1023 elif elem.name == 'recipe':
1024 recipe = Recipe()
1025 for recipe_step in elem.childNodes:
1026 if recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'archive':
1027 url = recipe_step.getAttribute('href')
1028 if not url:
1029 raise InvalidInterface(_("Missing href attribute on <archive>"))
1030 size = recipe_step.getAttribute('size')
1031 if not size:
1032 raise InvalidInterface(_("Missing size attribute on <archive>"))
1033 recipe.steps.append(DownloadSource(None, url = url, size = int(size),
1034 extract = recipe_step.getAttribute('extract'),
1035 start_offset = _get_long(recipe_step, 'start-offset'),
1036 type = recipe_step.getAttribute('type')))
1037 else:
1038 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step.name)
1039 break
1040 else:
1041 impl.download_sources.append(recipe)
1043 root_attrs = {'stability': 'testing'}
1044 root_commands = {}
1045 if main:
1046 info("Note: @main on document element is deprecated in %s", self)
1047 root_commands['run'] = Command(qdom.Element(XMLNS_IFACE, 'command', {'path': main}), None)
1048 process_group(feed_element, root_attrs, [], [], root_commands)
1050 def get_distro_feed(self):
1051 """Does this feed contain any <pacakge-implementation> elements?
1052 i.e. is it worth asking the package manager for more information?
1053 @return: the URL of the virtual feed, or None
1054 @since: 0.49"""
1055 if self._package_implementations:
1056 return "distribution:" + self.url
1057 return None
1059 def get_package_impls(self, distro):
1060 """Find the best <pacakge-implementation> element(s) for the given distribution.
1061 @param distro: the distribution to use to rate them
1062 @type distro: L{distro.Distribution}
1063 @return: a list of tuples for the best ranked elements
1064 @rtype: [str]
1065 @since: 0.49"""
1066 best_score = 0
1067 best_impls = []
1069 for item, item_attrs in self._package_implementations:
1070 distro_names = item_attrs.get('distributions', '')
1071 for distro_name in distro_names.split(' '):
1072 score = distro.get_score(distro_name)
1073 if score > best_score:
1074 best_score = score
1075 best_impls = []
1076 if score == best_score:
1077 best_impls.append((item, item_attrs))
1078 return best_impls
1080 def get_name(self):
1081 return self.name or '(' + os.path.basename(self.url) + ')'
1083 def __repr__(self):
1084 return _("<Feed %s>") % self.url
1086 def set_stability_policy(self, new):
1087 assert new is None or isinstance(new, Stability)
1088 self.stability_policy = new
1090 def get_feed(self, url):
1091 for x in self.feeds:
1092 if x.uri == url:
1093 return x
1094 return None
1096 def add_metadata(self, elem):
1097 self.metadata.append(elem)
1099 def get_metadata(self, uri, name):
1100 """Return a list of interface metadata elements with this name and namespace URI."""
1101 return [m for m in self.metadata if m.name == name and m.uri == uri]
1103 @property
1104 def summary(self):
1105 return _best_language_match(self.summaries) or self.first_summary
1107 @property
1108 def description(self):
1109 return _best_language_match(self.descriptions) or self.first_description
1111 class DummyFeed(object):
1112 """Temporary class used during API transition."""
1113 last_modified = None
1114 name = '-'
1115 last_checked = property(lambda self: None)
1116 implementations = property(lambda self: {})
1117 feeds = property(lambda self: [])
1118 summary = property(lambda self: '-')
1119 description = property(lambda self: '')
1120 def get_name(self): return self.name
1121 def get_feed(self, url): return None
1122 def get_metadata(self, uri, name): return []
1123 _dummy_feed = DummyFeed()
1125 def unescape(uri):
1126 """Convert each %20 to a space, etc.
1127 @rtype: str"""
1128 uri = uri.replace('#', '/')
1129 if '%' not in uri: return uri
1130 return re.sub('%[0-9a-fA-F][0-9a-fA-F]',
1131 lambda match: chr(int(match.group(0)[1:], 16)),
1132 uri).decode('utf-8')
1134 def escape(uri):
1135 """Convert each space to %20, etc
1136 @rtype: str"""
1137 return re.sub('[^-_.a-zA-Z0-9]',
1138 lambda match: '%%%02x' % ord(match.group(0)),
1139 uri.encode('utf-8'))
1141 def _pretty_escape(uri):
1142 """Convert each space to %20, etc
1143 : is preserved and / becomes #. This makes for nicer strings,
1144 and may replace L{escape} everywhere in future.
1145 @rtype: str"""
1146 if os.name == "posix":
1147 # Only preserve : on Posix systems
1148 preserveRegex = '[^-_.a-zA-Z0-9:/]'
1149 else:
1150 # Other OSes may not allow the : character in file names
1151 preserveRegex = '[^-_.a-zA-Z0-9/]'
1152 return re.sub(preserveRegex,
1153 lambda match: '%%%02x' % ord(match.group(0)),
1154 uri.encode('utf-8')).replace('/', '#')
1156 def canonical_iface_uri(uri):
1157 """If uri is a relative path, convert to an absolute one.
1158 A "file:///foo" URI is converted to "/foo".
1159 An "alias:prog" URI expands to the URI in the 0alias script
1160 Otherwise, return it unmodified.
1161 @rtype: str
1162 @raise SafeException: if uri isn't valid
1164 if uri.startswith('http://') or uri.startswith('https://'):
1165 if uri.count("/") < 3:
1166 raise SafeException(_("Missing / after hostname in URI '%s'") % uri)
1167 return uri
1168 elif uri.startswith('file:///'):
1169 return uri[7:]
1170 elif uri.startswith('alias:'):
1171 from zeroinstall import alias, support
1172 alias_prog = uri[6:]
1173 if not os.path.isabs(alias_prog):
1174 full_path = support.find_in_path(alias_prog)
1175 if not full_path:
1176 raise alias.NotAnAliasScript("Not found in $PATH: " + alias_prog)
1177 else:
1178 full_path = alias_prog
1179 interface_uri, main = alias.parse_script(full_path)
1180 return interface_uri
1181 else:
1182 iface_uri = os.path.realpath(uri)
1183 if os.path.isfile(iface_uri):
1184 return iface_uri
1185 raise SafeException(_("Bad interface name '%(uri)s'.\n"
1186 "(doesn't start with 'http:', and "
1187 "doesn't exist as a local file '%(interface_uri)s' either)") %
1188 {'uri': uri, 'interface_uri': iface_uri})
1190 _version_mod_to_value = {
1191 'pre': -2,
1192 'rc': -1,
1193 '': 0,
1194 'post': 1,
1197 # Reverse mapping
1198 _version_value_to_mod = {}
1199 for x in _version_mod_to_value: _version_value_to_mod[_version_mod_to_value[x]] = x
1200 del x
1202 _version_re = re.compile('-([a-z]*)')
1204 def parse_version(version_string):
1205 """Convert a version string to an internal representation.
1206 The parsed format can be compared quickly using the standard Python functions.
1207 - Version := DottedList ("-" Mod DottedList?)*
1208 - DottedList := (Integer ("." Integer)*)
1209 @rtype: tuple (opaque)
1210 @raise SafeException: if the string isn't a valid version
1211 @since: 0.24 (moved from L{reader}, from where it is still available):"""
1212 if version_string is None: return None
1213 parts = _version_re.split(version_string)
1214 if parts[-1] == '':
1215 del parts[-1] # Ends with a modifier
1216 else:
1217 parts.append('')
1218 if not parts:
1219 raise SafeException(_("Empty version string!"))
1220 l = len(parts)
1221 try:
1222 for x in range(0, l, 2):
1223 part = parts[x]
1224 if part:
1225 parts[x] = map(int, parts[x].split('.'))
1226 else:
1227 parts[x] = [] # (because ''.split('.') == [''], not [])
1228 for x in range(1, l, 2):
1229 parts[x] = _version_mod_to_value[parts[x]]
1230 return parts
1231 except ValueError as ex:
1232 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1233 except KeyError as ex:
1234 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1236 def format_version(version):
1237 """Format a parsed version for display. Undoes the effect of L{parse_version}.
1238 @see: L{Implementation.get_version}
1239 @rtype: str
1240 @since: 0.24"""
1241 version = version[:]
1242 l = len(version)
1243 for x in range(0, l, 2):
1244 version[x] = '.'.join(map(str, version[x]))
1245 for x in range(1, l, 2):
1246 version[x] = '-' + _version_value_to_mod[version[x]]
1247 if version[-1] == '-': del version[-1]
1248 return ''.join(version)