Added RetrievalMethod.retrieve
[zeroinstall/zeroinstall-limyreth.git] / zeroinstall / injector / model.py
blob470af6ccb8cb68783d6d302ad6a6a73743158f36
1 """In-memory representation of interfaces and other data structures.
3 The objects in this module are used to build a representation of an XML interface
4 file in memory.
6 @see: L{reader} constructs these data-structures
7 @see: U{http://0install.net/interface-spec.html} description of the domain model
9 @var defaults: Default values for the 'default' attribute for <environment> bindings of
10 well-known variables.
11 """
13 # Copyright (C) 2009, Thomas Leonard
14 # See the README file for details, or visit http://0install.net.
16 from zeroinstall import _
17 import os, re, locale
18 from logging import info, debug, warn
19 from zeroinstall import SafeException, version
20 from zeroinstall.injector.namespaces import XMLNS_IFACE
21 from zeroinstall.injector import qdom
22 from zeroinstall.zerostore import unpack
23 from zeroinstall.support import tasks
25 # Element names for bindings in feed files
26 binding_names = frozenset(['environment', 'overlay'])
28 network_offline = 'off-line'
29 network_minimal = 'minimal'
30 network_full = 'full'
31 network_levels = (network_offline, network_minimal, network_full)
33 stability_levels = {} # Name -> Stability
35 defaults = {
36 'PATH': '/bin:/usr/bin',
37 'XDG_CONFIG_DIRS': '/etc/xdg',
38 'XDG_DATA_DIRS': '/usr/local/share:/usr/share',
41 class InvalidInterface(SafeException):
42 """Raised when parsing an invalid feed."""
43 feed_url = None
45 def __init__(self, message, ex = None):
46 if ex:
47 try:
48 message += "\n\n(exact error: %s)" % ex
49 except:
50 # Some Python messages have type str but contain UTF-8 sequences.
51 # (e.g. IOException). Adding these to a Unicode 'message' (e.g.
52 # after gettext translation) will cause an error.
53 import codecs
54 decoder = codecs.lookup('utf-8')
55 decex = decoder.decode(str(ex), errors = 'replace')[0]
56 message += "\n\n(exact error: %s)" % decex
58 SafeException.__init__(self, message)
60 def __unicode__(self):
61 if hasattr(SafeException, '__unicode__'):
62 # Python >= 2.6
63 if self.feed_url:
64 return _('%s [%s]') % (SafeException.__unicode__(self), self.feed_url)
65 return SafeException.__unicode__(self)
66 else:
67 return unicode(SafeException.__str__(self))
69 def _split_arch(arch):
70 """Split an arch into an (os, machine) tuple. Either or both parts may be None."""
71 if not arch:
72 return None, None
73 elif '-' not in arch:
74 raise SafeException(_("Malformed arch '%s'") % arch)
75 else:
76 osys, machine = arch.split('-', 1)
77 if osys == '*': osys = None
78 if machine == '*': machine = None
79 return osys, machine
81 def _join_arch(osys, machine):
82 if osys == machine == None: return None
83 return "%s-%s" % (osys or '*', machine or '*')
85 def _best_language_match(options):
86 (language, encoding) = locale.getlocale()
88 if language:
89 # xml:lang uses '-', while LANG uses '_'
90 language = language.replace('_', '-')
91 else:
92 language = 'en-US'
94 return (options.get(language, None) or # Exact match (language+region)
95 options.get(language.split('-', 1)[0], None) or # Matching language
96 options.get('en', None)) # English
98 class Stability(object):
99 """A stability rating. Each implementation has an upstream stability rating and,
100 optionally, a user-set rating."""
101 __slots__ = ['level', 'name', 'description']
102 def __init__(self, level, name, description):
103 self.level = level
104 self.name = name
105 self.description = description
106 assert name not in stability_levels
107 stability_levels[name] = self
109 def __cmp__(self, other):
110 return cmp(self.level, other.level)
112 def __str__(self):
113 return self.name
115 def __repr__(self):
116 return _("<Stability: %s>") % self.description
118 def process_binding(e):
119 """Internal"""
120 if e.name == 'environment':
121 mode = {
122 None: EnvironmentBinding.PREPEND,
123 'prepend': EnvironmentBinding.PREPEND,
124 'append': EnvironmentBinding.APPEND,
125 'replace': EnvironmentBinding.REPLACE,
126 }[e.getAttribute('mode')]
128 binding = EnvironmentBinding(e.getAttribute('name'),
129 insert = e.getAttribute('insert'),
130 default = e.getAttribute('default'),
131 value = e.getAttribute('value'),
132 mode = mode,
133 separator = e.getAttribute('separator'))
134 if not binding.name: raise InvalidInterface(_("Missing 'name' in binding"))
135 if binding.insert is None and binding.value is None:
136 raise InvalidInterface(_("Missing 'insert' or 'value' in binding"))
137 if binding.insert is not None and binding.value is not None:
138 raise InvalidInterface(_("Binding contains both 'insert' and 'value'"))
139 return binding
140 elif e.name == 'overlay':
141 return OverlayBinding(e.getAttribute('src'), e.getAttribute('mount-point'))
142 else:
143 raise Exception(_("Unknown binding type '%s'") % e.name)
145 def process_depends(item, local_feed_dir):
146 """Internal"""
147 # Note: also called from selections
148 attrs = item.attrs
149 dep_iface = item.getAttribute('interface')
150 if not dep_iface:
151 raise InvalidInterface(_("Missing 'interface' on <%s>") % item.name)
152 if dep_iface.startswith('./'):
153 if local_feed_dir:
154 dep_iface = os.path.abspath(os.path.join(local_feed_dir, dep_iface))
155 # (updates the element too, in case we write it out again)
156 attrs['interface'] = dep_iface
157 else:
158 raise InvalidInterface(_('Relative interface URI "%s" in non-local feed') % dep_iface)
159 dependency = InterfaceDependency(dep_iface, element = item)
161 for e in item.childNodes:
162 if e.uri != XMLNS_IFACE: continue
163 if e.name in binding_names:
164 dependency.bindings.append(process_binding(e))
165 elif e.name == 'version':
166 dependency.restrictions.append(
167 VersionRangeRestriction(not_before = parse_version(e.getAttribute('not-before')),
168 before = parse_version(e.getAttribute('before'))))
169 return dependency
171 def N_(message): return message
173 insecure = Stability(0, N_('insecure'), _('This is a security risk'))
174 buggy = Stability(5, N_('buggy'), _('Known to have serious bugs'))
175 developer = Stability(10, N_('developer'), _('Work-in-progress - bugs likely'))
176 testing = Stability(20, N_('testing'), _('Stability unknown - please test!'))
177 stable = Stability(30, N_('stable'), _('Tested - no serious problems found'))
178 packaged = Stability(35, N_('packaged'), _('Supplied by the local package manager'))
179 preferred = Stability(40, N_('preferred'), _('Best of all - must be set manually'))
181 del N_
183 class Restriction(object):
184 """A Restriction limits the allowed implementations of an Interface."""
185 __slots__ = []
187 def meets_restriction(self, impl):
188 """Called by the L{solver.Solver} to check whether a particular implementation is acceptable.
189 @return: False if this implementation is not a possibility
190 @rtype: bool
192 raise NotImplementedError(_("Abstract"))
194 class VersionRestriction(Restriction):
195 """Only select implementations with a particular version number.
196 @since: 0.40"""
198 def __init__(self, version):
199 """@param version: the required version number
200 @see: L{parse_version}; use this to pre-process the version number
202 self.version = version
204 def meets_restriction(self, impl):
205 return impl.version == self.version
207 def __str__(self):
208 return _("(restriction: version = %s)") % format_version(self.version)
210 class VersionRangeRestriction(Restriction):
211 """Only versions within the given range are acceptable"""
212 __slots__ = ['before', 'not_before']
214 def __init__(self, before, not_before):
215 """@param before: chosen versions must be earlier than this
216 @param not_before: versions must be at least this high
217 @see: L{parse_version}; use this to pre-process the versions
219 self.before = before
220 self.not_before = not_before
222 def meets_restriction(self, impl):
223 if self.not_before and impl.version < self.not_before:
224 return False
225 if self.before and impl.version >= self.before:
226 return False
227 return True
229 def __str__(self):
230 if self.not_before is not None or self.before is not None:
231 range = ''
232 if self.not_before is not None:
233 range += format_version(self.not_before) + ' <= '
234 range += 'version'
235 if self.before is not None:
236 range += ' < ' + format_version(self.before)
237 else:
238 range = 'none'
239 return _("(restriction: %s)") % range
241 class Binding(object):
242 """Information about how the choice of a Dependency is made known
243 to the application being run."""
245 class EnvironmentBinding(Binding):
246 """Indicate the chosen implementation using an environment variable."""
247 __slots__ = ['name', 'insert', 'default', 'mode', 'value']
249 PREPEND = 'prepend'
250 APPEND = 'append'
251 REPLACE = 'replace'
253 def __init__(self, name, insert, default = None, mode = PREPEND,
254 value=None, separator=None):
256 mode argument added in version 0.28
257 value argument added in version 0.52
259 self.name = name
260 self.insert = insert
261 self.default = default
262 self.mode = mode
263 self.value = value
264 if separator is None:
265 self.separator = os.pathsep
266 else:
267 self.separator = separator
270 def __str__(self):
271 return _("<environ %(name)s %(mode)s %(insert)s %(value)s>") % {'name': self.name,'mode': self.mode, 'insert': self.insert, 'value': self.value}
273 __repr__ = __str__
275 def get_value(self, path, old_value):
276 """Calculate the new value of the environment variable after applying this binding.
277 @param path: the path to the selected implementation
278 @param old_value: the current value of the environment variable
279 @return: the new value for the environment variable"""
281 if self.insert is not None:
282 extra = os.path.join(path, self.insert)
283 else:
284 assert self.value is not None
285 extra = self.value
287 if self.mode == EnvironmentBinding.REPLACE:
288 return extra
290 if old_value is None:
291 old_value = self.default or defaults.get(self.name, None)
292 if old_value is None:
293 return extra
294 if self.mode == EnvironmentBinding.PREPEND:
295 return extra + self.separator + old_value
296 else:
297 return old_value + self.separator + extra
299 def _toxml(self, doc):
300 """Create a DOM element for this binding.
301 @param doc: document to use to create the element
302 @return: the new element
304 env_elem = doc.createElementNS(XMLNS_IFACE, 'environment')
305 env_elem.setAttributeNS(None, 'name', self.name)
306 if self.insert is not None:
307 env_elem.setAttributeNS(None, 'insert', self.insert)
308 else:
309 env_elem.setAttributeNS(None, 'value', self.value)
310 if self.default:
311 env_elem.setAttributeNS(None, 'default', self.default)
312 return env_elem
314 class OverlayBinding(Binding):
315 """Make the chosen implementation available by overlaying it onto another part of the file-system.
316 This is to support legacy programs which use hard-coded paths."""
317 __slots__ = ['src', 'mount_point']
319 def __init__(self, src, mount_point):
320 self.src = src
321 self.mount_point = mount_point
323 def __str__(self):
324 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self.src or '.', 'mount_point': self.mount_point or '/'}
326 __repr__ = __str__
328 def _toxml(self, doc):
329 """Create a DOM element for this binding.
330 @param doc: document to use to create the element
331 @return: the new element
333 env_elem = doc.createElementNS(XMLNS_IFACE, 'overlay')
334 if self.src is not None:
335 env_elem.setAttributeNS(None, 'src', self.src)
336 if self.mount_point is not None:
337 env_elem.setAttributeNS(None, 'mount-point', self.mount_point)
338 return env_elem
340 class Feed(object):
341 """An interface's feeds are other interfaces whose implementations can also be
342 used as implementations of this interface."""
343 __slots__ = ['uri', 'os', 'machine', 'user_override', 'langs']
344 def __init__(self, uri, arch, user_override, langs = None):
345 self.uri = uri
346 # This indicates whether the feed comes from the user's overrides
347 # file. If true, writer.py will write it when saving.
348 self.user_override = user_override
349 self.os, self.machine = _split_arch(arch)
350 self.langs = langs
352 def __str__(self):
353 return "<Feed from %s>" % self.uri
354 __repr__ = __str__
356 arch = property(lambda self: _join_arch(self.os, self.machine))
358 class Dependency(object):
359 """A Dependency indicates that an Implementation requires some additional
360 code to function. This is an abstract base class.
361 @ivar qdom: the XML element for this Dependency (since 0launch 0.51)
362 @type qdom: L{qdom.Element}
363 @ivar metadata: any extra attributes from the XML element
364 @type metadata: {str: str}
366 __slots__ = ['qdom']
368 def __init__(self, element):
369 assert isinstance(element, qdom.Element), type(element) # Use InterfaceDependency instead!
370 self.qdom = element
372 @property
373 def metadata(self):
374 return self.qdom.attrs
376 class InterfaceDependency(Dependency):
377 """A Dependency on a Zero Install interface.
378 @ivar interface: the interface required by this dependency
379 @type interface: str
380 @ivar restrictions: a list of constraints on acceptable implementations
381 @type restrictions: [L{Restriction}]
382 @ivar bindings: how to make the choice of implementation known
383 @type bindings: [L{Binding}]
384 @since: 0.28
386 __slots__ = ['interface', 'restrictions', 'bindings']
388 def __init__(self, interface, restrictions = None, element = None):
389 Dependency.__init__(self, element)
390 assert isinstance(interface, (str, unicode))
391 assert interface
392 self.interface = interface
393 if restrictions is None:
394 self.restrictions = []
395 else:
396 self.restrictions = restrictions
397 self.bindings = []
399 def __str__(self):
400 return _("<Dependency on %(interface)s; bindings: %(bindings)s%(restrictions)s>") % {'interface': self.interface, 'bindings': self.bindings, 'restrictions': self.restrictions}
402 class RetrievalMethod(object):
403 """A RetrievalMethod provides a way to fetch an implementation."""
404 __slots__ = []
406 @tasks.async
407 def retrieve(self, fetcher, required_digest, stores, force = False, impl_hint = None):
408 """Retrieve implementation using method
409 @param impl_hint: the Implementation this is for (if any) as a hint for the GUI
411 raise NotImplementedError("abstract")
413 class DownloadSource(RetrievalMethod):
414 """A DownloadSource provides a way to fetch an implementation."""
415 __slots__ = ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
417 def __init__(self, implementation, url, size, extract, start_offset = 0, type = None):
418 self.implementation = implementation
419 self.url = url
420 self.size = size
421 self.extract = extract
422 self.start_offset = start_offset
423 self.type = type # MIME type - see unpack.py
425 def prepare(self, fetcher, force, impl_hint):
427 class StepCommand(object):
428 __slots__ = ['blocker', '_stream']
430 def __init__(s):
431 s.blocker, s._stream = fetcher.download_archive(self, force = force, impl_hint = impl_hint)
433 def run(s, tmpdir):
434 s._stream.seek(0)
435 unpack.unpack_archive_over(self.url, s._stream, tmpdir,
436 extract = self.extract,
437 type = self.type,
438 start_offset = self.start_offset or 0)
439 return StepCommand()
441 def download(self, fetcher, force = False, impl_hint = None):
442 """Fetch an archive. You should normally call L{Implementation.retrieve}
443 instead, since it handles other kinds of retrieval method too."""
444 url = self.url
445 if not (url.startswith('http:') or url.startswith('https:') or url.startswith('ftp:')):
446 raise SafeException(_("Unknown scheme in download URL '%s'") % url)
448 mime_type = self.type
449 if not mime_type:
450 mime_type = unpack.type_from_url(self.url)
451 if not mime_type:
452 raise SafeException(_("No 'type' attribute on archive, and I can't guess from the name (%s)") % self.url)
453 unpack.check_type_ok(mime_type)
454 dl = fetcher.handler.get_download(self.url, force = force, hint = impl_hint)
455 dl.expected_size = self.size + (self.start_offset or 0)
456 return (dl.downloaded, dl.tempfile)
458 @tasks.async
459 def retrieve(self, fetcher, required_digest, stores, force = False, impl_hint = None):
460 blocker, stream = self.download(fetcher, force = force, impl_hint = impl_hint)
461 yield blocker
462 tasks.check(blocker)
464 stream.seek(0)
465 stores.add_archive_to_cache(required_digest, stream, self.url, self.extract,
466 type = self.type, start_offset = self.start_offset or 0)
469 class UnpackArchive(object):
470 """An UnpackArchive step provides unpacks/extracts an archive.
472 It can be used inside a Recipe."""
473 __slots__ = ['path', 'extract', 'type']
475 def __init__(self, path, extract, type):
476 self.path = path
477 self.extract = extract
478 self.type = type
480 def prepare(self, fetcher, force, impl_hint):
482 class StepCommand(object):
483 __slots__ = ['blocker']
485 def __init__(s):
486 s.blocker = None
488 def run(s, tmpdir):
489 path = os.path.join(tmpdir, self.path)
490 stream = open(path, 'rb')
491 stream.seek(0)
493 unpack.unpack_archive_over(path, stream, tmpdir,
494 extract = self.extract,
495 type = self.type,
496 start_offset = 0)
498 os.unlink(path)
500 return StepCommand()
502 class Recipe(RetrievalMethod):
503 """Get an implementation by following a series of steps.
504 @ivar size: the combined download sizes from all the steps
505 @type size: int
506 @ivar steps: the sequence of steps which must be performed
507 @type steps: [L{RetrievalMethod}]"""
508 __slots__ = ['steps']
510 def __init__(self):
511 self.steps = []
513 size = property(lambda self: sum([x.size for x in self.steps]))
515 @tasks.async
516 def retrieve(self, fetcher, required_digest, stores, force = False, impl_hint = None):
517 # Start preparing all steps
518 step_commands = [step.prepare(fetcher, force, impl_hint) for step in self.steps]
520 # Create an empty directory for the new implementation
521 store = stores.stores[0]
522 tmpdir = store.get_tmp_dir_for(required_digest)
524 try:
525 # Run steps
526 valid_blockers = [s.blocker for s in step_commands if s.blocker is not None]
527 for step_command in step_commands:
528 if step_command.blocker:
529 while not step_command.blocker.happened:
530 yield valid_blockers
531 tasks.check(valid_blockers)
532 step_command.run(tmpdir)
534 # Check that the result is correct and store it in the cache
535 store.check_manifest_and_rename(required_digest, tmpdir)
536 tmpdir = None
537 finally:
538 # If unpacking fails, remove the temporary directory
539 if tmpdir is not None:
540 from zeroinstall import support
541 support.ro_rmtree(tmpdir)
545 class DistributionSource(RetrievalMethod):
546 """A package that is installed using the distribution's tools (including PackageKit).
547 @ivar install: a function to call to install this package
548 @type install: (L{handler.Handler}) -> L{tasks.Blocker}
549 @ivar package_id: the package name, in a form recognised by the distribution's tools
550 @type package_id: str
551 @ivar size: the download size in bytes
552 @type size: int
553 @ivar needs_confirmation: whether the user should be asked to confirm before calling install()
554 @type needs_confirmation: bool"""
556 __slots__ = ['package_id', 'size', 'install', 'needs_confirmation']
558 def __init__(self, package_id, size, install, needs_confirmation = True):
559 RetrievalMethod.__init__(self)
560 self.package_id = package_id
561 self.size = size
562 self.install = install
563 self.needs_confirmation = needs_confirmation
565 class Command(object):
566 """A Command is a way of running an Implementation as a program."""
568 __slots__ = ['qdom', '_depends', '_local_dir', '_runner']
570 def __init__(self, qdom, local_dir):
571 """@param qdom: the <command> element
572 @param local_dir: the directory containing the feed (for relative dependencies), or None if not local
574 assert qdom.name == 'command', 'not <command>: %s' % qdom
575 self.qdom = qdom
576 self._local_dir = local_dir
577 self._depends = None
579 path = property(lambda self: self.qdom.attrs.get("path", None))
581 def _toxml(self, doc, prefixes):
582 return self.qdom.toDOM(doc, prefixes)
584 @property
585 def requires(self):
586 if self._depends is None:
587 self._runner = None
588 depends = []
589 for child in self.qdom.childNodes:
590 if child.name == 'requires':
591 dep = process_depends(child, self._local_dir)
592 depends.append(dep)
593 elif child.name == 'runner':
594 if self._runner:
595 raise InvalidInterface(_("Multiple <runner>s in <command>!"))
596 dep = process_depends(child, self._local_dir)
597 depends.append(dep)
598 self._runner = dep
599 self._depends = depends
600 return self._depends
602 def get_runner(self):
603 self.requires # (sets _runner)
604 return self._runner
606 class Implementation(object):
607 """An Implementation is a package which implements an Interface.
608 @ivar download_sources: list of methods of getting this implementation
609 @type download_sources: [L{RetrievalMethod}]
610 @ivar feed: the feed owning this implementation (since 0.32)
611 @type feed: [L{ZeroInstallFeed}]
612 @ivar bindings: how to tell this component where it itself is located (since 0.31)
613 @type bindings: [Binding]
614 @ivar upstream_stability: the stability reported by the packager
615 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged]
616 @ivar user_stability: the stability as set by the user
617 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred]
618 @ivar langs: natural languages supported by this package
619 @type langs: str
620 @ivar requires: interfaces this package depends on
621 @type requires: [L{Dependency}]
622 @ivar commands: ways to execute as a program
623 @type commands: {str: Command}
624 @ivar metadata: extra metadata from the feed
625 @type metadata: {"[URI ]localName": str}
626 @ivar id: a unique identifier for this Implementation
627 @ivar version: a parsed version number
628 @ivar released: release date
629 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path)
630 @type local_path: str | None
631 @ivar requires_root_install: whether the user will need admin rights to use this
632 @type requires_root_install: bool
635 # Note: user_stability shouldn't really be here
637 __slots__ = ['upstream_stability', 'user_stability', 'langs',
638 'requires', 'metadata', 'download_sources', 'commands',
639 'id', 'feed', 'version', 'released', 'bindings', 'machine']
641 def __init__(self, feed, id):
642 assert id
643 self.feed = feed
644 self.id = id
645 self.user_stability = None
646 self.upstream_stability = None
647 self.metadata = {} # [URI + " "] + localName -> value
648 self.requires = []
649 self.version = None
650 self.released = None
651 self.download_sources = []
652 self.langs = ""
653 self.machine = None
654 self.bindings = []
655 self.commands = {}
657 def get_stability(self):
658 return self.user_stability or self.upstream_stability or testing
660 def __str__(self):
661 return self.id
663 def __repr__(self):
664 return "v%s (%s)" % (self.get_version(), self.id)
666 def __cmp__(self, other):
667 """Newer versions come first"""
668 d = cmp(other.version, self.version)
669 if d: return d
670 # If the version number is the same, just give a stable sort order, and
671 # ensure that two different implementations don't compare equal.
672 d = cmp(other.feed.url, self.feed.url)
673 if d: return d
674 return cmp(other.id, self.id)
676 def get_version(self):
677 """Return the version as a string.
678 @see: L{format_version}
680 return format_version(self.version)
682 arch = property(lambda self: _join_arch(self.os, self.machine))
684 os = None
685 local_path = None
686 digests = None
687 requires_root_install = False
689 def _get_main(self):
690 """"@deprecated: use commands["run"] instead"""
691 main = self.commands.get("run", None)
692 if main is not None:
693 return main.path
694 return None
695 def _set_main(self, path):
696 """"@deprecated: use commands["run"] instead"""
697 if path is None:
698 if "run" in self.commands:
699 del self.commands["run"]
700 else:
701 self.commands["run"] = Command(qdom.Element(XMLNS_IFACE, 'command', {'path': path}), None)
702 main = property(_get_main, _set_main)
704 def is_available(self, stores):
705 """Is this Implementation available locally?
706 (a local implementation, an installed distribution package, or a cached ZeroInstallImplementation)
707 @rtype: bool
708 @since: 0.53
710 raise NotImplementedError("abstract")
712 @property
713 def best_download_source(self):
714 """Return the best download source for this implementation.
715 @rtype: L{model.RetrievalMethod}"""
716 if self.download_sources:
717 return self.download_sources[0]
718 return None
720 def retrieve(self, fetcher, retrieval_method, stores, force = False):
721 """Retrieve an implementation.
722 @param retrieval_method: a way of getting the implementation (e.g. an Archive or a Recipe)
723 @type retrieval_method: L{model.RetrievalMethod}
724 @param stores: where to store the downloaded implementation
725 @type stores: L{zerostore.Stores}
726 @param force: whether to abort and restart an existing download
727 @rtype: L{tasks.Blocker}"""
728 raise NotImplementedError("abstract")
730 class DistributionImplementation(Implementation):
731 """An implementation provided by the distribution. Information such as the version
732 comes from the package manager.
733 @since: 0.28"""
734 __slots__ = ['distro', 'installed']
736 def __init__(self, feed, id, distro):
737 assert id.startswith('package:')
738 Implementation.__init__(self, feed, id)
739 self.distro = distro
740 self.installed = False
742 @property
743 def requires_root_install(self):
744 return not self.installed
746 def is_available(self, stores):
747 return self.installed
749 def retrieve(self, fetcher, retrieval_method, stores, force = False):
750 return retrieval_method.install(fetcher.handler)
753 class ZeroInstallImplementation(Implementation):
754 """An implementation where all the information comes from Zero Install.
755 @ivar digests: a list of "algorith=value" strings (since 0.45)
756 @type digests: [str]
757 @since: 0.28"""
758 __slots__ = ['os', 'size', 'digests', 'local_path']
760 def __init__(self, feed, id, local_path):
761 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
762 assert not id.startswith('package:'), id
763 Implementation.__init__(self, feed, id)
764 self.size = None
765 self.os = None
766 self.digests = []
767 self.local_path = local_path
769 # Deprecated
770 dependencies = property(lambda self: dict([(x.interface, x) for x in self.requires
771 if isinstance(x, InterfaceDependency)]))
773 def add_download_source(self, url, size, extract, start_offset = 0, type = None):
774 """Add a download source."""
775 self.download_sources.append(DownloadSource(self, url, size, extract, start_offset, type))
777 def set_arch(self, arch):
778 self.os, self.machine = _split_arch(arch)
779 arch = property(lambda self: _join_arch(self.os, self.machine), set_arch)
781 def is_available(self, stores):
782 if self.local_path is not None:
783 return os.path.exists(self.local_path)
784 if self.digests:
785 path = stores.lookup_maybe(self.digests)
786 return path is not None
787 return False # (0compile creates fake entries with no digests)
789 @property
790 def best_digest(self):
791 """Return the best digest for this implementation
792 @return: tuple (alg, digest) or None"""
793 from zeroinstall.zerostore import manifest
794 best_alg = None
795 for digest in self.digests:
796 alg_name = digest.split('=', 1)[0]
797 alg = manifest.algorithms.get(alg_name, None)
798 if alg and (best_alg is None or best_alg.rating < alg.rating):
799 best_alg = alg
800 best_digest = digest
801 if best_alg:
802 return (best_alg, best_digest)
803 else:
804 return None
806 def retrieve(self, fetcher, retrieval_method, stores, force = False):
807 best = self.best_digest
809 if best is None:
810 if not self.digests:
811 raise SafeException(_("No <manifest-digest> given for '%(implementation)s' version %(version)s") %
812 {'implementation': self.feed.get_name(), 'version': self.get_version()})
813 raise SafeException(_("Unknown digest algorithms '%(algorithms)s' for '%(implementation)s' version %(version)s") %
814 {'algorithms': self.digests, 'implementation': self.feed.get_name(), 'version': self.get_version()})
815 else:
816 alg, required_digest = best
818 @tasks.async
819 def retrieve():
820 blocker = retrieval_method.retrieve(fetcher, required_digest, stores, force, impl_hint = self)
821 yield blocker
822 tasks.check(blocker)
823 fetcher.handler.impl_added_to_store(self)
824 return retrieve()
827 class Interface(object):
828 """An Interface represents some contract of behaviour.
829 @ivar uri: the URI for this interface.
830 @ivar stability_policy: user's configured policy.
831 Implementations at this level or higher are preferred.
832 Lower levels are used only if there is no other choice.
834 __slots__ = ['uri', 'stability_policy', 'extra_feeds']
836 implementations = property(lambda self: self._main_feed.implementations)
837 name = property(lambda self: self._main_feed.name)
838 description = property(lambda self: self._main_feed.description)
839 summary = property(lambda self: self._main_feed.summary)
840 last_modified = property(lambda self: self._main_feed.last_modified)
841 feeds = property(lambda self: self.extra_feeds + self._main_feed.feeds)
842 metadata = property(lambda self: self._main_feed.metadata)
844 last_checked = property(lambda self: self._main_feed.last_checked)
846 def __init__(self, uri):
847 assert uri
848 if uri.startswith('http:') or uri.startswith('https:') or os.path.isabs(uri):
849 self.uri = uri
850 else:
851 raise SafeException(_("Interface name '%s' doesn't start "
852 "with 'http:' or 'https:'") % uri)
853 self.reset()
855 def _get_feed_for(self):
856 retval = {}
857 for key in self._main_feed.feed_for:
858 retval[key] = True
859 return retval
860 feed_for = property(_get_feed_for) # Deprecated (used by 0publish)
862 def reset(self):
863 self.extra_feeds = []
864 self.stability_policy = None
866 def get_name(self):
867 from zeroinstall.injector.iface_cache import iface_cache
868 feed = iface_cache.get_feed(self.uri)
869 if feed:
870 return feed.get_name()
871 return '(' + os.path.basename(self.uri) + ')'
873 def __repr__(self):
874 return _("<Interface %s>") % self.uri
876 def set_stability_policy(self, new):
877 assert new is None or isinstance(new, Stability)
878 self.stability_policy = new
880 def get_feed(self, url):
881 #import warnings
882 #warnings.warn("use iface_cache.get_feed instead", DeprecationWarning, 2)
883 for x in self.extra_feeds:
884 if x.uri == url:
885 return x
886 #return self._main_feed.get_feed(url)
887 return None
889 def get_metadata(self, uri, name):
890 return self._main_feed.get_metadata(uri, name)
892 @property
893 def _main_feed(self):
894 #import warnings
895 #warnings.warn("use the feed instead", DeprecationWarning, 3)
896 from zeroinstall.injector import policy
897 iface_cache = policy.get_deprecated_singleton_config().iface_cache
898 feed = iface_cache.get_feed(self.uri)
899 if feed is None:
900 return _dummy_feed
901 return feed
903 def _merge_attrs(attrs, item):
904 """Add each attribute of item to a copy of attrs and return the copy.
905 @type attrs: {str: str}
906 @type item: L{qdom.Element}
907 @rtype: {str: str}
909 new = attrs.copy()
910 for a in item.attrs:
911 new[str(a)] = item.attrs[a]
912 return new
914 def _get_long(elem, attr_name):
915 val = elem.getAttribute(attr_name)
916 if val is not None:
917 try:
918 val = int(val)
919 except ValueError:
920 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name, 'value': val})
921 return val
923 class ZeroInstallFeed(object):
924 """A feed lists available implementations of an interface.
925 @ivar url: the URL for this feed
926 @ivar implementations: Implementations in this feed, indexed by ID
927 @type implementations: {str: L{Implementation}}
928 @ivar name: human-friendly name
929 @ivar summaries: short textual description (in various languages, since 0.49)
930 @type summaries: {str: str}
931 @ivar descriptions: long textual description (in various languages, since 0.49)
932 @type descriptions: {str: str}
933 @ivar last_modified: timestamp on signature
934 @ivar last_checked: time feed was last successfully downloaded and updated
935 @ivar feeds: list of <feed> elements in this feed
936 @type feeds: [L{Feed}]
937 @ivar feed_for: interfaces for which this could be a feed
938 @type feed_for: set(str)
939 @ivar metadata: extra elements we didn't understand
941 # _main is deprecated
942 __slots__ = ['url', 'implementations', 'name', 'descriptions', 'first_description', 'summaries', 'first_summary', '_package_implementations',
943 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
945 def __init__(self, feed_element, local_path = None, distro = None):
946 """Create a feed object from a DOM.
947 @param feed_element: the root element of a feed file
948 @type feed_element: L{qdom.Element}
949 @param local_path: the pathname of this local feed, or None for remote feeds"""
950 self.implementations = {}
951 self.name = None
952 self.summaries = {} # { lang: str }
953 self.first_summary = None
954 self.descriptions = {} # { lang: str }
955 self.first_description = None
956 self.last_modified = None
957 self.feeds = []
958 self.feed_for = set()
959 self.metadata = []
960 self.last_checked = None
961 self._package_implementations = []
963 if distro is not None:
964 import warnings
965 warnings.warn("distro argument is now ignored", DeprecationWarning, 2)
967 if feed_element is None:
968 return # XXX subclass?
970 assert feed_element.name in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
971 assert feed_element.uri == XMLNS_IFACE, "Wrong namespace on root element: %s" % feed_element.uri
973 main = feed_element.getAttribute('main')
974 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
976 if local_path:
977 self.url = local_path
978 local_dir = os.path.dirname(local_path)
979 else:
980 self.url = feed_element.getAttribute('uri')
981 if not self.url:
982 raise InvalidInterface(_("<interface> uri attribute missing"))
983 local_dir = None # Can't have relative paths
985 min_injector_version = feed_element.getAttribute('min-injector-version')
986 if min_injector_version:
987 if parse_version(min_injector_version) > parse_version(version):
988 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
989 "Zero Install, but I am only version %(version)s. "
990 "You can get a newer version from http://0install.net") %
991 {'min_version': min_injector_version, 'version': version})
993 for x in feed_element.childNodes:
994 if x.uri != XMLNS_IFACE:
995 self.metadata.append(x)
996 continue
997 if x.name == 'name':
998 self.name = x.content
999 elif x.name == 'description':
1000 if self.first_description == None:
1001 self.first_description = x.content
1002 self.descriptions[x.attrs.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x.content
1003 elif x.name == 'summary':
1004 if self.first_summary == None:
1005 self.first_summary = x.content
1006 self.summaries[x.attrs.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x.content
1007 elif x.name == 'feed-for':
1008 feed_iface = x.getAttribute('interface')
1009 if not feed_iface:
1010 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
1011 self.feed_for.add(feed_iface)
1012 # Bug report from a Debian/stable user that --feed gets the wrong value.
1013 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
1014 # in case it happens again.
1015 debug(_("Is feed-for %s"), feed_iface)
1016 elif x.name == 'feed':
1017 feed_src = x.getAttribute('src')
1018 if not feed_src:
1019 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
1020 if feed_src.startswith('http:') or feed_src.startswith('https:') or local_path:
1021 langs = x.getAttribute('langs')
1022 if langs: langs = langs.replace('_', '-')
1023 self.feeds.append(Feed(feed_src, x.getAttribute('arch'), False, langs = langs))
1024 else:
1025 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src)
1026 else:
1027 self.metadata.append(x)
1029 if not self.name:
1030 raise InvalidInterface(_("Missing <name> in feed"))
1031 if not self.summary:
1032 raise InvalidInterface(_("Missing <summary> in feed"))
1034 def process_group(group, group_attrs, base_depends, base_bindings, base_commands):
1035 for item in group.childNodes:
1036 if item.uri != XMLNS_IFACE: continue
1038 if item.name not in ('group', 'implementation', 'package-implementation'):
1039 continue
1041 # We've found a group or implementation. Scan for dependencies,
1042 # bindings and commands. Doing this here means that:
1043 # - We can share the code for groups and implementations here.
1044 # - The order doesn't matter, because these get processed first.
1045 # A side-effect is that the document root cannot contain
1046 # these.
1048 depends = base_depends[:]
1049 bindings = base_bindings[:]
1050 commands = base_commands.copy()
1052 for attr, command in [('main', 'run'),
1053 ('self-test', 'test')]:
1054 value = item.attrs.get(attr, None)
1055 if value is not None:
1056 commands[command] = Command(qdom.Element(XMLNS_IFACE, 'command', {'path': value}), None)
1058 for child in item.childNodes:
1059 if child.uri != XMLNS_IFACE: continue
1060 if child.name == 'requires':
1061 dep = process_depends(child, local_dir)
1062 depends.append(dep)
1063 elif child.name == 'command':
1064 command_name = child.attrs.get('name', None)
1065 if not command_name:
1066 raise InvalidInterface('Missing name for <command>')
1067 commands[command_name] = Command(child, local_dir)
1068 elif child.name in binding_names:
1069 bindings.append(process_binding(child))
1071 compile_command = item.attrs.get('http://zero-install.sourceforge.net/2006/namespaces/0compile command')
1072 if compile_command is not None:
1073 commands['compile'] = Command(qdom.Element(XMLNS_IFACE, 'command', {'shell-command': compile_command}), None)
1075 item_attrs = _merge_attrs(group_attrs, item)
1077 if item.name == 'group':
1078 process_group(item, item_attrs, depends, bindings, commands)
1079 elif item.name == 'implementation':
1080 process_impl(item, item_attrs, depends, bindings, commands)
1081 elif item.name == 'package-implementation':
1082 if depends:
1083 warn("A <package-implementation> with dependencies in %s!", self.url)
1084 self._package_implementations.append((item, item_attrs))
1085 else:
1086 assert 0
1088 def process_impl(item, item_attrs, depends, bindings, commands):
1089 id = item.getAttribute('id')
1090 if id is None:
1091 raise InvalidInterface(_("Missing 'id' attribute on %s") % item)
1092 local_path = item_attrs.get('local-path')
1093 if local_dir and local_path:
1094 abs_local_path = os.path.abspath(os.path.join(local_dir, local_path))
1095 impl = ZeroInstallImplementation(self, id, abs_local_path)
1096 elif local_dir and (id.startswith('/') or id.startswith('.')):
1097 # For old feeds
1098 id = os.path.abspath(os.path.join(local_dir, id))
1099 impl = ZeroInstallImplementation(self, id, id)
1100 else:
1101 impl = ZeroInstallImplementation(self, id, None)
1102 if '=' in id:
1103 # In older feeds, the ID was the (single) digest
1104 impl.digests.append(id)
1105 if id in self.implementations:
1106 warn(_("Duplicate ID '%(id)s' in feed '%(feed)s'"), {'id': id, 'feed': self})
1107 self.implementations[id] = impl
1109 impl.metadata = item_attrs
1110 try:
1111 version_mod = item_attrs.get('version-modifier', None)
1112 if version_mod:
1113 item_attrs['version'] += version_mod
1114 del item_attrs['version-modifier']
1115 version = item_attrs['version']
1116 except KeyError:
1117 raise InvalidInterface(_("Missing version attribute"))
1118 impl.version = parse_version(version)
1120 impl.commands = commands
1122 impl.released = item_attrs.get('released', None)
1123 impl.langs = item_attrs.get('langs', '').replace('_', '-')
1125 size = item.getAttribute('size')
1126 if size:
1127 impl.size = int(size)
1128 impl.arch = item_attrs.get('arch', None)
1129 try:
1130 stability = stability_levels[str(item_attrs['stability'])]
1131 except KeyError:
1132 stab = str(item_attrs['stability'])
1133 if stab != stab.lower():
1134 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs.stability)
1135 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs['stability'])
1136 if stability >= preferred:
1137 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
1138 impl.upstream_stability = stability
1140 impl.bindings = bindings
1141 impl.requires = depends
1143 for elem in item.childNodes:
1144 if elem.uri != XMLNS_IFACE: continue
1145 if elem.name == 'archive':
1146 url = elem.getAttribute('href')
1147 if not url:
1148 raise InvalidInterface(_("Missing href attribute on <archive>"))
1149 size = elem.getAttribute('size')
1150 if not size:
1151 raise InvalidInterface(_("Missing size attribute on <archive>"))
1152 impl.add_download_source(url = url, size = int(size),
1153 extract = elem.getAttribute('extract'),
1154 start_offset = _get_long(elem, 'start-offset'),
1155 type = elem.getAttribute('type'))
1156 elif elem.name == 'manifest-digest':
1157 for aname, avalue in elem.attrs.iteritems():
1158 if ' ' not in aname:
1159 impl.digests.append('%s=%s' % (aname, avalue))
1160 elif elem.name == 'recipe':
1161 recipe = Recipe()
1162 for recipe_step in elem.childNodes:
1163 if recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'archive':
1164 url = recipe_step.getAttribute('href')
1165 if not url:
1166 raise InvalidInterface(_("Missing href attribute on <archive>"))
1167 size = recipe_step.getAttribute('size')
1168 if not size:
1169 raise InvalidInterface(_("Missing size attribute on <archive>"))
1170 recipe.steps.append(DownloadSource(None, url = url, size = int(size),
1171 extract = recipe_step.getAttribute('extract'),
1172 start_offset = _get_long(recipe_step, 'start-offset'),
1173 type = recipe_step.getAttribute('type')))
1174 elif recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'unpack':
1175 path = recipe_step.getAttribute('path')
1176 if not path:
1177 raise InvalidInterface(_("Missing path attribute on <unpack>"))
1178 recipe.steps.append(UnpackArchive(path = path,
1179 extract = recipe_step.getAttribute('extract'),
1180 type = recipe_step.getAttribute('type')))
1181 else:
1182 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step.name)
1183 break
1184 else:
1185 impl.download_sources.append(recipe)
1187 root_attrs = {'stability': 'testing'}
1188 root_commands = {}
1189 if main:
1190 info("Note: @main on document element is deprecated in %s", self)
1191 root_commands['run'] = Command(qdom.Element(XMLNS_IFACE, 'command', {'path': main}), None)
1192 process_group(feed_element, root_attrs, [], [], root_commands)
1194 def get_distro_feed(self):
1195 """Does this feed contain any <pacakge-implementation> elements?
1196 i.e. is it worth asking the package manager for more information?
1197 @return: the URL of the virtual feed, or None
1198 @since: 0.49"""
1199 if self._package_implementations:
1200 return "distribution:" + self.url
1201 return None
1203 def get_package_impls(self, distro):
1204 """Find the best <pacakge-implementation> element(s) for the given distribution.
1205 @param distro: the distribution to use to rate them
1206 @type distro: L{distro.Distribution}
1207 @return: a list of tuples for the best ranked elements
1208 @rtype: [str]
1209 @since: 0.49"""
1210 best_score = 0
1211 best_impls = []
1213 for item, item_attrs in self._package_implementations:
1214 distro_names = item_attrs.get('distributions', '')
1215 for distro_name in distro_names.split(' '):
1216 score = distro.get_score(distro_name)
1217 if score > best_score:
1218 best_score = score
1219 best_impls = []
1220 if score == best_score:
1221 best_impls.append((item, item_attrs))
1222 return best_impls
1224 def get_name(self):
1225 return self.name or '(' + os.path.basename(self.url) + ')'
1227 def __repr__(self):
1228 return _("<Feed %s>") % self.url
1230 def set_stability_policy(self, new):
1231 assert new is None or isinstance(new, Stability)
1232 self.stability_policy = new
1234 def get_feed(self, url):
1235 for x in self.feeds:
1236 if x.uri == url:
1237 return x
1238 return None
1240 def add_metadata(self, elem):
1241 self.metadata.append(elem)
1243 def get_metadata(self, uri, name):
1244 """Return a list of interface metadata elements with this name and namespace URI."""
1245 return [m for m in self.metadata if m.name == name and m.uri == uri]
1247 @property
1248 def summary(self):
1249 return _best_language_match(self.summaries) or self.first_summary
1251 @property
1252 def description(self):
1253 return _best_language_match(self.descriptions) or self.first_description
1255 class DummyFeed(object):
1256 """Temporary class used during API transition."""
1257 last_modified = None
1258 name = '-'
1259 last_checked = property(lambda self: None)
1260 implementations = property(lambda self: {})
1261 feeds = property(lambda self: [])
1262 summary = property(lambda self: '-')
1263 description = property(lambda self: '')
1264 def get_name(self): return self.name
1265 def get_feed(self, url): return None
1266 def get_metadata(self, uri, name): return []
1267 _dummy_feed = DummyFeed()
1269 def unescape(uri):
1270 """Convert each %20 to a space, etc.
1271 @rtype: str"""
1272 uri = uri.replace('#', '/')
1273 if '%' not in uri: return uri
1274 return re.sub('%[0-9a-fA-F][0-9a-fA-F]',
1275 lambda match: chr(int(match.group(0)[1:], 16)),
1276 uri).decode('utf-8')
1278 def escape(uri):
1279 """Convert each space to %20, etc
1280 @rtype: str"""
1281 return re.sub('[^-_.a-zA-Z0-9]',
1282 lambda match: '%%%02x' % ord(match.group(0)),
1283 uri.encode('utf-8'))
1285 def _pretty_escape(uri):
1286 """Convert each space to %20, etc
1287 : is preserved and / becomes #. This makes for nicer strings,
1288 and may replace L{escape} everywhere in future.
1289 @rtype: str"""
1290 if os.name == "posix":
1291 # Only preserve : on Posix systems
1292 preserveRegex = '[^-_.a-zA-Z0-9:/]'
1293 else:
1294 # Other OSes may not allow the : character in file names
1295 preserveRegex = '[^-_.a-zA-Z0-9/]'
1296 return re.sub(preserveRegex,
1297 lambda match: '%%%02x' % ord(match.group(0)),
1298 uri.encode('utf-8')).replace('/', '#')
1300 def canonical_iface_uri(uri):
1301 """If uri is a relative path, convert to an absolute one.
1302 A "file:///foo" URI is converted to "/foo".
1303 An "alias:prog" URI expands to the URI in the 0alias script
1304 Otherwise, return it unmodified.
1305 @rtype: str
1306 @raise SafeException: if uri isn't valid
1308 if uri.startswith('http://') or uri.startswith('https://'):
1309 if uri.count("/") < 3:
1310 raise SafeException(_("Missing / after hostname in URI '%s'") % uri)
1311 return uri
1312 elif uri.startswith('file:///'):
1313 return uri[7:]
1314 elif uri.startswith('alias:'):
1315 from zeroinstall import alias, support
1316 alias_prog = uri[6:]
1317 if not os.path.isabs(alias_prog):
1318 full_path = support.find_in_path(alias_prog)
1319 if not full_path:
1320 raise alias.NotAnAliasScript("Not found in $PATH: " + alias_prog)
1321 else:
1322 full_path = alias_prog
1323 interface_uri, main = alias.parse_script(full_path)
1324 return interface_uri
1325 else:
1326 iface_uri = os.path.realpath(uri)
1327 if os.path.isfile(iface_uri):
1328 return iface_uri
1329 raise SafeException(_("Bad interface name '%(uri)s'.\n"
1330 "(doesn't start with 'http:', and "
1331 "doesn't exist as a local file '%(interface_uri)s' either)") %
1332 {'uri': uri, 'interface_uri': iface_uri})
1334 _version_mod_to_value = {
1335 'pre': -2,
1336 'rc': -1,
1337 '': 0,
1338 'post': 1,
1341 # Reverse mapping
1342 _version_value_to_mod = {}
1343 for x in _version_mod_to_value: _version_value_to_mod[_version_mod_to_value[x]] = x
1344 del x
1346 _version_re = re.compile('-([a-z]*)')
1348 def parse_version(version_string):
1349 """Convert a version string to an internal representation.
1350 The parsed format can be compared quickly using the standard Python functions.
1351 - Version := DottedList ("-" Mod DottedList?)*
1352 - DottedList := (Integer ("." Integer)*)
1353 @rtype: tuple (opaque)
1354 @raise SafeException: if the string isn't a valid version
1355 @since: 0.24 (moved from L{reader}, from where it is still available):"""
1356 if version_string is None: return None
1357 parts = _version_re.split(version_string)
1358 if parts[-1] == '':
1359 del parts[-1] # Ends with a modifier
1360 else:
1361 parts.append('')
1362 if not parts:
1363 raise SafeException(_("Empty version string!"))
1364 l = len(parts)
1365 try:
1366 for x in range(0, l, 2):
1367 part = parts[x]
1368 if part:
1369 parts[x] = map(int, parts[x].split('.'))
1370 else:
1371 parts[x] = [] # (because ''.split('.') == [''], not [])
1372 for x in range(1, l, 2):
1373 parts[x] = _version_mod_to_value[parts[x]]
1374 return parts
1375 except ValueError, ex:
1376 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1377 except KeyError, ex:
1378 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1380 def format_version(version):
1381 """Format a parsed version for display. Undoes the effect of L{parse_version}.
1382 @see: L{Implementation.get_version}
1383 @rtype: str
1384 @since: 0.24"""
1385 version = version[:]
1386 l = len(version)
1387 for x in range(0, l, 2):
1388 version[x] = '.'.join(map(str, version[x]))
1389 for x in range(1, l, 2):
1390 version[x] = '-' + _version_value_to_mod[version[x]]
1391 if version[-1] == '-': del version[-1]
1392 return ''.join(version)