|
13 | 13 | from coverage import env
|
14 | 14 | from coverage.backward import BUILTINS
|
15 | 15 | from coverage.backward import PYC_MAGIC_NUMBER, imp, importlib_util_find_spec
|
16 |
| -from coverage.files import python_reported_file |
| 16 | +from coverage.files import canonical_filename, python_reported_file |
17 | 17 | from coverage.misc import CoverageException, ExceptionDuringRun, NoCode, NoSource, isolate_module
|
18 | 18 | from coverage.phystokens import compile_unicode
|
19 | 19 | from coverage.python import get_python_source
|
@@ -120,32 +120,41 @@ def prepare(self):
|
120 | 120 |
|
121 | 121 | This needs to happen before any importing, and without importing anything.
|
122 | 122 | """
|
123 |
| - should_update_sys_path = True |
124 | 123 | if self.as_module:
|
125 | 124 | if env.PYBEHAVIOR.actual_syspath0_dash_m:
|
126 | 125 | path0 = os.getcwd()
|
127 | 126 | else:
|
128 | 127 | path0 = ""
|
129 |
| - sys.path[0] = path0 |
130 |
| - should_update_sys_path = False |
131 | 128 | elif os.path.isdir(self.arg0):
|
132 | 129 | # Running a directory means running the __main__.py file in that
|
133 | 130 | # directory.
|
134 | 131 | path0 = self.arg0
|
135 | 132 | else:
|
136 | 133 | path0 = os.path.abspath(os.path.dirname(self.arg0))
|
137 | 134 |
|
138 |
| - |
139 |
| - if should_update_sys_path: |
| 135 | + if os.path.isdir(sys.path[0]): |
140 | 136 | # sys.path fakery. If we are being run as a command, then sys.path[0]
|
141 | 137 | # is the directory of the "coverage" script. If this is so, replace
|
142 | 138 | # sys.path[0] with the directory of the file we're running, or the
|
143 | 139 | # current directory when running modules. If it isn't so, then we
|
144 | 140 | # don't know what's going on, and just leave it alone.
|
145 | 141 | top_file = inspect.stack()[-1][0].f_code.co_filename
|
146 |
| - if os.path.abspath(sys.path[0]) == os.path.abspath(os.path.dirname(top_file)): |
147 |
| - # Set sys.path correctly. |
148 |
| - sys.path[0] = python_reported_file(path0) |
| 142 | + sys_path_0_abs = os.path.abspath(sys.path[0]) |
| 143 | + top_file_dir_abs = os.path.abspath(os.path.dirname(top_file)) |
| 144 | + sys_path_0_abs = canonical_filename(sys_path_0_abs) |
| 145 | + top_file_dir_abs = canonical_filename(top_file_dir_abs) |
| 146 | + if sys_path_0_abs != top_file_dir_abs: |
| 147 | + path0 = None |
| 148 | + |
| 149 | + else: |
| 150 | + # sys.path[0] is a file. Is the next entry the directory containing |
| 151 | + # that file? |
| 152 | + if sys.path[1] == os.path.dirname(sys.path[0]): |
| 153 | + # Can it be right to always remove that? |
| 154 | + del sys.path[1] |
| 155 | + |
| 156 | + if path0 is not None: |
| 157 | + sys.path[0] = python_reported_file(path0) |
149 | 158 |
|
150 | 159 | def _prepare2(self):
|
151 | 160 | """Do more preparation to run Python code.
|
|
0 commit comments