Don't install N_() in the builtin namespace
[zeroinstall/zeroinstall-rsl.git] / zeroinstall / injector / model.py
blobea130c11fc5bba8d172be6c8f51560ab26d6bc30
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
4 file in memory.
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
10 well-known variables.
11 """
13 # Copyright (C) 2009, Thomas Leonard
14 # See the README file for details, or visit http://0install.net.
16 import os, re
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'
26 network_full = 'full'
27 network_levels = (network_offline, network_minimal, network_full)
29 stability_levels = {} # Name -> Stability
31 defaults = {
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):
40 if ex:
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."""
46 if not arch:
47 return None, None
48 elif '-' not in arch:
49 raise SafeException(_("Malformed arch '%s'") % arch)
50 else:
51 osys, machine = arch.split('-', 1)
52 if osys == '*': osys = None
53 if machine == '*': machine = None
54 return osys, machine
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):
65 self.level = level
66 self.name = name
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)
74 def __str__(self):
75 return self.name
77 def __repr__(self):
78 return _("<Stability: %s>") % self.description
80 def process_binding(e):
81 """Internal"""
82 if e.name == 'environment':
83 mode = {
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'),
93 mode = mode)
94 if not binding.name: raise InvalidInterface(_("Missing 'name' in binding"))
95 if binding.insert is None: raise InvalidInterface(_("Missing 'insert' in binding"))
96 return binding
97 elif e.name == 'overlay':
98 return OverlayBinding(e.getAttribute('src'), e.getAttribute('mount-point'))
99 else:
100 raise Exception(_("Unknown binding type '%s'") % e.name)
102 def process_depends(item):
103 """Internal"""
104 # Note: also called from selections
105 dep_iface = item.getAttribute('interface')
106 if not dep_iface:
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'))))
118 return dependency
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'))
130 del N_
132 class Restriction(object):
133 """A Restriction limits the allowed implementations of an Interface."""
134 __slots__ = []
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
139 @rtype: bool
141 raise NotImplementedError(_("Abstract"))
143 class VersionRestriction(Restriction):
144 """Only select implementations with a particular version number.
145 @since: 0.40"""
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
156 def __str__(self):
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
168 self.before = before
169 self.not_before = not_before
171 def meets_restriction(self, impl):
172 if self.not_before and impl.version < self.not_before:
173 return False
174 if self.before and impl.version >= self.before:
175 return False
176 return True
178 def __str__(self):
179 if self.not_before is not None or self.before is not None:
180 range = ''
181 if self.not_before is not None:
182 range += format_version(self.not_before) + ' <= '
183 range += 'version'
184 if self.before is not None:
185 range += ' < ' + format_version(self.before)
186 else:
187 range = 'none'
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']
198 PREPEND = 'prepend'
199 APPEND = 'append'
200 REPLACE = 'replace'
202 def __init__(self, name, insert, default = None, mode = PREPEND):
203 """mode argument added in version 0.28"""
204 self.name = name
205 self.insert = insert
206 self.default = default
207 self.mode = mode
209 def __str__(self):
210 return _("<environ %(name)s %(mode)s %(insert)s>") % {'name': self.name,'mode': self.mode, 'insert': self.insert}
212 __repr__ = __str__
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:
222 return extra
224 if old_value is None:
225 old_value = self.default or defaults.get(self.name, None)
226 if old_value is None:
227 return extra
228 if self.mode == EnvironmentBinding.PREPEND:
229 return extra + ':' + old_value
230 else:
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)
241 if self.default:
242 env_elem.setAttributeNS(None, 'default', self.default)
243 return env_elem
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):
251 self.src = src
252 self.mount_point = mount_point
254 def __str__(self):
255 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self.src or '.', 'mount_point': self.mount_point or '/'}
257 __repr__ = __str__
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)
269 return env_elem
271 class Feed(object):
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):
276 self.uri = uri
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)
281 self.langs = langs
283 def __str__(self):
284 return "<Feed from %s>" % self.uri
285 __repr__ = __str__
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):
298 if metadata is None:
299 metadata = {}
300 else:
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
307 @type interface: str
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}]
312 @since: 0.28
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))
319 assert interface
320 self.interface = interface
321 if restrictions is None:
322 self.restrictions = []
323 else:
324 self.restrictions = restrictions
325 self.bindings = []
327 def __str__(self):
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."""
332 __slots__ = []
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
340 self.url = url
341 self.size = size
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
349 @type size: int
350 @ivar steps: the sequence of steps which must be performed
351 @type steps: [L{RetrievalMethod}]"""
352 __slots__ = ['steps']
354 def __init__(self):
355 self.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):
388 assert id
389 self.feed = feed
390 self.id = id
391 self.main = None
392 self.user_stability = None
393 self.upstream_stability = None
394 self.metadata = {} # [URI + " "] + localName -> value
395 self.requires = []
396 self.version = None
397 self.released = None
398 self.download_sources = []
399 self.langs = None
400 self.machine = None
401 self.bindings = []
403 def get_stability(self):
404 return self.user_stability or self.upstream_stability or testing
406 def __str__(self):
407 return self.id
409 def __repr__(self):
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))
424 os = None
426 class DistributionImplementation(Implementation):
427 """An implementation provided by the distribution. Information such as the version
428 comes from the package manager.
429 @since: 0.28"""
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.
439 @since: 0.28"""
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)
445 self.size = None
446 self.os = None
448 # Deprecated
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):
480 assert uri
481 if uri.startswith('http:') or uri.startswith('/'):
482 self.uri = uri
483 else:
484 raise SafeException(_("Interface name '%s' doesn't start "
485 "with 'http:'") % uri)
486 self.reset()
488 def _get_feed_for(self):
489 retval = {}
490 for key in self._main_feed.feed_for:
491 retval[key] = True
492 return retval
493 feed_for = property(_get_feed_for) # Deprecated (used by 0publish)
495 def reset(self):
496 self.extra_feeds = []
497 self._main_feed = _dummy_feed
498 self.stability_policy = None
500 def get_name(self):
501 if self._main_feed is not _dummy_feed:
502 return self._main_feed.get_name()
503 return '(' + os.path.basename(self.uri) + ')'
505 def __repr__(self):
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:
514 if x.uri == url:
515 return x
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}
525 @rtype: {str: str}
527 new = attrs.copy()
528 for a in item.attrs:
529 new[str(a)] = item.attrs[a]
530 return new
532 def _get_long(elem, attr_name):
533 val = elem.getAttribute(attr_name)
534 if val is not None:
535 try:
536 val = long(val)
537 except ValueError, ex:
538 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name, 'value': val})
539 return 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"""
568 assert feed_element
569 self.implementations = {}
570 self.name = None
571 self.summary = None
572 self.description = ""
573 self.last_modified = None
574 self.feeds = []
575 self.feed_for = set()
576 self.metadata = []
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")
585 if local_path:
586 self.url = local_path
587 local_dir = os.path.dirname(local_path)
588 else:
589 self.url = feed_element.getAttribute('uri')
590 if not self.url:
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)
605 continue
606 if x.name == 'name':
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')
614 if not feed_iface:
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')
623 if not feed_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')))
627 else:
628 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src)
629 else:
630 self.metadata.append(x)
632 if not self.name:
633 raise InvalidInterface(_("Missing <name> in feed"))
634 if not self.summary:
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'):
642 continue
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
654 # these.
655 for child in item.childNodes:
656 if child.uri != XMLNS_IFACE: continue
657 if child.name == 'requires':
658 dep = process_depends(child)
659 depends.append(dep)
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)
669 else:
670 assert 0
672 def process_impl(item, item_attrs, depends, bindings):
673 id = item.getAttribute('id')
674 if id is None:
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)))
678 else:
679 if '=' not in id:
680 raise InvalidInterface(_('Invalid "id"; form is "alg=value" (got "%s")') % id)
681 alg, sha1 = id.split('=')
682 try:
683 long(sha1, 16)
684 except Exception, ex:
685 raise InvalidInterface(_('Bad SHA1 attribute: %s') % ex)
686 impl = self._get_impl(id)
688 impl.metadata = item_attrs
689 try:
690 version_mod = item_attrs.get('version-modifier', None)
691 if version_mod:
692 item_attrs['version'] += version_mod
693 del item_attrs['version-modifier']
694 version = item_attrs['version']
695 except KeyError:
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 '/'!") %
702 item_main)
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')
709 if size:
710 impl.size = long(size)
711 impl.arch = item_attrs.get('arch', None)
712 try:
713 stability = stability_levels[str(item_attrs['stability'])]
714 except KeyError:
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')
730 if not url:
731 raise InvalidInterface(_("Missing href attribute on <archive>"))
732 size = elem.getAttribute('size')
733 if not 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':
740 recipe = 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')
744 if not url:
745 raise InvalidInterface(_("Missing href attribute on <archive>"))
746 size = recipe_step.getAttribute('size')
747 if not 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')))
753 else:
754 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step.name)
755 break
756 else:
757 impl.download_sources.append(recipe)
759 def process_native_impl(item, item_attrs, depends):
760 package = item_attrs.get('package', None)
761 if package is None:
762 raise InvalidInterface(_("Missing 'package' attribute on %s") % item)
764 def factory(id):
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 '/'!") %
773 item_main)
774 impl.main = item_main
775 impl.upstream_stability = packaged
776 impl.requires = depends
778 return impl
780 distro.get_package_info(package, factory)
782 root_attrs = {'stability': 'testing'}
783 if main:
784 root_attrs['main'] = main
785 process_group(feed_element, root_attrs, [], [])
787 def get_name(self):
788 return self.name or '(' + os.path.basename(self.url) + ')'
790 def __repr__(self):
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)
797 else:
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):
807 for x in self.feeds:
808 if x.uri == url:
809 return x
810 return None
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."""
821 last_modified = None
822 name = '-'
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()
833 def unescape(uri):
834 """Convert each %20 to a space, etc.
835 @rtype: str"""
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)),
840 uri).decode('utf-8')
842 def escape(uri):
843 """Convert each space to %20, etc
844 @rtype: str"""
845 return re.sub('[^-_.a-zA-Z0-9]',
846 lambda match: '%%%02x' % ord(match.group(0)),
847 uri.encode('utf-8'))
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.
853 @rtype: str"""
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.
862 @rtype: str
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)
868 return uri
869 elif uri.startswith('file:///'):
870 return uri[7:]
871 else:
872 iface_uri = os.path.realpath(uri)
873 if os.path.isfile(iface_uri):
874 return 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 = {
881 'pre': -2,
882 'rc': -1,
883 '': 0,
884 'post': 1,
887 # Reverse mapping
888 _version_value_to_mod = {}
889 for x in _version_mod_to_value: _version_value_to_mod[_version_mod_to_value[x]] = x
890 del 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)
904 if parts[-1] == '':
905 del parts[-1] # Ends with a modifier
906 else:
907 parts.append('')
908 if not parts:
909 raise SafeException(_("Empty version string!"))
910 l = len(parts)
911 try:
912 for x in range(0, l, 2):
913 part = parts[x]
914 if part:
915 parts[x] = map(int, parts[x].split('.'))
916 else:
917 parts[x] = [] # (because ''.split('.') == [''], not [])
918 for x in range(1, l, 2):
919 parts[x] = _version_mod_to_value[parts[x]]
920 return parts
921 except ValueError, ex:
922 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
923 except KeyError, 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}
929 @rtype: str
930 @since: 0.24"""
931 version = version[:]
932 l = len(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)