Added support for @local-path attribute when parsing feeds
[zeroinstall/solver.git] / zeroinstall / injector / model.py
blob5c89c67f90fd0eb029cfee9ae075528e04e1e7c3
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 from zeroinstall import _
17 import os, re
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'
27 network_full = 'full'
28 network_levels = (network_offline, network_minimal, network_full)
30 stability_levels = {} # Name -> Stability
32 defaults = {
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):
41 if ex:
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."""
47 if not arch:
48 return None, None
49 elif '-' not in arch:
50 raise SafeException(_("Malformed arch '%s'") % arch)
51 else:
52 osys, machine = arch.split('-', 1)
53 if osys == '*': osys = None
54 if machine == '*': machine = None
55 return osys, machine
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):
66 self.level = level
67 self.name = name
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)
75 def __str__(self):
76 return self.name
78 def __repr__(self):
79 return _("<Stability: %s>") % self.description
81 def process_binding(e):
82 """Internal"""
83 if e.name == 'environment':
84 mode = {
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'),
94 mode = mode)
95 if not binding.name: raise InvalidInterface(_("Missing 'name' in binding"))
96 if binding.insert is None: raise InvalidInterface(_("Missing 'insert' in binding"))
97 return binding
98 elif e.name == 'overlay':
99 return OverlayBinding(e.getAttribute('src'), e.getAttribute('mount-point'))
100 else:
101 raise Exception(_("Unknown binding type '%s'") % e.name)
103 def process_depends(item):
104 """Internal"""
105 # Note: also called from selections
106 dep_iface = item.getAttribute('interface')
107 if not dep_iface:
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'))))
119 return dependency
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'))
131 del N_
133 class Restriction(object):
134 """A Restriction limits the allowed implementations of an Interface."""
135 __slots__ = []
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
140 @rtype: bool
142 raise NotImplementedError(_("Abstract"))
144 class VersionRestriction(Restriction):
145 """Only select implementations with a particular version number.
146 @since: 0.40"""
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
157 def __str__(self):
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
169 self.before = before
170 self.not_before = not_before
172 def meets_restriction(self, impl):
173 if self.not_before and impl.version < self.not_before:
174 return False
175 if self.before and impl.version >= self.before:
176 return False
177 return True
179 def __str__(self):
180 if self.not_before is not None or self.before is not None:
181 range = ''
182 if self.not_before is not None:
183 range += format_version(self.not_before) + ' <= '
184 range += 'version'
185 if self.before is not None:
186 range += ' < ' + format_version(self.before)
187 else:
188 range = 'none'
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']
199 PREPEND = 'prepend'
200 APPEND = 'append'
201 REPLACE = 'replace'
203 def __init__(self, name, insert, default = None, mode = PREPEND):
204 """mode argument added in version 0.28"""
205 self.name = name
206 self.insert = insert
207 self.default = default
208 self.mode = mode
210 def __str__(self):
211 return _("<environ %(name)s %(mode)s %(insert)s>") % {'name': self.name,'mode': self.mode, 'insert': self.insert}
213 __repr__ = __str__
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:
223 return extra
225 if old_value is None:
226 old_value = self.default or defaults.get(self.name, None)
227 if old_value is None:
228 return extra
229 if self.mode == EnvironmentBinding.PREPEND:
230 return extra + ':' + old_value
231 else:
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)
242 if self.default:
243 env_elem.setAttributeNS(None, 'default', self.default)
244 return env_elem
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):
252 self.src = src
253 self.mount_point = mount_point
255 def __str__(self):
256 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self.src or '.', 'mount_point': self.mount_point or '/'}
258 __repr__ = __str__
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)
270 return env_elem
272 class Feed(object):
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):
277 self.uri = uri
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)
282 self.langs = langs
284 def __str__(self):
285 return "<Feed from %s>" % self.uri
286 __repr__ = __str__
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):
299 if metadata is None:
300 metadata = {}
301 else:
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
308 @type interface: str
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}]
313 @since: 0.28
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))
320 assert interface
321 self.interface = interface
322 if restrictions is None:
323 self.restrictions = []
324 else:
325 self.restrictions = restrictions
326 self.bindings = []
328 def __str__(self):
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."""
333 __slots__ = []
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
341 self.url = url
342 self.size = size
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
350 @type size: int
351 @ivar steps: the sequence of steps which must be performed
352 @type steps: [L{RetrievalMethod}]"""
353 __slots__ = ['steps']
355 def __init__(self):
356 self.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 @ivar main: the default file to execute when running as a program
375 @ivar metadata: extra metadata from the feed
376 @type metadata: {"[URI ]localName": str}
377 @ivar id: a unique identifier for this Implementation
378 @ivar version: a parsed version number
379 @ivar released: release date
380 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path)
381 @type local_path: str | None
384 # Note: user_stability shouldn't really be here
386 __slots__ = ['upstream_stability', 'user_stability', 'langs',
387 'requires', 'main', 'metadata', 'download_sources',
388 'id', 'feed', 'version', 'released', 'bindings', 'machine']
390 def __init__(self, feed, id):
391 assert id
392 self.feed = feed
393 self.id = id
394 self.main = None
395 self.user_stability = None
396 self.upstream_stability = None
397 self.metadata = {} # [URI + " "] + localName -> value
398 self.requires = []
399 self.version = None
400 self.released = None
401 self.download_sources = []
402 self.langs = None
403 self.machine = None
404 self.bindings = []
406 def get_stability(self):
407 return self.user_stability or self.upstream_stability or testing
409 def __str__(self):
410 return self.id
412 def __repr__(self):
413 return "v%s (%s)" % (self.get_version(), self.id)
415 def __cmp__(self, other):
416 """Newer versions come first"""
417 return cmp(other.version, self.version)
419 def get_version(self):
420 """Return the version as a string.
421 @see: L{format_version}
423 return format_version(self.version)
425 arch = property(lambda self: _join_arch(self.os, self.machine))
427 os = None
429 local_path = None
431 class DistributionImplementation(Implementation):
432 """An implementation provided by the distribution. Information such as the version
433 comes from the package manager.
434 @since: 0.28"""
435 __slots__ = ['installed']
437 def __init__(self, feed, id):
438 assert id.startswith('package:')
439 Implementation.__init__(self, feed, id)
440 self.installed = True
442 class ZeroInstallImplementation(Implementation):
443 """An implementation where all the information comes from Zero Install.
444 @ivar digests: a list of "algorith=value" strings (since 0.45)
445 @type digests: [str]
446 @since: 0.28"""
447 __slots__ = ['os', 'size', 'digests', 'local_path']
449 def __init__(self, feed, id, local_path):
450 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
451 assert not id.startswith('package:'), id
452 Implementation.__init__(self, feed, id)
453 self.size = None
454 self.os = None
455 self.digests = []
456 self.local_path = local_path
458 # Deprecated
459 dependencies = property(lambda self: dict([(x.interface, x) for x in self.requires
460 if isinstance(x, InterfaceDependency)]))
462 def add_download_source(self, url, size, extract, start_offset = 0, type = None):
463 """Add a download source."""
464 self.download_sources.append(DownloadSource(self, url, size, extract, start_offset, type))
466 def set_arch(self, arch):
467 self.os, self.machine = _split_arch(arch)
468 arch = property(lambda self: _join_arch(self.os, self.machine), set_arch)
470 class Interface(object):
471 """An Interface represents some contract of behaviour.
472 @ivar uri: the URI for this interface.
473 @ivar stability_policy: user's configured policy.
474 Implementations at this level or higher are preferred.
475 Lower levels are used only if there is no other choice.
477 __slots__ = ['uri', 'stability_policy', '_main_feed', 'extra_feeds']
479 implementations = property(lambda self: self._main_feed.implementations)
480 name = property(lambda self: self._main_feed.name)
481 description = property(lambda self: self._main_feed.description)
482 summary = property(lambda self: self._main_feed.summary)
483 last_modified = property(lambda self: self._main_feed.last_modified)
484 feeds = property(lambda self: self.extra_feeds + self._main_feed.feeds)
485 metadata = property(lambda self: self._main_feed.metadata)
487 last_checked = property(lambda self: self._main_feed.last_checked)
489 def __init__(self, uri):
490 assert uri
491 if uri.startswith('http:') or uri.startswith('https:') or uri.startswith('/'):
492 self.uri = uri
493 else:
494 raise SafeException(_("Interface name '%s' doesn't start "
495 "with 'http:' or 'https:'") % uri)
496 self.reset()
498 def _get_feed_for(self):
499 retval = {}
500 for key in self._main_feed.feed_for:
501 retval[key] = True
502 return retval
503 feed_for = property(_get_feed_for) # Deprecated (used by 0publish)
505 def reset(self):
506 self.extra_feeds = []
507 self._main_feed = _dummy_feed
508 self.stability_policy = None
510 def get_name(self):
511 if self._main_feed is not _dummy_feed:
512 return self._main_feed.get_name()
513 return '(' + os.path.basename(self.uri) + ')'
515 def __repr__(self):
516 return _("<Interface %s>") % self.uri
518 def set_stability_policy(self, new):
519 assert new is None or isinstance(new, Stability)
520 self.stability_policy = new
522 def get_feed(self, url):
523 for x in self.extra_feeds:
524 if x.uri == url:
525 return x
526 return self._main_feed.get_feed(url)
528 def get_metadata(self, uri, name):
529 return self._main_feed.get_metadata(uri, name)
531 def _merge_attrs(attrs, item):
532 """Add each attribute of item to a copy of attrs and return the copy.
533 @type attrs: {str: str}
534 @type item: L{qdom.Element}
535 @rtype: {str: str}
537 new = attrs.copy()
538 for a in item.attrs:
539 new[str(a)] = item.attrs[a]
540 return new
542 def _get_long(elem, attr_name):
543 val = elem.getAttribute(attr_name)
544 if val is not None:
545 try:
546 val = long(val)
547 except ValueError, ex:
548 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name, 'value': val})
549 return val
551 class ZeroInstallFeed(object):
552 """A feed lists available implementations of an interface.
553 @ivar url: the URL for this feed
554 @ivar implementations: Implementations in this feed, indexed by ID
555 @type implementations: {str: L{Implementation}}
556 @ivar name: human-friendly name
557 @ivar summary: short textual description
558 @ivar description: long textual description
559 @ivar last_modified: timestamp on signature
560 @ivar last_checked: time feed was last successfully downloaded and updated
561 @ivar feeds: list of <feed> elements in this feed
562 @type feeds: [L{Feed}]
563 @ivar feed_for: interfaces for which this could be a feed
564 @type feed_for: set(str)
565 @ivar metadata: extra elements we didn't understand
567 # _main is deprecated
568 __slots__ = ['url', 'implementations', 'name', 'description', 'summary',
569 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
571 def __init__(self, feed_element, local_path = None, distro = None):
572 """Create a feed object from a DOM.
573 @param feed_element: the root element of a feed file
574 @type feed_element: L{qdom.Element}
575 @param local_path: the pathname of this local feed, or None for remote feeds
576 @param distro: used to resolve distribution package references
577 @type distro: L{distro.Distribution} or None"""
578 assert feed_element
579 self.implementations = {}
580 self.name = None
581 self.summary = None
582 self.description = ""
583 self.last_modified = None
584 self.feeds = []
585 self.feed_for = set()
586 self.metadata = []
587 self.last_checked = None
589 assert feed_element.name in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
590 assert feed_element.uri == XMLNS_IFACE, "Wrong namespace on root element: %s" % feed_element.uri
592 main = feed_element.getAttribute('main')
593 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
595 if local_path:
596 self.url = local_path
597 local_dir = os.path.dirname(local_path)
598 else:
599 self.url = feed_element.getAttribute('uri')
600 if not self.url:
601 raise InvalidInterface(_("<interface> uri attribute missing"))
602 local_dir = None # Can't have relative paths
604 min_injector_version = feed_element.getAttribute('min-injector-version')
605 if min_injector_version:
606 if parse_version(min_injector_version) > parse_version(version):
607 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
608 "Zero Install, but I am only version %(version)s. "
609 "You can get a newer version from http://0install.net") %
610 {'min_version': min_injector_version, 'version': version})
612 for x in feed_element.childNodes:
613 if x.uri != XMLNS_IFACE:
614 self.metadata.append(x)
615 continue
616 if x.name == 'name':
617 self.name = x.content
618 elif x.name == 'description':
619 self.description = x.content
620 elif x.name == 'summary':
621 self.summary = x.content
622 elif x.name == 'feed-for':
623 feed_iface = x.getAttribute('interface')
624 if not feed_iface:
625 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
626 self.feed_for.add(feed_iface)
627 # Bug report from a Debian/stable user that --feed gets the wrong value.
628 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
629 # in case it happens again.
630 debug(_("Is feed-for %s"), feed_iface)
631 elif x.name == 'feed':
632 feed_src = x.getAttribute('src')
633 if not feed_src:
634 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
635 if feed_src.startswith('http:') or feed_src.startswith('https:') or local_path:
636 self.feeds.append(Feed(feed_src, x.getAttribute('arch'), False, langs = x.getAttribute('langs')))
637 else:
638 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src)
639 else:
640 self.metadata.append(x)
642 if not self.name:
643 raise InvalidInterface(_("Missing <name> in feed"))
644 if not self.summary:
645 raise InvalidInterface(_("Missing <summary> in feed"))
647 package_impls = [0, []] # Best score so far and packages with that score
649 def process_group(group, group_attrs, base_depends, base_bindings):
650 for item in group.childNodes:
651 if item.uri != XMLNS_IFACE: continue
653 if item.name not in ('group', 'implementation', 'package-implementation'):
654 continue
656 depends = base_depends[:]
657 bindings = base_bindings[:]
659 item_attrs = _merge_attrs(group_attrs, item)
661 # We've found a group or implementation. Scan for dependencies
662 # and bindings. Doing this here means that:
663 # - We can share the code for groups and implementations here.
664 # - The order doesn't matter, because these get processed first.
665 # A side-effect is that the document root cannot contain
666 # these.
667 for child in item.childNodes:
668 if child.uri != XMLNS_IFACE: continue
669 if child.name == 'requires':
670 dep = process_depends(child)
671 depends.append(dep)
672 elif child.name in binding_names:
673 bindings.append(process_binding(child))
675 if item.name == 'group':
676 process_group(item, item_attrs, depends, bindings)
677 elif item.name == 'implementation':
678 process_impl(item, item_attrs, depends, bindings)
679 elif item.name == 'package-implementation':
680 distro_names = item_attrs.get('distributions', '')
681 for distro_name in distro_names.split(' '):
682 score = distro.get_score(distro_name)
683 if score > package_impls[0]:
684 package_impls[0] = score
685 package_impls[1] = []
686 if score == package_impls[0]:
687 package_impls[1].append((item, item_attrs, depends))
688 else:
689 assert 0
691 def process_impl(item, item_attrs, depends, bindings):
692 id = item.getAttribute('id')
693 if id is None:
694 raise InvalidInterface(_("Missing 'id' attribute on %s") % item)
695 local_path = item_attrs.get('local-path')
696 if local_dir and local_path:
697 impl = ZeroInstallImplementation(self, id, local_path)
698 elif local_dir and (id.startswith('/') or id.startswith('.')):
699 # For old feeds
700 id = os.path.abspath(os.path.join(local_dir, id))
701 impl = ZeroInstallImplementation(self, id, id)
702 else:
703 impl = ZeroInstallImplementation(self, id, None)
704 if '=' in id:
705 # In older feeds, the ID was the (single) digest
706 impl.digests.append(id)
707 if id in self.implementations:
708 warn(_("Duplicate ID '%s' in feed '%s'"), id, self)
709 self.implementations[id] = impl
711 impl.metadata = item_attrs
712 try:
713 version_mod = item_attrs.get('version-modifier', None)
714 if version_mod:
715 item_attrs['version'] += version_mod
716 del item_attrs['version-modifier']
717 version = item_attrs['version']
718 except KeyError:
719 raise InvalidInterface(_("Missing version attribute"))
720 impl.version = parse_version(version)
722 item_main = item_attrs.get('main', None)
723 if item_main and item_main.startswith('/'):
724 raise InvalidInterface(_("'main' attribute must be relative, but '%s' starts with '/'!") %
725 item_main)
726 impl.main = item_main
728 impl.released = item_attrs.get('released', None)
729 impl.langs = item_attrs.get('langs', None)
731 size = item.getAttribute('size')
732 if size:
733 impl.size = long(size)
734 impl.arch = item_attrs.get('arch', None)
735 try:
736 stability = stability_levels[str(item_attrs['stability'])]
737 except KeyError:
738 stab = str(item_attrs['stability'])
739 if stab != stab.lower():
740 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs.stability)
741 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs['stability'])
742 if stability >= preferred:
743 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
744 impl.upstream_stability = stability
746 impl.bindings = bindings
747 impl.requires = depends
749 for elem in item.childNodes:
750 if elem.uri != XMLNS_IFACE: continue
751 if elem.name == 'archive':
752 url = elem.getAttribute('href')
753 if not url:
754 raise InvalidInterface(_("Missing href attribute on <archive>"))
755 size = elem.getAttribute('size')
756 if not size:
757 raise InvalidInterface(_("Missing size attribute on <archive>"))
758 impl.add_download_source(url = url, size = long(size),
759 extract = elem.getAttribute('extract'),
760 start_offset = _get_long(elem, 'start-offset'),
761 type = elem.getAttribute('type'))
762 elif elem.name == 'manifest-digest':
763 for aname, avalue in elem.attrs.iteritems():
764 if ' ' not in aname:
765 impl.digests.append('%s=%s' % (aname, avalue))
766 elif elem.name == 'recipe':
767 recipe = Recipe()
768 for recipe_step in elem.childNodes:
769 if recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'archive':
770 url = recipe_step.getAttribute('href')
771 if not url:
772 raise InvalidInterface(_("Missing href attribute on <archive>"))
773 size = recipe_step.getAttribute('size')
774 if not size:
775 raise InvalidInterface(_("Missing size attribute on <archive>"))
776 recipe.steps.append(DownloadSource(None, url = url, size = long(size),
777 extract = recipe_step.getAttribute('extract'),
778 start_offset = _get_long(recipe_step, 'start-offset'),
779 type = recipe_step.getAttribute('type')))
780 else:
781 info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step.name)
782 break
783 else:
784 impl.download_sources.append(recipe)
786 def process_native_impl(item, item_attrs, depends):
787 package = item_attrs.get('package', None)
788 if package is None:
789 raise InvalidInterface(_("Missing 'package' attribute on %s") % item)
791 def factory(id):
792 assert id.startswith('package:')
793 if id in self.implementations:
794 warn(_("Duplicate ID '%s' for DistributionImplementation"), id)
795 impl = DistributionImplementation(self, id)
796 self.implementations[id] = impl
798 impl.metadata = item_attrs
800 item_main = item_attrs.get('main', None)
801 if item_main and not item_main.startswith('/'):
802 raise InvalidInterface(_("'main' attribute must be absolute, but '%s' doesn't start with '/'!") %
803 item_main)
804 impl.main = item_main
805 impl.upstream_stability = packaged
806 impl.requires = depends
808 return impl
810 distro.get_package_info(package, factory)
812 root_attrs = {'stability': 'testing'}
813 if main:
814 root_attrs['main'] = main
815 process_group(feed_element, root_attrs, [], [])
817 for args in package_impls[1]:
818 process_native_impl(*args)
820 def get_name(self):
821 return self.name or '(' + os.path.basename(self.url) + ')'
823 def __repr__(self):
824 return _("<Feed %s>") % self.url
826 """@deprecated"""
827 def _get_impl(self, id):
828 assert id not in self.implementations
830 if id.startswith('.') or id.startswith('/'):
831 id = os.path.abspath(os.path.join(self.url, id))
832 local_path = id
833 impl = ZeroInstallImplementation(self, id, local_path)
834 else:
835 impl = ZeroInstallImplementation(self, id, None)
836 impl.digests.append(id)
838 self.implementations[id] = impl
839 return impl
841 def set_stability_policy(self, new):
842 assert new is None or isinstance(new, Stability)
843 self.stability_policy = new
845 def get_feed(self, url):
846 for x in self.feeds:
847 if x.uri == url:
848 return x
849 return None
851 def add_metadata(self, elem):
852 self.metadata.append(elem)
854 def get_metadata(self, uri, name):
855 """Return a list of interface metadata elements with this name and namespace URI."""
856 return [m for m in self.metadata if m.name == name and m.uri == uri]
858 class DummyFeed(object):
859 """Temporary class used during API transition."""
860 last_modified = None
861 name = '-'
862 last_checked = property(lambda self: None)
863 implementations = property(lambda self: {})
864 feeds = property(lambda self: [])
865 summary = property(lambda self: '-')
866 description = property(lambda self: '')
867 def get_name(self): return self.name
868 def get_feed(self, url): return None
869 def get_metadata(self, uri, name): return []
870 _dummy_feed = DummyFeed()
872 def unescape(uri):
873 """Convert each %20 to a space, etc.
874 @rtype: str"""
875 uri = uri.replace('#', '/')
876 if '%' not in uri: return uri
877 return re.sub('%[0-9a-fA-F][0-9a-fA-F]',
878 lambda match: chr(int(match.group(0)[1:], 16)),
879 uri).decode('utf-8')
881 def escape(uri):
882 """Convert each space to %20, etc
883 @rtype: str"""
884 return re.sub('[^-_.a-zA-Z0-9]',
885 lambda match: '%%%02x' % ord(match.group(0)),
886 uri.encode('utf-8'))
888 def _pretty_escape(uri):
889 """Convert each space to %20, etc
890 : is preserved and / becomes #. This makes for nicer strings,
891 and may replace L{escape} everywhere in future.
892 @rtype: str"""
893 return re.sub('[^-_.a-zA-Z0-9:/]',
894 lambda match: '%%%02x' % ord(match.group(0)),
895 uri.encode('utf-8')).replace('/', '#')
897 def canonical_iface_uri(uri):
898 """If uri is a relative path, convert to an absolute one.
899 A "file:///foo" URI is converted to "/foo".
900 Otherwise, return it unmodified.
901 @rtype: str
902 @raise SafeException: if uri isn't valid
904 if uri.startswith('http://') or uri.startswith('https://'):
905 if uri.count("/") < 3:
906 raise SafeException(_("Missing / after hostname in URI '%s'") % uri)
907 return uri
908 elif uri.startswith('file:///'):
909 return uri[7:]
910 else:
911 iface_uri = os.path.realpath(uri)
912 if os.path.isfile(iface_uri):
913 return iface_uri
914 raise SafeException(_("Bad interface name '%(uri)s'.\n"
915 "(doesn't start with 'http:', and "
916 "doesn't exist as a local file '%(interface_uri)s' either)") %
917 {'uri': uri, 'interface_uri': iface_uri})
919 _version_mod_to_value = {
920 'pre': -2,
921 'rc': -1,
922 '': 0,
923 'post': 1,
926 # Reverse mapping
927 _version_value_to_mod = {}
928 for x in _version_mod_to_value: _version_value_to_mod[_version_mod_to_value[x]] = x
929 del x
931 _version_re = re.compile('-([a-z]*)')
933 def parse_version(version_string):
934 """Convert a version string to an internal representation.
935 The parsed format can be compared quickly using the standard Python functions.
936 - Version := DottedList ("-" Mod DottedList?)*
937 - DottedList := (Integer ("." Integer)*)
938 @rtype: tuple (opaque)
939 @raise SafeException: if the string isn't a valid version
940 @since: 0.24 (moved from L{reader}, from where it is still available):"""
941 if version_string is None: return None
942 parts = _version_re.split(version_string)
943 if parts[-1] == '':
944 del parts[-1] # Ends with a modifier
945 else:
946 parts.append('')
947 if not parts:
948 raise SafeException(_("Empty version string!"))
949 l = len(parts)
950 try:
951 for x in range(0, l, 2):
952 part = parts[x]
953 if part:
954 parts[x] = map(int, parts[x].split('.'))
955 else:
956 parts[x] = [] # (because ''.split('.') == [''], not [])
957 for x in range(1, l, 2):
958 parts[x] = _version_mod_to_value[parts[x]]
959 return parts
960 except ValueError, ex:
961 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
962 except KeyError, ex:
963 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
965 def format_version(version):
966 """Format a parsed version for display. Undoes the effect of L{parse_version}.
967 @see: L{Implementation.get_version}
968 @rtype: str
969 @since: 0.24"""
970 version = version[:]
971 l = len(version)
972 for x in range(0, l, 2):
973 version[x] = '.'.join(map(str, version[x]))
974 for x in range(1, l, 2):
975 version[x] = '-' + _version_value_to_mod[version[x]]
976 if version[-1] == '-': del version[-1]
977 return ''.join(version)