Added <unpack/> step for <recipe>
[zeroinstall/zeroinstall-limyreth.git] / zeroinstall / injector / model.py
blobc8ac300ba544518501178468c717ce0c5f0a9d5c
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
22 from zeroinstall.zerostore import unpack
24 # Element names for bindings in feed files
25 binding_names = frozenset(['environment', 'overlay'])
27 network_offline = 'off-line'
28 network_minimal = 'minimal'
29 network_full = 'full'
30 network_levels = (network_offline, network_minimal, network_full)
32 stability_levels = {} # Name -> Stability
34 defaults = {
35 'PATH': '/bin:/usr/bin',
36 'XDG_CONFIG_DIRS': '/etc/xdg',
37 'XDG_DATA_DIRS': '/usr/local/share:/usr/share',
40 class InvalidInterface(SafeException):
41 """Raised when parsing an invalid feed."""
42 feed_url = None
44 def __init__(self, message, ex = None):
45 if ex:
46 try:
47 message += "\n\n(exact error: %s)" % ex
48 except:
49 # Some Python messages have type str but contain UTF-8 sequences.
50 # (e.g. IOException). Adding these to a Unicode 'message' (e.g.
51 # after gettext translation) will cause an error.
52 import codecs
53 decoder = codecs.lookup('utf-8')
54 decex = decoder.decode(str(ex), errors = 'replace')[0]
55 message += "\n\n(exact error: %s)" % decex
57 SafeException.__init__(self, message)
59 def __unicode__(self):
60 if hasattr(SafeException, '__unicode__'):
61 # Python >= 2.6
62 if self.feed_url:
63 return _('%s [%s]') % (SafeException.__unicode__(self), self.feed_url)
64 return SafeException.__unicode__(self)
65 else:
66 return unicode(SafeException.__str__(self))
68 def _split_arch(arch):
69 """Split an arch into an (os, machine) tuple. Either or both parts may be None."""
70 if not arch:
71 return None, None
72 elif '-' not in arch:
73 raise SafeException(_("Malformed arch '%s'") % arch)
74 else:
75 osys, machine = arch.split('-', 1)
76 if osys == '*': osys = None
77 if machine == '*': machine = None
78 return osys, machine
80 def _join_arch(osys, machine):
81 if osys == machine == None: return None
82 return "%s-%s" % (osys or '*', machine or '*')
84 def _best_language_match(options):
85 (language, encoding) = locale.getlocale()
87 if language:
88 # xml:lang uses '-', while LANG uses '_'
89 language = language.replace('_', '-')
90 else:
91 language = 'en-US'
93 return (options.get(language, None) or # Exact match (language+region)
94 options.get(language.split('-', 1)[0], None) or # Matching language
95 options.get('en', None)) # English
97 class Stability(object):
98 """A stability rating. Each implementation has an upstream stability rating and,
99 optionally, a user-set rating."""
100 __slots__ = ['level', 'name', 'description']
101 def __init__(self, level, name, description):
102 self.level = level
103 self.name = name
104 self.description = description
105 assert name not in stability_levels
106 stability_levels[name] = self
108 def __cmp__(self, other):
109 return cmp(self.level, other.level)
111 def __str__(self):
112 return self.name
114 def __repr__(self):
115 return _("<Stability: %s>") % self.description
117 def process_binding(e):
118 """Internal"""
119 if e.name == 'environment':
120 mode = {
121 None: EnvironmentBinding.PREPEND,
122 'prepend': EnvironmentBinding.PREPEND,
123 'append': EnvironmentBinding.APPEND,
124 'replace': EnvironmentBinding.REPLACE,
125 }[e.getAttribute('mode')]
127 binding = EnvironmentBinding(e.getAttribute('name'),
128 insert = e.getAttribute('insert'),
129 default = e.getAttribute('default'),
130 value = e.getAttribute('value'),
131 mode = mode,
132 separator = e.getAttribute('separator'))
133 if not binding.name: raise InvalidInterface(_("Missing 'name' in binding"))
134 if binding.insert is None and binding.value is None:
135 raise InvalidInterface(_("Missing 'insert' or 'value' in binding"))
136 if binding.insert is not None and binding.value is not None:
137 raise InvalidInterface(_("Binding contains both 'insert' and 'value'"))
138 return binding
139 elif e.name == 'overlay':
140 return OverlayBinding(e.getAttribute('src'), e.getAttribute('mount-point'))
141 else:
142 raise Exception(_("Unknown binding type '%s'") % e.name)
144 def process_depends(item, local_feed_dir):
145 """Internal"""
146 # Note: also called from selections
147 attrs = item.attrs
148 dep_iface = item.getAttribute('interface')
149 if not dep_iface:
150 raise InvalidInterface(_("Missing 'interface' on <%s>") % item.name)
151 if dep_iface.startswith('./'):
152 if local_feed_dir:
153 dep_iface = os.path.abspath(os.path.join(local_feed_dir, dep_iface))
154 # (updates the element too, in case we write it out again)
155 attrs['interface'] = dep_iface
156 else:
157 raise InvalidInterface(_('Relative interface URI "%s" in non-local feed') % dep_iface)
158 dependency = InterfaceDependency(dep_iface, element = item)
160 for e in item.childNodes:
161 if e.uri != XMLNS_IFACE: continue
162 if e.name in binding_names:
163 dependency.bindings.append(process_binding(e))
164 elif e.name == 'version':
165 dependency.restrictions.append(
166 VersionRangeRestriction(not_before = parse_version(e.getAttribute('not-before')),
167 before = parse_version(e.getAttribute('before'))))
168 return dependency
170 def N_(message): return message
172 insecure = Stability(0, N_('insecure'), _('This is a security risk'))
173 buggy = Stability(5, N_('buggy'), _('Known to have serious bugs'))
174 developer = Stability(10, N_('developer'), _('Work-in-progress - bugs likely'))
175 testing = Stability(20, N_('testing'), _('Stability unknown - please test!'))
176 stable = Stability(30, N_('stable'), _('Tested - no serious problems found'))
177 packaged = Stability(35, N_('packaged'), _('Supplied by the local package manager'))
178 preferred = Stability(40, N_('preferred'), _('Best of all - must be set manually'))
180 del N_
182 class Restriction(object):
183 """A Restriction limits the allowed implementations of an Interface."""
184 __slots__ = []
186 def meets_restriction(self, impl):
187 """Called by the L{solver.Solver} to check whether a particular implementation is acceptable.
188 @return: False if this implementation is not a possibility
189 @rtype: bool
191 raise NotImplementedError(_("Abstract"))
193 class VersionRestriction(Restriction):
194 """Only select implementations with a particular version number.
195 @since: 0.40"""
197 def __init__(self, version):
198 """@param version: the required version number
199 @see: L{parse_version}; use this to pre-process the version number
201 self.version = version
203 def meets_restriction(self, impl):
204 return impl.version == self.version
206 def __str__(self):
207 return _("(restriction: version = %s)") % format_version(self.version)
209 class VersionRangeRestriction(Restriction):
210 """Only versions within the given range are acceptable"""
211 __slots__ = ['before', 'not_before']
213 def __init__(self, before, not_before):
214 """@param before: chosen versions must be earlier than this
215 @param not_before: versions must be at least this high
216 @see: L{parse_version}; use this to pre-process the versions
218 self.before = before
219 self.not_before = not_before
221 def meets_restriction(self, impl):
222 if self.not_before and impl.version < self.not_before:
223 return False
224 if self.before and impl.version >= self.before:
225 return False
226 return True
228 def __str__(self):
229 if self.not_before is not None or self.before is not None:
230 range = ''
231 if self.not_before is not None:
232 range += format_version(self.not_before) + ' <= '
233 range += 'version'
234 if self.before is not None:
235 range += ' < ' + format_version(self.before)
236 else:
237 range = 'none'
238 return _("(restriction: %s)") % range
240 class Binding(object):
241 """Information about how the choice of a Dependency is made known
242 to the application being run."""
244 class EnvironmentBinding(Binding):
245 """Indicate the chosen implementation using an environment variable."""
246 __slots__ = ['name', 'insert', 'default', 'mode', 'value']
248 PREPEND = 'prepend'
249 APPEND = 'append'
250 REPLACE = 'replace'
252 def __init__(self, name, insert, default = None, mode = PREPEND,
253 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):
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.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 def __init__(self, element):
368 assert isinstance(element, qdom.Element), type(element) # Use InterfaceDependency instead!
369 self.qdom = element
371 @property
372 def metadata(self):
373 return self.qdom.attrs
375 class InterfaceDependency(Dependency):
376 """A Dependency on a Zero Install interface.
377 @ivar interface: the interface required by this dependency
378 @type interface: str
379 @ivar restrictions: a list of constraints on acceptable implementations
380 @type restrictions: [L{Restriction}]
381 @ivar bindings: how to make the choice of implementation known
382 @type bindings: [L{Binding}]
383 @since: 0.28
385 __slots__ = ['interface', 'restrictions', 'bindings']
387 def __init__(self, interface, restrictions = None, element = None):
388 Dependency.__init__(self, element)
389 assert isinstance(interface, (str, unicode))
390 assert interface
391 self.interface = interface
392 if restrictions is None:
393 self.restrictions = []
394 else:
395 self.restrictions = restrictions
396 self.bindings = []
398 def __str__(self):
399 return _("<Dependency on %(interface)s; bindings: %(bindings)s%(restrictions)s>") % {'interface': self.interface, 'bindings': self.bindings, 'restrictions': self.restrictions}
401 class RetrievalMethod(object):
402 """A RetrievalMethod provides a way to fetch an implementation."""
403 __slots__ = []
405 class DownloadSource(RetrievalMethod):
406 """A DownloadSource provides a way to fetch an implementation."""
407 __slots__ = ['implementation', 'url', 'size', 'extract', 'start_offset', 'type', '_stream']
409 def __init__(self, implementation, url, size, extract, start_offset = 0, type = None):
410 self.implementation = implementation
411 self.url = url
412 self.size = size
413 self.extract = extract
414 self.start_offset = start_offset
415 self.type = type # MIME type - see unpack.py
416 self._stream = None
418 def prepare(self, fetcher, force, impl_hint):
419 blocker, self._stream = fetcher.download_archive(self, force = force, impl_hint = impl_hint)
420 assert self._stream, 'lol'
421 return blocker
423 def run(self, tmpdir):
424 assert self._stream, 'You must prepare the download step first'
425 self._stream.seek(0)
426 unpack.unpack_archive_over(self.url, self._stream, tmpdir,
427 extract = self.extract,
428 type = self.type,
429 start_offset = self.start_offset or 0)
431 class UnpackArchive(object):
432 """An UnpachArchive step provides unpacks/extracts an archive.
434 It can be used inside a Recipe."""
435 __slots__ = ['path', 'extract', 'type']
437 def __init__(self, path, extract, type):
438 self.path = path
439 self.extract = extract
440 self.type = type
442 def prepare(self, fetcher, force, impl_hint):
443 return None
445 def run(self, tmpdir):
446 path = os.path.join(tmpdir, self.path)
447 stream = open(path, 'rb')
448 stream.seek(0)
450 unpack.unpack_archive_over(path, stream, tmpdir,
451 extract = self.extract,
452 type = self.type,
453 start_offset = 0)
455 class Recipe(RetrievalMethod):
456 """Get an implementation by following a series of steps.
457 @ivar size: the combined download sizes from all the steps
458 @type size: int
459 @ivar steps: the sequence of steps which must be performed
460 @type steps: [L{RetrievalMethod}]"""
461 __slots__ = ['steps']
463 def __init__(self):
464 self.steps = []
466 size = property(lambda self: sum([x.size for x in self.steps]))
468 class DistributionSource(RetrievalMethod):
469 """A package that is installed using the distribution's tools (including PackageKit).
470 @ivar install: a function to call to install this package
471 @type install: (L{handler.Handler}) -> L{tasks.Blocker}
472 @ivar package_id: the package name, in a form recognised by the distribution's tools
473 @type package_id: str
474 @ivar size: the download size in bytes
475 @type size: int
476 @ivar needs_confirmation: whether the user should be asked to confirm before calling install()
477 @type needs_confirmation: bool"""
479 __slots__ = ['package_id', 'size', 'install', 'needs_confirmation']
481 def __init__(self, package_id, size, install, needs_confirmation = True):
482 RetrievalMethod.__init__(self)
483 self.package_id = package_id
484 self.size = size
485 self.install = install
486 self.needs_confirmation = needs_confirmation
488 class Command(object):
489 """A Command is a way of running an Implementation as a program."""
491 __slots__ = ['qdom', '_depends', '_local_dir', '_runner']
493 def __init__(self, qdom, local_dir):
494 """@param qdom: the <command> element
495 @param local_dir: the directory containing the feed (for relative dependencies), or None if not local
497 assert qdom.name == 'command', 'not <command>: %s' % qdom
498 self.qdom = qdom
499 self._local_dir = local_dir
500 self._depends = None
502 path = property(lambda self: self.qdom.attrs.get("path", None))
504 def _toxml(self, doc, prefixes):
505 return self.qdom.toDOM(doc, prefixes)
507 @property
508 def requires(self):
509 if self._depends is None:
510 self._runner = None
511 depends = []
512 for child in self.qdom.childNodes:
513 if child.name == 'requires':
514 dep = process_depends(child, self._local_dir)
515 depends.append(dep)
516 elif child.name == 'runner':
517 if self._runner:
518 raise InvalidInterface(_("Multiple <runner>s in <command>!"))
519 dep = process_depends(child, self._local_dir)
520 depends.append(dep)
521 self._runner = dep
522 self._depends = depends
523 return self._depends
525 def get_runner(self):
526 self.requires # (sets _runner)
527 return self._runner
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', {'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', {'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 elif recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'unpack':
1038 path = recipe_step.getAttribute('path')
1039 if not path:
1040 raise InvalidInterface(_("Missing path attribute on <unpack>"))
1041 recipe.steps.append(UnpackArchive(path = path,
1042 extract = recipe_step.getAttribute('extract'),
1043 type = recipe_step.getAttribute('type')))
1044 else:
1045 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step.name)
1046 break
1047 else:
1048 impl.download_sources.append(recipe)
1050 root_attrs = {'stability': 'testing'}
1051 root_commands = {}
1052 if main:
1053 info("Note: @main on document element is deprecated in %s", self)
1054 root_commands['run'] = Command(qdom.Element(XMLNS_IFACE, 'command', {'path': main}), None)
1055 process_group(feed_element, root_attrs, [], [], root_commands)
1057 def get_distro_feed(self):
1058 """Does this feed contain any <pacakge-implementation> elements?
1059 i.e. is it worth asking the package manager for more information?
1060 @return: the URL of the virtual feed, or None
1061 @since: 0.49"""
1062 if self._package_implementations:
1063 return "distribution:" + self.url
1064 return None
1066 def get_package_impls(self, distro):
1067 """Find the best <pacakge-implementation> element(s) for the given distribution.
1068 @param distro: the distribution to use to rate them
1069 @type distro: L{distro.Distribution}
1070 @return: a list of tuples for the best ranked elements
1071 @rtype: [str]
1072 @since: 0.49"""
1073 best_score = 0
1074 best_impls = []
1076 for item, item_attrs in self._package_implementations:
1077 distro_names = item_attrs.get('distributions', '')
1078 for distro_name in distro_names.split(' '):
1079 score = distro.get_score(distro_name)
1080 if score > best_score:
1081 best_score = score
1082 best_impls = []
1083 if score == best_score:
1084 best_impls.append((item, item_attrs))
1085 return best_impls
1087 def get_name(self):
1088 return self.name or '(' + os.path.basename(self.url) + ')'
1090 def __repr__(self):
1091 return _("<Feed %s>") % self.url
1093 def set_stability_policy(self, new):
1094 assert new is None or isinstance(new, Stability)
1095 self.stability_policy = new
1097 def get_feed(self, url):
1098 for x in self.feeds:
1099 if x.uri == url:
1100 return x
1101 return None
1103 def add_metadata(self, elem):
1104 self.metadata.append(elem)
1106 def get_metadata(self, uri, name):
1107 """Return a list of interface metadata elements with this name and namespace URI."""
1108 return [m for m in self.metadata if m.name == name and m.uri == uri]
1110 @property
1111 def summary(self):
1112 return _best_language_match(self.summaries) or self.first_summary
1114 @property
1115 def description(self):
1116 return _best_language_match(self.descriptions) or self.first_description
1118 class DummyFeed(object):
1119 """Temporary class used during API transition."""
1120 last_modified = None
1121 name = '-'
1122 last_checked = property(lambda self: None)
1123 implementations = property(lambda self: {})
1124 feeds = property(lambda self: [])
1125 summary = property(lambda self: '-')
1126 description = property(lambda self: '')
1127 def get_name(self): return self.name
1128 def get_feed(self, url): return None
1129 def get_metadata(self, uri, name): return []
1130 _dummy_feed = DummyFeed()
1132 def unescape(uri):
1133 """Convert each %20 to a space, etc.
1134 @rtype: str"""
1135 uri = uri.replace('#', '/')
1136 if '%' not in uri: return uri
1137 return re.sub('%[0-9a-fA-F][0-9a-fA-F]',
1138 lambda match: chr(int(match.group(0)[1:], 16)),
1139 uri).decode('utf-8')
1141 def escape(uri):
1142 """Convert each space to %20, etc
1143 @rtype: str"""
1144 return re.sub('[^-_.a-zA-Z0-9]',
1145 lambda match: '%%%02x' % ord(match.group(0)),
1146 uri.encode('utf-8'))
1148 def _pretty_escape(uri):
1149 """Convert each space to %20, etc
1150 : is preserved and / becomes #. This makes for nicer strings,
1151 and may replace L{escape} everywhere in future.
1152 @rtype: str"""
1153 if os.name == "posix":
1154 # Only preserve : on Posix systems
1155 preserveRegex = '[^-_.a-zA-Z0-9:/]'
1156 else:
1157 # Other OSes may not allow the : character in file names
1158 preserveRegex = '[^-_.a-zA-Z0-9/]'
1159 return re.sub(preserveRegex,
1160 lambda match: '%%%02x' % ord(match.group(0)),
1161 uri.encode('utf-8')).replace('/', '#')
1163 def canonical_iface_uri(uri):
1164 """If uri is a relative path, convert to an absolute one.
1165 A "file:///foo" URI is converted to "/foo".
1166 An "alias:prog" URI expands to the URI in the 0alias script
1167 Otherwise, return it unmodified.
1168 @rtype: str
1169 @raise SafeException: if uri isn't valid
1171 if uri.startswith('http://') or uri.startswith('https://'):
1172 if uri.count("/") < 3:
1173 raise SafeException(_("Missing / after hostname in URI '%s'") % uri)
1174 return uri
1175 elif uri.startswith('file:///'):
1176 return uri[7:]
1177 elif uri.startswith('alias:'):
1178 from zeroinstall import alias, support
1179 alias_prog = uri[6:]
1180 if not os.path.isabs(alias_prog):
1181 full_path = support.find_in_path(alias_prog)
1182 if not full_path:
1183 raise alias.NotAnAliasScript("Not found in $PATH: " + alias_prog)
1184 else:
1185 full_path = alias_prog
1186 interface_uri, main = alias.parse_script(full_path)
1187 return interface_uri
1188 else:
1189 iface_uri = os.path.realpath(uri)
1190 if os.path.isfile(iface_uri):
1191 return iface_uri
1192 raise SafeException(_("Bad interface name '%(uri)s'.\n"
1193 "(doesn't start with 'http:', and "
1194 "doesn't exist as a local file '%(interface_uri)s' either)") %
1195 {'uri': uri, 'interface_uri': iface_uri})
1197 _version_mod_to_value = {
1198 'pre': -2,
1199 'rc': -1,
1200 '': 0,
1201 'post': 1,
1204 # Reverse mapping
1205 _version_value_to_mod = {}
1206 for x in _version_mod_to_value: _version_value_to_mod[_version_mod_to_value[x]] = x
1207 del x
1209 _version_re = re.compile('-([a-z]*)')
1211 def parse_version(version_string):
1212 """Convert a version string to an internal representation.
1213 The parsed format can be compared quickly using the standard Python functions.
1214 - Version := DottedList ("-" Mod DottedList?)*
1215 - DottedList := (Integer ("." Integer)*)
1216 @rtype: tuple (opaque)
1217 @raise SafeException: if the string isn't a valid version
1218 @since: 0.24 (moved from L{reader}, from where it is still available):"""
1219 if version_string is None: return None
1220 parts = _version_re.split(version_string)
1221 if parts[-1] == '':
1222 del parts[-1] # Ends with a modifier
1223 else:
1224 parts.append('')
1225 if not parts:
1226 raise SafeException(_("Empty version string!"))
1227 l = len(parts)
1228 try:
1229 for x in range(0, l, 2):
1230 part = parts[x]
1231 if part:
1232 parts[x] = map(int, parts[x].split('.'))
1233 else:
1234 parts[x] = [] # (because ''.split('.') == [''], not [])
1235 for x in range(1, l, 2):
1236 parts[x] = _version_mod_to_value[parts[x]]
1237 return parts
1238 except ValueError, ex:
1239 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1240 except KeyError, ex:
1241 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1243 def format_version(version):
1244 """Format a parsed version for display. Undoes the effect of L{parse_version}.
1245 @see: L{Implementation.get_version}
1246 @rtype: str
1247 @since: 0.24"""
1248 version = version[:]
1249 l = len(version)
1250 for x in range(0, l, 2):
1251 version[x] = '.'.join(map(str, version[x]))
1252 for x in range(1, l, 2):
1253 version[x] = '-' + _version_value_to_mod[version[x]]
1254 if version[-1] == '-': del version[-1]
1255 return ''.join(version)