Fixed deprecation warning in GUI
[zeroinstall/solver.git] / zeroinstall / injector / model.py
blobb2c8f6f81cf7b850256f7f857a9525ed72c1ed65
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 _, logger
17 import os, re, locale, sys
18 from zeroinstall import SafeException, version
19 from zeroinstall.injector.namespaces import XMLNS_IFACE
20 from zeroinstall.injector import qdom
21 from zeroinstall import support, zerostore
23 # Element names for bindings in feed files
24 binding_names = frozenset(['environment', 'overlay', 'executable-in-path', 'executable-in-var'])
26 _dependency_names = frozenset(['requires', 'restricts'])
28 network_offline = 'off-line'
29 network_minimal = 'minimal'
30 network_full = 'full'
31 network_levels = (network_offline, network_minimal, network_full)
33 stability_levels = {} # Name -> Stability
35 defaults = {
36 'PATH': '/bin:/usr/bin',
37 'XDG_CONFIG_DIRS': '/etc/xdg',
38 'XDG_DATA_DIRS': '/usr/local/share:/usr/share',
41 class InvalidInterface(SafeException):
42 """Raised when parsing an invalid feed."""
43 feed_url = None
45 def __init__(self, message, ex = None):
46 if ex:
47 try:
48 message += "\n\n(exact error: %s)" % ex
49 except:
50 # Some Python messages have type str but contain UTF-8 sequences.
51 # (e.g. IOException). Adding these to a Unicode 'message' (e.g.
52 # after gettext translation) will cause an error.
53 import codecs
54 decoder = codecs.lookup('utf-8')
55 decex = decoder.decode(str(ex), errors = 'replace')[0]
56 message += "\n\n(exact error: %s)" % decex
58 SafeException.__init__(self, message)
60 def __unicode__(self):
61 if hasattr(SafeException, '__unicode__'):
62 # Python >= 2.6
63 if self.feed_url:
64 return _('%s [%s]') % (SafeException.__unicode__(self), self.feed_url)
65 return SafeException.__unicode__(self)
66 else:
67 return support.unicode(SafeException.__str__(self))
69 def _split_arch(arch):
70 """Split an arch into an (os, machine) tuple. Either or both parts may be None."""
71 if not arch:
72 return None, None
73 elif '-' not in arch:
74 raise SafeException(_("Malformed arch '%s'") % arch)
75 else:
76 osys, machine = arch.split('-', 1)
77 if osys == '*': osys = None
78 if machine == '*': machine = None
79 return osys, machine
81 def _join_arch(osys, machine):
82 if osys == machine == None: return None
83 return "%s-%s" % (osys or '*', machine or '*')
85 def _best_language_match(options):
86 (language, encoding) = locale.getlocale()
88 if language:
89 # xml:lang uses '-', while LANG uses '_'
90 language = language.replace('_', '-')
91 else:
92 language = 'en-US'
94 return (options.get(language, None) or # Exact match (language+region)
95 options.get(language.split('-', 1)[0], None) or # Matching language
96 options.get('en', None)) # English
98 class Stability(object):
99 """A stability rating. Each implementation has an upstream stability rating and,
100 optionally, a user-set rating."""
101 __slots__ = ['level', 'name', 'description']
102 def __init__(self, level, name, description):
103 self.level = level
104 self.name = name
105 self.description = description
106 assert name not in stability_levels
107 stability_levels[name] = self
109 def __cmp__(self, other):
110 return cmp(self.level, other.level)
112 def __lt__(self, other):
113 if isinstance(other, Stability):
114 return self.level < other.level
115 else:
116 return NotImplemented
118 def __eq__(self, other):
119 if isinstance(other, Stability):
120 return self.level == other.level
121 else:
122 return NotImplemented
124 def __str__(self):
125 return self.name
127 def __repr__(self):
128 return _("<Stability: %s>") % self.description
130 def process_binding(e):
131 """Internal"""
132 if e.name == 'environment':
133 mode = {
134 None: EnvironmentBinding.PREPEND,
135 'prepend': EnvironmentBinding.PREPEND,
136 'append': EnvironmentBinding.APPEND,
137 'replace': EnvironmentBinding.REPLACE,
138 }[e.getAttribute('mode')]
140 binding = EnvironmentBinding(e.getAttribute('name'),
141 insert = e.getAttribute('insert'),
142 default = e.getAttribute('default'),
143 value = e.getAttribute('value'),
144 mode = mode,
145 separator = e.getAttribute('separator'))
146 if not binding.name: raise InvalidInterface(_("Missing 'name' in binding"))
147 if binding.insert is None and binding.value is None:
148 raise InvalidInterface(_("Missing 'insert' or 'value' in binding"))
149 if binding.insert is not None and binding.value is not None:
150 raise InvalidInterface(_("Binding contains both 'insert' and 'value'"))
151 return binding
152 elif e.name == 'executable-in-path':
153 return ExecutableBinding(e, in_path = True)
154 elif e.name == 'executable-in-var':
155 return ExecutableBinding(e, in_path = False)
156 elif e.name == 'overlay':
157 return OverlayBinding(e.getAttribute('src'), e.getAttribute('mount-point'))
158 else:
159 raise Exception(_("Unknown binding type '%s'") % e.name)
161 def process_depends(item, local_feed_dir):
162 """Internal"""
163 # Note: also called from selections
164 attrs = item.attrs
165 dep_iface = item.getAttribute('interface')
166 if not dep_iface:
167 raise InvalidInterface(_("Missing 'interface' on <%s>") % item.name)
168 if dep_iface.startswith('.'):
169 if local_feed_dir:
170 dep_iface = os.path.abspath(os.path.join(local_feed_dir, dep_iface))
171 # (updates the element too, in case we write it out again)
172 attrs['interface'] = dep_iface
173 else:
174 raise InvalidInterface(_('Relative interface URI "%s" in non-local feed') % dep_iface)
176 if item.name == 'restricts':
177 dependency = InterfaceRestriction(dep_iface, element = item)
178 else:
179 dependency = InterfaceDependency(dep_iface, element = item)
181 for e in item.childNodes:
182 if e.uri != XMLNS_IFACE: continue
183 if e.name in binding_names:
184 dependency.bindings.append(process_binding(e))
185 elif e.name == 'version':
186 dependency.restrictions.append(
187 VersionRangeRestriction(not_before = parse_version(e.getAttribute('not-before')),
188 before = parse_version(e.getAttribute('before'))))
189 return dependency
191 def N_(message): return message
193 insecure = Stability(0, N_('insecure'), _('This is a security risk'))
194 buggy = Stability(5, N_('buggy'), _('Known to have serious bugs'))
195 developer = Stability(10, N_('developer'), _('Work-in-progress - bugs likely'))
196 testing = Stability(20, N_('testing'), _('Stability unknown - please test!'))
197 stable = Stability(30, N_('stable'), _('Tested - no serious problems found'))
198 packaged = Stability(35, N_('packaged'), _('Supplied by the local package manager'))
199 preferred = Stability(40, N_('preferred'), _('Best of all - must be set manually'))
201 del N_
203 class Restriction(object):
204 """A Restriction limits the allowed implementations of an Interface."""
205 __slots__ = []
207 def meets_restriction(self, impl):
208 """Called by the L{solver.Solver} to check whether a particular implementation is acceptable.
209 @return: False if this implementation is not a possibility
210 @rtype: bool
212 raise NotImplementedError(_("Abstract"))
214 class VersionRestriction(Restriction):
215 """Only select implementations with a particular version number.
216 @since: 0.40"""
218 def __init__(self, version):
219 """@param version: the required version number
220 @see: L{parse_version}; use this to pre-process the version number
222 self.version = version
224 def meets_restriction(self, impl):
225 return impl.version == self.version
227 def __str__(self):
228 return _("(restriction: version = %s)") % format_version(self.version)
230 class VersionRangeRestriction(Restriction):
231 """Only versions within the given range are acceptable"""
232 __slots__ = ['before', 'not_before']
234 def __init__(self, before, not_before):
235 """@param before: chosen versions must be earlier than this
236 @param not_before: versions must be at least this high
237 @see: L{parse_version}; use this to pre-process the versions
239 self.before = before
240 self.not_before = not_before
242 def meets_restriction(self, impl):
243 if self.not_before and impl.version < self.not_before:
244 return False
245 if self.before and impl.version >= self.before:
246 return False
247 return True
249 def __str__(self):
250 if self.not_before is not None or self.before is not None:
251 range = ''
252 if self.not_before is not None:
253 range += format_version(self.not_before) + ' <= '
254 range += 'version'
255 if self.before is not None:
256 range += ' < ' + format_version(self.before)
257 else:
258 range = 'none'
259 return _("(restriction: %s)") % range
261 class Binding(object):
262 """Information about how the choice of a Dependency is made known
263 to the application being run."""
265 @property
266 def command(self):
267 """"Returns the name of the specific command needed by this binding, if any.
268 @since: 1.2"""
269 return None
271 class EnvironmentBinding(Binding):
272 """Indicate the chosen implementation using an environment variable."""
273 __slots__ = ['name', 'insert', 'default', 'mode', 'value']
275 PREPEND = 'prepend'
276 APPEND = 'append'
277 REPLACE = 'replace'
279 def __init__(self, name, insert, default = None, mode = PREPEND, value=None, separator=None):
281 mode argument added in version 0.28
282 value argument added in version 0.52
284 self.name = name
285 self.insert = insert
286 self.default = default
287 self.mode = mode
288 self.value = value
289 if separator is None:
290 self.separator = os.pathsep
291 else:
292 self.separator = separator
295 def __str__(self):
296 return _("<environ %(name)s %(mode)s %(insert)s %(value)s>") % \
297 {'name': self.name, 'mode': self.mode, 'insert': self.insert, 'value': self.value}
299 __repr__ = __str__
301 def get_value(self, path, old_value):
302 """Calculate the new value of the environment variable after applying this binding.
303 @param path: the path to the selected implementation
304 @param old_value: the current value of the environment variable
305 @return: the new value for the environment variable"""
307 if self.insert is not None:
308 extra = os.path.join(path, self.insert)
309 else:
310 assert self.value is not None
311 extra = self.value
313 if self.mode == EnvironmentBinding.REPLACE:
314 return extra
316 if old_value is None:
317 old_value = self.default or defaults.get(self.name, None)
318 if old_value is None:
319 return extra
320 if self.mode == EnvironmentBinding.PREPEND:
321 return extra + self.separator + old_value
322 else:
323 return old_value + self.separator + extra
325 def _toxml(self, doc, prefixes):
326 """Create a DOM element for this binding.
327 @param doc: document to use to create the element
328 @return: the new element
330 env_elem = doc.createElementNS(XMLNS_IFACE, 'environment')
331 env_elem.setAttributeNS(None, 'name', self.name)
332 if self.mode is not None:
333 env_elem.setAttributeNS(None, 'mode', self.mode)
334 if self.insert is not None:
335 env_elem.setAttributeNS(None, 'insert', self.insert)
336 else:
337 env_elem.setAttributeNS(None, 'value', self.value)
338 if self.default:
339 env_elem.setAttributeNS(None, 'default', self.default)
340 if self.separator:
341 env_elem.setAttributeNS(None, 'separator', self.separator)
342 return env_elem
344 class ExecutableBinding(Binding):
345 """Make the chosen command available in $PATH.
346 @ivar in_path: True to add the named command to $PATH, False to store in named variable
347 @type in_path: bool
349 __slots__ = ['qdom']
351 def __init__(self, qdom, in_path):
352 self.qdom = qdom
353 self.in_path = in_path
355 def __str__(self):
356 return str(self.qdom)
358 __repr__ = __str__
360 def _toxml(self, doc, prefixes):
361 return self.qdom.toDOM(doc, prefixes)
363 @property
364 def name(self):
365 return self.qdom.getAttribute('name')
367 @property
368 def command(self):
369 return self.qdom.getAttribute("command") or 'run'
371 class OverlayBinding(Binding):
372 """Make the chosen implementation available by overlaying it onto another part of the file-system.
373 This is to support legacy programs which use hard-coded paths."""
374 __slots__ = ['src', 'mount_point']
376 def __init__(self, src, mount_point):
377 self.src = src
378 self.mount_point = mount_point
380 def __str__(self):
381 return _("<overlay %(src)s on %(mount_point)s>") % {'src': self.src or '.', 'mount_point': self.mount_point or '/'}
383 __repr__ = __str__
385 def _toxml(self, doc, prefixes):
386 """Create a DOM element for this binding.
387 @param doc: document to use to create the element
388 @return: the new element
390 env_elem = doc.createElementNS(XMLNS_IFACE, 'overlay')
391 if self.src is not None:
392 env_elem.setAttributeNS(None, 'src', self.src)
393 if self.mount_point is not None:
394 env_elem.setAttributeNS(None, 'mount-point', self.mount_point)
395 return env_elem
397 class Feed(object):
398 """An interface's feeds are other interfaces whose implementations can also be
399 used as implementations of this interface."""
400 __slots__ = ['uri', 'os', 'machine', 'user_override', 'langs', 'site_package']
401 def __init__(self, uri, arch, user_override, langs = None, site_package = False):
402 self.uri = uri
403 # This indicates whether the feed comes from the user's overrides
404 # file. If true, writer.py will write it when saving.
405 self.user_override = user_override
406 self.os, self.machine = _split_arch(arch)
407 self.langs = langs
408 self.site_package = site_package
410 def __str__(self):
411 return "<Feed from %s>" % self.uri
412 __repr__ = __str__
414 arch = property(lambda self: _join_arch(self.os, self.machine))
416 class Dependency(object):
417 """A Dependency indicates that an Implementation requires some additional
418 code to function. This is an abstract base class.
419 @ivar qdom: the XML element for this Dependency (since 0launch 0.51)
420 @type qdom: L{qdom.Element}
421 @ivar metadata: any extra attributes from the XML element
422 @type metadata: {str: str}
424 __slots__ = ['qdom']
426 Essential = "essential" # Must select a version of the dependency
427 Recommended = "recommended" # Prefer to select a version
428 Restricts = "restricts" # Just adds restrictions without expressing any opinion
430 def __init__(self, element):
431 assert isinstance(element, qdom.Element), type(element) # Use InterfaceDependency instead!
432 self.qdom = element
434 @property
435 def metadata(self):
436 return self.qdom.attrs
438 def get_required_commands(self):
439 """Return a list of command names needed by this dependency"""
440 return []
442 class InterfaceRestriction(Dependency):
443 """A Dependency that restricts the possible choices of a Zero Install interface.
444 @ivar interface: the interface required by this dependency
445 @type interface: str
446 @ivar restrictions: a list of constraints on acceptable implementations
447 @type restrictions: [L{Restriction}]
448 @since: 1.10
450 __slots__ = ['interface', 'restrictions']
452 def __init__(self, interface, restrictions = None, element = None):
453 Dependency.__init__(self, element)
454 assert isinstance(interface, (str, support.unicode))
455 assert interface
456 self.interface = interface
457 if restrictions is None:
458 self.restrictions = []
459 else:
460 self.restrictions = restrictions
462 importance = Dependency.Restricts
463 bindings = ()
465 def __str__(self):
466 return _("<Restriction on %(interface)s; %(restrictions)s>") % {'interface': self.interface, 'restrictions': self.restrictions}
468 class InterfaceDependency(InterfaceRestriction):
469 """A Dependency on a Zero Install interface.
470 @ivar interface: the interface required by this dependency
471 @type interface: str
472 @ivar restrictions: a list of constraints on acceptable implementations
473 @type restrictions: [L{Restriction}]
474 @ivar bindings: how to make the choice of implementation known
475 @type bindings: [L{Binding}]
476 @since: 0.28
478 __slots__ = ['bindings']
480 def __init__(self, interface, restrictions = None, element = None):
481 InterfaceRestriction.__init__(self, interface, restrictions, element)
482 self.bindings = []
484 def __str__(self):
485 return _("<Dependency on %(interface)s; bindings: %(bindings)s%(restrictions)s>") % {'interface': self.interface, 'bindings': self.bindings, 'restrictions': self.restrictions}
487 @property
488 def importance(self):
489 return self.qdom.getAttribute("importance") or Dependency.Essential
491 def get_required_commands(self):
492 """Return a list of command names needed by this dependency"""
493 if self.qdom.name == 'runner':
494 commands = [self.qdom.getAttribute('command') or 'run']
495 else:
496 commands = []
497 for b in self.bindings:
498 c = b.command
499 if c is not None:
500 commands.append(c)
501 return commands
503 @property
504 def command(self):
505 if self.qdom.name == 'runner':
506 return self.qdom.getAttribute('command') or 'run'
507 return None
509 class RetrievalMethod(object):
510 """A RetrievalMethod provides a way to fetch an implementation."""
511 __slots__ = []
513 class DownloadSource(RetrievalMethod):
514 """A DownloadSource provides a way to fetch an implementation."""
515 __slots__ = ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
517 def __init__(self, implementation, url, size, extract, start_offset = 0, type = None):
518 self.implementation = implementation
519 self.url = url
520 self.size = size
521 self.extract = extract
522 self.start_offset = start_offset
523 self.type = type # MIME type - see unpack.py
525 class RenameStep(RetrievalMethod):
526 """A Rename provides a way to rename / move a file within an implementation."""
527 __slots__ = ['source', 'dest']
529 def __init__(self, source, dest):
530 self.source = source
531 self.dest = dest
533 class Recipe(RetrievalMethod):
534 """Get an implementation by following a series of steps.
535 @ivar size: the combined download sizes from all the steps
536 @type size: int
537 @ivar steps: the sequence of steps which must be performed
538 @type steps: [L{RetrievalMethod}]"""
539 __slots__ = ['steps']
541 def __init__(self):
542 self.steps = []
544 size = property(lambda self: sum([x.size for x in self.steps if isinstance(x, DownloadSource)]))
546 class DistributionSource(RetrievalMethod):
547 """A package that is installed using the distribution's tools (including PackageKit).
548 @ivar install: a function to call to install this package
549 @type install: (L{handler.Handler}) -> L{tasks.Blocker}
550 @ivar package_id: the package name, in a form recognised by the distribution's tools
551 @type package_id: str
552 @ivar size: the download size in bytes
553 @type size: int
554 @ivar needs_confirmation: whether the user should be asked to confirm before calling install()
555 @type needs_confirmation: bool"""
557 __slots__ = ['package_id', 'size', 'install', 'needs_confirmation']
559 def __init__(self, package_id, size, install, needs_confirmation = True):
560 RetrievalMethod.__init__(self)
561 self.package_id = package_id
562 self.size = size
563 self.install = install
564 self.needs_confirmation = needs_confirmation
566 class Command(object):
567 """A Command is a way of running an Implementation as a program."""
569 __slots__ = ['qdom', '_depends', '_local_dir', '_runner', '_bindings']
571 def __init__(self, qdom, local_dir):
572 """@param qdom: the <command> element
573 @param local_dir: the directory containing the feed (for relative dependencies), or None if not local
575 assert qdom.name == 'command', 'not <command>: %s' % qdom
576 self.qdom = qdom
577 self._local_dir = local_dir
578 self._depends = None
579 self._bindings = None
581 path = property(lambda self: self.qdom.attrs.get("path", None))
583 def _toxml(self, doc, prefixes):
584 return self.qdom.toDOM(doc, prefixes)
586 @property
587 def requires(self):
588 if self._depends is None:
589 self._runner = None
590 depends = []
591 for child in self.qdom.childNodes:
592 if child.name in _dependency_names:
593 dep = process_depends(child, self._local_dir)
594 depends.append(dep)
595 elif child.name == 'runner':
596 if self._runner:
597 raise InvalidInterface(_("Multiple <runner>s in <command>!"))
598 dep = process_depends(child, self._local_dir)
599 depends.append(dep)
600 self._runner = dep
601 self._depends = depends
602 return self._depends
604 def get_runner(self):
605 self.requires # (sets _runner)
606 return self._runner
608 def __str__(self):
609 return str(self.qdom)
611 @property
612 def bindings(self):
613 """@since: 1.3"""
614 if self._bindings is None:
615 bindings = []
616 for e in self.qdom.childNodes:
617 if e.uri != XMLNS_IFACE: continue
618 if e.name in binding_names:
619 bindings.append(process_binding(e))
620 self._bindings = bindings
621 return self._bindings
623 class Implementation(object):
624 """An Implementation is a package which implements an Interface.
625 @ivar download_sources: list of methods of getting this implementation
626 @type download_sources: [L{RetrievalMethod}]
627 @ivar feed: the feed owning this implementation (since 0.32)
628 @type feed: [L{ZeroInstallFeed}]
629 @ivar bindings: how to tell this component where it itself is located (since 0.31)
630 @type bindings: [Binding]
631 @ivar upstream_stability: the stability reported by the packager
632 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged]
633 @ivar user_stability: the stability as set by the user
634 @type upstream_stability: [insecure | buggy | developer | testing | stable | packaged | preferred]
635 @ivar langs: natural languages supported by this package
636 @type langs: str
637 @ivar requires: interfaces this package depends on
638 @type requires: [L{Dependency}]
639 @ivar commands: ways to execute as a program
640 @type commands: {str: Command}
641 @ivar metadata: extra metadata from the feed
642 @type metadata: {"[URI ]localName": str}
643 @ivar id: a unique identifier for this Implementation
644 @ivar version: a parsed version number
645 @ivar released: release date
646 @ivar local_path: the directory containing this local implementation, or None if it isn't local (id isn't a path)
647 @type local_path: str | None
648 @ivar requires_root_install: whether the user will need admin rights to use this
649 @type requires_root_install: bool
652 # Note: user_stability shouldn't really be here
654 __slots__ = ['upstream_stability', 'user_stability', 'langs',
655 'requires', 'metadata', 'download_sources', 'commands',
656 'id', 'feed', 'version', 'released', 'bindings', 'machine']
658 def __init__(self, feed, id):
659 assert id
660 self.feed = feed
661 self.id = id
662 self.user_stability = None
663 self.upstream_stability = None
664 self.metadata = {} # [URI + " "] + localName -> value
665 self.requires = []
666 self.version = None
667 self.released = None
668 self.download_sources = []
669 self.langs = ""
670 self.machine = None
671 self.bindings = []
672 self.commands = {}
674 def get_stability(self):
675 return self.user_stability or self.upstream_stability or testing
677 def __str__(self):
678 return self.id
680 def __repr__(self):
681 return "v%s (%s)" % (self.get_version(), self.id)
683 def __cmp__(self, other):
684 """Newer versions come first"""
685 d = cmp(other.version, self.version)
686 if d: return d
687 # If the version number is the same, just give a stable sort order, and
688 # ensure that two different implementations don't compare equal.
689 d = cmp(other.feed.url, self.feed.url)
690 if d: return d
691 return cmp(other.id, self.id)
693 def __hash__(self):
694 return self.id.__hash__()
696 def __eq__(self, other):
697 return self is other
699 def __le__(self, other):
700 if isinstance(other, Implementation):
701 if other.version < self.version: return True
702 elif other.version > self.version: return False
704 if other.feed.url < self.feed.url: return True
705 elif other.feed.url > self.feed.url: return False
707 return other.id <= self.id
708 else:
709 return NotImplemented
711 def get_version(self):
712 """Return the version as a string.
713 @see: L{format_version}
715 return format_version(self.version)
717 arch = property(lambda self: _join_arch(self.os, self.machine))
719 os = None
720 local_path = None
721 digests = None
722 requires_root_install = False
724 def _get_main(self):
725 """"@deprecated: use commands["run"] instead"""
726 main = self.commands.get("run", None)
727 if main is not None:
728 return main.path
729 return None
730 def _set_main(self, path):
731 """"@deprecated: use commands["run"] instead"""
732 if path is None:
733 if "run" in self.commands:
734 del self.commands["run"]
735 else:
736 self.commands["run"] = Command(qdom.Element(XMLNS_IFACE, 'command', {'path': path, 'name': 'run'}), None)
737 main = property(_get_main, _set_main)
739 def is_available(self, stores):
740 """Is this Implementation available locally?
741 (a local implementation, an installed distribution package, or a cached ZeroInstallImplementation)
742 @rtype: bool
743 @since: 0.53
745 raise NotImplementedError("abstract")
747 class DistributionImplementation(Implementation):
748 """An implementation provided by the distribution. Information such as the version
749 comes from the package manager.
750 @ivar package_implementation: the <package-implementation> element that generated this impl (since 1.7)
751 @type package_implementation: L{qdom.Element}
752 @since: 0.28"""
753 __slots__ = ['distro', 'installed', 'package_implementation']
755 def __init__(self, feed, id, distro, package_implementation = None):
756 assert id.startswith('package:')
757 Implementation.__init__(self, feed, id)
758 self.distro = distro
759 self.installed = False
760 self.package_implementation = package_implementation
762 if package_implementation:
763 for child in package_implementation.childNodes:
764 if child.uri != XMLNS_IFACE: continue
765 if child.name == 'command':
766 command_name = child.attrs.get('name', None)
767 if not command_name:
768 raise InvalidInterface('Missing name for <command>')
769 self.commands[command_name] = Command(child, local_dir = None)
771 @property
772 def requires_root_install(self):
773 return not self.installed
775 def is_available(self, stores):
776 return self.installed
778 class ZeroInstallImplementation(Implementation):
779 """An implementation where all the information comes from Zero Install.
780 @ivar digests: a list of "algorith=value" or "algorith_value" strings (since 0.45)
781 @type digests: [str]
782 @since: 0.28"""
783 __slots__ = ['os', 'size', 'digests', 'local_path']
785 def __init__(self, feed, id, local_path):
786 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
787 assert not id.startswith('package:'), id
788 Implementation.__init__(self, feed, id)
789 self.size = None
790 self.os = None
791 self.digests = []
792 self.local_path = local_path
794 # Deprecated
795 dependencies = property(lambda self: dict([(x.interface, x) for x in self.requires
796 if isinstance(x, InterfaceRestriction)]))
798 def add_download_source(self, url, size, extract, start_offset = 0, type = None):
799 """Add a download source."""
800 self.download_sources.append(DownloadSource(self, url, size, extract, start_offset, type))
802 def set_arch(self, arch):
803 self.os, self.machine = _split_arch(arch)
804 arch = property(lambda self: _join_arch(self.os, self.machine), set_arch)
806 def is_available(self, stores):
807 if self.local_path is not None:
808 return os.path.exists(self.local_path)
809 if self.digests:
810 path = stores.lookup_maybe(self.digests)
811 return path is not None
812 return False # (0compile creates fake entries with no digests)
814 class Interface(object):
815 """An Interface represents some contract of behaviour.
816 @ivar uri: the URI for this interface.
817 @ivar stability_policy: user's configured policy.
818 Implementations at this level or higher are preferred.
819 Lower levels are used only if there is no other choice.
821 __slots__ = ['uri', 'stability_policy', 'extra_feeds']
823 implementations = property(lambda self: self._main_feed.implementations)
824 name = property(lambda self: self._main_feed.name)
825 description = property(lambda self: self._main_feed.description)
826 summary = property(lambda self: self._main_feed.summary)
827 last_modified = property(lambda self: self._main_feed.last_modified)
828 feeds = property(lambda self: self.extra_feeds + self._main_feed.feeds)
829 metadata = property(lambda self: self._main_feed.metadata)
831 last_checked = property(lambda self: self._main_feed.last_checked)
833 def __init__(self, uri):
834 assert uri
835 if uri.startswith('http:') or uri.startswith('https:') or os.path.isabs(uri):
836 self.uri = uri
837 else:
838 raise SafeException(_("Interface name '%s' doesn't start "
839 "with 'http:' or 'https:'") % uri)
840 self.reset()
842 def _get_feed_for(self):
843 retval = {}
844 for key in self._main_feed.feed_for:
845 retval[key] = True
846 return retval
847 feed_for = property(_get_feed_for) # Deprecated (used by 0publish)
849 def reset(self):
850 self.extra_feeds = []
851 self.stability_policy = None
853 def get_name(self):
854 from zeroinstall.injector.iface_cache import iface_cache
855 feed = iface_cache.get_feed(self.uri)
856 if feed:
857 return feed.get_name()
858 return '(' + os.path.basename(self.uri) + ')'
860 def __repr__(self):
861 return _("<Interface %s>") % self.uri
863 def set_stability_policy(self, new):
864 assert new is None or isinstance(new, Stability)
865 self.stability_policy = new
867 def get_feed(self, url):
868 #import warnings
869 #warnings.warn("use iface_cache.get_feed instead", DeprecationWarning, 2)
870 for x in self.extra_feeds:
871 if x.uri == url:
872 return x
873 #return self._main_feed.get_feed(url)
874 return None
876 def get_metadata(self, uri, name):
877 return self._main_feed.get_metadata(uri, name)
879 @property
880 def _main_feed(self):
881 import warnings
882 warnings.warn("use the feed instead", DeprecationWarning, 3)
883 from zeroinstall.injector import policy
884 iface_cache = policy.get_deprecated_singleton_config().iface_cache
885 feed = iface_cache.get_feed(self.uri)
886 if feed is None:
887 return _dummy_feed
888 return feed
890 def _merge_attrs(attrs, item):
891 """Add each attribute of item to a copy of attrs and return the copy.
892 @type attrs: {str: str}
893 @type item: L{qdom.Element}
894 @rtype: {str: str}
896 new = attrs.copy()
897 for a in item.attrs:
898 new[str(a)] = item.attrs[a]
899 return new
901 def _get_long(elem, attr_name):
902 val = elem.getAttribute(attr_name)
903 if val is not None:
904 try:
905 val = int(val)
906 except ValueError:
907 raise SafeException(_("Invalid value for integer attribute '%(attribute_name)s': %(value)s") % {'attribute_name': attr_name, 'value': val})
908 return val
910 class ZeroInstallFeed(object):
911 """A feed lists available implementations of an interface.
912 @ivar url: the URL for this feed
913 @ivar implementations: Implementations in this feed, indexed by ID
914 @type implementations: {str: L{Implementation}}
915 @ivar name: human-friendly name
916 @ivar summaries: short textual description (in various languages, since 0.49)
917 @type summaries: {str: str}
918 @ivar descriptions: long textual description (in various languages, since 0.49)
919 @type descriptions: {str: str}
920 @ivar last_modified: timestamp on signature
921 @ivar last_checked: time feed was last successfully downloaded and updated
922 @ivar local_path: the path of this local feed, or None if remote (since 1.7)
923 @type local_path: str | None
924 @ivar feeds: list of <feed> elements in this feed
925 @type feeds: [L{Feed}]
926 @ivar feed_for: interfaces for which this could be a feed
927 @type feed_for: set(str)
928 @ivar metadata: extra elements we didn't understand
930 # _main is deprecated
931 __slots__ = ['url', 'implementations', 'name', 'descriptions', 'first_description', 'summaries', 'first_summary', '_package_implementations',
932 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata', 'local_path']
934 def __init__(self, feed_element, local_path = None, distro = None):
935 """Create a feed object from a DOM.
936 @param feed_element: the root element of a feed file
937 @type feed_element: L{qdom.Element}
938 @param local_path: the pathname of this local feed, or None for remote feeds"""
939 self.local_path = local_path
940 self.implementations = {}
941 self.name = None
942 self.summaries = {} # { lang: str }
943 self.first_summary = None
944 self.descriptions = {} # { lang: str }
945 self.first_description = None
946 self.last_modified = None
947 self.feeds = []
948 self.feed_for = set()
949 self.metadata = []
950 self.last_checked = None
951 self._package_implementations = []
953 if distro is not None:
954 import warnings
955 warnings.warn("distro argument is now ignored", DeprecationWarning, 2)
957 if feed_element is None:
958 return # XXX subclass?
960 assert feed_element.name in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
961 assert feed_element.uri == XMLNS_IFACE, "Wrong namespace on root element: %s" % feed_element.uri
963 main = feed_element.getAttribute('main')
964 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
966 if local_path:
967 self.url = local_path
968 local_dir = os.path.dirname(local_path)
969 else:
970 assert local_path is None
971 self.url = feed_element.getAttribute('uri')
972 if not self.url:
973 raise InvalidInterface(_("<interface> uri attribute missing"))
974 local_dir = None # Can't have relative paths
976 min_injector_version = feed_element.getAttribute('min-injector-version')
977 if min_injector_version:
978 if parse_version(min_injector_version) > parse_version(version):
979 raise InvalidInterface(_("This feed requires version %(min_version)s or later of "
980 "Zero Install, but I am only version %(version)s. "
981 "You can get a newer version from http://0install.net") %
982 {'min_version': min_injector_version, 'version': version})
984 for x in feed_element.childNodes:
985 if x.uri != XMLNS_IFACE:
986 self.metadata.append(x)
987 continue
988 if x.name == 'name':
989 self.name = x.content
990 elif x.name == 'description':
991 if self.first_description == None:
992 self.first_description = x.content
993 self.descriptions[x.attrs.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x.content
994 elif x.name == 'summary':
995 if self.first_summary == None:
996 self.first_summary = x.content
997 self.summaries[x.attrs.get("http://www.w3.org/XML/1998/namespace lang", 'en')] = x.content
998 elif x.name == 'feed-for':
999 feed_iface = x.getAttribute('interface')
1000 if not feed_iface:
1001 raise InvalidInterface(_('Missing "interface" attribute in <feed-for>'))
1002 self.feed_for.add(feed_iface)
1003 # Bug report from a Debian/stable user that --feed gets the wrong value.
1004 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
1005 # in case it happens again.
1006 logger.debug(_("Is feed-for %s"), feed_iface)
1007 elif x.name == 'feed':
1008 feed_src = x.getAttribute('src')
1009 if not feed_src:
1010 raise InvalidInterface(_('Missing "src" attribute in <feed>'))
1011 if feed_src.startswith('http:') or feed_src.startswith('https:') or local_path:
1012 if feed_src.startswith('.'):
1013 feed_src = os.path.abspath(os.path.join(local_dir, feed_src))
1015 langs = x.getAttribute('langs')
1016 if langs: langs = langs.replace('_', '-')
1017 self.feeds.append(Feed(feed_src, x.getAttribute('arch'), False, langs = langs))
1018 else:
1019 raise InvalidInterface(_("Invalid feed URL '%s'") % feed_src)
1020 else:
1021 self.metadata.append(x)
1023 if not self.name:
1024 raise InvalidInterface(_("Missing <name> in feed"))
1025 if not self.summary:
1026 raise InvalidInterface(_("Missing <summary> in feed"))
1028 def process_group(group, group_attrs, base_depends, base_bindings, base_commands):
1029 for item in group.childNodes:
1030 if item.uri != XMLNS_IFACE: continue
1032 if item.name not in ('group', 'implementation', 'package-implementation'):
1033 continue
1035 # We've found a group or implementation. Scan for dependencies,
1036 # bindings and commands. Doing this here means that:
1037 # - We can share the code for groups and implementations here.
1038 # - The order doesn't matter, because these get processed first.
1039 # A side-effect is that the document root cannot contain
1040 # these.
1042 depends = base_depends[:]
1043 bindings = base_bindings[:]
1044 commands = base_commands.copy()
1046 for attr, command in [('main', 'run'),
1047 ('self-test', 'test')]:
1048 value = item.attrs.get(attr, None)
1049 if value is not None:
1050 commands[command] = Command(qdom.Element(XMLNS_IFACE, 'command', {'name': command, 'path': value}), None)
1052 for child in item.childNodes:
1053 if child.uri != XMLNS_IFACE: continue
1054 if child.name in _dependency_names:
1055 dep = process_depends(child, local_dir)
1056 depends.append(dep)
1057 elif child.name == 'command':
1058 command_name = child.attrs.get('name', None)
1059 if not command_name:
1060 raise InvalidInterface('Missing name for <command>')
1061 commands[command_name] = Command(child, local_dir)
1062 elif child.name in binding_names:
1063 bindings.append(process_binding(child))
1065 compile_command = item.attrs.get('http://zero-install.sourceforge.net/2006/namespaces/0compile command')
1066 if compile_command is not None:
1067 commands['compile'] = Command(qdom.Element(XMLNS_IFACE, 'command', {'name': 'compile', 'shell-command': compile_command}), None)
1069 item_attrs = _merge_attrs(group_attrs, item)
1071 if item.name == 'group':
1072 process_group(item, item_attrs, depends, bindings, commands)
1073 elif item.name == 'implementation':
1074 process_impl(item, item_attrs, depends, bindings, commands)
1075 elif item.name == 'package-implementation':
1076 if depends:
1077 logger.warn("A <package-implementation> with dependencies in %s!", self.url)
1078 self._package_implementations.append((item, item_attrs))
1079 else:
1080 assert 0
1082 def process_impl(item, item_attrs, depends, bindings, commands):
1083 id = item.getAttribute('id')
1084 if id is None:
1085 raise InvalidInterface(_("Missing 'id' attribute on %s") % item)
1086 local_path = item_attrs.get('local-path')
1087 if local_dir and local_path:
1088 abs_local_path = os.path.abspath(os.path.join(local_dir, local_path))
1089 impl = ZeroInstallImplementation(self, id, abs_local_path)
1090 elif local_dir and (id.startswith('/') or id.startswith('.')):
1091 # For old feeds
1092 id = os.path.abspath(os.path.join(local_dir, id))
1093 impl = ZeroInstallImplementation(self, id, id)
1094 else:
1095 impl = ZeroInstallImplementation(self, id, None)
1096 if '=' in id:
1097 # In older feeds, the ID was the (single) digest
1098 impl.digests.append(id)
1099 if id in self.implementations:
1100 logger.warn(_("Duplicate ID '%(id)s' in feed '%(feed)s'"), {'id': id, 'feed': self})
1101 self.implementations[id] = impl
1103 impl.metadata = item_attrs
1104 try:
1105 version_mod = item_attrs.get('version-modifier', None)
1106 if version_mod:
1107 item_attrs['version'] += version_mod
1108 del item_attrs['version-modifier']
1109 version = item_attrs['version']
1110 except KeyError:
1111 raise InvalidInterface(_("Missing version attribute"))
1112 impl.version = parse_version(version)
1114 impl.commands = commands
1116 impl.released = item_attrs.get('released', None)
1117 impl.langs = item_attrs.get('langs', '').replace('_', '-')
1119 size = item.getAttribute('size')
1120 if size:
1121 impl.size = int(size)
1122 impl.arch = item_attrs.get('arch', None)
1123 try:
1124 stability = stability_levels[str(item_attrs['stability'])]
1125 except KeyError:
1126 stab = str(item_attrs['stability'])
1127 if stab != stab.lower():
1128 raise InvalidInterface(_('Stability "%s" invalid - use lower case!') % item_attrs.stability)
1129 raise InvalidInterface(_('Stability "%s" invalid') % item_attrs['stability'])
1130 if stability >= preferred:
1131 raise InvalidInterface(_("Upstream can't set stability to preferred!"))
1132 impl.upstream_stability = stability
1134 impl.bindings = bindings
1135 impl.requires = depends
1137 for elem in item.childNodes:
1138 if elem.uri != XMLNS_IFACE: continue
1139 if elem.name == 'archive':
1140 url = elem.getAttribute('href')
1141 if not url:
1142 raise InvalidInterface(_("Missing href attribute on <archive>"))
1143 size = elem.getAttribute('size')
1144 if not size:
1145 raise InvalidInterface(_("Missing size attribute on <archive>"))
1146 impl.add_download_source(url = url, size = int(size),
1147 extract = elem.getAttribute('extract'),
1148 start_offset = _get_long(elem, 'start-offset'),
1149 type = elem.getAttribute('type'))
1150 elif elem.name == 'manifest-digest':
1151 for aname, avalue in elem.attrs.items():
1152 if ' ' not in aname:
1153 impl.digests.append(zerostore.format_algorithm_digest_pair(aname, avalue))
1154 elif elem.name == 'recipe':
1155 recipe = Recipe()
1156 for recipe_step in elem.childNodes:
1157 if recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'archive':
1158 url = recipe_step.getAttribute('href')
1159 if not url:
1160 raise InvalidInterface(_("Missing href attribute on <archive>"))
1161 size = recipe_step.getAttribute('size')
1162 if not size:
1163 raise InvalidInterface(_("Missing size attribute on <archive>"))
1164 recipe.steps.append(DownloadSource(None, url = url, size = int(size),
1165 extract = recipe_step.getAttribute('extract'),
1166 start_offset = _get_long(recipe_step, 'start-offset'),
1167 type = recipe_step.getAttribute('type')))
1168 elif recipe_step.uri == XMLNS_IFACE and recipe_step.name == 'rename':
1169 source = recipe_step.getAttribute('source')
1170 if not source:
1171 raise InvalidInterface(_("Missing source attribute on <rename>"))
1172 dest = recipe_step.getAttribute('dest')
1173 if not dest:
1174 raise InvalidInterface(_("Missing dest attribute on <rename>"))
1175 recipe.steps.append(RenameStep(source=source, dest=dest))
1176 else:
1177 logger.info(_("Unknown step '%s' in recipe; skipping recipe"), recipe_step.name)
1178 break
1179 else:
1180 impl.download_sources.append(recipe)
1182 root_attrs = {'stability': 'testing'}
1183 root_commands = {}
1184 if main:
1185 logger.info("Note: @main on document element is deprecated in %s", self)
1186 root_commands['run'] = Command(qdom.Element(XMLNS_IFACE, 'command', {'path': main, 'name': 'run'}), None)
1187 process_group(feed_element, root_attrs, [], [], root_commands)
1189 def get_distro_feed(self):
1190 """Does this feed contain any <pacakge-implementation> elements?
1191 i.e. is it worth asking the package manager for more information?
1192 @return: the URL of the virtual feed, or None
1193 @since: 0.49"""
1194 if self._package_implementations:
1195 return "distribution:" + self.url
1196 return None
1198 def get_package_impls(self, distro):
1199 """Find the best <pacakge-implementation> element(s) for the given distribution.
1200 @param distro: the distribution to use to rate them
1201 @type distro: L{distro.Distribution}
1202 @return: a list of tuples for the best ranked elements
1203 @rtype: [str]
1204 @since: 0.49"""
1205 best_score = 0
1206 best_impls = []
1208 for item, item_attrs in self._package_implementations:
1209 distro_names = item_attrs.get('distributions', '')
1210 score_this_item = max(
1211 distro.get_score(distro_name) if distro_name else 0.5
1212 for distro_name in distro_names.split(' '))
1213 if score_this_item > best_score:
1214 best_score = score_this_item
1215 best_impls = []
1216 if score_this_item == best_score:
1217 best_impls.append((item, item_attrs))
1218 return best_impls
1220 def get_name(self):
1221 return self.name or '(' + os.path.basename(self.url) + ')'
1223 def __repr__(self):
1224 return _("<Feed %s>") % self.url
1226 def set_stability_policy(self, new):
1227 assert new is None or isinstance(new, Stability)
1228 self.stability_policy = new
1230 def get_feed(self, url):
1231 for x in self.feeds:
1232 if x.uri == url:
1233 return x
1234 return None
1236 def add_metadata(self, elem):
1237 self.metadata.append(elem)
1239 def get_metadata(self, uri, name):
1240 """Return a list of interface metadata elements with this name and namespace URI."""
1241 return [m for m in self.metadata if m.name == name and m.uri == uri]
1243 @property
1244 def summary(self):
1245 return _best_language_match(self.summaries) or self.first_summary
1247 @property
1248 def description(self):
1249 return _best_language_match(self.descriptions) or self.first_description
1251 def get_replaced_by(self):
1252 """Return the URI of the interface that replaced the one with the URI of this feed's URL.
1253 This is the value of the feed's <replaced-by interface'...'/> element.
1254 @return: the new URI, or None if it hasn't been replaced
1255 @since: 1.7"""
1256 for child in self.metadata:
1257 if child.uri == XMLNS_IFACE and child.name == 'replaced-by':
1258 new_uri = child.getAttribute('interface')
1259 if new_uri and (new_uri.startswith('http:') or new_uri.startswith('https:') or self.local_path):
1260 return new_uri
1261 return None
1263 class DummyFeed(object):
1264 """Temporary class used during API transition."""
1265 last_modified = None
1266 name = '-'
1267 last_checked = property(lambda self: None)
1268 implementations = property(lambda self: {})
1269 feeds = property(lambda self: [])
1270 summary = property(lambda self: '-')
1271 description = property(lambda self: '')
1272 def get_name(self): return self.name
1273 def get_feed(self, url): return None
1274 def get_metadata(self, uri, name): return []
1275 _dummy_feed = DummyFeed()
1277 if sys.version_info[0] > 2:
1278 # Python 3
1280 from functools import total_ordering
1281 # (note: delete these two lines when generating epydoc)
1282 Stability = total_ordering(Stability)
1283 Implementation = total_ordering(Implementation)
1285 # These could be replaced by urllib.parse.quote, except that
1286 # it uses upper-case escapes and we use lower-case ones...
1287 def unescape(uri):
1288 """Convert each %20 to a space, etc.
1289 @rtype: str"""
1290 uri = uri.replace('#', '/')
1291 if '%' not in uri: return uri
1292 return re.sub(b'%[0-9a-fA-F][0-9a-fA-F]',
1293 lambda match: bytes([int(match.group(0)[1:], 16)]),
1294 uri.encode('ascii')).decode('utf-8')
1296 def escape(uri):
1297 """Convert each space to %20, etc
1298 @rtype: str"""
1299 return re.sub(b'[^-_.a-zA-Z0-9]',
1300 lambda match: ('%%%02x' % ord(match.group(0))).encode('ascii'),
1301 uri.encode('utf-8')).decode('ascii')
1303 def _pretty_escape(uri):
1304 """Convert each space to %20, etc
1305 : is preserved and / becomes #. This makes for nicer strings,
1306 and may replace L{escape} everywhere in future.
1307 @rtype: str"""
1308 if os.name == "posix":
1309 # Only preserve : on Posix systems
1310 preserveRegex = b'[^-_.a-zA-Z0-9:/]'
1311 else:
1312 # Other OSes may not allow the : character in file names
1313 preserveRegex = b'[^-_.a-zA-Z0-9/]'
1314 return re.sub(preserveRegex,
1315 lambda match: ('%%%02x' % ord(match.group(0))).encode('ascii'),
1316 uri.encode('utf-8')).decode('ascii').replace('/', '#')
1317 else:
1318 # Python 2
1320 def unescape(uri):
1321 """Convert each %20 to a space, etc.
1322 @rtype: str"""
1323 uri = uri.replace('#', '/')
1324 if '%' not in uri: return uri
1325 return re.sub('%[0-9a-fA-F][0-9a-fA-F]',
1326 lambda match: chr(int(match.group(0)[1:], 16)),
1327 uri).decode('utf-8')
1329 def escape(uri):
1330 """Convert each space to %20, etc
1331 @rtype: str"""
1332 return re.sub('[^-_.a-zA-Z0-9]',
1333 lambda match: '%%%02x' % ord(match.group(0)),
1334 uri.encode('utf-8'))
1336 def _pretty_escape(uri):
1337 """Convert each space to %20, etc
1338 : is preserved and / becomes #. This makes for nicer strings,
1339 and may replace L{escape} everywhere in future.
1340 @rtype: str"""
1341 if os.name == "posix":
1342 # Only preserve : on Posix systems
1343 preserveRegex = '[^-_.a-zA-Z0-9:/]'
1344 else:
1345 # Other OSes may not allow the : character in file names
1346 preserveRegex = '[^-_.a-zA-Z0-9/]'
1347 return re.sub(preserveRegex,
1348 lambda match: '%%%02x' % ord(match.group(0)),
1349 uri.encode('utf-8')).replace('/', '#')
1351 def canonical_iface_uri(uri):
1352 """If uri is a relative path, convert to an absolute one.
1353 A "file:///foo" URI is converted to "/foo".
1354 An "alias:prog" URI expands to the URI in the 0alias script
1355 Otherwise, return it unmodified.
1356 @rtype: str
1357 @raise SafeException: if uri isn't valid
1359 if uri.startswith('http://') or uri.startswith('https://'):
1360 if uri.count("/") < 3:
1361 raise SafeException(_("Missing / after hostname in URI '%s'") % uri)
1362 return uri
1363 elif uri.startswith('file:///'):
1364 path = uri[7:]
1365 elif uri.startswith('file:'):
1366 if uri[5] == '/':
1367 raise SafeException(_('Use file:///path for absolute paths, not {uri}').format(uri = uri))
1368 path = os.path.abspath(uri[5:])
1369 elif uri.startswith('alias:'):
1370 from zeroinstall import alias
1371 alias_prog = uri[6:]
1372 if not os.path.isabs(alias_prog):
1373 full_path = support.find_in_path(alias_prog)
1374 if not full_path:
1375 raise alias.NotAnAliasScript("Not found in $PATH: " + alias_prog)
1376 else:
1377 full_path = alias_prog
1378 return alias.parse_script(full_path).uri
1379 else:
1380 path = os.path.realpath(uri)
1382 if os.path.isfile(path):
1383 return path
1384 raise SafeException(_("Bad interface name '%(uri)s'.\n"
1385 "(doesn't start with 'http:', and "
1386 "doesn't exist as a local file '%(interface_uri)s' either)") %
1387 {'uri': uri, 'interface_uri': path})
1389 _version_mod_to_value = {
1390 'pre': -2,
1391 'rc': -1,
1392 '': 0,
1393 'post': 1,
1396 # Reverse mapping
1397 _version_value_to_mod = {}
1398 for x in _version_mod_to_value: _version_value_to_mod[_version_mod_to_value[x]] = x
1399 del x
1401 _version_re = re.compile('-([a-z]*)')
1403 def parse_version(version_string):
1404 """Convert a version string to an internal representation.
1405 The parsed format can be compared quickly using the standard Python functions.
1406 - Version := DottedList ("-" Mod DottedList?)*
1407 - DottedList := (Integer ("." Integer)*)
1408 @rtype: tuple (opaque)
1409 @raise SafeException: if the string isn't a valid version
1410 @since: 0.24 (moved from L{reader}, from where it is still available):"""
1411 if version_string is None: return None
1412 parts = _version_re.split(version_string)
1413 if parts[-1] == '':
1414 del parts[-1] # Ends with a modifier
1415 else:
1416 parts.append('')
1417 if not parts:
1418 raise SafeException(_("Empty version string!"))
1419 l = len(parts)
1420 try:
1421 for x in range(0, l, 2):
1422 part = parts[x]
1423 if part:
1424 parts[x] = list(map(int, parts[x].split('.')))
1425 else:
1426 parts[x] = [] # (because ''.split('.') == [''], not [])
1427 for x in range(1, l, 2):
1428 parts[x] = _version_mod_to_value[parts[x]]
1429 return parts
1430 except ValueError as ex:
1431 raise SafeException(_("Invalid version format in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1432 except KeyError as ex:
1433 raise SafeException(_("Invalid version modifier in '%(version_string)s': %(exception)s") % {'version_string': version_string, 'exception': ex})
1435 def format_version(version):
1436 """Format a parsed version for display. Undoes the effect of L{parse_version}.
1437 @see: L{Implementation.get_version}
1438 @rtype: str
1439 @since: 0.24"""
1440 version = version[:]
1441 l = len(version)
1442 for x in range(0, l, 2):
1443 version[x] = '.'.join(map(str, version[x]))
1444 for x in range(1, l, 2):
1445 version[x] = '-' + _version_value_to_mod[version[x]]
1446 if version[-1] == '-': del version[-1]
1447 return ''.join(version)