This class manages a list of search paths and helps to find and open application-bound resources (files). :param base: default value for :meth:`add_path` calls. :param opener: callable used to open resources. :param cachemode: controls which lookups are cached. One
| 3040 | |
| 3041 | |
| 3042 | class ResourceManager(object): |
| 3043 | """ This class manages a list of search paths and helps to find and open |
| 3044 | application-bound resources (files). |
| 3045 | |
| 3046 | :param base: default value for :meth:`add_path` calls. |
| 3047 | :param opener: callable used to open resources. |
| 3048 | :param cachemode: controls which lookups are cached. One of 'all', |
| 3049 | 'found' or 'none'. |
| 3050 | """ |
| 3051 | |
| 3052 | def __init__(self, base='./', opener=open, cachemode='all'): |
| 3053 | self.opener = opener |
| 3054 | self.base = base |
| 3055 | self.cachemode = cachemode |
| 3056 | |
| 3057 | #: A list of search paths. See :meth:`add_path` for details. |
| 3058 | self.path = [] |
| 3059 | #: A cache for resolved paths. ``res.cache.clear()`` clears the cache. |
| 3060 | self.cache = {} |
| 3061 | |
| 3062 | def add_path(self, path, base=None, index=None, create=False): |
| 3063 | """ Add a new path to the list of search paths. Return False if the |
| 3064 | path does not exist. |
| 3065 | |
| 3066 | :param path: The new search path. Relative paths are turned into |
| 3067 | an absolute and normalized form. If the path looks like a file |
| 3068 | (not ending in `/`), the filename is stripped off. |
| 3069 | :param base: Path used to absolutize relative search paths. |
| 3070 | Defaults to :attr:`base` which defaults to ``os.getcwd()``. |
| 3071 | :param index: Position within the list of search paths. Defaults |
| 3072 | to last index (appends to the list). |
| 3073 | |
| 3074 | The `base` parameter makes it easy to reference files installed |
| 3075 | along with a python module or package:: |
| 3076 | |
| 3077 | res.add_path('./resources/', __file__) |
| 3078 | """ |
| 3079 | base = os.path.abspath(os.path.dirname(base or self.base)) |
| 3080 | path = os.path.abspath(os.path.join(base, os.path.dirname(path))) |
| 3081 | path += os.sep |
| 3082 | if path in self.path: |
| 3083 | self.path.remove(path) |
| 3084 | if create and not os.path.isdir(path): |
| 3085 | os.makedirs(path) |
| 3086 | if index is None: |
| 3087 | self.path.append(path) |
| 3088 | else: |
| 3089 | self.path.insert(index, path) |
| 3090 | self.cache.clear() |
| 3091 | return os.path.exists(path) |
| 3092 | |
| 3093 | def __iter__(self): |
| 3094 | """ Iterate over all existing files in all registered paths. """ |
| 3095 | search = self.path[:] |
| 3096 | while search: |
| 3097 | path = search.pop() |
| 3098 | if not os.path.isdir(path): continue |
| 3099 | for name in os.listdir(path): |
no outgoing calls
no test coverage detected
searching dependent graphs…