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
, 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 Restriction(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."""
128 __slots__
= ['before', 'not_before']
129 def __init__(self
, before
, not_before
):
131 self
.not_before
= not_before
133 def meets_restriction(self
, impl
):
134 if self
.not_before
and impl
.version
< self
.not_before
:
136 if self
.before
and impl
.version
>= self
.before
:
141 if self
.not_before
is not None or self
.before
is not None:
143 if self
.not_before
is not None:
144 range += format_version(self
.not_before
) + ' <= '
146 if self
.before
is not None:
147 range += ' < ' + format_version(self
.before
)
150 return "(restriction: %s)" % range
152 class Binding(object):
153 """Information about how the choice of a Dependency is made known
154 to the application being run."""
156 class EnvironmentBinding(Binding
):
157 """Indicate the chosen implementation using an environment variable."""
158 __slots__
= ['name', 'insert', 'default', 'mode']
164 def __init__(self
, name
, insert
, default
= None, mode
= PREPEND
):
165 """mode argument added in version 0.28"""
168 self
.default
= default
172 return "<environ %s %s %s>" % (self
.name
, self
.mode
, self
.insert
)
176 def get_value(self
, path
, old_value
):
177 """Calculate the new value of the environment variable after applying this binding.
178 @param path: the path to the selected implementation
179 @param old_value: the current value of the environment variable
180 @return: the new value for the environment variable"""
181 extra
= os
.path
.join(path
, self
.insert
)
183 if self
.mode
== EnvironmentBinding
.REPLACE
:
186 if old_value
is None:
187 old_value
= self
.default
or defaults
.get(self
.name
, None)
188 if old_value
is None:
190 if self
.mode
== EnvironmentBinding
.PREPEND
:
191 return extra
+ ':' + old_value
193 return old_value
+ ':' + extra
195 def _toxml(self
, doc
):
196 """Create a DOM element for this binding.
197 @param doc: document to use to create the element
198 @return: the new element
200 env_elem
= doc
.createElementNS(XMLNS_IFACE
, 'environment')
201 env_elem
.setAttributeNS(None, 'name', self
.name
)
202 env_elem
.setAttributeNS(None, 'insert', self
.insert
)
204 env_elem
.setAttributeNS(None, 'default', self
.default
)
208 """An interface's feeds are other interfaces whose implementations can also be
209 used as implementations of this interface."""
210 __slots__
= ['uri', 'os', 'machine', 'user_override', 'langs']
211 def __init__(self
, uri
, arch
, user_override
, langs
= None):
213 # This indicates whether the feed comes from the user's overrides
214 # file. If true, writer.py will write it when saving.
215 self
.user_override
= user_override
216 self
.os
, self
.machine
= _split_arch(arch
)
220 return "<Feed from %s>" % self
.uri
223 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
225 class Dependency(object):
226 """A Dependency indicates that an Implementation requires some additional
227 code to function. This is an abstract base class.
228 @ivar metadata: any extra attributes from the XML element
229 @type metadata: {str: str}
231 __slots__
= ['metadata']
233 def __init__(self
, metadata
):
237 assert not isinstance(metadata
, basestring
) # Use InterfaceDependency instead!
238 self
.metadata
= metadata
240 class InterfaceDependency(Dependency
):
241 """A Dependency on a Zero Install interface.
242 @ivar interface: the interface required by this dependency
244 @ivar restrictions: a list of constraints on acceptable implementations
245 @type restrictions: [L{Restriction}]
246 @ivar bindings: how to make the choice of implementation known
247 @type bindings: [L{Binding}]
250 __slots__
= ['interface', 'restrictions', 'bindings', 'metadata']
252 def __init__(self
, interface
, restrictions
= None, metadata
= None):
253 Dependency
.__init
__(self
, metadata
)
254 assert isinstance(interface
, (str, unicode))
256 self
.interface
= interface
257 if restrictions
is None:
258 self
.restrictions
= []
260 self
.restrictions
= restrictions
264 return "<Dependency on %s; bindings: %s%s>" % (self
.interface
, self
.bindings
, self
.restrictions
)
266 class RetrievalMethod(object):
267 """A RetrievalMethod provides a way to fetch an implementation."""
270 class DownloadSource(RetrievalMethod
):
271 """A DownloadSource provides a way to fetch an implementation."""
272 __slots__
= ['implementation', 'url', 'size', 'extract', 'start_offset', 'type']
274 def __init__(self
, implementation
, url
, size
, extract
, start_offset
= 0, type = None):
275 assert url
.startswith('http:') or url
.startswith('ftp:') or url
.startswith('/')
276 self
.implementation
= implementation
279 self
.extract
= extract
280 self
.start_offset
= start_offset
281 self
.type = type # MIME type - see unpack.py
283 class Recipe(RetrievalMethod
):
284 """Get an implementation by following a series of steps.
285 @ivar size: the combined download sizes from all the steps
287 @ivar steps: the sequence of steps which must be performed
288 @type steps: [L{RetrievalMethod}]"""
289 __slots__
= ['steps']
294 size
= property(lambda self
: sum([x
.size
for x
in self
.steps
]))
296 class Implementation(object):
297 """An Implementation is a package which implements an Interface.
298 @ivar download_sources: list of methods of getting this implementation
299 @type download_sources: [L{RetrievalMethod}]
300 @ivar feed: the feed owning this implementation (since 0.32)
301 @type feed: [L{ZeroInstallFeed}]
302 @ivar bindings: how to tell this component where it itself is located (since 0.31)
303 @type bindings: [Binding]
306 __slots__
= ['upstream_stability', 'user_stability', 'langs',
307 'requires', 'main', 'metadata', 'download_sources',
308 'id', 'feed', 'version', 'released', 'bindings']
310 def __init__(self
, feed
, id):
315 self
.user_stability
= None
316 self
.upstream_stability
= None
317 self
.metadata
= {} # [URI + " "] + localName -> value
321 self
.download_sources
= []
325 def get_stability(self
):
326 return self
.user_stability
or self
.upstream_stability
or testing
331 def __cmp__(self
, other
):
332 """Newer versions come first"""
333 return cmp(other
.version
, self
.version
)
335 def get_version(self
):
336 """Return the version as a string.
337 @see: L{format_version}
339 return format_version(self
.version
)
341 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
345 class DistributionImplementation(Implementation
):
346 """An implementation provided by the distribution. Information such as the version
347 comes from the package manager.
349 __slots__
= ['installed']
351 def __init__(self
, feed
, id):
352 assert id.startswith('package:')
353 Implementation
.__init
__(self
, feed
, id)
354 self
.installed
= True
356 class ZeroInstallImplementation(Implementation
):
357 """An implementation where all the information comes from Zero Install.
359 __slots__
= ['os', 'machine', 'upstream_stability', 'user_stability',
360 'size', 'requires', 'main', 'id']
362 def __init__(self
, feed
, id):
363 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
364 Implementation
.__init
__(self
, feed
, id)
370 dependencies
= property(lambda self
: dict([(x
.interface
, x
) for x
in self
.requires
371 if isinstance(x
, InterfaceDependency
)]))
373 def add_download_source(self
, url
, size
, extract
, start_offset
= 0, type = None):
374 """Add a download source."""
375 self
.download_sources
.append(DownloadSource(self
, url
, size
, extract
, start_offset
, type))
377 def set_arch(self
, arch
):
378 self
.os
, self
.machine
= _split_arch(arch
)
379 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
), set_arch
)
381 class Interface(object):
382 """An Interface represents some contract of behaviour.
383 @ivar uri: the URI for this interface.
384 @ivar stability_policy: user's configured policy.
385 Implementations at this level or higher are preferred.
386 Lower levels are used only if there is no other choice.
387 @ivar last_checked: time feed was last successfully downloaded and updated
388 @ivar last_check_attempt: time we last tried to check for updates (in the background)
390 __slots__
= ['uri', 'stability_policy', '_main_feed', 'extra_feeds',
391 'last_checked', 'last_check_attempt']
393 implementations
= property(lambda self
: self
._main
_feed
.implementations
)
394 name
= property(lambda self
: self
._main
_feed
.name
)
395 description
= property(lambda self
: self
._main
_feed
.description
)
396 summary
= property(lambda self
: self
._main
_feed
.summary
)
397 last_modified
= property(lambda self
: self
._main
_feed
.last_modified
)
398 feeds
= property(lambda self
: self
.extra_feeds
+ self
._main
_feed
.feeds
)
399 metadata
= property(lambda self
: self
._main
_feed
.metadata
)
401 def __init__(self
, uri
):
403 if uri
.startswith('http:') or uri
.startswith('/'):
406 raise SafeException("Interface name '%s' doesn't start "
407 "with 'http:'" % uri
)
410 def _get_feed_for(self
):
412 for key
in self
._main
_feed
.feed_for
:
415 feed_for
= property(_get_feed_for
) # Deprecated (used by 0publish)
418 self
.extra_feeds
= []
419 self
._main
_feed
= _dummy_feed
420 self
.stability_policy
= None
421 self
.last_checked
= None
422 self
.last_check_attempt
= None
425 if self
._main
_feed
is not _dummy_feed
:
426 return self
._main
_feed
.get_name()
427 return '(' + os
.path
.basename(self
.uri
) + ')'
430 return "<Interface %s>" % self
.uri
432 def set_stability_policy(self
, new
):
433 assert new
is None or isinstance(new
, Stability
)
434 self
.stability_policy
= new
436 def get_feed(self
, url
):
437 for x
in self
.extra_feeds
:
440 return self
._main
_feed
.get_feed(url
)
442 def get_metadata(self
, uri
, name
):
443 return self
._main
_feed
.get_metadata(uri
, name
)
445 def _merge_attrs(attrs
, item
):
446 """Add each attribute of item to a copy of attrs and return the copy.
447 @type attrs: {str: str}
448 @type item: L{qdom.Element}
453 new
[str(a
)] = item
.attrs
[a
]
456 def _get_long(elem
, attr_name
):
457 val
= elem
.getAttribute(attr_name
)
461 except ValueError, ex
:
462 raise SafeException("Invalid value for integer attribute '%s': %s" % (attr_name
, val
))
465 class ZeroInstallFeed(object):
466 """A feed lists available implementations of an interface.
467 @ivar url: the URL for this feed
468 @ivar implementations: Implementations in this feed, indexed by ID
469 @type implementations: {str: L{Implementation}}
470 @ivar name: human-friendly name
471 @ivar summary: short textual description
472 @ivar description: long textual description
473 @ivar last_modified: timestamp on signature
474 @ivar last_checked: time feed was last successfully downloaded and updated
475 @ivar last_check_attempt: time we last tried to check for updates (in the background)
476 @ivar feeds: list of <feed> elements in this feed
477 @type feeds: [L{Feed}]
478 @ivar feed_for: interfaces for which this could be a feed
479 @type feed_for: set(str)
480 @ivar metadata: extra elements we didn't understand
482 # _main is deprecated
483 __slots__
= ['url', 'implementations', 'name', 'description', 'summary',
484 'last_modified', 'feeds', 'feed_for', 'metadata']
486 def __init__(self
, feed_element
, local_path
= None, distro
= None):
487 """Create a feed object from a DOM.
488 @param feed_element: the root element of a feed file
489 @type feed_element: L{qdom.Element}
490 @param interface: temporary hack for restructuring. will go away.
491 @param local_name: the pathname of this local feed, or None for remote feeds
492 @param distro: used to resolve distribution package references
493 @type distro: L{distro.Distribution} or None"""
495 self
.implementations
= {}
498 self
.description
= None
499 self
.last_modified
= None
501 self
.feed_for
= set()
504 assert feed_element
.name
in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
505 assert feed_element
.uri
== XMLNS_IFACE
, "Wrong namespace on root element: %s" % feed_element
.uri
507 main
= feed_element
.getAttribute('main')
508 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
511 self
.url
= local_path
512 local_dir
= os
.path
.dirname(local_path
)
514 self
.url
= feed_element
.getAttribute('uri')
516 raise InvalidInterface("<interface> uri attribute missing")
517 local_dir
= None # Can't have relative paths
519 min_injector_version
= feed_element
.getAttribute('min-injector-version')
520 if min_injector_version
:
521 if parse_version(min_injector_version
) > parse_version(version
):
522 raise InvalidInterface("This feed requires version %s or later of "
523 "Zero Install, but I am only version %s. "
524 "You can get a newer version from http://0install.net" %
525 (min_injector_version
, version
))
527 for x
in feed_element
.childNodes
:
528 if x
.uri
!= XMLNS_IFACE
:
529 self
.metadata
.append(x
)
532 self
.name
= x
.content
533 elif x
.name
== 'description':
534 self
.description
= x
.content
535 elif x
.name
== 'summary':
536 self
.summary
= x
.content
537 elif x
.name
== 'feed-for':
538 feed_iface
= x
.getAttribute('interface')
540 raise InvalidInterface('Missing "interface" attribute in <feed-for>')
541 self
.feed_for
.add(feed_iface
)
542 # Bug report from a Debian/stable user that --feed gets the wrong value.
543 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
544 # in case it happens again.
545 debug("Is feed-for %s", feed_iface
)
546 elif x
.name
== 'feed':
547 feed_src
= x
.getAttribute('src')
549 raise InvalidInterface('Missing "src" attribute in <feed>')
550 if feed_src
.startswith('http:') or local_path
:
551 self
.feeds
.append(Feed(feed_src
, x
.getAttribute('arch'), False, langs
= x
.getAttribute('langs')))
553 raise InvalidInterface("Invalid feed URL '%s'" % feed_src
)
555 self
.metadata
.append(x
)
557 def process_group(group
, group_attrs
, base_depends
, base_bindings
):
558 for item
in group
.childNodes
:
559 if item
.uri
!= XMLNS_IFACE
: continue
561 if item
.name
not in ('group', 'implementation', 'package-implementation'):
564 depends
= base_depends
[:]
565 bindings
= base_bindings
[:]
567 item_attrs
= _merge_attrs(group_attrs
, item
)
569 # We've found a group or implementation. Scan for dependencies
570 # and bindings. Doing this here means that:
571 # - We can share the code for groups and implementations here.
572 # - The order doesn't matter, because these get processed first.
573 # A side-effect is that the document root cannot contain
575 for child
in item
.childNodes
:
576 if child
.uri
!= XMLNS_IFACE
: continue
577 if child
.name
== 'requires':
578 dep
= process_depends(child
)
580 elif child
.name
in binding_names
:
581 bindings
.append(process_binding(child
))
583 if item
.name
== 'group':
584 process_group(item
, item_attrs
, depends
, bindings
)
585 elif item
.name
== 'implementation':
586 process_impl(item
, item_attrs
, depends
, bindings
)
587 elif item
.name
== 'package-implementation':
588 process_native_impl(item
, item_attrs
, depends
)
592 def process_impl(item
, item_attrs
, depends
, bindings
):
593 id = item
.getAttribute('id')
595 raise InvalidInterface("Missing 'id' attribute on %s" % item
)
596 if local_dir
and (id.startswith('/') or id.startswith('.')):
597 impl
= self
._get
_impl
(os
.path
.abspath(os
.path
.join(local_dir
, id)))
600 raise InvalidInterface('Invalid "id"; form is "alg=value" (got "%s")' % id)
601 alg
, sha1
= id.split('=')
604 except Exception, ex
:
605 raise InvalidInterface('Bad SHA1 attribute: %s' % ex
)
606 impl
= self
._get
_impl
(id)
608 impl
.metadata
= item_attrs
610 version
= item_attrs
['version']
611 version_mod
= item_attrs
.get('version-modifier', None)
612 if version_mod
: version
+= version_mod
614 raise InvalidInterface("Missing version attribute")
615 impl
.version
= parse_version(version
)
617 item_main
= item_attrs
.get('main', None)
618 if item_main
and item_main
.startswith('/'):
619 raise InvalidInterface("'main' attribute must be relative, but '%s' starts with '/'!" %
621 impl
.main
= item_main
623 impl
.released
= item_attrs
.get('released', None)
624 impl
.langs
= item_attrs
.get('langs', None)
626 size
= item
.getAttribute('size')
628 impl
.size
= long(size
)
629 impl
.arch
= item_attrs
.get('arch', None)
631 stability
= stability_levels
[str(item_attrs
['stability'])]
633 stab
= str(item_attrs
['stability'])
634 if stab
!= stab
.lower():
635 raise InvalidInterface('Stability "%s" invalid - use lower case!' % item_attrs
.stability
)
636 raise InvalidInterface('Stability "%s" invalid' % item_attrs
['stability'])
637 if stability
>= preferred
:
638 raise InvalidInterface("Upstream can't set stability to preferred!")
639 impl
.upstream_stability
= stability
641 impl
.bindings
= bindings
642 impl
.requires
= depends
644 for elem
in item
.childNodes
:
645 if elem
.uri
!= XMLNS_IFACE
: continue
646 if elem
.name
== 'archive':
647 url
= elem
.getAttribute('href')
649 raise InvalidInterface("Missing href attribute on <archive>")
650 size
= elem
.getAttribute('size')
652 raise InvalidInterface("Missing size attribute on <archive>")
653 impl
.add_download_source(url
= url
, size
= long(size
),
654 extract
= elem
.getAttribute('extract'),
655 start_offset
= _get_long(elem
, 'start-offset'),
656 type = elem
.getAttribute('type'))
657 elif elem
.name
== 'recipe':
659 for recipe_step
in elem
.childNodes
:
660 if recipe_step
.uri
== XMLNS_IFACE
and recipe_step
.name
== 'archive':
661 url
= recipe_step
.getAttribute('href')
663 raise InvalidInterface("Missing href attribute on <archive>")
664 size
= recipe_step
.getAttribute('size')
666 raise InvalidInterface("Missing size attribute on <archive>")
667 recipe
.steps
.append(DownloadSource(None, url
= url
, size
= long(size
),
668 extract
= recipe_step
.getAttribute('extract'),
669 start_offset
= _get_long(recipe_step
, 'start-offset'),
670 type = recipe_step
.getAttribute('type')))
672 info("Unknown step '%s' in recipe; skipping recipe", recipe_step
.name
)
675 impl
.download_sources
.append(recipe
)
677 def process_native_impl(item
, item_attrs
, depends
):
678 package
= item_attrs
.get('package', None)
680 raise InvalidInterface("Missing 'package' attribute on %s" % item
)
683 assert id.startswith('package:')
684 impl
= self
._get
_impl
(id)
686 impl
.metadata
= item_attrs
688 item_main
= item_attrs
.get('main', None)
689 if item_main
and not item_main
.startswith('/'):
690 raise InvalidInterface("'main' attribute must be absolute, but '%s' doesn't start with '/'!" %
692 impl
.main
= item_main
693 impl
.upstream_stability
= packaged
694 impl
.requires
= depends
698 distro
.get_package_info(package
, factory
)
700 process_group(feed_element
,
701 {'stability': 'testing',
707 return self
.name
or '(' + os
.path
.basename(self
.url
) + ')'
710 return "<Feed %s>" % self
.url
712 def _get_impl(self
, id):
713 if id not in self
.implementations
:
714 if id.startswith('package:'):
715 impl
= DistributionImplementation(self
, id)
717 impl
= ZeroInstallImplementation(self
, id)
718 self
.implementations
[id] = impl
719 return self
.implementations
[id]
721 def set_stability_policy(self
, new
):
722 assert new
is None or isinstance(new
, Stability
)
723 self
.stability_policy
= new
725 def get_feed(self
, url
):
731 def add_metadata(self
, elem
):
732 self
.metadata
.append(elem
)
734 def get_metadata(self
, uri
, name
):
735 """Return a list of interface metadata elements with this name and namespace URI."""
736 return [m
for m
in self
.metadata
if m
.name
== name
and m
.uri
== uri
]
738 class DummyFeed(object):
741 implementations
= property(lambda self
: {})
742 feeds
= property(lambda self
: [])
743 summary
= property(lambda self
: '-')
744 description
= property(lambda self
: '')
745 def get_name(self
): return self
.name
746 def get_feed(self
, url
): return None
747 def get_metadata(self
, uri
, name
): return []
748 _dummy_feed
= DummyFeed()
751 """Convert each %20 to a space, etc.
753 uri
= uri
.replace('#', '/')
754 if '%' not in uri
: return uri
755 return re
.sub('%[0-9a-fA-F][0-9a-fA-F]',
756 lambda match
: chr(int(match
.group(0)[1:], 16)),
760 """Convert each space to %20, etc
762 return re
.sub('[^-_.a-zA-Z0-9]',
763 lambda match
: '%%%02x' % ord(match
.group(0)),
766 def _pretty_escape(uri
):
767 """Convert each space to %20, etc
768 : is preserved and / becomes #. This makes for nicer strings,
769 and may replace L{escape} everywhere in future.
771 return re
.sub('[^-_.a-zA-Z0-9:/]',
772 lambda match
: '%%%02x' % ord(match
.group(0)),
773 uri
.encode('utf-8')).replace('/', '#')
775 def canonical_iface_uri(uri
):
776 """If uri is a relative path, convert to an absolute one.
777 Otherwise, return it unmodified.
779 @raise SafeException: if uri isn't valid
781 if uri
.startswith('http:'):
784 iface_uri
= os
.path
.realpath(uri
)
785 if os
.path
.isfile(iface_uri
):
787 raise SafeException("Bad interface name '%s'.\n"
788 "(doesn't start with 'http:', and "
789 "doesn't exist as a local file '%s' either)" %
792 _version_mod_to_value
= {
800 _version_value_to_mod
= {}
801 for x
in _version_mod_to_value
: _version_value_to_mod
[_version_mod_to_value
[x
]] = x
804 _version_re
= re
.compile('-([a-z]*)')
806 def parse_version(version_string
):
807 """Convert a version string to an internal representation.
808 The parsed format can be compared quickly using the standard Python functions.
809 - Version := DottedList ("-" Mod DottedList?)*
810 - DottedList := (Integer ("." Integer)*)
811 @rtype: tuple (opaque)
812 @raise SafeException: if the string isn't a valid version
813 @since: 0.24 (moved from L{reader}, from where it is still available):"""
814 if version_string
is None: return None
815 parts
= _version_re
.split(version_string
)
817 del parts
[-1] # Ends with a modifier
821 raise SafeException("Empty version string!")
824 for x
in range(0, l
, 2):
827 parts
[x
] = map(int, parts
[x
].split('.'))
829 parts
[x
] = [] # (because ''.split('.') == [''], not [])
830 for x
in range(1, l
, 2):
831 parts
[x
] = _version_mod_to_value
[parts
[x
]]
833 except ValueError, ex
:
834 raise SafeException("Invalid version format in '%s': %s" % (version_string
, ex
))
836 raise SafeException("Invalid version modifier in '%s': %s" % (version_string
, ex
))
838 def format_version(version
):
839 """Format a parsed version for display. Undoes the effect of L{parse_version}.
840 @see: L{Implementation.get_version}
845 for x
in range(0, l
, 2):
846 version
[x
] = '.'.join(map(str, version
[x
]))
847 for x
in range(1, l
, 2):
848 version
[x
] = '-' + _version_value_to_mod
[version
[x
]]
849 if version
[-1] == '-': del version
[-1]
850 return ''.join(version
)