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.
17 from logging
import info
, debug
18 from zeroinstall
import SafeException
, version
19 from zeroinstall
.injector
.namespaces
import XMLNS_IFACE
21 # Element names for bindings in feed files
22 binding_names
= frozenset(['environment', 'overlay'])
24 network_offline
= 'off-line'
25 network_minimal
= 'minimal'
27 network_levels
= (network_offline
, network_minimal
, network_full
)
29 stability_levels
= {} # Name -> Stability
32 'PATH': '/bin:/usr/bin',
33 'XDG_CONFIG_DIRS': '/etc/xdg',
34 'XDG_DATA_DIRS': '/usr/local/share:/usr/share',
37 class InvalidInterface(SafeException
):
38 """Raised when parsing an invalid feed."""
39 def __init__(self
, message
, ex
= None):
41 message
+= "\n\n(exact error: %s)" % ex
42 SafeException
.__init
__(self
, message
)
44 def _split_arch(arch
):
45 """Split an arch into an (os, machine) tuple. Either or both parts may be None."""
49 raise SafeException(_("Malformed arch '%s'") % arch
)
51 osys
, machine
= arch
.split('-', 1)
52 if osys
== '*': osys
= None
53 if machine
== '*': machine
= None
56 def _join_arch(osys
, machine
):
57 if osys
== machine
== None: return None
58 return "%s-%s" % (osys
or '*', machine
or '*')
60 class Stability(object):
61 """A stability rating. Each implementation has an upstream stability rating and,
62 optionally, a user-set rating."""
63 __slots__
= ['level', 'name', 'description']
64 def __init__(self
, level
, name
, description
):
67 self
.description
= description
68 assert name
not in stability_levels
69 stability_levels
[name
] = self
71 def __cmp__(self
, other
):
72 return cmp(self
.level
, other
.level
)
78 return _("<Stability: %s>") % self
.description
80 def process_binding(e
):
82 if e
.name
== 'environment':
84 None: EnvironmentBinding
.PREPEND
,
85 'prepend': EnvironmentBinding
.PREPEND
,
86 'append': EnvironmentBinding
.APPEND
,
87 'replace': EnvironmentBinding
.REPLACE
,
88 }[e
.getAttribute('mode')]
90 binding
= EnvironmentBinding(e
.getAttribute('name'),
91 insert
= e
.getAttribute('insert'),
92 default
= e
.getAttribute('default'),
94 if not binding
.name
: raise InvalidInterface(_("Missing 'name' in binding"))
95 if binding
.insert
is None: raise InvalidInterface(_("Missing 'insert' in binding"))
97 elif e
.name
== 'overlay':
98 return OverlayBinding(e
.getAttribute('src'), e
.getAttribute('mount-point'))
100 raise Exception(_("Unknown binding type '%s'") % e
.name
)
102 def process_depends(item
):
104 # Note: also called from selections
105 dep_iface
= item
.getAttribute('interface')
107 raise InvalidInterface(_("Missing 'interface' on <requires>"))
108 dependency
= InterfaceDependency(dep_iface
, metadata
= item
.attrs
)
110 for e
in item
.childNodes
:
111 if e
.uri
!= XMLNS_IFACE
: continue
112 if e
.name
in binding_names
:
113 dependency
.bindings
.append(process_binding(e
))
114 elif e
.name
== 'version':
115 dependency
.restrictions
.append(
116 VersionRangeRestriction(not_before
= parse_version(e
.getAttribute('not-before')),
117 before
= parse_version(e
.getAttribute('before'))))
120 def N_(message
): return message
122 insecure
= Stability(0, N_('insecure'), _('This is a security risk'))
123 buggy
= Stability(5, N_('buggy'), _('Known to have serious bugs'))
124 developer
= Stability(10, N_('developer'), _('Work-in-progress - bugs likely'))
125 testing
= Stability(20, N_('testing'), _('Stability unknown - please test!'))
126 stable
= Stability(30, N_('stable'), _('Tested - no serious problems found'))
127 packaged
= Stability(35, N_('packaged'), _('Supplied by the local package manager'))
128 preferred
= Stability(40, N_('preferred'), _('Best of all - must be set manually'))
132 class Restriction(object):
133 """A Restriction limits the allowed implementations of an Interface."""
136 def meets_restriction(self
, impl
):
137 """Called by the L{Solver} to check whether a particular implementation is acceptable.
138 @return: False if this implementation is not a possibility
141 raise NotImplementedError(_("Abstract"))
143 class VersionRestriction(Restriction
):
144 """Only select implementations with a particular version number.
147 def __init__(self
, version
):
148 """@param version: the required version number
149 @see: L{parse_version}; use this to pre-process the version number
151 self
.version
= version
153 def meets_restriction(self
, impl
):
154 return impl
.version
== self
.version
157 return _("(restriction: version = %s)") % format_version(self
.version
)
159 class VersionRangeRestriction(Restriction
):
160 """Only versions within the given range are acceptable"""
161 __slots__
= ['before', 'not_before']
163 def __init__(self
, before
, not_before
):
164 """@param before: chosen versions must be earlier than this
165 @param not_before: versions must be at least this high
166 @see: L{parse_version}; use this to pre-process the versions
169 self
.not_before
= not_before
171 def meets_restriction(self
, impl
):
172 if self
.not_before
and impl
.version
< self
.not_before
:
174 if self
.before
and impl
.version
>= self
.before
:
179 if self
.not_before
is not None or self
.before
is not None:
181 if self
.not_before
is not None:
182 range += format_version(self
.not_before
) + ' <= '
184 if self
.before
is not None:
185 range += ' < ' + format_version(self
.before
)
188 return _("(restriction: %s)") % range
190 class Binding(object):
191 """Information about how the choice of a Dependency is made known
192 to the application being run."""
194 class EnvironmentBinding(Binding
):
195 """Indicate the chosen implementation using an environment variable."""
196 __slots__
= ['name', 'insert', 'default', 'mode']
202 def __init__(self
, name
, insert
, default
= None, mode
= PREPEND
):
203 """mode argument added in version 0.28"""
206 self
.default
= default
210 return _("<environ %(name)s %(mode)s %(insert)s>") % {'name': self
.name
,'mode': self
.mode
, 'insert': self
.insert
}
214 def get_value(self
, path
, old_value
):
215 """Calculate the new value of the environment variable after applying this binding.
216 @param path: the path to the selected implementation
217 @param old_value: the current value of the environment variable
218 @return: the new value for the environment variable"""
219 extra
= os
.path
.join(path
, self
.insert
)
221 if self
.mode
== EnvironmentBinding
.REPLACE
:
224 if old_value
is None:
225 old_value
= self
.default
or defaults
.get(self
.name
, None)
226 if old_value
is None:
228 if self
.mode
== EnvironmentBinding
.PREPEND
:
229 return extra
+ ':' + old_value
231 return old_value
+ ':' + extra
233 def _toxml(self
, doc
):
234 """Create a DOM element for this binding.
235 @param doc: document to use to create the element
236 @return: the new element
238 env_elem
= doc
.createElementNS(XMLNS_IFACE
, 'environment')
239 env_elem
.setAttributeNS(None, 'name', self
.name
)
240 env_elem
.setAttributeNS(None, 'insert', self
.insert
)
242 env_elem
.setAttributeNS(None, 'default', self
.default
)
245 class OverlayBinding(Binding
):
246 """Make the chosen implementation available by overlaying it onto another part of the file-system.
247 This is to support legacy programs which use hard-coded paths."""
248 __slots__
= ['src', 'mount_point']
250 def __init__(self
, src
, mount_point
):
252 self
.mount_point
= mount_point
255 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self
.src
or '.', 'mount_point': self
.mount_point
or '/'}
259 def _toxml(self
, doc
):
260 """Create a DOM element for this binding.
261 @param doc: document to use to create the element
262 @return: the new element
264 env_elem
= doc
.createElementNS(XMLNS_IFACE
, 'overlay')
265 if self
.src
is not None:
266 env_elem
.setAttributeNS(None, 'src', self
.src
)
267 if self
.mount_point
is not None:
268 env_elem
.setAttributeNS(None, 'mount-point', self
.mount_point
)
272 """An interface's feeds are other interfaces whose implementations can also be
273 used as implementations of this interface."""
274 __slots__
= ['uri', 'os', 'machine', 'user_override', 'langs']
275 def __init__(self
, uri
, arch
, user_override
, langs
= None):
277 # This indicates whether the feed comes from the user's overrides
278 # file. If true, writer.py will write it when saving.
279 self
.user_override
= user_override
280 self
.os
, self
.machine
= _split_arch(arch
)
284 return "<Feed from %s>" % self
.uri
287 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
289 class Dependency(object):
290 """A Dependency indicates that an Implementation requires some additional
291 code to function. This is an abstract base class.
292 @ivar metadata: any extra attributes from the XML element
293 @type metadata: {str: str}
295 __slots__
= ['metadata']
297 def __init__(self
, metadata
):
301 assert not isinstance(metadata
, basestring
) # Use InterfaceDependency instead!
302 self
.metadata
= metadata
304 class InterfaceDependency(Dependency
):
305 """A Dependency on a Zero Install interface.
306 @ivar interface: the interface required by this dependency
308 @ivar restrictions: a list of constraints on acceptable implementations
309 @type restrictions: [L{Restriction}]
310 @ivar bindings: how to make the choice of implementation known
311 @type bindings: [L{Binding}]
314 __slots__
= ['interface', 'restrictions', 'bindings', 'metadata']
316 def __init__(self
, interface
, restrictions
= None, metadata
= None):
317 Dependency
.__init
__(self
, metadata
)
318 assert isinstance(interface
, (str, unicode))
320 self
.interface
= interface
321 if restrictions
is None:
322 self
.restrictions
= []
324 self
.restrictions
= restrictions
328 return _("<Dependency on %(interface)s; bindings: %(bindings)s%(restrictions)s>") % {'interface': self
.interface
, 'bindings': self
.bindings
, 'restrictions': self
.restrictions
}
330 class RetrievalMethod(object):
331 """A RetrievalMethod provides a way to fetch an implementation."""
334 class DownloadSource(RetrievalMethod
):
335 """A DownloadSource provides a way to fetch an implementation."""
336 __slots__
= ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
338 def __init__(self
, implementation
, url
, size
, extract
, start_offset
= 0, type = None):
339 self
.implementation
= implementation
342 self
.extract
= extract
343 self
.start_offset
= start_offset
344 self
.type = type # MIME type - see unpack.py
346 class Recipe(RetrievalMethod
):
347 """Get an implementation by following a series of steps.
348 @ivar size: the combined download sizes from all the steps
350 @ivar steps: the sequence of steps which must be performed
351 @type steps: [L{RetrievalMethod}]"""
352 __slots__
= ['steps']
357 size
= property(lambda self
: sum([x
.size
for x
in self
.steps
]))
359 class Implementation(object):
360 """An Implementation is a package which implements an Interface.
361 @ivar download_sources: list of methods of getting this implementation
362 @type download_sources: [L{RetrievalMethod}]
363 @ivar feed: the feed owning this implementation (since 0.32)
364 @type feed: [L{ZeroInstallFeed}]
365 @ivar bindings: how to tell this component where it itself is located (since 0.31)
366 @type bindings: [Binding]
367 @ivar upstream_stability: the stability reported by the packager
368 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged]
369 @ivar user_stability: the stability as set by the user
370 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred]
371 @ivar langs: natural languages supported by this package
372 @ivar requires: interfaces this package depends on
373 @ivar main: the default file to execute when running as a program
374 @ivar metadata: extra metadata from the feed
375 @type metadata: {"[URI ]localName": str}
376 @ivar id: a unique identifier for this Implementation
377 @ivar version: a parsed version number
378 @ivar released: release date
381 # Note: user_stability shouldn't really be here
383 __slots__
= ['upstream_stability', 'user_stability', 'langs',
384 'requires', 'main', 'metadata', 'download_sources',
385 'id', 'feed', 'version', 'released', 'bindings', 'machine']
387 def __init__(self
, feed
, id):
392 self
.user_stability
= None
393 self
.upstream_stability
= None
394 self
.metadata
= {} # [URI + " "] + localName -> value
398 self
.download_sources
= []
403 def get_stability(self
):
404 return self
.user_stability
or self
.upstream_stability
or testing
410 return "v%s (%s)" % (self
.get_version(), self
.id)
412 def __cmp__(self
, other
):
413 """Newer versions come first"""
414 return cmp(other
.version
, self
.version
)
416 def get_version(self
):
417 """Return the version as a string.
418 @see: L{format_version}
420 return format_version(self
.version
)
422 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
426 class DistributionImplementation(Implementation
):
427 """An implementation provided by the distribution. Information such as the version
428 comes from the package manager.
430 __slots__
= ['installed']
432 def __init__(self
, feed
, id):
433 assert id.startswith('package:')
434 Implementation
.__init
__(self
, feed
, id)
435 self
.installed
= True
437 class ZeroInstallImplementation(Implementation
):
438 """An implementation where all the information comes from Zero Install.
440 __slots__
= ['os', 'size']
442 def __init__(self
, feed
, id):
443 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
444 Implementation
.__init
__(self
, feed
, id)
449 dependencies
= property(lambda self
: dict([(x
.interface
, x
) for x
in self
.requires
450 if isinstance(x
, InterfaceDependency
)]))
452 def add_download_source(self
, url
, size
, extract
, start_offset
= 0, type = None):
453 """Add a download source."""
454 self
.download_sources
.append(DownloadSource(self
, url
, size
, extract
, start_offset
, type))
456 def set_arch(self
, arch
):
457 self
.os
, self
.machine
= _split_arch(arch
)
458 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
), set_arch
)
460 class Interface(object):
461 """An Interface represents some contract of behaviour.
462 @ivar uri: the URI for this interface.
463 @ivar stability_policy: user's configured policy.
464 Implementations at this level or higher are preferred.
465 Lower levels are used only if there is no other choice.
467 __slots__
= ['uri', 'stability_policy', '_main_feed', 'extra_feeds']
469 implementations
= property(lambda self
: self
._main
_feed
.implementations
)
470 name
= property(lambda self
: self
._main
_feed
.name
)
471 description
= property(lambda self
: self
._main
_feed
.description
)
472 summary
= property(lambda self
: self
._main
_feed
.summary
)
473 last_modified
= property(lambda self
: self
._main
_feed
.last_modified
)
474 feeds
= property(lambda self
: self
.extra_feeds
+ self
._main
_feed
.feeds
)
475 metadata
= property(lambda self
: self
._main
_feed
.metadata
)
477 last_checked
= property(lambda self
: self
._main
_feed
.last_checked
)
479 def __init__(self
, uri
):
481 if uri
.startswith('http:') or uri
.startswith('/'):
484 raise SafeException(_("Interface name '%s' doesn't start "
485 "with 'http:'") % uri
)
488 def _get_feed_for(self
):
490 for key
in self
._main
_feed
.feed_for
:
493 feed_for
= property(_get_feed_for
) # Deprecated (used by 0publish)
496 self
.extra_feeds
= []
497 self
._main
_feed
= _dummy_feed
498 self
.stability_policy
= None
501 if self
._main
_feed
is not _dummy_feed
:
502 return self
._main
_feed
.get_name()
503 return '(' + os
.path
.basename(self
.uri
) + ')'
506 return _("<Interface %s>") % self
.uri
508 def set_stability_policy(self
, new
):
509 assert new
is None or isinstance(new
, Stability
)
510 self
.stability_policy
= new
512 def get_feed(self
, url
):
513 for x
in self
.extra_feeds
:
516 return self
._main
_feed
.get_feed(url
)
518 def get_metadata(self
, uri
, name
):
519 return self
._main
_feed
.get_metadata(uri
, name
)
521 def _merge_attrs(attrs
, item
):
522 """Add each attribute of item to a copy of attrs and return the copy.
523 @type attrs: {str: str}
524 @type item: L{qdom.Element}
529 new
[str(a
)] = item
.attrs
[a
]
532 def _get_long(elem
, attr_name
):
533 val
= elem
.getAttribute(attr_name
)
537 except ValueError, ex
:
538 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name
, 'value': val
})
541 class ZeroInstallFeed(object):
542 """A feed lists available implementations of an interface.
543 @ivar url: the URL for this feed
544 @ivar implementations: Implementations in this feed, indexed by ID
545 @type implementations: {str: L{Implementation}}
546 @ivar name: human-friendly name
547 @ivar summary: short textual description
548 @ivar description: long textual description
549 @ivar last_modified: timestamp on signature
550 @ivar last_checked: time feed was last successfully downloaded and updated
551 @ivar feeds: list of <feed> elements in this feed
552 @type feeds: [L{Feed}]
553 @ivar feed_for: interfaces for which this could be a feed
554 @type feed_for: set(str)
555 @ivar metadata: extra elements we didn't understand
557 # _main is deprecated
558 __slots__
= ['url', 'implementations', 'name', 'description', 'summary',
559 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
561 def __init__(self
, feed_element
, local_path
= None, distro
= None):
562 """Create a feed object from a DOM.
563 @param feed_element: the root element of a feed file
564 @type feed_element: L{qdom.Element}
565 @param local_path: the pathname of this local feed, or None for remote feeds
566 @param distro: used to resolve distribution package references
567 @type distro: L{distro.Distribution} or None"""
569 self
.implementations
= {}
572 self
.description
= ""
573 self
.last_modified
= None
575 self
.feed_for
= set()
577 self
.last_checked
= None
579 assert feed_element
.name
in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
580 assert feed_element
.uri
== XMLNS_IFACE
, "Wrong namespace on root element: %s" % feed_element
.uri
582 main
= feed_element
.getAttribute('main')
583 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
586 self
.url
= local_path
587 local_dir
= os
.path
.dirname(local_path
)
589 self
.url
= feed_element
.getAttribute('uri')
591 raise InvalidInterface(_("<interface> uri attribute missing"))
592 local_dir
= None # Can't have relative paths
594 min_injector_version
= feed_element
.getAttribute('min-injector-version')
595 if min_injector_version
:
596 if parse_version(min_injector_version
) > parse_version(version
):
597 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
598 "Zero Install, but I am only version %(version)s. "
599 "You can get a newer version from http://0install.net") %
600 {'min_version': min_injector_version
, 'version': version
})
602 for x
in feed_element
.childNodes
:
603 if x
.uri
!= XMLNS_IFACE
:
604 self
.metadata
.append(x
)
607 self
.name
= x
.content
608 elif x
.name
== 'description':
609 self
.description
= x
.content
610 elif x
.name
== 'summary':
611 self
.summary
= x
.content
612 elif x
.name
== 'feed-for':
613 feed_iface
= x
.getAttribute('interface')
615 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
616 self
.feed_for
.add(feed_iface
)
617 # Bug report from a Debian/stable user that --feed gets the wrong value.
618 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
619 # in case it happens again.
620 debug(_("Is feed-for %s"), feed_iface
)
621 elif x
.name
== 'feed':
622 feed_src
= x
.getAttribute('src')
624 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
625 if feed_src
.startswith('http:') or local_path
:
626 self
.feeds
.append(Feed(feed_src
, x
.getAttribute('arch'), False, langs
= x
.getAttribute('langs')))
628 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src
)
630 self
.metadata
.append(x
)
633 raise InvalidInterface(_("Missing <name> in feed"))
635 raise InvalidInterface(_("Missing <summary> in feed"))
637 def process_group(group
, group_attrs
, base_depends
, base_bindings
):
638 for item
in group
.childNodes
:
639 if item
.uri
!= XMLNS_IFACE
: continue
641 if item
.name
not in ('group', 'implementation', 'package-implementation'):
644 depends
= base_depends
[:]
645 bindings
= base_bindings
[:]
647 item_attrs
= _merge_attrs(group_attrs
, item
)
649 # We've found a group or implementation. Scan for dependencies
650 # and bindings. Doing this here means that:
651 # - We can share the code for groups and implementations here.
652 # - The order doesn't matter, because these get processed first.
653 # A side-effect is that the document root cannot contain
655 for child
in item
.childNodes
:
656 if child
.uri
!= XMLNS_IFACE
: continue
657 if child
.name
== 'requires':
658 dep
= process_depends(child
)
660 elif child
.name
in binding_names
:
661 bindings
.append(process_binding(child
))
663 if item
.name
== 'group':
664 process_group(item
, item_attrs
, depends
, bindings
)
665 elif item
.name
== 'implementation':
666 process_impl(item
, item_attrs
, depends
, bindings
)
667 elif item
.name
== 'package-implementation':
668 process_native_impl(item
, item_attrs
, depends
)
672 def process_impl(item
, item_attrs
, depends
, bindings
):
673 id = item
.getAttribute('id')
675 raise InvalidInterface(_("Missing 'id' attribute on %s") % item
)
676 if local_dir
and (id.startswith('/') or id.startswith('.')):
677 impl
= self
._get
_impl
(os
.path
.abspath(os
.path
.join(local_dir
, id)))
680 raise InvalidInterface(_('Invalid "id"; form is "alg=value" (got "%s")') % id)
681 alg
, sha1
= id.split('=')
684 except Exception, ex
:
685 raise InvalidInterface(_('Bad SHA1 attribute: %s') % ex
)
686 impl
= self
._get
_impl
(id)
688 impl
.metadata
= item_attrs
690 version_mod
= item_attrs
.get('version-modifier', None)
692 item_attrs
['version'] += version_mod
693 del item_attrs
['version-modifier']
694 version
= item_attrs
['version']
696 raise InvalidInterface(_("Missing version attribute"))
697 impl
.version
= parse_version(version
)
699 item_main
= item_attrs
.get('main', None)
700 if item_main
and item_main
.startswith('/'):
701 raise InvalidInterface(_("'main' attribute must be relative, but '%s' starts with '/'!") %
703 impl
.main
= item_main
705 impl
.released
= item_attrs
.get('released', None)
706 impl
.langs
= item_attrs
.get('langs', None)
708 size
= item
.getAttribute('size')
710 impl
.size
= long(size
)
711 impl
.arch
= item_attrs
.get('arch', None)
713 stability
= stability_levels
[str(item_attrs
['stability'])]
715 stab
= str(item_attrs
['stability'])
716 if stab
!= stab
.lower():
717 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs
.stability
)
718 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs
['stability'])
719 if stability
>= preferred
:
720 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
721 impl
.upstream_stability
= stability
723 impl
.bindings
= bindings
724 impl
.requires
= depends
726 for elem
in item
.childNodes
:
727 if elem
.uri
!= XMLNS_IFACE
: continue
728 if elem
.name
== 'archive':
729 url
= elem
.getAttribute('href')
731 raise InvalidInterface(_("Missing href attribute on <archive>"))
732 size
= elem
.getAttribute('size')
734 raise InvalidInterface(_("Missing size attribute on <archive>"))
735 impl
.add_download_source(url
= url
, size
= long(size
),
736 extract
= elem
.getAttribute('extract'),
737 start_offset
= _get_long(elem
, 'start-offset'),
738 type = elem
.getAttribute('type'))
739 elif elem
.name
== 'recipe':
741 for recipe_step
in elem
.childNodes
:
742 if recipe_step
.uri
== XMLNS_IFACE
and recipe_step
.name
== 'archive':
743 url
= recipe_step
.getAttribute('href')
745 raise InvalidInterface(_("Missing href attribute on <archive>"))
746 size
= recipe_step
.getAttribute('size')
748 raise InvalidInterface(_("Missing size attribute on <archive>"))
749 recipe
.steps
.append(DownloadSource(None, url
= url
, size
= long(size
),
750 extract
= recipe_step
.getAttribute('extract'),
751 start_offset
= _get_long(recipe_step
, 'start-offset'),
752 type = recipe_step
.getAttribute('type')))
754 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step
.name
)
757 impl
.download_sources
.append(recipe
)
759 def process_native_impl(item
, item_attrs
, depends
):
760 package
= item_attrs
.get('package', None)
762 raise InvalidInterface(_("Missing 'package' attribute on %s") % item
)
765 assert id.startswith('package:')
766 impl
= self
._get
_impl
(id)
768 impl
.metadata
= item_attrs
770 item_main
= item_attrs
.get('main', None)
771 if item_main
and not item_main
.startswith('/'):
772 raise InvalidInterface(_("'main' attribute must be absolute, but '%s' doesn't start with '/'!") %
774 impl
.main
= item_main
775 impl
.upstream_stability
= packaged
776 impl
.requires
= depends
780 distro
.get_package_info(package
, factory
)
782 root_attrs
= {'stability': 'testing'}
784 root_attrs
['main'] = main
785 process_group(feed_element
, root_attrs
, [], [])
788 return self
.name
or '(' + os
.path
.basename(self
.url
) + ')'
791 return _("<Feed %s>") % self
.url
793 def _get_impl(self
, id):
794 if id not in self
.implementations
:
795 if id.startswith('package:'):
796 impl
= DistributionImplementation(self
, id)
798 impl
= ZeroInstallImplementation(self
, id)
799 self
.implementations
[id] = impl
800 return self
.implementations
[id]
802 def set_stability_policy(self
, new
):
803 assert new
is None or isinstance(new
, Stability
)
804 self
.stability_policy
= new
806 def get_feed(self
, url
):
812 def add_metadata(self
, elem
):
813 self
.metadata
.append(elem
)
815 def get_metadata(self
, uri
, name
):
816 """Return a list of interface metadata elements with this name and namespace URI."""
817 return [m
for m
in self
.metadata
if m
.name
== name
and m
.uri
== uri
]
819 class DummyFeed(object):
820 """Temporary class used during API transition."""
823 last_checked
= property(lambda self
: None)
824 implementations
= property(lambda self
: {})
825 feeds
= property(lambda self
: [])
826 summary
= property(lambda self
: '-')
827 description
= property(lambda self
: '')
828 def get_name(self
): return self
.name
829 def get_feed(self
, url
): return None
830 def get_metadata(self
, uri
, name
): return []
831 _dummy_feed
= DummyFeed()
834 """Convert each %20 to a space, etc.
836 uri
= uri
.replace('#', '/')
837 if '%' not in uri
: return uri
838 return re
.sub('%[0-9a-fA-F][0-9a-fA-F]',
839 lambda match
: chr(int(match
.group(0)[1:], 16)),
843 """Convert each space to %20, etc
845 return re
.sub('[^-_.a-zA-Z0-9]',
846 lambda match
: '%%%02x' % ord(match
.group(0)),
849 def _pretty_escape(uri
):
850 """Convert each space to %20, etc
851 : is preserved and / becomes #. This makes for nicer strings,
852 and may replace L{escape} everywhere in future.
854 return re
.sub('[^-_.a-zA-Z0-9:/]',
855 lambda match
: '%%%02x' % ord(match
.group(0)),
856 uri
.encode('utf-8')).replace('/', '#')
858 def canonical_iface_uri(uri
):
859 """If uri is a relative path, convert to an absolute one.
860 A "file:///foo" URI is converted to "/foo".
861 Otherwise, return it unmodified.
863 @raise SafeException: if uri isn't valid
865 if uri
.startswith('http://'):
866 if uri
.find("/", 7) == -1:
867 raise SafeException(_("Missing / after hostname in URI '%s'") % uri
)
869 elif uri
.startswith('file:///'):
872 iface_uri
= os
.path
.realpath(uri
)
873 if os
.path
.isfile(iface_uri
):
875 raise SafeException(_("Bad interface name '%(uri)s'.\n"
876 "(doesn't start with 'http:', and "
877 "doesn't exist as a local file '%(interface_uri)s' either)") %
878 {'uri': uri
, 'interface_uri': iface_uri
})
880 _version_mod_to_value
= {
888 _version_value_to_mod
= {}
889 for x
in _version_mod_to_value
: _version_value_to_mod
[_version_mod_to_value
[x
]] = x
892 _version_re
= re
.compile('-([a-z]*)')
894 def parse_version(version_string
):
895 """Convert a version string to an internal representation.
896 The parsed format can be compared quickly using the standard Python functions.
897 - Version := DottedList ("-" Mod DottedList?)*
898 - DottedList := (Integer ("." Integer)*)
899 @rtype: tuple (opaque)
900 @raise SafeException: if the string isn't a valid version
901 @since: 0.24 (moved from L{reader}, from where it is still available):"""
902 if version_string
is None: return None
903 parts
= _version_re
.split(version_string
)
905 del parts
[-1] # Ends with a modifier
909 raise SafeException(_("Empty version string!"))
912 for x
in range(0, l
, 2):
915 parts
[x
] = map(int, parts
[x
].split('.'))
917 parts
[x
] = [] # (because ''.split('.') == [''], not [])
918 for x
in range(1, l
, 2):
919 parts
[x
] = _version_mod_to_value
[parts
[x
]]
921 except ValueError, ex
:
922 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string
, 'exception': ex
})
924 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string
, 'exception': ex
})
926 def format_version(version
):
927 """Format a parsed version for display. Undoes the effect of L{parse_version}.
928 @see: L{Implementation.get_version}
933 for x
in range(0, l
, 2):
934 version
[x
] = '.'.join(map(str, version
[x
]))
935 for x
in range(1, l
, 2):
936 version
[x
] = '-' + _version_value_to_mod
[version
[x
]]
937 if version
[-1] == '-': del version
[-1]
938 return ''.join(version
)