Debian Codegraph @

envisage/resource/package_resource_protocol.py

raw
1 # (C) Copyright 2007-2025 Enthought, Inc., Austin, TX
2 # All rights reserved.
3 #
4 # This software is provided without warranty under the terms of the BSD
5 # license included in LICENSE.txt and may be redistributed only under
6 # the conditions described in the aforementioned license. The license
7 # is also available online at http://www.enthought.com/licenses/BSD.txt
8 #
9 # Thanks for using Enthought open source!
10 """ A resource protocol for package resources. """
11
12
13 # Standard library imports.
14 try:
15 from importlib.resources import files
16 except ImportError:
17 from importlib_resources import files
18
19 # Enthought library imports.
20 from traits.api import HasTraits, provides
21
22 # Local imports.
23 from .i_resource_protocol import IResourceProtocol
24 from .no_such_resource_error import NoSuchResourceError
25
26
27 @provides(IResourceProtocol)
28 class PackageResourceProtocol(HasTraits):
29 """A resource protocol for package resources.
30
31 This protocol uses 'importlib.resources' to find and access resources.
32
33 An address for this protocol is a string in the form::
34
35 'package/resource'
36
37 e.g::
38
39 'acme.ui.workbench/preferences.ini'
40 """
41
42 ###########################################################################
43 # 'IResourceProtocol' interface.
44 ###########################################################################
45
46 def file(self, address):
47 """Return a readable file-like object for the specified address."""
48
49 package, *resource_path = address.split("/")
50
51 if not package or not resource_path:
52 raise NoSuchResourceError(address)
53
54 try:
55 f = files(package).joinpath(*resource_path).open("rb")
56 except (
57 ModuleNotFoundError,
58 TypeError, # TypeError is raised if package is a module
59 FileNotFoundError,
60 IsADirectoryError,
61 PermissionError,
62 ):
63 raise NoSuchResourceError(address)
64
65 return f