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