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 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 # Note: user_stability shouldn't really be here
308 __slots__
= ['upstream_stability', 'user_stability', 'langs',
309 'requires', 'main', 'metadata', 'download_sources',
310 'id', 'feed', 'version', 'released', 'bindings']
312 def __init__(self
, feed
, id):
317 self
.user_stability
= None
318 self
.upstream_stability
= None
319 self
.metadata
= {} # [URI + " "] + localName -> value
323 self
.download_sources
= []
327 def get_stability(self
):
328 return self
.user_stability
or self
.upstream_stability
or testing
333 def __cmp__(self
, other
):
334 """Newer versions come first"""
335 return cmp(other
.version
, self
.version
)
337 def get_version(self
):
338 """Return the version as a string.
339 @see: L{format_version}
341 return format_version(self
.version
)
343 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
))
347 class DistributionImplementation(Implementation
):
348 """An implementation provided by the distribution. Information such as the version
349 comes from the package manager.
351 __slots__
= ['installed']
353 def __init__(self
, feed
, id):
354 assert id.startswith('package:')
355 Implementation
.__init
__(self
, feed
, id)
356 self
.installed
= True
358 class ZeroInstallImplementation(Implementation
):
359 """An implementation where all the information comes from Zero Install.
361 __slots__
= ['os', 'machine', 'upstream_stability', 'user_stability',
362 'size', 'requires', 'main', 'id']
364 def __init__(self
, feed
, id):
365 """id can be a local path (string starting with /) or a manifest hash (eg "sha1=XXX")"""
366 Implementation
.__init
__(self
, feed
, id)
372 dependencies
= property(lambda self
: dict([(x
.interface
, x
) for x
in self
.requires
373 if isinstance(x
, InterfaceDependency
)]))
375 def add_download_source(self
, url
, size
, extract
, start_offset
= 0, type = None):
376 """Add a download source."""
377 self
.download_sources
.append(DownloadSource(self
, url
, size
, extract
, start_offset
, type))
379 def set_arch(self
, arch
):
380 self
.os
, self
.machine
= _split_arch(arch
)
381 arch
= property(lambda self
: _join_arch(self
.os
, self
.machine
), set_arch
)
383 class Interface(object):
384 """An Interface represents some contract of behaviour.
385 @ivar uri: the URI for this interface.
386 @ivar stability_policy: user's configured policy.
387 Implementations at this level or higher are preferred.
388 Lower levels are used only if there is no other choice.
390 __slots__
= ['uri', 'stability_policy', '_main_feed', 'extra_feeds']
392 implementations
= property(lambda self
: self
._main
_feed
.implementations
)
393 name
= property(lambda self
: self
._main
_feed
.name
)
394 description
= property(lambda self
: self
._main
_feed
.description
)
395 summary
= property(lambda self
: self
._main
_feed
.summary
)
396 last_modified
= property(lambda self
: self
._main
_feed
.last_modified
)
397 feeds
= property(lambda self
: self
.extra_feeds
+ self
._main
_feed
.feeds
)
398 metadata
= property(lambda self
: self
._main
_feed
.metadata
)
400 last_checked
= property(lambda self
: self
._main
_feed
.last_checked
)
402 def __init__(self
, uri
):
404 if uri
.startswith('http:') or uri
.startswith('/'):
407 raise SafeException("Interface name '%s' doesn't start "
408 "with 'http:'" % uri
)
411 def _get_feed_for(self
):
413 for key
in self
._main
_feed
.feed_for
:
416 feed_for
= property(_get_feed_for
) # Deprecated (used by 0publish)
419 self
.extra_feeds
= []
420 self
._main
_feed
= _dummy_feed
421 self
.stability_policy
= None
424 if self
._main
_feed
is not _dummy_feed
:
425 return self
._main
_feed
.get_name()
426 return '(' + os
.path
.basename(self
.uri
) + ')'
429 return "<Interface %s>" % self
.uri
431 def set_stability_policy(self
, new
):
432 assert new
is None or isinstance(new
, Stability
)
433 self
.stability_policy
= new
435 def get_feed(self
, url
):
436 for x
in self
.extra_feeds
:
439 return self
._main
_feed
.get_feed(url
)
441 def get_metadata(self
, uri
, name
):
442 return self
._main
_feed
.get_metadata(uri
, name
)
444 def _merge_attrs(attrs
, item
):
445 """Add each attribute of item to a copy of attrs and return the copy.
446 @type attrs: {str: str}
447 @type item: L{qdom.Element}
452 new
[str(a
)] = item
.attrs
[a
]
455 def _get_long(elem
, attr_name
):
456 val
= elem
.getAttribute(attr_name
)
460 except ValueError, ex
:
461 raise SafeException("Invalid value for integer attribute '%s': %s" % (attr_name
, val
))
464 class ZeroInstallFeed(object):
465 """A feed lists available implementations of an interface.
466 @ivar url: the URL for this feed
467 @ivar implementations: Implementations in this feed, indexed by ID
468 @type implementations: {str: L{Implementation}}
469 @ivar name: human-friendly name
470 @ivar summary: short textual description
471 @ivar description: long textual description
472 @ivar last_modified: timestamp on signature
473 @ivar last_checked: time feed was last successfully downloaded and updated
474 @ivar feeds: list of <feed> elements in this feed
475 @type feeds: [L{Feed}]
476 @ivar feed_for: interfaces for which this could be a feed
477 @type feed_for: set(str)
478 @ivar metadata: extra elements we didn't understand
480 # _main is deprecated
481 __slots__
= ['url', 'implementations', 'name', 'description', 'summary',
482 'last_checked', 'last_modified', 'feeds', 'feed_for', 'metadata']
484 def __init__(self
, feed_element
, local_path
= None, distro
= None):
485 """Create a feed object from a DOM.
486 @param feed_element: the root element of a feed file
487 @type feed_element: L{qdom.Element}
488 @param interface: temporary hack for restructuring. will go away.
489 @param local_name: the pathname of this local feed, or None for remote feeds
490 @param distro: used to resolve distribution package references
491 @type distro: L{distro.Distribution} or None"""
493 self
.implementations
= {}
496 self
.description
= ""
497 self
.last_modified
= None
499 self
.feed_for
= set()
501 self
.last_checked
= None
503 assert feed_element
.name
in ('interface', 'feed'), "Root element should be <interface>, not %s" % feed_element
504 assert feed_element
.uri
== XMLNS_IFACE
, "Wrong namespace on root element: %s" % feed_element
.uri
506 main
= feed_element
.getAttribute('main')
507 #if main: warn("Setting 'main' on the root element is deprecated. Put it on a <group> instead")
510 self
.url
= local_path
511 local_dir
= os
.path
.dirname(local_path
)
513 self
.url
= feed_element
.getAttribute('uri')
515 raise InvalidInterface("<interface> uri attribute missing")
516 local_dir
= None # Can't have relative paths
518 min_injector_version
= feed_element
.getAttribute('min-injector-version')
519 if min_injector_version
:
520 if parse_version(min_injector_version
) > parse_version(version
):
521 raise InvalidInterface("This feed requires version %s or later of "
522 "Zero Install, but I am only version %s. "
523 "You can get a newer version from http://0install.net" %
524 (min_injector_version
, version
))
526 for x
in feed_element
.childNodes
:
527 if x
.uri
!= XMLNS_IFACE
:
528 self
.metadata
.append(x
)
531 self
.name
= x
.content
532 elif x
.name
== 'description':
533 self
.description
= x
.content
534 elif x
.name
== 'summary':
535 self
.summary
= x
.content
536 elif x
.name
== 'feed-for':
537 feed_iface
= x
.getAttribute('interface')
539 raise InvalidInterface('Missing "interface" attribute in <feed-for>')
540 self
.feed_for
.add(feed_iface
)
541 # Bug report from a Debian/stable user that --feed gets the wrong value.
542 # Can't reproduce (even in a Debian/stable chroot), but add some logging here
543 # in case it happens again.
544 debug("Is feed-for %s", feed_iface
)
545 elif x
.name
== 'feed':
546 feed_src
= x
.getAttribute('src')
548 raise InvalidInterface('Missing "src" attribute in <feed>')
549 if feed_src
.startswith('http:') or local_path
:
550 self
.feeds
.append(Feed(feed_src
, x
.getAttribute('arch'), False, langs
= x
.getAttribute('langs')))
552 raise InvalidInterface("Invalid feed URL '%s'" % feed_src
)
554 self
.metadata
.append(x
)
557 raise InvalidInterface("Missing <name> in feed")
559 raise InvalidInterface("Missing <summary> in feed")
561 def process_group(group
, group_attrs
, base_depends
, base_bindings
):
562 for item
in group
.childNodes
:
563 if item
.uri
!= XMLNS_IFACE
: continue
565 if item
.name
not in ('group', 'implementation', 'package-implementation'):
568 depends
= base_depends
[:]
569 bindings
= base_bindings
[:]
571 item_attrs
= _merge_attrs(group_attrs
, item
)
573 # We've found a group or implementation. Scan for dependencies
574 # and bindings. Doing this here means that:
575 # - We can share the code for groups and implementations here.
576 # - The order doesn't matter, because these get processed first.
577 # A side-effect is that the document root cannot contain
579 for child
in item
.childNodes
:
580 if child
.uri
!= XMLNS_IFACE
: continue
581 if child
.name
== 'requires':
582 dep
= process_depends(child
)
584 elif child
.name
in binding_names
:
585 bindings
.append(process_binding(child
))
587 if item
.name
== 'group':
588 process_group(item
, item_attrs
, depends
, bindings
)
589 elif item
.name
== 'implementation':
590 process_impl(item
, item_attrs
, depends
, bindings
)
591 elif item
.name
== 'package-implementation':
592 process_native_impl(item
, item_attrs
, depends
)
596 def process_impl(item
, item_attrs
, depends
, bindings
):
597 id = item
.getAttribute('id')
599 raise InvalidInterface("Missing 'id' attribute on %s" % item
)
600 if local_dir
and (id.startswith('/') or id.startswith('.')):
601 impl
= self
._get
_impl
(os
.path
.abspath(os
.path
.join(local_dir
, id)))
604 raise InvalidInterface('Invalid "id"; form is "alg=value" (got "%s")' % id)
605 alg
, sha1
= id.split('=')
608 except Exception, ex
:
609 raise InvalidInterface('Bad SHA1 attribute: %s' % ex
)
610 impl
= self
._get
_impl
(id)
612 impl
.metadata
= item_attrs
614 version
= item_attrs
['version']
615 version_mod
= item_attrs
.get('version-modifier', None)
616 if version_mod
: version
+= version_mod
618 raise InvalidInterface("Missing version attribute")
619 impl
.version
= parse_version(version
)
621 item_main
= item_attrs
.get('main', None)
622 if item_main
and item_main
.startswith('/'):
623 raise InvalidInterface("'main' attribute must be relative, but '%s' starts with '/'!" %
625 impl
.main
= item_main
627 impl
.released
= item_attrs
.get('released', None)
628 impl
.langs
= item_attrs
.get('langs', None)
630 size
= item
.getAttribute('size')
632 impl
.size
= long(size
)
633 impl
.arch
= item_attrs
.get('arch', None)
635 stability
= stability_levels
[str(item_attrs
['stability'])]
637 stab
= str(item_attrs
['stability'])
638 if stab
!= stab
.lower():
639 raise InvalidInterface('Stability "%s" invalid - use lower case!' % item_attrs
.stability
)
640 raise InvalidInterface('Stability "%s" invalid' % item_attrs
['stability'])
641 if stability
>= preferred
:
642 raise InvalidInterface("Upstream can't set stability to preferred!")
643 impl
.upstream_stability
= stability
645 impl
.bindings
= bindings
646 impl
.requires
= depends
648 for elem
in item
.childNodes
:
649 if elem
.uri
!= XMLNS_IFACE
: continue
650 if elem
.name
== 'archive':
651 url
= elem
.getAttribute('href')
653 raise InvalidInterface("Missing href attribute on <archive>")
654 size
= elem
.getAttribute('size')
656 raise InvalidInterface("Missing size attribute on <archive>")
657 impl
.add_download_source(url
= url
, size
= long(size
),
658 extract
= elem
.getAttribute('extract'),
659 start_offset
= _get_long(elem
, 'start-offset'),
660 type = elem
.getAttribute('type'))
661 elif elem
.name
== 'recipe':
663 for recipe_step
in elem
.childNodes
:
664 if recipe_step
.uri
== XMLNS_IFACE
and recipe_step
.name
== 'archive':
665 url
= recipe_step
.getAttribute('href')
667 raise InvalidInterface("Missing href attribute on <archive>")
668 size
= recipe_step
.getAttribute('size')
670 raise InvalidInterface("Missing size attribute on <archive>")
671 recipe
.steps
.append(DownloadSource(None, url
= url
, size
= long(size
),
672 extract
= recipe_step
.getAttribute('extract'),
673 start_offset
= _get_long(recipe_step
, 'start-offset'),
674 type = recipe_step
.getAttribute('type')))
676 info("Unknown step '%s' in recipe; skipping recipe", recipe_step
.name
)
679 impl
.download_sources
.append(recipe
)
681 def process_native_impl(item
, item_attrs
, depends
):
682 package
= item_attrs
.get('package', None)
684 raise InvalidInterface("Missing 'package' attribute on %s" % item
)
687 assert id.startswith('package:')
688 impl
= self
._get
_impl
(id)
690 impl
.metadata
= item_attrs
692 item_main
= item_attrs
.get('main', None)
693 if item_main
and not item_main
.startswith('/'):
694 raise InvalidInterface("'main' attribute must be absolute, but '%s' doesn't start with '/'!" %
696 impl
.main
= item_main
697 impl
.upstream_stability
= packaged
698 impl
.requires
= depends
702 distro
.get_package_info(package
, factory
)
704 process_group(feed_element
,
705 {'stability': 'testing',
711 return self
.name
or '(' + os
.path
.basename(self
.url
) + ')'
714 return "<Feed %s>" % self
.url
716 def _get_impl(self
, id):
717 if id not in self
.implementations
:
718 if id.startswith('package:'):
719 impl
= DistributionImplementation(self
, id)
721 impl
= ZeroInstallImplementation(self
, id)
722 self
.implementations
[id] = impl
723 return self
.implementations
[id]
725 def set_stability_policy(self
, new
):
726 assert new
is None or isinstance(new
, Stability
)
727 self
.stability_policy
= new
729 def get_feed(self
, url
):
735 def add_metadata(self
, elem
):
736 self
.metadata
.append(elem
)
738 def get_metadata(self
, uri
, name
):
739 """Return a list of interface metadata elements with this name and namespace URI."""
740 return [m
for m
in self
.metadata
if m
.name
== name
and m
.uri
== uri
]
742 class DummyFeed(object):
745 last_checked
= property(lambda self
: None)
746 implementations
= property(lambda self
: {})
747 feeds
= property(lambda self
: [])
748 summary
= property(lambda self
: '-')
749 description
= property(lambda self
: '')
750 def get_name(self
): return self
.name
751 def get_feed(self
, url
): return None
752 def get_metadata(self
, uri
, name
): return []
753 _dummy_feed
= DummyFeed()
756 """Convert each %20 to a space, etc.
758 uri
= uri
.replace('#', '/')
759 if '%' not in uri
: return uri
760 return re
.sub('%[0-9a-fA-F][0-9a-fA-F]',
761 lambda match
: chr(int(match
.group(0)[1:], 16)),
765 """Convert each space to %20, etc
767 return re
.sub('[^-_.a-zA-Z0-9]',
768 lambda match
: '%%%02x' % ord(match
.group(0)),
771 def _pretty_escape(uri
):
772 """Convert each space to %20, etc
773 : is preserved and / becomes #. This makes for nicer strings,
774 and may replace L{escape} everywhere in future.
776 return re
.sub('[^-_.a-zA-Z0-9:/]',
777 lambda match
: '%%%02x' % ord(match
.group(0)),
778 uri
.encode('utf-8')).replace('/', '#')
780 def canonical_iface_uri(uri
):
781 """If uri is a relative path, convert to an absolute one.
782 Otherwise, return it unmodified.
784 @raise SafeException: if uri isn't valid
786 if uri
.startswith('http:'):
789 iface_uri
= os
.path
.realpath(uri
)
790 if os
.path
.isfile(iface_uri
):
792 raise SafeException("Bad interface name '%s'.\n"
793 "(doesn't start with 'http:', and "
794 "doesn't exist as a local file '%s' either)" %
797 _version_mod_to_value
= {
805 _version_value_to_mod
= {}
806 for x
in _version_mod_to_value
: _version_value_to_mod
[_version_mod_to_value
[x
]] = x
809 _version_re
= re
.compile('-([a-z]*)')
811 def parse_version(version_string
):
812 """Convert a version string to an internal representation.
813 The parsed format can be compared quickly using the standard Python functions.
814 - Version := DottedList ("-" Mod DottedList?)*
815 - DottedList := (Integer ("." Integer)*)
816 @rtype: tuple (opaque)
817 @raise SafeException: if the string isn't a valid version
818 @since: 0.24 (moved from L{reader}, from where it is still available):"""
819 if version_string
is None: return None
820 parts
= _version_re
.split(version_string
)
822 del parts
[-1] # Ends with a modifier
826 raise SafeException("Empty version string!")
829 for x
in range(0, l
, 2):
832 parts
[x
] = map(int, parts
[x
].split('.'))
834 parts
[x
] = [] # (because ''.split('.') == [''], not [])
835 for x
in range(1, l
, 2):
836 parts
[x
] = _version_mod_to_value
[parts
[x
]]
838 except ValueError, ex
:
839 raise SafeException("Invalid version format in '%s': %s" % (version_string
, ex
))
841 raise SafeException("Invalid version modifier in '%s': %s" % (version_string
, ex
))
843 def format_version(version
):
844 """Format a parsed version for display. Undoes the effect of L{parse_version}.
845 @see: L{Implementation.get_version}
850 for x
in range(0, l
, 2):
851 version
[x
] = '.'.join(map(str, version
[x
]))
852 for x
in range(1, l
, 2):
853 version
[x
] = '-' + _version_value_to_mod
[version
[x
]]
854 if version
[-1] == '-': del version
[-1]
855 return ''.join(version
)