Only process each <package-implementation> once, even if several distributions match...
[zeroinstall/solver.git] / zeroinstall / injector / model.py
blob8aa8f5751ed0aaa8520b4e7c673112e0896245e0
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, sys
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 __lt__(self, other):
111 if isinstance(other, Stability):
112 return self.level < other.level
113 else:
114 return NotImplemented
116 def __eq__(self, other):
117 if isinstance(other, Stability):
118 return self.level == other.level
119 else:
120 return NotImplemented
122 def __str__(self):
123 return self.name
125 def __repr__(self):
126 return _("<Stability: %s>") % self.description
128 def process_binding(e):
129 """Internal"""
130 if e.name == 'environment':
131 mode = {
132 None: EnvironmentBinding.PREPEND,
133 'prepend': EnvironmentBinding.PREPEND,
134 'append': EnvironmentBinding.APPEND,
135 'replace': EnvironmentBinding.REPLACE,
136 }[e.getAttribute('mode')]
138 binding = EnvironmentBinding(e.getAttribute('name'),
139 insert = e.getAttribute('insert'),
140 default = e.getAttribute('default'),
141 value = e.getAttribute('value'),
142 mode = mode,
143 separator = e.getAttribute('separator'))
144 if not binding.name: raise InvalidInterface(_("Missing 'name' in binding"))
145 if binding.insert is None and binding.value is None:
146 raise InvalidInterface(_("Missing 'insert' or 'value' in binding"))
147 if binding.insert is not None and binding.value is not None:
148 raise InvalidInterface(_("Binding contains both 'insert' and 'value'"))
149 return binding
150 elif e.name == 'executable-in-path':
151 return ExecutableBinding(e, in_path = True)
152 elif e.name == 'executable-in-var':
153 return ExecutableBinding(e, in_path = False)
154 elif e.name == 'overlay':
155 return OverlayBinding(e.getAttribute('src'), e.getAttribute('mount-point'))
156 else:
157 raise Exception(_("Unknown binding type '%s'") % e.name)
159 def process_depends(item, local_feed_dir):
160 """Internal"""
161 # Note: also called from selections
162 attrs = item.attrs
163 dep_iface = item.getAttribute('interface')
164 if not dep_iface:
165 raise InvalidInterface(_("Missing 'interface' on <%s>") % item.name)
166 if dep_iface.startswith('.'):
167 if local_feed_dir:
168 dep_iface = os.path.abspath(os.path.join(local_feed_dir, dep_iface))
169 # (updates the element too, in case we write it out again)
170 attrs['interface'] = dep_iface
171 else:
172 raise InvalidInterface(_('Relative interface URI "%s" in non-local feed') % dep_iface)
173 dependency = InterfaceDependency(dep_iface, element = item)
175 for e in item.childNodes:
176 if e.uri != XMLNS_IFACE: continue
177 if e.name in binding_names:
178 dependency.bindings.append(process_binding(e))
179 elif e.name == 'version':
180 dependency.restrictions.append(
181 VersionRangeRestriction(not_before = parse_version(e.getAttribute('not-before')),
182 before = parse_version(e.getAttribute('before'))))
183 return dependency
185 def N_(message): return message
187 insecure = Stability(0, N_('insecure'), _('This is a security risk'))
188 buggy = Stability(5, N_('buggy'), _('Known to have serious bugs'))
189 developer = Stability(10, N_('developer'), _('Work-in-progress - bugs likely'))
190 testing = Stability(20, N_('testing'), _('Stability unknown - please test!'))
191 stable = Stability(30, N_('stable'), _('Tested - no serious problems found'))
192 packaged = Stability(35, N_('packaged'), _('Supplied by the local package manager'))
193 preferred = Stability(40, N_('preferred'), _('Best of all - must be set manually'))
195 del N_
197 class Restriction(object):
198 """A Restriction limits the allowed implementations of an Interface."""
199 __slots__ = []
201 def meets_restriction(self, impl):
202 """Called by the L{solver.Solver} to check whether a particular implementation is acceptable.
203 @return: False if this implementation is not a possibility
204 @rtype: bool
206 raise NotImplementedError(_("Abstract"))
208 class VersionRestriction(Restriction):
209 """Only select implementations with a particular version number.
210 @since: 0.40"""
212 def __init__(self, version):
213 """@param version: the required version number
214 @see: L{parse_version}; use this to pre-process the version number
216 self.version = version
218 def meets_restriction(self, impl):
219 return impl.version == self.version
221 def __str__(self):
222 return _("(restriction: version = %s)") % format_version(self.version)
224 class VersionRangeRestriction(Restriction):
225 """Only versions within the given range are acceptable"""
226 __slots__ = ['before', 'not_before']
228 def __init__(self, before, not_before):
229 """@param before: chosen versions must be earlier than this
230 @param not_before: versions must be at least this high
231 @see: L{parse_version}; use this to pre-process the versions
233 self.before = before
234 self.not_before = not_before
236 def meets_restriction(self, impl):
237 if self.not_before and impl.version < self.not_before:
238 return False
239 if self.before and impl.version >= self.before:
240 return False
241 return True
243 def __str__(self):
244 if self.not_before is not None or self.before is not None:
245 range = ''
246 if self.not_before is not None:
247 range += format_version(self.not_before) + ' <= '
248 range += 'version'
249 if self.before is not None:
250 range += ' < ' + format_version(self.before)
251 else:
252 range = 'none'
253 return _("(restriction: %s)") % range
255 class Binding(object):
256 """Information about how the choice of a Dependency is made known
257 to the application being run."""
259 @property
260 def command(self):
261 """"Returns the name of the specific command needed by this binding, if any.
262 @since: 1.2"""
263 return None
265 class EnvironmentBinding(Binding):
266 """Indicate the chosen implementation using an environment variable."""
267 __slots__ = ['name', 'insert', 'default', 'mode', 'value']
269 PREPEND = 'prepend'
270 APPEND = 'append'
271 REPLACE = 'replace'
273 def __init__(self, name, insert, default = None, mode = PREPEND, value=None, separator=None):
275 mode argument added in version 0.28
276 value argument added in version 0.52
278 self.name = name
279 self.insert = insert
280 self.default = default
281 self.mode = mode
282 self.value = value
283 if separator is None:
284 self.separator = os.pathsep
285 else:
286 self.separator = separator
289 def __str__(self):
290 return _("<environ %(name)s %(mode)s %(insert)s %(value)s>") % \
291 {'name': self.name, 'mode': self.mode, 'insert': self.insert, 'value': self.value}
293 __repr__ = __str__
295 def get_value(self, path, old_value):
296 """Calculate the new value of the environment variable after applying this binding.
297 @param path: the path to the selected implementation
298 @param old_value: the current value of the environment variable
299 @return: the new value for the environment variable"""
301 if self.insert is not None:
302 extra = os.path.join(path, self.insert)
303 else:
304 assert self.value is not None
305 extra = self.value
307 if self.mode == EnvironmentBinding.REPLACE:
308 return extra
310 if old_value is None:
311 old_value = self.default or defaults.get(self.name, None)
312 if old_value is None:
313 return extra
314 if self.mode == EnvironmentBinding.PREPEND:
315 return extra + self.separator + old_value
316 else:
317 return old_value + self.separator + extra
319 def _toxml(self, doc, prefixes):
320 """Create a DOM element for this binding.
321 @param doc: document to use to create the element
322 @return: the new element
324 env_elem = doc.createElementNS(XMLNS_IFACE, 'environment')
325 env_elem.setAttributeNS(None, 'name', self.name)
326 if self.mode is not None:
327 env_elem.setAttributeNS(None, 'mode', self.mode)
328 if self.insert is not None:
329 env_elem.setAttributeNS(None, 'insert', self.insert)
330 else:
331 env_elem.setAttributeNS(None, 'value', self.value)
332 if self.default:
333 env_elem.setAttributeNS(None, 'default', self.default)
334 if self.separator:
335 env_elem.setAttributeNS(None, 'separator', self.separator)
336 return env_elem
338 class ExecutableBinding(Binding):
339 """Make the chosen command available in $PATH.
340 @ivar in_path: True to add the named command to $PATH, False to store in named variable
341 @type in_path: bool
343 __slots__ = ['qdom']
345 def __init__(self, qdom, in_path):
346 self.qdom = qdom
347 self.in_path = in_path
349 def __str__(self):
350 return str(self.qdom)
352 __repr__ = __str__
354 def _toxml(self, doc, prefixes):
355 return self.qdom.toDOM(doc, prefixes)
357 @property
358 def name(self):
359 return self.qdom.getAttribute('name')
361 @property
362 def command(self):
363 return self.qdom.getAttribute("command") or 'run'
365 class OverlayBinding(Binding):
366 """Make the chosen implementation available by overlaying it onto another part of the file-system.
367 This is to support legacy programs which use hard-coded paths."""
368 __slots__ = ['src', 'mount_point']
370 def __init__(self, src, mount_point):
371 self.src = src
372 self.mount_point = mount_point
374 def __str__(self):
375 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self.src or '.', 'mount_point': self.mount_point or '/'}
377 __repr__ = __str__
379 def _toxml(self, doc, prefixes):
380 """Create a DOM element for this binding.
381 @param doc: document to use to create the element
382 @return: the new element
384 env_elem = doc.createElementNS(XMLNS_IFACE, 'overlay')
385 if self.src is not None:
386 env_elem.setAttributeNS(None, 'src', self.src)
387 if self.mount_point is not None:
388 env_elem.setAttributeNS(None, 'mount-point', self.mount_point)
389 return env_elem
391 class Feed(object):
392 """An interface's feeds are other interfaces whose implementations can also be
393 used as implementations of this interface."""
394 __slots__ = ['uri', 'os', 'machine', 'user_override', 'langs', 'site_package']
395 def __init__(self, uri, arch, user_override, langs = None, site_package = False):
396 self.uri = uri
397 # This indicates whether the feed comes from the user's overrides
398 # file. If true, writer.py will write it when saving.
399 self.user_override = user_override
400 self.os, self.machine = _split_arch(arch)
401 self.langs = langs
402 self.site_package = site_package
404 def __str__(self):
405 return "<Feed from %s>" % self.uri
406 __repr__ = __str__
408 arch = property(lambda self: _join_arch(self.os, self.machine))
410 class Dependency(object):
411 """A Dependency indicates that an Implementation requires some additional
412 code to function. This is an abstract base class.
413 @ivar qdom: the XML element for this Dependency (since 0launch 0.51)
414 @type qdom: L{qdom.Element}
415 @ivar metadata: any extra attributes from the XML element
416 @type metadata: {str: str}
418 __slots__ = ['qdom']
420 Essential = "essential"
421 Recommended = "recommended"
423 def __init__(self, element):
424 assert isinstance(element, qdom.Element), type(element) # Use InterfaceDependency instead!
425 self.qdom = element
427 @property
428 def metadata(self):
429 return self.qdom.attrs
431 @property
432 def importance(self):
433 return self.qdom.getAttribute("importance") or Dependency.Essential
435 def get_required_commands(self):
436 """Return a list of command names needed by this dependency"""
437 return []
439 class InterfaceDependency(Dependency):
440 """A Dependency on a Zero Install interface.
441 @ivar interface: the interface required by this dependency
442 @type interface: str
443 @ivar restrictions: a list of constraints on acceptable implementations
444 @type restrictions: [L{Restriction}]
445 @ivar bindings: how to make the choice of implementation known
446 @type bindings: [L{Binding}]
447 @since: 0.28
449 __slots__ = ['interface', 'restrictions', 'bindings']
451 def __init__(self, interface, restrictions = None, element = None):
452 Dependency.__init__(self, element)
453 assert isinstance(interface, (str, unicode))
454 assert interface
455 self.interface = interface
456 if restrictions is None:
457 self.restrictions = []
458 else:
459 self.restrictions = restrictions
460 self.bindings = []
462 def __str__(self):
463 return _("<Dependency on %(interface)s; bindings: %(bindings)s%(restrictions)s>") % {'interface': self.interface, 'bindings': self.bindings, 'restrictions': self.restrictions}
465 def get_required_commands(self):
466 """Return a list of command names needed by this dependency"""
467 if self.qdom.name == 'runner':
468 commands = [self.qdom.getAttribute('command') or 'run']
469 else:
470 commands = []
471 for b in self.bindings:
472 c = b.command
473 if c is not None:
474 commands.append(c)
475 return commands
477 @property
478 def command(self):
479 if self.qdom.name == 'runner':
480 return self.qdom.getAttribute('command') or 'run'
481 return None
483 class RetrievalMethod(object):
484 """A RetrievalMethod provides a way to fetch an implementation."""
485 __slots__ = []
487 class DownloadSource(RetrievalMethod):
488 """A DownloadSource provides a way to fetch an implementation."""
489 __slots__ = ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
491 def __init__(self, implementation, url, size, extract, start_offset = 0, type = None):
492 self.implementation = implementation
493 self.url = url
494 self.size = size
495 self.extract = extract
496 self.start_offset = start_offset
497 self.type = type # MIME type - see unpack.py
499 class RenameStep(RetrievalMethod):
500 """A Rename provides a way to rename / move a file within an implementation."""
501 __slots__ = ['source', 'dest']
503 def __init__(self, source, dest):
504 self.source = source
505 self.dest = dest
507 class Recipe(RetrievalMethod):
508 """Get an implementation by following a series of steps.
509 @ivar size: the combined download sizes from all the steps
510 @type size: int
511 @ivar steps: the sequence of steps which must be performed
512 @type steps: [L{RetrievalMethod}]"""
513 __slots__ = ['steps']
515 def __init__(self):
516 self.steps = []
518 size = property(lambda self: sum([x.size for x in self.steps if isinstance(x, DownloadSource)]))
520 class DistributionSource(RetrievalMethod):
521 """A package that is installed using the distribution's tools (including PackageKit).
522 @ivar install: a function to call to install this package
523 @type install: (L{handler.Handler}) -> L{tasks.Blocker}
524 @ivar package_id: the package name, in a form recognised by the distribution's tools
525 @type package_id: str
526 @ivar size: the download size in bytes
527 @type size: int
528 @ivar needs_confirmation: whether the user should be asked to confirm before calling install()
529 @type needs_confirmation: bool"""
531 __slots__ = ['package_id', 'size', 'install', 'needs_confirmation']
533 def __init__(self, package_id, size, install, needs_confirmation = True):
534 RetrievalMethod.__init__(self)
535 self.package_id = package_id
536 self.size = size
537 self.install = install
538 self.needs_confirmation = needs_confirmation
540 class Command(object):
541 """A Command is a way of running an Implementation as a program."""
543 __slots__ = ['qdom', '_depends', '_local_dir', '_runner', '_bindings']
545 def __init__(self, qdom, local_dir):
546 """@param qdom: the <command> element
547 @param local_dir: the directory containing the feed (for relative dependencies), or None if not local
549 assert qdom.name == 'command', 'not <command>: %s' % qdom
550 self.qdom = qdom
551 self._local_dir = local_dir
552 self._depends = None
553 self._bindings = None
555 path = property(lambda self: self.qdom.attrs.get("path", None))
557 def _toxml(self, doc, prefixes):
558 return self.qdom.toDOM(doc, prefixes)
560 @property
561 def requires(self):
562 if self._depends is None:
563 self._runner = None
564 depends = []
565 for child in self.qdom.childNodes:
566 if child.name == 'requires':
567 dep = process_depends(child, self._local_dir)
568 depends.append(dep)
569 elif child.name == 'runner':
570 if self._runner:
571 raise InvalidInterface(_("Multiple <runner>s in <command>!"))
572 dep = process_depends(child, self._local_dir)
573 depends.append(dep)
574 self._runner = dep
575 self._depends = depends
576 return self._depends
578 def get_runner(self):
579 self.requires # (sets _runner)
580 return self._runner
582 def __str__(self):
583 return str(self.qdom)
585 @property
586 def bindings(self):
587 """@since: 1.3"""
588 if self._bindings is None:
589 bindings = []
590 for e in self.qdom.childNodes:
591 if e.uri != XMLNS_IFACE: continue
592 if e.name in binding_names:
593 bindings.append(process_binding(e))
594 self._bindings = bindings
595 return self._bindings
597 class Implementation(object):
598 """An Implementation is a package which implements an Interface.
599 @ivar download_sources: list of methods of getting this implementation
600 @type download_sources: [L{RetrievalMethod}]
601 @ivar feed: the feed owning this implementation (since 0.32)
602 @type feed: [L{ZeroInstallFeed}]
603 @ivar bindings: how to tell this component where it itself is located (since 0.31)
604 @type bindings: [Binding]
605 @ivar upstream_stability: the stability reported by the packager
606 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged]
607 @ivar user_stability: the stability as set by the user
608 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred]
609 @ivar langs: natural languages supported by this package
610 @type langs: str
611 @ivar requires: interfaces this package depends on
612 @type requires: [L{Dependency}]
613 @ivar commands: ways to execute as a program
614 @type commands: {str: Command}
615 @ivar metadata: extra metadata from the feed
616 @type metadata: {"[URI ]localName": str}
617 @ivar id: a unique identifier for this Implementation
618 @ivar version: a parsed version number
619 @ivar released: release date
620 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path)
621 @type local_path: str | None
622 @ivar requires_root_install: whether the user will need admin rights to use this
623 @type requires_root_install: bool
626 # Note: user_stability shouldn't really be here
628 __slots__ = ['upstream_stability', 'user_stability', 'langs',
629 'requires', 'metadata', 'download_sources', 'commands',
630 'id', 'feed', 'version', 'released', 'bindings', 'machine']
632 def __init__(self, feed, id):
633 assert id
634 self.feed = feed
635 self.id = id
636 self.user_stability = None
637 self.upstream_stability = None
638 self.metadata = {} # [URI + " "] + localName -> value
639 self.requires = []
640 self.version = None
641 self.released = None
642 self.download_sources = []
643 self.langs = ""
644 self.machine = None
645 self.bindings = []
646 self.commands = {}
648 def get_stability(self):
649 return self.user_stability or self.upstream_stability or testing
651 def __str__(self):
652 return self.id
654 def __repr__(self):
655 return "v%s (%s)" % (self.get_version(), self.id)
657 def __cmp__(self, other):
658 """Newer versions come first"""
659 d = cmp(other.version, self.version)
660 if d: return d
661 # If the version number is the same, just give a stable sort order, and
662 # ensure that two different implementations don't compare equal.
663 d = cmp(other.feed.url, self.feed.url)
664 if d: return d
665 return cmp(other.id, self.id)
667 def __hash__(self):
668 return self.id.__hash__()
670 def __eq__(self, other):
671 return self is other
673 def __le__(self, other):
674 if isinstance(other, Implementation):
675 if other.version < self.version: return True
676 elif other.version > self.version: return False
678 if other.feed.url < self.feed.url: return True
679 elif other.feed.url > self.feed.url: return False
681 return other.id <= self.id
682 else:
683 return NotImplemented
685 def get_version(self):
686 """Return the version as a string.
687 @see: L{format_version}
689 return format_version(self.version)
691 arch = property(lambda self: _join_arch(self.os, self.machine))
693 os = None
694 local_path = None
695 digests = None
696 requires_root_install = False
698 def _get_main(self):
699 """"@deprecated: use commands["run"] instead"""
700 main = self.commands.get("run", None)
701 if main is not None:
702 return main.path
703 return None
704 def _set_main(self, path):
705 """"@deprecated: use commands["run"] instead"""
706 if path is None:
707 if "run" in self.commands:
708 del self.commands["run"]
709 else:
710 self.commands["run"] = Command(qdom.Element(XMLNS_IFACE, 'command', {'path': path, 'name': 'run'}), None)
711 main = property(_get_main, _set_main)
713 def is_available(self, stores):
714 """Is this Implementation available locally?
715 (a local implementation, an installed distribution package, or a cached ZeroInstallImplementation)
716 @rtype: bool
717 @since: 0.53
719 raise NotImplementedError("abstract")
721 class DistributionImplementation(Implementation):
722 """An implementation provided by the distribution. Information such as the version
723 comes from the package manager.
724 @ivar package_implementation: the <package-implementation> element that generated this impl (since 1.7)
725 @type package_implementation: L{qdom.Element}
726 @since: 0.28"""
727 __slots__ = ['distro', 'installed', 'package_implementation']
729 def __init__(self, feed, id, distro, package_implementation = None):
730 assert id.startswith('package:')
731 Implementation.__init__(self, feed, id)
732 self.distro = distro
733 self.installed = False
734 self.package_implementation = package_implementation
736 if package_implementation:
737 for child in package_implementation.childNodes:
738 if child.uri != XMLNS_IFACE: continue
739 if child.name == 'command':
740 command_name = child.attrs.get('name', None)
741 if not command_name:
742 raise InvalidInterface('Missing name for <command>')
743 self.commands[command_name] = Command(child, local_dir = None)
745 @property
746 def requires_root_install(self):
747 return not self.installed
749 def is_available(self, stores):
750 return self.installed
752 class ZeroInstallImplementation(Implementation):
753 """An implementation where all the information comes from Zero Install.
754 @ivar digests: a list of "algorith=value" strings (since 0.45)
755 @type digests: [str]
756 @since: 0.28"""
757 __slots__ = ['os', 'size', 'digests', 'local_path']
759 def __init__(self, feed, id, local_path):
760 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
761 assert not id.startswith('package:'), id
762 Implementation.__init__(self, feed, id)
763 self.size = None
764 self.os = None
765 self.digests = []
766 self.local_path = local_path
768 # Deprecated
769 dependencies = property(lambda self: dict([(x.interface, x) for x in self.requires
770 if isinstance(x, InterfaceDependency)]))
772 def add_download_source(self, url, size, extract, start_offset = 0, type = None):
773 """Add a download source."""
774 self.download_sources.append(DownloadSource(self, url, size, extract, start_offset, type))
776 def set_arch(self, arch):
777 self.os, self.machine = _split_arch(arch)
778 arch = property(lambda self: _join_arch(self.os, self.machine), set_arch)
780 def is_available(self, stores):
781 if self.local_path is not None:
782 return os.path.exists(self.local_path)
783 if self.digests:
784 path = stores.lookup_maybe(self.digests)
785 return path is not None
786 return False # (0compile creates fake entries with no digests)
788 class Interface(object):
789 """An Interface represents some contract of behaviour.
790 @ivar uri: the URI for this interface.
791 @ivar stability_policy: user's configured policy.
792 Implementations at this level or higher are preferred.
793 Lower levels are used only if there is no other choice.
795 __slots__ = ['uri', 'stability_policy', 'extra_feeds']
797 implementations = property(lambda self: self._main_feed.implementations)
798 name = property(lambda self: self._main_feed.name)
799 description = property(lambda self: self._main_feed.description)
800 summary = property(lambda self: self._main_feed.summary)
801 last_modified = property(lambda self: self._main_feed.last_modified)
802 feeds = property(lambda self: self.extra_feeds + self._main_feed.feeds)
803 metadata = property(lambda self: self._main_feed.metadata)
805 last_checked = property(lambda self: self._main_feed.last_checked)
807 def __init__(self, uri):
808 assert uri
809 if uri.startswith('http:') or uri.startswith('https:') or os.path.isabs(uri):
810 self.uri = uri
811 else:
812 raise SafeException(_("Interface name '%s' doesn't start "
813 "with 'http:' or 'https:'") % uri)
814 self.reset()
816 def _get_feed_for(self):
817 retval = {}
818 for key in self._main_feed.feed_for:
819 retval[key] = True
820 return retval
821 feed_for = property(_get_feed_for) # Deprecated (used by 0publish)
823 def reset(self):
824 self.extra_feeds = []
825 self.stability_policy = None
827 def get_name(self):
828 from zeroinstall.injector.iface_cache import iface_cache
829 feed = iface_cache.get_feed(self.uri)
830 if feed:
831 return feed.get_name()
832 return '(' + os.path.basename(self.uri) + ')'
834 def __repr__(self):
835 return _("<Interface %s>") % self.uri
837 def set_stability_policy(self, new):
838 assert new is None or isinstance(new, Stability)
839 self.stability_policy = new
841 def get_feed(self, url):
842 #import warnings
843 #warnings.warn("use iface_cache.get_feed instead", DeprecationWarning, 2)
844 for x in self.extra_feeds:
845 if x.uri == url:
846 return x
847 #return self._main_feed.get_feed(url)
848 return None
850 def get_metadata(self, uri, name):
851 return self._main_feed.get_metadata(uri, name)
853 @property
854 def _main_feed(self):
855 #import warnings
856 #warnings.warn("use the feed instead", DeprecationWarning, 3)
857 from zeroinstall.injector import policy
858 iface_cache = policy.get_deprecated_singleton_config().iface_cache
859 feed = iface_cache.get_feed(self.uri)
860 if feed is None:
861 return _dummy_feed
862 return feed
864 def _merge_attrs(attrs, item):
865 """Add each attribute of item to a copy of attrs and return the copy.
866 @type attrs: {str: str}
867 @type item: L{qdom.Element}
868 @rtype: {str: str}
870 new = attrs.copy()
871 for a in item.attrs:
872 new[str(a)] = item.attrs[a]
873 return new
875 def _get_long(elem, attr_name):
876 val = elem.getAttribute(attr_name)
877 if val is not None:
878 try:
879 val = int(val)
880 except ValueError:
881 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name, 'value': val})
882 return val
884 class ZeroInstallFeed(object):
885 """A feed lists available implementations of an interface.
886 @ivar url: the URL for this feed
887 @ivar implementations: Implementations in this feed, indexed by ID
888 @type implementations: {str: L{Implementation}}
889 @ivar name: human-friendly name
890 @ivar summaries: short textual description (in various languages, since 0.49)
891 @type summaries: {str: str}
892 @ivar descriptions: long textual description (in various languages, since 0.49)
893 @type descriptions: {str: str}
894 @ivar last_modified: timestamp on signature
895 @ivar last_checked: time feed was last successfully downloaded and updated
896 @ivar local_path: the path of this local feed, or None if remote (since 1.7)
897 @type local_path: str | None
898 @ivar feeds: list of <feed> elements in this feed
899 @type feeds: [L{Feed}]
900 @ivar feed_for: interfaces for which this could be a feed
901 @type feed_for: set(str)
902 @ivar metadata: extra elements we didn't understand
904 # _main is deprecated
905 __slots__ = ['url', 'implementations', 'name', 'descriptions', 'first_description', 'summaries', 'first_summary', '_package_implementations',
906 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata', 'local_path']
908 def __init__(self, feed_element, local_path = None, distro = None):
909 """Create a feed object from a DOM.
910 @param feed_element: the root element of a feed file
911 @type feed_element: L{qdom.Element}
912 @param local_path: the pathname of this local feed, or None for remote feeds"""
913 self.local_path = local_path
914 self.implementations = {}
915 self.name = None
916 self.summaries = {} # { lang: str }
917 self.first_summary = None
918 self.descriptions = {} # { lang: str }
919 self.first_description = None
920 self.last_modified = None
921 self.feeds = []
922 self.feed_for = set()
923 self.metadata = []
924 self.last_checked = None
925 self._package_implementations = []
927 if distro is not None:
928 import warnings
929 warnings.warn("distro argument is now ignored", DeprecationWarning, 2)
931 if feed_element is None:
932 return # XXX subclass?
934 assert feed_element.name in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
935 assert feed_element.uri == XMLNS_IFACE, "Wrong namespace on root element: %s" % feed_element.uri
937 main = feed_element.getAttribute('main')
938 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
940 if local_path:
941 self.url = local_path
942 local_dir = os.path.dirname(local_path)
943 else:
944 assert local_path is None
945 self.url = feed_element.getAttribute('uri')
946 if not self.url:
947 raise InvalidInterface(_("<interface> uri attribute missing"))
948 local_dir = None # Can't have relative paths
950 min_injector_version = feed_element.getAttribute('min-injector-version')
951 if min_injector_version:
952 if parse_version(min_injector_version) > parse_version(version):
953 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
954 "Zero Install, but I am only version %(version)s. "
955 "You can get a newer version from http://0install.net") %
956 {'min_version': min_injector_version, 'version': version})
958 for x in feed_element.childNodes:
959 if x.uri != XMLNS_IFACE:
960 self.metadata.append(x)
961 continue
962 if x.name == 'name':
963 self.name = x.content
964 elif x.name == 'description':
965 if self.first_description == None:
966 self.first_description = x.content
967 self.descriptions[x.attrs.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x.content
968 elif x.name == 'summary':
969 if self.first_summary == None:
970 self.first_summary = x.content
971 self.summaries[x.attrs.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x.content
972 elif x.name == 'feed-for':
973 feed_iface = x.getAttribute('interface')
974 if not feed_iface:
975 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
976 self.feed_for.add(feed_iface)
977 # Bug report from a Debian/stable user that --feed gets the wrong value.
978 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
979 # in case it happens again.
980 debug(_("Is feed-for %s"), feed_iface)
981 elif x.name == 'feed':
982 feed_src = x.getAttribute('src')
983 if not feed_src:
984 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
985 if feed_src.startswith('http:') or feed_src.startswith('https:') or local_path:
986 langs = x.getAttribute('langs')
987 if langs: langs = langs.replace('_', '-')
988 self.feeds.append(Feed(feed_src, x.getAttribute('arch'), False, langs = langs))
989 else:
990 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src)
991 else:
992 self.metadata.append(x)
994 if not self.name:
995 raise InvalidInterface(_("Missing <name> in feed"))
996 if not self.summary:
997 raise InvalidInterface(_("Missing <summary> in feed"))
999 def process_group(group, group_attrs, base_depends, base_bindings, base_commands):
1000 for item in group.childNodes:
1001 if item.uri != XMLNS_IFACE: continue
1003 if item.name not in ('group', 'implementation', 'package-implementation'):
1004 continue
1006 # We've found a group or implementation. Scan for dependencies,
1007 # bindings and commands. Doing this here means that:
1008 # - We can share the code for groups and implementations here.
1009 # - The order doesn't matter, because these get processed first.
1010 # A side-effect is that the document root cannot contain
1011 # these.
1013 depends = base_depends[:]
1014 bindings = base_bindings[:]
1015 commands = base_commands.copy()
1017 for attr, command in [('main', 'run'),
1018 ('self-test', 'test')]:
1019 value = item.attrs.get(attr, None)
1020 if value is not None:
1021 commands[command] = Command(qdom.Element(XMLNS_IFACE, 'command', {'name': command, 'path': value}), None)
1023 for child in item.childNodes:
1024 if child.uri != XMLNS_IFACE: continue
1025 if child.name == 'requires':
1026 dep = process_depends(child, local_dir)
1027 depends.append(dep)
1028 elif child.name == 'command':
1029 command_name = child.attrs.get('name', None)
1030 if not command_name:
1031 raise InvalidInterface('Missing name for <command>')
1032 commands[command_name] = Command(child, local_dir)
1033 elif child.name in binding_names:
1034 bindings.append(process_binding(child))
1036 compile_command = item.attrs.get('http://zero-install.sourceforge.net/2006/namespaces/0compile command')
1037 if compile_command is not None:
1038 commands['compile'] = Command(qdom.Element(XMLNS_IFACE, 'command', {'name': 'compile', 'shell-command': compile_command}), None)
1040 item_attrs = _merge_attrs(group_attrs, item)
1042 if item.name == 'group':
1043 process_group(item, item_attrs, depends, bindings, commands)
1044 elif item.name == 'implementation':
1045 process_impl(item, item_attrs, depends, bindings, commands)
1046 elif item.name == 'package-implementation':
1047 if depends:
1048 warn("A <package-implementation> with dependencies in %s!", self.url)
1049 self._package_implementations.append((item, item_attrs))
1050 else:
1051 assert 0
1053 def process_impl(item, item_attrs, depends, bindings, commands):
1054 id = item.getAttribute('id')
1055 if id is None:
1056 raise InvalidInterface(_("Missing 'id' attribute on %s") % item)
1057 local_path = item_attrs.get('local-path')
1058 if local_dir and local_path:
1059 abs_local_path = os.path.abspath(os.path.join(local_dir, local_path))
1060 impl = ZeroInstallImplementation(self, id, abs_local_path)
1061 elif local_dir and (id.startswith('/') or id.startswith('.')):
1062 # For old feeds
1063 id = os.path.abspath(os.path.join(local_dir, id))
1064 impl = ZeroInstallImplementation(self, id, id)
1065 else:
1066 impl = ZeroInstallImplementation(self, id, None)
1067 if '=' in id:
1068 # In older feeds, the ID was the (single) digest
1069 impl.digests.append(id)
1070 if id in self.implementations:
1071 warn(_("Duplicate ID '%(id)s' in feed '%(feed)s'"), {'id': id, 'feed': self})
1072 self.implementations[id] = impl
1074 impl.metadata = item_attrs
1075 try:
1076 version_mod = item_attrs.get('version-modifier', None)
1077 if version_mod:
1078 item_attrs['version'] += version_mod
1079 del item_attrs['version-modifier']
1080 version = item_attrs['version']
1081 except KeyError:
1082 raise InvalidInterface(_("Missing version attribute"))
1083 impl.version = parse_version(version)
1085 impl.commands = commands
1087 impl.released = item_attrs.get('released', None)
1088 impl.langs = item_attrs.get('langs', '').replace('_', '-')
1090 size = item.getAttribute('size')
1091 if size:
1092 impl.size = int(size)
1093 impl.arch = item_attrs.get('arch', None)
1094 try:
1095 stability = stability_levels[str(item_attrs['stability'])]
1096 except KeyError:
1097 stab = str(item_attrs['stability'])
1098 if stab != stab.lower():
1099 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs.stability)
1100 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs['stability'])
1101 if stability >= preferred:
1102 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
1103 impl.upstream_stability = stability
1105 impl.bindings = bindings
1106 impl.requires = depends
1108 for elem in item.childNodes:
1109 if elem.uri != XMLNS_IFACE: continue
1110 if elem.name == 'archive':
1111 url = elem.getAttribute('href')
1112 if not url:
1113 raise InvalidInterface(_("Missing href attribute on <archive>"))
1114 size = elem.getAttribute('size')
1115 if not size:
1116 raise InvalidInterface(_("Missing size attribute on <archive>"))
1117 impl.add_download_source(url = url, size = int(size),
1118 extract = elem.getAttribute('extract'),
1119 start_offset = _get_long(elem, 'start-offset'),
1120 type = elem.getAttribute('type'))
1121 elif elem.name == 'manifest-digest':
1122 for aname, avalue in elem.attrs.items():
1123 if ' ' not in aname:
1124 impl.digests.append('%s=%s' % (aname, avalue))
1125 elif elem.name == 'recipe':
1126 recipe = Recipe()
1127 for recipe_step in elem.childNodes:
1128 if recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'archive':
1129 url = recipe_step.getAttribute('href')
1130 if not url:
1131 raise InvalidInterface(_("Missing href attribute on <archive>"))
1132 size = recipe_step.getAttribute('size')
1133 if not size:
1134 raise InvalidInterface(_("Missing size attribute on <archive>"))
1135 recipe.steps.append(DownloadSource(None, url = url, size = int(size),
1136 extract = recipe_step.getAttribute('extract'),
1137 start_offset = _get_long(recipe_step, 'start-offset'),
1138 type = recipe_step.getAttribute('type')))
1139 elif recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'rename':
1140 source = recipe_step.getAttribute('source')
1141 if not source:
1142 raise InvalidInterface(_("Missing source attribute on <rename>"))
1143 dest = recipe_step.getAttribute('dest')
1144 if not dest:
1145 raise InvalidInterface(_("Missing dest attribute on <rename>"))
1146 recipe.steps.append(RenameStep(source=source, dest=dest))
1147 else:
1148 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step.name)
1149 break
1150 else:
1151 impl.download_sources.append(recipe)
1153 root_attrs = {'stability': 'testing'}
1154 root_commands = {}
1155 if main:
1156 info("Note: @main on document element is deprecated in %s", self)
1157 root_commands['run'] = Command(qdom.Element(XMLNS_IFACE, 'command', {'path': main, 'name': 'run'}), None)
1158 process_group(feed_element, root_attrs, [], [], root_commands)
1160 def get_distro_feed(self):
1161 """Does this feed contain any <pacakge-implementation> elements?
1162 i.e. is it worth asking the package manager for more information?
1163 @return: the URL of the virtual feed, or None
1164 @since: 0.49"""
1165 if self._package_implementations:
1166 return "distribution:" + self.url
1167 return None
1169 def get_package_impls(self, distro):
1170 """Find the best <pacakge-implementation> element(s) for the given distribution.
1171 @param distro: the distribution to use to rate them
1172 @type distro: L{distro.Distribution}
1173 @return: a list of tuples for the best ranked elements
1174 @rtype: [str]
1175 @since: 0.49"""
1176 best_score = 0
1177 best_impls = []
1179 for item, item_attrs in self._package_implementations:
1180 distro_names = item_attrs.get('distributions', '')
1181 added_this = False
1182 for distro_name in distro_names.split(' '):
1183 score = distro.get_score(distro_name) if distro_name else 0.5
1184 if score > best_score:
1185 best_score = score
1186 best_impls = []
1187 if score == best_score and not added_this:
1188 best_impls.append((item, item_attrs))
1189 added_this = True
1190 return best_impls
1192 def get_name(self):
1193 return self.name or '(' + os.path.basename(self.url) + ')'
1195 def __repr__(self):
1196 return _("<Feed %s>") % self.url
1198 def set_stability_policy(self, new):
1199 assert new is None or isinstance(new, Stability)
1200 self.stability_policy = new
1202 def get_feed(self, url):
1203 for x in self.feeds:
1204 if x.uri == url:
1205 return x
1206 return None
1208 def add_metadata(self, elem):
1209 self.metadata.append(elem)
1211 def get_metadata(self, uri, name):
1212 """Return a list of interface metadata elements with this name and namespace URI."""
1213 return [m for m in self.metadata if m.name == name and m.uri == uri]
1215 @property
1216 def summary(self):
1217 return _best_language_match(self.summaries) or self.first_summary
1219 @property
1220 def description(self):
1221 return _best_language_match(self.descriptions) or self.first_description
1223 def get_replaced_by(self):
1224 """Return the URI of the interface that replaced the one with the URI of this feed's URL.
1225 This is the value of the feed's <replaced-by interface'...'/> element.
1226 @return: the new URI, or None if it hasn't been replaced
1227 @since: 1.7"""
1228 for child in self.metadata:
1229 if child.uri == XMLNS_IFACE and child.name == 'replaced-by':
1230 new_uri = child.getAttribute('interface')
1231 if new_uri and (new_uri.startswith('http:') or new_uri.startswith('https:') or self.local_path):
1232 return new_uri
1233 return None
1235 class DummyFeed(object):
1236 """Temporary class used during API transition."""
1237 last_modified = None
1238 name = '-'
1239 last_checked = property(lambda self: None)
1240 implementations = property(lambda self: {})
1241 feeds = property(lambda self: [])
1242 summary = property(lambda self: '-')
1243 description = property(lambda self: '')
1244 def get_name(self): return self.name
1245 def get_feed(self, url): return None
1246 def get_metadata(self, uri, name): return []
1247 _dummy_feed = DummyFeed()
1249 if sys.version_info[0] > 2:
1250 # Python 3
1251 from functools import total_ordering
1252 Stability = total_ordering(Stability)
1253 Implementation = total_ordering(Implementation)
1255 unicode = str
1256 basestring = str
1257 intern = sys.intern
1259 # These could be replaced by urllib.parse.quote, except that
1260 # it uses upper-case escapes and we use lower-case ones...
1261 def unescape(uri):
1262 """Convert each %20 to a space, etc.
1263 @rtype: str"""
1264 uri = uri.replace('#', '/')
1265 if '%' not in uri: return uri
1266 return re.sub(b'%[0-9a-fA-F][0-9a-fA-F]',
1267 lambda match: bytes([int(match.group(0)[1:], 16)]),
1268 uri.encode('ascii')).decode('utf-8')
1270 def escape(uri):
1271 """Convert each space to %20, etc
1272 @rtype: str"""
1273 return re.sub(b'[^-_.a-zA-Z0-9]',
1274 lambda match: ('%%%02x' % ord(match.group(0))).encode('ascii'),
1275 uri.encode('utf-8')).decode('ascii')
1277 def _pretty_escape(uri):
1278 """Convert each space to %20, etc
1279 : is preserved and / becomes #. This makes for nicer strings,
1280 and may replace L{escape} everywhere in future.
1281 @rtype: str"""
1282 if os.name == "posix":
1283 # Only preserve : on Posix systems
1284 preserveRegex = b'[^-_.a-zA-Z0-9:/]'
1285 else:
1286 # Other OSes may not allow the : character in file names
1287 preserveRegex = b'[^-_.a-zA-Z0-9/]'
1288 return re.sub(preserveRegex,
1289 lambda match: ('%%%02x' % ord(match.group(0))).encode('ascii'),
1290 uri.encode('utf-8')).decode('ascii').replace('/', '#')
1291 else:
1292 # Python 2
1293 unicode = unicode # (otherwise it can't be imported)
1294 basestring = basestring
1295 intern = intern
1297 def unescape(uri):
1298 """Convert each %20 to a space, etc.
1299 @rtype: str"""
1300 uri = uri.replace('#', '/')
1301 if '%' not in uri: return uri
1302 return re.sub('%[0-9a-fA-F][0-9a-fA-F]',
1303 lambda match: chr(int(match.group(0)[1:], 16)),
1304 uri).decode('utf-8')
1306 def escape(uri):
1307 """Convert each space to %20, etc
1308 @rtype: str"""
1309 return re.sub('[^-_.a-zA-Z0-9]',
1310 lambda match: '%%%02x' % ord(match.group(0)),
1311 uri.encode('utf-8'))
1313 def _pretty_escape(uri):
1314 """Convert each space to %20, etc
1315 : is preserved and / becomes #. This makes for nicer strings,
1316 and may replace L{escape} everywhere in future.
1317 @rtype: str"""
1318 if os.name == "posix":
1319 # Only preserve : on Posix systems
1320 preserveRegex = '[^-_.a-zA-Z0-9:/]'
1321 else:
1322 # Other OSes may not allow the : character in file names
1323 preserveRegex = '[^-_.a-zA-Z0-9/]'
1324 return re.sub(preserveRegex,
1325 lambda match: '%%%02x' % ord(match.group(0)),
1326 uri.encode('utf-8')).replace('/', '#')
1328 def canonical_iface_uri(uri):
1329 """If uri is a relative path, convert to an absolute one.
1330 A "file:///foo" URI is converted to "/foo".
1331 An "alias:prog" URI expands to the URI in the 0alias script
1332 Otherwise, return it unmodified.
1333 @rtype: str
1334 @raise SafeException: if uri isn't valid
1336 if uri.startswith('http://') or uri.startswith('https://'):
1337 if uri.count("/") < 3:
1338 raise SafeException(_("Missing / after hostname in URI '%s'") % uri)
1339 return uri
1340 elif uri.startswith('file:///'):
1341 path = uri[7:]
1342 elif uri.startswith('file:'):
1343 if uri[5] == '/':
1344 raise SafeException(_('Use file:///path for absolute paths, not {uri}').format(uri = uri))
1345 path = os.path.abspath(uri[5:])
1346 elif uri.startswith('alias:'):
1347 from zeroinstall import alias, support
1348 alias_prog = uri[6:]
1349 if not os.path.isabs(alias_prog):
1350 full_path = support.find_in_path(alias_prog)
1351 if not full_path:
1352 raise alias.NotAnAliasScript("Not found in $PATH: " + alias_prog)
1353 else:
1354 full_path = alias_prog
1355 return alias.parse_script(full_path).uri
1356 else:
1357 path = os.path.realpath(uri)
1359 if os.path.isfile(path):
1360 return path
1361 raise SafeException(_("Bad interface name '%(uri)s'.\n"
1362 "(doesn't start with 'http:', and "
1363 "doesn't exist as a local file '%(interface_uri)s' either)") %
1364 {'uri': uri, 'interface_uri': path})
1366 _version_mod_to_value = {
1367 'pre': -2,
1368 'rc': -1,
1369 '': 0,
1370 'post': 1,
1373 # Reverse mapping
1374 _version_value_to_mod = {}
1375 for x in _version_mod_to_value: _version_value_to_mod[_version_mod_to_value[x]] = x
1376 del x
1378 _version_re = re.compile('-([a-z]*)')
1380 def parse_version(version_string):
1381 """Convert a version string to an internal representation.
1382 The parsed format can be compared quickly using the standard Python functions.
1383 - Version := DottedList ("-" Mod DottedList?)*
1384 - DottedList := (Integer ("." Integer)*)
1385 @rtype: tuple (opaque)
1386 @raise SafeException: if the string isn't a valid version
1387 @since: 0.24 (moved from L{reader}, from where it is still available):"""
1388 if version_string is None: return None
1389 parts = _version_re.split(version_string)
1390 if parts[-1] == '':
1391 del parts[-1] # Ends with a modifier
1392 else:
1393 parts.append('')
1394 if not parts:
1395 raise SafeException(_("Empty version string!"))
1396 l = len(parts)
1397 try:
1398 for x in range(0, l, 2):
1399 part = parts[x]
1400 if part:
1401 parts[x] = list(map(int, parts[x].split('.')))
1402 else:
1403 parts[x] = [] # (because ''.split('.') == [''], not [])
1404 for x in range(1, l, 2):
1405 parts[x] = _version_mod_to_value[parts[x]]
1406 return parts
1407 except ValueError as ex:
1408 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1409 except KeyError as ex:
1410 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1412 def format_version(version):
1413 """Format a parsed version for display. Undoes the effect of L{parse_version}.
1414 @see: L{Implementation.get_version}
1415 @rtype: str
1416 @since: 0.24"""
1417 version = version[:]
1418 l = len(version)
1419 for x in range(0, l, 2):
1420 version[x] = '.'.join(map(str, version[x]))
1421 for x in range(1, l, 2):
1422 version[x] = '-' + _version_value_to_mod[version[x]]
1423 if version[-1] == '-': del version[-1]
1424 return ''.join(version)