imphook.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2005-2021, PyInstaller Development Team.
  3. #
  4. # Distributed under the terms of the GNU General Public License (version 2
  5. # or later) with exception for distributing the bootloader.
  6. #
  7. # The full license is in the file COPYING.txt, distributed with this software.
  8. #
  9. # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
  10. #-----------------------------------------------------------------------------
  11. """
  12. Code related to processing of import hooks.
  13. """
  14. import glob, sys, weakref
  15. import os.path
  16. from PyInstaller.exceptions import ImportErrorWhenRunningHook
  17. from PyInstaller import log as logging
  18. from PyInstaller.compat import expand_path, importlib_load_source
  19. from PyInstaller.depend.imphookapi import PostGraphAPI
  20. from PyInstaller.building.utils import format_binaries_and_datas
  21. logger = logging.getLogger(__name__)
  22. # Safety check: Hook module names need to be unique. Duplicate names might
  23. # occur if the cached PyuModuleGraph has an issue.
  24. HOOKS_MODULE_NAMES = set()
  25. class ModuleHookCache(dict):
  26. """
  27. Cache of lazily loadable hook script objects.
  28. This cache is implemented as a `dict` subclass mapping from the
  29. fully-qualified names of all modules with at least one hook script to lists
  30. of `ModuleHook` instances encapsulating these scripts. As a `dict` subclass,
  31. all cached module names and hook scripts are accessible via standard
  32. dictionary operations.
  33. Attributes
  34. ----------
  35. module_graph : ModuleGraph
  36. Current module graph.
  37. _hook_module_name_prefix : str
  38. String prefixing the names of all in-memory modules lazily loaded from
  39. cached hook scripts. See also the `hook_module_name_prefix` parameter
  40. passed to the `ModuleHook.__init__()` method.
  41. """
  42. _cache_id_next = 0
  43. """
  44. 0-based identifier unique to the next `ModuleHookCache` to be instantiated.
  45. This identifier is incremented on each instantiation of a new
  46. `ModuleHookCache` to isolate in-memory modules of lazily loaded hook scripts
  47. in that cache to the same cache-specific namespace, preventing edge-case
  48. collisions with existing in-memory modules in other caches.
  49. """
  50. def __init__(self, module_graph, hook_dirs):
  51. """
  52. Cache all hook scripts in the passed directories.
  53. **Order of caching is significant** with respect to hooks for the same
  54. module, as the values of this dictionary are lists. Hooks for the same
  55. module will be run in the order in which they are cached. Previously
  56. cached hooks are always preserved rather than overidden.
  57. By default, official hooks are cached _before_ user-defined hooks. For
  58. modules with both official and user-defined hooks, this implies that the
  59. former take priority over and hence will be loaded _before_ the latter.
  60. Parameters
  61. ----------
  62. module_graph : ModuleGraph
  63. Current module graph.
  64. hook_dirs : list
  65. List of the absolute or relative paths of all directories containing
  66. **hook scripts** (i.e., Python scripts with filenames matching
  67. `hook-{module_name}.py`, where `{module_name}` is the module hooked
  68. by that script) to be cached.
  69. """
  70. super(ModuleHookCache, self).__init__()
  71. # To avoid circular references and hence increased memory consumption,
  72. # a weak rather than strong reference is stored to the passed graph.
  73. # Since this graph is guaranteed to live longer than this cache, this is
  74. # guaranteed to be safe.
  75. self.module_graph = weakref.proxy(module_graph)
  76. # String unique to this cache prefixing the names of all in-memory
  77. # modules lazily loaded from cached hook scripts, privatized for safety.
  78. self._hook_module_name_prefix = '__PyInstaller_hooks_{}_'.format(
  79. ModuleHookCache._cache_id_next)
  80. ModuleHookCache._cache_id_next += 1
  81. # Cache all hook scripts in the passed directories.
  82. self._cache_hook_dirs(hook_dirs)
  83. def _cache_hook_dirs(self, hook_dirs):
  84. """
  85. Cache all hook scripts in the passed directories.
  86. Parameters
  87. ----------
  88. hook_dirs : list
  89. List of the absolute or relative paths of all directories containing
  90. hook scripts to be cached.
  91. """
  92. for hook_dir in hook_dirs:
  93. # Canonicalize this directory's path and validate its existence.
  94. hook_dir = os.path.abspath(expand_path(hook_dir))
  95. if not os.path.isdir(hook_dir):
  96. raise FileNotFoundError(
  97. 'Hook directory "{}" not found.'.format(hook_dir))
  98. # For each hook script in this directory...
  99. hook_filenames = glob.glob(os.path.join(hook_dir, 'hook-*.py'))
  100. for hook_filename in hook_filenames:
  101. # Fully-qualified name of this hook's corresponding module,
  102. # constructed by removing the "hook-" prefix and ".py" suffix.
  103. module_name = os.path.basename(hook_filename)[5:-3]
  104. if module_name in self:
  105. logger.warning("Several hooks defined for module %r. "
  106. "Please take care they do not conflict.",
  107. module_name)
  108. # Lazily loadable hook object.
  109. module_hook = ModuleHook(
  110. module_graph=self.module_graph,
  111. module_name=module_name,
  112. hook_filename=hook_filename,
  113. hook_module_name_prefix=self._hook_module_name_prefix,
  114. )
  115. # Add this hook to this module's list of hooks.
  116. module_hooks = self.setdefault(module_name, [])
  117. module_hooks.append(module_hook)
  118. def remove_modules(self, *module_names):
  119. """
  120. Remove the passed modules and all hook scripts cached for these modules
  121. from this cache.
  122. Parameters
  123. ----------
  124. module_names : list
  125. List of all fully-qualified module names to be removed.
  126. """
  127. for module_name in module_names:
  128. # Unload this module's hook script modules from memory. Since these
  129. # are top-level pure-Python modules cached only in the "sys.modules"
  130. # dictionary, popping these modules from this dictionary suffices
  131. # to garbage collect these modules.
  132. module_hooks = self.get(module_name, [])
  133. for module_hook in module_hooks:
  134. sys.modules.pop(module_hook.hook_module_name, None)
  135. # Remove this module and its hook script objects from this cache.
  136. self.pop(module_name, None)
  137. # Dictionary mapping the names of magic attributes required by the "ModuleHook"
  138. # class to 2-tuples "(default_type, sanitizer_func)", where:
  139. #
  140. # * "default_type" is the type to which that attribute will be initialized when
  141. # that hook is lazily loaded.
  142. # * "sanitizer_func" is the callable sanitizing the original value of that
  143. # attribute defined by that hook into a safer value consumable by "ModuleHook"
  144. # callers if any or "None" if the original value requires no sanitization.
  145. #
  146. # To avoid subtleties in the ModuleHook.__getattr__() method, this dictionary is
  147. # declared as a module rather than a class attribute. If declared as a class
  148. # attribute and then undefined (...for whatever reason), attempting to access
  149. # this attribute from that method would produce infinite recursion.
  150. _MAGIC_MODULE_HOOK_ATTRS = {
  151. # Collections in which order is insignificant. This includes:
  152. #
  153. # * "datas", sanitized from hook-style 2-tuple lists defined by hooks into
  154. # TOC-style 2-tuple sets consumable by "ModuleHook" callers.
  155. # * "binaries", sanitized in the same way.
  156. 'datas': (set, format_binaries_and_datas),
  157. 'binaries': (set, format_binaries_and_datas),
  158. 'excludedimports': (set, None),
  159. # Collections in which order is significant. This includes:
  160. #
  161. # * "hiddenimports", as order of importation is significant. On module
  162. # importation, hook scripts are loaded and hook functions declared by
  163. # these scripts are called. As these scripts and functions can have side
  164. # effects dependent on module importation order, module importation itself
  165. # can have side effects dependent on this order!
  166. 'hiddenimports': (list, None),
  167. }
  168. class ModuleHook(object):
  169. """
  170. Cached object encapsulating a lazy loadable hook script.
  171. This object exposes public attributes (e.g., `datas`) of the underlying hook
  172. script as attributes of the same name of this object. On the first access of
  173. any such attribute, this hook script is lazily loaded into an in-memory
  174. private module reused on subsequent accesses. These dynamic attributes are
  175. referred to as "magic." All other static attributes of this object (e.g.,
  176. `hook_module_name`) are referred to as "non-magic."
  177. Attributes (Magic)
  178. ----------
  179. datas : set
  180. Set of `TOC`-style 2-tuples `(target_file, source_file)` for all
  181. external non-executable files required by the module being hooked,
  182. converted from the `datas` list of hook-style 2-tuples
  183. `(source_dir_or_glob, target_dir)` defined by this hook script.
  184. binaries : set
  185. Set of `TOC`-style 2-tuples `(target_file, source_file)` for all
  186. external executable files required by the module being hooked, converted
  187. from the `binaries` list of hook-style 2-tuples
  188. `(source_dir_or_glob, target_dir)` defined by this hook script.
  189. excludedimports : set
  190. Set of the fully-qualified names of all modules imported by the module
  191. being hooked to be ignored rather than imported from that module,
  192. converted from the `excludedimports` list defined by this hook script.
  193. These modules will only be "locally" rather than "globally" ignored.
  194. These modules will remain importable from all modules other than the
  195. module being hooked.
  196. hiddenimports : set
  197. Set of the fully-qualified names of all modules imported by the module
  198. being hooked that are _not_ automatically detectable by PyInstaller
  199. (usually due to being dynamically imported in that module), converted
  200. from the `hiddenimports` list defined by this hook script.
  201. Attributes (Non-magic)
  202. ----------
  203. module_graph : ModuleGraph
  204. Current module graph.
  205. module_name : str
  206. Name of the module hooked by this hook script.
  207. hook_filename : str
  208. Absolute or relative path of this hook script.
  209. hook_module_name : str
  210. Name of the in-memory module of this hook script's interpreted contents.
  211. _hook_module : module
  212. In-memory module of this hook script's interpreted contents, lazily
  213. loaded on the first call to the `_load_hook_module()` method _or_ `None`
  214. if this method has yet to be accessed.
  215. """
  216. ## Magic
  217. def __init__(self, module_graph, module_name, hook_filename,
  218. hook_module_name_prefix):
  219. """
  220. Initialize this metadata.
  221. Parameters
  222. ----------
  223. module_graph : ModuleGraph
  224. Current module graph.
  225. module_name : str
  226. Name of the module hooked by this hook script.
  227. hook_filename : str
  228. Absolute or relative path of this hook script.
  229. hook_module_name_prefix : str
  230. String prefixing the name of the in-memory module for this hook
  231. script. To avoid namespace clashes with similar modules created by
  232. other `ModuleHook` objects in other `ModuleHookCache` containers,
  233. this string _must_ be unique to the `ModuleHookCache` container
  234. containing this `ModuleHook` object. If this string is non-unique,
  235. an existing in-memory module will be erroneously reused when lazily
  236. loading this hook script, thus erroneously resanitizing previously
  237. sanitized hook script attributes (e.g., `datas`) with the
  238. `format_binaries_and_datas()` helper.
  239. """
  240. # Note that the passed module graph is already a weak reference,
  241. # avoiding circular reference issues. See ModuleHookCache.__init__().
  242. # TODO: Add a failure message
  243. assert isinstance(module_graph, weakref.ProxyTypes)
  244. self.module_graph = module_graph
  245. self.module_name = module_name
  246. self.hook_filename = hook_filename
  247. # Name of the in-memory module fabricated to refer to this hook script.
  248. self.hook_module_name = (
  249. hook_module_name_prefix + self.module_name.replace('.', '_'))
  250. # Safety check, see above
  251. global HOOKS_MODULE_NAMES
  252. if self.hook_module_name in HOOKS_MODULE_NAMES:
  253. # When self._shallow is true, this class never loads the hook and
  254. # sets the attributes to empty values
  255. self._shallow = True
  256. else:
  257. self._shallow = False
  258. HOOKS_MODULE_NAMES.add(self.hook_module_name)
  259. # Attributes subsequently defined by the _load_hook_module() method.
  260. self._hook_module = None
  261. def __getattr__(self, attr_name):
  262. """
  263. Get the magic attribute with the passed name (e.g., `datas`) from this
  264. lazily loaded hook script if any _or_ raise `AttributeError` otherwise.
  265. This special method is called only for attributes _not_ already defined
  266. by this object. This includes undefined attributes and the first attempt
  267. to access magic attributes.
  268. This special method is _not_ called for subsequent attempts to access
  269. magic attributes. The first attempt to access magic attributes defines
  270. corresponding instance variables accessible via the `self.__dict__`
  271. instance dictionary (e.g., as `self.datas`) without calling this method.
  272. This approach also allows magic attributes to be deleted from this
  273. object _without_ defining the `__delattr__()` special method.
  274. See Also
  275. ----------
  276. Class docstring for supported magic attributes.
  277. """
  278. # If this is a magic attribute, initialize this attribute by lazy
  279. # loading this hook script and then return this attribute. To avoid
  280. # recursion, the superclass method rather than getattr() is called.
  281. if attr_name in _MAGIC_MODULE_HOOK_ATTRS:
  282. self._load_hook_module()
  283. return super(ModuleHook, self).__getattr__(attr_name)
  284. # Else, this is an undefined attribute. Raise an exception.
  285. else:
  286. raise AttributeError(attr_name)
  287. def __setattr__(self, attr_name, attr_value):
  288. """
  289. Set the attribute with the passed name to the passed value.
  290. If this is a magic attribute, this hook script will be lazily loaded
  291. before setting this attribute. Unlike `__getattr__()`, this special
  292. method is called to set _any_ attribute -- including magic, non-magic,
  293. and undefined attributes.
  294. See Also
  295. ----------
  296. Class docstring for supported magic attributes.
  297. """
  298. # If this is a magic attribute, initialize this attribute by lazy
  299. # loading this hook script before overwriting this attribute.
  300. if attr_name in _MAGIC_MODULE_HOOK_ATTRS:
  301. self._load_hook_module()
  302. # Set this attribute to the passed value. To avoid recursion, the
  303. # superclass method rather than setattr() is called.
  304. return super(ModuleHook, self).__setattr__(attr_name, attr_value)
  305. ## Loading
  306. def _load_hook_module(self):
  307. """
  308. Lazily load this hook script into an in-memory private module.
  309. This method (and, indeed, this class) preserves all attributes and
  310. functions defined by this hook script as is, ensuring sane behaviour in
  311. hook functions _not_ expecting unplanned external modification. Instead,
  312. this method copies public attributes defined by this hook script
  313. (e.g., `binaries`) into private attributes of this object, which the
  314. special `__getattr__()` and `__setattr__()` methods safely expose to
  315. external callers. For public attributes _not_ defined by this hook
  316. script, the corresponding private attributes will be assigned sane
  317. defaults. For some public attributes defined by this hook script, the
  318. corresponding private attributes will be transformed into objects more
  319. readily and safely consumed elsewhere by external callers.
  320. See Also
  321. ----------
  322. Class docstring for supported attributes.
  323. """
  324. # If this hook script module has already been loaded,
  325. # or we are _shallow, noop.
  326. if self._hook_module is not None or self._shallow:
  327. if self._shallow:
  328. self._hook_module = True # Not None
  329. # Inform the user
  330. logger.debug(
  331. 'Skipping module hook %r from %r because a hook for %s has'
  332. ' already been loaded.',
  333. *os.path.split(self.hook_filename)[::-1], self.module_name
  334. )
  335. # Set the default attributes to empty instances of the type.
  336. for attr_name, \
  337. (attr_type, _) in _MAGIC_MODULE_HOOK_ATTRS.items():
  338. super(ModuleHook, self).__setattr__(attr_name, attr_type())
  339. return
  340. # Load and execute the hook script. Even if mechanisms from the import
  341. # machinery are used, this does not import the hook as the module.
  342. head, tail = os.path.split(self.hook_filename)
  343. logger.info(
  344. 'Loading module hook %r from %r...', tail, head)
  345. try:
  346. self._hook_module = importlib_load_source(
  347. self.hook_module_name, self.hook_filename)
  348. except ImportError:
  349. logger.debug("Hook failed with:", exc_info=True)
  350. raise ImportErrorWhenRunningHook(
  351. self.hook_module_name, self.hook_filename)
  352. # Copy hook script attributes into magic attributes exposed as instance
  353. # variables of the current "ModuleHook" instance.
  354. for attr_name, (default_type, sanitizer_func) in (
  355. _MAGIC_MODULE_HOOK_ATTRS.items()):
  356. # Unsanitized value of this attribute.
  357. attr_value = getattr(self._hook_module, attr_name, None)
  358. # If this attribute is undefined, expose a sane default instead.
  359. if attr_value is None:
  360. attr_value = default_type()
  361. # Else if this attribute requires sanitization, do so.
  362. elif sanitizer_func is not None:
  363. attr_value = sanitizer_func(attr_value)
  364. # Else, expose the unsanitized value of this attribute.
  365. # Expose this attribute as an instance variable of the same name.
  366. setattr(self, attr_name, attr_value)
  367. ## Hooks
  368. def post_graph(self, analysis):
  369. """
  370. Call the **post-graph hook** (i.e., `hook()` function) defined by this
  371. hook script if any.
  372. Parameters
  373. ----------
  374. analysis: build_main.Analysis
  375. Analysis that calls the hook
  376. This method is intended to be called _after_ the module graph for this
  377. application is constructed.
  378. """
  379. # Lazily load this hook script into an in-memory module.
  380. self._load_hook_module()
  381. # Call this hook script's hook() function, which modifies attributes
  382. # accessed by subsequent methods and hence must be called first.
  383. self._process_hook_func(analysis)
  384. # Order is insignificant here.
  385. self._process_hidden_imports()
  386. self._process_excluded_imports()
  387. def _process_hook_func(self, analysis):
  388. """
  389. Call this hook's `hook()` function if defined.
  390. Parameters
  391. ----------
  392. analysis: build_main.Analysis
  393. Analysis that calls the hook
  394. """
  395. # If this hook script defines no hook() function, noop.
  396. if not hasattr(self._hook_module, 'hook'):
  397. return
  398. # Call this hook() function.
  399. hook_api = PostGraphAPI(
  400. module_name=self.module_name, module_graph=self.module_graph,
  401. analysis=analysis)
  402. try:
  403. self._hook_module.hook(hook_api)
  404. except ImportError:
  405. logger.debug("Hook failed with:", exc_info=True)
  406. raise ImportErrorWhenRunningHook(
  407. self.hook_module_name, self.hook_filename)
  408. # Update all magic attributes modified by the prior call.
  409. self.datas.update(set(hook_api._added_datas))
  410. self.binaries.update(set(hook_api._added_binaries))
  411. self.hiddenimports.extend(hook_api._added_imports)
  412. #FIXME: Deleted imports should be appended to
  413. #"self.excludedimports" rather than handled here. However, see the
  414. #_process_excluded_imports() FIXME below for a sensible alternative.
  415. for deleted_module_name in hook_api._deleted_imports:
  416. # Remove the graph link between the hooked module and item.
  417. # This removes the 'item' node from the graph if no other
  418. # links go to it (no other modules import it)
  419. self.module_graph.removeReference(
  420. hook_api.node, deleted_module_name)
  421. def _process_hidden_imports(self):
  422. """
  423. Add all imports listed in this hook script's `hiddenimports` attribute
  424. to the module graph as if directly imported by this hooked module.
  425. These imports are typically _not_ implicitly detectable by PyInstaller
  426. and hence must be explicitly defined by hook scripts.
  427. """
  428. # For each hidden import required by the module being hooked...
  429. for import_module_name in self.hiddenimports:
  430. try:
  431. # Graph node for this module. Do not implicitly create namespace
  432. # packages for non-existent packages.
  433. caller = self.module_graph.find_node(
  434. self.module_name, create_nspkg=False)
  435. # Manually import this hidden import from this module.
  436. self.module_graph.import_hook(import_module_name, caller)
  437. # If this hidden import is unimportable, print a non-fatal warning.
  438. # Hidden imports often become desynchronized from upstream packages
  439. # and hence are only "soft" recommendations.
  440. except ImportError:
  441. logger.warning('Hidden import "%s" not found!', import_module_name)
  442. #FIXME: This is pretty... intense. Attempting to cleanly "undo" prior module
  443. #graph operations is a recipe for subtle edge cases and difficult-to-debug
  444. #issues. It would be both safer and simpler to prevent these imports from
  445. #being added to the graph in the first place. To do so:
  446. #
  447. #* Remove the _process_excluded_imports() method below.
  448. #* Remove the PostGraphAPI.del_imports() method, which cannot reasonably be
  449. # supported by the following solution, appears to be currently broken, and
  450. # (in any case) is not called anywhere in the PyInstaller codebase.
  451. #* Override the ModuleGraph._safe_import_hook() superclass method with a new
  452. # PyiModuleGraph._safe_import_hook() subclass method resembling:
  453. #
  454. # def _safe_import_hook(
  455. # self, target_module_name, source_module, fromlist,
  456. # level=DEFAULT_IMPORT_LEVEL, attr=None):
  457. #
  458. # if source_module.identifier in self._module_hook_cache:
  459. # for module_hook in self._module_hook_cache[
  460. # source_module.identifier]:
  461. # if target_module_name in module_hook.excludedimports:
  462. # return []
  463. #
  464. # return super(PyiModuleGraph, self)._safe_import_hook(
  465. # target_module_name, source_module, fromlist,
  466. # level=level, attr=attr)
  467. def _process_excluded_imports(self):
  468. """
  469. 'excludedimports' is a list of Python module names that PyInstaller
  470. should not detect as dependency of this module name.
  471. So remove all import-edges from the current module (and it's
  472. submodules) to the given `excludedimports` (end their submodules).
  473. """
  474. def find_all_package_nodes(name):
  475. mods = [name]
  476. name += '.'
  477. for subnode in self.module_graph.nodes():
  478. if subnode.identifier.startswith(name):
  479. mods.append(subnode.identifier)
  480. return mods
  481. # If this hook excludes no imports, noop.
  482. if not self.excludedimports:
  483. return
  484. # Collect all submodules of this module.
  485. hooked_mods = find_all_package_nodes(self.module_name)
  486. # Collect all dependencies and their submodules
  487. # TODO: Optimize this by using a pattern and walking the graph
  488. # only once.
  489. for item in set(self.excludedimports):
  490. excluded_node = self.module_graph.find_node(item, create_nspkg=False)
  491. if excluded_node is None:
  492. logger.info("Import to be excluded not found: %r", item)
  493. continue
  494. imports_to_remove = set(find_all_package_nodes(item))
  495. # Remove references between module nodes, as though they would
  496. # not be imported from 'name'.
  497. # Note: Doing this in a nested loop is less efficient than
  498. # collecting all import to remove first, but log messages
  499. # are easier to understand since related to the "Excluding ..."
  500. # message above.
  501. for src in hooked_mods:
  502. # modules, this `src` does import
  503. references = set(
  504. node.identifier
  505. for node in self.module_graph.outgoing(src))
  506. # Remove all of these imports which are also in
  507. # "imports_to_remove".
  508. for dest in imports_to_remove & references:
  509. self.module_graph.removeReference(src, dest)
  510. logger.debug(
  511. "Excluding import of %s from module %s", dest, src)
  512. class AdditionalFilesCache(object):
  513. """
  514. Cache for storing what binaries and datas were pushed by what modules
  515. when import hooks were processed.
  516. """
  517. def __init__(self):
  518. self._binaries = {}
  519. self._datas = {}
  520. def add(self, modname, binaries, datas):
  521. self._binaries.setdefault(modname, [])
  522. self._binaries[modname].extend(binaries or [])
  523. self._datas.setdefault(modname, [])
  524. self._datas[modname].extend(datas or [])
  525. def __contains__(self, name):
  526. return name in self._binaries or name in self._datas
  527. def binaries(self, modname):
  528. """
  529. Return list of binaries for given module name.
  530. """
  531. return self._binaries[modname]
  532. def datas(self, modname):
  533. """
  534. Return list of datas for given module name.
  535. """
  536. return self._datas[modname]