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
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
13 # Copyright (C) 2009, Thomas Leonard
14 # See the README file for details, or visit http://0install.net.
16 from zeroinstall
import _
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'
31 network_levels
= (network_offline
, network_minimal
, network_full
)
33 stability_levels
= {} # Name -> Stability
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."""
45 def __init__(self
, message
, ex
= None):
48 message
+= "\n\n(exact error: %s)" % ex
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.
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__'):
64 return _('%s [%s]') % (SafeException
.__unicode
__(self
), self
.feed_url
)
65 return SafeException
.__unicode
__(self
)
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."""
74 raise SafeException(_("Malformed arch '%s'") % arch
)
76 osys
, machine
= arch
.split('-', 1)
77 if osys
== '*': osys
= None
78 if machine
== '*': machine
= None
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()
89 # xml:lang uses '-', while LANG uses '_'
90 language
= language
.replace('_', '-')
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
):
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
)
116 return _("<Stability: %s>") % self
.description
118 def process_binding(e
):
120 if e
.name
== 'environment':
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'),
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'"))
140 elif e
.name
== 'overlay':
141 return OverlayBinding(e
.getAttribute('src'), e
.getAttribute('mount-point'))
143 raise Exception(_("Unknown binding type '%s'") % e
.name
)
145 def process_depends(item
, local_feed_dir
):
147 # Note: also called from selections
149 dep_iface
= item
.getAttribute('interface')
151 raise InvalidInterface(_("Missing 'interface' on <%s>") % item
.name
)
152 if dep_iface
.startswith('./'):
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
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'))))
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'))
183 class Restriction(object):
184 """A Restriction limits the allowed implementations of an Interface."""
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
192 raise NotImplementedError(_("Abstract"))
194 class VersionRestriction(Restriction
):
195 """Only select implementations with a particular version number.
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
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
220 self
.not_before
= not_before
222 def meets_restriction(self
, impl
):
223 if self
.not_before
and impl
.version
< self
.not_before
:
225 if self
.before
and impl
.version
>= self
.before
:
230 if self
.not_before
is not None or self
.before
is not None:
232 if self
.not_before
is not None:
233 range += format_version(self
.not_before
) + ' <= '
235 if self
.before
is not None:
236 range += ' < ' + format_version(self
.before
)
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']
253 def __init__(self
, name
, insert
, default
= None, mode
= PREPEND
, value
=None, separator
=None):
255 mode argument added in version 0.28
256 value argument added in version 0.52
260 self
.default
= default
264 if separator
is None:
265 self
.separator
= os
.pathsep
267 self
.separator
= separator
271 return _("<environ %(name)s %(mode)s %(insert)s %(value)s>") % {'name': self
.name
,'mode': self
.mode
, 'insert': self
.insert
, 'value': self
.value
}
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
)
284 assert self
.value
is not None
287 if self
.mode
== EnvironmentBinding
.REPLACE
:
290 if old_value
is None:
291 old_value
= self
.default
or defaults
.get(self
.name
, None)
292 if old_value
is None:
294 if self
.mode
== EnvironmentBinding
.PREPEND
:
295 return extra
+ self
.separator
+ old_value
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
.mode
is not None:
307 env_elem
.setAttributeNS(None, 'mode', self
.mode
)
308 if self
.insert
is not None:
309 env_elem
.setAttributeNS(None, 'insert', self
.insert
)
311 env_elem
.setAttributeNS(None, 'value', self
.value
)
313 env_elem
.setAttributeNS(None, 'default', self
.default
)
316 class OverlayBinding(Binding
):
317 """Make the chosen implementation available by overlaying it onto another part of the file-system.
318 This is to support legacy programs which use hard-coded paths."""
319 __slots__
= ['src', 'mount_point']
321 def __init__(self
, src
, mount_point
):
323 self
.mount_point
= mount_point
326 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self
.src
or '.', 'mount_point': self
.mount_point
or '/'}
330 def _toxml(self
, doc
):
331 """Create a DOM element for this binding.
332 @param doc: document to use to create the element
333 @return: the new element
335 env_elem
= doc
.createElementNS(XMLNS_IFACE
, 'overlay')
336 if self
.src
is not None:
337 env_elem
.setAttributeNS(None, 'src', self
.src
)
338 if self
.mount_point
is not None:
339 env_elem
.setAttributeNS(None, 'mount-point', self
.mount_point
)
343 """An interface's feeds are other interfaces whose implementations can also be
344 used as implementations of this interface."""
345 __slots__
= ['uri', 'os', 'machine', 'user_override', 'langs']
346 def __init__(self
, uri
, arch
, user_override
, langs
= None):
348 # This indicates whether the feed comes from the user's overrides
349 # file. If true, writer.py will write it when saving.
350 self
.user_override
= user_override
351 self
.os
, self
.machine
= _split_arch(arch
)
355 return "<Feed from %s>" % self
.uri
358 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
360 class Dependency(object):
361 """A Dependency indicates that an Implementation requires some additional
362 code to function. This is an abstract base class.
363 @ivar qdom: the XML element for this Dependency (since 0launch 0.51)
364 @type qdom: L{qdom.Element}
365 @ivar metadata: any extra attributes from the XML element
366 @type metadata: {str: str}
370 Essential
= "essential"
371 Recommended
= "recommended"
373 def __init__(self
, element
):
374 assert isinstance(element
, qdom
.Element
), type(element
) # Use InterfaceDependency instead!
379 return self
.qdom
.attrs
382 def importance(self
):
383 return self
.qdom
.getAttribute("importance") or Dependency
.Essential
385 class InterfaceDependency(Dependency
):
386 """A Dependency on a Zero Install interface.
387 @ivar interface: the interface required by this dependency
389 @ivar restrictions: a list of constraints on acceptable implementations
390 @type restrictions: [L{Restriction}]
391 @ivar bindings: how to make the choice of implementation known
392 @type bindings: [L{Binding}]
395 __slots__
= ['interface', 'restrictions', 'bindings']
397 def __init__(self
, interface
, restrictions
= None, element
= None):
398 Dependency
.__init
__(self
, element
)
399 assert isinstance(interface
, (str, unicode))
401 self
.interface
= interface
402 if restrictions
is None:
403 self
.restrictions
= []
405 self
.restrictions
= restrictions
409 return _("<Dependency on %(interface)s; bindings: %(bindings)s%(restrictions)s>") % {'interface': self
.interface
, 'bindings': self
.bindings
, 'restrictions': self
.restrictions
}
411 class RetrievalMethod(object):
412 """A RetrievalMethod provides a way to fetch an implementation."""
416 def retrieve(self
, fetcher
, destination
, force
= False, impl_hint
= None):
417 """Retrieve implementation using method
418 @param destination: where to put the retrieved files
419 @param impl_hint: the Implementation this is for (if any) as a hint for the GUI
421 raise NotImplementedError("abstract")
425 '''get all archives in this retrieval method'''
429 class DownloadSource(RetrievalMethod
):
430 """A DownloadSource provides a way to fetch an implementation."""
431 __slots__
= ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
433 def __init__(self
, implementation
, url
, size
, extract
, start_offset
= 0, type = None):
434 self
.implementation
= implementation
437 self
.extract
= extract
438 self
.start_offset
= start_offset
439 self
.type = type # MIME type - see unpack.py
446 def _generate_size(self
, fetcher
):
447 dl
= self
._download
(fetcher
)
448 tasks
.wait_for_blocker(dl
.downloaded
)
449 self
.size
= dl
.get_bytes_downloaded_so_far()
452 def fromDOM(elem
, impl
, generate_sizes
=False, fetcher
=None):
453 """Make a DownloadSource from a DOM archive element."""
455 url
= elem
.getAttribute('href')
457 raise InvalidInterface(_("Missing href attribute on <archive>"))
459 size
= elem
.getAttribute('size')
462 elif not generate_sizes
:
463 raise InvalidInterface(_("Missing size attribute on <archive>"))
465 archive
= DownloadSource(impl
, url
= url
, size
= size
, extract
= elem
.getAttribute('extract'),
466 start_offset
= _get_long(elem
, 'start-offset'), type = elem
.getAttribute('type'))
468 if not size
and generate_sizes
:
469 archive
._generate
_size
(fetcher
)
473 def prepare(self
, fetcher
, force
, impl_hint
):
475 class StepCommand(object):
476 __slots__
= ['blocker', '_stream']
479 s
.blocker
, s
._stream
= self
.download(fetcher
, force
= force
, impl_hint
= impl_hint
)
481 def run(s
, destination
):
483 unpack
.unpack_archive_over(self
.url
, s
._stream
, destination
,
484 extract
= self
.extract
,
486 start_offset
= self
.start_offset
or 0)
489 def download(self
, fetcher
, force
= False, impl_hint
= None):
490 """Fetch an archive. You should normally call L{Implementation.retrieve}
491 instead, since it handles other kinds of retrieval method too."""
492 dl
= self
._download
(fetcher
, force
, impl_hint
)
493 return (dl
.downloaded
, dl
.tempfile
)
495 def _download(self
, fetcher
, force
= False, impl_hint
= None):
497 if not (url
.startswith('http:') or url
.startswith('https:') or url
.startswith('ftp:')):
498 raise SafeException(_("Unknown scheme in download URL '%s'") % url
)
500 mime_type
= self
.type
502 mime_type
= unpack
.type_from_url(self
.url
)
504 raise SafeException(_("No 'type' attribute on archive, and I can't guess from the name (%s)") % self
.url
)
505 unpack
.check_type_ok(mime_type
)
506 dl
= fetcher
.handler
.get_download(self
.url
, force
= force
, hint
= impl_hint
)
508 dl
.expected_size
= self
.size
+ (self
.start_offset
or 0)
512 def retrieve(self
, fetcher
, destination
, force
= False, impl_hint
= None):
513 command
= self
.prepare(fetcher
, force
, impl_hint
)
514 yield command
.blocker
515 tasks
.check(command
.blocker
)
516 command
.run(destination
)
519 class UnpackArchive(RetrievalMethod
):
520 """An UnpackArchive step provides unpacks/extracts an archive.
522 It can be used inside a Recipe."""
523 __slots__
= ['path', 'extract', 'type']
525 def __init__(self
, path
, extract
, type):
527 self
.extract
= extract
530 def prepare(self
, fetcher
, force
, impl_hint
):
532 class StepCommand(object):
533 __slots__
= ['blocker']
539 path
= os
.path
.join(tmpdir
, self
.path
)
540 stream
= open(path
, 'rb')
543 unpack
.unpack_archive_over(path
, stream
, tmpdir
,
544 extract
= self
.extract
,
552 class Recipe(RetrievalMethod
):
553 """Get an implementation by following a series of steps.
554 @ivar size: the combined download sizes from all the steps
556 @ivar steps: the sequence of steps which must be performed
557 @type steps: [L{RetrievalMethod}]"""
558 __slots__
= ['steps']
563 size
= property(lambda self
: sum([x
.size
for x
in self
.steps
]))
567 '''get all archives in this retrieval method'''
568 from itertools
import chain
569 return chain(*[step
.archives
for step
in self
.steps
])
572 def retrieve(self
, fetcher
, destination
, force
= False, impl_hint
= None):
573 # Start preparing all steps
574 step_commands
= [step
.prepare(fetcher
, force
, impl_hint
) for step
in self
.steps
]
577 valid_blockers
= [s
.blocker
for s
in step_commands
if s
.blocker
is not None]
578 for step_command
in step_commands
:
579 if step_command
.blocker
:
580 while not step_command
.blocker
.happened
:
582 tasks
.check(valid_blockers
)
583 step_command
.run(destination
)
586 def fromDOM(elem
, generate_sizes
=False, fetcher
=None):
587 """Make a Recipe from a DOM recipe element"""
589 for recipe_step
in elem
.childNodes
:
590 if recipe_step
.uri
== XMLNS_IFACE
and recipe_step
.name
== 'archive':
591 recipe
.steps
.append(DownloadSource
.fromDOM(recipe_step
, None, generate_sizes
, fetcher
))
592 elif recipe_step
.uri
== XMLNS_IFACE
and recipe_step
.name
== 'unpack':
593 path
= recipe_step
.getAttribute('path')
595 raise InvalidInterface(_("Missing path attribute on <unpack>"))
596 recipe
.steps
.append(UnpackArchive(path
= path
,
597 extract
= recipe_step
.getAttribute('extract'),
598 type = recipe_step
.getAttribute('type')))
600 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step
.name
)
605 class DistributionSource(RetrievalMethod
):
606 """A package that is installed using the distribution's tools (including PackageKit).
607 @ivar install: a function to call to install this package
608 @type install: (L{handler.Handler}) -> L{tasks.Blocker}
609 @ivar package_id: the package name, in a form recognised by the distribution's tools
610 @type package_id: str
611 @ivar size: the download size in bytes
613 @ivar needs_confirmation: whether the user should be asked to confirm before calling install()
614 @type needs_confirmation: bool"""
616 __slots__
= ['package_id', 'size', 'install', 'needs_confirmation']
618 def __init__(self
, package_id
, size
, install
, needs_confirmation
= True):
619 RetrievalMethod
.__init
__(self
)
620 self
.package_id
= package_id
622 self
.install
= install
623 self
.needs_confirmation
= needs_confirmation
625 class Command(object):
626 """A Command is a way of running an Implementation as a program."""
628 __slots__
= ['qdom', '_depends', '_local_dir', '_runner']
630 def __init__(self
, qdom
, local_dir
):
631 """@param qdom: the <command> element
632 @param local_dir: the directory containing the feed (for relative dependencies), or None if not local
634 assert qdom
.name
== 'command', 'not <command>: %s' % qdom
636 self
._local
_dir
= local_dir
639 path
= property(lambda self
: self
.qdom
.attrs
.get("path", None))
641 def _toxml(self
, doc
, prefixes
):
642 return self
.qdom
.toDOM(doc
, prefixes
)
646 if self
._depends
is None:
649 for child
in self
.qdom
.childNodes
:
650 if child
.name
== 'requires':
651 dep
= process_depends(child
, self
._local
_dir
)
653 elif child
.name
== 'runner':
655 raise InvalidInterface(_("Multiple <runner>s in <command>!"))
656 dep
= process_depends(child
, self
._local
_dir
)
659 self
._depends
= depends
662 def get_runner(self
):
663 self
.requires
# (sets _runner)
666 class Implementation(object):
667 """An Implementation is a package which implements an Interface.
668 @ivar download_sources: list of methods of getting this implementation
669 @type download_sources: [L{RetrievalMethod}]
670 @ivar feed: the feed owning this implementation (since 0.32)
671 @type feed: [L{ZeroInstallFeed}]
672 @ivar bindings: how to tell this component where it itself is located (since 0.31)
673 @type bindings: [Binding]
674 @ivar upstream_stability: the stability reported by the packager
675 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged]
676 @ivar user_stability: the stability as set by the user
677 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred]
678 @ivar langs: natural languages supported by this package
680 @ivar requires: interfaces this package depends on
681 @type requires: [L{Dependency}]
682 @ivar commands: ways to execute as a program
683 @type commands: {str: Command}
684 @ivar metadata: extra metadata from the feed
685 @type metadata: {"[URI ]localName": str}
686 @ivar id: a unique identifier for this Implementation
687 @ivar version: a parsed version number
688 @ivar released: release date
689 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path)
690 @type local_path: str | None
691 @ivar requires_root_install: whether the user will need admin rights to use this
692 @type requires_root_install: bool
695 # Note: user_stability shouldn't really be here
697 __slots__
= ['upstream_stability', 'user_stability', 'langs',
698 'requires', 'metadata', 'download_sources', 'commands',
699 'id', 'feed', 'version', 'released', 'bindings', 'machine']
701 def __init__(self
, feed
, id):
704 self
.user_stability
= None
705 self
.upstream_stability
= None
706 self
.metadata
= {} # [URI + " "] + localName -> value
710 self
.download_sources
= []
716 def get_stability(self
):
717 return self
.user_stability
or self
.upstream_stability
or testing
723 return "v%s (%s)" % (self
.get_version(), self
.id)
725 def __cmp__(self
, other
):
726 """Newer versions come first"""
727 d
= cmp(other
.version
, self
.version
)
729 # If the version number is the same, just give a stable sort order, and
730 # ensure that two different implementations don't compare equal.
731 d
= cmp(other
.feed
.url
, self
.feed
.url
)
733 return cmp(other
.id, self
.id)
735 def get_version(self
):
736 """Return the version as a string.
737 @see: L{format_version}
739 return format_version(self
.version
)
741 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
746 requires_root_install
= False
749 """"@deprecated: use commands["run"] instead"""
750 main
= self
.commands
.get("run", None)
754 def _set_main(self
, path
):
755 """"@deprecated: use commands["run"] instead"""
757 if "run" in self
.commands
:
758 del self
.commands
["run"]
760 self
.commands
["run"] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'path': path
}), None)
761 main
= property(_get_main
, _set_main
)
763 def is_available(self
, stores
):
764 """Is this Implementation available locally?
765 (a local implementation, an installed distribution package, or a cached ZeroInstallImplementation)
769 raise NotImplementedError("abstract")
772 def best_download_source(self
):
773 """Return the best download source for this implementation.
774 @rtype: L{model.RetrievalMethod}"""
775 if self
.download_sources
:
776 return self
.download_sources
[0]
779 def retrieve(self
, fetcher
, retrieval_method
, stores
, force
= False):
780 """Retrieve an implementation.
781 @param retrieval_method: a way of getting the implementation (e.g. an Archive or a Recipe)
782 @type retrieval_method: L{model.RetrievalMethod}
783 @param stores: where to store the downloaded implementation
784 @type stores: L{zerostore.Stores}
785 @param force: whether to abort and restart an existing download
786 @rtype: L{tasks.Blocker}"""
787 raise NotImplementedError("abstract")
791 '''get all archives in this implementation'''
795 class DistributionImplementation(Implementation
):
796 """An implementation provided by the distribution. Information such as the version
797 comes from the package manager.
799 __slots__
= ['distro', 'installed']
801 def __init__(self
, feed
, id, distro
):
802 assert id.startswith('package:')
803 Implementation
.__init
__(self
, feed
, id)
805 self
.installed
= False
808 def requires_root_install(self
):
809 return not self
.installed
811 def is_available(self
, stores
):
812 return self
.installed
814 def retrieve(self
, fetcher
, retrieval_method
, stores
, force
= False):
815 return retrieval_method
.install(fetcher
.handler
)
818 class ZeroInstallImplementation(Implementation
):
819 """An implementation where all the information comes from Zero Install.
820 @ivar digests: a list of "algorith=value" strings (since 0.45)
823 __slots__
= ['os', 'size', 'digests', 'local_path']
825 def __init__(self
, feed
, id, local_path
):
826 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
828 assert not id.startswith('package:'), id
829 Implementation
.__init
__(self
, feed
, id)
833 self
.local_path
= local_path
837 '''get all archives in this implementation'''
838 from itertools
import chain
839 return chain([method
.archives
for method
in self
.download_sources
])
843 def fromDOM(feed
, item
, item_attrs
, local_dir
, commands
, bindings
, depends
,
844 generate_sizes
=False, id_generation_alg
=None, fetcher
=None, stores
=None):
845 """Make an implementation from a DOM implementation element.
846 @param generate_sizes: if True, sizes of archives with missing size attributes will be generated
847 @type generate_sizes: bool
848 @param id_generation_alg: if specified, id will be autogenerated, if id is None, with this alg
849 @type id_generation_alg: L{Algorithm}
850 @param fetcher: must be specified if id_generation_alg/generate_sizes is specified/True
851 @param stores: must be specified if id_generation_alg is specified
853 id = item
.getAttribute('id')
854 local_path
= item_attrs
.get('local-path')
855 if local_dir
and local_path
:
856 abs_local_path
= os
.path
.abspath(os
.path
.join(local_dir
, local_path
))
857 impl
= ZeroInstallImplementation(feed
, id, abs_local_path
)
858 elif local_dir
and (id and (id.startswith('/') or id.startswith('.'))):
860 id = os
.path
.abspath(os
.path
.join(local_dir
, id))
861 impl
= ZeroInstallImplementation(feed
, id, id)
863 impl
= ZeroInstallImplementation(feed
, id, None)
865 # In older feeds, the ID was the (single) digest
866 impl
.digests
.append(id)
869 version_mod
= item_attrs
.get('version-modifier', None)
871 item_attrs
['version'] += version_mod
872 del item_attrs
['version-modifier']
873 version
= item_attrs
['version']
875 raise InvalidInterface(_("Missing version attribute"))
876 impl
.version
= parse_version(version
)
878 impl
.metadata
= item_attrs
879 impl
.commands
= commands
880 impl
.bindings
= bindings
881 impl
.requires
= depends
882 impl
.released
= item_attrs
.get('released', None)
883 impl
.langs
= item_attrs
.get('langs', '').replace('_', '-')
885 size
= item
.getAttribute('size')
887 impl
.size
= int(size
)
889 impl
.arch
= item_attrs
.get('arch', None)
892 stability
= stability_levels
[str(item_attrs
['stability'])]
894 stab
= str(item_attrs
['stability'])
895 if stab
!= stab
.lower():
896 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs
.stability
)
897 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs
['stability'])
898 if stability
>= preferred
:
899 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
900 impl
.upstream_stability
= stability
902 for elem
in item
.childNodes
:
903 if elem
.uri
!= XMLNS_IFACE
: continue
904 if elem
.name
== 'archive':
905 impl
.download_sources
.append(DownloadSource
.fromDOM(elem
, impl
, generate_sizes
, fetcher
))
906 elif elem
.name
== 'manifest-digest':
907 for aname
, avalue
in elem
.attrs
.iteritems():
909 impl
.digests
.append('%s=%s' % (aname
, avalue
))
910 elif elem
.name
== 'recipe':
911 recipe
= Recipe
.fromDOM(elem
, generate_sizes
, fetcher
)
913 impl
.download_sources
.append(recipe
)
915 if id is None and id_generation_alg
:
918 impl
.id = impl
._generate
_digest
(fetcher
, stores
, id_generation_alg
)
919 feed
.changed_implementations
.append(impl
)
921 raise InvalidInterface(_("Missing 'id' attribute on %s") % item
)
927 dependencies
= property(lambda self
: dict([(x
.interface
, x
) for x
in self
.requires
928 if isinstance(x
, InterfaceDependency
)]))
930 def add_download_source(self
, url
, size
, extract
, start_offset
= 0, type = None):
931 """Add a download source."""
932 # TODO should deprecate?
933 self
.download_sources
.append(DownloadSource(self
, url
, size
, extract
, start_offset
, type))
935 def set_arch(self
, arch
):
936 self
.os
, self
.machine
= _split_arch(arch
)
937 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
), set_arch
)
939 def is_available(self
, stores
):
940 if self
.local_path
is not None:
941 return os
.path
.exists(self
.local_path
)
943 path
= stores
.lookup_maybe(self
.digests
)
944 return path
is not None
945 return False # (0compile creates fake entries with no digests)
948 def best_digest(self
):
949 """Return the best digest for this implementation
950 @return: tuple (alg, digest) or None"""
951 from zeroinstall
.zerostore
import manifest
953 for digest
in self
.digests
:
954 alg_name
= digest
.split('=', 1)[0]
955 alg
= manifest
.algorithms
.get(alg_name
, None)
956 if alg
and (best_alg
is None or best_alg
.rating
< alg
.rating
):
960 return (best_alg
, best_digest
)
964 def _generate_digest(self
, fetcher
, stores
, alg
):
967 # Create an empty directory for the new implementation
968 store
= stores
.stores
[0]
969 tmpdir
= store
.get_tmp_dir_for('missing')
972 blocker
= self
.best_download_source
.retrieve(fetcher
, tmpdir
, force
=False, impl_hint
= self
)
973 tasks
.wait_for_blocker(blocker
)
975 from zeroinstall
.zerostore
import manifest
976 manifest
.fixup_permissions(tmpdir
)
977 digest
= alg
.getID(manifest
.add_manifest_file(tmpdir
, alg
))
979 # If unpacking fails, remove the temporary directory
980 if tmpdir
is not None:
981 from zeroinstall
import support
982 support
.ro_rmtree(tmpdir
)
987 def retrieve(self
, fetcher
, retrieval_method
, stores
, force
= False):
988 best
= self
.best_digest
992 raise SafeException(_("No <manifest-digest> given for '%(implementation)s' version %(version)s") %
993 {'implementation': self
.feed
.get_name(), 'version': self
.get_version()})
994 raise SafeException(_("Unknown digest algorithms '%(algorithms)s' for '%(implementation)s' version %(version)s") %
995 {'algorithms': self
.digests
, 'implementation': self
.feed
.get_name(), 'version': self
.get_version()})
997 alg
, required_digest
= best
1001 # Create an empty directory for the new implementation
1002 store
= stores
.stores
[0]
1003 tmpdir
= store
.get_tmp_dir_for(required_digest
)
1006 blocker
= retrieval_method
.retrieve(fetcher
, tmpdir
, force
, impl_hint
= self
)
1008 tasks
.check(blocker
)
1010 # Check that the result is correct and store it in the cache
1011 store
.check_manifest_and_rename(required_digest
, tmpdir
)
1015 # If unpacking fails, remove the temporary directory
1016 if tmpdir
is not None:
1017 from zeroinstall
import support
1018 support
.ro_rmtree(tmpdir
)
1020 fetcher
.handler
.impl_added_to_store(self
)
1025 class Interface(object):
1026 """An Interface represents some contract of behaviour.
1027 @ivar uri: the URI for this interface.
1028 @ivar stability_policy: user's configured policy.
1029 Implementations at this level or higher are preferred.
1030 Lower levels are used only if there is no other choice.
1032 __slots__
= ['uri', 'stability_policy', 'extra_feeds']
1034 implementations
= property(lambda self
: self
._main
_feed
.implementations
)
1035 name
= property(lambda self
: self
._main
_feed
.name
)
1036 description
= property(lambda self
: self
._main
_feed
.description
)
1037 summary
= property(lambda self
: self
._main
_feed
.summary
)
1038 last_modified
= property(lambda self
: self
._main
_feed
.last_modified
)
1039 feeds
= property(lambda self
: self
.extra_feeds
+ self
._main
_feed
.feeds
)
1040 metadata
= property(lambda self
: self
._main
_feed
.metadata
)
1042 last_checked
= property(lambda self
: self
._main
_feed
.last_checked
)
1044 def __init__(self
, uri
):
1046 if uri
.startswith('http:') or uri
.startswith('https:') or os
.path
.isabs(uri
):
1049 raise SafeException(_("Interface name '%s' doesn't start "
1050 "with 'http:' or 'https:'") % uri
)
1053 def _get_feed_for(self
):
1055 for key
in self
._main
_feed
.feed_for
:
1058 feed_for
= property(_get_feed_for
) # Deprecated (used by 0publish)
1061 self
.extra_feeds
= []
1062 self
.stability_policy
= None
1065 from zeroinstall
.injector
.iface_cache
import iface_cache
1066 feed
= iface_cache
.get_feed(self
.uri
)
1068 return feed
.get_name()
1069 return '(' + os
.path
.basename(self
.uri
) + ')'
1072 return _("<Interface %s>") % self
.uri
1074 def set_stability_policy(self
, new
):
1075 assert new
is None or isinstance(new
, Stability
)
1076 self
.stability_policy
= new
1078 def get_feed(self
, url
):
1080 #warnings.warn("use iface_cache.get_feed instead", DeprecationWarning, 2)
1081 for x
in self
.extra_feeds
:
1084 #return self._main_feed.get_feed(url)
1087 def get_metadata(self
, uri
, name
):
1088 return self
._main
_feed
.get_metadata(uri
, name
)
1091 def _main_feed(self
):
1093 #warnings.warn("use the feed instead", DeprecationWarning, 3)
1094 from zeroinstall
.injector
import policy
1095 iface_cache
= policy
.get_deprecated_singleton_config().iface_cache
1096 feed
= iface_cache
.get_feed(self
.uri
)
1101 def _merge_attrs(attrs
, item
):
1102 """Add each attribute of item to a copy of attrs and return the copy.
1103 @type attrs: {str: str}
1104 @type item: L{qdom.Element}
1108 for a
in item
.attrs
:
1109 new
[str(a
)] = item
.attrs
[a
]
1112 def _get_long(elem
, attr_name
):
1113 val
= elem
.getAttribute(attr_name
)
1118 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name
, 'value': val
})
1121 class ZeroInstallFeed(object):
1122 """A feed lists available implementations of an interface.
1123 @ivar url: the URL for this feed
1124 @ivar implementations: Implementations in this feed, indexed by ID
1125 @type implementations: {str: L{Implementation}}
1126 @ivar changed_implementations: Ordered list of implementations that had their ID changed (i.e. they had their id changed)
1127 @ivar name: human-friendly name
1128 @ivar summaries: short textual description (in various languages, since 0.49)
1129 @type summaries: {str: str}
1130 @ivar descriptions: long textual description (in various languages, since 0.49)
1131 @type descriptions: {str: str}
1132 @ivar last_modified: timestamp on signature
1133 @ivar last_checked: time feed was last successfully downloaded and updated
1134 @ivar feeds: list of <feed> elements in this feed
1135 @type feeds: [L{Feed}]
1136 @ivar feed_for: interfaces for which this could be a feed
1137 @type feed_for: set(str)
1138 @ivar metadata: extra elements we didn't understand
1140 # _main is deprecated
1141 __slots__
= ['url', 'implementations', 'changed_implementations', 'name', 'descriptions', 'first_description', 'summaries', 'first_summary', '_package_implementations',
1142 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
1144 def __init__(self
, feed_element
, local_path
= None, distro
= None, generate_sizes
= False,
1145 implementation_id_alg
=None, fetcher
=None, stores
=None):
1146 """Create a feed object from a DOM.
1147 @param feed_element: the root element of a feed file
1148 @type feed_element: L{qdom.Element}
1149 @param local_path: the pathname of this local feed, or None for remote feeds
1150 @param generate_sizes: if True, sizes of archives with missing size attributes will be generated
1151 @type generate_sizes: bool
1152 @param implementation_id_alg: if specified, missing impl ids will be generated with this alg
1153 @type implementation_id_alg: L{Algorithm}
1154 @param fetcher: cannot be None if implementation_id_alg is specified
1155 @param stores: cannot be None if implementation_id_alg is specified"""
1156 self
.implementations
= {}
1157 self
.changed_implementations
= []
1159 self
.summaries
= {} # { lang: str }
1160 self
.first_summary
= None
1161 self
.descriptions
= {} # { lang: str }
1162 self
.first_description
= None
1163 self
.last_modified
= None
1165 self
.feed_for
= set()
1167 self
.last_checked
= None
1168 self
._package
_implementations
= []
1170 if distro
is not None:
1172 warnings
.warn("distro argument is now ignored", DeprecationWarning, 2)
1174 if feed_element
is None:
1175 return # XXX subclass?
1177 assert feed_element
.name
in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
1178 assert feed_element
.uri
== XMLNS_IFACE
, "Wrong namespace on root element: %s" % feed_element
.uri
1180 main
= feed_element
.getAttribute('main')
1181 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
1184 self
.url
= local_path
1185 local_dir
= os
.path
.dirname(local_path
)
1187 self
.url
= feed_element
.getAttribute('uri')
1189 raise InvalidInterface(_("<interface> uri attribute missing"))
1190 local_dir
= None # Can't have relative paths
1192 min_injector_version
= feed_element
.getAttribute('min-injector-version')
1193 if min_injector_version
:
1194 if parse_version(min_injector_version
) > parse_version(version
):
1195 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
1196 "Zero Install, but I am only version %(version)s. "
1197 "You can get a newer version from http://0install.net") %
1198 {'min_version': min_injector_version
, 'version': version
})
1200 for x
in feed_element
.childNodes
:
1201 if x
.uri
!= XMLNS_IFACE
:
1202 self
.metadata
.append(x
)
1204 if x
.name
== 'name':
1205 self
.name
= x
.content
1206 elif x
.name
== 'description':
1207 if self
.first_description
== None:
1208 self
.first_description
= x
.content
1209 self
.descriptions
[x
.attrs
.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x
.content
1210 elif x
.name
== 'summary':
1211 if self
.first_summary
== None:
1212 self
.first_summary
= x
.content
1213 self
.summaries
[x
.attrs
.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x
.content
1214 elif x
.name
== 'feed-for':
1215 feed_iface
= x
.getAttribute('interface')
1217 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
1218 self
.feed_for
.add(feed_iface
)
1219 # Bug report from a Debian/stable user that --feed gets the wrong value.
1220 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
1221 # in case it happens again.
1222 debug(_("Is feed-for %s"), feed_iface
)
1223 elif x
.name
== 'feed':
1224 feed_src
= x
.getAttribute('src')
1226 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
1227 if feed_src
.startswith('http:') or feed_src
.startswith('https:') or local_path
:
1228 langs
= x
.getAttribute('langs')
1229 if langs
: langs
= langs
.replace('_', '-')
1230 self
.feeds
.append(Feed(feed_src
, x
.getAttribute('arch'), False, langs
= langs
))
1232 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src
)
1234 self
.metadata
.append(x
)
1237 raise InvalidInterface(_("Missing <name> in feed"))
1238 if not self
.summary
:
1239 raise InvalidInterface(_("Missing <summary> in feed"))
1241 def process_group(group
, group_attrs
, base_depends
, base_bindings
, base_commands
):
1242 for item
in group
.childNodes
:
1243 if item
.uri
!= XMLNS_IFACE
: continue
1245 if item
.name
not in ('group', 'implementation', 'package-implementation'):
1248 # We've found a group or implementation. Scan for dependencies,
1249 # bindings and commands. Doing this here means that:
1250 # - We can share the code for groups and implementations here.
1251 # - The order doesn't matter, because these get processed first.
1252 # A side-effect is that the document root cannot contain
1255 depends
= base_depends
[:]
1256 bindings
= base_bindings
[:]
1257 commands
= base_commands
.copy()
1259 for attr
, command
in [('main', 'run'),
1260 ('self-test', 'test')]:
1261 value
= item
.attrs
.get(attr
, None)
1262 if value
is not None:
1263 commands
[command
] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'path': value
}), None)
1265 for child
in item
.childNodes
:
1266 if child
.uri
!= XMLNS_IFACE
: continue
1267 if child
.name
== 'requires':
1268 dep
= process_depends(child
, local_dir
)
1270 elif child
.name
== 'command':
1271 command_name
= child
.attrs
.get('name', None)
1272 if not command_name
:
1273 raise InvalidInterface('Missing name for <command>')
1274 commands
[command_name
] = Command(child
, local_dir
)
1275 elif child
.name
in binding_names
:
1276 bindings
.append(process_binding(child
))
1278 compile_command
= item
.attrs
.get('http://zero-install.sourceforge.net/2006/namespaces/0compile command')
1279 if compile_command
is not None:
1280 commands
['compile'] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'shell-command': compile_command
}), None)
1282 item_attrs
= _merge_attrs(group_attrs
, item
)
1284 if item
.name
== 'group':
1285 process_group(item
, item_attrs
, depends
, bindings
, commands
)
1286 elif item
.name
== 'implementation':
1287 impl
= ZeroInstallImplementation
.fromDOM(self
, item
, item_attrs
, local_dir
, commands
, bindings
, depends
,
1288 generate_sizes
, implementation_id_alg
, fetcher
, stores
)
1289 if impl
.id in self
.implementations
:
1290 warn(_("Duplicate ID '%(id)s' in feed '%(feed)s'"), {'id': id, 'feed': self
})
1291 self
.implementations
[impl
.id] = impl
1292 elif item
.name
== 'package-implementation':
1294 warn("A <package-implementation> with dependencies in %s!", self
.url
)
1295 self
._package
_implementations
.append((item
, item_attrs
))
1299 root_attrs
= {'stability': 'testing'}
1302 info("Note: @main on document element is deprecated in %s", self
)
1303 root_commands
['run'] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'path': main
}), None)
1304 process_group(feed_element
, root_attrs
, [], [], root_commands
)
1308 '''get all archives in this feed'''
1309 from itertools
import chain
1310 return chain(*[impl
.archives
for impl
in self
.implementations
.itervalues()])
1312 def get_distro_feed(self
):
1313 """Does this feed contain any <pacakge-implementation> elements?
1314 i.e. is it worth asking the package manager for more information?
1315 @return: the URL of the virtual feed, or None
1317 if self
._package
_implementations
:
1318 return "distribution:" + self
.url
1321 def get_package_impls(self
, distro
):
1322 """Find the best <pacakge-implementation> element(s) for the given distribution.
1323 @param distro: the distribution to use to rate them
1324 @type distro: L{distro.Distribution}
1325 @return: a list of tuples for the best ranked elements
1331 for item
, item_attrs
in self
._package
_implementations
:
1332 distro_names
= item_attrs
.get('distributions', '')
1333 for distro_name
in distro_names
.split(' '):
1334 score
= distro
.get_score(distro_name
)
1335 if score
> best_score
:
1338 if score
== best_score
:
1339 best_impls
.append((item
, item_attrs
))
1343 return self
.name
or '(' + os
.path
.basename(self
.url
) + ')'
1346 return _("<Feed %s>") % self
.url
1348 def set_stability_policy(self
, new
):
1349 assert new
is None or isinstance(new
, Stability
)
1350 self
.stability_policy
= new
1352 def get_feed(self
, url
):
1353 for x
in self
.feeds
:
1358 def add_metadata(self
, elem
):
1359 self
.metadata
.append(elem
)
1361 def get_metadata(self
, uri
, name
):
1362 """Return a list of interface metadata elements with this name and namespace URI."""
1363 return [m
for m
in self
.metadata
if m
.name
== name
and m
.uri
== uri
]
1367 return _best_language_match(self
.summaries
) or self
.first_summary
1370 def description(self
):
1371 return _best_language_match(self
.descriptions
) or self
.first_description
1373 class DummyFeed(object):
1374 """Temporary class used during API transition."""
1375 last_modified
= None
1377 last_checked
= property(lambda self
: None)
1378 implementations
= property(lambda self
: {})
1379 feeds
= property(lambda self
: [])
1380 summary
= property(lambda self
: '-')
1381 description
= property(lambda self
: '')
1382 def get_name(self
): return self
.name
1383 def get_feed(self
, url
): return None
1384 def get_metadata(self
, uri
, name
): return []
1385 _dummy_feed
= DummyFeed()
1388 """Convert each %20 to a space, etc.
1390 uri
= uri
.replace('#', '/')
1391 if '%' not in uri
: return uri
1392 return re
.sub('%[0-9a-fA-F][0-9a-fA-F]',
1393 lambda match
: chr(int(match
.group(0)[1:], 16)),
1394 uri
).decode('utf-8')
1397 """Convert each space to %20, etc
1399 return re
.sub('[^-_.a-zA-Z0-9]',
1400 lambda match
: '%%%02x' % ord(match
.group(0)),
1401 uri
.encode('utf-8'))
1403 def _pretty_escape(uri
):
1404 """Convert each space to %20, etc
1405 : is preserved and / becomes #. This makes for nicer strings,
1406 and may replace L{escape} everywhere in future.
1408 if os
.name
== "posix":
1409 # Only preserve : on Posix systems
1410 preserveRegex
= '[^-_.a-zA-Z0-9:/]'
1412 # Other OSes may not allow the : character in file names
1413 preserveRegex
= '[^-_.a-zA-Z0-9/]'
1414 return re
.sub(preserveRegex
,
1415 lambda match
: '%%%02x' % ord(match
.group(0)),
1416 uri
.encode('utf-8')).replace('/', '#')
1418 def canonical_iface_uri(uri
):
1419 """If uri is a relative path, convert to an absolute one.
1420 A "file:///foo" URI is converted to "/foo".
1421 An "alias:prog" URI expands to the URI in the 0alias script
1422 Otherwise, return it unmodified.
1424 @raise SafeException: if uri isn't valid
1426 if uri
.startswith('http://') or uri
.startswith('https://'):
1427 if uri
.count("/") < 3:
1428 raise SafeException(_("Missing / after hostname in URI '%s'") % uri
)
1430 elif uri
.startswith('file:///'):
1432 elif uri
.startswith('alias:'):
1433 from zeroinstall
import alias
, support
1434 alias_prog
= uri
[6:]
1435 if not os
.path
.isabs(alias_prog
):
1436 full_path
= support
.find_in_path(alias_prog
)
1438 raise alias
.NotAnAliasScript("Not found in $PATH: " + alias_prog
)
1440 full_path
= alias_prog
1441 interface_uri
, main
= alias
.parse_script(full_path
)
1442 return interface_uri
1444 iface_uri
= os
.path
.realpath(uri
)
1445 if os
.path
.isfile(iface_uri
):
1447 raise SafeException(_("Bad interface name '%(uri)s'.\n"
1448 "(doesn't start with 'http:', and "
1449 "doesn't exist as a local file '%(interface_uri)s' either)") %
1450 {'uri': uri
, 'interface_uri': iface_uri
})
1452 _version_mod_to_value
= {
1460 _version_value_to_mod
= {}
1461 for x
in _version_mod_to_value
: _version_value_to_mod
[_version_mod_to_value
[x
]] = x
1464 _version_re
= re
.compile('-([a-z]*)')
1466 def parse_version(version_string
):
1467 """Convert a version string to an internal representation.
1468 The parsed format can be compared quickly using the standard Python functions.
1469 - Version := DottedList ("-" Mod DottedList?)*
1470 - DottedList := (Integer ("." Integer)*)
1471 @rtype: tuple (opaque)
1472 @raise SafeException: if the string isn't a valid version
1473 @since: 0.24 (moved from L{reader}, from where it is still available):"""
1474 if version_string
is None: return None
1475 parts
= _version_re
.split(version_string
)
1477 del parts
[-1] # Ends with a modifier
1481 raise SafeException(_("Empty version string!"))
1484 for x
in range(0, l
, 2):
1487 parts
[x
] = map(int, parts
[x
].split('.'))
1489 parts
[x
] = [] # (because ''.split('.') == [''], not [])
1490 for x
in range(1, l
, 2):
1491 parts
[x
] = _version_mod_to_value
[parts
[x
]]
1493 except ValueError as ex
:
1494 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string
, 'exception': ex
})
1495 except KeyError as ex
:
1496 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string
, 'exception': ex
})
1498 def format_version(version
):
1499 """Format a parsed version for display. Undoes the effect of L{parse_version}.
1500 @see: L{Implementation.get_version}
1503 version
= version
[:]
1505 for x
in range(0, l
, 2):
1506 version
[x
] = '.'.join(map(str, version
[x
]))
1507 for x
in range(1, l
, 2):
1508 version
[x
] = '-' + _version_value_to_mod
[version
[x
]]
1509 if version
[-1] == '-': del version
[-1]
1510 return ''.join(version
)