From d9a76e61e75f77fbacf6ee5525f64fe2ac37184f Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Sat, 27 Jun 2009 03:35:00 +0000 Subject: - Use the ``pkg_resources`` API to locate template filenames instead of dead-reckoning using the ``os.path`` module. --- repoze/bfg/path.py | 41 +++++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 18 deletions(-) (limited to 'repoze/bfg/path.py') diff --git a/repoze/bfg/path.py b/repoze/bfg/path.py index 6fee43791..d8e90f0ff 100644 --- a/repoze/bfg/path.py +++ b/repoze/bfg/path.py @@ -1,27 +1,32 @@ import os import sys +import pkg_resources -def caller_path(path, level=2, package_globals=None): # package_globals==testing +def caller_path(path, level=2): if not os.path.isabs(path): + module = caller_module(level+1) + prefix = package_path(module) + path = os.path.join(prefix, path) + return path - if package_globals is None: - package_globals = sys._getframe(level).f_globals - - if '__bfg_abspath__' in package_globals: - return os.path.join(package_globals['__bfg_abspath__'], path) +def caller_module(level=2): + module_globals = sys._getframe(level).f_globals + module_name = module_globals['__name__'] + module = sys.modules[module_name] + return module - # computing the abspath is actually kinda expensive so we - # memoize the result - package_name = package_globals['__name__'] - package = sys.modules[package_name] - prefix = package_path(package) +def package_path(package): + # computing the abspath is actually kinda expensive so we memoize + # the result + prefix = getattr(package, '__bfg_abspath__', None) + if prefix is None: + prefix = pkg_resources.resource_filename(package.__name__, '') + # pkg_resources doesn't care whether we feed it a package + # name or a module name within the package, the result + # will be the same: a directory name to the package itself try: - package_globals['__bfg_abspath__'] = prefix + package.__bfg_abspath__ = prefix except: + # this is only an optimization, ignore any error pass - path = os.path.join(prefix, path) - return path - -def package_path(package): - return os.path.abspath(os.path.dirname(package.__file__)) - + return prefix -- cgit v1.2.3