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