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