Debian Codegraph @

mesonbuild/templates/sampleimpl.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2019 The Meson development team
3 # Copyright © 2023-2025 Intel Corporation
4
5 from __future__ import annotations
6 from pathlib import Path
7
8 import abc
9 import os
10 import re
11 import typing as T
12
13 from ..mesonlib import SimpleABC
14
15 if T.TYPE_CHECKING:
16 from ..minit import Arguments
17
18
19 class SampleImpl(metaclass=SimpleABC):
20
21 def __init__(self, args: Arguments):
22 self.name = args.name
23 self.executable_name = args.executable if args.executable else None
24 self.version = args.version
25 self.lowercase_token = re.sub(r'[^a-z0-9]', '_', self.name.lower())
26 self.uppercase_token = self.lowercase_token.upper()
27 self.capitalized_token = self.lowercase_token.capitalize()
28 self.meson_version = '1.0.0'
29 self.force = args.force
30 self.dependencies = args.deps.split(',') if args.deps else []
31 self.sources: list[Path] = []
32
33 @abc.abstractmethod
34 def create_executable(self) -> None:
35 pass
36
37 @abc.abstractmethod
38 def create_library(self) -> None:
39 pass
40
41 @property
42 @abc.abstractmethod
43 def exe_template(self) -> str:
44 pass
45
46 @property
47 @abc.abstractmethod
48 def exe_meson_template(self) -> str:
49 pass
50
51 @property
52 @abc.abstractmethod
53 def lib_template(self) -> str:
54 pass
55
56 @property
57 @abc.abstractmethod
58 def lib_test_template(self) -> T.Optional[str]:
59 pass
60
61 @property
62 @abc.abstractmethod
63 def lib_meson_template(self) -> str:
64 pass
65
66 @property
67 @abc.abstractmethod
68 def source_ext(self) -> str:
69 pass
70
71 def _format_dependencies(self) -> str:
72 return ''.join(f"\n dependency('{d}')," for d in self.dependencies)
73
74 def _format_sources(self) -> str:
75 return ''.join(f"\n '{x}'," for x in self.sources)
76
77 def _detect_sources(self, srcfiles: T.List[Path], transform: T.Callable[[str], str]) -> T.Tuple[str, T.List[Path]]:
78 # Try a source based on the executable name, fallback to one based
79 # on the project name if none is found.
80 expected_name = f'{transform(self.executable_name)}.{self.source_ext}'
81 if any(str(x) == expected_name for x in srcfiles):
82 return expected_name, srcfiles
83 expected_name = f'{transform(self.lowercase_token)}.{self.source_ext}'
84 if any(str(x) == expected_name for x in srcfiles):
85 return expected_name, srcfiles
86 return expected_name, [Path(expected_name)]
87
88 class ClassImpl(SampleImpl):
89
90 """For Class based languages, like Java and C#"""
91
92 def __init__(self, args: Arguments):
93 super().__init__(args)
94 self.source_name, self.sources = self._detect_sources(args.srcfiles, str.capitalize)
95
96 def create_executable(self) -> None:
97 if not os.path.exists(self.source_name):
98 with open(self.source_name, 'w', encoding='utf-8') as f:
99 f.write(self.exe_template.format(project_name=self.name,
100 class_name=self.capitalized_token))
101 if self.force or not os.path.exists('meson.build'):
102 with open('meson.build', 'w', encoding='utf-8') as f:
103 f.write(self.exe_meson_template.format(project_name=self.name,
104 exe_name=self.executable_name,
105 source_name=self.source_name,
106 version=self.version,
107 meson_version=self.meson_version,
108 dependencies=self._format_dependencies(),
109 source_files=self._format_sources()))
110
111 def create_library(self) -> None:
112 test_name = f'{self.capitalized_token}_test.{self.source_ext}'
113 kwargs = {
114 'utoken': self.uppercase_token,
115 'ltoken': self.lowercase_token,
116 'class_test': f'{self.capitalized_token}_test',
117 'class_name': self.capitalized_token,
118 'source_file': self.source_name,
119 'test_source_file': test_name,
120 'test_exe_name': f'{self.lowercase_token}_test',
121 'project_name': self.name,
122 'lib_name': self.lowercase_token,
123 'test_name': self.lowercase_token,
124 'version': self.version,
125 'meson_version': self.meson_version,
126 'dependencies': self._format_dependencies(),
127 'source_files': self._format_sources(),
128 }
129 if not os.path.exists(self.source_name):
130 with open(self.source_name, 'w', encoding='utf-8') as f:
131 f.write(self.lib_template.format(**kwargs))
132 if self.lib_test_template and not os.path.exists(test_name):
133 with open(test_name, 'w', encoding='utf-8') as f:
134 f.write(self.lib_test_template.format(**kwargs))
135 if self.force or not os.path.exists('meson.build'):
136 with open('meson.build', 'w', encoding='utf-8') as f:
137 f.write(self.lib_meson_template.format(**kwargs))
138
139
140 class FileImpl(SampleImpl):
141
142 """File based languages without headers"""
143
144 def __init__(self, args: Arguments):
145 super().__init__(args)
146 self.source_name, self.sources = self._detect_sources(args.srcfiles, str.lower)
147
148 def create_executable(self) -> None:
149 if not os.path.exists(self.source_name):
150 with open(self.source_name, 'w', encoding='utf-8') as f:
151 f.write(self.exe_template.format(project_name=self.name))
152 if self.force or not os.path.exists('meson.build'):
153 with open('meson.build', 'w', encoding='utf-8') as f:
154 f.write(self.exe_meson_template.format(project_name=self.name,
155 exe_name=self.executable_name,
156 source_name=self.source_name,
157 version=self.version,
158 meson_version=self.meson_version,
159 dependencies=self._format_dependencies(),
160 source_files=self._format_sources()))
161
162 def lib_kwargs(self) -> T.Dict[str, str]:
163 """Get Language specific keyword arguments
164
165 :return: A dictionary of key: values to fill in the templates
166 """
167 return {
168 'utoken': self.uppercase_token,
169 'ltoken': self.lowercase_token,
170 'header_dir': self.lowercase_token,
171 'class_name': self.capitalized_token,
172 'function_name': f'{self.lowercase_token[0:3]}_func',
173 'namespace': self.lowercase_token,
174 'source_file': f'{self.lowercase_token}.{self.source_ext}',
175 'test_source_file': f'{self.lowercase_token}_test.{self.source_ext}',
176 'test_exe_name': f'{self.lowercase_token}_test',
177 'project_name': self.name,
178 'lib_name': self.lowercase_token,
179 'test_name': self.lowercase_token,
180 'version': self.version,
181 'meson_version': self.meson_version,
182 'dependencies': self._format_dependencies(),
183 'source_files': self._format_sources(),
184 }
185
186 def create_library(self) -> None:
187 test_name = f'{self.lowercase_token}_test.{self.source_ext}'
188 kwargs = self.lib_kwargs()
189 if not os.path.exists(self.source_name):
190 with open(self.source_name, 'w', encoding='utf-8') as f:
191 f.write(self.lib_template.format(**kwargs))
192 if self.lib_test_template and not os.path.exists(test_name):
193 with open(test_name, 'w', encoding='utf-8') as f:
194 f.write(self.lib_test_template.format(**kwargs))
195 if self.force or not os.path.exists('meson.build'):
196 with open('meson.build', 'w', encoding='utf-8') as f:
197 f.write(self.lib_meson_template.format(**kwargs))
198
199
200 class FileHeaderImpl(FileImpl):
201
202 @property
203 @abc.abstractmethod
204 def header_ext(self) -> str:
205 pass
206
207 @property
208 @abc.abstractmethod
209 def lib_header_template(self) -> str:
210 pass
211
212 def lib_kwargs(self) -> T.Dict[str, str]:
213 kwargs = super().lib_kwargs()
214 kwargs['header_file'] = f'{self.lowercase_token}.{self.header_ext}'
215 return kwargs
216
217 def create_library(self) -> None:
218 super().create_library()
219 kwargs = self.lib_kwargs()
220 if not os.path.exists(kwargs['header_file']):
221 with open(kwargs['header_file'], 'w', encoding='utf-8') as f:
222 f.write(self.lib_header_template.format_map(kwargs))