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
23 # Element names for bindings in feed files
24 binding_names
= frozenset(['environment', 'overlay'])
26 network_offline
= 'off-line'
27 network_minimal
= 'minimal'
29 network_levels
= (network_offline
, network_minimal
, network_full
)
31 stability_levels
= {} # Name -> Stability
34 'PATH': '/bin:/usr/bin',
35 'XDG_CONFIG_DIRS': '/etc/xdg',
36 'XDG_DATA_DIRS': '/usr/local/share:/usr/share',
39 class InvalidInterface(SafeException
):
40 """Raised when parsing an invalid feed."""
43 def __init__(self
, message
, ex
= None):
46 message
+= "\n\n(exact error: %s)" % ex
48 # Some Python messages have type str but contain UTF-8 sequences.
49 # (e.g. IOException). Adding these to a Unicode 'message' (e.g.
50 # after gettext translation) will cause an error.
52 decoder
= codecs
.lookup('utf-8')
53 decex
= decoder
.decode(str(ex
), errors
= 'replace')[0]
54 message
+= "\n\n(exact error: %s)" % decex
56 SafeException
.__init
__(self
, message
)
58 def __unicode__(self
):
59 if hasattr(SafeException
, '__unicode__'):
62 return _('%s [%s]') % (SafeException
.__unicode
__(self
), self
.feed_url
)
63 return SafeException
.__unicode
__(self
)
65 return unicode(SafeException
.__str
__(self
))
67 def _split_arch(arch
):
68 """Split an arch into an (os, machine) tuple. Either or both parts may be None."""
72 raise SafeException(_("Malformed arch '%s'") % arch
)
74 osys
, machine
= arch
.split('-', 1)
75 if osys
== '*': osys
= None
76 if machine
== '*': machine
= None
79 def _join_arch(osys
, machine
):
80 if osys
== machine
== None: return None
81 return "%s-%s" % (osys
or '*', machine
or '*')
83 def _best_language_match(options
):
84 (language
, encoding
) = locale
.getlocale()
87 # xml:lang uses '-', while LANG uses '_'
88 language
= language
.replace('_', '-')
92 return (options
.get(language
, None) or # Exact match (language+region)
93 options
.get(language
.split('-', 1)[0], None) or # Matching language
94 options
.get('en', None)) # English
96 class Stability(object):
97 """A stability rating. Each implementation has an upstream stability rating and,
98 optionally, a user-set rating."""
99 __slots__
= ['level', 'name', 'description']
100 def __init__(self
, level
, name
, description
):
103 self
.description
= description
104 assert name
not in stability_levels
105 stability_levels
[name
] = self
107 def __cmp__(self
, other
):
108 return cmp(self
.level
, other
.level
)
114 return _("<Stability: %s>") % self
.description
116 def process_binding(e
):
118 if e
.name
== 'environment':
120 None: EnvironmentBinding
.PREPEND
,
121 'prepend': EnvironmentBinding
.PREPEND
,
122 'append': EnvironmentBinding
.APPEND
,
123 'replace': EnvironmentBinding
.REPLACE
,
124 }[e
.getAttribute('mode')]
126 binding
= EnvironmentBinding(e
.getAttribute('name'),
127 insert
= e
.getAttribute('insert'),
128 default
= e
.getAttribute('default'),
129 value
= e
.getAttribute('value'),
131 if not binding
.name
: raise InvalidInterface(_("Missing 'name' in binding"))
132 if binding
.insert
is None and binding
.value
is None:
133 raise InvalidInterface(_("Missing 'insert' or 'value' in binding"))
134 if binding
.insert
is not None and binding
.value
is not None:
135 raise InvalidInterface(_("Binding contains both 'insert' and 'value'"))
137 elif e
.name
== 'overlay':
138 return OverlayBinding(e
.getAttribute('src'), e
.getAttribute('mount-point'))
140 raise Exception(_("Unknown binding type '%s'") % e
.name
)
142 def process_depends(item
, local_feed_dir
):
144 # Note: also called from selections
146 dep_iface
= item
.getAttribute('interface')
148 raise InvalidInterface(_("Missing 'interface' on <%s>") % item
.name
)
149 if dep_iface
.startswith('./'):
151 dep_iface
= os
.path
.abspath(os
.path
.join(local_feed_dir
, dep_iface
))
152 # (updates the element too, in case we write it out again)
153 attrs
['interface'] = dep_iface
155 raise InvalidInterface(_('Relative interface URI "%s" in non-local feed') % dep_iface
)
156 dependency
= InterfaceDependency(dep_iface
, element
= item
)
158 for e
in item
.childNodes
:
159 if e
.uri
!= XMLNS_IFACE
: continue
160 if e
.name
in binding_names
:
161 dependency
.bindings
.append(process_binding(e
))
162 elif e
.name
== 'version':
163 dependency
.restrictions
.append(
164 VersionRangeRestriction(not_before
= parse_version(e
.getAttribute('not-before')),
165 before
= parse_version(e
.getAttribute('before'))))
168 def N_(message
): return message
170 insecure
= Stability(0, N_('insecure'), _('This is a security risk'))
171 buggy
= Stability(5, N_('buggy'), _('Known to have serious bugs'))
172 developer
= Stability(10, N_('developer'), _('Work-in-progress - bugs likely'))
173 testing
= Stability(20, N_('testing'), _('Stability unknown - please test!'))
174 stable
= Stability(30, N_('stable'), _('Tested - no serious problems found'))
175 packaged
= Stability(35, N_('packaged'), _('Supplied by the local package manager'))
176 preferred
= Stability(40, N_('preferred'), _('Best of all - must be set manually'))
180 class Restriction(object):
181 """A Restriction limits the allowed implementations of an Interface."""
184 def meets_restriction(self
, impl
):
185 """Called by the L{solver.Solver} to check whether a particular implementation is acceptable.
186 @return: False if this implementation is not a possibility
189 raise NotImplementedError(_("Abstract"))
191 class VersionRestriction(Restriction
):
192 """Only select implementations with a particular version number.
195 def __init__(self
, version
):
196 """@param version: the required version number
197 @see: L{parse_version}; use this to pre-process the version number
199 self
.version
= version
201 def meets_restriction(self
, impl
):
202 return impl
.version
== self
.version
205 return _("(restriction: version = %s)") % format_version(self
.version
)
207 class VersionRangeRestriction(Restriction
):
208 """Only versions within the given range are acceptable"""
209 __slots__
= ['before', 'not_before']
211 def __init__(self
, before
, not_before
):
212 """@param before: chosen versions must be earlier than this
213 @param not_before: versions must be at least this high
214 @see: L{parse_version}; use this to pre-process the versions
217 self
.not_before
= not_before
219 def meets_restriction(self
, impl
):
220 if self
.not_before
and impl
.version
< self
.not_before
:
222 if self
.before
and impl
.version
>= self
.before
:
227 if self
.not_before
is not None or self
.before
is not None:
229 if self
.not_before
is not None:
230 range += format_version(self
.not_before
) + ' <= '
232 if self
.before
is not None:
233 range += ' < ' + format_version(self
.before
)
236 return _("(restriction: %s)") % range
238 class Binding(object):
239 """Information about how the choice of a Dependency is made known
240 to the application being run."""
242 class EnvironmentBinding(Binding
):
243 """Indicate the chosen implementation using an environment variable."""
244 __slots__
= ['name', 'insert', 'default', 'mode', 'value']
250 def __init__(self
, name
, insert
, default
= None, mode
= PREPEND
, value
=None):
252 mode argument added in version 0.28
253 value argument added in version 0.52
257 self
.default
= default
262 return _("<environ %(name)s %(mode)s %(insert)s %(value)s>") % {'name': self
.name
,'mode': self
.mode
, 'insert': self
.insert
, 'value': self
.value
}
266 def get_value(self
, path
, old_value
):
267 """Calculate the new value of the environment variable after applying this binding.
268 @param path: the path to the selected implementation
269 @param old_value: the current value of the environment variable
270 @return: the new value for the environment variable"""
272 if self
.insert
is not None:
273 extra
= os
.path
.join(path
, self
.insert
)
275 assert self
.value
is not None
278 if self
.mode
== EnvironmentBinding
.REPLACE
:
281 if old_value
is None:
282 old_value
= self
.default
or defaults
.get(self
.name
, None)
283 if old_value
is None:
285 if self
.mode
== EnvironmentBinding
.PREPEND
:
286 return extra
+ os
.pathsep
+ old_value
288 return old_value
+ os
.pathsep
+ extra
290 def _toxml(self
, doc
):
291 """Create a DOM element for this binding.
292 @param doc: document to use to create the element
293 @return: the new element
295 env_elem
= doc
.createElementNS(XMLNS_IFACE
, 'environment')
296 env_elem
.setAttributeNS(None, 'name', self
.name
)
297 if self
.mode
is not None:
298 env_elem
.setAttributeNS(None, 'mode', self
.mode
)
299 if self
.insert
is not None:
300 env_elem
.setAttributeNS(None, 'insert', self
.insert
)
302 env_elem
.setAttributeNS(None, 'value', self
.value
)
304 env_elem
.setAttributeNS(None, 'default', self
.default
)
307 class OverlayBinding(Binding
):
308 """Make the chosen implementation available by overlaying it onto another part of the file-system.
309 This is to support legacy programs which use hard-coded paths."""
310 __slots__
= ['src', 'mount_point']
312 def __init__(self
, src
, mount_point
):
314 self
.mount_point
= mount_point
317 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self
.src
or '.', 'mount_point': self
.mount_point
or '/'}
321 def _toxml(self
, doc
):
322 """Create a DOM element for this binding.
323 @param doc: document to use to create the element
324 @return: the new element
326 env_elem
= doc
.createElementNS(XMLNS_IFACE
, 'overlay')
327 if self
.src
is not None:
328 env_elem
.setAttributeNS(None, 'src', self
.src
)
329 if self
.mount_point
is not None:
330 env_elem
.setAttributeNS(None, 'mount-point', self
.mount_point
)
334 """An interface's feeds are other interfaces whose implementations can also be
335 used as implementations of this interface."""
336 __slots__
= ['uri', 'os', 'machine', 'user_override', 'langs']
337 def __init__(self
, uri
, arch
, user_override
, langs
= None):
339 # This indicates whether the feed comes from the user's overrides
340 # file. If true, writer.py will write it when saving.
341 self
.user_override
= user_override
342 self
.os
, self
.machine
= _split_arch(arch
)
346 return "<Feed from %s>" % self
.uri
349 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
351 class Dependency(object):
352 """A Dependency indicates that an Implementation requires some additional
353 code to function. This is an abstract base class.
354 @ivar qdom: the XML element for this Dependency (since 0launch 0.51)
355 @type qdom: L{qdom.Element}
356 @ivar metadata: any extra attributes from the XML element
357 @type metadata: {str: str}
361 def __init__(self
, element
):
362 assert isinstance(element
, qdom
.Element
), type(element
) # Use InterfaceDependency instead!
367 return self
.qdom
.attrs
369 class InterfaceDependency(Dependency
):
370 """A Dependency on a Zero Install interface.
371 @ivar interface: the interface required by this dependency
373 @ivar restrictions: a list of constraints on acceptable implementations
374 @type restrictions: [L{Restriction}]
375 @ivar bindings: how to make the choice of implementation known
376 @type bindings: [L{Binding}]
379 __slots__
= ['interface', 'restrictions', 'bindings']
381 def __init__(self
, interface
, restrictions
= None, element
= None):
382 Dependency
.__init
__(self
, element
)
383 assert isinstance(interface
, (str, unicode))
385 self
.interface
= interface
386 if restrictions
is None:
387 self
.restrictions
= []
389 self
.restrictions
= restrictions
393 return _("<Dependency on %(interface)s; bindings: %(bindings)s%(restrictions)s>") % {'interface': self
.interface
, 'bindings': self
.bindings
, 'restrictions': self
.restrictions
}
395 class RetrievalMethod(object):
396 """A RetrievalMethod provides a way to fetch an implementation."""
399 class DownloadSource(RetrievalMethod
):
400 """A DownloadSource provides a way to fetch an implementation."""
401 __slots__
= ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
403 def __init__(self
, implementation
, url
, size
, extract
, start_offset
= 0, type = None):
404 self
.implementation
= implementation
407 self
.extract
= extract
408 self
.start_offset
= start_offset
409 self
.type = type # MIME type - see unpack.py
411 class Recipe(RetrievalMethod
):
412 """Get an implementation by following a series of steps.
413 @ivar size: the combined download sizes from all the steps
415 @ivar steps: the sequence of steps which must be performed
416 @type steps: [L{RetrievalMethod}]"""
417 __slots__
= ['steps']
422 size
= property(lambda self
: sum([x
.size
for x
in self
.steps
]))
424 class DistributionSource(RetrievalMethod
):
425 """A package that is installed using the distribution's tools (including PackageKit).
426 @ivar install: a function to call to install this package
427 @type install: (L{handler.Handler}) -> L{tasks.Blocker}
428 @ivar package_id: the package name, in a form recognised by the distribution's tools
429 @type package_id: str
430 @ivar size: the download size in bytes
432 @ivar needs_confirmation: whether the user should be asked to confirm before calling install()
433 @type needs_confirmation: bool"""
435 __slots__
= ['package_id', 'size', 'install', 'needs_confirmation']
437 def __init__(self
, package_id
, size
, install
, needs_confirmation
= True):
438 RetrievalMethod
.__init
__(self
)
439 self
.package_id
= package_id
441 self
.install
= install
442 self
.needs_confirmation
= needs_confirmation
444 class Command(object):
445 """A Command is a way of running an Implementation as a program."""
447 __slots__
= ['qdom', '_depends', '_local_dir', '_runner']
449 def __init__(self
, qdom
, local_dir
):
450 """@param qdom: the <command> element
451 @param local_dir: the directory containing the feed (for relative dependencies), or None if not local
453 assert qdom
.name
== 'command', 'not <command>: %s' % qdom
455 self
._local
_dir
= local_dir
458 path
= property(lambda self
: self
.qdom
.attrs
.get("path", None))
460 def _toxml(self
, doc
, prefixes
):
461 return self
.qdom
.toDOM(doc
, prefixes
)
465 if self
._depends
is None:
468 for child
in self
.qdom
.childNodes
:
469 if child
.name
== 'requires':
470 dep
= process_depends(child
, self
._local
_dir
)
472 elif child
.name
== 'runner':
474 raise InvalidInterface(_("Multiple <runner>s in <command>!"))
475 dep
= process_depends(child
, self
._local
_dir
)
478 self
._depends
= depends
481 def get_runner(self
):
482 self
.requires
# (sets _runner)
485 class Implementation(object):
486 """An Implementation is a package which implements an Interface.
487 @ivar download_sources: list of methods of getting this implementation
488 @type download_sources: [L{RetrievalMethod}]
489 @ivar feed: the feed owning this implementation (since 0.32)
490 @type feed: [L{ZeroInstallFeed}]
491 @ivar bindings: how to tell this component where it itself is located (since 0.31)
492 @type bindings: [Binding]
493 @ivar upstream_stability: the stability reported by the packager
494 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged]
495 @ivar user_stability: the stability as set by the user
496 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred]
497 @ivar langs: natural languages supported by this package
499 @ivar requires: interfaces this package depends on
500 @type requires: [L{Dependency}]
501 @ivar commands: ways to execute as a program
502 @type commands: {str: Command}
503 @ivar metadata: extra metadata from the feed
504 @type metadata: {"[URI ]localName": str}
505 @ivar id: a unique identifier for this Implementation
506 @ivar version: a parsed version number
507 @ivar released: release date
508 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path)
509 @type local_path: str | None
510 @ivar requires_root_install: whether the user will need admin rights to use this
511 @type requires_root_install: bool
514 # Note: user_stability shouldn't really be here
516 __slots__
= ['upstream_stability', 'user_stability', 'langs',
517 'requires', 'metadata', 'download_sources', 'commands',
518 'id', 'feed', 'version', 'released', 'bindings', 'machine']
520 def __init__(self
, feed
, id):
524 self
.user_stability
= None
525 self
.upstream_stability
= None
526 self
.metadata
= {} # [URI + " "] + localName -> value
530 self
.download_sources
= []
536 def get_stability(self
):
537 return self
.user_stability
or self
.upstream_stability
or testing
543 return "v%s (%s)" % (self
.get_version(), self
.id)
545 def __cmp__(self
, other
):
546 """Newer versions come first"""
547 d
= cmp(other
.version
, self
.version
)
549 # If the version number is the same, just give a stable sort order, and
550 # ensure that two different implementations don't compare equal.
551 d
= cmp(other
.feed
.url
, self
.feed
.url
)
553 return cmp(other
.id, self
.id)
555 def get_version(self
):
556 """Return the version as a string.
557 @see: L{format_version}
559 return format_version(self
.version
)
561 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
566 requires_root_install
= False
569 """"@deprecated: use commands["run"] instead"""
570 main
= self
.commands
.get("run", None)
574 def _set_main(self
, path
):
575 """"@deprecated: use commands["run"] instead"""
577 if "run" in self
.commands
:
578 del self
.commands
["run"]
580 self
.commands
["run"] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'path': path
}), None)
581 main
= property(_get_main
, _set_main
)
583 def is_available(self
, stores
):
584 """Is this Implementation available locally?
585 (a local implementation, an installed distribution package, or a cached ZeroInstallImplementation)
589 raise NotImplementedError("abstract")
591 class DistributionImplementation(Implementation
):
592 """An implementation provided by the distribution. Information such as the version
593 comes from the package manager.
595 __slots__
= ['distro', 'installed']
597 def __init__(self
, feed
, id, distro
):
598 assert id.startswith('package:')
599 Implementation
.__init
__(self
, feed
, id)
601 self
.installed
= False
604 def requires_root_install(self
):
605 return not self
.installed
607 def is_available(self
, stores
):
608 return self
.installed
610 class ZeroInstallImplementation(Implementation
):
611 """An implementation where all the information comes from Zero Install.
612 @ivar digests: a list of "algorith=value" strings (since 0.45)
615 __slots__
= ['os', 'size', 'digests', 'local_path']
617 def __init__(self
, feed
, id, local_path
):
618 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
619 assert not id.startswith('package:'), id
620 Implementation
.__init
__(self
, feed
, id)
624 self
.local_path
= local_path
627 dependencies
= property(lambda self
: dict([(x
.interface
, x
) for x
in self
.requires
628 if isinstance(x
, InterfaceDependency
)]))
630 def add_download_source(self
, url
, size
, extract
, start_offset
= 0, type = None):
631 """Add a download source."""
632 self
.download_sources
.append(DownloadSource(self
, url
, size
, extract
, start_offset
, type))
634 def set_arch(self
, arch
):
635 self
.os
, self
.machine
= _split_arch(arch
)
636 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
), set_arch
)
638 def is_available(self
, stores
):
639 if self
.local_path
is not None:
640 return os
.path
.exists(self
.local_path
)
642 path
= stores
.lookup_maybe(self
.digests
)
643 return path
is not None
644 return False # (0compile creates fake entries with no digests)
646 class Interface(object):
647 """An Interface represents some contract of behaviour.
648 @ivar uri: the URI for this interface.
649 @ivar stability_policy: user's configured policy.
650 Implementations at this level or higher are preferred.
651 Lower levels are used only if there is no other choice.
653 __slots__
= ['uri', 'stability_policy', 'extra_feeds']
655 implementations
= property(lambda self
: self
._main
_feed
.implementations
)
656 name
= property(lambda self
: self
._main
_feed
.name
)
657 description
= property(lambda self
: self
._main
_feed
.description
)
658 summary
= property(lambda self
: self
._main
_feed
.summary
)
659 last_modified
= property(lambda self
: self
._main
_feed
.last_modified
)
660 feeds
= property(lambda self
: self
.extra_feeds
+ self
._main
_feed
.feeds
)
661 metadata
= property(lambda self
: self
._main
_feed
.metadata
)
663 last_checked
= property(lambda self
: self
._main
_feed
.last_checked
)
665 def __init__(self
, uri
):
667 if uri
.startswith('http:') or uri
.startswith('https:') or os
.path
.isabs(uri
):
670 raise SafeException(_("Interface name '%s' doesn't start "
671 "with 'http:' or 'https:'") % uri
)
674 def _get_feed_for(self
):
676 for key
in self
._main
_feed
.feed_for
:
679 feed_for
= property(_get_feed_for
) # Deprecated (used by 0publish)
682 self
.extra_feeds
= []
683 self
.stability_policy
= None
686 from zeroinstall
.injector
.iface_cache
import iface_cache
687 feed
= iface_cache
.get_feed(self
.uri
)
689 return feed
.get_name()
690 return '(' + os
.path
.basename(self
.uri
) + ')'
693 return _("<Interface %s>") % self
.uri
695 def set_stability_policy(self
, new
):
696 assert new
is None or isinstance(new
, Stability
)
697 self
.stability_policy
= new
699 def get_feed(self
, url
):
701 #warnings.warn("use iface_cache.get_feed instead", DeprecationWarning, 2)
702 for x
in self
.extra_feeds
:
705 #return self._main_feed.get_feed(url)
708 def get_metadata(self
, uri
, name
):
709 return self
._main
_feed
.get_metadata(uri
, name
)
712 def _main_feed(self
):
714 #warnings.warn("use the feed instead", DeprecationWarning, 3)
715 from zeroinstall
.injector
import policy
716 iface_cache
= policy
.get_deprecated_singleton_config().iface_cache
717 feed
= iface_cache
.get_feed(self
.uri
)
722 def _merge_attrs(attrs
, item
):
723 """Add each attribute of item to a copy of attrs and return the copy.
724 @type attrs: {str: str}
725 @type item: L{qdom.Element}
730 new
[str(a
)] = item
.attrs
[a
]
733 def _get_long(elem
, attr_name
):
734 val
= elem
.getAttribute(attr_name
)
739 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name
, 'value': val
})
742 class ZeroInstallFeed(object):
743 """A feed lists available implementations of an interface.
744 @ivar url: the URL for this feed
745 @ivar implementations: Implementations in this feed, indexed by ID
746 @type implementations: {str: L{Implementation}}
747 @ivar name: human-friendly name
748 @ivar summaries: short textual description (in various languages, since 0.49)
749 @type summaries: {str: str}
750 @ivar descriptions: long textual description (in various languages, since 0.49)
751 @type descriptions: {str: str}
752 @ivar last_modified: timestamp on signature
753 @ivar last_checked: time feed was last successfully downloaded and updated
754 @ivar feeds: list of <feed> elements in this feed
755 @type feeds: [L{Feed}]
756 @ivar feed_for: interfaces for which this could be a feed
757 @type feed_for: set(str)
758 @ivar metadata: extra elements we didn't understand
760 # _main is deprecated
761 __slots__
= ['url', 'implementations', 'name', 'descriptions', 'first_description', 'summaries', 'first_summary', '_package_implementations',
762 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
764 def __init__(self
, feed_element
, local_path
= None, distro
= None):
765 """Create a feed object from a DOM.
766 @param feed_element: the root element of a feed file
767 @type feed_element: L{qdom.Element}
768 @param local_path: the pathname of this local feed, or None for remote feeds"""
769 self
.implementations
= {}
771 self
.summaries
= {} # { lang: str }
772 self
.first_summary
= None
773 self
.descriptions
= {} # { lang: str }
774 self
.first_description
= None
775 self
.last_modified
= None
777 self
.feed_for
= set()
779 self
.last_checked
= None
780 self
._package
_implementations
= []
782 if distro
is not None:
784 warnings
.warn("distro argument is now ignored", DeprecationWarning, 2)
786 if feed_element
is None:
787 return # XXX subclass?
789 assert feed_element
.name
in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
790 assert feed_element
.uri
== XMLNS_IFACE
, "Wrong namespace on root element: %s" % feed_element
.uri
792 main
= feed_element
.getAttribute('main')
793 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
796 self
.url
= local_path
797 local_dir
= os
.path
.dirname(local_path
)
799 self
.url
= feed_element
.getAttribute('uri')
801 raise InvalidInterface(_("<interface> uri attribute missing"))
802 local_dir
= None # Can't have relative paths
804 min_injector_version
= feed_element
.getAttribute('min-injector-version')
805 if min_injector_version
:
806 if parse_version(min_injector_version
) > parse_version(version
):
807 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
808 "Zero Install, but I am only version %(version)s. "
809 "You can get a newer version from http://0install.net") %
810 {'min_version': min_injector_version
, 'version': version
})
812 for x
in feed_element
.childNodes
:
813 if x
.uri
!= XMLNS_IFACE
:
814 self
.metadata
.append(x
)
817 self
.name
= x
.content
818 elif x
.name
== 'description':
819 if self
.first_description
== None:
820 self
.first_description
= x
.content
821 self
.descriptions
[x
.attrs
.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x
.content
822 elif x
.name
== 'summary':
823 if self
.first_summary
== None:
824 self
.first_summary
= x
.content
825 self
.summaries
[x
.attrs
.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x
.content
826 elif x
.name
== 'feed-for':
827 feed_iface
= x
.getAttribute('interface')
829 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
830 self
.feed_for
.add(feed_iface
)
831 # Bug report from a Debian/stable user that --feed gets the wrong value.
832 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
833 # in case it happens again.
834 debug(_("Is feed-for %s"), feed_iface
)
835 elif x
.name
== 'feed':
836 feed_src
= x
.getAttribute('src')
838 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
839 if feed_src
.startswith('http:') or feed_src
.startswith('https:') or local_path
:
840 langs
= x
.getAttribute('langs')
841 if langs
: langs
= langs
.replace('_', '-')
842 self
.feeds
.append(Feed(feed_src
, x
.getAttribute('arch'), False, langs
= langs
))
844 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src
)
846 self
.metadata
.append(x
)
849 raise InvalidInterface(_("Missing <name> in feed"))
851 raise InvalidInterface(_("Missing <summary> in feed"))
853 def process_group(group
, group_attrs
, base_depends
, base_bindings
, base_commands
):
854 for item
in group
.childNodes
:
855 if item
.uri
!= XMLNS_IFACE
: continue
857 if item
.name
not in ('group', 'implementation', 'package-implementation'):
860 # We've found a group or implementation. Scan for dependencies,
861 # bindings and commands. Doing this here means that:
862 # - We can share the code for groups and implementations here.
863 # - The order doesn't matter, because these get processed first.
864 # A side-effect is that the document root cannot contain
867 depends
= base_depends
[:]
868 bindings
= base_bindings
[:]
869 commands
= base_commands
.copy()
871 for attr
, command
in [('main', 'run'),
872 ('self-test', 'test')]:
873 value
= item
.attrs
.get(attr
, None)
874 if value
is not None:
875 commands
[command
] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'path': value
}), None)
877 for child
in item
.childNodes
:
878 if child
.uri
!= XMLNS_IFACE
: continue
879 if child
.name
== 'requires':
880 dep
= process_depends(child
, local_dir
)
882 elif child
.name
== 'command':
883 command_name
= child
.attrs
.get('name', None)
885 raise InvalidInterface('Missing name for <command>')
886 commands
[command_name
] = Command(child
, local_dir
)
887 elif child
.name
in binding_names
:
888 bindings
.append(process_binding(child
))
890 compile_command
= item
.attrs
.get('http://zero-install.sourceforge.net/2006/namespaces/0compile command')
891 if compile_command
is not None:
892 commands
['compile'] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'shell-command': compile_command
}), None)
894 item_attrs
= _merge_attrs(group_attrs
, item
)
896 if item
.name
== 'group':
897 process_group(item
, item_attrs
, depends
, bindings
, commands
)
898 elif item
.name
== 'implementation':
899 process_impl(item
, item_attrs
, depends
, bindings
, commands
)
900 elif item
.name
== 'package-implementation':
902 warn("A <package-implementation> with dependencies in %s!", self
.url
)
903 self
._package
_implementations
.append((item
, item_attrs
))
907 def process_impl(item
, item_attrs
, depends
, bindings
, commands
):
908 id = item
.getAttribute('id')
910 raise InvalidInterface(_("Missing 'id' attribute on %s") % item
)
911 local_path
= item_attrs
.get('local-path')
912 if local_dir
and local_path
:
913 abs_local_path
= os
.path
.abspath(os
.path
.join(local_dir
, local_path
))
914 impl
= ZeroInstallImplementation(self
, id, abs_local_path
)
915 elif local_dir
and (id.startswith('/') or id.startswith('.')):
917 id = os
.path
.abspath(os
.path
.join(local_dir
, id))
918 impl
= ZeroInstallImplementation(self
, id, id)
920 impl
= ZeroInstallImplementation(self
, id, None)
922 # In older feeds, the ID was the (single) digest
923 impl
.digests
.append(id)
924 if id in self
.implementations
:
925 warn(_("Duplicate ID '%(id)s' in feed '%(feed)s'"), {'id': id, 'feed': self
})
926 self
.implementations
[id] = impl
928 impl
.metadata
= item_attrs
930 version_mod
= item_attrs
.get('version-modifier', None)
932 item_attrs
['version'] += version_mod
933 del item_attrs
['version-modifier']
934 version
= item_attrs
['version']
936 raise InvalidInterface(_("Missing version attribute"))
937 impl
.version
= parse_version(version
)
939 impl
.commands
= commands
941 impl
.released
= item_attrs
.get('released', None)
942 impl
.langs
= item_attrs
.get('langs', '').replace('_', '-')
944 size
= item
.getAttribute('size')
946 impl
.size
= int(size
)
947 impl
.arch
= item_attrs
.get('arch', None)
949 stability
= stability_levels
[str(item_attrs
['stability'])]
951 stab
= str(item_attrs
['stability'])
952 if stab
!= stab
.lower():
953 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs
.stability
)
954 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs
['stability'])
955 if stability
>= preferred
:
956 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
957 impl
.upstream_stability
= stability
959 impl
.bindings
= bindings
960 impl
.requires
= depends
962 for elem
in item
.childNodes
:
963 if elem
.uri
!= XMLNS_IFACE
: continue
964 if elem
.name
== 'archive':
965 url
= elem
.getAttribute('href')
967 raise InvalidInterface(_("Missing href attribute on <archive>"))
968 size
= elem
.getAttribute('size')
970 raise InvalidInterface(_("Missing size attribute on <archive>"))
971 impl
.add_download_source(url
= url
, size
= int(size
),
972 extract
= elem
.getAttribute('extract'),
973 start_offset
= _get_long(elem
, 'start-offset'),
974 type = elem
.getAttribute('type'))
975 elif elem
.name
== 'manifest-digest':
976 for aname
, avalue
in elem
.attrs
.iteritems():
978 impl
.digests
.append('%s=%s' % (aname
, avalue
))
979 elif elem
.name
== 'recipe':
981 for recipe_step
in elem
.childNodes
:
982 if recipe_step
.uri
== XMLNS_IFACE
and recipe_step
.name
== 'archive':
983 url
= recipe_step
.getAttribute('href')
985 raise InvalidInterface(_("Missing href attribute on <archive>"))
986 size
= recipe_step
.getAttribute('size')
988 raise InvalidInterface(_("Missing size attribute on <archive>"))
989 recipe
.steps
.append(DownloadSource(None, url
= url
, size
= int(size
),
990 extract
= recipe_step
.getAttribute('extract'),
991 start_offset
= _get_long(recipe_step
, 'start-offset'),
992 type = recipe_step
.getAttribute('type')))
994 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step
.name
)
997 impl
.download_sources
.append(recipe
)
999 root_attrs
= {'stability': 'testing'}
1002 info("Note: @main on document element is deprecated in %s", self
)
1003 root_commands
['run'] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'path': main
}), None)
1004 process_group(feed_element
, root_attrs
, [], [], root_commands
)
1006 def get_distro_feed(self
):
1007 """Does this feed contain any <pacakge-implementation> elements?
1008 i.e. is it worth asking the package manager for more information?
1009 @return: the URL of the virtual feed, or None
1011 if self
._package
_implementations
:
1012 return "distribution:" + self
.url
1015 def get_package_impls(self
, distro
):
1016 """Find the best <pacakge-implementation> element(s) for the given distribution.
1017 @param distro: the distribution to use to rate them
1018 @type distro: L{distro.Distribution}
1019 @return: a list of tuples for the best ranked elements
1025 for item
, item_attrs
in self
._package
_implementations
:
1026 distro_names
= item_attrs
.get('distributions', '')
1027 for distro_name
in distro_names
.split(' '):
1028 score
= distro
.get_score(distro_name
)
1029 if score
> best_score
:
1032 if score
== best_score
:
1033 best_impls
.append((item
, item_attrs
))
1037 return self
.name
or '(' + os
.path
.basename(self
.url
) + ')'
1040 return _("<Feed %s>") % self
.url
1042 def set_stability_policy(self
, new
):
1043 assert new
is None or isinstance(new
, Stability
)
1044 self
.stability_policy
= new
1046 def get_feed(self
, url
):
1047 for x
in self
.feeds
:
1052 def add_metadata(self
, elem
):
1053 self
.metadata
.append(elem
)
1055 def get_metadata(self
, uri
, name
):
1056 """Return a list of interface metadata elements with this name and namespace URI."""
1057 return [m
for m
in self
.metadata
if m
.name
== name
and m
.uri
== uri
]
1061 return _best_language_match(self
.summaries
) or self
.first_summary
1064 def description(self
):
1065 return _best_language_match(self
.descriptions
) or self
.first_description
1067 class DummyFeed(object):
1068 """Temporary class used during API transition."""
1069 last_modified
= None
1071 last_checked
= property(lambda self
: None)
1072 implementations
= property(lambda self
: {})
1073 feeds
= property(lambda self
: [])
1074 summary
= property(lambda self
: '-')
1075 description
= property(lambda self
: '')
1076 def get_name(self
): return self
.name
1077 def get_feed(self
, url
): return None
1078 def get_metadata(self
, uri
, name
): return []
1079 _dummy_feed
= DummyFeed()
1082 """Convert each %20 to a space, etc.
1084 uri
= uri
.replace('#', '/')
1085 if '%' not in uri
: return uri
1086 return re
.sub('%[0-9a-fA-F][0-9a-fA-F]',
1087 lambda match
: chr(int(match
.group(0)[1:], 16)),
1088 uri
).decode('utf-8')
1091 """Convert each space to %20, etc
1093 return re
.sub('[^-_.a-zA-Z0-9]',
1094 lambda match
: '%%%02x' % ord(match
.group(0)),
1095 uri
.encode('utf-8'))
1097 def _pretty_escape(uri
):
1098 """Convert each space to %20, etc
1099 : is preserved and / becomes #. This makes for nicer strings,
1100 and may replace L{escape} everywhere in future.
1102 if os
.name
== "posix":
1103 # Only preserve : on Posix systems
1104 preserveRegex
= '[^-_.a-zA-Z0-9:/]'
1106 # Other OSes may not allow the : character in file names
1107 preserveRegex
= '[^-_.a-zA-Z0-9/]'
1108 return re
.sub(preserveRegex
,
1109 lambda match
: '%%%02x' % ord(match
.group(0)),
1110 uri
.encode('utf-8')).replace('/', '#')
1112 def canonical_iface_uri(uri
):
1113 """If uri is a relative path, convert to an absolute one.
1114 A "file:///foo" URI is converted to "/foo".
1115 An "alias:prog" URI expands to the URI in the 0alias script
1116 Otherwise, return it unmodified.
1118 @raise SafeException: if uri isn't valid
1120 if uri
.startswith('http://') or uri
.startswith('https://'):
1121 if uri
.count("/") < 3:
1122 raise SafeException(_("Missing / after hostname in URI '%s'") % uri
)
1124 elif uri
.startswith('file:///'):
1126 elif uri
.startswith('alias:'):
1127 from zeroinstall
import alias
, support
1128 alias_prog
= uri
[6:]
1129 if not os
.path
.isabs(alias_prog
):
1130 full_path
= support
.find_in_path(alias_prog
)
1132 raise alias
.NotAnAliasScript("Not found in $PATH: " + alias_prog
)
1134 full_path
= alias_prog
1135 interface_uri
, main
= alias
.parse_script(full_path
)
1136 return interface_uri
1138 iface_uri
= os
.path
.realpath(uri
)
1139 if os
.path
.isfile(iface_uri
):
1141 raise SafeException(_("Bad interface name '%(uri)s'.\n"
1142 "(doesn't start with 'http:', and "
1143 "doesn't exist as a local file '%(interface_uri)s' either)") %
1144 {'uri': uri
, 'interface_uri': iface_uri
})
1146 _version_mod_to_value
= {
1154 _version_value_to_mod
= {}
1155 for x
in _version_mod_to_value
: _version_value_to_mod
[_version_mod_to_value
[x
]] = x
1158 _version_re
= re
.compile('-([a-z]*)')
1160 def parse_version(version_string
):
1161 """Convert a version string to an internal representation.
1162 The parsed format can be compared quickly using the standard Python functions.
1163 - Version := DottedList ("-" Mod DottedList?)*
1164 - DottedList := (Integer ("." Integer)*)
1165 @rtype: tuple (opaque)
1166 @raise SafeException: if the string isn't a valid version
1167 @since: 0.24 (moved from L{reader}, from where it is still available):"""
1168 if version_string
is None: return None
1169 parts
= _version_re
.split(version_string
)
1171 del parts
[-1] # Ends with a modifier
1175 raise SafeException(_("Empty version string!"))
1178 for x
in range(0, l
, 2):
1181 parts
[x
] = map(int, parts
[x
].split('.'))
1183 parts
[x
] = [] # (because ''.split('.') == [''], not [])
1184 for x
in range(1, l
, 2):
1185 parts
[x
] = _version_mod_to_value
[parts
[x
]]
1187 except ValueError, ex
:
1188 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string
, 'exception': ex
})
1189 except KeyError, ex
:
1190 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string
, 'exception': ex
})
1192 def format_version(version
):
1193 """Format a parsed version for display. Undoes the effect of L{parse_version}.
1194 @see: L{Implementation.get_version}
1197 version
= version
[:]
1199 for x
in range(0, l
, 2):
1200 version
[x
] = '.'.join(map(str, version
[x
]))
1201 for x
in range(1, l
, 2):
1202 version
[x
] = '-' + _version_value_to_mod
[version
[x
]]
1203 if version
[-1] == '-': del version
[-1]
1204 return ''.join(version
)