| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2021 The Meson development team |
| 3 |
|
| 4 |
''' |
| 5 |
This module soly exists to work around a pathlib.resolve bug on |
| 6 |
certain Windows systems: |
| 7 |
|
| 8 |
https://github.com/mesonbuild/meson/issues/7295 |
| 9 |
https://bugs.python.org/issue31842 |
| 10 |
|
| 11 |
It should **never** be used directly. Instead, it is automatically |
| 12 |
used when `import pathlib` is used. This is achieved by messing with |
| 13 |
`sys.modules['pathlib']` in mesonmain. |
| 14 |
|
| 15 |
Additionally, the sole purpose of this module is to work around a |
| 16 |
python bug. This only bugfixes to pathlib functions and classes are |
| 17 |
allowed here. Finally, this file should be removed once all upstream |
| 18 |
python bugs are fixed and it is OK to tell our users to "just upgrade |
| 19 |
python". |
| 20 |
''' |
| 21 |
from __future__ import annotations |
| 22 |
|
| 23 |
import pathlib |
| 24 |
import os |
| 25 |
import platform |
| 26 |
|
| 27 |
__all__ = [ |
| 28 |
'PurePath', |
| 29 |
'PurePosixPath', |
| 30 |
'PureWindowsPath', |
| 31 |
'Path', |
| 32 |
] |
| 33 |
|
| 34 |
PurePath = pathlib.PurePath |
| 35 |
PurePosixPath = pathlib.PurePosixPath |
| 36 |
PureWindowsPath = pathlib.PureWindowsPath |
| 37 |
|
| 38 |
# Only patch on platforms where the bug occurs |
| 39 |
if platform.system().lower() == 'windows': |
| 40 |
# Can not directly inherit from pathlib.Path because the __new__ |
| 41 |
# operator of pathlib.Path() returns a {Posix,Windows}Path object |
| 42 |
# until Python 3.12, when this was changed so that Path can be directly |
| 43 |
# inherited. |
| 44 |
# |
| 45 |
# Since this particular code path is only relevant to Windows, just inherit |
| 46 |
# WindowsPath directly. |
| 47 |
class _Path(pathlib.WindowsPath): |
| 48 |
def resolve(self, strict: bool = False) -> _Path: |
| 49 |
''' |
| 50 |
Work around a resolve bug on certain Windows systems: |
| 51 |
|
| 52 |
https://github.com/mesonbuild/meson/issues/7295 |
| 53 |
https://bugs.python.org/issue31842 |
| 54 |
''' |
| 55 |
|
| 56 |
try: |
| 57 |
return super().resolve(strict=strict) |
| 58 |
except OSError: |
| 59 |
return _Path(os.path.normpath(self)) |
| 60 |
|
| 61 |
Path: type[pathlib.Path] = _Path |
| 62 |
else: |
| 63 |
Path = pathlib.Path |
| 64 |
PosixPath = pathlib.PosixPath |
| 65 |
WindowsPath = pathlib.WindowsPath |
| 66 |
|
| 67 |
__all__ += [ |
| 68 |
'PosixPath', |
| 69 |
'WindowsPath', |
| 70 |
] |