imphook.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2005-2023, 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
  15. import os.path
  16. import sys
  17. import weakref
  18. import re
  19. from PyInstaller import log as logging
  20. from PyInstaller.building.utils import format_binaries_and_datas
  21. from PyInstaller.compat import importlib_load_source
  22. from PyInstaller.depend.imphookapi import PostGraphAPI
  23. from PyInstaller.exceptions import ImportErrorWhenRunningHook
  24. logger = logging.getLogger(__name__)
  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 fully-qualified names of all modules with at
  29. least one hook script to lists of `ModuleHook` instances encapsulating these scripts. As a `dict` subclass,
  30. all cached module names and hook scripts are accessible via standard dictionary operations.
  31. Attributes
  32. ----------
  33. module_graph : ModuleGraph
  34. Current module graph.
  35. _hook_module_name_prefix : str
  36. String prefixing the names of all in-memory modules lazily loaded from cached hook scripts. See also the
  37. `hook_module_name_prefix` parameter passed to the `ModuleHook.__init__()` method.
  38. """
  39. _cache_id_next = 0
  40. """
  41. 0-based identifier unique to the next `ModuleHookCache` to be instantiated.
  42. This identifier is incremented on each instantiation of a new `ModuleHookCache` to isolate in-memory modules of
  43. lazily loaded hook scripts in that cache to the same cache-specific namespace, preventing edge-case collisions
  44. with existing in-memory modules in other caches.
  45. """
  46. def __init__(self, module_graph, hook_dirs):
  47. """
  48. Cache all hook scripts in the passed directories.
  49. **Order of caching is significant** with respect to hooks for the same module, as the values of this
  50. dictionary are lists. Hooks for the same module will be run in the order in which they are cached. Previously
  51. cached hooks are always preserved rather than overridden.
  52. By default, official hooks are cached _before_ user-defined hooks. For modules with both official and
  53. user-defined hooks, this implies that the former take priority over and hence will be loaded _before_ the
  54. latter.
  55. Parameters
  56. ----------
  57. module_graph : ModuleGraph
  58. Current module graph.
  59. hook_dirs : list
  60. List of the absolute or relative paths of all directories containing **hook scripts** (i.e.,
  61. Python scripts with filenames matching `hook-{module_name}.py`, where `{module_name}` is the module
  62. hooked by that script) to be cached.
  63. """
  64. super().__init__()
  65. # To avoid circular references and hence increased memory consumption, a weak rather than strong reference is
  66. # stored to the passed graph. Since this graph is guaranteed to live longer than this cache,
  67. # this is guaranteed to be safe.
  68. self.module_graph = weakref.proxy(module_graph)
  69. # String unique to this cache prefixing the names of all in-memory modules lazily loaded from cached hook
  70. # scripts, privatized for safety.
  71. self._hook_module_name_prefix = '__PyInstaller_hooks_{}_'.format(ModuleHookCache._cache_id_next)
  72. ModuleHookCache._cache_id_next += 1
  73. # Cache all hook scripts in the passed directories.
  74. self._cache_hook_dirs(hook_dirs)
  75. def _cache_hook_dirs(self, hook_dirs):
  76. """
  77. Cache all hook scripts in the passed directories.
  78. Parameters
  79. ----------
  80. hook_dirs : list
  81. List of the absolute or relative paths of all directories containing hook scripts to be cached.
  82. """
  83. for hook_dir, default_priority in hook_dirs:
  84. # Canonicalize this directory's path and validate its existence.
  85. hook_dir = os.path.abspath(hook_dir)
  86. if not os.path.isdir(hook_dir):
  87. raise FileNotFoundError('Hook directory "{}" not found.'.format(hook_dir))
  88. # For each hook script in this directory...
  89. hook_filenames = glob.glob(os.path.join(hook_dir, 'hook-*.py'))
  90. for hook_filename in hook_filenames:
  91. # Fully-qualified name of this hook's corresponding module, constructed by removing the "hook-" prefix
  92. # and ".py" suffix.
  93. module_name = os.path.basename(hook_filename)[5:-3]
  94. # Lazily loadable hook object.
  95. module_hook = ModuleHook(
  96. module_graph=self.module_graph,
  97. module_name=module_name,
  98. hook_filename=hook_filename,
  99. hook_module_name_prefix=self._hook_module_name_prefix,
  100. default_priority=default_priority,
  101. )
  102. # Add this hook to this module's list of hooks.
  103. module_hooks = self.setdefault(module_name, [])
  104. module_hooks.append(module_hook)
  105. # Post-processing: we allow only one instance of hook per module. Currently, the priority order is defined
  106. # implicitly, via order of hook directories, so the first hook in the list has the highest priority.
  107. for module_name in self.keys():
  108. hooks = self[module_name]
  109. if len(hooks) == 1:
  110. self[module_name] = hooks[0]
  111. else:
  112. # Order by priority value, in descending order.
  113. sorted_hooks = sorted(hooks, key=lambda hook: hook.priority, reverse=True)
  114. self[module_name] = sorted_hooks[0]
  115. def remove_modules(self, *module_names):
  116. """
  117. Remove the passed modules and all hook scripts cached for these modules from this cache.
  118. Parameters
  119. ----------
  120. module_names : list
  121. List of all fully-qualified module names to be removed.
  122. """
  123. for module_name in module_names:
  124. # Unload this module's hook script modules from memory. Since these are top-level pure-Python modules cached
  125. # only in the "sys.modules" dictionary, popping these modules from this dictionary suffices to garbage
  126. # collect them.
  127. module_hook = self.pop(module_name, None) # Remove our reference, if available.
  128. if module_hook is not None:
  129. sys.modules.pop(module_hook.hook_module_name, None)
  130. def _module_collection_mode_sanitizer(value):
  131. if isinstance(value, dict):
  132. # Hook set a dictionary; use it as-is
  133. return value
  134. elif isinstance(value, str):
  135. # Hook set a mode string; convert to a dictionary and assign the string to `None` (= the hooked module).
  136. return {None: value}
  137. raise ValueError(f"Invalid module collection mode setting value: {value!r}")
  138. def _bindepend_symlink_suppression_sanitizer(value):
  139. if isinstance(value, (list, set)):
  140. # Hook set a list or a set; use it as-is
  141. return set(value)
  142. elif isinstance(value, str):
  143. # Hook set a string; create a set with single element.
  144. return set([value])
  145. raise ValueError(f"Invalid value for bindepend_symlink_suppression: {value!r}")
  146. # Dictionary mapping the names of magic attributes required by the "ModuleHook" class to 2-tuples "(default_type,
  147. # sanitizer_func)", where:
  148. #
  149. # * "default_type" is the type to which that attribute will be initialized when that hook is lazily loaded.
  150. # * "sanitizer_func" is the callable sanitizing the original value of that attribute defined by that hook into a
  151. # safer value consumable by "ModuleHook" callers if any or "None" if the original value requires no sanitization.
  152. #
  153. # To avoid subtleties in the ModuleHook.__getattr__() method, this dictionary is declared as a module rather than a
  154. # class attribute. If declared as a class attribute and then undefined (...for whatever reason), attempting to access
  155. # this attribute from that method would produce infinite recursion.
  156. _MAGIC_MODULE_HOOK_ATTRS = {
  157. # Collections in which order is insignificant. This includes:
  158. #
  159. # * "datas", sanitized from hook-style 2-tuple lists defined by hooks into TOC-style 2-tuple sets consumable by
  160. # "ModuleHook" callers.
  161. # * "binaries", sanitized in the same way.
  162. 'datas': (set, format_binaries_and_datas),
  163. 'binaries': (set, format_binaries_and_datas),
  164. 'excludedimports': (set, None),
  165. # Collections in which order is significant. This includes:
  166. #
  167. # * "hiddenimports", as order of importation is significant. On module importation, hook scripts are loaded and hook
  168. # functions declared by these scripts are called. As these scripts and functions can have side effects dependent
  169. # on module importation order, module importation itself can have side effects dependent on this order!
  170. 'hiddenimports': (list, None),
  171. # Flags
  172. 'warn_on_missing_hiddenimports': (lambda: True, bool),
  173. # Package/module collection mode dictionary.
  174. 'module_collection_mode': (dict, _module_collection_mode_sanitizer),
  175. # Path patterns for suppression of symbolic links created by binary dependency analysis.
  176. 'bindepend_symlink_suppression': (set, _bindepend_symlink_suppression_sanitizer),
  177. }
  178. class ModuleHook:
  179. """
  180. Cached object encapsulating a lazy loadable hook script.
  181. This object exposes public attributes (e.g., `datas`) of the underlying hook script as attributes of the same
  182. name of this object. On the first access of any such attribute, this hook script is lazily loaded into an
  183. in-memory private module reused on subsequent accesses. These dynamic attributes are referred to as "magic." All
  184. other static attributes of this object (e.g., `hook_module_name`) are referred to as "non-magic."
  185. Attributes (Magic)
  186. ----------
  187. datas : set
  188. Set of `TOC`-style 2-tuples `(target_file, source_file)` for all external non-executable files required by
  189. the module being hooked, converted from the `datas` list of hook-style 2-tuples `(source_dir_or_glob,
  190. target_dir)` defined by this hook script.
  191. binaries : set
  192. Set of `TOC`-style 2-tuples `(target_file, source_file)` for all external executable files required by the
  193. module being hooked, converted from the `binaries` list of hook-style 2-tuples `(source_dir_or_glob,
  194. target_dir)` defined by this hook script.
  195. excludedimports : set
  196. Set of the fully-qualified names of all modules imported by the module being hooked to be ignored rather than
  197. imported from that module, converted from the `excludedimports` list defined by this hook script. These
  198. modules will only be "locally" rather than "globally" ignored. These modules will remain importable from all
  199. modules other than the module being hooked.
  200. hiddenimports : set
  201. Set of the fully-qualified names of all modules imported by the module being hooked that are _not_
  202. automatically detectable by PyInstaller (usually due to being dynamically imported in that module),
  203. converted from the `hiddenimports` list defined by this hook script.
  204. warn_on_missing_hiddenimports : bool
  205. Boolean flag indicating whether missing hidden imports from the hook should generate warnings or not. This
  206. behavior is enabled by default, but individual hooks can opt out of it.
  207. module_collection_mode : dict
  208. A dictionary of package/module names and their corresponding collection mode strings ('pyz', 'pyc', 'py',
  209. 'pyz+py', 'py+pyz').
  210. bindepend_symlink_suppression : set
  211. A set of paths or path patterns corresponding to shared libraries for which binary dependency analysis should
  212. not create symbolic links into top-level application directory.
  213. Attributes (Non-magic)
  214. ----------
  215. module_graph : ModuleGraph
  216. Current module graph.
  217. module_name : str
  218. Name of the module hooked by this hook script.
  219. hook_filename : str
  220. Absolute or relative path of this hook script.
  221. hook_module_name : str
  222. Name of the in-memory module of this hook script's interpreted contents.
  223. _hook_module : module
  224. In-memory module of this hook script's interpreted contents, lazily loaded on the first call to the
  225. `_load_hook_module()` method _or_ `None` if this method has yet to be accessed.
  226. _default_priority : int
  227. Default (location-based) priority for this hook.
  228. priority : int
  229. Actual priority for this hook. Might be different from `_default_priority` if hook file specifies the hook
  230. priority override.
  231. """
  232. #-- Magic --
  233. def __init__(self, module_graph, module_name, hook_filename, hook_module_name_prefix, default_priority):
  234. """
  235. Initialize this metadata.
  236. Parameters
  237. ----------
  238. module_graph : ModuleGraph
  239. Current module graph.
  240. module_name : str
  241. Name of the module hooked by this hook script.
  242. hook_filename : str
  243. Absolute or relative path of this hook script.
  244. hook_module_name_prefix : str
  245. String prefixing the name of the in-memory module for this hook script. To avoid namespace clashes with
  246. similar modules created by other `ModuleHook` objects in other `ModuleHookCache` containers, this string
  247. _must_ be unique to the `ModuleHookCache` container containing this `ModuleHook` object. If this string
  248. is non-unique, an existing in-memory module will be erroneously reused when lazily loading this hook
  249. script, thus erroneously resanitizing previously sanitized hook script attributes (e.g., `datas`) with
  250. the `format_binaries_and_datas()` helper.
  251. default_priority : int
  252. Default, location-based priority for this hook. Used to select active hook when multiple hooks are defined
  253. for the same module.
  254. """
  255. # Note that the passed module graph is already a weak reference, avoiding circular reference issues. See
  256. # ModuleHookCache.__init__(). TODO: Add a failure message
  257. assert isinstance(module_graph, weakref.ProxyTypes)
  258. self.module_graph = module_graph
  259. self.module_name = module_name
  260. self.hook_filename = hook_filename
  261. # Default priority; used as fall-back for dynamic `hook_priority` attribute.
  262. self._default_priority = default_priority
  263. # Name of the in-memory module fabricated to refer to this hook script.
  264. self.hook_module_name = hook_module_name_prefix + self.module_name.replace('.', '_')
  265. # Attributes subsequently defined by the _load_hook_module() method.
  266. self._loaded = False
  267. self._has_hook_function = False
  268. self._hook_module = None
  269. def __getattr__(self, attr_name):
  270. """
  271. Get the magic attribute with the passed name (e.g., `datas`) from this lazily loaded hook script if any _or_
  272. raise `AttributeError` otherwise.
  273. This special method is called only for attributes _not_ already defined by this object. This includes
  274. undefined attributes and the first attempt to access magic attributes.
  275. This special method is _not_ called for subsequent attempts to access magic attributes. The first attempt to
  276. access magic attributes defines corresponding instance variables accessible via the `self.__dict__` instance
  277. dictionary (e.g., as `self.datas`) without calling this method. This approach also allows magic attributes to
  278. be deleted from this object _without_ defining the `__delattr__()` special method.
  279. See Also
  280. ----------
  281. Class docstring for supported magic attributes.
  282. """
  283. if attr_name == 'priority':
  284. # If attribute is part of hook metadata, read metadata from hook script and return the attribute value.
  285. self._load_hook_metadata()
  286. return getattr(self, attr_name)
  287. if attr_name in _MAGIC_MODULE_HOOK_ATTRS and not self._loaded:
  288. # If attribute is hook's magic attribute, load and run the hook script, and return the attribute value.
  289. self._load_hook_module()
  290. return getattr(self, attr_name)
  291. else:
  292. # This is an undefined attribute. Raise an exception.
  293. raise AttributeError(attr_name)
  294. def __setattr__(self, attr_name, attr_value):
  295. """
  296. Set the attribute with the passed name to the passed value.
  297. If this is a magic attribute, this hook script will be lazily loaded before setting this attribute. Unlike
  298. `__getattr__()`, this special method is called to set _any_ attribute -- including magic, non-magic,
  299. and undefined attributes.
  300. See Also
  301. ----------
  302. Class docstring for supported magic attributes.
  303. """
  304. # If this is a magic attribute, initialize this attribute by lazy loading this hook script before overwriting
  305. # this attribute.
  306. if attr_name in _MAGIC_MODULE_HOOK_ATTRS:
  307. self._load_hook_module()
  308. # Set this attribute to the passed value. To avoid recursion, the superclass method rather than setattr() is
  309. # called.
  310. return super().__setattr__(attr_name, attr_value)
  311. #-- Loading --
  312. def _load_hook_metadata(self):
  313. """
  314. Load hook metadata from its source file.
  315. """
  316. self.priority = self._default_priority
  317. # Priority override pattern: `# $PyInstaller-Hook-Priority: <value>`
  318. priority_pattern = re.compile(r"^\s*#\s*\$PyInstaller-Hook-Priority:\s*(?P<value>[\S]+)")
  319. with open(self.hook_filename, "r", encoding="utf-8") as f:
  320. for line in f:
  321. # Attempt to match and parse hook priority directive
  322. m = priority_pattern.match(line)
  323. if m is not None:
  324. try:
  325. self.priority = int(m.group('value'))
  326. except Exception:
  327. logger.warning(
  328. "Failed to parse hook priority value string: %r!", m.group('value'), exc_info=True
  329. )
  330. # Currently, this is our only line of interest, so we can stop the search here.
  331. return
  332. def _load_hook_module(self, keep_module_ref=False):
  333. """
  334. Lazily load this hook script into an in-memory private module.
  335. This method (and, indeed, this class) preserves all attributes and functions defined by this hook script as
  336. is, ensuring sane behaviour in hook functions _not_ expecting unplanned external modification. Instead,
  337. this method copies public attributes defined by this hook script (e.g., `binaries`) into private attributes
  338. of this object, which the special `__getattr__()` and `__setattr__()` methods safely expose to external
  339. callers. For public attributes _not_ defined by this hook script, the corresponding private attributes will
  340. be assigned sane defaults. For some public attributes defined by this hook script, the corresponding private
  341. attributes will be transformed into objects more readily and safely consumed elsewhere by external callers.
  342. See Also
  343. ----------
  344. Class docstring for supported attributes.
  345. """
  346. # If this hook script module has already been loaded, noop.
  347. if self._loaded and (self._hook_module is not None or not keep_module_ref):
  348. return
  349. # Load and execute the hook script. Even if mechanisms from the import machinery are used, this does not import
  350. # the hook as the module.
  351. hook_path, hook_basename = os.path.split(self.hook_filename)
  352. logger.info('Processing standard module hook %r from %r', hook_basename, hook_path)
  353. try:
  354. self._hook_module = importlib_load_source(self.hook_module_name, self.hook_filename)
  355. except ImportError:
  356. logger.debug("Hook failed with:", exc_info=True)
  357. raise ImportErrorWhenRunningHook(self.hook_module_name, self.hook_filename)
  358. # Mark as loaded
  359. self._loaded = True
  360. # Check if module has hook() function.
  361. self._has_hook_function = hasattr(self._hook_module, 'hook')
  362. # Copy hook script attributes into magic attributes exposed as instance variables of the current "ModuleHook"
  363. # instance.
  364. for attr_name, (default_type, sanitizer_func) in _MAGIC_MODULE_HOOK_ATTRS.items():
  365. # Unsanitized value of this attribute.
  366. attr_value = getattr(self._hook_module, attr_name, None)
  367. # If this attribute is undefined, expose a sane default instead.
  368. if attr_value is None:
  369. attr_value = default_type()
  370. # Else if this attribute requires sanitization, do so.
  371. elif sanitizer_func is not None:
  372. attr_value = sanitizer_func(attr_value)
  373. # Else, expose the unsanitized value of this attribute.
  374. # Expose this attribute as an instance variable of the same name.
  375. setattr(self, attr_name, attr_value)
  376. # If module_collection_mode has an entry with None key, reassign it to the hooked module's name.
  377. setattr(
  378. self, 'module_collection_mode', {
  379. key if key is not None else self.module_name: value
  380. for key, value in getattr(self, 'module_collection_mode').items()
  381. }
  382. )
  383. # Release the module if we do not need the reference. This is the case when hook is loaded during the analysis
  384. # rather as part of the post-graph operations.
  385. if not keep_module_ref:
  386. self._hook_module = None
  387. #-- Hooks --
  388. def post_graph(self, analysis):
  389. """
  390. Call the **post-graph hook** (i.e., `hook()` function) defined by this hook script, if any.
  391. Parameters
  392. ----------
  393. analysis: build_main.Analysis
  394. Analysis that calls the hook
  395. This method is intended to be called _after_ the module graph for this application is constructed.
  396. """
  397. # Lazily load this hook script into an in-memory module.
  398. # The script might have been loaded before during modulegraph analysis; in that case, it needs to be reloaded
  399. # only if it provides a hook() function.
  400. if not self._loaded or self._has_hook_function:
  401. # Keep module reference when loading the hook, so we can call its hook function!
  402. self._load_hook_module(keep_module_ref=True)
  403. # Call this hook script's hook() function, which modifies attributes accessed by subsequent methods and
  404. # hence must be called first.
  405. self._process_hook_func(analysis)
  406. # Order is insignificant here.
  407. self._process_hidden_imports()
  408. def _process_hook_func(self, analysis):
  409. """
  410. Call this hook's `hook()` function if defined.
  411. Parameters
  412. ----------
  413. analysis: build_main.Analysis
  414. Analysis that calls the hook
  415. """
  416. # If this hook script defines no hook() function, noop.
  417. if not hasattr(self._hook_module, 'hook'):
  418. return
  419. # Call this hook() function.
  420. hook_api = PostGraphAPI(module_name=self.module_name, module_graph=self.module_graph, analysis=analysis)
  421. try:
  422. self._hook_module.hook(hook_api)
  423. except ImportError:
  424. logger.debug("Hook failed with:", exc_info=True)
  425. raise ImportErrorWhenRunningHook(self.hook_module_name, self.hook_filename)
  426. # Update all magic attributes modified by the prior call.
  427. self.datas.update(set(hook_api._added_datas))
  428. self.binaries.update(set(hook_api._added_binaries))
  429. self.hiddenimports.extend(hook_api._added_imports)
  430. self.module_collection_mode.update(hook_api._module_collection_mode)
  431. self.bindepend_symlink_suppression.update(hook_api._bindepend_symlink_suppression)
  432. # FIXME: `hook_api._deleted_imports` should be appended to `self.excludedimports` and used to suppress module
  433. # import during the modulegraph construction rather than handled here. However, for that to work, the `hook()`
  434. # function needs to be ran during modulegraph construction instead of in post-processing (and this in turn
  435. # requires additional code refactoring in order to be able to pass `analysis` to `PostGraphAPI` object at
  436. # that point). So once the modulegraph rewrite is complete, remove the code block below.
  437. for deleted_module_name in hook_api._deleted_imports:
  438. # Remove the graph link between the hooked module and item. This removes the 'item' node from the graph if
  439. # no other links go to it (no other modules import it)
  440. self.module_graph.removeReference(hook_api.node, deleted_module_name)
  441. def _process_hidden_imports(self):
  442. """
  443. Add all imports listed in this hook script's `hiddenimports` attribute to the module graph as if directly
  444. imported by this hooked module.
  445. These imports are typically _not_ implicitly detectable by PyInstaller and hence must be explicitly defined
  446. by hook scripts.
  447. """
  448. # For each hidden import required by the module being hooked...
  449. for import_module_name in self.hiddenimports:
  450. try:
  451. # Graph node for this module. Do not implicitly create namespace packages for non-existent packages.
  452. caller = self.module_graph.find_node(self.module_name, create_nspkg=False)
  453. # Manually import this hidden import from this module.
  454. self.module_graph.import_hook(import_module_name, caller)
  455. # If this hidden import is unimportable, print a non-fatal warning. Hidden imports often become
  456. # desynchronized from upstream packages and hence are only "soft" recommendations.
  457. except ImportError:
  458. if self.warn_on_missing_hiddenimports:
  459. logger.warning('Hidden import "%s" not found!', import_module_name)
  460. class AdditionalFilesCache:
  461. """
  462. Cache for storing what binaries and datas were pushed by what modules when import hooks were processed.
  463. """
  464. def __init__(self):
  465. self._binaries = {}
  466. self._datas = {}
  467. def add(self, modname, binaries, datas):
  468. self._binaries.setdefault(modname, [])
  469. self._binaries[modname].extend(binaries or [])
  470. self._datas.setdefault(modname, [])
  471. self._datas[modname].extend(datas or [])
  472. def __contains__(self, name):
  473. return name in self._binaries or name in self._datas
  474. def binaries(self, modname):
  475. """
  476. Return list of binaries for given module name.
  477. """
  478. return self._binaries.get(modname, [])
  479. def datas(self, modname):
  480. """
  481. Return list of datas for given module name.
  482. """
  483. return self._datas.get(modname, [])