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
22 # Element names for bindings in feed files
23 binding_names
= frozenset(['environment', 'overlay'])
25 network_offline
= 'off-line'
26 network_minimal
= 'minimal'
28 network_levels
= (network_offline
, network_minimal
, network_full
)
30 stability_levels
= {} # Name -> Stability
33 'PATH': '/bin:/usr/bin',
34 'XDG_CONFIG_DIRS': '/etc/xdg',
35 'XDG_DATA_DIRS': '/usr/local/share:/usr/share',
38 class InvalidInterface(SafeException
):
39 """Raised when parsing an invalid feed."""
40 def __init__(self
, message
, ex
= None):
42 message
+= "\n\n(exact error: %s)" % ex
43 SafeException
.__init
__(self
, message
)
45 def _split_arch(arch
):
46 """Split an arch into an (os, machine) tuple. Either or both parts may be None."""
50 raise SafeException(_("Malformed arch '%s'") % arch
)
52 osys
, machine
= arch
.split('-', 1)
53 if osys
== '*': osys
= None
54 if machine
== '*': machine
= None
57 def _join_arch(osys
, machine
):
58 if osys
== machine
== None: return None
59 return "%s-%s" % (osys
or '*', machine
or '*')
61 class Stability(object):
62 """A stability rating. Each implementation has an upstream stability rating and,
63 optionally, a user-set rating."""
64 __slots__
= ['level', 'name', 'description']
65 def __init__(self
, level
, name
, description
):
68 self
.description
= description
69 assert name
not in stability_levels
70 stability_levels
[name
] = self
72 def __cmp__(self
, other
):
73 return cmp(self
.level
, other
.level
)
79 return _("<Stability: %s>") % self
.description
81 def process_binding(e
):
83 if e
.name
== 'environment':
85 None: EnvironmentBinding
.PREPEND
,
86 'prepend': EnvironmentBinding
.PREPEND
,
87 'append': EnvironmentBinding
.APPEND
,
88 'replace': EnvironmentBinding
.REPLACE
,
89 }[e
.getAttribute('mode')]
91 binding
= EnvironmentBinding(e
.getAttribute('name'),
92 insert
= e
.getAttribute('insert'),
93 default
= e
.getAttribute('default'),
95 if not binding
.name
: raise InvalidInterface(_("Missing 'name' in binding"))
96 if binding
.insert
is None: raise InvalidInterface(_("Missing 'insert' in binding"))
98 elif e
.name
== 'overlay':
99 return OverlayBinding(e
.getAttribute('src'), e
.getAttribute('mount-point'))
101 raise Exception(_("Unknown binding type '%s'") % e
.name
)
103 def process_depends(item
):
105 # Note: also called from selections
106 dep_iface
= item
.getAttribute('interface')
108 raise InvalidInterface(_("Missing 'interface' on <requires>"))
109 dependency
= InterfaceDependency(dep_iface
, metadata
= item
.attrs
)
111 for e
in item
.childNodes
:
112 if e
.uri
!= XMLNS_IFACE
: continue
113 if e
.name
in binding_names
:
114 dependency
.bindings
.append(process_binding(e
))
115 elif e
.name
== 'version':
116 dependency
.restrictions
.append(
117 VersionRangeRestriction(not_before
= parse_version(e
.getAttribute('not-before')),
118 before
= parse_version(e
.getAttribute('before'))))
121 def N_(message
): return message
123 insecure
= Stability(0, N_('insecure'), _('This is a security risk'))
124 buggy
= Stability(5, N_('buggy'), _('Known to have serious bugs'))
125 developer
= Stability(10, N_('developer'), _('Work-in-progress - bugs likely'))
126 testing
= Stability(20, N_('testing'), _('Stability unknown - please test!'))
127 stable
= Stability(30, N_('stable'), _('Tested - no serious problems found'))
128 packaged
= Stability(35, N_('packaged'), _('Supplied by the local package manager'))
129 preferred
= Stability(40, N_('preferred'), _('Best of all - must be set manually'))
133 class Restriction(object):
134 """A Restriction limits the allowed implementations of an Interface."""
137 def meets_restriction(self
, impl
):
138 """Called by the L{Solver} to check whether a particular implementation is acceptable.
139 @return: False if this implementation is not a possibility
142 raise NotImplementedError(_("Abstract"))
144 class VersionRestriction(Restriction
):
145 """Only select implementations with a particular version number.
148 def __init__(self
, version
):
149 """@param version: the required version number
150 @see: L{parse_version}; use this to pre-process the version number
152 self
.version
= version
154 def meets_restriction(self
, impl
):
155 return impl
.version
== self
.version
158 return _("(restriction: version = %s)") % format_version(self
.version
)
160 class VersionRangeRestriction(Restriction
):
161 """Only versions within the given range are acceptable"""
162 __slots__
= ['before', 'not_before']
164 def __init__(self
, before
, not_before
):
165 """@param before: chosen versions must be earlier than this
166 @param not_before: versions must be at least this high
167 @see: L{parse_version}; use this to pre-process the versions
170 self
.not_before
= not_before
172 def meets_restriction(self
, impl
):
173 if self
.not_before
and impl
.version
< self
.not_before
:
175 if self
.before
and impl
.version
>= self
.before
:
180 if self
.not_before
is not None or self
.before
is not None:
182 if self
.not_before
is not None:
183 range += format_version(self
.not_before
) + ' <= '
185 if self
.before
is not None:
186 range += ' < ' + format_version(self
.before
)
189 return _("(restriction: %s)") % range
191 class Binding(object):
192 """Information about how the choice of a Dependency is made known
193 to the application being run."""
195 class EnvironmentBinding(Binding
):
196 """Indicate the chosen implementation using an environment variable."""
197 __slots__
= ['name', 'insert', 'default', 'mode']
203 def __init__(self
, name
, insert
, default
= None, mode
= PREPEND
):
204 """mode argument added in version 0.28"""
207 self
.default
= default
211 return _("<environ %(name)s %(mode)s %(insert)s>") % {'name': self
.name
,'mode': self
.mode
, 'insert': self
.insert
}
215 def get_value(self
, path
, old_value
):
216 """Calculate the new value of the environment variable after applying this binding.
217 @param path: the path to the selected implementation
218 @param old_value: the current value of the environment variable
219 @return: the new value for the environment variable"""
220 extra
= os
.path
.join(path
, self
.insert
)
222 if self
.mode
== EnvironmentBinding
.REPLACE
:
225 if old_value
is None:
226 old_value
= self
.default
or defaults
.get(self
.name
, None)
227 if old_value
is None:
229 if self
.mode
== EnvironmentBinding
.PREPEND
:
230 return extra
+ ':' + old_value
232 return old_value
+ ':' + extra
234 def _toxml(self
, doc
):
235 """Create a DOM element for this binding.
236 @param doc: document to use to create the element
237 @return: the new element
239 env_elem
= doc
.createElementNS(XMLNS_IFACE
, 'environment')
240 env_elem
.setAttributeNS(None, 'name', self
.name
)
241 env_elem
.setAttributeNS(None, 'insert', self
.insert
)
243 env_elem
.setAttributeNS(None, 'default', self
.default
)
246 class OverlayBinding(Binding
):
247 """Make the chosen implementation available by overlaying it onto another part of the file-system.
248 This is to support legacy programs which use hard-coded paths."""
249 __slots__
= ['src', 'mount_point']
251 def __init__(self
, src
, mount_point
):
253 self
.mount_point
= mount_point
256 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self
.src
or '.', 'mount_point': self
.mount_point
or '/'}
260 def _toxml(self
, doc
):
261 """Create a DOM element for this binding.
262 @param doc: document to use to create the element
263 @return: the new element
265 env_elem
= doc
.createElementNS(XMLNS_IFACE
, 'overlay')
266 if self
.src
is not None:
267 env_elem
.setAttributeNS(None, 'src', self
.src
)
268 if self
.mount_point
is not None:
269 env_elem
.setAttributeNS(None, 'mount-point', self
.mount_point
)
273 """An interface's feeds are other interfaces whose implementations can also be
274 used as implementations of this interface."""
275 __slots__
= ['uri', 'os', 'machine', 'user_override', 'langs']
276 def __init__(self
, uri
, arch
, user_override
, langs
= None):
278 # This indicates whether the feed comes from the user's overrides
279 # file. If true, writer.py will write it when saving.
280 self
.user_override
= user_override
281 self
.os
, self
.machine
= _split_arch(arch
)
285 return "<Feed from %s>" % self
.uri
288 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
290 class Dependency(object):
291 """A Dependency indicates that an Implementation requires some additional
292 code to function. This is an abstract base class.
293 @ivar metadata: any extra attributes from the XML element
294 @type metadata: {str: str}
296 __slots__
= ['metadata']
298 def __init__(self
, metadata
):
302 assert not isinstance(metadata
, basestring
) # Use InterfaceDependency instead!
303 self
.metadata
= metadata
305 class InterfaceDependency(Dependency
):
306 """A Dependency on a Zero Install interface.
307 @ivar interface: the interface required by this dependency
309 @ivar restrictions: a list of constraints on acceptable implementations
310 @type restrictions: [L{Restriction}]
311 @ivar bindings: how to make the choice of implementation known
312 @type bindings: [L{Binding}]
315 __slots__
= ['interface', 'restrictions', 'bindings', 'metadata']
317 def __init__(self
, interface
, restrictions
= None, metadata
= None):
318 Dependency
.__init
__(self
, metadata
)
319 assert isinstance(interface
, (str, unicode))
321 self
.interface
= interface
322 if restrictions
is None:
323 self
.restrictions
= []
325 self
.restrictions
= restrictions
329 return _("<Dependency on %(interface)s; bindings: %(bindings)s%(restrictions)s>") % {'interface': self
.interface
, 'bindings': self
.bindings
, 'restrictions': self
.restrictions
}
331 class RetrievalMethod(object):
332 """A RetrievalMethod provides a way to fetch an implementation."""
335 class DownloadSource(RetrievalMethod
):
336 """A DownloadSource provides a way to fetch an implementation."""
337 __slots__
= ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
339 def __init__(self
, implementation
, url
, size
, extract
, start_offset
= 0, type = None):
340 self
.implementation
= implementation
343 self
.extract
= extract
344 self
.start_offset
= start_offset
345 self
.type = type # MIME type - see unpack.py
347 class Recipe(RetrievalMethod
):
348 """Get an implementation by following a series of steps.
349 @ivar size: the combined download sizes from all the steps
351 @ivar steps: the sequence of steps which must be performed
352 @type steps: [L{RetrievalMethod}]"""
353 __slots__
= ['steps']
358 size
= property(lambda self
: sum([x
.size
for x
in self
.steps
]))
360 class Implementation(object):
361 """An Implementation is a package which implements an Interface.
362 @ivar download_sources: list of methods of getting this implementation
363 @type download_sources: [L{RetrievalMethod}]
364 @ivar feed: the feed owning this implementation (since 0.32)
365 @type feed: [L{ZeroInstallFeed}]
366 @ivar bindings: how to tell this component where it itself is located (since 0.31)
367 @type bindings: [Binding]
368 @ivar upstream_stability: the stability reported by the packager
369 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged]
370 @ivar user_stability: the stability as set by the user
371 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred]
372 @ivar langs: natural languages supported by this package
373 @ivar requires: interfaces this package depends on
374 @type requires: [L{Dependency}]
375 @ivar main: the default file to execute when running as a program
376 @ivar metadata: extra metadata from the feed
377 @type metadata: {"[URI ]localName": str}
378 @ivar id: a unique identifier for this Implementation
379 @ivar version: a parsed version number
380 @ivar released: release date
381 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path)
382 @type local_path: str | None
385 # Note: user_stability shouldn't really be here
387 __slots__
= ['upstream_stability', 'user_stability', 'langs',
388 'requires', 'main', 'metadata', 'download_sources',
389 'id', 'feed', 'version', 'released', 'bindings', 'machine']
391 def __init__(self
, feed
, id):
396 self
.user_stability
= None
397 self
.upstream_stability
= None
398 self
.metadata
= {} # [URI + " "] + localName -> value
402 self
.download_sources
= []
407 def get_stability(self
):
408 return self
.user_stability
or self
.upstream_stability
or testing
414 return "v%s (%s)" % (self
.get_version(), self
.id)
416 def __cmp__(self
, other
):
417 """Newer versions come first"""
418 return cmp(other
.version
, self
.version
)
420 def get_version(self
):
421 """Return the version as a string.
422 @see: L{format_version}
424 return format_version(self
.version
)
426 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
432 class DistributionImplementation(Implementation
):
433 """An implementation provided by the distribution. Information such as the version
434 comes from the package manager.
436 __slots__
= ['installed']
438 def __init__(self
, feed
, id):
439 assert id.startswith('package:')
440 Implementation
.__init
__(self
, feed
, id)
441 self
.installed
= True
443 class ZeroInstallImplementation(Implementation
):
444 """An implementation where all the information comes from Zero Install.
445 @ivar digests: a list of "algorith=value" strings (since 0.45)
448 __slots__
= ['os', 'size', 'digests', 'local_path']
450 def __init__(self
, feed
, id, local_path
):
451 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
452 assert not id.startswith('package:'), id
453 Implementation
.__init
__(self
, feed
, id)
457 self
.local_path
= local_path
460 dependencies
= property(lambda self
: dict([(x
.interface
, x
) for x
in self
.requires
461 if isinstance(x
, InterfaceDependency
)]))
463 def add_download_source(self
, url
, size
, extract
, start_offset
= 0, type = None):
464 """Add a download source."""
465 self
.download_sources
.append(DownloadSource(self
, url
, size
, extract
, start_offset
, type))
467 def set_arch(self
, arch
):
468 self
.os
, self
.machine
= _split_arch(arch
)
469 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
), set_arch
)
471 class Interface(object):
472 """An Interface represents some contract of behaviour.
473 @ivar uri: the URI for this interface.
474 @ivar stability_policy: user's configured policy.
475 Implementations at this level or higher are preferred.
476 Lower levels are used only if there is no other choice.
478 __slots__
= ['uri', 'stability_policy', '_main_feed', 'extra_feeds']
480 implementations
= property(lambda self
: self
._main
_feed
.implementations
)
481 name
= property(lambda self
: self
._main
_feed
.name
)
482 description
= property(lambda self
: self
._main
_feed
.description
)
483 summary
= property(lambda self
: self
._main
_feed
.summary
)
484 last_modified
= property(lambda self
: self
._main
_feed
.last_modified
)
485 feeds
= property(lambda self
: self
.extra_feeds
+ self
._main
_feed
.feeds
)
486 metadata
= property(lambda self
: self
._main
_feed
.metadata
)
488 last_checked
= property(lambda self
: self
._main
_feed
.last_checked
)
490 def __init__(self
, uri
):
492 if uri
.startswith('http:') or uri
.startswith('https:') or uri
.startswith('/'):
495 raise SafeException(_("Interface name '%s' doesn't start "
496 "with 'http:' or 'https:'") % uri
)
499 def _get_feed_for(self
):
501 for key
in self
._main
_feed
.feed_for
:
504 feed_for
= property(_get_feed_for
) # Deprecated (used by 0publish)
507 self
.extra_feeds
= []
508 self
._main
_feed
= _dummy_feed
509 self
.stability_policy
= None
512 if self
._main
_feed
is not _dummy_feed
:
513 return self
._main
_feed
.get_name()
514 return '(' + os
.path
.basename(self
.uri
) + ')'
517 return _("<Interface %s>") % self
.uri
519 def set_stability_policy(self
, new
):
520 assert new
is None or isinstance(new
, Stability
)
521 self
.stability_policy
= new
523 def get_feed(self
, url
):
524 for x
in self
.extra_feeds
:
527 return self
._main
_feed
.get_feed(url
)
529 def get_metadata(self
, uri
, name
):
530 return self
._main
_feed
.get_metadata(uri
, name
)
532 def _merge_attrs(attrs
, item
):
533 """Add each attribute of item to a copy of attrs and return the copy.
534 @type attrs: {str: str}
535 @type item: L{qdom.Element}
540 new
[str(a
)] = item
.attrs
[a
]
543 def _get_long(elem
, attr_name
):
544 val
= elem
.getAttribute(attr_name
)
548 except ValueError, ex
:
549 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name
, 'value': val
})
552 class ZeroInstallFeed(object):
553 """A feed lists available implementations of an interface.
554 @ivar url: the URL for this feed
555 @ivar implementations: Implementations in this feed, indexed by ID
556 @type implementations: {str: L{Implementation}}
557 @ivar name: human-friendly name
558 @ivar summary: short textual description
559 @ivar description: long textual description
560 @ivar last_modified: timestamp on signature
561 @ivar last_checked: time feed was last successfully downloaded and updated
562 @ivar feeds: list of <feed> elements in this feed
563 @type feeds: [L{Feed}]
564 @ivar feed_for: interfaces for which this could be a feed
565 @type feed_for: set(str)
566 @ivar metadata: extra elements we didn't understand
568 # _main is deprecated
569 __slots__
= ['url', 'implementations', 'name', 'description', 'summary',
570 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
572 def __init__(self
, feed_element
, local_path
= None, distro
= None):
573 """Create a feed object from a DOM.
574 @param feed_element: the root element of a feed file
575 @type feed_element: L{qdom.Element}
576 @param local_path: the pathname of this local feed, or None for remote feeds
577 @param distro: used to resolve distribution package references
578 @type distro: L{distro.Distribution} or None"""
580 self
.implementations
= {}
583 self
.description
= ""
584 self
.last_modified
= None
586 self
.feed_for
= set()
588 self
.last_checked
= None
590 assert feed_element
.name
in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
591 assert feed_element
.uri
== XMLNS_IFACE
, "Wrong namespace on root element: %s" % feed_element
.uri
593 main
= feed_element
.getAttribute('main')
594 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
597 self
.url
= local_path
598 local_dir
= os
.path
.dirname(local_path
)
600 self
.url
= feed_element
.getAttribute('uri')
602 raise InvalidInterface(_("<interface> uri attribute missing"))
603 local_dir
= None # Can't have relative paths
605 min_injector_version
= feed_element
.getAttribute('min-injector-version')
606 if min_injector_version
:
607 if parse_version(min_injector_version
) > parse_version(version
):
608 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
609 "Zero Install, but I am only version %(version)s. "
610 "You can get a newer version from http://0install.net") %
611 {'min_version': min_injector_version
, 'version': version
})
613 for x
in feed_element
.childNodes
:
614 if x
.uri
!= XMLNS_IFACE
:
615 self
.metadata
.append(x
)
618 self
.name
= x
.content
619 elif x
.name
== 'description':
620 self
.description
= x
.content
621 elif x
.name
== 'summary':
622 self
.summary
= x
.content
623 elif x
.name
== 'feed-for':
624 feed_iface
= x
.getAttribute('interface')
626 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
627 self
.feed_for
.add(feed_iface
)
628 # Bug report from a Debian/stable user that --feed gets the wrong value.
629 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
630 # in case it happens again.
631 debug(_("Is feed-for %s"), feed_iface
)
632 elif x
.name
== 'feed':
633 feed_src
= x
.getAttribute('src')
635 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
636 if feed_src
.startswith('http:') or feed_src
.startswith('https:') or local_path
:
637 self
.feeds
.append(Feed(feed_src
, x
.getAttribute('arch'), False, langs
= x
.getAttribute('langs')))
639 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src
)
641 self
.metadata
.append(x
)
644 raise InvalidInterface(_("Missing <name> in feed"))
646 raise InvalidInterface(_("Missing <summary> in feed"))
648 package_impls
= [0, []] # Best score so far and packages with that score
650 def process_group(group
, group_attrs
, base_depends
, base_bindings
):
651 for item
in group
.childNodes
:
652 if item
.uri
!= XMLNS_IFACE
: continue
654 if item
.name
not in ('group', 'implementation', 'package-implementation'):
657 depends
= base_depends
[:]
658 bindings
= base_bindings
[:]
660 item_attrs
= _merge_attrs(group_attrs
, item
)
662 # We've found a group or implementation. Scan for dependencies
663 # and bindings. Doing this here means that:
664 # - We can share the code for groups and implementations here.
665 # - The order doesn't matter, because these get processed first.
666 # A side-effect is that the document root cannot contain
668 for child
in item
.childNodes
:
669 if child
.uri
!= XMLNS_IFACE
: continue
670 if child
.name
== 'requires':
671 dep
= process_depends(child
)
673 elif child
.name
in binding_names
:
674 bindings
.append(process_binding(child
))
676 if item
.name
== 'group':
677 process_group(item
, item_attrs
, depends
, bindings
)
678 elif item
.name
== 'implementation':
679 process_impl(item
, item_attrs
, depends
, bindings
)
680 elif item
.name
== 'package-implementation':
681 distro_names
= item_attrs
.get('distributions', '')
682 for distro_name
in distro_names
.split(' '):
683 score
= distro
.get_score(distro_name
)
684 if score
> package_impls
[0]:
685 package_impls
[0] = score
686 package_impls
[1] = []
687 if score
== package_impls
[0]:
688 package_impls
[1].append((item
, item_attrs
, depends
))
692 def process_impl(item
, item_attrs
, depends
, bindings
):
693 id = item
.getAttribute('id')
695 raise InvalidInterface(_("Missing 'id' attribute on %s") % item
)
696 local_path
= item_attrs
.get('local-path')
697 if local_dir
and local_path
:
698 abs_local_path
= os
.path
.abspath(os
.path
.join(local_dir
, local_path
))
699 impl
= ZeroInstallImplementation(self
, id, abs_local_path
)
700 elif local_dir
and (id.startswith('/') or id.startswith('.')):
702 id = os
.path
.abspath(os
.path
.join(local_dir
, id))
703 impl
= ZeroInstallImplementation(self
, id, id)
705 impl
= ZeroInstallImplementation(self
, id, None)
707 # In older feeds, the ID was the (single) digest
708 impl
.digests
.append(id)
709 if id in self
.implementations
:
710 warn(_("Duplicate ID '%s' in feed '%s'"), id, self
)
711 self
.implementations
[id] = impl
713 impl
.metadata
= item_attrs
715 version_mod
= item_attrs
.get('version-modifier', None)
717 item_attrs
['version'] += version_mod
718 del item_attrs
['version-modifier']
719 version
= item_attrs
['version']
721 raise InvalidInterface(_("Missing version attribute"))
722 impl
.version
= parse_version(version
)
724 item_main
= item_attrs
.get('main', None)
725 if item_main
and item_main
.startswith('/'):
726 raise InvalidInterface(_("'main' attribute must be relative, but '%s' starts with '/'!") %
728 impl
.main
= item_main
730 impl
.released
= item_attrs
.get('released', None)
731 impl
.langs
= item_attrs
.get('langs', None)
733 size
= item
.getAttribute('size')
735 impl
.size
= long(size
)
736 impl
.arch
= item_attrs
.get('arch', None)
738 stability
= stability_levels
[str(item_attrs
['stability'])]
740 stab
= str(item_attrs
['stability'])
741 if stab
!= stab
.lower():
742 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs
.stability
)
743 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs
['stability'])
744 if stability
>= preferred
:
745 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
746 impl
.upstream_stability
= stability
748 impl
.bindings
= bindings
749 impl
.requires
= depends
751 for elem
in item
.childNodes
:
752 if elem
.uri
!= XMLNS_IFACE
: continue
753 if elem
.name
== 'archive':
754 url
= elem
.getAttribute('href')
756 raise InvalidInterface(_("Missing href attribute on <archive>"))
757 size
= elem
.getAttribute('size')
759 raise InvalidInterface(_("Missing size attribute on <archive>"))
760 impl
.add_download_source(url
= url
, size
= long(size
),
761 extract
= elem
.getAttribute('extract'),
762 start_offset
= _get_long(elem
, 'start-offset'),
763 type = elem
.getAttribute('type'))
764 elif elem
.name
== 'manifest-digest':
765 for aname
, avalue
in elem
.attrs
.iteritems():
767 impl
.digests
.append('%s=%s' % (aname
, avalue
))
768 elif elem
.name
== 'recipe':
770 for recipe_step
in elem
.childNodes
:
771 if recipe_step
.uri
== XMLNS_IFACE
and recipe_step
.name
== 'archive':
772 url
= recipe_step
.getAttribute('href')
774 raise InvalidInterface(_("Missing href attribute on <archive>"))
775 size
= recipe_step
.getAttribute('size')
777 raise InvalidInterface(_("Missing size attribute on <archive>"))
778 recipe
.steps
.append(DownloadSource(None, url
= url
, size
= long(size
),
779 extract
= recipe_step
.getAttribute('extract'),
780 start_offset
= _get_long(recipe_step
, 'start-offset'),
781 type = recipe_step
.getAttribute('type')))
783 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step
.name
)
786 impl
.download_sources
.append(recipe
)
788 def process_native_impl(item
, item_attrs
, depends
):
789 package
= item_attrs
.get('package', None)
791 raise InvalidInterface(_("Missing 'package' attribute on %s") % item
)
794 assert id.startswith('package:')
795 if id in self
.implementations
:
796 warn(_("Duplicate ID '%s' for DistributionImplementation"), id)
797 impl
= DistributionImplementation(self
, id)
798 self
.implementations
[id] = impl
800 impl
.metadata
= item_attrs
802 item_main
= item_attrs
.get('main', None)
803 if item_main
and not item_main
.startswith('/'):
804 raise InvalidInterface(_("'main' attribute must be absolute, but '%s' doesn't start with '/'!") %
806 impl
.main
= item_main
807 impl
.upstream_stability
= packaged
808 impl
.requires
= depends
812 distro
.get_package_info(package
, factory
)
814 root_attrs
= {'stability': 'testing'}
816 root_attrs
['main'] = main
817 process_group(feed_element
, root_attrs
, [], [])
819 for args
in package_impls
[1]:
820 process_native_impl(*args
)
823 return self
.name
or '(' + os
.path
.basename(self
.url
) + ')'
826 return _("<Feed %s>") % self
.url
829 def _get_impl(self
, id):
830 assert id not in self
.implementations
832 if id.startswith('.') or id.startswith('/'):
833 id = os
.path
.abspath(os
.path
.join(self
.url
, id))
835 impl
= ZeroInstallImplementation(self
, id, local_path
)
837 impl
= ZeroInstallImplementation(self
, id, None)
838 impl
.digests
.append(id)
840 self
.implementations
[id] = impl
843 def set_stability_policy(self
, new
):
844 assert new
is None or isinstance(new
, Stability
)
845 self
.stability_policy
= new
847 def get_feed(self
, url
):
853 def add_metadata(self
, elem
):
854 self
.metadata
.append(elem
)
856 def get_metadata(self
, uri
, name
):
857 """Return a list of interface metadata elements with this name and namespace URI."""
858 return [m
for m
in self
.metadata
if m
.name
== name
and m
.uri
== uri
]
860 class DummyFeed(object):
861 """Temporary class used during API transition."""
864 last_checked
= property(lambda self
: None)
865 implementations
= property(lambda self
: {})
866 feeds
= property(lambda self
: [])
867 summary
= property(lambda self
: '-')
868 description
= property(lambda self
: '')
869 def get_name(self
): return self
.name
870 def get_feed(self
, url
): return None
871 def get_metadata(self
, uri
, name
): return []
872 _dummy_feed
= DummyFeed()
875 """Convert each %20 to a space, etc.
877 uri
= uri
.replace('#', '/')
878 if '%' not in uri
: return uri
879 return re
.sub('%[0-9a-fA-F][0-9a-fA-F]',
880 lambda match
: chr(int(match
.group(0)[1:], 16)),
884 """Convert each space to %20, etc
886 return re
.sub('[^-_.a-zA-Z0-9]',
887 lambda match
: '%%%02x' % ord(match
.group(0)),
890 def _pretty_escape(uri
):
891 """Convert each space to %20, etc
892 : is preserved and / becomes #. This makes for nicer strings,
893 and may replace L{escape} everywhere in future.
895 return re
.sub('[^-_.a-zA-Z0-9:/]',
896 lambda match
: '%%%02x' % ord(match
.group(0)),
897 uri
.encode('utf-8')).replace('/', '#')
899 def canonical_iface_uri(uri
):
900 """If uri is a relative path, convert to an absolute one.
901 A "file:///foo" URI is converted to "/foo".
902 Otherwise, return it unmodified.
904 @raise SafeException: if uri isn't valid
906 if uri
.startswith('http://') or uri
.startswith('https://'):
907 if uri
.count("/") < 3:
908 raise SafeException(_("Missing / after hostname in URI '%s'") % uri
)
910 elif uri
.startswith('file:///'):
913 iface_uri
= os
.path
.realpath(uri
)
914 if os
.path
.isfile(iface_uri
):
916 raise SafeException(_("Bad interface name '%(uri)s'.\n"
917 "(doesn't start with 'http:', and "
918 "doesn't exist as a local file '%(interface_uri)s' either)") %
919 {'uri': uri
, 'interface_uri': iface_uri
})
921 _version_mod_to_value
= {
929 _version_value_to_mod
= {}
930 for x
in _version_mod_to_value
: _version_value_to_mod
[_version_mod_to_value
[x
]] = x
933 _version_re
= re
.compile('-([a-z]*)')
935 def parse_version(version_string
):
936 """Convert a version string to an internal representation.
937 The parsed format can be compared quickly using the standard Python functions.
938 - Version := DottedList ("-" Mod DottedList?)*
939 - DottedList := (Integer ("." Integer)*)
940 @rtype: tuple (opaque)
941 @raise SafeException: if the string isn't a valid version
942 @since: 0.24 (moved from L{reader}, from where it is still available):"""
943 if version_string
is None: return None
944 parts
= _version_re
.split(version_string
)
946 del parts
[-1] # Ends with a modifier
950 raise SafeException(_("Empty version string!"))
953 for x
in range(0, l
, 2):
956 parts
[x
] = map(int, parts
[x
].split('.'))
958 parts
[x
] = [] # (because ''.split('.') == [''], not [])
959 for x
in range(1, l
, 2):
960 parts
[x
] = _version_mod_to_value
[parts
[x
]]
962 except ValueError, ex
:
963 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string
, 'exception': ex
})
965 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string
, 'exception': ex
})
967 def format_version(version
):
968 """Format a parsed version for display. Undoes the effect of L{parse_version}.
969 @see: L{Implementation.get_version}
974 for x
in range(0, l
, 2):
975 version
[x
] = '.'.join(map(str, version
[x
]))
976 for x
in range(1, l
, 2):
977 version
[x
] = '-' + _version_value_to_mod
[version
[x
]]
978 if version
[-1] == '-': del version
[-1]
979 return ''.join(version
)