1 """In-memory representation of interfaces and other data structures.
3 The objects in this module are used to build a representation of an XML interface
6 @see: L{reader} constructs these data-structures.
8 @var defaults: Default values for the 'default' attribute for <environment> bindings of
12 # Copyright (C) 2006, Thomas Leonard
13 # See the README file for details, or visit http://0install.net.
16 from logging
import warn
, info
, debug
17 from zeroinstall
import SafeException
, version
18 from zeroinstall
.injector
.namespaces
import XMLNS_IFACE
20 # Element names for bindings in feed files
21 binding_names
= frozenset(['environment'])
23 network_offline
= 'off-line'
24 network_minimal
= 'minimal'
26 network_levels
= (network_offline
, network_minimal
, network_full
)
28 stability_levels
= {} # Name -> Stability
31 'PATH': '/bin:/usr/bin',
32 'XDG_CONFIG_DIRS': '/etc/xdg',
33 'XDG_DATA_DIRS': '/usr/local/share:/usr/share',
36 class InvalidInterface(SafeException
):
37 """Raised when parsing an invalid feed."""
38 def __init__(self
, message
, ex
= None):
40 message
+= "\n\n(exact error: %s)" % ex
41 SafeException
.__init
__(self
, message
)
43 def _split_arch(arch
):
44 """Split an arch into an (os, machine) tuple. Either or both parts may be None."""
48 raise SafeException("Malformed arch '%s'" % arch
)
50 os
, machine
= arch
.split('-', 1)
51 if os
== '*': os
= None
52 if machine
== '*': machine
= None
55 def _join_arch(os
, machine
):
56 if os
== machine
== None: return None
57 return "%s-%s" % (os
or '*', machine
or '*')
59 class Stability(object):
60 """A stability rating. Each implementation has an upstream stability rating and,
61 optionally, a user-set rating."""
62 __slots__
= ['level', 'name', 'description']
63 def __init__(self
, level
, name
, description
):
66 self
.description
= description
67 assert name
not in stability_levels
68 stability_levels
[name
] = self
70 def __cmp__(self
, other
):
71 return cmp(self
.level
, other
.level
)
77 return "<Stability: " + self
.description
+ ">"
79 def process_binding(e
):
81 if e
.name
== 'environment':
83 None: EnvironmentBinding
.PREPEND
,
84 'prepend': EnvironmentBinding
.PREPEND
,
85 'append': EnvironmentBinding
.APPEND
,
86 'replace': EnvironmentBinding
.REPLACE
,
87 }[e
.getAttribute('mode')]
89 binding
= EnvironmentBinding(e
.getAttribute('name'),
90 insert
= e
.getAttribute('insert'),
91 default
= e
.getAttribute('default'),
93 if not binding
.name
: raise InvalidInterface("Missing 'name' in binding")
94 if binding
.insert
is None: raise InvalidInterface("Missing 'insert' in binding")
97 raise Exception("Unknown binding type '%s'" % e
.name
)
99 def process_depends(item
):
101 # Note: also called from selections
102 dep_iface
= item
.getAttribute('interface')
104 raise InvalidInterface("Missing 'interface' on <requires>")
105 dependency
= InterfaceDependency(dep_iface
, metadata
= item
.attrs
)
107 for e
in item
.childNodes
:
108 if e
.uri
!= XMLNS_IFACE
: continue
109 if e
.name
in binding_names
:
110 dependency
.bindings
.append(process_binding(e
))
111 elif e
.name
== 'version':
112 dependency
.restrictions
.append(
113 VersionRangeRestriction(not_before
= parse_version(e
.getAttribute('not-before')),
114 before
= parse_version(e
.getAttribute('before'))))
118 insecure
= Stability(0, 'insecure', 'This is a security risk')
119 buggy
= Stability(5, 'buggy', 'Known to have serious bugs')
120 developer
= Stability(10, 'developer', 'Work-in-progress - bugs likely')
121 testing
= Stability(20, 'testing', 'Stability unknown - please test!')
122 stable
= Stability(30, 'stable', 'Tested - no serious problems found')
123 packaged
= Stability(35, 'packaged', 'Supplied by the local package manager')
124 preferred
= Stability(40, 'preferred', 'Best of all - must be set manually')
126 class Restriction(object):
127 """A Restriction limits the allowed implementations of an Interface."""
130 def meets_restriction(self
, impl
):
131 raise NotImplementedError("Abstract")
133 class VersionRangeRestriction(Restriction
):
134 """Only versions within the given range are acceptable"""
135 __slots__
= ['before', 'not_before']
136 def __init__(self
, before
, not_before
):
138 self
.not_before
= not_before
140 def meets_restriction(self
, impl
):
141 if self
.not_before
and impl
.version
< self
.not_before
:
143 if self
.before
and impl
.version
>= self
.before
:
148 if self
.not_before
is not None or self
.before
is not None:
150 if self
.not_before
is not None:
151 range += format_version(self
.not_before
) + ' <= '
153 if self
.before
is not None:
154 range += ' < ' + format_version(self
.before
)
157 return "(restriction: %s)" % range
159 class Binding(object):
160 """Information about how the choice of a Dependency is made known
161 to the application being run."""
163 class EnvironmentBinding(Binding
):
164 """Indicate the chosen implementation using an environment variable."""
165 __slots__
= ['name', 'insert', 'default', 'mode']
171 def __init__(self
, name
, insert
, default
= None, mode
= PREPEND
):
172 """mode argument added in version 0.28"""
175 self
.default
= default
179 return "<environ %s %s %s>" % (self
.name
, self
.mode
, self
.insert
)
183 def get_value(self
, path
, old_value
):
184 """Calculate the new value of the environment variable after applying this binding.
185 @param path: the path to the selected implementation
186 @param old_value: the current value of the environment variable
187 @return: the new value for the environment variable"""
188 extra
= os
.path
.join(path
, self
.insert
)
190 if self
.mode
== EnvironmentBinding
.REPLACE
:
193 if old_value
is None:
194 old_value
= self
.default
or defaults
.get(self
.name
, None)
195 if old_value
is None:
197 if self
.mode
== EnvironmentBinding
.PREPEND
:
198 return extra
+ ':' + old_value
200 return old_value
+ ':' + extra
202 def _toxml(self
, doc
):
203 """Create a DOM element for this binding.
204 @param doc: document to use to create the element
205 @return: the new element
207 env_elem
= doc
.createElementNS(XMLNS_IFACE
, 'environment')
208 env_elem
.setAttributeNS(None, 'name', self
.name
)
209 env_elem
.setAttributeNS(None, 'insert', self
.insert
)
211 env_elem
.setAttributeNS(None, 'default', self
.default
)
215 """An interface's feeds are other interfaces whose implementations can also be
216 used as implementations of this interface."""
217 __slots__
= ['uri', 'os', 'machine', 'user_override', 'langs']
218 def __init__(self
, uri
, arch
, user_override
, langs
= None):
220 # This indicates whether the feed comes from the user's overrides
221 # file. If true, writer.py will write it when saving.
222 self
.user_override
= user_override
223 self
.os
, self
.machine
= _split_arch(arch
)
227 return "<Feed from %s>" % self
.uri
230 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
232 class Dependency(object):
233 """A Dependency indicates that an Implementation requires some additional
234 code to function. This is an abstract base class.
235 @ivar metadata: any extra attributes from the XML element
236 @type metadata: {str: str}
238 __slots__
= ['metadata']
240 def __init__(self
, metadata
):
244 assert not isinstance(metadata
, basestring
) # Use InterfaceDependency instead!
245 self
.metadata
= metadata
247 class InterfaceDependency(Dependency
):
248 """A Dependency on a Zero Install interface.
249 @ivar interface: the interface required by this dependency
251 @ivar restrictions: a list of constraints on acceptable implementations
252 @type restrictions: [L{Restriction}]
253 @ivar bindings: how to make the choice of implementation known
254 @type bindings: [L{Binding}]
257 __slots__
= ['interface', 'restrictions', 'bindings', 'metadata']
259 def __init__(self
, interface
, restrictions
= None, metadata
= None):
260 Dependency
.__init
__(self
, metadata
)
261 assert isinstance(interface
, (str, unicode))
263 self
.interface
= interface
264 if restrictions
is None:
265 self
.restrictions
= []
267 self
.restrictions
= restrictions
271 return "<Dependency on %s; bindings: %s%s>" % (self
.interface
, self
.bindings
, self
.restrictions
)
273 class RetrievalMethod(object):
274 """A RetrievalMethod provides a way to fetch an implementation."""
277 class DownloadSource(RetrievalMethod
):
278 """A DownloadSource provides a way to fetch an implementation."""
279 __slots__
= ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
281 def __init__(self
, implementation
, url
, size
, extract
, start_offset
= 0, type = None):
282 assert url
.startswith('http:') or url
.startswith('ftp:') or url
.startswith('/')
283 self
.implementation
= implementation
286 self
.extract
= extract
287 self
.start_offset
= start_offset
288 self
.type = type # MIME type - see unpack.py
290 class Recipe(RetrievalMethod
):
291 """Get an implementation by following a series of steps.
292 @ivar size: the combined download sizes from all the steps
294 @ivar steps: the sequence of steps which must be performed
295 @type steps: [L{RetrievalMethod}]"""
296 __slots__
= ['steps']
301 size
= property(lambda self
: sum([x
.size
for x
in self
.steps
]))
303 class Implementation(object):
304 """An Implementation is a package which implements an Interface.
305 @ivar download_sources: list of methods of getting this implementation
306 @type download_sources: [L{RetrievalMethod}]
307 @ivar feed: the feed owning this implementation (since 0.32)
308 @type feed: [L{ZeroInstallFeed}]
309 @ivar bindings: how to tell this component where it itself is located (since 0.31)
310 @type bindings: [Binding]
313 # Note: user_stability shouldn't really be here
315 __slots__
= ['upstream_stability', 'user_stability', 'langs',
316 'requires', 'main', 'metadata', 'download_sources',
317 'id', 'feed', 'version', 'released', 'bindings']
319 def __init__(self
, feed
, id):
324 self
.user_stability
= None
325 self
.upstream_stability
= None
326 self
.metadata
= {} # [URI + " "] + localName -> value
330 self
.download_sources
= []
334 def get_stability(self
):
335 return self
.user_stability
or self
.upstream_stability
or testing
341 return "v%s (%s)" % (self
.get_version(), self
.id)
343 def __cmp__(self
, other
):
344 """Newer versions come first"""
345 return cmp(other
.version
, self
.version
)
347 def get_version(self
):
348 """Return the version as a string.
349 @see: L{format_version}
351 return format_version(self
.version
)
353 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
357 class DistributionImplementation(Implementation
):
358 """An implementation provided by the distribution. Information such as the version
359 comes from the package manager.
361 __slots__
= ['installed']
363 def __init__(self
, feed
, id):
364 assert id.startswith('package:')
365 Implementation
.__init
__(self
, feed
, id)
366 self
.installed
= True
368 class ZeroInstallImplementation(Implementation
):
369 """An implementation where all the information comes from Zero Install.
371 __slots__
= ['os', 'machine', 'upstream_stability', 'user_stability',
372 'size', 'requires', 'main', 'id']
374 def __init__(self
, feed
, id):
375 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
376 Implementation
.__init
__(self
, feed
, id)
382 dependencies
= property(lambda self
: dict([(x
.interface
, x
) for x
in self
.requires
383 if isinstance(x
, InterfaceDependency
)]))
385 def add_download_source(self
, url
, size
, extract
, start_offset
= 0, type = None):
386 """Add a download source."""
387 self
.download_sources
.append(DownloadSource(self
, url
, size
, extract
, start_offset
, type))
389 def set_arch(self
, arch
):
390 self
.os
, self
.machine
= _split_arch(arch
)
391 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
), set_arch
)
393 class Interface(object):
394 """An Interface represents some contract of behaviour.
395 @ivar uri: the URI for this interface.
396 @ivar stability_policy: user's configured policy.
397 Implementations at this level or higher are preferred.
398 Lower levels are used only if there is no other choice.
400 __slots__
= ['uri', 'stability_policy', '_main_feed', 'extra_feeds']
402 implementations
= property(lambda self
: self
._main
_feed
.implementations
)
403 name
= property(lambda self
: self
._main
_feed
.name
)
404 description
= property(lambda self
: self
._main
_feed
.description
)
405 summary
= property(lambda self
: self
._main
_feed
.summary
)
406 last_modified
= property(lambda self
: self
._main
_feed
.last_modified
)
407 feeds
= property(lambda self
: self
.extra_feeds
+ self
._main
_feed
.feeds
)
408 metadata
= property(lambda self
: self
._main
_feed
.metadata
)
410 last_checked
= property(lambda self
: self
._main
_feed
.last_checked
)
412 def __init__(self
, uri
):
414 if uri
.startswith('http:') or uri
.startswith('/'):
417 raise SafeException("Interface name '%s' doesn't start "
418 "with 'http:'" % uri
)
421 def _get_feed_for(self
):
423 for key
in self
._main
_feed
.feed_for
:
426 feed_for
= property(_get_feed_for
) # Deprecated (used by 0publish)
429 self
.extra_feeds
= []
430 self
._main
_feed
= _dummy_feed
431 self
.stability_policy
= None
434 if self
._main
_feed
is not _dummy_feed
:
435 return self
._main
_feed
.get_name()
436 return '(' + os
.path
.basename(self
.uri
) + ')'
439 return "<Interface %s>" % self
.uri
441 def set_stability_policy(self
, new
):
442 assert new
is None or isinstance(new
, Stability
)
443 self
.stability_policy
= new
445 def get_feed(self
, url
):
446 for x
in self
.extra_feeds
:
449 return self
._main
_feed
.get_feed(url
)
451 def get_metadata(self
, uri
, name
):
452 return self
._main
_feed
.get_metadata(uri
, name
)
454 def _merge_attrs(attrs
, item
):
455 """Add each attribute of item to a copy of attrs and return the copy.
456 @type attrs: {str: str}
457 @type item: L{qdom.Element}
462 new
[str(a
)] = item
.attrs
[a
]
465 def _get_long(elem
, attr_name
):
466 val
= elem
.getAttribute(attr_name
)
470 except ValueError, ex
:
471 raise SafeException("Invalid value for integer attribute '%s': %s" % (attr_name
, val
))
474 class ZeroInstallFeed(object):
475 """A feed lists available implementations of an interface.
476 @ivar url: the URL for this feed
477 @ivar implementations: Implementations in this feed, indexed by ID
478 @type implementations: {str: L{Implementation}}
479 @ivar name: human-friendly name
480 @ivar summary: short textual description
481 @ivar description: long textual description
482 @ivar last_modified: timestamp on signature
483 @ivar last_checked: time feed was last successfully downloaded and updated
484 @ivar feeds: list of <feed> elements in this feed
485 @type feeds: [L{Feed}]
486 @ivar feed_for: interfaces for which this could be a feed
487 @type feed_for: set(str)
488 @ivar metadata: extra elements we didn't understand
490 # _main is deprecated
491 __slots__
= ['url', 'implementations', 'name', 'description', 'summary',
492 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
494 def __init__(self
, feed_element
, local_path
= None, distro
= None):
495 """Create a feed object from a DOM.
496 @param feed_element: the root element of a feed file
497 @type feed_element: L{qdom.Element}
498 @param interface: temporary hack for restructuring. will go away.
499 @param local_name: the pathname of this local feed, or None for remote feeds
500 @param distro: used to resolve distribution package references
501 @type distro: L{distro.Distribution} or None"""
503 self
.implementations
= {}
506 self
.description
= ""
507 self
.last_modified
= None
509 self
.feed_for
= set()
511 self
.last_checked
= None
513 assert feed_element
.name
in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
514 assert feed_element
.uri
== XMLNS_IFACE
, "Wrong namespace on root element: %s" % feed_element
.uri
516 main
= feed_element
.getAttribute('main')
517 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
520 self
.url
= local_path
521 local_dir
= os
.path
.dirname(local_path
)
523 self
.url
= feed_element
.getAttribute('uri')
525 raise InvalidInterface("<interface> uri attribute missing")
526 local_dir
= None # Can't have relative paths
528 min_injector_version
= feed_element
.getAttribute('min-injector-version')
529 if min_injector_version
:
530 if parse_version(min_injector_version
) > parse_version(version
):
531 raise InvalidInterface("This feed requires version %s or later of "
532 "Zero Install, but I am only version %s. "
533 "You can get a newer version from http://0install.net" %
534 (min_injector_version
, version
))
536 for x
in feed_element
.childNodes
:
537 if x
.uri
!= XMLNS_IFACE
:
538 self
.metadata
.append(x
)
541 self
.name
= x
.content
542 elif x
.name
== 'description':
543 self
.description
= x
.content
544 elif x
.name
== 'summary':
545 self
.summary
= x
.content
546 elif x
.name
== 'feed-for':
547 feed_iface
= x
.getAttribute('interface')
549 raise InvalidInterface('Missing "interface" attribute in <feed-for>')
550 self
.feed_for
.add(feed_iface
)
551 # Bug report from a Debian/stable user that --feed gets the wrong value.
552 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
553 # in case it happens again.
554 debug("Is feed-for %s", feed_iface
)
555 elif x
.name
== 'feed':
556 feed_src
= x
.getAttribute('src')
558 raise InvalidInterface('Missing "src" attribute in <feed>')
559 if feed_src
.startswith('http:') or local_path
:
560 self
.feeds
.append(Feed(feed_src
, x
.getAttribute('arch'), False, langs
= x
.getAttribute('langs')))
562 raise InvalidInterface("Invalid feed URL '%s'" % feed_src
)
564 self
.metadata
.append(x
)
567 raise InvalidInterface("Missing <name> in feed")
569 raise InvalidInterface("Missing <summary> in feed")
571 def process_group(group
, group_attrs
, base_depends
, base_bindings
):
572 for item
in group
.childNodes
:
573 if item
.uri
!= XMLNS_IFACE
: continue
575 if item
.name
not in ('group', 'implementation', 'package-implementation'):
578 depends
= base_depends
[:]
579 bindings
= base_bindings
[:]
581 item_attrs
= _merge_attrs(group_attrs
, item
)
583 # We've found a group or implementation. Scan for dependencies
584 # and bindings. Doing this here means that:
585 # - We can share the code for groups and implementations here.
586 # - The order doesn't matter, because these get processed first.
587 # A side-effect is that the document root cannot contain
589 for child
in item
.childNodes
:
590 if child
.uri
!= XMLNS_IFACE
: continue
591 if child
.name
== 'requires':
592 dep
= process_depends(child
)
594 elif child
.name
in binding_names
:
595 bindings
.append(process_binding(child
))
597 if item
.name
== 'group':
598 process_group(item
, item_attrs
, depends
, bindings
)
599 elif item
.name
== 'implementation':
600 process_impl(item
, item_attrs
, depends
, bindings
)
601 elif item
.name
== 'package-implementation':
602 process_native_impl(item
, item_attrs
, depends
)
606 def process_impl(item
, item_attrs
, depends
, bindings
):
607 id = item
.getAttribute('id')
609 raise InvalidInterface("Missing 'id' attribute on %s" % item
)
610 if local_dir
and (id.startswith('/') or id.startswith('.')):
611 impl
= self
._get
_impl
(os
.path
.abspath(os
.path
.join(local_dir
, id)))
614 raise InvalidInterface('Invalid "id"; form is "alg=value" (got "%s")' % id)
615 alg
, sha1
= id.split('=')
618 except Exception, ex
:
619 raise InvalidInterface('Bad SHA1 attribute: %s' % ex
)
620 impl
= self
._get
_impl
(id)
622 impl
.metadata
= item_attrs
624 version
= item_attrs
['version']
625 version_mod
= item_attrs
.get('version-modifier', None)
626 if version_mod
: version
+= version_mod
628 raise InvalidInterface("Missing version attribute")
629 impl
.version
= parse_version(version
)
631 item_main
= item_attrs
.get('main', None)
632 if item_main
and item_main
.startswith('/'):
633 raise InvalidInterface("'main' attribute must be relative, but '%s' starts with '/'!" %
635 impl
.main
= item_main
637 impl
.released
= item_attrs
.get('released', None)
638 impl
.langs
= item_attrs
.get('langs', None)
640 size
= item
.getAttribute('size')
642 impl
.size
= long(size
)
643 impl
.arch
= item_attrs
.get('arch', None)
645 stability
= stability_levels
[str(item_attrs
['stability'])]
647 stab
= str(item_attrs
['stability'])
648 if stab
!= stab
.lower():
649 raise InvalidInterface('Stability "%s" invalid - use lower case!' % item_attrs
.stability
)
650 raise InvalidInterface('Stability "%s" invalid' % item_attrs
['stability'])
651 if stability
>= preferred
:
652 raise InvalidInterface("Upstream can't set stability to preferred!")
653 impl
.upstream_stability
= stability
655 impl
.bindings
= bindings
656 impl
.requires
= depends
658 for elem
in item
.childNodes
:
659 if elem
.uri
!= XMLNS_IFACE
: continue
660 if elem
.name
== 'archive':
661 url
= elem
.getAttribute('href')
663 raise InvalidInterface("Missing href attribute on <archive>")
664 size
= elem
.getAttribute('size')
666 raise InvalidInterface("Missing size attribute on <archive>")
667 impl
.add_download_source(url
= url
, size
= long(size
),
668 extract
= elem
.getAttribute('extract'),
669 start_offset
= _get_long(elem
, 'start-offset'),
670 type = elem
.getAttribute('type'))
671 elif elem
.name
== 'recipe':
673 for recipe_step
in elem
.childNodes
:
674 if recipe_step
.uri
== XMLNS_IFACE
and recipe_step
.name
== 'archive':
675 url
= recipe_step
.getAttribute('href')
677 raise InvalidInterface("Missing href attribute on <archive>")
678 size
= recipe_step
.getAttribute('size')
680 raise InvalidInterface("Missing size attribute on <archive>")
681 recipe
.steps
.append(DownloadSource(None, url
= url
, size
= long(size
),
682 extract
= recipe_step
.getAttribute('extract'),
683 start_offset
= _get_long(recipe_step
, 'start-offset'),
684 type = recipe_step
.getAttribute('type')))
686 info("Unknown step '%s' in recipe; skipping recipe", recipe_step
.name
)
689 impl
.download_sources
.append(recipe
)
691 def process_native_impl(item
, item_attrs
, depends
):
692 package
= item_attrs
.get('package', None)
694 raise InvalidInterface("Missing 'package' attribute on %s" % item
)
697 assert id.startswith('package:')
698 impl
= self
._get
_impl
(id)
700 impl
.metadata
= item_attrs
702 item_main
= item_attrs
.get('main', None)
703 if item_main
and not item_main
.startswith('/'):
704 raise InvalidInterface("'main' attribute must be absolute, but '%s' doesn't start with '/'!" %
706 impl
.main
= item_main
707 impl
.upstream_stability
= packaged
708 impl
.requires
= depends
712 distro
.get_package_info(package
, factory
)
714 process_group(feed_element
,
715 {'stability': 'testing',
721 return self
.name
or '(' + os
.path
.basename(self
.url
) + ')'
724 return "<Feed %s>" % self
.url
726 def _get_impl(self
, id):
727 if id not in self
.implementations
:
728 if id.startswith('package:'):
729 impl
= DistributionImplementation(self
, id)
731 impl
= ZeroInstallImplementation(self
, id)
732 self
.implementations
[id] = impl
733 return self
.implementations
[id]
735 def set_stability_policy(self
, new
):
736 assert new
is None or isinstance(new
, Stability
)
737 self
.stability_policy
= new
739 def get_feed(self
, url
):
745 def add_metadata(self
, elem
):
746 self
.metadata
.append(elem
)
748 def get_metadata(self
, uri
, name
):
749 """Return a list of interface metadata elements with this name and namespace URI."""
750 return [m
for m
in self
.metadata
if m
.name
== name
and m
.uri
== uri
]
752 class DummyFeed(object):
755 last_checked
= property(lambda self
: None)
756 implementations
= property(lambda self
: {})
757 feeds
= property(lambda self
: [])
758 summary
= property(lambda self
: '-')
759 description
= property(lambda self
: '')
760 def get_name(self
): return self
.name
761 def get_feed(self
, url
): return None
762 def get_metadata(self
, uri
, name
): return []
763 _dummy_feed
= DummyFeed()
766 """Convert each %20 to a space, etc.
768 uri
= uri
.replace('#', '/')
769 if '%' not in uri
: return uri
770 return re
.sub('%[0-9a-fA-F][0-9a-fA-F]',
771 lambda match
: chr(int(match
.group(0)[1:], 16)),
775 """Convert each space to %20, etc
777 return re
.sub('[^-_.a-zA-Z0-9]',
778 lambda match
: '%%%02x' % ord(match
.group(0)),
781 def _pretty_escape(uri
):
782 """Convert each space to %20, etc
783 : is preserved and / becomes #. This makes for nicer strings,
784 and may replace L{escape} everywhere in future.
786 return re
.sub('[^-_.a-zA-Z0-9:/]',
787 lambda match
: '%%%02x' % ord(match
.group(0)),
788 uri
.encode('utf-8')).replace('/', '#')
790 def canonical_iface_uri(uri
):
791 """If uri is a relative path, convert to an absolute one.
792 Otherwise, return it unmodified.
794 @raise SafeException: if uri isn't valid
796 if uri
.startswith('http:'):
799 iface_uri
= os
.path
.realpath(uri
)
800 if os
.path
.isfile(iface_uri
):
802 raise SafeException("Bad interface name '%s'.\n"
803 "(doesn't start with 'http:', and "
804 "doesn't exist as a local file '%s' either)" %
807 _version_mod_to_value
= {
815 _version_value_to_mod
= {}
816 for x
in _version_mod_to_value
: _version_value_to_mod
[_version_mod_to_value
[x
]] = x
819 _version_re
= re
.compile('-([a-z]*)')
821 def parse_version(version_string
):
822 """Convert a version string to an internal representation.
823 The parsed format can be compared quickly using the standard Python functions.
824 - Version := DottedList ("-" Mod DottedList?)*
825 - DottedList := (Integer ("." Integer)*)
826 @rtype: tuple (opaque)
827 @raise SafeException: if the string isn't a valid version
828 @since: 0.24 (moved from L{reader}, from where it is still available):"""
829 if version_string
is None: return None
830 parts
= _version_re
.split(version_string
)
832 del parts
[-1] # Ends with a modifier
836 raise SafeException("Empty version string!")
839 for x
in range(0, l
, 2):
842 parts
[x
] = map(int, parts
[x
].split('.'))
844 parts
[x
] = [] # (because ''.split('.') == [''], not [])
845 for x
in range(1, l
, 2):
846 parts
[x
] = _version_mod_to_value
[parts
[x
]]
848 except ValueError, ex
:
849 raise SafeException("Invalid version format in '%s': %s" % (version_string
, ex
))
851 raise SafeException("Invalid version modifier in '%s': %s" % (version_string
, ex
))
853 def format_version(version
):
854 """Format a parsed version for display. Undoes the effect of L{parse_version}.
855 @see: L{Implementation.get_version}
860 for x
in range(0, l
, 2):
861 version
[x
] = '.'.join(map(str, version
[x
]))
862 for x
in range(1, l
, 2):
863 version
[x
] = '-' + _version_value_to_mod
[version
[x
]]
864 if version
[-1] == '-': del version
[-1]
865 return ''.join(version
)