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
,
254 value
=None, separator
=None):
256 mode argument added in version 0.28
257 value argument added in version 0.52
261 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
.insert
is not None:
307 env_elem
.setAttributeNS(None, 'insert', self
.insert
)
309 env_elem
.setAttributeNS(None, 'value', self
.value
)
311 env_elem
.setAttributeNS(None, 'default', self
.default
)
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
):
321 self
.mount_point
= mount_point
324 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self
.src
or '.', 'mount_point': self
.mount_point
or '/'}
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
)
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):
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
)
353 return "<Feed from %s>" % self
.uri
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}
368 def __init__(self
, element
):
369 assert isinstance(element
, qdom
.Element
), type(element
) # Use InterfaceDependency instead!
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
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}]
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))
392 self
.interface
= interface
393 if restrictions
is None:
394 self
.restrictions
= []
396 self
.restrictions
= restrictions
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."""
406 class DownloadSource(RetrievalMethod
):
407 """A DownloadSource provides a way to fetch an implementation."""
408 __slots__
= ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
410 def __init__(self
, implementation
, url
, size
, extract
, start_offset
= 0, type = None):
411 self
.implementation
= implementation
414 self
.extract
= extract
415 self
.start_offset
= start_offset
416 self
.type = type # MIME type - see unpack.py
418 def prepare(self
, fetcher
, force
, impl_hint
):
420 class StepCommand(object):
421 __slots__
= ['blocker', '_stream']
424 s
.blocker
, s
._stream
= fetcher
.download_archive(self
, force
= force
, impl_hint
= impl_hint
)
428 unpack
.unpack_archive_over(self
.url
, s
._stream
, tmpdir
,
429 extract
= self
.extract
,
431 start_offset
= self
.start_offset
or 0)
435 class UnpackArchive(object):
436 """An UnpackArchive step provides unpacks/extracts an archive.
438 It can be used inside a Recipe."""
439 __slots__
= ['path', 'extract', 'type']
441 def __init__(self
, path
, extract
, type):
443 self
.extract
= extract
446 def prepare(self
, fetcher
, force
, impl_hint
):
448 class StepCommand(object):
449 __slots__
= ['blocker']
455 path
= os
.path
.join(tmpdir
, self
.path
)
456 stream
= open(path
, 'rb')
459 unpack
.unpack_archive_over(path
, stream
, tmpdir
,
460 extract
= self
.extract
,
468 class Recipe(RetrievalMethod
):
469 """Get an implementation by following a series of steps.
470 @ivar size: the combined download sizes from all the steps
472 @ivar steps: the sequence of steps which must be performed
473 @type steps: [L{RetrievalMethod}]"""
474 __slots__
= ['steps']
479 size
= property(lambda self
: sum([x
.size
for x
in self
.steps
]))
481 class DistributionSource(RetrievalMethod
):
482 """A package that is installed using the distribution's tools (including PackageKit).
483 @ivar install: a function to call to install this package
484 @type install: (L{handler.Handler}) -> L{tasks.Blocker}
485 @ivar package_id: the package name, in a form recognised by the distribution's tools
486 @type package_id: str
487 @ivar size: the download size in bytes
489 @ivar needs_confirmation: whether the user should be asked to confirm before calling install()
490 @type needs_confirmation: bool"""
492 __slots__
= ['package_id', 'size', 'install', 'needs_confirmation']
494 def __init__(self
, package_id
, size
, install
, needs_confirmation
= True):
495 RetrievalMethod
.__init
__(self
)
496 self
.package_id
= package_id
498 self
.install
= install
499 self
.needs_confirmation
= needs_confirmation
501 class Command(object):
502 """A Command is a way of running an Implementation as a program."""
504 __slots__
= ['qdom', '_depends', '_local_dir', '_runner']
506 def __init__(self
, qdom
, local_dir
):
507 """@param qdom: the <command> element
508 @param local_dir: the directory containing the feed (for relative dependencies), or None if not local
510 assert qdom
.name
== 'command', 'not <command>: %s' % qdom
512 self
._local
_dir
= local_dir
515 path
= property(lambda self
: self
.qdom
.attrs
.get("path", None))
517 def _toxml(self
, doc
, prefixes
):
518 return self
.qdom
.toDOM(doc
, prefixes
)
522 if self
._depends
is None:
525 for child
in self
.qdom
.childNodes
:
526 if child
.name
== 'requires':
527 dep
= process_depends(child
, self
._local
_dir
)
529 elif child
.name
== 'runner':
531 raise InvalidInterface(_("Multiple <runner>s in <command>!"))
532 dep
= process_depends(child
, self
._local
_dir
)
535 self
._depends
= depends
538 def get_runner(self
):
539 self
.requires
# (sets _runner)
542 class Implementation(object):
543 """An Implementation is a package which implements an Interface.
544 @ivar download_sources: list of methods of getting this implementation
545 @type download_sources: [L{RetrievalMethod}]
546 @ivar feed: the feed owning this implementation (since 0.32)
547 @type feed: [L{ZeroInstallFeed}]
548 @ivar bindings: how to tell this component where it itself is located (since 0.31)
549 @type bindings: [Binding]
550 @ivar upstream_stability: the stability reported by the packager
551 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged]
552 @ivar user_stability: the stability as set by the user
553 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred]
554 @ivar langs: natural languages supported by this package
556 @ivar requires: interfaces this package depends on
557 @type requires: [L{Dependency}]
558 @ivar commands: ways to execute as a program
559 @type commands: {str: Command}
560 @ivar metadata: extra metadata from the feed
561 @type metadata: {"[URI ]localName": str}
562 @ivar id: a unique identifier for this Implementation
563 @ivar version: a parsed version number
564 @ivar released: release date
565 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path)
566 @type local_path: str | None
567 @ivar requires_root_install: whether the user will need admin rights to use this
568 @type requires_root_install: bool
571 # Note: user_stability shouldn't really be here
573 __slots__
= ['upstream_stability', 'user_stability', 'langs',
574 'requires', 'metadata', 'download_sources', 'commands',
575 'id', 'feed', 'version', 'released', 'bindings', 'machine']
577 def __init__(self
, feed
, id):
581 self
.user_stability
= None
582 self
.upstream_stability
= None
583 self
.metadata
= {} # [URI + " "] + localName -> value
587 self
.download_sources
= []
593 def get_stability(self
):
594 return self
.user_stability
or self
.upstream_stability
or testing
600 return "v%s (%s)" % (self
.get_version(), self
.id)
602 def __cmp__(self
, other
):
603 """Newer versions come first"""
604 d
= cmp(other
.version
, self
.version
)
606 # If the version number is the same, just give a stable sort order, and
607 # ensure that two different implementations don't compare equal.
608 d
= cmp(other
.feed
.url
, self
.feed
.url
)
610 return cmp(other
.id, self
.id)
612 def get_version(self
):
613 """Return the version as a string.
614 @see: L{format_version}
616 return format_version(self
.version
)
618 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
623 requires_root_install
= False
626 """"@deprecated: use commands["run"] instead"""
627 main
= self
.commands
.get("run", None)
631 def _set_main(self
, path
):
632 """"@deprecated: use commands["run"] instead"""
634 if "run" in self
.commands
:
635 del self
.commands
["run"]
637 self
.commands
["run"] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'path': path
}), None)
638 main
= property(_get_main
, _set_main
)
640 def is_available(self
, stores
):
641 """Is this Implementation available locally?
642 (a local implementation, an installed distribution package, or a cached ZeroInstallImplementation)
646 raise NotImplementedError("abstract")
649 def best_download_source(self
):
650 """Return the best download source for this implementation.
651 @rtype: L{model.RetrievalMethod}"""
652 if self
.download_sources
:
653 return self
.download_sources
[0]
656 def retrieve(self
, fetcher
, retrieval_method
, stores
, force
= False):
657 """Retrieve an implementation.
658 @param retrieval_method: a way of getting the implementation (e.g. an Archive or a Recipe)
659 @type retrieval_method: L{model.RetrievalMethod}
660 @param stores: where to store the downloaded implementation
661 @type stores: L{zerostore.Stores}
662 @param force: whether to abort and restart an existing download
663 @rtype: L{tasks.Blocker}"""
664 raise NotImplementedError("abstract")
666 class DistributionImplementation(Implementation
):
667 """An implementation provided by the distribution. Information such as the version
668 comes from the package manager.
670 __slots__
= ['distro', 'installed']
672 def __init__(self
, feed
, id, distro
):
673 assert id.startswith('package:')
674 Implementation
.__init
__(self
, feed
, id)
676 self
.installed
= False
679 def requires_root_install(self
):
680 return not self
.installed
682 def is_available(self
, stores
):
683 return self
.installed
685 def retrieve(self
, fetcher
, retrieval_method
, stores
, force
= False):
686 return retrieval_method
.install(fetcher
.handler
)
689 class ZeroInstallImplementation(Implementation
):
690 """An implementation where all the information comes from Zero Install.
691 @ivar digests: a list of "algorith=value" strings (since 0.45)
694 __slots__
= ['os', 'size', 'digests', 'local_path']
696 def __init__(self
, feed
, id, local_path
):
697 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
698 assert not id.startswith('package:'), id
699 Implementation
.__init
__(self
, feed
, id)
703 self
.local_path
= local_path
706 dependencies
= property(lambda self
: dict([(x
.interface
, x
) for x
in self
.requires
707 if isinstance(x
, InterfaceDependency
)]))
709 def add_download_source(self
, url
, size
, extract
, start_offset
= 0, type = None):
710 """Add a download source."""
711 self
.download_sources
.append(DownloadSource(self
, url
, size
, extract
, start_offset
, type))
713 def set_arch(self
, arch
):
714 self
.os
, self
.machine
= _split_arch(arch
)
715 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
), set_arch
)
717 def is_available(self
, stores
):
718 if self
.local_path
is not None:
719 return os
.path
.exists(self
.local_path
)
721 path
= stores
.lookup_maybe(self
.digests
)
722 return path
is not None
723 return False # (0compile creates fake entries with no digests)
726 def best_digest(self
):
727 """Return the best digest for this implementation
728 @return: tuple (alg, digest) or None"""
729 from zeroinstall
.zerostore
import manifest
731 for digest
in self
.digests
:
732 alg_name
= digest
.split('=', 1)[0]
733 alg
= manifest
.algorithms
.get(alg_name
, None)
734 if alg
and (best_alg
is None or best_alg
.rating
< alg
.rating
):
738 return (best_alg
, best_digest
)
742 def retrieve(self
, fetcher
, retrieval_method
, stores
, force
= False):
743 best
= self
.best_digest
747 raise SafeException(_("No <manifest-digest> given for '%(implementation)s' version %(version)s") %
748 {'implementation': self
.feed
.get_name(), 'version': self
.get_version()})
749 raise SafeException(_("Unknown digest algorithms '%(algorithms)s' for '%(implementation)s' version %(version)s") %
750 {'algorithms': self
.digests
, 'implementation': self
.feed
.get_name(), 'version': self
.get_version()})
752 alg
, required_digest
= best
756 if isinstance(retrieval_method
, DownloadSource
):
757 blocker
, stream
= fetcher
.download_archive(retrieval_method
, force
= force
, impl_hint
= self
)
762 stores
.add_archive_to_cache(required_digest
, stream
, retrieval_method
.url
, retrieval_method
.extract
,
763 type = retrieval_method
.type, start_offset
= retrieval_method
.start_offset
or 0)
764 elif isinstance(retrieval_method
, Recipe
):
765 blocker
= fetcher
.cook(required_digest
, retrieval_method
, stores
, force
, impl_hint
= self
)
769 raise Exception(_("Unknown download type for '%s'") % retrieval_method
)
771 fetcher
.handler
.impl_added_to_store(self
)
775 class Interface(object):
776 """An Interface represents some contract of behaviour.
777 @ivar uri: the URI for this interface.
778 @ivar stability_policy: user's configured policy.
779 Implementations at this level or higher are preferred.
780 Lower levels are used only if there is no other choice.
782 __slots__
= ['uri', 'stability_policy', 'extra_feeds']
784 implementations
= property(lambda self
: self
._main
_feed
.implementations
)
785 name
= property(lambda self
: self
._main
_feed
.name
)
786 description
= property(lambda self
: self
._main
_feed
.description
)
787 summary
= property(lambda self
: self
._main
_feed
.summary
)
788 last_modified
= property(lambda self
: self
._main
_feed
.last_modified
)
789 feeds
= property(lambda self
: self
.extra_feeds
+ self
._main
_feed
.feeds
)
790 metadata
= property(lambda self
: self
._main
_feed
.metadata
)
792 last_checked
= property(lambda self
: self
._main
_feed
.last_checked
)
794 def __init__(self
, uri
):
796 if uri
.startswith('http:') or uri
.startswith('https:') or os
.path
.isabs(uri
):
799 raise SafeException(_("Interface name '%s' doesn't start "
800 "with 'http:' or 'https:'") % uri
)
803 def _get_feed_for(self
):
805 for key
in self
._main
_feed
.feed_for
:
808 feed_for
= property(_get_feed_for
) # Deprecated (used by 0publish)
811 self
.extra_feeds
= []
812 self
.stability_policy
= None
815 from zeroinstall
.injector
.iface_cache
import iface_cache
816 feed
= iface_cache
.get_feed(self
.uri
)
818 return feed
.get_name()
819 return '(' + os
.path
.basename(self
.uri
) + ')'
822 return _("<Interface %s>") % self
.uri
824 def set_stability_policy(self
, new
):
825 assert new
is None or isinstance(new
, Stability
)
826 self
.stability_policy
= new
828 def get_feed(self
, url
):
830 #warnings.warn("use iface_cache.get_feed instead", DeprecationWarning, 2)
831 for x
in self
.extra_feeds
:
834 #return self._main_feed.get_feed(url)
837 def get_metadata(self
, uri
, name
):
838 return self
._main
_feed
.get_metadata(uri
, name
)
841 def _main_feed(self
):
843 #warnings.warn("use the feed instead", DeprecationWarning, 3)
844 from zeroinstall
.injector
import policy
845 iface_cache
= policy
.get_deprecated_singleton_config().iface_cache
846 feed
= iface_cache
.get_feed(self
.uri
)
851 def _merge_attrs(attrs
, item
):
852 """Add each attribute of item to a copy of attrs and return the copy.
853 @type attrs: {str: str}
854 @type item: L{qdom.Element}
859 new
[str(a
)] = item
.attrs
[a
]
862 def _get_long(elem
, attr_name
):
863 val
= elem
.getAttribute(attr_name
)
868 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name
, 'value': val
})
871 class ZeroInstallFeed(object):
872 """A feed lists available implementations of an interface.
873 @ivar url: the URL for this feed
874 @ivar implementations: Implementations in this feed, indexed by ID
875 @type implementations: {str: L{Implementation}}
876 @ivar name: human-friendly name
877 @ivar summaries: short textual description (in various languages, since 0.49)
878 @type summaries: {str: str}
879 @ivar descriptions: long textual description (in various languages, since 0.49)
880 @type descriptions: {str: str}
881 @ivar last_modified: timestamp on signature
882 @ivar last_checked: time feed was last successfully downloaded and updated
883 @ivar feeds: list of <feed> elements in this feed
884 @type feeds: [L{Feed}]
885 @ivar feed_for: interfaces for which this could be a feed
886 @type feed_for: set(str)
887 @ivar metadata: extra elements we didn't understand
889 # _main is deprecated
890 __slots__
= ['url', 'implementations', 'name', 'descriptions', 'first_description', 'summaries', 'first_summary', '_package_implementations',
891 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
893 def __init__(self
, feed_element
, local_path
= None, distro
= None):
894 """Create a feed object from a DOM.
895 @param feed_element: the root element of a feed file
896 @type feed_element: L{qdom.Element}
897 @param local_path: the pathname of this local feed, or None for remote feeds"""
898 self
.implementations
= {}
900 self
.summaries
= {} # { lang: str }
901 self
.first_summary
= None
902 self
.descriptions
= {} # { lang: str }
903 self
.first_description
= None
904 self
.last_modified
= None
906 self
.feed_for
= set()
908 self
.last_checked
= None
909 self
._package
_implementations
= []
911 if distro
is not None:
913 warnings
.warn("distro argument is now ignored", DeprecationWarning, 2)
915 if feed_element
is None:
916 return # XXX subclass?
918 assert feed_element
.name
in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
919 assert feed_element
.uri
== XMLNS_IFACE
, "Wrong namespace on root element: %s" % feed_element
.uri
921 main
= feed_element
.getAttribute('main')
922 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
925 self
.url
= local_path
926 local_dir
= os
.path
.dirname(local_path
)
928 self
.url
= feed_element
.getAttribute('uri')
930 raise InvalidInterface(_("<interface> uri attribute missing"))
931 local_dir
= None # Can't have relative paths
933 min_injector_version
= feed_element
.getAttribute('min-injector-version')
934 if min_injector_version
:
935 if parse_version(min_injector_version
) > parse_version(version
):
936 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
937 "Zero Install, but I am only version %(version)s. "
938 "You can get a newer version from http://0install.net") %
939 {'min_version': min_injector_version
, 'version': version
})
941 for x
in feed_element
.childNodes
:
942 if x
.uri
!= XMLNS_IFACE
:
943 self
.metadata
.append(x
)
946 self
.name
= x
.content
947 elif x
.name
== 'description':
948 if self
.first_description
== None:
949 self
.first_description
= x
.content
950 self
.descriptions
[x
.attrs
.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x
.content
951 elif x
.name
== 'summary':
952 if self
.first_summary
== None:
953 self
.first_summary
= x
.content
954 self
.summaries
[x
.attrs
.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x
.content
955 elif x
.name
== 'feed-for':
956 feed_iface
= x
.getAttribute('interface')
958 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
959 self
.feed_for
.add(feed_iface
)
960 # Bug report from a Debian/stable user that --feed gets the wrong value.
961 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
962 # in case it happens again.
963 debug(_("Is feed-for %s"), feed_iface
)
964 elif x
.name
== 'feed':
965 feed_src
= x
.getAttribute('src')
967 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
968 if feed_src
.startswith('http:') or feed_src
.startswith('https:') or local_path
:
969 langs
= x
.getAttribute('langs')
970 if langs
: langs
= langs
.replace('_', '-')
971 self
.feeds
.append(Feed(feed_src
, x
.getAttribute('arch'), False, langs
= langs
))
973 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src
)
975 self
.metadata
.append(x
)
978 raise InvalidInterface(_("Missing <name> in feed"))
980 raise InvalidInterface(_("Missing <summary> in feed"))
982 def process_group(group
, group_attrs
, base_depends
, base_bindings
, base_commands
):
983 for item
in group
.childNodes
:
984 if item
.uri
!= XMLNS_IFACE
: continue
986 if item
.name
not in ('group', 'implementation', 'package-implementation'):
989 # We've found a group or implementation. Scan for dependencies,
990 # bindings and commands. Doing this here means that:
991 # - We can share the code for groups and implementations here.
992 # - The order doesn't matter, because these get processed first.
993 # A side-effect is that the document root cannot contain
996 depends
= base_depends
[:]
997 bindings
= base_bindings
[:]
998 commands
= base_commands
.copy()
1000 for attr
, command
in [('main', 'run'),
1001 ('self-test', 'test')]:
1002 value
= item
.attrs
.get(attr
, None)
1003 if value
is not None:
1004 commands
[command
] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'path': value
}), None)
1006 for child
in item
.childNodes
:
1007 if child
.uri
!= XMLNS_IFACE
: continue
1008 if child
.name
== 'requires':
1009 dep
= process_depends(child
, local_dir
)
1011 elif child
.name
== 'command':
1012 command_name
= child
.attrs
.get('name', None)
1013 if not command_name
:
1014 raise InvalidInterface('Missing name for <command>')
1015 commands
[command_name
] = Command(child
, local_dir
)
1016 elif child
.name
in binding_names
:
1017 bindings
.append(process_binding(child
))
1019 compile_command
= item
.attrs
.get('http://zero-install.sourceforge.net/2006/namespaces/0compile command')
1020 if compile_command
is not None:
1021 commands
['compile'] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'shell-command': compile_command
}), None)
1023 item_attrs
= _merge_attrs(group_attrs
, item
)
1025 if item
.name
== 'group':
1026 process_group(item
, item_attrs
, depends
, bindings
, commands
)
1027 elif item
.name
== 'implementation':
1028 process_impl(item
, item_attrs
, depends
, bindings
, commands
)
1029 elif item
.name
== 'package-implementation':
1031 warn("A <package-implementation> with dependencies in %s!", self
.url
)
1032 self
._package
_implementations
.append((item
, item_attrs
))
1036 def process_impl(item
, item_attrs
, depends
, bindings
, commands
):
1037 id = item
.getAttribute('id')
1039 raise InvalidInterface(_("Missing 'id' attribute on %s") % item
)
1040 local_path
= item_attrs
.get('local-path')
1041 if local_dir
and local_path
:
1042 abs_local_path
= os
.path
.abspath(os
.path
.join(local_dir
, local_path
))
1043 impl
= ZeroInstallImplementation(self
, id, abs_local_path
)
1044 elif local_dir
and (id.startswith('/') or id.startswith('.')):
1046 id = os
.path
.abspath(os
.path
.join(local_dir
, id))
1047 impl
= ZeroInstallImplementation(self
, id, id)
1049 impl
= ZeroInstallImplementation(self
, id, None)
1051 # In older feeds, the ID was the (single) digest
1052 impl
.digests
.append(id)
1053 if id in self
.implementations
:
1054 warn(_("Duplicate ID '%(id)s' in feed '%(feed)s'"), {'id': id, 'feed': self
})
1055 self
.implementations
[id] = impl
1057 impl
.metadata
= item_attrs
1059 version_mod
= item_attrs
.get('version-modifier', None)
1061 item_attrs
['version'] += version_mod
1062 del item_attrs
['version-modifier']
1063 version
= item_attrs
['version']
1065 raise InvalidInterface(_("Missing version attribute"))
1066 impl
.version
= parse_version(version
)
1068 impl
.commands
= commands
1070 impl
.released
= item_attrs
.get('released', None)
1071 impl
.langs
= item_attrs
.get('langs', '').replace('_', '-')
1073 size
= item
.getAttribute('size')
1075 impl
.size
= int(size
)
1076 impl
.arch
= item_attrs
.get('arch', None)
1078 stability
= stability_levels
[str(item_attrs
['stability'])]
1080 stab
= str(item_attrs
['stability'])
1081 if stab
!= stab
.lower():
1082 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs
.stability
)
1083 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs
['stability'])
1084 if stability
>= preferred
:
1085 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
1086 impl
.upstream_stability
= stability
1088 impl
.bindings
= bindings
1089 impl
.requires
= depends
1091 for elem
in item
.childNodes
:
1092 if elem
.uri
!= XMLNS_IFACE
: continue
1093 if elem
.name
== 'archive':
1094 url
= elem
.getAttribute('href')
1096 raise InvalidInterface(_("Missing href attribute on <archive>"))
1097 size
= elem
.getAttribute('size')
1099 raise InvalidInterface(_("Missing size attribute on <archive>"))
1100 impl
.add_download_source(url
= url
, size
= int(size
),
1101 extract
= elem
.getAttribute('extract'),
1102 start_offset
= _get_long(elem
, 'start-offset'),
1103 type = elem
.getAttribute('type'))
1104 elif elem
.name
== 'manifest-digest':
1105 for aname
, avalue
in elem
.attrs
.iteritems():
1106 if ' ' not in aname
:
1107 impl
.digests
.append('%s=%s' % (aname
, avalue
))
1108 elif elem
.name
== 'recipe':
1110 for recipe_step
in elem
.childNodes
:
1111 if recipe_step
.uri
== XMLNS_IFACE
and recipe_step
.name
== 'archive':
1112 url
= recipe_step
.getAttribute('href')
1114 raise InvalidInterface(_("Missing href attribute on <archive>"))
1115 size
= recipe_step
.getAttribute('size')
1117 raise InvalidInterface(_("Missing size attribute on <archive>"))
1118 recipe
.steps
.append(DownloadSource(None, url
= url
, size
= int(size
),
1119 extract
= recipe_step
.getAttribute('extract'),
1120 start_offset
= _get_long(recipe_step
, 'start-offset'),
1121 type = recipe_step
.getAttribute('type')))
1122 elif recipe_step
.uri
== XMLNS_IFACE
and recipe_step
.name
== 'unpack':
1123 path
= recipe_step
.getAttribute('path')
1125 raise InvalidInterface(_("Missing path attribute on <unpack>"))
1126 recipe
.steps
.append(UnpackArchive(path
= path
,
1127 extract
= recipe_step
.getAttribute('extract'),
1128 type = recipe_step
.getAttribute('type')))
1130 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step
.name
)
1133 impl
.download_sources
.append(recipe
)
1135 root_attrs
= {'stability': 'testing'}
1138 info("Note: @main on document element is deprecated in %s", self
)
1139 root_commands
['run'] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'path': main
}), None)
1140 process_group(feed_element
, root_attrs
, [], [], root_commands
)
1142 def get_distro_feed(self
):
1143 """Does this feed contain any <pacakge-implementation> elements?
1144 i.e. is it worth asking the package manager for more information?
1145 @return: the URL of the virtual feed, or None
1147 if self
._package
_implementations
:
1148 return "distribution:" + self
.url
1151 def get_package_impls(self
, distro
):
1152 """Find the best <pacakge-implementation> element(s) for the given distribution.
1153 @param distro: the distribution to use to rate them
1154 @type distro: L{distro.Distribution}
1155 @return: a list of tuples for the best ranked elements
1161 for item
, item_attrs
in self
._package
_implementations
:
1162 distro_names
= item_attrs
.get('distributions', '')
1163 for distro_name
in distro_names
.split(' '):
1164 score
= distro
.get_score(distro_name
)
1165 if score
> best_score
:
1168 if score
== best_score
:
1169 best_impls
.append((item
, item_attrs
))
1173 return self
.name
or '(' + os
.path
.basename(self
.url
) + ')'
1176 return _("<Feed %s>") % self
.url
1178 def set_stability_policy(self
, new
):
1179 assert new
is None or isinstance(new
, Stability
)
1180 self
.stability_policy
= new
1182 def get_feed(self
, url
):
1183 for x
in self
.feeds
:
1188 def add_metadata(self
, elem
):
1189 self
.metadata
.append(elem
)
1191 def get_metadata(self
, uri
, name
):
1192 """Return a list of interface metadata elements with this name and namespace URI."""
1193 return [m
for m
in self
.metadata
if m
.name
== name
and m
.uri
== uri
]
1197 return _best_language_match(self
.summaries
) or self
.first_summary
1200 def description(self
):
1201 return _best_language_match(self
.descriptions
) or self
.first_description
1203 class DummyFeed(object):
1204 """Temporary class used during API transition."""
1205 last_modified
= None
1207 last_checked
= property(lambda self
: None)
1208 implementations
= property(lambda self
: {})
1209 feeds
= property(lambda self
: [])
1210 summary
= property(lambda self
: '-')
1211 description
= property(lambda self
: '')
1212 def get_name(self
): return self
.name
1213 def get_feed(self
, url
): return None
1214 def get_metadata(self
, uri
, name
): return []
1215 _dummy_feed
= DummyFeed()
1218 """Convert each %20 to a space, etc.
1220 uri
= uri
.replace('#', '/')
1221 if '%' not in uri
: return uri
1222 return re
.sub('%[0-9a-fA-F][0-9a-fA-F]',
1223 lambda match
: chr(int(match
.group(0)[1:], 16)),
1224 uri
).decode('utf-8')
1227 """Convert each space to %20, etc
1229 return re
.sub('[^-_.a-zA-Z0-9]',
1230 lambda match
: '%%%02x' % ord(match
.group(0)),
1231 uri
.encode('utf-8'))
1233 def _pretty_escape(uri
):
1234 """Convert each space to %20, etc
1235 : is preserved and / becomes #. This makes for nicer strings,
1236 and may replace L{escape} everywhere in future.
1238 if os
.name
== "posix":
1239 # Only preserve : on Posix systems
1240 preserveRegex
= '[^-_.a-zA-Z0-9:/]'
1242 # Other OSes may not allow the : character in file names
1243 preserveRegex
= '[^-_.a-zA-Z0-9/]'
1244 return re
.sub(preserveRegex
,
1245 lambda match
: '%%%02x' % ord(match
.group(0)),
1246 uri
.encode('utf-8')).replace('/', '#')
1248 def canonical_iface_uri(uri
):
1249 """If uri is a relative path, convert to an absolute one.
1250 A "file:///foo" URI is converted to "/foo".
1251 An "alias:prog" URI expands to the URI in the 0alias script
1252 Otherwise, return it unmodified.
1254 @raise SafeException: if uri isn't valid
1256 if uri
.startswith('http://') or uri
.startswith('https://'):
1257 if uri
.count("/") < 3:
1258 raise SafeException(_("Missing / after hostname in URI '%s'") % uri
)
1260 elif uri
.startswith('file:///'):
1262 elif uri
.startswith('alias:'):
1263 from zeroinstall
import alias
, support
1264 alias_prog
= uri
[6:]
1265 if not os
.path
.isabs(alias_prog
):
1266 full_path
= support
.find_in_path(alias_prog
)
1268 raise alias
.NotAnAliasScript("Not found in $PATH: " + alias_prog
)
1270 full_path
= alias_prog
1271 interface_uri
, main
= alias
.parse_script(full_path
)
1272 return interface_uri
1274 iface_uri
= os
.path
.realpath(uri
)
1275 if os
.path
.isfile(iface_uri
):
1277 raise SafeException(_("Bad interface name '%(uri)s'.\n"
1278 "(doesn't start with 'http:', and "
1279 "doesn't exist as a local file '%(interface_uri)s' either)") %
1280 {'uri': uri
, 'interface_uri': iface_uri
})
1282 _version_mod_to_value
= {
1290 _version_value_to_mod
= {}
1291 for x
in _version_mod_to_value
: _version_value_to_mod
[_version_mod_to_value
[x
]] = x
1294 _version_re
= re
.compile('-([a-z]*)')
1296 def parse_version(version_string
):
1297 """Convert a version string to an internal representation.
1298 The parsed format can be compared quickly using the standard Python functions.
1299 - Version := DottedList ("-" Mod DottedList?)*
1300 - DottedList := (Integer ("." Integer)*)
1301 @rtype: tuple (opaque)
1302 @raise SafeException: if the string isn't a valid version
1303 @since: 0.24 (moved from L{reader}, from where it is still available):"""
1304 if version_string
is None: return None
1305 parts
= _version_re
.split(version_string
)
1307 del parts
[-1] # Ends with a modifier
1311 raise SafeException(_("Empty version string!"))
1314 for x
in range(0, l
, 2):
1317 parts
[x
] = map(int, parts
[x
].split('.'))
1319 parts
[x
] = [] # (because ''.split('.') == [''], not [])
1320 for x
in range(1, l
, 2):
1321 parts
[x
] = _version_mod_to_value
[parts
[x
]]
1323 except ValueError, ex
:
1324 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string
, 'exception': ex
})
1325 except KeyError, ex
:
1326 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string
, 'exception': ex
})
1328 def format_version(version
):
1329 """Format a parsed version for display. Undoes the effect of L{parse_version}.
1330 @see: L{Implementation.get_version}
1333 version
= version
[:]
1335 for x
in range(0, l
, 2):
1336 version
[x
] = '.'.join(map(str, version
[x
]))
1337 for x
in range(1, l
, 2):
1338 version
[x
] = '-' + _version_value_to_mod
[version
[x
]]
1339 if version
[-1] == '-': del version
[-1]
1340 return ''.join(version
)