| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2017, 2019 The Meson development team |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import os |
| 7 |
import typing as T |
| 8 |
|
| 9 |
from . import ExtensionModule, ModuleInfo |
| 10 |
from .. import mesonlib |
| 11 |
from ..interpreterbase import noKwargs, typed_pos_args |
| 12 |
|
| 13 |
if T.TYPE_CHECKING: |
| 14 |
from ..interpreter import Interpreter |
| 15 |
from . import ModuleState |
| 16 |
|
| 17 |
class KeyvalModule(ExtensionModule): |
| 18 |
|
| 19 |
INFO = ModuleInfo('keyval', '0.55.0', stabilized='0.56.0') |
| 20 |
|
| 21 |
def __init__(self, interp: 'Interpreter'): |
| 22 |
super().__init__(interp) |
| 23 |
self.methods.update({ |
| 24 |
'load': self.load, |
| 25 |
}) |
| 26 |
|
| 27 |
@staticmethod |
| 28 |
def _load_file(path_to_config: str) -> T.Dict[str, str]: |
| 29 |
result: T.Dict[str, str] = {} |
| 30 |
try: |
| 31 |
with open(path_to_config, encoding='utf-8') as f: |
| 32 |
for line in f: |
| 33 |
if '#' in line: |
| 34 |
comment_idx = line.index('#') |
| 35 |
line = line[:comment_idx] |
| 36 |
line = line.strip() |
| 37 |
try: |
| 38 |
name, val = line.split('=', 1) |
| 39 |
except ValueError: |
| 40 |
continue |
| 41 |
result[name.strip()] = val.strip() |
| 42 |
except OSError as e: |
| 43 |
raise mesonlib.MesonException(f'Failed to load {path_to_config}: {e}') |
| 44 |
|
| 45 |
return result |
| 46 |
|
| 47 |
@noKwargs |
| 48 |
@typed_pos_args('keyval.load', (str, mesonlib.File)) |
| 49 |
def load(self, state: 'ModuleState', args: T.Tuple['mesonlib.FileOrString'], kwargs: T.Dict[str, T.Any]) -> T.Dict[str, str]: |
| 50 |
s = args[0] |
| 51 |
is_built = False |
| 52 |
if isinstance(s, mesonlib.File): |
| 53 |
is_built = is_built or s.is_built |
| 54 |
s = s.absolute_path(self.interpreter.environment.source_dir, self.interpreter.environment.build_dir) |
| 55 |
else: |
| 56 |
s = os.path.join(self.interpreter.environment.source_dir, s) |
| 57 |
|
| 58 |
if not is_built: |
| 59 |
self.interpreter.build_def_files.add(s) |
| 60 |
|
| 61 |
return self._load_file(s) |
| 62 |
|
| 63 |
|
| 64 |
def initialize(interp: 'Interpreter') -> KeyvalModule: |
| 65 |
return KeyvalModule(interp) |