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 separator
= e
.getAttribute('separator'))
132 if not binding
.name
: raise InvalidInterface(_("Missing 'name' in binding"))
133 if binding
.insert
is None and binding
.value
is None:
134 raise InvalidInterface(_("Missing 'insert' or 'value' in binding"))
135 if binding
.insert
is not None and binding
.value
is not None:
136 raise InvalidInterface(_("Binding contains both 'insert' and 'value'"))
138 elif e
.name
== 'overlay':
139 return OverlayBinding(e
.getAttribute('src'), e
.getAttribute('mount-point'))
141 raise Exception(_("Unknown binding type '%s'") % e
.name
)
143 def process_depends(item
, local_feed_dir
):
145 # Note: also called from selections
147 dep_iface
= item
.getAttribute('interface')
149 raise InvalidInterface(_("Missing 'interface' on <%s>") % item
.name
)
150 if dep_iface
.startswith('./'):
152 dep_iface
= os
.path
.abspath(os
.path
.join(local_feed_dir
, dep_iface
))
153 # (updates the element too, in case we write it out again)
154 attrs
['interface'] = dep_iface
156 raise InvalidInterface(_('Relative interface URI "%s" in non-local feed') % dep_iface
)
157 dependency
= InterfaceDependency(dep_iface
, element
= item
)
159 for e
in item
.childNodes
:
160 if e
.uri
!= XMLNS_IFACE
: continue
161 if e
.name
in binding_names
:
162 dependency
.bindings
.append(process_binding(e
))
163 elif e
.name
== 'version':
164 dependency
.restrictions
.append(
165 VersionRangeRestriction(not_before
= parse_version(e
.getAttribute('not-before')),
166 before
= parse_version(e
.getAttribute('before'))))
169 def N_(message
): return message
171 insecure
= Stability(0, N_('insecure'), _('This is a security risk'))
172 buggy
= Stability(5, N_('buggy'), _('Known to have serious bugs'))
173 developer
= Stability(10, N_('developer'), _('Work-in-progress - bugs likely'))
174 testing
= Stability(20, N_('testing'), _('Stability unknown - please test!'))
175 stable
= Stability(30, N_('stable'), _('Tested - no serious problems found'))
176 packaged
= Stability(35, N_('packaged'), _('Supplied by the local package manager'))
177 preferred
= Stability(40, N_('preferred'), _('Best of all - must be set manually'))
181 class Restriction(object):
182 """A Restriction limits the allowed implementations of an Interface."""
185 def meets_restriction(self
, impl
):
186 """Called by the L{solver.Solver} to check whether a particular implementation is acceptable.
187 @return: False if this implementation is not a possibility
190 raise NotImplementedError(_("Abstract"))
192 class VersionRestriction(Restriction
):
193 """Only select implementations with a particular version number.
196 def __init__(self
, version
):
197 """@param version: the required version number
198 @see: L{parse_version}; use this to pre-process the version number
200 self
.version
= version
202 def meets_restriction(self
, impl
):
203 return impl
.version
== self
.version
206 return _("(restriction: version = %s)") % format_version(self
.version
)
208 class VersionRangeRestriction(Restriction
):
209 """Only versions within the given range are acceptable"""
210 __slots__
= ['before', 'not_before']
212 def __init__(self
, before
, not_before
):
213 """@param before: chosen versions must be earlier than this
214 @param not_before: versions must be at least this high
215 @see: L{parse_version}; use this to pre-process the versions
218 self
.not_before
= not_before
220 def meets_restriction(self
, impl
):
221 if self
.not_before
and impl
.version
< self
.not_before
:
223 if self
.before
and impl
.version
>= self
.before
:
228 if self
.not_before
is not None or self
.before
is not None:
230 if self
.not_before
is not None:
231 range += format_version(self
.not_before
) + ' <= '
233 if self
.before
is not None:
234 range += ' < ' + format_version(self
.before
)
237 return _("(restriction: %s)") % range
239 class Binding(object):
240 """Information about how the choice of a Dependency is made known
241 to the application being run."""
243 class EnvironmentBinding(Binding
):
244 """Indicate the chosen implementation using an environment variable."""
245 __slots__
= ['name', 'insert', 'default', 'mode', 'value']
251 def __init__(self
, name
, insert
, default
= None, mode
= PREPEND
, value
=None, separator
=None):
253 mode argument added in version 0.28
254 value argument added in version 0.52
258 self
.default
= default
261 if separator
is None:
262 self
.separator
= os
.pathsep
264 self
.separator
= separator
268 return _("<environ %(name)s %(mode)s %(insert)s %(value)s>") % {'name': self
.name
,'mode': self
.mode
, 'insert': self
.insert
, 'value': self
.value
}
272 def get_value(self
, path
, old_value
):
273 """Calculate the new value of the environment variable after applying this binding.
274 @param path: the path to the selected implementation
275 @param old_value: the current value of the environment variable
276 @return: the new value for the environment variable"""
278 if self
.insert
is not None:
279 extra
= os
.path
.join(path
, self
.insert
)
281 assert self
.value
is not None
284 if self
.mode
== EnvironmentBinding
.REPLACE
:
287 if old_value
is None:
288 old_value
= self
.default
or defaults
.get(self
.name
, None)
289 if old_value
is None:
291 if self
.mode
== EnvironmentBinding
.PREPEND
:
292 return extra
+ self
.separator
+ old_value
294 return old_value
+ self
.separator
+ extra
296 def _toxml(self
, doc
):
297 """Create a DOM element for this binding.
298 @param doc: document to use to create the element
299 @return: the new element
301 env_elem
= doc
.createElementNS(XMLNS_IFACE
, 'environment')
302 env_elem
.setAttributeNS(None, 'name', self
.name
)
303 if self
.mode
is not None:
304 env_elem
.setAttributeNS(None, 'mode', self
.mode
)
305 if self
.insert
is not None:
306 env_elem
.setAttributeNS(None, 'insert', self
.insert
)
308 env_elem
.setAttributeNS(None, 'value', self
.value
)
310 env_elem
.setAttributeNS(None, 'default', self
.default
)
312 env_elem
.setAttributeNS(None, 'separator', self
.separator
)
315 class OverlayBinding(Binding
):
316 """Make the chosen implementation available by overlaying it onto another part of the file-system.
317 This is to support legacy programs which use hard-coded paths."""
318 __slots__
= ['src', 'mount_point']
320 def __init__(self
, src
, mount_point
):
322 self
.mount_point
= mount_point
325 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self
.src
or '.', 'mount_point': self
.mount_point
or '/'}
329 def _toxml(self
, doc
):
330 """Create a DOM element for this binding.
331 @param doc: document to use to create the element
332 @return: the new element
334 env_elem
= doc
.createElementNS(XMLNS_IFACE
, 'overlay')
335 if self
.src
is not None:
336 env_elem
.setAttributeNS(None, 'src', self
.src
)
337 if self
.mount_point
is not None:
338 env_elem
.setAttributeNS(None, 'mount-point', self
.mount_point
)
342 """An interface's feeds are other interfaces whose implementations can also be
343 used as implementations of this interface."""
344 __slots__
= ['uri', 'os', 'machine', 'user_override', 'langs']
345 def __init__(self
, uri
, arch
, user_override
, langs
= None):
347 # This indicates whether the feed comes from the user's overrides
348 # file. If true, writer.py will write it when saving.
349 self
.user_override
= user_override
350 self
.os
, self
.machine
= _split_arch(arch
)
354 return "<Feed from %s>" % self
.uri
357 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
359 class Dependency(object):
360 """A Dependency indicates that an Implementation requires some additional
361 code to function. This is an abstract base class.
362 @ivar qdom: the XML element for this Dependency (since 0launch 0.51)
363 @type qdom: L{qdom.Element}
364 @ivar metadata: any extra attributes from the XML element
365 @type metadata: {str: str}
369 Essential
= "essential"
370 Recommended
= "recommended"
372 def __init__(self
, element
):
373 assert isinstance(element
, qdom
.Element
), type(element
) # Use InterfaceDependency instead!
378 return self
.qdom
.attrs
381 def importance(self
):
382 return self
.qdom
.getAttribute("importance") or Dependency
.Essential
384 class InterfaceDependency(Dependency
):
385 """A Dependency on a Zero Install interface.
386 @ivar interface: the interface required by this dependency
388 @ivar restrictions: a list of constraints on acceptable implementations
389 @type restrictions: [L{Restriction}]
390 @ivar bindings: how to make the choice of implementation known
391 @type bindings: [L{Binding}]
394 __slots__
= ['interface', 'restrictions', 'bindings']
396 def __init__(self
, interface
, restrictions
= None, element
= None):
397 Dependency
.__init
__(self
, element
)
398 assert isinstance(interface
, (str, unicode))
400 self
.interface
= interface
401 if restrictions
is None:
402 self
.restrictions
= []
404 self
.restrictions
= restrictions
408 return _("<Dependency on %(interface)s; bindings: %(bindings)s%(restrictions)s>") % {'interface': self
.interface
, 'bindings': self
.bindings
, 'restrictions': self
.restrictions
}
412 return self
.qdom
.getAttribute("command") or ('run' if self
.qdom
.name
== 'runner' else None)
415 class RetrievalMethod(object):
416 """A RetrievalMethod provides a way to fetch an implementation."""
419 class DownloadSource(RetrievalMethod
):
420 """A DownloadSource provides a way to fetch an implementation."""
421 __slots__
= ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
423 def __init__(self
, implementation
, url
, size
, extract
, start_offset
= 0, type = None):
424 self
.implementation
= implementation
427 self
.extract
= extract
428 self
.start_offset
= start_offset
429 self
.type = type # MIME type - see unpack.py
431 class Recipe(RetrievalMethod
):
432 """Get an implementation by following a series of steps.
433 @ivar size: the combined download sizes from all the steps
435 @ivar steps: the sequence of steps which must be performed
436 @type steps: [L{RetrievalMethod}]"""
437 __slots__
= ['steps']
442 size
= property(lambda self
: sum([x
.size
for x
in self
.steps
]))
444 class DistributionSource(RetrievalMethod
):
445 """A package that is installed using the distribution's tools (including PackageKit).
446 @ivar install: a function to call to install this package
447 @type install: (L{handler.Handler}) -> L{tasks.Blocker}
448 @ivar package_id: the package name, in a form recognised by the distribution's tools
449 @type package_id: str
450 @ivar size: the download size in bytes
452 @ivar needs_confirmation: whether the user should be asked to confirm before calling install()
453 @type needs_confirmation: bool"""
455 __slots__
= ['package_id', 'size', 'install', 'needs_confirmation']
457 def __init__(self
, package_id
, size
, install
, needs_confirmation
= True):
458 RetrievalMethod
.__init
__(self
)
459 self
.package_id
= package_id
461 self
.install
= install
462 self
.needs_confirmation
= needs_confirmation
464 class Command(object):
465 """A Command is a way of running an Implementation as a program."""
467 __slots__
= ['qdom', '_depends', '_local_dir', '_runner']
469 def __init__(self
, qdom
, local_dir
):
470 """@param qdom: the <command> element
471 @param local_dir: the directory containing the feed (for relative dependencies), or None if not local
473 assert qdom
.name
== 'command', 'not <command>: %s' % qdom
475 self
._local
_dir
= local_dir
478 path
= property(lambda self
: self
.qdom
.attrs
.get("path", None))
480 def _toxml(self
, doc
, prefixes
):
481 return self
.qdom
.toDOM(doc
, prefixes
)
485 if self
._depends
is None:
488 for child
in self
.qdom
.childNodes
:
489 if child
.name
== 'requires':
490 dep
= process_depends(child
, self
._local
_dir
)
492 elif child
.name
== 'runner':
494 raise InvalidInterface(_("Multiple <runner>s in <command>!"))
495 dep
= process_depends(child
, self
._local
_dir
)
498 self
._depends
= depends
501 def get_runner(self
):
502 self
.requires
# (sets _runner)
506 return str(self
.qdom
)
508 class Implementation(object):
509 """An Implementation is a package which implements an Interface.
510 @ivar download_sources: list of methods of getting this implementation
511 @type download_sources: [L{RetrievalMethod}]
512 @ivar feed: the feed owning this implementation (since 0.32)
513 @type feed: [L{ZeroInstallFeed}]
514 @ivar bindings: how to tell this component where it itself is located (since 0.31)
515 @type bindings: [Binding]
516 @ivar upstream_stability: the stability reported by the packager
517 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged]
518 @ivar user_stability: the stability as set by the user
519 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred]
520 @ivar langs: natural languages supported by this package
522 @ivar requires: interfaces this package depends on
523 @type requires: [L{Dependency}]
524 @ivar commands: ways to execute as a program
525 @type commands: {str: Command}
526 @ivar metadata: extra metadata from the feed
527 @type metadata: {"[URI ]localName": str}
528 @ivar id: a unique identifier for this Implementation
529 @ivar version: a parsed version number
530 @ivar released: release date
531 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path)
532 @type local_path: str | None
533 @ivar requires_root_install: whether the user will need admin rights to use this
534 @type requires_root_install: bool
537 # Note: user_stability shouldn't really be here
539 __slots__
= ['upstream_stability', 'user_stability', 'langs',
540 'requires', 'metadata', 'download_sources', 'commands',
541 'id', 'feed', 'version', 'released', 'bindings', 'machine']
543 def __init__(self
, feed
, id):
547 self
.user_stability
= None
548 self
.upstream_stability
= None
549 self
.metadata
= {} # [URI + " "] + localName -> value
553 self
.download_sources
= []
559 def get_stability(self
):
560 return self
.user_stability
or self
.upstream_stability
or testing
566 return "v%s (%s)" % (self
.get_version(), self
.id)
568 def __cmp__(self
, other
):
569 """Newer versions come first"""
570 d
= cmp(other
.version
, self
.version
)
572 # If the version number is the same, just give a stable sort order, and
573 # ensure that two different implementations don't compare equal.
574 d
= cmp(other
.feed
.url
, self
.feed
.url
)
576 return cmp(other
.id, self
.id)
578 def get_version(self
):
579 """Return the version as a string.
580 @see: L{format_version}
582 return format_version(self
.version
)
584 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
589 requires_root_install
= False
592 """"@deprecated: use commands["run"] instead"""
593 main
= self
.commands
.get("run", None)
597 def _set_main(self
, path
):
598 """"@deprecated: use commands["run"] instead"""
600 if "run" in self
.commands
:
601 del self
.commands
["run"]
603 self
.commands
["run"] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'path': path
}), None)
604 main
= property(_get_main
, _set_main
)
606 def is_available(self
, stores
):
607 """Is this Implementation available locally?
608 (a local implementation, an installed distribution package, or a cached ZeroInstallImplementation)
612 raise NotImplementedError("abstract")
614 class DistributionImplementation(Implementation
):
615 """An implementation provided by the distribution. Information such as the version
616 comes from the package manager.
618 __slots__
= ['distro', 'installed']
620 def __init__(self
, feed
, id, distro
):
621 assert id.startswith('package:')
622 Implementation
.__init
__(self
, feed
, id)
624 self
.installed
= False
627 def requires_root_install(self
):
628 return not self
.installed
630 def is_available(self
, stores
):
631 return self
.installed
633 class ZeroInstallImplementation(Implementation
):
634 """An implementation where all the information comes from Zero Install.
635 @ivar digests: a list of "algorith=value" strings (since 0.45)
638 __slots__
= ['os', 'size', 'digests', 'local_path']
640 def __init__(self
, feed
, id, local_path
):
641 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
642 assert not id.startswith('package:'), id
643 Implementation
.__init
__(self
, feed
, id)
647 self
.local_path
= local_path
650 dependencies
= property(lambda self
: dict([(x
.interface
, x
) for x
in self
.requires
651 if isinstance(x
, InterfaceDependency
)]))
653 def add_download_source(self
, url
, size
, extract
, start_offset
= 0, type = None):
654 """Add a download source."""
655 self
.download_sources
.append(DownloadSource(self
, url
, size
, extract
, start_offset
, type))
657 def set_arch(self
, arch
):
658 self
.os
, self
.machine
= _split_arch(arch
)
659 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
), set_arch
)
661 def is_available(self
, stores
):
662 if self
.local_path
is not None:
663 return os
.path
.exists(self
.local_path
)
665 path
= stores
.lookup_maybe(self
.digests
)
666 return path
is not None
667 return False # (0compile creates fake entries with no digests)
669 class Interface(object):
670 """An Interface represents some contract of behaviour.
671 @ivar uri: the URI for this interface.
672 @ivar stability_policy: user's configured policy.
673 Implementations at this level or higher are preferred.
674 Lower levels are used only if there is no other choice.
676 __slots__
= ['uri', 'stability_policy', 'extra_feeds']
678 implementations
= property(lambda self
: self
._main
_feed
.implementations
)
679 name
= property(lambda self
: self
._main
_feed
.name
)
680 description
= property(lambda self
: self
._main
_feed
.description
)
681 summary
= property(lambda self
: self
._main
_feed
.summary
)
682 last_modified
= property(lambda self
: self
._main
_feed
.last_modified
)
683 feeds
= property(lambda self
: self
.extra_feeds
+ self
._main
_feed
.feeds
)
684 metadata
= property(lambda self
: self
._main
_feed
.metadata
)
686 last_checked
= property(lambda self
: self
._main
_feed
.last_checked
)
688 def __init__(self
, uri
):
690 if uri
.startswith('http:') or uri
.startswith('https:') or os
.path
.isabs(uri
):
693 raise SafeException(_("Interface name '%s' doesn't start "
694 "with 'http:' or 'https:'") % uri
)
697 def _get_feed_for(self
):
699 for key
in self
._main
_feed
.feed_for
:
702 feed_for
= property(_get_feed_for
) # Deprecated (used by 0publish)
705 self
.extra_feeds
= []
706 self
.stability_policy
= None
709 from zeroinstall
.injector
.iface_cache
import iface_cache
710 feed
= iface_cache
.get_feed(self
.uri
)
712 return feed
.get_name()
713 return '(' + os
.path
.basename(self
.uri
) + ')'
716 return _("<Interface %s>") % self
.uri
718 def set_stability_policy(self
, new
):
719 assert new
is None or isinstance(new
, Stability
)
720 self
.stability_policy
= new
722 def get_feed(self
, url
):
724 #warnings.warn("use iface_cache.get_feed instead", DeprecationWarning, 2)
725 for x
in self
.extra_feeds
:
728 #return self._main_feed.get_feed(url)
731 def get_metadata(self
, uri
, name
):
732 return self
._main
_feed
.get_metadata(uri
, name
)
735 def _main_feed(self
):
737 #warnings.warn("use the feed instead", DeprecationWarning, 3)
738 from zeroinstall
.injector
import policy
739 iface_cache
= policy
.get_deprecated_singleton_config().iface_cache
740 feed
= iface_cache
.get_feed(self
.uri
)
745 def _merge_attrs(attrs
, item
):
746 """Add each attribute of item to a copy of attrs and return the copy.
747 @type attrs: {str: str}
748 @type item: L{qdom.Element}
753 new
[str(a
)] = item
.attrs
[a
]
756 def _get_long(elem
, attr_name
):
757 val
= elem
.getAttribute(attr_name
)
762 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name
, 'value': val
})
765 class ZeroInstallFeed(object):
766 """A feed lists available implementations of an interface.
767 @ivar url: the URL for this feed
768 @ivar implementations: Implementations in this feed, indexed by ID
769 @type implementations: {str: L{Implementation}}
770 @ivar name: human-friendly name
771 @ivar summaries: short textual description (in various languages, since 0.49)
772 @type summaries: {str: str}
773 @ivar descriptions: long textual description (in various languages, since 0.49)
774 @type descriptions: {str: str}
775 @ivar last_modified: timestamp on signature
776 @ivar last_checked: time feed was last successfully downloaded and updated
777 @ivar feeds: list of <feed> elements in this feed
778 @type feeds: [L{Feed}]
779 @ivar feed_for: interfaces for which this could be a feed
780 @type feed_for: set(str)
781 @ivar metadata: extra elements we didn't understand
783 # _main is deprecated
784 __slots__
= ['url', 'implementations', 'name', 'descriptions', 'first_description', 'summaries', 'first_summary', '_package_implementations',
785 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
787 def __init__(self
, feed_element
, local_path
= None, distro
= None):
788 """Create a feed object from a DOM.
789 @param feed_element: the root element of a feed file
790 @type feed_element: L{qdom.Element}
791 @param local_path: the pathname of this local feed, or None for remote feeds"""
792 self
.implementations
= {}
794 self
.summaries
= {} # { lang: str }
795 self
.first_summary
= None
796 self
.descriptions
= {} # { lang: str }
797 self
.first_description
= None
798 self
.last_modified
= None
800 self
.feed_for
= set()
802 self
.last_checked
= None
803 self
._package
_implementations
= []
805 if distro
is not None:
807 warnings
.warn("distro argument is now ignored", DeprecationWarning, 2)
809 if feed_element
is None:
810 return # XXX subclass?
812 assert feed_element
.name
in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
813 assert feed_element
.uri
== XMLNS_IFACE
, "Wrong namespace on root element: %s" % feed_element
.uri
815 main
= feed_element
.getAttribute('main')
816 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
819 self
.url
= local_path
820 local_dir
= os
.path
.dirname(local_path
)
822 self
.url
= feed_element
.getAttribute('uri')
824 raise InvalidInterface(_("<interface> uri attribute missing"))
825 local_dir
= None # Can't have relative paths
827 min_injector_version
= feed_element
.getAttribute('min-injector-version')
828 if min_injector_version
:
829 if parse_version(min_injector_version
) > parse_version(version
):
830 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
831 "Zero Install, but I am only version %(version)s. "
832 "You can get a newer version from http://0install.net") %
833 {'min_version': min_injector_version
, 'version': version
})
835 for x
in feed_element
.childNodes
:
836 if x
.uri
!= XMLNS_IFACE
:
837 self
.metadata
.append(x
)
840 self
.name
= x
.content
841 elif x
.name
== 'description':
842 if self
.first_description
== None:
843 self
.first_description
= x
.content
844 self
.descriptions
[x
.attrs
.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x
.content
845 elif x
.name
== 'summary':
846 if self
.first_summary
== None:
847 self
.first_summary
= x
.content
848 self
.summaries
[x
.attrs
.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x
.content
849 elif x
.name
== 'feed-for':
850 feed_iface
= x
.getAttribute('interface')
852 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
853 self
.feed_for
.add(feed_iface
)
854 # Bug report from a Debian/stable user that --feed gets the wrong value.
855 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
856 # in case it happens again.
857 debug(_("Is feed-for %s"), feed_iface
)
858 elif x
.name
== 'feed':
859 feed_src
= x
.getAttribute('src')
861 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
862 if feed_src
.startswith('http:') or feed_src
.startswith('https:') or local_path
:
863 langs
= x
.getAttribute('langs')
864 if langs
: langs
= langs
.replace('_', '-')
865 self
.feeds
.append(Feed(feed_src
, x
.getAttribute('arch'), False, langs
= langs
))
867 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src
)
869 self
.metadata
.append(x
)
872 raise InvalidInterface(_("Missing <name> in feed"))
874 raise InvalidInterface(_("Missing <summary> in feed"))
876 def process_group(group
, group_attrs
, base_depends
, base_bindings
, base_commands
):
877 for item
in group
.childNodes
:
878 if item
.uri
!= XMLNS_IFACE
: continue
880 if item
.name
not in ('group', 'implementation', 'package-implementation'):
883 # We've found a group or implementation. Scan for dependencies,
884 # bindings and commands. Doing this here means that:
885 # - We can share the code for groups and implementations here.
886 # - The order doesn't matter, because these get processed first.
887 # A side-effect is that the document root cannot contain
890 depends
= base_depends
[:]
891 bindings
= base_bindings
[:]
892 commands
= base_commands
.copy()
894 for attr
, command
in [('main', 'run'),
895 ('self-test', 'test')]:
896 value
= item
.attrs
.get(attr
, None)
897 if value
is not None:
898 commands
[command
] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'name': command
, 'path': value
}), None)
900 for child
in item
.childNodes
:
901 if child
.uri
!= XMLNS_IFACE
: continue
902 if child
.name
== 'requires':
903 dep
= process_depends(child
, local_dir
)
905 elif child
.name
== 'command':
906 command_name
= child
.attrs
.get('name', None)
908 raise InvalidInterface('Missing name for <command>')
909 commands
[command_name
] = Command(child
, local_dir
)
910 elif child
.name
in binding_names
:
911 bindings
.append(process_binding(child
))
913 compile_command
= item
.attrs
.get('http://zero-install.sourceforge.net/2006/namespaces/0compile command')
914 if compile_command
is not None:
915 commands
['compile'] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'name': 'compile', 'shell-command': compile_command
}), None)
917 item_attrs
= _merge_attrs(group_attrs
, item
)
919 if item
.name
== 'group':
920 process_group(item
, item_attrs
, depends
, bindings
, commands
)
921 elif item
.name
== 'implementation':
922 process_impl(item
, item_attrs
, depends
, bindings
, commands
)
923 elif item
.name
== 'package-implementation':
925 warn("A <package-implementation> with dependencies in %s!", self
.url
)
926 self
._package
_implementations
.append((item
, item_attrs
))
930 def process_impl(item
, item_attrs
, depends
, bindings
, commands
):
931 id = item
.getAttribute('id')
933 raise InvalidInterface(_("Missing 'id' attribute on %s") % item
)
934 local_path
= item_attrs
.get('local-path')
935 if local_dir
and local_path
:
936 abs_local_path
= os
.path
.abspath(os
.path
.join(local_dir
, local_path
))
937 impl
= ZeroInstallImplementation(self
, id, abs_local_path
)
938 elif local_dir
and (id.startswith('/') or id.startswith('.')):
940 id = os
.path
.abspath(os
.path
.join(local_dir
, id))
941 impl
= ZeroInstallImplementation(self
, id, id)
943 impl
= ZeroInstallImplementation(self
, id, None)
945 # In older feeds, the ID was the (single) digest
946 impl
.digests
.append(id)
947 if id in self
.implementations
:
948 warn(_("Duplicate ID '%(id)s' in feed '%(feed)s'"), {'id': id, 'feed': self
})
949 self
.implementations
[id] = impl
951 impl
.metadata
= item_attrs
953 version_mod
= item_attrs
.get('version-modifier', None)
955 item_attrs
['version'] += version_mod
956 del item_attrs
['version-modifier']
957 version
= item_attrs
['version']
959 raise InvalidInterface(_("Missing version attribute"))
960 impl
.version
= parse_version(version
)
962 impl
.commands
= commands
964 impl
.released
= item_attrs
.get('released', None)
965 impl
.langs
= item_attrs
.get('langs', '').replace('_', '-')
967 size
= item
.getAttribute('size')
969 impl
.size
= int(size
)
970 impl
.arch
= item_attrs
.get('arch', None)
972 stability
= stability_levels
[str(item_attrs
['stability'])]
974 stab
= str(item_attrs
['stability'])
975 if stab
!= stab
.lower():
976 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs
.stability
)
977 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs
['stability'])
978 if stability
>= preferred
:
979 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
980 impl
.upstream_stability
= stability
982 impl
.bindings
= bindings
983 impl
.requires
= depends
985 for elem
in item
.childNodes
:
986 if elem
.uri
!= XMLNS_IFACE
: continue
987 if elem
.name
== 'archive':
988 url
= elem
.getAttribute('href')
990 raise InvalidInterface(_("Missing href attribute on <archive>"))
991 size
= elem
.getAttribute('size')
993 raise InvalidInterface(_("Missing size attribute on <archive>"))
994 impl
.add_download_source(url
= url
, size
= int(size
),
995 extract
= elem
.getAttribute('extract'),
996 start_offset
= _get_long(elem
, 'start-offset'),
997 type = elem
.getAttribute('type'))
998 elif elem
.name
== 'manifest-digest':
999 for aname
, avalue
in elem
.attrs
.iteritems():
1000 if ' ' not in aname
:
1001 impl
.digests
.append('%s=%s' % (aname
, avalue
))
1002 elif elem
.name
== 'recipe':
1004 for recipe_step
in elem
.childNodes
:
1005 if recipe_step
.uri
== XMLNS_IFACE
and recipe_step
.name
== 'archive':
1006 url
= recipe_step
.getAttribute('href')
1008 raise InvalidInterface(_("Missing href attribute on <archive>"))
1009 size
= recipe_step
.getAttribute('size')
1011 raise InvalidInterface(_("Missing size attribute on <archive>"))
1012 recipe
.steps
.append(DownloadSource(None, url
= url
, size
= int(size
),
1013 extract
= recipe_step
.getAttribute('extract'),
1014 start_offset
= _get_long(recipe_step
, 'start-offset'),
1015 type = recipe_step
.getAttribute('type')))
1017 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step
.name
)
1020 impl
.download_sources
.append(recipe
)
1022 root_attrs
= {'stability': 'testing'}
1025 info("Note: @main on document element is deprecated in %s", self
)
1026 root_commands
['run'] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'path': main
}), None)
1027 process_group(feed_element
, root_attrs
, [], [], root_commands
)
1029 def get_distro_feed(self
):
1030 """Does this feed contain any <pacakge-implementation> elements?
1031 i.e. is it worth asking the package manager for more information?
1032 @return: the URL of the virtual feed, or None
1034 if self
._package
_implementations
:
1035 return "distribution:" + self
.url
1038 def get_package_impls(self
, distro
):
1039 """Find the best <pacakge-implementation> element(s) for the given distribution.
1040 @param distro: the distribution to use to rate them
1041 @type distro: L{distro.Distribution}
1042 @return: a list of tuples for the best ranked elements
1048 for item
, item_attrs
in self
._package
_implementations
:
1049 distro_names
= item_attrs
.get('distributions', '')
1050 for distro_name
in distro_names
.split(' '):
1051 score
= distro
.get_score(distro_name
)
1052 if score
> best_score
:
1055 if score
== best_score
:
1056 best_impls
.append((item
, item_attrs
))
1060 return self
.name
or '(' + os
.path
.basename(self
.url
) + ')'
1063 return _("<Feed %s>") % self
.url
1065 def set_stability_policy(self
, new
):
1066 assert new
is None or isinstance(new
, Stability
)
1067 self
.stability_policy
= new
1069 def get_feed(self
, url
):
1070 for x
in self
.feeds
:
1075 def add_metadata(self
, elem
):
1076 self
.metadata
.append(elem
)
1078 def get_metadata(self
, uri
, name
):
1079 """Return a list of interface metadata elements with this name and namespace URI."""
1080 return [m
for m
in self
.metadata
if m
.name
== name
and m
.uri
== uri
]
1084 return _best_language_match(self
.summaries
) or self
.first_summary
1087 def description(self
):
1088 return _best_language_match(self
.descriptions
) or self
.first_description
1090 class DummyFeed(object):
1091 """Temporary class used during API transition."""
1092 last_modified
= None
1094 last_checked
= property(lambda self
: None)
1095 implementations
= property(lambda self
: {})
1096 feeds
= property(lambda self
: [])
1097 summary
= property(lambda self
: '-')
1098 description
= property(lambda self
: '')
1099 def get_name(self
): return self
.name
1100 def get_feed(self
, url
): return None
1101 def get_metadata(self
, uri
, name
): return []
1102 _dummy_feed
= DummyFeed()
1105 """Convert each %20 to a space, etc.
1107 uri
= uri
.replace('#', '/')
1108 if '%' not in uri
: return uri
1109 return re
.sub('%[0-9a-fA-F][0-9a-fA-F]',
1110 lambda match
: chr(int(match
.group(0)[1:], 16)),
1111 uri
).decode('utf-8')
1114 """Convert each space to %20, etc
1116 return re
.sub('[^-_.a-zA-Z0-9]',
1117 lambda match
: '%%%02x' % ord(match
.group(0)),
1118 uri
.encode('utf-8'))
1120 def _pretty_escape(uri
):
1121 """Convert each space to %20, etc
1122 : is preserved and / becomes #. This makes for nicer strings,
1123 and may replace L{escape} everywhere in future.
1125 if os
.name
== "posix":
1126 # Only preserve : on Posix systems
1127 preserveRegex
= '[^-_.a-zA-Z0-9:/]'
1129 # Other OSes may not allow the : character in file names
1130 preserveRegex
= '[^-_.a-zA-Z0-9/]'
1131 return re
.sub(preserveRegex
,
1132 lambda match
: '%%%02x' % ord(match
.group(0)),
1133 uri
.encode('utf-8')).replace('/', '#')
1135 def canonical_iface_uri(uri
):
1136 """If uri is a relative path, convert to an absolute one.
1137 A "file:///foo" URI is converted to "/foo".
1138 An "alias:prog" URI expands to the URI in the 0alias script
1139 Otherwise, return it unmodified.
1141 @raise SafeException: if uri isn't valid
1143 if uri
.startswith('http://') or uri
.startswith('https://'):
1144 if uri
.count("/") < 3:
1145 raise SafeException(_("Missing / after hostname in URI '%s'") % uri
)
1147 elif uri
.startswith('file:///'):
1149 elif uri
.startswith('alias:'):
1150 from zeroinstall
import alias
, support
1151 alias_prog
= uri
[6:]
1152 if not os
.path
.isabs(alias_prog
):
1153 full_path
= support
.find_in_path(alias_prog
)
1155 raise alias
.NotAnAliasScript("Not found in $PATH: " + alias_prog
)
1157 full_path
= alias_prog
1158 interface_uri
, main
= alias
.parse_script(full_path
)
1159 return interface_uri
1161 iface_uri
= os
.path
.realpath(uri
)
1162 if os
.path
.isfile(iface_uri
):
1164 raise SafeException(_("Bad interface name '%(uri)s'.\n"
1165 "(doesn't start with 'http:', and "
1166 "doesn't exist as a local file '%(interface_uri)s' either)") %
1167 {'uri': uri
, 'interface_uri': iface_uri
})
1169 _version_mod_to_value
= {
1177 _version_value_to_mod
= {}
1178 for x
in _version_mod_to_value
: _version_value_to_mod
[_version_mod_to_value
[x
]] = x
1181 _version_re
= re
.compile('-([a-z]*)')
1183 def parse_version(version_string
):
1184 """Convert a version string to an internal representation.
1185 The parsed format can be compared quickly using the standard Python functions.
1186 - Version := DottedList ("-" Mod DottedList?)*
1187 - DottedList := (Integer ("." Integer)*)
1188 @rtype: tuple (opaque)
1189 @raise SafeException: if the string isn't a valid version
1190 @since: 0.24 (moved from L{reader}, from where it is still available):"""
1191 if version_string
is None: return None
1192 parts
= _version_re
.split(version_string
)
1194 del parts
[-1] # Ends with a modifier
1198 raise SafeException(_("Empty version string!"))
1201 for x
in range(0, l
, 2):
1204 parts
[x
] = map(int, parts
[x
].split('.'))
1206 parts
[x
] = [] # (because ''.split('.') == [''], not [])
1207 for x
in range(1, l
, 2):
1208 parts
[x
] = _version_mod_to_value
[parts
[x
]]
1210 except ValueError as ex
:
1211 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string
, 'exception': ex
})
1212 except KeyError as ex
:
1213 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string
, 'exception': ex
})
1215 def format_version(version
):
1216 """Format a parsed version for display. Undoes the effect of L{parse_version}.
1217 @see: L{Implementation.get_version}
1220 version
= version
[:]
1222 for x
in range(0, l
, 2):
1223 version
[x
] = '.'.join(map(str, version
[x
]))
1224 for x
in range(1, l
, 2):
1225 version
[x
] = '-' + _version_value_to_mod
[version
[x
]]
1226 if version
[-1] == '-': del version
[-1]
1227 return ''.join(version
)