| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2021 The Meson development team |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
|
| 7 |
import importlib.resources |
| 8 |
from pathlib import PurePosixPath, Path |
| 9 |
import typing as T |
| 10 |
|
| 11 |
if T.TYPE_CHECKING: |
| 12 |
from .environment import Environment |
| 13 |
|
| 14 |
class DataFile: |
| 15 |
def __init__(self, path: str) -> None: |
| 16 |
self.path = PurePosixPath(path) |
| 17 |
|
| 18 |
def write_once(self, path: Path) -> None: |
| 19 |
if not path.exists(): |
| 20 |
data = importlib.resources.read_text( # [ignore encoding] it's on the next lines, Mr. Lint |
| 21 |
('mesonbuild' / self.path.parent).as_posix().replace('/', '.'), |
| 22 |
self.path.name, |
| 23 |
encoding='utf-8') |
| 24 |
path.write_text(data, encoding='utf-8') |
| 25 |
|
| 26 |
def write_to_private(self, env: 'Environment') -> Path: |
| 27 |
try: |
| 28 |
# The issue that mypy/pyright see here is caused by a bug in typeshed: |
| 29 |
# https://github.com/python/typeshed/pull/15108 |
| 30 |
resource = importlib.resources.files('mesonbuild') / self.path # type: ignore[operator] |
| 31 |
if isinstance(resource, Path): |
| 32 |
return resource |
| 33 |
except AttributeError: |
| 34 |
# fall through to zipapp compatible code |
| 35 |
pass |
| 36 |
|
| 37 |
out_file = Path(env.scratch_dir) / 'data' / self.path.name |
| 38 |
out_file.parent.mkdir(exist_ok=True) |
| 39 |
self.write_once(out_file) |
| 40 |
return out_file |