Debian Codegraph @

python/src/feature_check/obtain.py

raw
1 # SPDX-FileCopyrightText: Peter Pentchev <[email protected]>
2 # SPDX-License-Identifier: BSD-2-Clause
3
4 """Query a program for the list of features that it supports."""
5
6 from __future__ import annotations
7
8 import subprocess # noqa: S404
9 from typing import Final
10
11 from . import defs
12 from . import parser as fparser
13 from . import version as fver
14
15
16 class ObtainError(defs.FCError):
17 """A base class for errors in obtaining the program's features."""
18
19
20 class ObtainExecError(ObtainError):
21 """An error that occurred while executing the queried program."""
22
23 def __init__(self, err: str) -> None:
24 """Initialize an error object."""
25 super().__init__(1, err)
26
27
28 class ObtainNoFeaturesSupportError(ObtainExecError):
29 """The program does not seem to support the "--features" option."""
30
31 def __init__(self, program: str, option: str) -> None:
32 """Store the program name."""
33 super().__init__(
34 f"The {program} program does not seem to support "
35 f"the {option} option for querying features",
36 )
37
38
39 class ObtainNoFeaturesError(ObtainError):
40 """An error that occurred while looking for the features line."""
41
42 def __init__(self, program: str, option: str, prefix: str) -> None:
43 """Initialize an error object."""
44 super().__init__(
45 2,
46 f"The '{program} {option}' output did not contain a single '{prefix}' line",
47 )
48
49
50 def obtain_features(
51 program: str,
52 option: str = defs.DEFAULT_OPTION,
53 prefix: str = defs.DEFAULT_PREFIX,
54 ) -> dict[str, fver.Version]:
55 """Execute the specified program and get its list of features.
56
57 The program is run with the specified query option (default:
58 "--features") and its output is examined for a line starting with
59 the specified prefix (default: "Features: "). The rest of the line
60 is parsed as a whitespace-separated list of either feature names or
61 "name=version" pairs. The function returns a dictionary of the features
62 obtained with their versions (or "1.0" if only a feature name was found
63 in the program's output).
64
65 import feature_check
66
67 data = feature_check.obtain_features("timelimit")
68 print(data.get("subsecond", "not supported"))
69
70 For programs that need a different command-line option to list features:
71
72 import feature_check
73
74 print("SSL" in feature_check.obtain_features("curl",
75 option="--version"))
76 """
77
78 def try_run() -> list[str]:
79 """Query a program about its features, return the output lines."""
80 res: Final = subprocess.run( # noqa: S603
81 [program, option],
82 capture_output=True,
83 check=False,
84 stdin=None,
85 )
86 if res.returncode != 0 or res.stderr.decode():
87 # It does not support '--features', does it?
88 raise ObtainNoFeaturesSupportError(program, option)
89
90 return res.stdout.decode().split("\n")
91
92 try:
93 lines: Final = try_run()
94 except ObtainExecError:
95 raise
96 # Yes, we do want to convert any error into an ObtainExecError one
97 except Exception as exc:
98 # Something went wrong in the --features processing
99 raise ObtainExecError(str(exc)) from exc
100
101 matching: Final = (
102 [
103 rest
104 for line, rest in ((line, line.removeprefix(prefix)) for line in lines)
105 if rest != line
106 ]
107 if prefix
108 else [line for line in lines if line]
109 )
110 if len(matching) != 1:
111 raise ObtainNoFeaturesError(program, option, prefix)
112
113 return fparser.parse_features_line(matching[0])