Added <executable-in-var>
[zeroinstall.git] / zeroinstall / injector / model.py
blob0252e5a6997f42e131b66c4b9dfab5f41ea4cca5
1 """In-memory representation of interfaces and other data structures.
3 The objects in this module are used to build a representation of an XML interface
4 file in memory.
6 @see: L{reader} constructs these data-structures
7 @see: U{http://0install.net/interface-spec.html} description of the domain model
9 @var defaults: Default values for the 'default' attribute for <environment> bindings of
10 well-known variables.
11 """
13 # Copyright (C) 2009, Thomas Leonard
14 # See the README file for details, or visit http://0install.net.
16 from zeroinstall import _
17 import os, re, locale
18 from logging import info, debug, warn
19 from zeroinstall import SafeException, version
20 from zeroinstall.injector.namespaces import XMLNS_IFACE
21 from zeroinstall.injector import qdom
23 # Element names for bindings in feed files
24 binding_names = frozenset(['environment', 'overlay', 'executable-in-path', 'executable-in-var'])
26 network_offline = 'off-line'
27 network_minimal = 'minimal'
28 network_full = 'full'
29 network_levels = (network_offline, network_minimal, network_full)
31 stability_levels = {} # Name -> Stability
33 defaults = {
34 'PATH': '/bin:/usr/bin',
35 'XDG_CONFIG_DIRS': '/etc/xdg',
36 'XDG_DATA_DIRS': '/usr/local/share:/usr/share',
39 class InvalidInterface(SafeException):
40 """Raised when parsing an invalid feed."""
41 feed_url = None
43 def __init__(self, message, ex = None):
44 if ex:
45 try:
46 message += "\n\n(exact error: %s)" % ex
47 except:
48 # Some Python messages have type str but contain UTF-8 sequences.
49 # (e.g. IOException). Adding these to a Unicode 'message' (e.g.
50 # after gettext translation) will cause an error.
51 import codecs
52 decoder = codecs.lookup('utf-8')
53 decex = decoder.decode(str(ex), errors = 'replace')[0]
54 message += "\n\n(exact error: %s)" % decex
56 SafeException.__init__(self, message)
58 def __unicode__(self):
59 if hasattr(SafeException, '__unicode__'):
60 # Python >= 2.6
61 if self.feed_url:
62 return _('%s [%s]') % (SafeException.__unicode__(self), self.feed_url)
63 return SafeException.__unicode__(self)
64 else:
65 return unicode(SafeException.__str__(self))
67 def _split_arch(arch):
68 """Split an arch into an (os, machine) tuple. Either or both parts may be None."""
69 if not arch:
70 return None, None
71 elif '-' not in arch:
72 raise SafeException(_("Malformed arch '%s'") % arch)
73 else:
74 osys, machine = arch.split('-', 1)
75 if osys == '*': osys = None
76 if machine == '*': machine = None
77 return osys, machine
79 def _join_arch(osys, machine):
80 if osys == machine == None: return None
81 return "%s-%s" % (osys or '*', machine or '*')
83 def _best_language_match(options):
84 (language, encoding) = locale.getlocale()
86 if language:
87 # xml:lang uses '-', while LANG uses '_'
88 language = language.replace('_', '-')
89 else:
90 language = 'en-US'
92 return (options.get(language, None) or # Exact match (language+region)
93 options.get(language.split('-', 1)[0], None) or # Matching language
94 options.get('en', None)) # English
96 class Stability(object):
97 """A stability rating. Each implementation has an upstream stability rating and,
98 optionally, a user-set rating."""
99 __slots__ = ['level', 'name', 'description']
100 def __init__(self, level, name, description):
101 self.level = level
102 self.name = name
103 self.description = description
104 assert name not in stability_levels
105 stability_levels[name] = self
107 def __cmp__(self, other):
108 return cmp(self.level, other.level)
110 def __str__(self):
111 return self.name
113 def __repr__(self):
114 return _("<Stability: %s>") % self.description
116 def process_binding(e):
117 """Internal"""
118 if e.name == 'environment':
119 mode = {
120 None: EnvironmentBinding.PREPEND,
121 'prepend': EnvironmentBinding.PREPEND,
122 'append': EnvironmentBinding.APPEND,
123 'replace': EnvironmentBinding.REPLACE,
124 }[e.getAttribute('mode')]
126 binding = EnvironmentBinding(e.getAttribute('name'),
127 insert = e.getAttribute('insert'),
128 default = e.getAttribute('default'),
129 value = e.getAttribute('value'),
130 mode = mode,
131 separator = e.getAttribute('separator'))
132 if not binding.name: raise InvalidInterface(_("Missing 'name' in binding"))
133 if binding.insert is None and binding.value is None:
134 raise InvalidInterface(_("Missing 'insert' or 'value' in binding"))
135 if binding.insert is not None and binding.value is not None:
136 raise InvalidInterface(_("Binding contains both 'insert' and 'value'"))
137 return binding
138 elif e.name == 'executable-in-path':
139 return ExecutableBinding(e, in_path = True)
140 elif e.name == 'executable-in-var':
141 return ExecutableBinding(e, in_path = False)
142 elif e.name == 'overlay':
143 return OverlayBinding(e.getAttribute('src'), e.getAttribute('mount-point'))
144 else:
145 raise Exception(_("Unknown binding type '%s'") % e.name)
147 def process_depends(item, local_feed_dir):
148 """Internal"""
149 # Note: also called from selections
150 attrs = item.attrs
151 dep_iface = item.getAttribute('interface')
152 if not dep_iface:
153 raise InvalidInterface(_("Missing 'interface' on <%s>") % item.name)
154 if dep_iface.startswith('./'):
155 if local_feed_dir:
156 dep_iface = os.path.abspath(os.path.join(local_feed_dir, dep_iface))
157 # (updates the element too, in case we write it out again)
158 attrs['interface'] = dep_iface
159 else:
160 raise InvalidInterface(_('Relative interface URI "%s" in non-local feed') % dep_iface)
161 dependency = InterfaceDependency(dep_iface, element = item)
163 for e in item.childNodes:
164 if e.uri != XMLNS_IFACE: continue
165 if e.name in binding_names:
166 dependency.bindings.append(process_binding(e))
167 elif e.name == 'version':
168 dependency.restrictions.append(
169 VersionRangeRestriction(not_before = parse_version(e.getAttribute('not-before')),
170 before = parse_version(e.getAttribute('before'))))
171 return dependency
173 def N_(message): return message
175 insecure = Stability(0, N_('insecure'), _('This is a security risk'))
176 buggy = Stability(5, N_('buggy'), _('Known to have serious bugs'))
177 developer = Stability(10, N_('developer'), _('Work-in-progress - bugs likely'))
178 testing = Stability(20, N_('testing'), _('Stability unknown - please test!'))
179 stable = Stability(30, N_('stable'), _('Tested - no serious problems found'))
180 packaged = Stability(35, N_('packaged'), _('Supplied by the local package manager'))
181 preferred = Stability(40, N_('preferred'), _('Best of all - must be set manually'))
183 del N_
185 class Restriction(object):
186 """A Restriction limits the allowed implementations of an Interface."""
187 __slots__ = []
189 def meets_restriction(self, impl):
190 """Called by the L{solver.Solver} to check whether a particular implementation is acceptable.
191 @return: False if this implementation is not a possibility
192 @rtype: bool
194 raise NotImplementedError(_("Abstract"))
196 class VersionRestriction(Restriction):
197 """Only select implementations with a particular version number.
198 @since: 0.40"""
200 def __init__(self, version):
201 """@param version: the required version number
202 @see: L{parse_version}; use this to pre-process the version number
204 self.version = version
206 def meets_restriction(self, impl):
207 return impl.version == self.version
209 def __str__(self):
210 return _("(restriction: version = %s)") % format_version(self.version)
212 class VersionRangeRestriction(Restriction):
213 """Only versions within the given range are acceptable"""
214 __slots__ = ['before', 'not_before']
216 def __init__(self, before, not_before):
217 """@param before: chosen versions must be earlier than this
218 @param not_before: versions must be at least this high
219 @see: L{parse_version}; use this to pre-process the versions
221 self.before = before
222 self.not_before = not_before
224 def meets_restriction(self, impl):
225 if self.not_before and impl.version < self.not_before:
226 return False
227 if self.before and impl.version >= self.before:
228 return False
229 return True
231 def __str__(self):
232 if self.not_before is not None or self.before is not None:
233 range = ''
234 if self.not_before is not None:
235 range += format_version(self.not_before) + ' <= '
236 range += 'version'
237 if self.before is not None:
238 range += ' < ' + format_version(self.before)
239 else:
240 range = 'none'
241 return _("(restriction: %s)") % range
243 class Binding(object):
244 """Information about how the choice of a Dependency is made known
245 to the application being run."""
247 class EnvironmentBinding(Binding):
248 """Indicate the chosen implementation using an environment variable."""
249 __slots__ = ['name', 'insert', 'default', 'mode', 'value']
251 PREPEND = 'prepend'
252 APPEND = 'append'
253 REPLACE = 'replace'
255 def __init__(self, name, insert, default = None, mode = PREPEND, value=None, separator=None):
257 mode argument added in version 0.28
258 value argument added in version 0.52
260 self.name = name
261 self.insert = insert
262 self.default = default
263 self.mode = mode
264 self.value = value
265 if separator is None:
266 self.separator = os.pathsep
267 else:
268 self.separator = separator
271 def __str__(self):
272 return _("<environ %(name)s %(mode)s %(insert)s %(value)s>") % {'name': self.name,'mode': self.mode, 'insert': self.insert, 'value': self.value}
274 __repr__ = __str__
276 def get_value(self, path, old_value):
277 """Calculate the new value of the environment variable after applying this binding.
278 @param path: the path to the selected implementation
279 @param old_value: the current value of the environment variable
280 @return: the new value for the environment variable"""
282 if self.insert is not None:
283 extra = os.path.join(path, self.insert)
284 else:
285 assert self.value is not None
286 extra = self.value
288 if self.mode == EnvironmentBinding.REPLACE:
289 return extra
291 if old_value is None:
292 old_value = self.default or defaults.get(self.name, None)
293 if old_value is None:
294 return extra
295 if self.mode == EnvironmentBinding.PREPEND:
296 return extra + self.separator + old_value
297 else:
298 return old_value + self.separator + extra
300 def _toxml(self, doc, prefixes):
301 """Create a DOM element for this binding.
302 @param doc: document to use to create the element
303 @return: the new element
305 env_elem = doc.createElementNS(XMLNS_IFACE, 'environment')
306 env_elem.setAttributeNS(None, 'name', self.name)
307 if self.mode is not None:
308 env_elem.setAttributeNS(None, 'mode', self.mode)
309 if self.insert is not None:
310 env_elem.setAttributeNS(None, 'insert', self.insert)
311 else:
312 env_elem.setAttributeNS(None, 'value', self.value)
313 if self.default:
314 env_elem.setAttributeNS(None, 'default', self.default)
315 if self.separator:
316 env_elem.setAttributeNS(None, 'separator', self.separator)
317 return env_elem
319 class ExecutableBinding(Binding):
320 """Make the chosen command available in $PATH.
321 @ivar in_path: True to add the named command to $PATH, False to store in named variable
322 @type in_path: bool
324 __slots__ = ['qdom']
326 def __init__(self, qdom, in_path):
327 self.qdom = qdom
328 self.in_path = in_path
330 def __str__(self):
331 return str(self.qdom)
333 __repr__ = __str__
335 def _toxml(self, doc, prefixes):
336 return self.qdom.toDOM(doc, prefixes)
338 @property
339 def name(self):
340 return self.qdom.getAttribute('name')
342 class OverlayBinding(Binding):
343 """Make the chosen implementation available by overlaying it onto another part of the file-system.
344 This is to support legacy programs which use hard-coded paths."""
345 __slots__ = ['src', 'mount_point']
347 def __init__(self, src, mount_point):
348 self.src = src
349 self.mount_point = mount_point
351 def __str__(self):
352 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self.src or '.', 'mount_point': self.mount_point or '/'}
354 __repr__ = __str__
356 def _toxml(self, doc):
357 """Create a DOM element for this binding.
358 @param doc: document to use to create the element
359 @return: the new element
361 env_elem = doc.createElementNS(XMLNS_IFACE, 'overlay')
362 if self.src is not None:
363 env_elem.setAttributeNS(None, 'src', self.src)
364 if self.mount_point is not None:
365 env_elem.setAttributeNS(None, 'mount-point', self.mount_point)
366 return env_elem
368 class Feed(object):
369 """An interface's feeds are other interfaces whose implementations can also be
370 used as implementations of this interface."""
371 __slots__ = ['uri', 'os', 'machine', 'user_override', 'langs']
372 def __init__(self, uri, arch, user_override, langs = None):
373 self.uri = uri
374 # This indicates whether the feed comes from the user's overrides
375 # file. If true, writer.py will write it when saving.
376 self.user_override = user_override
377 self.os, self.machine = _split_arch(arch)
378 self.langs = langs
380 def __str__(self):
381 return "<Feed from %s>" % self.uri
382 __repr__ = __str__
384 arch = property(lambda self: _join_arch(self.os, self.machine))
386 class Dependency(object):
387 """A Dependency indicates that an Implementation requires some additional
388 code to function. This is an abstract base class.
389 @ivar qdom: the XML element for this Dependency (since 0launch 0.51)
390 @type qdom: L{qdom.Element}
391 @ivar metadata: any extra attributes from the XML element
392 @type metadata: {str: str}
394 __slots__ = ['qdom']
396 Essential = "essential"
397 Recommended = "recommended"
399 def __init__(self, element):
400 assert isinstance(element, qdom.Element), type(element) # Use InterfaceDependency instead!
401 self.qdom = element
403 @property
404 def metadata(self):
405 return self.qdom.attrs
407 @property
408 def importance(self):
409 return self.qdom.getAttribute("importance") or Dependency.Essential
411 class InterfaceDependency(Dependency):
412 """A Dependency on a Zero Install interface.
413 @ivar interface: the interface required by this dependency
414 @type interface: str
415 @ivar restrictions: a list of constraints on acceptable implementations
416 @type restrictions: [L{Restriction}]
417 @ivar bindings: how to make the choice of implementation known
418 @type bindings: [L{Binding}]
419 @since: 0.28
421 __slots__ = ['interface', 'restrictions', 'bindings']
423 def __init__(self, interface, restrictions = None, element = None):
424 Dependency.__init__(self, element)
425 assert isinstance(interface, (str, unicode))
426 assert interface
427 self.interface = interface
428 if restrictions is None:
429 self.restrictions = []
430 else:
431 self.restrictions = restrictions
432 self.bindings = []
434 def __str__(self):
435 return _("<Dependency on %(interface)s; bindings: %(bindings)s%(restrictions)s>") % {'interface': self.interface, 'bindings': self.bindings, 'restrictions': self.restrictions}
437 @property
438 def command(self):
439 return self.qdom.getAttribute("command") or ('run' if self.qdom.name == 'runner' else None)
442 class RetrievalMethod(object):
443 """A RetrievalMethod provides a way to fetch an implementation."""
444 __slots__ = []
446 class DownloadSource(RetrievalMethod):
447 """A DownloadSource provides a way to fetch an implementation."""
448 __slots__ = ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
450 def __init__(self, implementation, url, size, extract, start_offset = 0, type = None):
451 self.implementation = implementation
452 self.url = url
453 self.size = size
454 self.extract = extract
455 self.start_offset = start_offset
456 self.type = type # MIME type - see unpack.py
458 class Recipe(RetrievalMethod):
459 """Get an implementation by following a series of steps.
460 @ivar size: the combined download sizes from all the steps
461 @type size: int
462 @ivar steps: the sequence of steps which must be performed
463 @type steps: [L{RetrievalMethod}]"""
464 __slots__ = ['steps']
466 def __init__(self):
467 self.steps = []
469 size = property(lambda self: sum([x.size for x in self.steps]))
471 class DistributionSource(RetrievalMethod):
472 """A package that is installed using the distribution's tools (including PackageKit).
473 @ivar install: a function to call to install this package
474 @type install: (L{handler.Handler}) -> L{tasks.Blocker}
475 @ivar package_id: the package name, in a form recognised by the distribution's tools
476 @type package_id: str
477 @ivar size: the download size in bytes
478 @type size: int
479 @ivar needs_confirmation: whether the user should be asked to confirm before calling install()
480 @type needs_confirmation: bool"""
482 __slots__ = ['package_id', 'size', 'install', 'needs_confirmation']
484 def __init__(self, package_id, size, install, needs_confirmation = True):
485 RetrievalMethod.__init__(self)
486 self.package_id = package_id
487 self.size = size
488 self.install = install
489 self.needs_confirmation = needs_confirmation
491 class Command(object):
492 """A Command is a way of running an Implementation as a program."""
494 __slots__ = ['qdom', '_depends', '_local_dir', '_runner']
496 def __init__(self, qdom, local_dir):
497 """@param qdom: the <command> element
498 @param local_dir: the directory containing the feed (for relative dependencies), or None if not local
500 assert qdom.name == 'command', 'not <command>: %s' % qdom
501 self.qdom = qdom
502 self._local_dir = local_dir
503 self._depends = None
505 path = property(lambda self: self.qdom.attrs.get("path", None))
507 def _toxml(self, doc, prefixes):
508 return self.qdom.toDOM(doc, prefixes)
510 @property
511 def requires(self):
512 if self._depends is None:
513 self._runner = None
514 depends = []
515 for child in self.qdom.childNodes:
516 if child.name == 'requires':
517 dep = process_depends(child, self._local_dir)
518 depends.append(dep)
519 elif child.name == 'runner':
520 if self._runner:
521 raise InvalidInterface(_("Multiple <runner>s in <command>!"))
522 dep = process_depends(child, self._local_dir)
523 depends.append(dep)
524 self._runner = dep
525 self._depends = depends
526 return self._depends
528 def get_runner(self):
529 self.requires # (sets _runner)
530 return self._runner
532 def __str__(self):
533 return str(self.qdom)
535 class Implementation(object):
536 """An Implementation is a package which implements an Interface.
537 @ivar download_sources: list of methods of getting this implementation
538 @type download_sources: [L{RetrievalMethod}]
539 @ivar feed: the feed owning this implementation (since 0.32)
540 @type feed: [L{ZeroInstallFeed}]
541 @ivar bindings: how to tell this component where it itself is located (since 0.31)
542 @type bindings: [Binding]
543 @ivar upstream_stability: the stability reported by the packager
544 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged]
545 @ivar user_stability: the stability as set by the user
546 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred]
547 @ivar langs: natural languages supported by this package
548 @type langs: str
549 @ivar requires: interfaces this package depends on
550 @type requires: [L{Dependency}]
551 @ivar commands: ways to execute as a program
552 @type commands: {str: Command}
553 @ivar metadata: extra metadata from the feed
554 @type metadata: {"[URI ]localName": str}
555 @ivar id: a unique identifier for this Implementation
556 @ivar version: a parsed version number
557 @ivar released: release date
558 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path)
559 @type local_path: str | None
560 @ivar requires_root_install: whether the user will need admin rights to use this
561 @type requires_root_install: bool
564 # Note: user_stability shouldn't really be here
566 __slots__ = ['upstream_stability', 'user_stability', 'langs',
567 'requires', 'metadata', 'download_sources', 'commands',
568 'id', 'feed', 'version', 'released', 'bindings', 'machine']
570 def __init__(self, feed, id):
571 assert id
572 self.feed = feed
573 self.id = id
574 self.user_stability = None
575 self.upstream_stability = None
576 self.metadata = {} # [URI + " "] + localName -> value
577 self.requires = []
578 self.version = None
579 self.released = None
580 self.download_sources = []
581 self.langs = ""
582 self.machine = None
583 self.bindings = []
584 self.commands = {}
586 def get_stability(self):
587 return self.user_stability or self.upstream_stability or testing
589 def __str__(self):
590 return self.id
592 def __repr__(self):
593 return "v%s (%s)" % (self.get_version(), self.id)
595 def __cmp__(self, other):
596 """Newer versions come first"""
597 d = cmp(other.version, self.version)
598 if d: return d
599 # If the version number is the same, just give a stable sort order, and
600 # ensure that two different implementations don't compare equal.
601 d = cmp(other.feed.url, self.feed.url)
602 if d: return d
603 return cmp(other.id, self.id)
605 def get_version(self):
606 """Return the version as a string.
607 @see: L{format_version}
609 return format_version(self.version)
611 arch = property(lambda self: _join_arch(self.os, self.machine))
613 os = None
614 local_path = None
615 digests = None
616 requires_root_install = False
618 def _get_main(self):
619 """"@deprecated: use commands["run"] instead"""
620 main = self.commands.get("run", None)
621 if main is not None:
622 return main.path
623 return None
624 def _set_main(self, path):
625 """"@deprecated: use commands["run"] instead"""
626 if path is None:
627 if "run" in self.commands:
628 del self.commands["run"]
629 else:
630 self.commands["run"] = Command(qdom.Element(XMLNS_IFACE, 'command', {'path': path}), None)
631 main = property(_get_main, _set_main)
633 def is_available(self, stores):
634 """Is this Implementation available locally?
635 (a local implementation, an installed distribution package, or a cached ZeroInstallImplementation)
636 @rtype: bool
637 @since: 0.53
639 raise NotImplementedError("abstract")
641 class DistributionImplementation(Implementation):
642 """An implementation provided by the distribution. Information such as the version
643 comes from the package manager.
644 @since: 0.28"""
645 __slots__ = ['distro', 'installed']
647 def __init__(self, feed, id, distro):
648 assert id.startswith('package:')
649 Implementation.__init__(self, feed, id)
650 self.distro = distro
651 self.installed = False
653 @property
654 def requires_root_install(self):
655 return not self.installed
657 def is_available(self, stores):
658 return self.installed
660 class ZeroInstallImplementation(Implementation):
661 """An implementation where all the information comes from Zero Install.
662 @ivar digests: a list of "algorith=value" strings (since 0.45)
663 @type digests: [str]
664 @since: 0.28"""
665 __slots__ = ['os', 'size', 'digests', 'local_path']
667 def __init__(self, feed, id, local_path):
668 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
669 assert not id.startswith('package:'), id
670 Implementation.__init__(self, feed, id)
671 self.size = None
672 self.os = None
673 self.digests = []
674 self.local_path = local_path
676 # Deprecated
677 dependencies = property(lambda self: dict([(x.interface, x) for x in self.requires
678 if isinstance(x, InterfaceDependency)]))
680 def add_download_source(self, url, size, extract, start_offset = 0, type = None):
681 """Add a download source."""
682 self.download_sources.append(DownloadSource(self, url, size, extract, start_offset, type))
684 def set_arch(self, arch):
685 self.os, self.machine = _split_arch(arch)
686 arch = property(lambda self: _join_arch(self.os, self.machine), set_arch)
688 def is_available(self, stores):
689 if self.local_path is not None:
690 return os.path.exists(self.local_path)
691 if self.digests:
692 path = stores.lookup_maybe(self.digests)
693 return path is not None
694 return False # (0compile creates fake entries with no digests)
696 class Interface(object):
697 """An Interface represents some contract of behaviour.
698 @ivar uri: the URI for this interface.
699 @ivar stability_policy: user's configured policy.
700 Implementations at this level or higher are preferred.
701 Lower levels are used only if there is no other choice.
703 __slots__ = ['uri', 'stability_policy', 'extra_feeds']
705 implementations = property(lambda self: self._main_feed.implementations)
706 name = property(lambda self: self._main_feed.name)
707 description = property(lambda self: self._main_feed.description)
708 summary = property(lambda self: self._main_feed.summary)
709 last_modified = property(lambda self: self._main_feed.last_modified)
710 feeds = property(lambda self: self.extra_feeds + self._main_feed.feeds)
711 metadata = property(lambda self: self._main_feed.metadata)
713 last_checked = property(lambda self: self._main_feed.last_checked)
715 def __init__(self, uri):
716 assert uri
717 if uri.startswith('http:') or uri.startswith('https:') or os.path.isabs(uri):
718 self.uri = uri
719 else:
720 raise SafeException(_("Interface name '%s' doesn't start "
721 "with 'http:' or 'https:'") % uri)
722 self.reset()
724 def _get_feed_for(self):
725 retval = {}
726 for key in self._main_feed.feed_for:
727 retval[key] = True
728 return retval
729 feed_for = property(_get_feed_for) # Deprecated (used by 0publish)
731 def reset(self):
732 self.extra_feeds = []
733 self.stability_policy = None
735 def get_name(self):
736 from zeroinstall.injector.iface_cache import iface_cache
737 feed = iface_cache.get_feed(self.uri)
738 if feed:
739 return feed.get_name()
740 return '(' + os.path.basename(self.uri) + ')'
742 def __repr__(self):
743 return _("<Interface %s>") % self.uri
745 def set_stability_policy(self, new):
746 assert new is None or isinstance(new, Stability)
747 self.stability_policy = new
749 def get_feed(self, url):
750 #import warnings
751 #warnings.warn("use iface_cache.get_feed instead", DeprecationWarning, 2)
752 for x in self.extra_feeds:
753 if x.uri == url:
754 return x
755 #return self._main_feed.get_feed(url)
756 return None
758 def get_metadata(self, uri, name):
759 return self._main_feed.get_metadata(uri, name)
761 @property
762 def _main_feed(self):
763 #import warnings
764 #warnings.warn("use the feed instead", DeprecationWarning, 3)
765 from zeroinstall.injector import policy
766 iface_cache = policy.get_deprecated_singleton_config().iface_cache
767 feed = iface_cache.get_feed(self.uri)
768 if feed is None:
769 return _dummy_feed
770 return feed
772 def _merge_attrs(attrs, item):
773 """Add each attribute of item to a copy of attrs and return the copy.
774 @type attrs: {str: str}
775 @type item: L{qdom.Element}
776 @rtype: {str: str}
778 new = attrs.copy()
779 for a in item.attrs:
780 new[str(a)] = item.attrs[a]
781 return new
783 def _get_long(elem, attr_name):
784 val = elem.getAttribute(attr_name)
785 if val is not None:
786 try:
787 val = int(val)
788 except ValueError:
789 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name, 'value': val})
790 return val
792 class ZeroInstallFeed(object):
793 """A feed lists available implementations of an interface.
794 @ivar url: the URL for this feed
795 @ivar implementations: Implementations in this feed, indexed by ID
796 @type implementations: {str: L{Implementation}}
797 @ivar name: human-friendly name
798 @ivar summaries: short textual description (in various languages, since 0.49)
799 @type summaries: {str: str}
800 @ivar descriptions: long textual description (in various languages, since 0.49)
801 @type descriptions: {str: str}
802 @ivar last_modified: timestamp on signature
803 @ivar last_checked: time feed was last successfully downloaded and updated
804 @ivar feeds: list of <feed> elements in this feed
805 @type feeds: [L{Feed}]
806 @ivar feed_for: interfaces for which this could be a feed
807 @type feed_for: set(str)
808 @ivar metadata: extra elements we didn't understand
810 # _main is deprecated
811 __slots__ = ['url', 'implementations', 'name', 'descriptions', 'first_description', 'summaries', 'first_summary', '_package_implementations',
812 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
814 def __init__(self, feed_element, local_path = None, distro = None):
815 """Create a feed object from a DOM.
816 @param feed_element: the root element of a feed file
817 @type feed_element: L{qdom.Element}
818 @param local_path: the pathname of this local feed, or None for remote feeds"""
819 self.implementations = {}
820 self.name = None
821 self.summaries = {} # { lang: str }
822 self.first_summary = None
823 self.descriptions = {} # { lang: str }
824 self.first_description = None
825 self.last_modified = None
826 self.feeds = []
827 self.feed_for = set()
828 self.metadata = []
829 self.last_checked = None
830 self._package_implementations = []
832 if distro is not None:
833 import warnings
834 warnings.warn("distro argument is now ignored", DeprecationWarning, 2)
836 if feed_element is None:
837 return # XXX subclass?
839 assert feed_element.name in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
840 assert feed_element.uri == XMLNS_IFACE, "Wrong namespace on root element: %s" % feed_element.uri
842 main = feed_element.getAttribute('main')
843 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
845 if local_path:
846 self.url = local_path
847 local_dir = os.path.dirname(local_path)
848 else:
849 self.url = feed_element.getAttribute('uri')
850 if not self.url:
851 raise InvalidInterface(_("<interface> uri attribute missing"))
852 local_dir = None # Can't have relative paths
854 min_injector_version = feed_element.getAttribute('min-injector-version')
855 if min_injector_version:
856 if parse_version(min_injector_version) > parse_version(version):
857 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
858 "Zero Install, but I am only version %(version)s. "
859 "You can get a newer version from http://0install.net") %
860 {'min_version': min_injector_version, 'version': version})
862 for x in feed_element.childNodes:
863 if x.uri != XMLNS_IFACE:
864 self.metadata.append(x)
865 continue
866 if x.name == 'name':
867 self.name = x.content
868 elif x.name == 'description':
869 if self.first_description == None:
870 self.first_description = x.content
871 self.descriptions[x.attrs.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x.content
872 elif x.name == 'summary':
873 if self.first_summary == None:
874 self.first_summary = x.content
875 self.summaries[x.attrs.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x.content
876 elif x.name == 'feed-for':
877 feed_iface = x.getAttribute('interface')
878 if not feed_iface:
879 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
880 self.feed_for.add(feed_iface)
881 # Bug report from a Debian/stable user that --feed gets the wrong value.
882 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
883 # in case it happens again.
884 debug(_("Is feed-for %s"), feed_iface)
885 elif x.name == 'feed':
886 feed_src = x.getAttribute('src')
887 if not feed_src:
888 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
889 if feed_src.startswith('http:') or feed_src.startswith('https:') or local_path:
890 langs = x.getAttribute('langs')
891 if langs: langs = langs.replace('_', '-')
892 self.feeds.append(Feed(feed_src, x.getAttribute('arch'), False, langs = langs))
893 else:
894 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src)
895 else:
896 self.metadata.append(x)
898 if not self.name:
899 raise InvalidInterface(_("Missing <name> in feed"))
900 if not self.summary:
901 raise InvalidInterface(_("Missing <summary> in feed"))
903 def process_group(group, group_attrs, base_depends, base_bindings, base_commands):
904 for item in group.childNodes:
905 if item.uri != XMLNS_IFACE: continue
907 if item.name not in ('group', 'implementation', 'package-implementation'):
908 continue
910 # We've found a group or implementation. Scan for dependencies,
911 # bindings and commands. Doing this here means that:
912 # - We can share the code for groups and implementations here.
913 # - The order doesn't matter, because these get processed first.
914 # A side-effect is that the document root cannot contain
915 # these.
917 depends = base_depends[:]
918 bindings = base_bindings[:]
919 commands = base_commands.copy()
921 for attr, command in [('main', 'run'),
922 ('self-test', 'test')]:
923 value = item.attrs.get(attr, None)
924 if value is not None:
925 commands[command] = Command(qdom.Element(XMLNS_IFACE, 'command', {'name': command, 'path': value}), None)
927 for child in item.childNodes:
928 if child.uri != XMLNS_IFACE: continue
929 if child.name == 'requires':
930 dep = process_depends(child, local_dir)
931 depends.append(dep)
932 elif child.name == 'command':
933 command_name = child.attrs.get('name', None)
934 if not command_name:
935 raise InvalidInterface('Missing name for <command>')
936 commands[command_name] = Command(child, local_dir)
937 elif child.name in binding_names:
938 bindings.append(process_binding(child))
940 compile_command = item.attrs.get('http://zero-install.sourceforge.net/2006/namespaces/0compile command')
941 if compile_command is not None:
942 commands['compile'] = Command(qdom.Element(XMLNS_IFACE, 'command', {'name': 'compile', 'shell-command': compile_command}), None)
944 item_attrs = _merge_attrs(group_attrs, item)
946 if item.name == 'group':
947 process_group(item, item_attrs, depends, bindings, commands)
948 elif item.name == 'implementation':
949 process_impl(item, item_attrs, depends, bindings, commands)
950 elif item.name == 'package-implementation':
951 if depends:
952 warn("A <package-implementation> with dependencies in %s!", self.url)
953 self._package_implementations.append((item, item_attrs))
954 else:
955 assert 0
957 def process_impl(item, item_attrs, depends, bindings, commands):
958 id = item.getAttribute('id')
959 if id is None:
960 raise InvalidInterface(_("Missing 'id' attribute on %s") % item)
961 local_path = item_attrs.get('local-path')
962 if local_dir and local_path:
963 abs_local_path = os.path.abspath(os.path.join(local_dir, local_path))
964 impl = ZeroInstallImplementation(self, id, abs_local_path)
965 elif local_dir and (id.startswith('/') or id.startswith('.')):
966 # For old feeds
967 id = os.path.abspath(os.path.join(local_dir, id))
968 impl = ZeroInstallImplementation(self, id, id)
969 else:
970 impl = ZeroInstallImplementation(self, id, None)
971 if '=' in id:
972 # In older feeds, the ID was the (single) digest
973 impl.digests.append(id)
974 if id in self.implementations:
975 warn(_("Duplicate ID '%(id)s' in feed '%(feed)s'"), {'id': id, 'feed': self})
976 self.implementations[id] = impl
978 impl.metadata = item_attrs
979 try:
980 version_mod = item_attrs.get('version-modifier', None)
981 if version_mod:
982 item_attrs['version'] += version_mod
983 del item_attrs['version-modifier']
984 version = item_attrs['version']
985 except KeyError:
986 raise InvalidInterface(_("Missing version attribute"))
987 impl.version = parse_version(version)
989 impl.commands = commands
991 impl.released = item_attrs.get('released', None)
992 impl.langs = item_attrs.get('langs', '').replace('_', '-')
994 size = item.getAttribute('size')
995 if size:
996 impl.size = int(size)
997 impl.arch = item_attrs.get('arch', None)
998 try:
999 stability = stability_levels[str(item_attrs['stability'])]
1000 except KeyError:
1001 stab = str(item_attrs['stability'])
1002 if stab != stab.lower():
1003 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs.stability)
1004 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs['stability'])
1005 if stability >= preferred:
1006 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
1007 impl.upstream_stability = stability
1009 impl.bindings = bindings
1010 impl.requires = depends
1012 for elem in item.childNodes:
1013 if elem.uri != XMLNS_IFACE: continue
1014 if elem.name == 'archive':
1015 url = elem.getAttribute('href')
1016 if not url:
1017 raise InvalidInterface(_("Missing href attribute on <archive>"))
1018 size = elem.getAttribute('size')
1019 if not size:
1020 raise InvalidInterface(_("Missing size attribute on <archive>"))
1021 impl.add_download_source(url = url, size = int(size),
1022 extract = elem.getAttribute('extract'),
1023 start_offset = _get_long(elem, 'start-offset'),
1024 type = elem.getAttribute('type'))
1025 elif elem.name == 'manifest-digest':
1026 for aname, avalue in elem.attrs.iteritems():
1027 if ' ' not in aname:
1028 impl.digests.append('%s=%s' % (aname, avalue))
1029 elif elem.name == 'recipe':
1030 recipe = Recipe()
1031 for recipe_step in elem.childNodes:
1032 if recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'archive':
1033 url = recipe_step.getAttribute('href')
1034 if not url:
1035 raise InvalidInterface(_("Missing href attribute on <archive>"))
1036 size = recipe_step.getAttribute('size')
1037 if not size:
1038 raise InvalidInterface(_("Missing size attribute on <archive>"))
1039 recipe.steps.append(DownloadSource(None, url = url, size = int(size),
1040 extract = recipe_step.getAttribute('extract'),
1041 start_offset = _get_long(recipe_step, 'start-offset'),
1042 type = recipe_step.getAttribute('type')))
1043 else:
1044 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step.name)
1045 break
1046 else:
1047 impl.download_sources.append(recipe)
1049 root_attrs = {'stability': 'testing'}
1050 root_commands = {}
1051 if main:
1052 info("Note: @main on document element is deprecated in %s", self)
1053 root_commands['run'] = Command(qdom.Element(XMLNS_IFACE, 'command', {'path': main}), None)
1054 process_group(feed_element, root_attrs, [], [], root_commands)
1056 def get_distro_feed(self):
1057 """Does this feed contain any <pacakge-implementation> elements?
1058 i.e. is it worth asking the package manager for more information?
1059 @return: the URL of the virtual feed, or None
1060 @since: 0.49"""
1061 if self._package_implementations:
1062 return "distribution:" + self.url
1063 return None
1065 def get_package_impls(self, distro):
1066 """Find the best <pacakge-implementation> element(s) for the given distribution.
1067 @param distro: the distribution to use to rate them
1068 @type distro: L{distro.Distribution}
1069 @return: a list of tuples for the best ranked elements
1070 @rtype: [str]
1071 @since: 0.49"""
1072 best_score = 0
1073 best_impls = []
1075 for item, item_attrs in self._package_implementations:
1076 distro_names = item_attrs.get('distributions', '')
1077 for distro_name in distro_names.split(' '):
1078 score = distro.get_score(distro_name)
1079 if score > best_score:
1080 best_score = score
1081 best_impls = []
1082 if score == best_score:
1083 best_impls.append((item, item_attrs))
1084 return best_impls
1086 def get_name(self):
1087 return self.name or '(' + os.path.basename(self.url) + ')'
1089 def __repr__(self):
1090 return _("<Feed %s>") % self.url
1092 def set_stability_policy(self, new):
1093 assert new is None or isinstance(new, Stability)
1094 self.stability_policy = new
1096 def get_feed(self, url):
1097 for x in self.feeds:
1098 if x.uri == url:
1099 return x
1100 return None
1102 def add_metadata(self, elem):
1103 self.metadata.append(elem)
1105 def get_metadata(self, uri, name):
1106 """Return a list of interface metadata elements with this name and namespace URI."""
1107 return [m for m in self.metadata if m.name == name and m.uri == uri]
1109 @property
1110 def summary(self):
1111 return _best_language_match(self.summaries) or self.first_summary
1113 @property
1114 def description(self):
1115 return _best_language_match(self.descriptions) or self.first_description
1117 class DummyFeed(object):
1118 """Temporary class used during API transition."""
1119 last_modified = None
1120 name = '-'
1121 last_checked = property(lambda self: None)
1122 implementations = property(lambda self: {})
1123 feeds = property(lambda self: [])
1124 summary = property(lambda self: '-')
1125 description = property(lambda self: '')
1126 def get_name(self): return self.name
1127 def get_feed(self, url): return None
1128 def get_metadata(self, uri, name): return []
1129 _dummy_feed = DummyFeed()
1131 def unescape(uri):
1132 """Convert each %20 to a space, etc.
1133 @rtype: str"""
1134 uri = uri.replace('#', '/')
1135 if '%' not in uri: return uri
1136 return re.sub('%[0-9a-fA-F][0-9a-fA-F]',
1137 lambda match: chr(int(match.group(0)[1:], 16)),
1138 uri).decode('utf-8')
1140 def escape(uri):
1141 """Convert each space to %20, etc
1142 @rtype: str"""
1143 return re.sub('[^-_.a-zA-Z0-9]',
1144 lambda match: '%%%02x' % ord(match.group(0)),
1145 uri.encode('utf-8'))
1147 def _pretty_escape(uri):
1148 """Convert each space to %20, etc
1149 : is preserved and / becomes #. This makes for nicer strings,
1150 and may replace L{escape} everywhere in future.
1151 @rtype: str"""
1152 if os.name == "posix":
1153 # Only preserve : on Posix systems
1154 preserveRegex = '[^-_.a-zA-Z0-9:/]'
1155 else:
1156 # Other OSes may not allow the : character in file names
1157 preserveRegex = '[^-_.a-zA-Z0-9/]'
1158 return re.sub(preserveRegex,
1159 lambda match: '%%%02x' % ord(match.group(0)),
1160 uri.encode('utf-8')).replace('/', '#')
1162 def canonical_iface_uri(uri):
1163 """If uri is a relative path, convert to an absolute one.
1164 A "file:///foo" URI is converted to "/foo".
1165 An "alias:prog" URI expands to the URI in the 0alias script
1166 Otherwise, return it unmodified.
1167 @rtype: str
1168 @raise SafeException: if uri isn't valid
1170 if uri.startswith('http://') or uri.startswith('https://'):
1171 if uri.count("/") < 3:
1172 raise SafeException(_("Missing / after hostname in URI '%s'") % uri)
1173 return uri
1174 elif uri.startswith('file:///'):
1175 return uri[7:]
1176 elif uri.startswith('alias:'):
1177 from zeroinstall import alias, support
1178 alias_prog = uri[6:]
1179 if not os.path.isabs(alias_prog):
1180 full_path = support.find_in_path(alias_prog)
1181 if not full_path:
1182 raise alias.NotAnAliasScript("Not found in $PATH: " + alias_prog)
1183 else:
1184 full_path = alias_prog
1185 interface_uri, main = alias.parse_script(full_path)
1186 return interface_uri
1187 else:
1188 iface_uri = os.path.realpath(uri)
1189 if os.path.isfile(iface_uri):
1190 return iface_uri
1191 raise SafeException(_("Bad interface name '%(uri)s'.\n"
1192 "(doesn't start with 'http:', and "
1193 "doesn't exist as a local file '%(interface_uri)s' either)") %
1194 {'uri': uri, 'interface_uri': iface_uri})
1196 _version_mod_to_value = {
1197 'pre': -2,
1198 'rc': -1,
1199 '': 0,
1200 'post': 1,
1203 # Reverse mapping
1204 _version_value_to_mod = {}
1205 for x in _version_mod_to_value: _version_value_to_mod[_version_mod_to_value[x]] = x
1206 del x
1208 _version_re = re.compile('-([a-z]*)')
1210 def parse_version(version_string):
1211 """Convert a version string to an internal representation.
1212 The parsed format can be compared quickly using the standard Python functions.
1213 - Version := DottedList ("-" Mod DottedList?)*
1214 - DottedList := (Integer ("." Integer)*)
1215 @rtype: tuple (opaque)
1216 @raise SafeException: if the string isn't a valid version
1217 @since: 0.24 (moved from L{reader}, from where it is still available):"""
1218 if version_string is None: return None
1219 parts = _version_re.split(version_string)
1220 if parts[-1] == '':
1221 del parts[-1] # Ends with a modifier
1222 else:
1223 parts.append('')
1224 if not parts:
1225 raise SafeException(_("Empty version string!"))
1226 l = len(parts)
1227 try:
1228 for x in range(0, l, 2):
1229 part = parts[x]
1230 if part:
1231 parts[x] = map(int, parts[x].split('.'))
1232 else:
1233 parts[x] = [] # (because ''.split('.') == [''], not [])
1234 for x in range(1, l, 2):
1235 parts[x] = _version_mod_to_value[parts[x]]
1236 return parts
1237 except ValueError as ex:
1238 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1239 except KeyError as ex:
1240 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1242 def format_version(version):
1243 """Format a parsed version for display. Undoes the effect of L{parse_version}.
1244 @see: L{Implementation.get_version}
1245 @rtype: str
1246 @since: 0.24"""
1247 version = version[:]
1248 l = len(version)
1249 for x in range(0, l, 2):
1250 version[x] = '.'.join(map(str, version[x]))
1251 for x in range(1, l, 2):
1252 version[x] = '-' + _version_value_to_mod[version[x]]
1253 if version[-1] == '-': del version[-1]
1254 return ''.join(version)