Debian Codegraph @

mesonbuild/dependencies/configtool.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2021 The Meson development team
3
4 from __future__ import annotations
5
6 from .base import ExternalDependency, DependencyException, DependencyTypeName
7 from ..mesonlib import listify, Popen_safe, Popen_safe_logged, split_args, version_compare, version_compare_many
8 from ..programs import find_external_program
9 from .. import mlog
10 import re
11 import typing as T
12
13 if T.TYPE_CHECKING:
14 from ..environment import Environment
15 from ..interpreter.type_checking import PkgConfigDefineType
16 from .base import DependencyObjectKWs
17
18
19 class ConfigToolDependency(ExternalDependency):
20
21 """Class representing dependencies found using a config tool.
22
23 Takes the following extra keys in kwargs that it uses internally:
24 :tools List[str]: A list of tool names to use
25 :version_arg str: The argument to pass to the tool to get its version
26 :skip_version str: The argument to pass to the tool to ignore its version
27 (if ``version_arg`` fails, but it may start accepting it in the future)
28 Because some tools are stupid and don't accept --version
29 :returncode_value int: The value of the correct returncode
30 Because some tools are stupid and don't return 0
31 """
32
33 tools: T.Optional[T.List[str]] = None
34 tool_name: T.Optional[str] = None
35 version_arg = '--version'
36 skip_version: T.Optional[str] = None
37 allow_default_for_cross = False
38 __strip_version = re.compile(r'^[0-9][0-9.]+')
39 type_name = DependencyTypeName('config-tool')
40
41 def __init__(self, name: str, environment: 'Environment', kwargs: DependencyObjectKWs, exclude_paths: T.Optional[T.List[str]] = None):
42 super().__init__(name, environment, kwargs)
43 # You may want to overwrite the class version in some cases
44 self.tools = listify(kwargs.get('tools', self.tools))
45 if not self.tool_name:
46 self.tool_name = self.tools[0]
47 if 'version_arg' in kwargs:
48 self.version_arg = kwargs['version_arg']
49
50 req_version = kwargs.get('version', [])
51 tool, version = self.find_config(req_version, kwargs.get('returncode_value', 0), exclude_paths=exclude_paths)
52 self.config = tool
53 self.is_found = self.report_config(version, req_version)
54 if not self.is_found:
55 self.config = None
56 return
57 self.version = version
58
59 def _sanitize_version(self, version: str) -> str:
60 """Remove any non-numeric, non-point version suffixes."""
61 m = self.__strip_version.match(version)
62 if m:
63 # Ensure that there isn't a trailing '.', such as an input like
64 # `1.2.3.git-1234`
65 return m.group(0).rstrip('.')
66 return version
67
68 def _check_and_get_version(self, tool: T.List[str], returncode: int) -> T.Tuple[bool, T.Union[str, None]]:
69 """Check whether a command is valid and get its version"""
70 p, out = Popen_safe(tool + [self.version_arg])[:2]
71 valid = True
72 if p.returncode != returncode:
73 if self.skip_version:
74 # maybe the executable is valid even if it doesn't support --version
75 p = Popen_safe(tool + [self.skip_version])[0]
76 if p.returncode != returncode:
77 valid = False
78 else:
79 valid = False
80 version = self._sanitize_version(out.strip())
81 return valid, version
82
83 def find_config(self, versions: T.List[str], returncode: int = 0, exclude_paths: T.Optional[T.List[str]] = None) \
84 -> T.Tuple[T.Optional[T.List[str]], T.Optional[str]]:
85 """Helper method that searches for config tool binaries in PATH and
86 returns the one that best matches the given version requirements.
87 """
88 exclude_paths = [] if exclude_paths is None else exclude_paths
89 best_match: T.Tuple[T.Optional[T.List[str]], T.Optional[str]] = (None, None)
90 for potential_bin in find_external_program(
91 self.env, self.for_machine, self.tool_name,
92 self.tool_name, self.tools, exclude_paths=exclude_paths,
93 allow_default_for_cross=self.allow_default_for_cross):
94 if not potential_bin.found():
95 continue
96 tool = potential_bin.get_command()
97 try:
98 valid, version = self._check_and_get_version(tool, returncode)
99 except (FileNotFoundError, PermissionError):
100 continue
101 if not valid:
102 continue
103
104 # Some tools, like pcap-config don't supply a version, but also
105 # don't fail with --version, in that case just assume that there is
106 # only one version and return it.
107 if not version:
108 return (tool, None)
109 if versions:
110 is_found = version_compare_many(version, versions)[0]
111 # This allows returning a found version without a config tool,
112 # which is useful to inform the user that you found version x,
113 # but y was required.
114 if not is_found:
115 tool = None
116 if best_match[1]:
117 if version_compare(version, '> {}'.format(best_match[1])):
118 best_match = (tool, version)
119 else:
120 best_match = (tool, version)
121
122 return best_match
123
124 def report_config(self, version: T.Optional[str], req_version: T.List[str]) -> bool:
125 """Helper method to print messages about the tool."""
126
127 found_msg: T.List[T.Union[str, mlog.AnsiDecorator]] = [mlog.bold(self.tool_name), 'found:']
128
129 if self.config is None:
130 found_msg.append(mlog.red('NO'))
131 if version is not None and req_version:
132 found_msg.append(f'found {version!r} but need {req_version!r}')
133 elif req_version:
134 found_msg.append(f'need {req_version!r}')
135 else:
136 found_msg += [mlog.green('YES'), '({})'.format(' '.join(self.config)), version]
137
138 mlog.log(*found_msg)
139
140 return self.config is not None
141
142 def get_config_value(self, args: T.List[str], stage: str, required: bool = False) -> T.List[str]:
143 p, out, err = Popen_safe_logged(self.config + args)
144 if p.returncode != 0:
145 if self.required or required:
146 raise DependencyException(f'Could not generate {stage} for {self.name}.\n{err}')
147 return []
148 return split_args(out)
149
150 def get_variable_args(self, variable_name: str) -> T.List[str]:
151 return [f'--{variable_name}']
152
153 def get_variable(self, *, cmake: T.Optional[str] = None, pkgconfig: T.Optional[str] = None,
154 configtool: T.Optional[str] = None, internal: T.Optional[str] = None,
155 system: T.Optional[str] = None, default_value: T.Optional[str] = None,
156 pkgconfig_define: PkgConfigDefineType = None) -> str:
157 if configtool:
158 p, out, _ = Popen_safe(self.config + self.get_variable_args(configtool))
159 if p.returncode == 0:
160 variable = out.strip()
161 mlog.debug(f'Got config-tool variable {configtool} : {variable}')
162 return variable
163 if default_value is not None:
164 return default_value
165 raise DependencyException(f'Could not get config-tool variable and no default provided for {self!r}')