| 100 | _find_spec = importlib.machinery.PathFinder.find_spec |
| 101 | |
| 102 | def find_spec( |
| 103 | self, |
| 104 | name: str, |
| 105 | path: Sequence[str | bytes] | None = None, |
| 106 | target: types.ModuleType | None = None, |
| 107 | ) -> importlib.machinery.ModuleSpec | None: |
| 108 | if self._writing_pyc: |
| 109 | return None |
| 110 | state = self.config.stash[assertstate_key] |
| 111 | if self._early_rewrite_bailout(name, state): |
| 112 | return None |
| 113 | state.trace(f"find_module called for: {name}") |
| 114 | |
| 115 | # Type ignored because mypy is confused about the `self` binding here. |
| 116 | spec = self._find_spec(name, path) # type: ignore |
| 117 | |
| 118 | if ( |
| 119 | # the import machinery could not find a file to import |
| 120 | spec is None |
| 121 | # this is a namespace package (without `__init__.py`) |
| 122 | # there's nothing to rewrite there |
| 123 | or spec.origin is None |
| 124 | # we can only rewrite source files |
| 125 | or not isinstance(spec.loader, importlib.machinery.SourceFileLoader) |
| 126 | # if the file doesn't exist, we can't rewrite it |
| 127 | or not os.path.exists(spec.origin) |
| 128 | ): |
| 129 | return None |
| 130 | else: |
| 131 | fn = spec.origin |
| 132 | |
| 133 | if not self._should_rewrite(name, fn, state): |
| 134 | return None |
| 135 | |
| 136 | return importlib.util.spec_from_file_location( |
| 137 | name, |
| 138 | fn, |
| 139 | loader=self, |
| 140 | submodule_search_locations=spec.submodule_search_locations, |
| 141 | ) |
| 142 | |
| 143 | def create_module( |
| 144 | self, spec: importlib.machinery.ModuleSpec |