[Zope3-checkins] SVN: Zope3/branches/zipimport-support/src/zope/
separate the resource-reference aspects of the ZIP-based
package support from
Fred L. Drake, Jr.
fdrake at gmail.com
Tue Nov 8 20:53:34 EST 2005
Log message for revision 39995:
separate the resource-reference aspects of the ZIP-based package support from
the use of that in zope.configuration; many packages will need to be able
to use such references, and will not want to know about the configuration
package
Changed:
U Zope3/branches/zipimport-support/src/zope/configuration/config.py
D Zope3/branches/zipimport-support/src/zope/configuration/path.py
D Zope3/branches/zipimport-support/src/zope/configuration/path.txt
A Zope3/branches/zipimport-support/src/zope/configuration/tests/resources.txt
U Zope3/branches/zipimport-support/src/zope/configuration/tests/test_config.py
D Zope3/branches/zipimport-support/src/zope/configuration/tests/zippitysample.zip
D Zope3/branches/zipimport-support/src/zope/configuration/tests/zipsource/
U Zope3/branches/zipimport-support/src/zope/configuration/xmlconfig.py
A Zope3/branches/zipimport-support/src/zope/resource/
A Zope3/branches/zipimport-support/src/zope/resource/README.txt
A Zope3/branches/zipimport-support/src/zope/resource/__init__.py
A Zope3/branches/zipimport-support/src/zope/resource/interfaces.py
A Zope3/branches/zipimport-support/src/zope/resource/reference.py
A Zope3/branches/zipimport-support/src/zope/resource/tests.py
A Zope3/branches/zipimport-support/src/zope/resource/zippitysample.zip
A Zope3/branches/zipimport-support/src/zope/resource/zipsource/
-=-
Modified: Zope3/branches/zipimport-support/src/zope/configuration/config.py
===================================================================
--- Zope3/branches/zipimport-support/src/zope/configuration/config.py 2005-11-08 22:57:51 UTC (rev 39994)
+++ Zope3/branches/zipimport-support/src/zope/configuration/config.py 2005-11-09 01:53:33 UTC (rev 39995)
@@ -26,6 +26,7 @@
from keyword import iskeyword
import zope.deprecation
+import zope.resource
from zope.configuration.exceptions import ConfigurationError
from zope.configuration.interfaces import IConfigurationContext
from zope.configuration.interfaces import IGroupingContext
@@ -34,7 +35,6 @@
from zope.interface.interfaces import IInterface
from zope.schema.interfaces import WrongType
from zope.configuration import fields
-from zope.configuration.path import newReference
zopens = 'http://namespaces.zope.org/zope'
@@ -250,7 +250,7 @@
package = getattr(self, 'package', None)
else:
package = self.package
- return newReference(filename, package, basepath)
+ return zope.resource.new(filename, package, basepath)
def checkDuplicate(self, filename):
"""Check for duplicate imports of the same file.
Deleted: Zope3/branches/zipimport-support/src/zope/configuration/path.py
===================================================================
--- Zope3/branches/zipimport-support/src/zope/configuration/path.py 2005-11-08 22:57:51 UTC (rev 39994)
+++ Zope3/branches/zipimport-support/src/zope/configuration/path.py 2005-11-09 01:53:33 UTC (rev 39995)
@@ -1,121 +0,0 @@
-"""Path reference to package-relative resources.
-"""
-__docformat__ = "reStructuredText"
-
-import errno
-import os
-import StringIO
-
-import zope.interface
-
-try:
- import pkg_resources
-except ImportError:
- pkg_resources = None
-
-
-class IResourceReference(zope.interface.Interface):
-
- def open(mode="rb"):
- """Open the referenced resource, returning a file-like object.
-
- Only 'read' modes are supported.
-
- """
-
-
-def newReference(path, package=None, basepath=None):
-
- if os.path.isabs(path):
- return PathReference(path)
-
- # Got a relative path, combine with base path.
- # If we have no basepath, compute the base path from the package
- # path.
-
- if not basepath:
- if package is None:
- basepath = os.getcwd()
- else:
- basepath = os.path.dirname(package.__file__)
-
- p = os.path.join(basepath, path)
- p = os.path.normpath(p)
- p = os.path.abspath(p)
-
- if package:
- return PackagePathReference(p, package, path)
- else:
- return PathReference(p)
-
-
-class PathReference(str):
-
- zope.interface.implements(IResourceReference)
-
- def __add__(self, other):
- path = str(self) + other
- return self.__class__(path)
-
- def open(self, mode="rb"):
- return open(self, mode)
-
-
-class PackagePathReference(str):
-
- zope.interface.implements(IResourceReference)
-
- def __new__(cls, value, package, relpath):
- assert package
- self = str.__new__(cls, value)
- self._package = package
- self._relpath = relpath
- return self
-
- def __add__(self, other):
- value = str(self) + other
- relpath = self._relpath + other
- return self.__class__(value, self._package, relpath)
-
- def open_pkg_resources(self, mode="rb"):
- try:
- data = pkg_resources.resource_string(
- self._package.__name__, self._relpath)
- except IOError, e:
- if len(e.args) == 1:
- # zipimport raises IOError w/ insufficient arguments
- raise IOError(errno.ENOENT, "file not found", self)
- else:
- raise
- f = StringIO.StringIO(data)
- f.name = self
- f.mode = mode
- return f
-
- def open_path_or_loader(self, mode="rb"):
- try:
- loader = self._package.__loader__
- except AttributeError:
- for dir in self._package.__path__:
- filename = os.path.join(dir, self._relpath)
- if os.path.exists(filename):
- break
- return open(filename, mode)
- else:
- dir = os.path.dirname(self._package.__file__)
- filename = os.path.join(dir, self._relpath)
- return loader.get_data(self._package.__name__)
-
- if pkg_resources:
- open = open_pkg_resources
- else:
- open = open_path_or_loader
-
-
-def openResource(path, mode="rb"):
- if not mode.startswith("r"):
- raise ValueError("`mode` must be a read-only mode")
- if IResourceReference.providedBy(path):
- return path.open(mode)
- else:
- return open(path, mode)
Deleted: Zope3/branches/zipimport-support/src/zope/configuration/path.txt
===================================================================
--- Zope3/branches/zipimport-support/src/zope/configuration/path.txt 2005-11-08 22:57:51 UTC (rev 39994)
+++ Zope3/branches/zipimport-support/src/zope/configuration/path.txt 2005-11-09 01:53:33 UTC (rev 39995)
@@ -1,159 +0,0 @@
-====================================
-Package-relative resource references
-====================================
-
-The `zope.configuration.path` module provides a way to refer to and
-open a file using a package-relative path. This is especially useful
-for packages imported from ZIP files (including eggs). Such files are
-considered resources, and may only be opened in read-only mode.
-
-Resource references have a dual personality: They are both strings
-and objects with interesting non-string methods. The string behavior
-is intended to help support compatibility for code that was written
-before this API existed, while new code can use the extended API for
-more flexibility.
-
-There are two functions which are used::
-
- >>> from zope.configuration.path import newReference, openResource
-
-`newReference()` is used to construct a new path reference, and
-`openResource()` is used to open the resource as a file-like object.
-
-`newReference()` takes three arguments: a path, a package, and a base
-path. Only the first is required; passing `None` for the `package`
-and `basepath` arguments is equivalent to omitting them.
-
-The idea of the resource references is that they can carry along
-additional information that allows them to retain package-relative
-information, so they are most interesting when the `package` argument
-to the constructor is non-`None`. Let's take a look at what this
-provides::
-
- >>> import os
- >>> import zope.configuration
-
- >>> ref = newReference("path.txt", package=zope.configuration)
-
-If we examine the reference as a string, we get a path that points
-into the package::
-
- >>> directory = os.path.dirname(zope.configuration.__file__)
- >>> ref == os.path.join(directory, "path.txt")
- True
-
-The resource can be opened using the `openResource()` function (which
-also accepts simple strings)::
-
- >>> f = openResource(ref)
- >>> f.readline()
- '====================================\n'
- >>> f.close()
-
-While this looks little different from using a simple string to refer
-to the resource file, it provides more functionality if the resource
-being referenced is part of a package contained in a ZIP archive.
-Let's add a convenient ZIP file containing a Python package to the
-module search path::
-
- >>> import sys
-
- >>> here = os.path.normpath(os.path.dirname(__file__))
- >>> zipfile = os.path.join(here, "tests", "zippitysample.zip")
- >>> sys.path.append(zipfile)
-
-We can now import the package contained in the zipfile and load
-resources from it::
-
- >>> import zippity.sample
- >>> ref = newReference("configure.zcml", package=zippity.sample)
-
- >>> f = openResource(ref)
- >>> f.readline()
- '<configure\n'
- >>> f.close()
-
-Note that only read modes are supported::
-
- >>> openResource(ref, "w")
- Traceback (most recent call last):
- ...
- ValueError: `mode` must be a read-only mode
-
- >>> openResource(ref, "w+")
- Traceback (most recent call last):
- ...
- ValueError: `mode` must be a read-only mode
-
- >>> openResource(ref, "a")
- Traceback (most recent call last):
- ...
- ValueError: `mode` must be a read-only mode
-
- >>> openResource(ref, "a+")
- Traceback (most recent call last):
- ...
- ValueError: `mode` must be a read-only mode
-
-
-Use in ZCML
------------
-
-The ZCML loading machinery uses these functions to deal with
-references to files that should be loaded. This allows including ZCML
-files from ZIP archives using <include/> directives.
-
-Our example ZIP file includes an example ZCML file; let's see how we
-can load it using <include/>::
-
- >>> from StringIO import StringIO
- >>> from zope.configuration import config, xmlconfig
-
- >>> context = config.ConfigurationMachine()
- >>> xmlconfig.registerCommonDirectives(context)
-
- >>> f = StringIO('<include package="zippity.sample"/>')
- >>> xmlconfig.processxmlfile(f, context, testing=True)
- >>> f.close()
-
-We can now check that the "feature" provided by our sample
-configuration has been defined::
-
- >>> context.hasFeature("sample")
- True
-
-We can also include one ZCML file from another in the ZIP archive.
-We'll create a new context so the provided feature is no longer
-known::
-
- >>> context = config.ConfigurationMachine()
- >>> xmlconfig.registerCommonDirectives(context)
-
- >>> context.hasFeature("sample")
- False
-
-Loading an alternate configuration file that includes the first should
-cause the "sample" feature to be provided::
-
- >>> f = StringIO('<include package="zippity.sample" file="including.zcml"/>')
- >>> xmlconfig.processxmlfile(f, context, testing=True)
- >>> f.close()
-
- >>> context.hasFeature("sample")
- True
-
-One oddball feature of the ZCML machinery is that if a ZCML file being
-loaded doesn't exist, but a file of the same name with '.in' appended
-does, that will be loaded instead. In this example, the sample
-package provides a 'silliness.zcml.in', but we're going to request
-'silliness.zcml'::
-
- >>> context = config.ConfigurationMachine()
- >>> xmlconfig.registerCommonDirectives(context)
-
- >>> f = StringIO('<include package="zippity.sample" file="silliness.zcml"/>')
- >>> xmlconfig.processxmlfile(f, context, testing=True)
- >>> f.close()
-
- >>> context.hasFeature("silliness")
- True
Added: Zope3/branches/zipimport-support/src/zope/configuration/tests/resources.txt
===================================================================
--- Zope3/branches/zipimport-support/src/zope/configuration/tests/resources.txt 2005-11-08 22:57:51 UTC (rev 39994)
+++ Zope3/branches/zipimport-support/src/zope/configuration/tests/resources.txt 2005-11-09 01:53:33 UTC (rev 39995)
@@ -0,0 +1,67 @@
+===========================
+Resource references in ZCML
+===========================
+
+The ZCML loading machinery uses the `zope.resource` facilities to deal
+with references to files that should be loaded. This allows including
+ZCML files from ZIP archives using <include/> directives, and allows
+ZCML directives that have Path schema attributes as arguments to use
+the `zope.resource` facilities as well.
+
+We'll use the sample ZIP archive provided for the `zope.resource`
+tests::
+
+ >>> import os
+ >>> import sys
+ >>> import zope.resource
+
+ >>> directory = os.path.normpath(os.path.dirname(zope.resource.__file__))
+ >>> zipfile = os.path.join(directory, "zippitysample.zip")
+ >>> sys.path.append(zipfile)
+
+Our example ZIP file includes an example ZCML file; let's see how we
+can load it using <include/>::
+
+ >>> from StringIO import StringIO
+ >>> from zope.configuration import config, xmlconfig
+
+ >>> def zcml(text):
+ ... context = config.ConfigurationMachine()
+ ... xmlconfig.registerCommonDirectives(context)
+ ... f = StringIO(text)
+ ... xmlconfig.processxmlfile(f, context, testing=True)
+ ... f.close()
+ ... return context
+
+ >>> context = zcml('<include package="zippity.sample"/>')
+
+We can now check that the "feature" provided by our sample
+configuration has been defined::
+
+ >>> context.hasFeature("sample")
+ True
+
+We can also include one ZCML file from another in the ZIP archive.
+Loading an alternate configuration file that includes the first should
+cause the "sample" feature to be provided::
+
+ >>> context = zcml(
+ ... '<include package="zippity.sample" file="including.zcml"/>')
+
+ >>> context.hasFeature("sample")
+ True
+
+One oddball feature of the ZCML machinery is that if a ZCML file being
+loaded doesn't exist, but a file of the same name with '.in' appended
+does, that will be loaded instead. In this example, the sample
+package provides a 'silliness.zcml.in', but we're going to request
+'silliness.zcml'::
+
+ >>> context = config.ConfigurationMachine()
+ >>> xmlconfig.registerCommonDirectives(context)
+
+ >>> context = zcml(
+ ... '<include package="zippity.sample" file="silliness.zcml"/>')
+
+ >>> context.hasFeature("silliness")
+ True
Property changes on: Zope3/branches/zipimport-support/src/zope/configuration/tests/resources.txt
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:eol-style
+ native
Modified: Zope3/branches/zipimport-support/src/zope/configuration/tests/test_config.py
===================================================================
--- Zope3/branches/zipimport-support/src/zope/configuration/tests/test_config.py 2005-11-08 22:57:51 UTC (rev 39994)
+++ Zope3/branches/zipimport-support/src/zope/configuration/tests/test_config.py 2005-11-09 01:53:33 UTC (rev 39995)
@@ -276,11 +276,12 @@
def test_suite():
return unittest.TestSuite((
- DocFileSuite('../path.txt',
+ DocFileSuite('resources.txt',
setUp=sys_path_setUp, tearDown=sys_path_tearDown),
DocTestSuite('zope.configuration.fields'),
DocTestSuite('zope.configuration.config'),
DocTestSuite(),
))
-if __name__ == '__main__': unittest.main()
+if __name__ == '__main__':
+ unittest.main()
Deleted: Zope3/branches/zipimport-support/src/zope/configuration/tests/zippitysample.zip
===================================================================
(Binary files differ)
Modified: Zope3/branches/zipimport-support/src/zope/configuration/xmlconfig.py
===================================================================
--- Zope3/branches/zipimport-support/src/zope/configuration/xmlconfig.py 2005-11-08 22:57:51 UTC (rev 39994)
+++ Zope3/branches/zipimport-support/src/zope/configuration/xmlconfig.py 2005-11-09 01:53:33 UTC (rev 39995)
@@ -26,6 +26,7 @@
import sys
import logging
import zope.configuration.config as config
+import zope.resource
from glob import glob
from xml.sax import make_parser
@@ -34,7 +35,6 @@
from xml.sax import SAXParseException
from zope import schema
from zope.configuration.exceptions import ConfigurationError
-from zope.configuration.path import openResource
from zope.configuration.zopeconfigure import IZopeConfigure, ZopeConfigure
from zope.interface import Interface
@@ -392,13 +392,12 @@
"""
try:
- fp = openResource(filename)
+ fp = zope.resource.open(filename)
except IOError, e:
- code, msg = e
- if code == errno.ENOENT:
+ if e.errno == errno.ENOENT:
fn = filename + ".in"
try:
- fp = openResource(fn)
+ fp = zope.resource.open(fn)
except IOError:
raise e
else:
Copied: Zope3/branches/zipimport-support/src/zope/resource/README.txt (from rev 39988, Zope3/branches/zipimport-support/src/zope/configuration/path.txt)
===================================================================
--- Zope3/branches/zipimport-support/src/zope/configuration/path.txt 2005-11-08 22:55:56 UTC (rev 39988)
+++ Zope3/branches/zipimport-support/src/zope/resource/README.txt 2005-11-09 01:53:33 UTC (rev 39995)
@@ -0,0 +1,93 @@
+====================================
+Package-relative resource references
+====================================
+
+The `zope.configuration.path` module provides a way to refer to and
+open a file using a package-relative path. This is especially useful
+for packages imported from ZIP files (including eggs). Such files are
+considered resources, and may only be opened in read-only mode.
+
+Resource references have a dual personality: They are both strings
+and objects with interesting non-string methods. The string behavior
+is intended to help support compatibility for code that was written
+before this API existed, while new code can use the extended API for
+more flexibility.
+
+There are two interesting functions: `new()` is used to construct a
+new path reference, and `open()` is used to open the resource as a
+file-like object.
+
+`new()` takes three arguments: a path, a package, and a base path.
+Only the first is required; passing `None` for the `package` and
+`basepath` arguments is equivalent to omitting them.
+
+The idea of the resource references is that they can carry along
+additional information that allows them to retain package-relative
+information, so they are most interesting when the `package` argument
+to the constructor is non-`None`. Let's take a look at what this
+provides::
+
+ >>> import os
+ >>> import zope.resource
+
+ >>> ref = zope.resource.new("README.txt", package=zope.resource)
+
+If we examine the reference as a string, we get a path that points
+into the package::
+
+ >>> directory = os.path.dirname(zope.resource.__file__)
+ >>> ref == os.path.join(directory, "README.txt")
+ True
+
+The resource can be opened using the `open()` function (which
+also accepts simple strings)::
+
+ >>> f = zope.resource.open(ref)
+ >>> f.readline()
+ '====================================\n'
+ >>> f.close()
+
+While this looks little different from using a simple string to refer
+to the resource file, it provides more functionality if the resource
+being referenced is part of a package contained in a ZIP archive.
+Let's add a convenient ZIP file containing a Python package to the
+module search path::
+
+ >>> import sys
+
+ >>> here = os.path.normpath(os.path.dirname(__file__))
+ >>> zipfile = os.path.join(here, "zippitysample.zip")
+ >>> sys.path.append(zipfile)
+
+We can now import the package contained in the zipfile and load
+resources from it::
+
+ >>> import zippity.sample
+ >>> ref = zope.resource.new("configure.zcml", package=zippity.sample)
+
+ >>> f = zope.resource.open(ref)
+ >>> f.readline()
+ '<configure\n'
+ >>> f.close()
+
+Note that only read modes are supported::
+
+ >>> zope.resource.open(ref, "w")
+ Traceback (most recent call last):
+ ...
+ ValueError: `mode` must be a read-only mode
+
+ >>> zope.resource.open(ref, "w+")
+ Traceback (most recent call last):
+ ...
+ ValueError: `mode` must be a read-only mode
+
+ >>> zope.resource.open(ref, "a")
+ Traceback (most recent call last):
+ ...
+ ValueError: `mode` must be a read-only mode
+
+ >>> zope.resource.open(ref, "a+")
+ Traceback (most recent call last):
+ ...
+ ValueError: `mode` must be a read-only mode
Added: Zope3/branches/zipimport-support/src/zope/resource/__init__.py
===================================================================
--- Zope3/branches/zipimport-support/src/zope/resource/__init__.py 2005-11-08 22:57:51 UTC (rev 39994)
+++ Zope3/branches/zipimport-support/src/zope/resource/__init__.py 2005-11-09 01:53:33 UTC (rev 39995)
@@ -0,0 +1,21 @@
+##############################################################################
+#
+# Copyright (c) 2005 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Resource references.
+
+"""
+__docformat__ = "reStructuredText"
+
+
+from reference import newReference as new
+from reference import openResource as open
Property changes on: Zope3/branches/zipimport-support/src/zope/resource/__init__.py
___________________________________________________________________
Name: svn:mime-type
+ text/x-python
Name: svn:eol-style
+ native
Added: Zope3/branches/zipimport-support/src/zope/resource/interfaces.py
===================================================================
--- Zope3/branches/zipimport-support/src/zope/resource/interfaces.py 2005-11-08 22:57:51 UTC (rev 39994)
+++ Zope3/branches/zipimport-support/src/zope/resource/interfaces.py 2005-11-09 01:53:33 UTC (rev 39995)
@@ -0,0 +1,29 @@
+##############################################################################
+#
+# Copyright (c) 2001, 2002, 2003 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Interfaces for zope.resource.
+
+"""
+__docformat__ = "reStructuredText"
+
+import zope.interface
+
+
+class IResourceReference(zope.interface.Interface):
+
+ def open(mode="rb"):
+ """Open the referenced resource, returning a file-like object.
+
+ Only 'read' modes are supported.
+
+ """
Property changes on: Zope3/branches/zipimport-support/src/zope/resource/interfaces.py
___________________________________________________________________
Name: svn:mime-type
+ text/x-python
Name: svn:eol-style
+ native
Copied: Zope3/branches/zipimport-support/src/zope/resource/reference.py (from rev 39988, Zope3/branches/zipimport-support/src/zope/configuration/path.py)
===================================================================
--- Zope3/branches/zipimport-support/src/zope/configuration/path.py 2005-11-08 22:55:56 UTC (rev 39988)
+++ Zope3/branches/zipimport-support/src/zope/resource/reference.py 2005-11-09 01:53:33 UTC (rev 39995)
@@ -0,0 +1,127 @@
+##############################################################################
+#
+# Copyright (c) 2001, 2002, 2003 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""References to package-relative resources.
+
+"""
+__docformat__ = "reStructuredText"
+
+import errno
+import os
+import StringIO
+
+import zope.interface
+
+from zope.resource.interfaces import IResourceReference
+
+try:
+ import pkg_resources
+except ImportError:
+ pkg_resources = None
+
+
+def openResource(path, mode="rb"):
+ if not mode.startswith("r"):
+ raise ValueError("`mode` must be a read-only mode")
+ if IResourceReference.providedBy(path):
+ return path.open(mode)
+ else:
+ return open(path, mode)
+
+
+def newReference(path, package=None, basepath=None):
+
+ if os.path.isabs(path):
+ return PathReference(path)
+
+ # Got a relative path, combine with base path.
+ # If we have no basepath, compute the base path from the package
+ # path.
+
+ if not basepath:
+ if package is None:
+ basepath = os.getcwd()
+ else:
+ basepath = os.path.dirname(package.__file__)
+
+ p = os.path.join(basepath, path)
+ p = os.path.normpath(p)
+ p = os.path.abspath(p)
+
+ if package:
+ return PackagePathReference(p, package, path)
+ else:
+ return PathReference(p)
+
+
+class PathReference(str):
+
+ zope.interface.implements(IResourceReference)
+
+ def __add__(self, other):
+ path = str(self) + other
+ return self.__class__(path)
+
+ def open(self, mode="rb"):
+ return open(self, mode)
+
+
+class PackagePathReference(str):
+
+ zope.interface.implements(IResourceReference)
+
+ def __new__(cls, value, package, relpath):
+ assert package
+ self = str.__new__(cls, value)
+ self._package = package
+ self._relpath = relpath
+ return self
+
+ def __add__(self, other):
+ value = str(self) + other
+ relpath = self._relpath + other
+ return self.__class__(value, self._package, relpath)
+
+ def open_pkg_resources(self, mode="rb"):
+ try:
+ data = pkg_resources.resource_string(
+ self._package.__name__, self._relpath)
+ except IOError, e:
+ if len(e.args) == 1:
+ # zipimport raises IOError w/ insufficient arguments
+ raise IOError(errno.ENOENT, "file not found", self)
+ else:
+ raise
+ f = StringIO.StringIO(data)
+ f.name = self
+ f.mode = mode
+ return f
+
+ def open_path_or_loader(self, mode="rb"):
+ try:
+ loader = self._package.__loader__
+ except AttributeError:
+ for dir in self._package.__path__:
+ filename = os.path.join(dir, self._relpath)
+ if os.path.exists(filename):
+ break
+ return open(filename, mode)
+ else:
+ dir = os.path.dirname(self._package.__file__)
+ filename = os.path.join(dir, self._relpath)
+ return loader.get_data(self._package.__name__)
+
+ if pkg_resources:
+ open = open_pkg_resources
+ else:
+ open = open_path_or_loader
Added: Zope3/branches/zipimport-support/src/zope/resource/tests.py
===================================================================
--- Zope3/branches/zipimport-support/src/zope/resource/tests.py 2005-11-08 22:57:51 UTC (rev 39994)
+++ Zope3/branches/zipimport-support/src/zope/resource/tests.py 2005-11-09 01:53:33 UTC (rev 39995)
@@ -0,0 +1,33 @@
+##############################################################################
+#
+# Copyright (c) 2003 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Test resource machinery.
+
+"""
+__docformat__ = "reStructuredText"
+
+import sys
+
+from zope.testing import doctest
+
+
+def sys_path_setUp(self):
+ self.__old_path = sys.path[:]
+
+def sys_path_tearDown(self):
+ sys.path[:] = self.__old_path
+
+
+def test_suite():
+ return doctest.DocFileSuite(
+ "README.txt", setUp=sys_path_setUp, tearDown=sys_path_tearDown)
Property changes on: Zope3/branches/zipimport-support/src/zope/resource/tests.py
___________________________________________________________________
Name: svn:mime-type
+ text/x-python
Name: svn:eol-style
+ native
Copied: Zope3/branches/zipimport-support/src/zope/resource/zippitysample.zip (from rev 39988, Zope3/branches/zipimport-support/src/zope/configuration/tests/zippitysample.zip)
Copied: Zope3/branches/zipimport-support/src/zope/resource/zipsource (from rev 39988, Zope3/branches/zipimport-support/src/zope/configuration/tests/zipsource)
More information about the Zope3-Checkins
mailing list