| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2019 The Meson development team |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
from ntpath import sep as ntsep |
| 6 |
from pathlib import Path |
| 7 |
from posixpath import sep as posixsep |
| 8 |
import hashlib |
| 9 |
import os |
| 10 |
import typing as T |
| 11 |
|
| 12 |
from . import ExtensionModule, ModuleReturnValue, ModuleInfo |
| 13 |
from .. import mlog |
| 14 |
from ..build import BuildTarget, CustomTarget, CustomTargetIndex, InvalidArguments |
| 15 |
from ..interpreter.type_checking import INSTALL_KW, INSTALL_MODE_KW, INSTALL_TAG_KW, \ |
| 16 |
BUILD_SUBDIR_KW, NoneType |
| 17 |
from ..interpreterbase import FeatureNew, KwargInfo, typed_kwargs, typed_pos_args, noKwargs |
| 18 |
from ..mesonlib import File, MesonException, has_path_sep, is_windows, path_is_in_root, relpath |
| 19 |
|
| 20 |
if T.TYPE_CHECKING: |
| 21 |
from . import ModuleState |
| 22 |
from ..build import BuildTargetTypes |
| 23 |
from ..interpreter import Interpreter |
| 24 |
from ..interpreterbase import TYPE_kwargs |
| 25 |
from ..mesonlib import FileOrString, FileMode |
| 26 |
|
| 27 |
from typing_extensions import TypedDict |
| 28 |
|
| 29 |
FilePathTypes = str | File | BuildTargetTypes |
| 30 |
|
| 31 |
class ReadKwArgs(TypedDict): |
| 32 |
"""Keyword Arguments for fs.read.""" |
| 33 |
|
| 34 |
encoding: str |
| 35 |
|
| 36 |
class CopyKw(TypedDict): |
| 37 |
|
| 38 |
"""Kwargs for fs.copy""" |
| 39 |
|
| 40 |
build_subdir: str |
| 41 |
install: bool |
| 42 |
install_dir: T.Optional[str] |
| 43 |
install_mode: FileMode |
| 44 |
install_tag: T.Optional[str] |
| 45 |
|
| 46 |
|
| 47 |
class FSModule(ExtensionModule): |
| 48 |
|
| 49 |
INFO = ModuleInfo('fs', '0.53.0') |
| 50 |
|
| 51 |
def __init__(self, interpreter: Interpreter) -> None: |
| 52 |
super().__init__(interpreter) |
| 53 |
self.methods.update({ |
| 54 |
'as_posix': self.as_posix, |
| 55 |
'copyfile': self.copyfile, |
| 56 |
'exists': self.exists, |
| 57 |
'expanduser': self.expanduser, |
| 58 |
'hash': self.hash, |
| 59 |
'is_absolute': self.is_absolute, |
| 60 |
'is_dir': self.is_dir, |
| 61 |
'is_file': self.is_file, |
| 62 |
'is_samepath': self.is_samepath, |
| 63 |
'is_symlink': self.is_symlink, |
| 64 |
'name': self.name, |
| 65 |
'parent': self.parent, |
| 66 |
'read': self.read, |
| 67 |
'relative_to': self.relative_to, |
| 68 |
'replace_suffix': self.replace_suffix, |
| 69 |
'size': self.size, |
| 70 |
'stem': self.stem, |
| 71 |
'suffix': self.suffix, |
| 72 |
}) |
| 73 |
|
| 74 |
def _absolute_dir(self, state: ModuleState, arg: FileOrString) -> str: |
| 75 |
""" |
| 76 |
make an absolute path from a relative path, WITHOUT resolving symlinks |
| 77 |
""" |
| 78 |
if isinstance(arg, File): |
| 79 |
return arg.absolute_path(state.source_root, state.environment.get_build_dir()) |
| 80 |
return os.path.join(state.source_root, state.subdir, os.path.expanduser(arg)) |
| 81 |
|
| 82 |
@staticmethod |
| 83 |
def _obj_to_pathstr(feature_new_prefix: str, obj: FilePathTypes, state: ModuleState) -> str: |
| 84 |
if isinstance(obj, str): |
| 85 |
return obj |
| 86 |
|
| 87 |
if isinstance(obj, File): |
| 88 |
FeatureNew(f'{feature_new_prefix} with file', '0.59.0').use(state.subproject, location=state.current_node) |
| 89 |
return str(obj) |
| 90 |
|
| 91 |
FeatureNew(f'{feature_new_prefix} with build_tgt, custom_tgt, and custom_idx', '1.4.0').use(state.subproject, location=state.current_node) |
| 92 |
return state.backend.get_target_filename(obj) |
| 93 |
|
| 94 |
def _resolve_dir(self, state: ModuleState, arg: FileOrString) -> str: |
| 95 |
""" |
| 96 |
resolves symlinks and makes absolute a directory relative to calling meson.build, |
| 97 |
if not already absolute |
| 98 |
""" |
| 99 |
path = self._absolute_dir(state, arg) |
| 100 |
try: |
| 101 |
# accommodate unresolvable paths e.g. symlink loops |
| 102 |
path = os.path.realpath(path) |
| 103 |
except Exception: |
| 104 |
# return the best we could do |
| 105 |
pass |
| 106 |
return path |
| 107 |
|
| 108 |
@noKwargs |
| 109 |
@FeatureNew('fs.expanduser', '0.54.0') |
| 110 |
@typed_pos_args('fs.expanduser', str) |
| 111 |
def expanduser(self, state: ModuleState, args: T.Tuple[str], kwargs: T.Dict[str, T.Any]) -> str: |
| 112 |
return os.path.expanduser(args[0]) |
| 113 |
|
| 114 |
@noKwargs |
| 115 |
@FeatureNew('fs.is_absolute', '0.54.0') |
| 116 |
@typed_pos_args('fs.is_absolute', (str, File)) |
| 117 |
def is_absolute(self, state: ModuleState, args: T.Tuple[FileOrString], kwargs: T.Dict[str, T.Any]) -> bool: |
| 118 |
path = args[0] |
| 119 |
if isinstance(path, File): |
| 120 |
FeatureNew('fs.is_absolute with file', '0.59.0').use(state.subproject, location=state.current_node) |
| 121 |
path = str(path) |
| 122 |
if is_windows(): |
| 123 |
# os.path.isabs was broken for Windows before Python 3.13, so we implement it ourselves |
| 124 |
path = path[:3].replace(posixsep, ntsep) |
| 125 |
return path.startswith(ntsep * 2) or path.startswith(':' + ntsep, 1) |
| 126 |
return path.startswith(posixsep) |
| 127 |
|
| 128 |
@noKwargs |
| 129 |
@FeatureNew('fs.as_posix', '0.54.0') |
| 130 |
@typed_pos_args('fs.as_posix', str) |
| 131 |
def as_posix(self, state: ModuleState, args: T.Tuple[str], kwargs: T.Dict[str, T.Any]) -> str: |
| 132 |
r""" |
| 133 |
this function assumes you are passing a Windows path, even if on a Unix-like system |
| 134 |
and so ALL '\' are turned to '/', even if you meant to escape a character |
| 135 |
""" |
| 136 |
return args[0].replace(ntsep, posixsep) |
| 137 |
|
| 138 |
@noKwargs |
| 139 |
@typed_pos_args('fs.exists', str) |
| 140 |
def exists(self, state: ModuleState, args: T.Tuple[str], kwargs: T.Dict[str, T.Any]) -> bool: |
| 141 |
return os.path.exists(self._resolve_dir(state, args[0])) |
| 142 |
|
| 143 |
@noKwargs |
| 144 |
@typed_pos_args('fs.is_symlink', (str, File)) |
| 145 |
def is_symlink(self, state: ModuleState, args: T.Tuple[FileOrString], kwargs: T.Dict[str, T.Any]) -> bool: |
| 146 |
if isinstance(args[0], File): |
| 147 |
FeatureNew('fs.is_symlink with file', '0.59.0').use(state.subproject, location=state.current_node) |
| 148 |
return os.path.islink(self._absolute_dir(state, args[0])) |
| 149 |
|
| 150 |
@noKwargs |
| 151 |
@typed_pos_args('fs.is_file', str) |
| 152 |
def is_file(self, state: ModuleState, args: T.Tuple[str], kwargs: T.Dict[str, T.Any]) -> bool: |
| 153 |
return os.path.isfile(self._resolve_dir(state, args[0])) |
| 154 |
|
| 155 |
@noKwargs |
| 156 |
@typed_pos_args('fs.is_dir', str) |
| 157 |
def is_dir(self, state: ModuleState, args: T.Tuple[str], kwargs: T.Dict[str, T.Any]) -> bool: |
| 158 |
return os.path.isdir(self._resolve_dir(state, args[0])) |
| 159 |
|
| 160 |
@noKwargs |
| 161 |
@typed_pos_args('fs.hash', (str, File), str) |
| 162 |
def hash(self, state: ModuleState, args: T.Tuple[FileOrString, str], kwargs: T.Dict[str, T.Any]) -> str: |
| 163 |
if isinstance(args[0], File): |
| 164 |
FeatureNew('fs.hash with file', '0.59.0').use(state.subproject, location=state.current_node) |
| 165 |
file = self._resolve_dir(state, args[0]) |
| 166 |
if not os.path.isfile(file): |
| 167 |
raise MesonException(f'{file} is not a file and therefore cannot be hashed') |
| 168 |
try: |
| 169 |
h = hashlib.new(args[1]) |
| 170 |
except ValueError: |
| 171 |
raise MesonException('hash algorithm {} is not available'.format(args[1])) |
| 172 |
mlog.debug('computing {} sum of {} size {} bytes'.format(args[1], file, os.stat(file).st_size)) |
| 173 |
with open(file, mode='rb', buffering=0) as f: |
| 174 |
h.update(f.read()) |
| 175 |
return h.hexdigest() |
| 176 |
|
| 177 |
@noKwargs |
| 178 |
@typed_pos_args('fs.size', (str, File)) |
| 179 |
def size(self, state: ModuleState, args: T.Tuple[FileOrString], kwargs: T.Dict[str, T.Any]) -> int: |
| 180 |
if isinstance(args[0], File): |
| 181 |
FeatureNew('fs.size with file', '0.59.0').use(state.subproject, location=state.current_node) |
| 182 |
file = self._resolve_dir(state, args[0]) |
| 183 |
if not os.path.isfile(file): |
| 184 |
raise MesonException(f'{file} is not a file and therefore cannot be sized') |
| 185 |
try: |
| 186 |
return os.stat(file).st_size |
| 187 |
except ValueError: |
| 188 |
raise MesonException('{} size could not be determined'.format(args[0])) |
| 189 |
|
| 190 |
@noKwargs |
| 191 |
@typed_pos_args('fs.is_samepath', (str, File), (str, File)) |
| 192 |
def is_samepath(self, state: ModuleState, args: T.Tuple[FileOrString, FileOrString], kwargs: T.Dict[str, T.Any]) -> bool: |
| 193 |
if isinstance(args[0], File) or isinstance(args[1], File): |
| 194 |
FeatureNew('fs.is_samepath with file', '0.59.0').use(state.subproject, location=state.current_node) |
| 195 |
file1 = self._resolve_dir(state, args[0]) |
| 196 |
file2 = self._resolve_dir(state, args[1]) |
| 197 |
if not os.path.exists(file1): |
| 198 |
return False |
| 199 |
if not os.path.exists(file2): |
| 200 |
return False |
| 201 |
try: |
| 202 |
return os.path.samefile(file1, file2) |
| 203 |
except OSError: |
| 204 |
return False |
| 205 |
|
| 206 |
@noKwargs |
| 207 |
@typed_pos_args('fs.replace_suffix', (str, File, CustomTarget, CustomTargetIndex, BuildTarget), str) |
| 208 |
def replace_suffix(self, state: ModuleState, args: T.Tuple[FilePathTypes, str], kwargs: T.Dict[str, T.Any]) -> str: |
| 209 |
if args[1] and not args[1].startswith('.'): |
| 210 |
raise ValueError(f"Invalid suffix {args[1]!r}") |
| 211 |
path = self._obj_to_pathstr('fs.replace_suffix', args[0], state) |
| 212 |
return os.path.splitext(path)[0] + args[1] |
| 213 |
|
| 214 |
@noKwargs |
| 215 |
@typed_pos_args('fs.parent', (str, File, CustomTarget, CustomTargetIndex, BuildTarget)) |
| 216 |
def parent(self, state: ModuleState, args: T.Tuple[FilePathTypes], kwargs: T.Dict[str, T.Any]) -> str: |
| 217 |
path = self._obj_to_pathstr('fs.parent', args[0], state) |
| 218 |
return os.path.split(path)[0] or '.' |
| 219 |
|
| 220 |
@noKwargs |
| 221 |
@typed_pos_args('fs.name', (str, File, CustomTarget, CustomTargetIndex, BuildTarget)) |
| 222 |
def name(self, state: ModuleState, args: T.Tuple[FilePathTypes], kwargs: T.Dict[str, T.Any]) -> str: |
| 223 |
path = self._obj_to_pathstr('fs.name', args[0], state) |
| 224 |
return os.path.basename(path) |
| 225 |
|
| 226 |
@noKwargs |
| 227 |
@typed_pos_args('fs.stem', (str, File, CustomTarget, CustomTargetIndex, BuildTarget)) |
| 228 |
@FeatureNew('fs.stem', '0.54.0') |
| 229 |
def stem(self, state: ModuleState, args: T.Tuple[FilePathTypes], kwargs: T.Dict[str, T.Any]) -> str: |
| 230 |
path = self._obj_to_pathstr('fs.name', args[0], state) |
| 231 |
return os.path.splitext(os.path.basename(path))[0] |
| 232 |
|
| 233 |
@noKwargs |
| 234 |
@typed_pos_args('fs.suffix', (str, File, CustomTarget, CustomTargetIndex, BuildTarget)) |
| 235 |
@FeatureNew('fs.suffix', '1.9.0') |
| 236 |
def suffix(self, state: ModuleState, args: T.Tuple[FilePathTypes], kwargs: T.Dict[str, T.Any]) -> str: |
| 237 |
path = self._obj_to_pathstr('fs.suffix', args[0], state) |
| 238 |
return os.path.splitext(path)[1] |
| 239 |
|
| 240 |
@FeatureNew('fs.read', '0.57.0') |
| 241 |
@typed_pos_args('fs.read', (str, File)) |
| 242 |
@typed_kwargs('fs.read', KwargInfo('encoding', str, default='utf-8')) |
| 243 |
def read(self, state: ModuleState, args: T.Tuple[FileOrString], kwargs: ReadKwArgs) -> str: |
| 244 |
"""Read a file from the source tree and return its value as a decoded |
| 245 |
string. |
| 246 |
|
| 247 |
If the encoding is not specified, the file is assumed to be utf-8 |
| 248 |
encoded. Paths must be relative by default (to prevent accidents) and |
| 249 |
are forbidden to be read from the build directory (to prevent build |
| 250 |
loops) |
| 251 |
""" |
| 252 |
path = args[0] |
| 253 |
encoding = kwargs['encoding'] |
| 254 |
src_dir = state.environment.source_dir |
| 255 |
sub_dir = state.subdir |
| 256 |
build_dir = state.environment.get_build_dir() |
| 257 |
|
| 258 |
if isinstance(path, File): |
| 259 |
if path.is_built: |
| 260 |
raise MesonException( |
| 261 |
'fs.read does not accept built files() objects') |
| 262 |
path = os.path.join(src_dir, path.relative_name()) |
| 263 |
else: |
| 264 |
if sub_dir: |
| 265 |
src_dir = os.path.join(src_dir, sub_dir) |
| 266 |
path = os.path.join(src_dir, path) |
| 267 |
|
| 268 |
path = os.path.abspath(path) |
| 269 |
if path_is_in_root(Path(path), Path(build_dir), resolve=True): |
| 270 |
raise MesonException('path must not be in the build tree') |
| 271 |
try: |
| 272 |
with open(path, encoding=encoding) as f: |
| 273 |
data = f.read() |
| 274 |
except FileNotFoundError: |
| 275 |
raise MesonException(f'File {args[0]} does not exist.') |
| 276 |
except UnicodeDecodeError: |
| 277 |
raise MesonException(f'decoding failed for {args[0]}') |
| 278 |
# Reconfigure when this file changes as it can contain data used by any |
| 279 |
# part of the build configuration (e.g. `project(..., version: |
| 280 |
# fs.read_file('VERSION')` or `configure_file(...)` |
| 281 |
self.interpreter.add_build_def_file(path) |
| 282 |
return data |
| 283 |
|
| 284 |
@FeatureNew('fs.copyfile', '0.64.0') |
| 285 |
@typed_pos_args('fs.copyfile', (File, str), optargs=[str]) |
| 286 |
@typed_kwargs( |
| 287 |
'fs.copyfile', |
| 288 |
INSTALL_KW, |
| 289 |
INSTALL_MODE_KW, |
| 290 |
INSTALL_TAG_KW, |
| 291 |
KwargInfo('install_dir', (str, NoneType)), |
| 292 |
BUILD_SUBDIR_KW.evolve(since='1.12.0'), |
| 293 |
) |
| 294 |
def copyfile(self, state: ModuleState, args: T.Tuple[FileOrString, T.Optional[str]], |
| 295 |
kwargs: CopyKw) -> ModuleReturnValue: |
| 296 |
"""Copy a file into the build directory at build time.""" |
| 297 |
if kwargs['install'] and not kwargs['install_dir']: |
| 298 |
raise InvalidArguments('"install_dir" must be specified when "install" is true') |
| 299 |
|
| 300 |
src = self.interpreter.source_strings_to_files([args[0]])[0] |
| 301 |
|
| 302 |
# The input is allowed to have path separators, but the output may not, |
| 303 |
# so use the basename for the default case |
| 304 |
dest = args[1] if args[1] else os.path.basename(src.fname) |
| 305 |
if has_path_sep(dest): |
| 306 |
raise InvalidArguments('Destination path may not have path separators') |
| 307 |
|
| 308 |
ct = CustomTarget( |
| 309 |
dest, |
| 310 |
state.subdir, |
| 311 |
state.environment, |
| 312 |
state.environment.get_build_command() + ['--internal', 'copy', '@INPUT@', '@OUTPUT@'], |
| 313 |
[src], |
| 314 |
[dest], |
| 315 |
state.current_build_project, |
| 316 |
build_by_default=True, |
| 317 |
install=kwargs['install'], |
| 318 |
install_dir=[kwargs['install_dir']], |
| 319 |
install_mode=kwargs['install_mode'], |
| 320 |
install_tag=[kwargs['install_tag']], |
| 321 |
backend=state.backend, |
| 322 |
description='Copying file {}', |
| 323 |
build_subdir=kwargs['build_subdir'], |
| 324 |
) |
| 325 |
|
| 326 |
return ModuleReturnValue(ct, [ct]) |
| 327 |
|
| 328 |
@FeatureNew('fs.relative_to', '1.3.0') |
| 329 |
@typed_pos_args('fs.relative_to', (str, File, CustomTarget, CustomTargetIndex, BuildTarget), (str, File, CustomTarget, CustomTargetIndex, BuildTarget)) |
| 330 |
@noKwargs |
| 331 |
def relative_to(self, state: ModuleState, args: T.Tuple[FilePathTypes, FilePathTypes], kwargs: TYPE_kwargs) -> str: |
| 332 |
def to_path(arg: FilePathTypes) -> str: |
| 333 |
if isinstance(arg, File): |
| 334 |
return arg.absolute_path(state.environment.source_dir, state.environment.build_dir) |
| 335 |
elif isinstance(arg, (CustomTarget, CustomTargetIndex, BuildTarget)): |
| 336 |
return state.backend.get_target_filename_abs(arg) |
| 337 |
else: |
| 338 |
return os.path.join(state.environment.source_dir, state.subdir, arg) |
| 339 |
|
| 340 |
t = to_path(args[0]) |
| 341 |
f = to_path(args[1]) |
| 342 |
|
| 343 |
return relpath(t, f) |
| 344 |
|
| 345 |
|
| 346 |
def initialize(*args: T.Any, **kwargs: T.Any) -> FSModule: |
| 347 |
return FSModule(*args, **kwargs) |