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', 'working-dir'])
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
)
60 return SafeException
.__str
__(self
) + ' in ' + self
.feed_url
61 return SafeException
.__str
__(self
)
63 def _split_arch(arch
):
64 """Split an arch into an (os, machine) tuple. Either or both parts may be None."""
68 raise SafeException(_("Malformed arch '%s'") % arch
)
70 osys
, machine
= arch
.split('-', 1)
71 if osys
== '*': osys
= None
72 if machine
== '*': machine
= None
75 def _join_arch(osys
, machine
):
76 if osys
== machine
== None: return None
77 return "%s-%s" % (osys
or '*', machine
or '*')
79 def _best_language_match(options
):
80 (language
, encoding
) = locale
.getlocale(locale
.LC_ALL
)
83 # xml:lang uses '-', while LANG uses '_'
84 language
= language
.replace('_', '-')
88 return (options
.get(language
, None) or # Exact match (language+region)
89 options
.get(language
.split('-', 1)[0], None) or # Matching language
90 options
.get('en', None)) # English
92 class Stability(object):
93 """A stability rating. Each implementation has an upstream stability rating and,
94 optionally, a user-set rating."""
95 __slots__
= ['level', 'name', 'description']
96 def __init__(self
, level
, name
, description
):
99 self
.description
= description
100 assert name
not in stability_levels
101 stability_levels
[name
] = self
103 def __cmp__(self
, other
):
104 return cmp(self
.level
, other
.level
)
110 return _("<Stability: %s>") % self
.description
112 def process_binding(e
):
114 if e
.name
== 'environment':
116 None: EnvironmentBinding
.PREPEND
,
117 'prepend': EnvironmentBinding
.PREPEND
,
118 'append': EnvironmentBinding
.APPEND
,
119 'replace': EnvironmentBinding
.REPLACE
,
120 }[e
.getAttribute('mode')]
122 binding
= EnvironmentBinding(e
.getAttribute('name'),
123 insert
= e
.getAttribute('insert'),
124 default
= e
.getAttribute('default'),
125 value
= e
.getAttribute('value'),
127 if not binding
.name
: raise InvalidInterface(_("Missing 'name' in binding"))
128 if binding
.insert
is None and binding
.value
is None:
129 raise InvalidInterface(_("Missing 'insert' or 'value' in binding"))
130 if binding
.insert
is not None and binding
.value
is not None:
131 raise InvalidInterface(_("Binding contains both 'insert' and 'value'"))
133 elif e
.name
== 'overlay':
134 return OverlayBinding(e
.getAttribute('src'), e
.getAttribute('mount-point'))
135 elif e
.name
== 'working-dir':
136 return WorkingDirBinding(e
.getAttribute('src'))
138 raise Exception(_("Unknown binding type '%s'") % e
.name
)
140 def process_depends(item
, local_feed_dir
):
142 # Note: also called from selections
144 dep_iface
= item
.getAttribute('interface')
146 raise InvalidInterface(_("Missing 'interface' on <%s>") % item
.name
)
147 if dep_iface
.startswith('./'):
149 dep_iface
= os
.path
.abspath(os
.path
.join(local_feed_dir
, dep_iface
))
150 # (updates the element too, in case we write it out again)
151 attrs
['interface'] = dep_iface
153 raise InvalidInterface(_('Relative interface URI "%s" in non-local feed') % dep_iface
)
154 dependency
= InterfaceDependency(dep_iface
, element
= item
)
156 for e
in item
.childNodes
:
157 if e
.uri
!= XMLNS_IFACE
: continue
158 if e
.name
in binding_names
:
159 dependency
.bindings
.append(process_binding(e
))
160 elif e
.name
== 'version':
161 dependency
.restrictions
.append(
162 VersionRangeRestriction(not_before
= parse_version(e
.getAttribute('not-before')),
163 before
= parse_version(e
.getAttribute('before'))))
166 def N_(message
): return message
168 insecure
= Stability(0, N_('insecure'), _('This is a security risk'))
169 buggy
= Stability(5, N_('buggy'), _('Known to have serious bugs'))
170 developer
= Stability(10, N_('developer'), _('Work-in-progress - bugs likely'))
171 testing
= Stability(20, N_('testing'), _('Stability unknown - please test!'))
172 stable
= Stability(30, N_('stable'), _('Tested - no serious problems found'))
173 packaged
= Stability(35, N_('packaged'), _('Supplied by the local package manager'))
174 preferred
= Stability(40, N_('preferred'), _('Best of all - must be set manually'))
178 class Restriction(object):
179 """A Restriction limits the allowed implementations of an Interface."""
182 def meets_restriction(self
, impl
):
183 """Called by the L{solver.Solver} to check whether a particular implementation is acceptable.
184 @return: False if this implementation is not a possibility
187 raise NotImplementedError(_("Abstract"))
189 class VersionRestriction(Restriction
):
190 """Only select implementations with a particular version number.
193 def __init__(self
, version
):
194 """@param version: the required version number
195 @see: L{parse_version}; use this to pre-process the version number
197 self
.version
= version
199 def meets_restriction(self
, impl
):
200 return impl
.version
== self
.version
203 return _("(restriction: version = %s)") % format_version(self
.version
)
205 class VersionRangeRestriction(Restriction
):
206 """Only versions within the given range are acceptable"""
207 __slots__
= ['before', 'not_before']
209 def __init__(self
, before
, not_before
):
210 """@param before: chosen versions must be earlier than this
211 @param not_before: versions must be at least this high
212 @see: L{parse_version}; use this to pre-process the versions
215 self
.not_before
= not_before
217 def meets_restriction(self
, impl
):
218 if self
.not_before
and impl
.version
< self
.not_before
:
220 if self
.before
and impl
.version
>= self
.before
:
225 if self
.not_before
is not None or self
.before
is not None:
227 if self
.not_before
is not None:
228 range += format_version(self
.not_before
) + ' <= '
230 if self
.before
is not None:
231 range += ' < ' + format_version(self
.before
)
234 return _("(restriction: %s)") % range
236 class Binding(object):
237 """Information about how the choice of a Dependency is made known
238 to the application being run."""
240 class EnvironmentBinding(Binding
):
241 """Indicate the chosen implementation using an environment variable."""
242 __slots__
= ['name', 'insert', 'default', 'mode', 'value']
248 def __init__(self
, name
, insert
, default
= None, mode
= PREPEND
, value
=None):
250 mode argument added in version 0.28
251 value argument added in version 0.52
255 self
.default
= default
260 return _("<environ %(name)s %(mode)s %(insert)s %(value)s>") % {'name': self
.name
,'mode': self
.mode
, 'insert': self
.insert
, 'value': self
.value
}
264 def get_value(self
, path
, old_value
):
265 """Calculate the new value of the environment variable after applying this binding.
266 @param path: the path to the selected implementation
267 @param old_value: the current value of the environment variable
268 @return: the new value for the environment variable"""
270 if self
.insert
is not None:
271 extra
= os
.path
.join(path
, self
.insert
)
273 assert self
.value
is not None
276 if self
.mode
== EnvironmentBinding
.REPLACE
:
279 if old_value
is None:
280 old_value
= self
.default
or defaults
.get(self
.name
, None)
281 if old_value
is None:
283 if self
.mode
== EnvironmentBinding
.PREPEND
:
284 return extra
+ os
.pathsep
+ old_value
286 return old_value
+ os
.pathsep
+ extra
288 def _toxml(self
, doc
):
289 """Create a DOM element for this binding.
290 @param doc: document to use to create the element
291 @return: the new element
293 env_elem
= doc
.createElementNS(XMLNS_IFACE
, 'environment')
294 env_elem
.setAttributeNS(None, 'name', self
.name
)
295 if self
.insert
is not None:
296 env_elem
.setAttributeNS(None, 'insert', self
.insert
)
298 env_elem
.setAttributeNS(None, 'value', self
.value
)
300 env_elem
.setAttributeNS(None, 'default', self
.default
)
303 class OverlayBinding(Binding
):
304 """Make the chosen implementation available by overlaying it onto another part of the file-system.
305 This is to support legacy programs which use hard-coded paths."""
306 __slots__
= ['src', 'mount_point']
308 def __init__(self
, src
, mount_point
):
310 self
.mount_point
= mount_point
313 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self
.src
or '.', 'mount_point': self
.mount_point
or '/'}
317 def _toxml(self
, doc
):
318 """Create a DOM element for this binding.
319 @param doc: document to use to create the element
320 @return: the new element
322 env_elem
= doc
.createElementNS(XMLNS_IFACE
, 'overlay')
323 if self
.src
is not None:
324 env_elem
.setAttributeNS(None, 'src', self
.src
)
325 if self
.mount_point
is not None:
326 env_elem
.setAttributeNS(None, 'mount-point', self
.mount_point
)
329 class WorkingDirBinding(Binding
):
330 """Make the chosen implementation available by changing the working directory.
331 This is to support legacy programs which can't properly locate their installation directory."""
334 def __init__(self
, src
):
338 return _("<working-dir %(src)s>") % {'src': self
.src
or '.'}
342 def _toxml(self
, doc
):
343 """Create a DOM element for this binding.
344 @param doc: document to use to create the element
345 @return: the new element
347 env_elem
= doc
.createElementNS(XMLNS_IFACE
, 'working-dir')
348 if self
.src
is not None:
349 env_elem
.setAttributeNS(None, 'src', self
.src
)
353 """An interface's feeds are other interfaces whose implementations can also be
354 used as implementations of this interface."""
355 __slots__
= ['uri', 'os', 'machine', 'user_override', 'langs']
356 def __init__(self
, uri
, arch
, user_override
, langs
= None):
358 # This indicates whether the feed comes from the user's overrides
359 # file. If true, writer.py will write it when saving.
360 self
.user_override
= user_override
361 self
.os
, self
.machine
= _split_arch(arch
)
365 return "<Feed from %s>" % self
.uri
368 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
370 class Dependency(object):
371 """A Dependency indicates that an Implementation requires some additional
372 code to function. This is an abstract base class.
373 @ivar qdom: the XML element for this Dependency (since 0launch 0.51)
374 @type qdom: L{qdom.Element}
375 @ivar metadata: any extra attributes from the XML element
376 @type metadata: {str: str}
380 def __init__(self
, element
):
381 assert isinstance(element
, qdom
.Element
), type(element
) # Use InterfaceDependency instead!
386 return self
.qdom
.attrs
388 class InterfaceDependency(Dependency
):
389 """A Dependency on a Zero Install interface.
390 @ivar interface: the interface required by this dependency
392 @ivar restrictions: a list of constraints on acceptable implementations
393 @type restrictions: [L{Restriction}]
394 @ivar bindings: how to make the choice of implementation known
395 @type bindings: [L{Binding}]
398 __slots__
= ['interface', 'restrictions', 'bindings']
400 def __init__(self
, interface
, restrictions
= None, element
= None):
401 Dependency
.__init
__(self
, element
)
402 assert isinstance(interface
, (str, unicode))
404 self
.interface
= interface
405 if restrictions
is None:
406 self
.restrictions
= []
408 self
.restrictions
= restrictions
412 return _("<Dependency on %(interface)s; bindings: %(bindings)s%(restrictions)s>") % {'interface': self
.interface
, 'bindings': self
.bindings
, 'restrictions': self
.restrictions
}
414 class RetrievalMethod(object):
415 """A RetrievalMethod provides a way to fetch an implementation."""
418 class DownloadSource(RetrievalMethod
):
419 """A DownloadSource provides a way to fetch an implementation."""
420 __slots__
= ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
422 def __init__(self
, implementation
, url
, size
, extract
, start_offset
= 0, type = None):
423 self
.implementation
= implementation
426 self
.extract
= extract
427 self
.start_offset
= start_offset
428 self
.type = type # MIME type - see unpack.py
430 class Recipe(RetrievalMethod
):
431 """Get an implementation by following a series of steps.
432 @ivar size: the combined download sizes from all the steps
434 @ivar steps: the sequence of steps which must be performed
435 @type steps: [L{RetrievalMethod}]"""
436 __slots__
= ['steps']
441 size
= property(lambda self
: sum([x
.size
for x
in self
.steps
]))
443 class DistributionSource(RetrievalMethod
):
444 """A package that is installed using the distribution's tools (including PackageKit).
445 @ivar install: a function to call to install this package
446 @type install: (L{handler.Handler}) -> L{tasks.Blocker}
447 @ivar package_id: the package name, in a form recognised by the distribution's tools
448 @type package_id: str
449 @ivar size: the download size in bytes
451 @ivar needs_confirmation: whether the user should be asked to confirm before calling install()
452 @type needs_confirmation: bool"""
454 __slots__
= ['package_id', 'size', 'install', 'needs_confirmation']
456 def __init__(self
, package_id
, size
, install
, needs_confirmation
= True):
457 RetrievalMethod
.__init
__(self
)
458 self
.package_id
= package_id
460 self
.install
= install
461 self
.needs_confirmation
= needs_confirmation
463 class Command(object):
464 """A Command is a way of running an Implementation as a program."""
466 __slots__
= ['qdom', '_depends', '_local_dir', '_runner']
468 def __init__(self
, qdom
, local_dir
):
469 """@param qdom: the <command> element
470 @param local_dir: the directory containing the feed (for relative dependencies), or None if not local
472 assert qdom
.name
== 'command', 'not <command>: %s' % qdom
474 self
._local
_dir
= local_dir
477 path
= property(lambda self
: self
.qdom
.attrs
.get("path", None))
479 def _toxml(self
, doc
, prefixes
):
480 return self
.qdom
.toDOM(doc
, prefixes
)
484 if self
._depends
is None:
487 for child
in self
.qdom
.childNodes
:
488 if child
.name
== 'requires':
489 dep
= process_depends(child
, self
._local
_dir
)
491 elif child
.name
== 'runner':
493 raise InvalidInterface(_("Multiple <runner>s in <command>!"))
494 dep
= process_depends(child
, self
._local
_dir
)
497 self
._depends
= depends
500 def get_runner(self
):
501 self
.requires
# (sets _runner)
504 class Implementation(object):
505 """An Implementation is a package which implements an Interface.
506 @ivar download_sources: list of methods of getting this implementation
507 @type download_sources: [L{RetrievalMethod}]
508 @ivar feed: the feed owning this implementation (since 0.32)
509 @type feed: [L{ZeroInstallFeed}]
510 @ivar bindings: how to tell this component where it itself is located (since 0.31)
511 @type bindings: [Binding]
512 @ivar upstream_stability: the stability reported by the packager
513 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged]
514 @ivar user_stability: the stability as set by the user
515 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred]
516 @ivar langs: natural languages supported by this package
518 @ivar requires: interfaces this package depends on
519 @type requires: [L{Dependency}]
520 @ivar commands: ways to execute as a program
521 @type commands: {str: Command}
522 @ivar metadata: extra metadata from the feed
523 @type metadata: {"[URI ]localName": str}
524 @ivar id: a unique identifier for this Implementation
525 @ivar version: a parsed version number
526 @ivar released: release date
527 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path)
528 @type local_path: str | None
529 @ivar requires_root_install: whether the user will need admin rights to use this
530 @type requires_root_install: bool
533 # Note: user_stability shouldn't really be here
535 __slots__
= ['upstream_stability', 'user_stability', 'langs',
536 'requires', 'metadata', 'download_sources', 'commands',
537 'id', 'feed', 'version', 'released', 'bindings', 'machine']
539 def __init__(self
, feed
, id):
543 self
.user_stability
= None
544 self
.upstream_stability
= None
545 self
.metadata
= {} # [URI + " "] + localName -> value
549 self
.download_sources
= []
555 def get_stability(self
):
556 return self
.user_stability
or self
.upstream_stability
or testing
562 return "v%s (%s)" % (self
.get_version(), self
.id)
564 def __cmp__(self
, other
):
565 """Newer versions come first"""
566 d
= cmp(other
.version
, self
.version
)
568 # If the version number is the same, just give a stable sort order, and
569 # ensure that two different implementations don't compare equal.
570 d
= cmp(other
.feed
.url
, self
.feed
.url
)
572 return cmp(other
.id, self
.id)
574 def get_version(self
):
575 """Return the version as a string.
576 @see: L{format_version}
578 return format_version(self
.version
)
580 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
585 requires_root_install
= False
588 """"@deprecated: use commands["run"] instead"""
589 main
= self
.commands
.get("run", None)
593 def _set_main(self
, path
):
594 """"@deprecated: use commands["run"] instead"""
596 if "run" in self
.commands
:
597 del self
.commands
["run"]
599 self
.commands
["run"] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'path': path
}), None)
600 main
= property(_get_main
, _set_main
)
602 def is_available(self
, stores
):
603 """Is this Implementation available locally?
604 (a local implementation, an installed distribution package, or a cached ZeroInstallImplementation)
608 raise NotImplementedError("abstract")
610 class DistributionImplementation(Implementation
):
611 """An implementation provided by the distribution. Information such as the version
612 comes from the package manager.
614 __slots__
= ['distro', 'installed']
616 def __init__(self
, feed
, id, distro
):
617 assert id.startswith('package:')
618 Implementation
.__init
__(self
, feed
, id)
620 self
.installed
= False
623 def requires_root_install(self
):
624 return not self
.installed
626 def is_available(self
, stores
):
627 return self
.installed
629 class ZeroInstallImplementation(Implementation
):
630 """An implementation where all the information comes from Zero Install.
631 @ivar digests: a list of "algorith=value" strings (since 0.45)
634 __slots__
= ['os', 'size', 'digests', 'local_path']
636 def __init__(self
, feed
, id, local_path
):
637 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
638 assert not id.startswith('package:'), id
639 Implementation
.__init
__(self
, feed
, id)
643 self
.local_path
= local_path
646 dependencies
= property(lambda self
: dict([(x
.interface
, x
) for x
in self
.requires
647 if isinstance(x
, InterfaceDependency
)]))
649 def add_download_source(self
, url
, size
, extract
, start_offset
= 0, type = None):
650 """Add a download source."""
651 self
.download_sources
.append(DownloadSource(self
, url
, size
, extract
, start_offset
, type))
653 def set_arch(self
, arch
):
654 self
.os
, self
.machine
= _split_arch(arch
)
655 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
), set_arch
)
657 def is_available(self
, stores
):
658 if self
.local_path
is not None:
659 return os
.path
.exists(self
.local_path
)
661 path
= stores
.lookup_maybe(self
.digests
)
662 return path
is not None
663 return False # (0compile creates fake entries with no digests)
665 class Interface(object):
666 """An Interface represents some contract of behaviour.
667 @ivar uri: the URI for this interface.
668 @ivar stability_policy: user's configured policy.
669 Implementations at this level or higher are preferred.
670 Lower levels are used only if there is no other choice.
672 __slots__
= ['uri', 'stability_policy', 'extra_feeds']
674 implementations
= property(lambda self
: self
._main
_feed
.implementations
)
675 name
= property(lambda self
: self
._main
_feed
.name
)
676 description
= property(lambda self
: self
._main
_feed
.description
)
677 summary
= property(lambda self
: self
._main
_feed
.summary
)
678 last_modified
= property(lambda self
: self
._main
_feed
.last_modified
)
679 feeds
= property(lambda self
: self
.extra_feeds
+ self
._main
_feed
.feeds
)
680 metadata
= property(lambda self
: self
._main
_feed
.metadata
)
682 last_checked
= property(lambda self
: self
._main
_feed
.last_checked
)
684 def __init__(self
, uri
):
686 if uri
.startswith('http:') or uri
.startswith('https:') or os
.path
.isabs(uri
):
689 raise SafeException(_("Interface name '%s' doesn't start "
690 "with 'http:' or 'https:'") % uri
)
693 def _get_feed_for(self
):
695 for key
in self
._main
_feed
.feed_for
:
698 feed_for
= property(_get_feed_for
) # Deprecated (used by 0publish)
701 self
.extra_feeds
= []
702 self
.stability_policy
= None
705 from zeroinstall
.injector
.iface_cache
import iface_cache
706 feed
= iface_cache
.get_feed(self
.uri
)
708 return feed
.get_name()
709 return '(' + os
.path
.basename(self
.uri
) + ')'
712 return _("<Interface %s>") % self
.uri
714 def set_stability_policy(self
, new
):
715 assert new
is None or isinstance(new
, Stability
)
716 self
.stability_policy
= new
718 def get_feed(self
, url
):
720 #warnings.warn("use iface_cache.get_feed instead", DeprecationWarning, 2)
721 for x
in self
.extra_feeds
:
724 #return self._main_feed.get_feed(url)
727 def get_metadata(self
, uri
, name
):
728 return self
._main
_feed
.get_metadata(uri
, name
)
731 def _main_feed(self
):
733 #warnings.warn("use the feed instead", DeprecationWarning, 3)
734 from zeroinstall
.injector
import policy
735 iface_cache
= policy
.get_deprecated_singleton_config().iface_cache
736 feed
= iface_cache
.get_feed(self
.uri
)
741 def _merge_attrs(attrs
, item
):
742 """Add each attribute of item to a copy of attrs and return the copy.
743 @type attrs: {str: str}
744 @type item: L{qdom.Element}
749 new
[str(a
)] = item
.attrs
[a
]
752 def _get_long(elem
, attr_name
):
753 val
= elem
.getAttribute(attr_name
)
758 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name
, 'value': val
})
761 class ZeroInstallFeed(object):
762 """A feed lists available implementations of an interface.
763 @ivar url: the URL for this feed
764 @ivar implementations: Implementations in this feed, indexed by ID
765 @type implementations: {str: L{Implementation}}
766 @ivar name: human-friendly name
767 @ivar summaries: short textual description (in various languages, since 0.49)
768 @type summaries: {str: str}
769 @ivar descriptions: long textual description (in various languages, since 0.49)
770 @type descriptions: {str: str}
771 @ivar last_modified: timestamp on signature
772 @ivar last_checked: time feed was last successfully downloaded and updated
773 @ivar feeds: list of <feed> elements in this feed
774 @type feeds: [L{Feed}]
775 @ivar feed_for: interfaces for which this could be a feed
776 @type feed_for: set(str)
777 @ivar metadata: extra elements we didn't understand
779 # _main is deprecated
780 __slots__
= ['url', 'implementations', 'name', 'descriptions', 'first_description', 'summaries', 'first_summary', '_package_implementations',
781 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
783 def __init__(self
, feed_element
, local_path
= None, distro
= None):
784 """Create a feed object from a DOM.
785 @param feed_element: the root element of a feed file
786 @type feed_element: L{qdom.Element}
787 @param local_path: the pathname of this local feed, or None for remote feeds"""
788 self
.implementations
= {}
790 self
.summaries
= {} # { lang: str }
791 self
.first_summary
= None
792 self
.descriptions
= {} # { lang: str }
793 self
.first_description
= None
794 self
.last_modified
= None
796 self
.feed_for
= set()
798 self
.last_checked
= None
799 self
._package
_implementations
= []
801 if distro
is not None:
803 warnings
.warn("distro argument is now ignored", DeprecationWarning, 2)
805 if feed_element
is None:
806 return # XXX subclass?
808 assert feed_element
.name
in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
809 assert feed_element
.uri
== XMLNS_IFACE
, "Wrong namespace on root element: %s" % feed_element
.uri
811 main
= feed_element
.getAttribute('main')
812 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
815 self
.url
= local_path
816 local_dir
= os
.path
.dirname(local_path
)
818 self
.url
= feed_element
.getAttribute('uri')
820 raise InvalidInterface(_("<interface> uri attribute missing"))
821 local_dir
= None # Can't have relative paths
823 min_injector_version
= feed_element
.getAttribute('min-injector-version')
824 if min_injector_version
:
825 if parse_version(min_injector_version
) > parse_version(version
):
826 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
827 "Zero Install, but I am only version %(version)s. "
828 "You can get a newer version from http://0install.net") %
829 {'min_version': min_injector_version
, 'version': version
})
831 for x
in feed_element
.childNodes
:
832 if x
.uri
!= XMLNS_IFACE
:
833 self
.metadata
.append(x
)
836 self
.name
= x
.content
837 elif x
.name
== 'description':
838 if self
.first_description
== None:
839 self
.first_description
= x
.content
840 self
.descriptions
[x
.attrs
.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x
.content
841 elif x
.name
== 'summary':
842 if self
.first_summary
== None:
843 self
.first_summary
= x
.content
844 self
.summaries
[x
.attrs
.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x
.content
845 elif x
.name
== 'feed-for':
846 feed_iface
= x
.getAttribute('interface')
848 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
849 self
.feed_for
.add(feed_iface
)
850 # Bug report from a Debian/stable user that --feed gets the wrong value.
851 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
852 # in case it happens again.
853 debug(_("Is feed-for %s"), feed_iface
)
854 elif x
.name
== 'feed':
855 feed_src
= x
.getAttribute('src')
857 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
858 if feed_src
.startswith('http:') or feed_src
.startswith('https:') or local_path
:
859 self
.feeds
.append(Feed(feed_src
, x
.getAttribute('arch'), False, langs
= x
.getAttribute('langs')))
861 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src
)
863 self
.metadata
.append(x
)
866 raise InvalidInterface(_("Missing <name> in feed"))
868 raise InvalidInterface(_("Missing <summary> in feed"))
870 def process_group(group
, group_attrs
, base_depends
, base_bindings
, base_commands
):
871 for item
in group
.childNodes
:
872 if item
.uri
!= XMLNS_IFACE
: continue
874 if item
.name
not in ('group', 'implementation', 'package-implementation'):
877 depends
= base_depends
[:]
878 bindings
= base_bindings
[:]
879 commands
= base_commands
.copy()
881 item_attrs
= _merge_attrs(group_attrs
, item
)
883 # We've found a group or implementation. Scan for dependencies
884 # and bindings. 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
889 for child
in item
.childNodes
:
890 if child
.uri
!= XMLNS_IFACE
: continue
891 if child
.name
== 'requires':
892 dep
= process_depends(child
, local_dir
)
894 elif child
.name
== 'command':
895 command_name
= child
.attrs
.get('name', None)
897 raise InvalidInterface('Missing name for <command>')
898 commands
[command_name
] = Command(child
, local_dir
)
899 elif child
.name
in binding_names
:
900 bindings
.append(process_binding(child
))
902 for attr
, command
in [('main', 'run'),
903 ('self-test', 'test')]:
904 value
= item
.attrs
.get(attr
, None)
905 if value
is not None:
906 commands
[command
] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'path': value
}), None)
908 compile_command
= item
.attrs
.get('http://zero-install.sourceforge.net/2006/namespaces/0compile command')
909 if compile_command
is not None:
910 commands
['compile'] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'shell-command': compile_command
}), None)
912 if item
.name
== 'group':
913 process_group(item
, item_attrs
, depends
, bindings
, commands
)
914 elif item
.name
== 'implementation':
915 process_impl(item
, item_attrs
, depends
, bindings
, commands
)
916 elif item
.name
== 'package-implementation':
918 warn("A <package-implementation> with dependencies in %s!", self
.url
)
919 self
._package
_implementations
.append((item
, item_attrs
))
923 def process_impl(item
, item_attrs
, depends
, bindings
, commands
):
924 id = item
.getAttribute('id')
926 raise InvalidInterface(_("Missing 'id' attribute on %s") % item
)
927 local_path
= item_attrs
.get('local-path')
928 if local_dir
and local_path
:
929 abs_local_path
= os
.path
.abspath(os
.path
.join(local_dir
, local_path
))
930 impl
= ZeroInstallImplementation(self
, id, abs_local_path
)
931 elif local_dir
and (id.startswith('/') or id.startswith('.')):
933 id = os
.path
.abspath(os
.path
.join(local_dir
, id))
934 impl
= ZeroInstallImplementation(self
, id, id)
936 impl
= ZeroInstallImplementation(self
, id, None)
938 # In older feeds, the ID was the (single) digest
939 impl
.digests
.append(id)
940 if id in self
.implementations
:
941 warn(_("Duplicate ID '%(id)s' in feed '%(feed)s'"), {'id': id, 'feed': self
})
942 self
.implementations
[id] = impl
944 impl
.metadata
= item_attrs
946 version_mod
= item_attrs
.get('version-modifier', None)
948 item_attrs
['version'] += version_mod
949 del item_attrs
['version-modifier']
950 version
= item_attrs
['version']
952 raise InvalidInterface(_("Missing version attribute"))
953 impl
.version
= parse_version(version
)
955 impl
.commands
= commands
957 impl
.released
= item_attrs
.get('released', None)
958 impl
.langs
= item_attrs
.get('langs', '')
960 size
= item
.getAttribute('size')
962 impl
.size
= int(size
)
963 impl
.arch
= item_attrs
.get('arch', None)
965 stability
= stability_levels
[str(item_attrs
['stability'])]
967 stab
= str(item_attrs
['stability'])
968 if stab
!= stab
.lower():
969 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs
.stability
)
970 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs
['stability'])
971 if stability
>= preferred
:
972 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
973 impl
.upstream_stability
= stability
975 impl
.bindings
= bindings
976 impl
.requires
= depends
978 for elem
in item
.childNodes
:
979 if elem
.uri
!= XMLNS_IFACE
: continue
980 if elem
.name
== 'archive':
981 url
= elem
.getAttribute('href')
983 raise InvalidInterface(_("Missing href attribute on <archive>"))
984 size
= elem
.getAttribute('size')
986 raise InvalidInterface(_("Missing size attribute on <archive>"))
987 impl
.add_download_source(url
= url
, size
= int(size
),
988 extract
= elem
.getAttribute('extract'),
989 start_offset
= _get_long(elem
, 'start-offset'),
990 type = elem
.getAttribute('type'))
991 elif elem
.name
== 'manifest-digest':
992 for aname
, avalue
in elem
.attrs
.iteritems():
994 impl
.digests
.append('%s=%s' % (aname
, avalue
))
995 elif elem
.name
== 'recipe':
997 for recipe_step
in elem
.childNodes
:
998 if recipe_step
.uri
== XMLNS_IFACE
and recipe_step
.name
== 'archive':
999 url
= recipe_step
.getAttribute('href')
1001 raise InvalidInterface(_("Missing href attribute on <archive>"))
1002 size
= recipe_step
.getAttribute('size')
1004 raise InvalidInterface(_("Missing size attribute on <archive>"))
1005 recipe
.steps
.append(DownloadSource(None, url
= url
, size
= int(size
),
1006 extract
= recipe_step
.getAttribute('extract'),
1007 start_offset
= _get_long(recipe_step
, 'start-offset'),
1008 type = recipe_step
.getAttribute('type')))
1010 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step
.name
)
1013 impl
.download_sources
.append(recipe
)
1015 root_attrs
= {'stability': 'testing'}
1018 info("Note: @main on document element is deprecated in %s", self
)
1019 root_commands
['run'] = Command(qdom
.Element(XMLNS_IFACE
, 'command', {'path': main
}), None)
1020 process_group(feed_element
, root_attrs
, [], [], root_commands
)
1022 def get_distro_feed(self
):
1023 """Does this feed contain any <pacakge-implementation> elements?
1024 i.e. is it worth asking the package manager for more information?
1025 @return: the URL of the virtual feed, or None
1027 if self
._package
_implementations
:
1028 return "distribution:" + self
.url
1031 def get_package_impls(self
, distro
):
1032 """Find the best <pacakge-implementation> element(s) for the given distribution.
1033 @param distro: the distribution to use to rate them
1034 @type distro: L{distro.Distribution}
1035 @return: a list of tuples for the best ranked elements
1041 for item
, item_attrs
in self
._package
_implementations
:
1042 distro_names
= item_attrs
.get('distributions', '')
1043 for distro_name
in distro_names
.split(' '):
1044 score
= distro
.get_score(distro_name
)
1045 if score
> best_score
:
1048 if score
== best_score
:
1049 best_impls
.append((item
, item_attrs
))
1053 return self
.name
or '(' + os
.path
.basename(self
.url
) + ')'
1056 return _("<Feed %s>") % self
.url
1058 def set_stability_policy(self
, new
):
1059 assert new
is None or isinstance(new
, Stability
)
1060 self
.stability_policy
= new
1062 def get_feed(self
, url
):
1063 for x
in self
.feeds
:
1068 def add_metadata(self
, elem
):
1069 self
.metadata
.append(elem
)
1071 def get_metadata(self
, uri
, name
):
1072 """Return a list of interface metadata elements with this name and namespace URI."""
1073 return [m
for m
in self
.metadata
if m
.name
== name
and m
.uri
== uri
]
1077 return _best_language_match(self
.summaries
) or self
.first_summary
1080 def description(self
):
1081 return _best_language_match(self
.descriptions
) or self
.first_description
1083 class DummyFeed(object):
1084 """Temporary class used during API transition."""
1085 last_modified
= None
1087 last_checked
= property(lambda self
: None)
1088 implementations
= property(lambda self
: {})
1089 feeds
= property(lambda self
: [])
1090 summary
= property(lambda self
: '-')
1091 description
= property(lambda self
: '')
1092 def get_name(self
): return self
.name
1093 def get_feed(self
, url
): return None
1094 def get_metadata(self
, uri
, name
): return []
1095 _dummy_feed
= DummyFeed()
1098 """Convert each %20 to a space, etc.
1100 uri
= uri
.replace('#', '/')
1101 if '%' not in uri
: return uri
1102 return re
.sub('%[0-9a-fA-F][0-9a-fA-F]',
1103 lambda match
: chr(int(match
.group(0)[1:], 16)),
1104 uri
).decode('utf-8')
1107 """Convert each space to %20, etc
1109 return re
.sub('[^-_.a-zA-Z0-9]',
1110 lambda match
: '%%%02x' % ord(match
.group(0)),
1111 uri
.encode('utf-8'))
1113 def _pretty_escape(uri
):
1114 """Convert each space to %20, etc
1115 : is preserved and / becomes #. This makes for nicer strings,
1116 and may replace L{escape} everywhere in future.
1118 return re
.sub('[^-_.a-zA-Z0-9/]',
1119 lambda match
: '%%%02x' % ord(match
.group(0)),
1120 uri
.encode('utf-8')).replace('/', '#')
1122 def canonical_iface_uri(uri
):
1123 """If uri is a relative path, convert to an absolute one.
1124 A "file:///foo" URI is converted to "/foo".
1125 An "alias:prog" URI expands to the URI in the 0alias script
1126 Otherwise, return it unmodified.
1128 @raise SafeException: if uri isn't valid
1130 if uri
.startswith('http://') or uri
.startswith('https://'):
1131 if uri
.count("/") < 3:
1132 raise SafeException(_("Missing / after hostname in URI '%s'") % uri
)
1134 elif uri
.startswith('file:///'):
1136 elif uri
.startswith('alias:'):
1137 from zeroinstall
import alias
, support
1138 alias_prog
= uri
[6:]
1139 if not os
.path
.isabs(alias_prog
):
1140 full_path
= support
.find_in_path(alias_prog
)
1142 raise alias
.NotAnAliasScript("Not found in $PATH: " + alias_prog
)
1144 full_path
= alias_prog
1145 interface_uri
, main
= alias
.parse_script(full_path
)
1146 return interface_uri
1148 iface_uri
= os
.path
.realpath(uri
)
1149 if os
.path
.isfile(iface_uri
):
1151 raise SafeException(_("Bad interface name '%(uri)s'.\n"
1152 "(doesn't start with 'http:', and "
1153 "doesn't exist as a local file '%(interface_uri)s' either)") %
1154 {'uri': uri
, 'interface_uri': iface_uri
})
1156 _version_mod_to_value
= {
1164 _version_value_to_mod
= {}
1165 for x
in _version_mod_to_value
: _version_value_to_mod
[_version_mod_to_value
[x
]] = x
1168 _version_re
= re
.compile('-([a-z]*)')
1170 def parse_version(version_string
):
1171 """Convert a version string to an internal representation.
1172 The parsed format can be compared quickly using the standard Python functions.
1173 - Version := DottedList ("-" Mod DottedList?)*
1174 - DottedList := (Integer ("." Integer)*)
1175 @rtype: tuple (opaque)
1176 @raise SafeException: if the string isn't a valid version
1177 @since: 0.24 (moved from L{reader}, from where it is still available):"""
1178 if version_string
is None: return None
1179 parts
= _version_re
.split(version_string
)
1181 del parts
[-1] # Ends with a modifier
1185 raise SafeException(_("Empty version string!"))
1188 for x
in range(0, l
, 2):
1191 parts
[x
] = map(int, parts
[x
].split('.'))
1193 parts
[x
] = [] # (because ''.split('.') == [''], not [])
1194 for x
in range(1, l
, 2):
1195 parts
[x
] = _version_mod_to_value
[parts
[x
]]
1197 except ValueError, ex
:
1198 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string
, 'exception': ex
})
1199 except KeyError, ex
:
1200 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string
, 'exception': ex
})
1202 def format_version(version
):
1203 """Format a parsed version for display. Undoes the effect of L{parse_version}.
1204 @see: L{Implementation.get_version}
1207 version
= version
[:]
1209 for x
in range(0, l
, 2):
1210 version
[x
] = '.'.join(map(str, version
[x
]))
1211 for x
in range(1, l
, 2):
1212 version
[x
] = '-' + _version_value_to_mod
[version
[x
]]
1213 if version
[-1] == '-': del version
[-1]
1214 return ''.join(version
)