summaryrefslogtreecommitdiff
path: root/tools/check_curl_symbols.py
blob: 3aecb206ff2ccaf4d10bd170c40184dd1449d46e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#!/usr/bin/env python3
#
# Copyright (C) 2023-2024 Sébastien Helleu <flashcode@flashtux.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#

"""
Check if Curl symbols defined in src/core/wee-url.c are matching symbols
defined in Curl (introduced/deprecated/last versions), using this file:
https://github.com/curl/curl/blob/master/docs/libcurl/symbols-in-versions.

File symbols-in-versions must be passed as stdin to the script.

Usage example:

```
URL=https://raw.githubusercontent.com/curl/curl/master/docs/libcurl/symbols-in-versions
curl $URL | ./check_curl_symbols.py
```

Or with Curl repository cloned locally:

```
./check_curl_symbols.py < /path/to/curl/docs/libcurl/symbols-in-versions
```

This script requires Python 3.7+.
"""

from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, TextIO, Tuple

import re
import sys

SRC_PATH = (
    Path(__file__).resolve().parent.parent / "src" / "core" / "wee-url.c"
)

WEECHAT_CURL_MIN_VERSION_RE = (
    r"#if LIBCURL_VERSION_NUM >= (?P<hex_min_version>0x[0-9A-F]+) "
    r"/\* (?P<str_min_version>[0-9][0-9.]+) \*/"
)

WEECHAT_CURL_MIN_MAX_VERSION_RE = (
    r"#if LIBCURL_VERSION_NUM >= (?P<hex_min_version>0x[0-9A-F]+) "
    r"&& LIBCURL_VERSION_NUM < (?P<hex_max_version>0x[0-9A-F]+) "
    r"/\* (?P<str_min_version>[0-9][0-9.]+) < "
    r"(?P<str_max_version>[0-9][0-9.]+) \*/"
)
WEECHAT_ENDIF_RE = r"#endif"
WEECHAT_CURL_CONSTANT_RE = (
    r"    URL_DEF_CONST\((?P<prefix>[A-Z0-9_]+), (?P<name>[A-Z0-9_]+)\),"
)
WEECHAT_CURL_OPTION_RE = (
    r"    URL_DEF_OPTION\((?P<name>[A-Z0-9_]+), (?P<type>[A-Z]+)\), "
    r"(?P<values>[A-Za-z0-9_]+)\),"
)
CURL_SYMBOL_RE = r"[A-Z][A-Z0-9_]"


@dataclass
class WeechatCurlSymbol:
    """A Curl symbol declared in WeeChat."""

    name: str
    min_curl: int = 0
    max_curl: int = 0
    line_no: int = 0


def curl_version_to_int(version: str) -> int:
    """
    Convert Curl version as string to integer.

    :param version: version as string (eg: "7.87.0")
    :return: version as integer, eg: 481024 (== 0x075700, 0x57 == 87)
    """
    if version == "-":
        return 0
    result = 0
    items = version.split(".")
    if len(items) < 3:
        items.append("0")
    factor = 0
    for item in reversed(items):
        result += int(item) << factor
        factor += 8
    return result


def curl_version_to_str(version: int) -> str:
    """
    Convert Curl version as integer to string.

    :param version: version as integer, eg: 481024 (0x075700)
    :return: version as string, eg: "7.87.0"
    """
    if version == 0:
        return "-"
    result = ""
    while version > 0:
        result = str(version & 0xFF) + "." + result
        version = version >> 8
    return result.rstrip(".")


def get_curl_symbols(symbols_file: TextIO) -> Dict[str, Tuple[int, int]]:
    """
    Parse file docs/libcurl/symbols-in-versions from Curl repository.

    :param symbols_file: file with Curl symbols
    :return: Curl symbols as dict: {name: (version_min, version_max)}
    """
    curl_symbol_pattern = re.compile(CURL_SYMBOL_RE)
    symbols: Dict[str, Tuple[int, int]] = {}
    if symbols_file.isatty():
        return symbols
    for line in symbols_file:
        match = re.match(curl_symbol_pattern, line)
        if match:
            name, intro, deprec, last, *_ = (line + " - -").split()
            v_max = last if last != "-" else deprec
            symbols[name] = (
                curl_version_to_int(intro),
                curl_version_to_int(v_max),
            )
    return symbols


def get_weechat_curl_symbols() -> Tuple[List[WeechatCurlSymbol], int]:
    """
    Parse Curl symbols declared in src/core/wee-url.c.

    :return: tuple (list_symbols, errors)
    """
    # pylint: disable=too-many-locals,too-many-statements
    min_version_pattern = re.compile(WEECHAT_CURL_MIN_VERSION_RE)
    min_max_version_pattern = re.compile(WEECHAT_CURL_MIN_MAX_VERSION_RE)
    endif_pattern = re.compile(WEECHAT_ENDIF_RE)
    constant_pattern = re.compile(WEECHAT_CURL_CONSTANT_RE)
    option_pattern = re.compile(WEECHAT_CURL_OPTION_RE)
    v_min: int = 0
    v_max: int = 0
    symbols: List[WeechatCurlSymbol] = []
    errors: int = 0
    line_no: int = 0
    with open(SRC_PATH, encoding="utf-8") as src_file:
        for line in src_file:
            line_no += 1
            # min Curl version
            match = re.match(min_version_pattern, line)
            if match:
                hex_min_vers = match["hex_min_version"]
                str_min_vers = match["str_min_version"]
                v_min, v_max = int(hex_min_vers, 0), 0
                comment_min = curl_version_to_int(str_min_vers)
                if v_min != comment_min:
                    print(
                        f"{SRC_PATH}:{line_no}: min version not matching "
                        f"the comment: "
                        f"{hex_min_vers} != {str_min_vers}"
                    )
                    errors += 1
                continue
            # min + max Curl version
            match = re.match(min_max_version_pattern, line)
            if match:
                hex_min_vers = match["hex_min_version"]
                hex_max_vers = match["hex_max_version"]
                str_min_vers = match["str_min_version"]
                str_max_vers = match["str_max_version"]
                v_min, v_max = int(hex_min_vers, 0), int(hex_max_vers, 0)
                comment_min = curl_version_to_int(str_min_vers)
                comment_max = curl_version_to_int(str_max_vers)
                if v_min != comment_min:
                    print(
                        f"{SRC_PATH}:{line_no}: min version not matching "
                        f"the comment: "
                        f"{hex_min_vers} != {str_min_vers}"
                    )
                    errors += 1
                if v_max != comment_max:
                    print(
                        f"{SRC_PATH}:{line_no}: max version not matching "
                        f"the comment: "
                        f"{hex_max_vers} != {str_max_vers}"
                    )
                    errors += 1
                continue
            # end of min/max Curl version
            match = re.match(endif_pattern, line)
            if match:
                v_min, v_max = 0, 0
                continue
            # Curl constant
            match = re.match(constant_pattern, line)
            if match:
                name = f"CURL{match['prefix']}_{match['name']}"
                symbols.append(WeechatCurlSymbol(name, v_min, v_max, line_no))
                continue
            # Curl option
            match = re.match(option_pattern, line)
            if match:
                symbols.append(
                    WeechatCurlSymbol(match["name"], v_min, v_max, line_no)
                )
                continue
    return symbols, errors


def check_symbols(
    weechat_curl_symbols: List[WeechatCurlSymbol],
    curl_symbols: Dict[str, Tuple[int, int]],
) -> int:
    """
    Check that symbols declared are matching Curl symbols.

    :param weechat_curl_symbols: list of Curl symbols in WeeChat
    :param curl_symbols: list of all Curl symbols
    """
    to_str = curl_version_to_str
    errors = 0
    for symbol in weechat_curl_symbols:
        curl_symbol = curl_symbols.get(symbol.name)
        if not curl_symbol:
            print(
                f"{SRC_PATH}:{symbol.line_no}: symbol {symbol.name} "
                f"not found in Curl"
            )
            errors += 1
            continue
        if symbol.min_curl != curl_symbol[0]:
            print(
                f"{SRC_PATH}:{symbol.line_no}: min version for "
                f"symbol {symbol.name} differs: "
                f"{to_str(symbol.min_curl)} in WeeChat, "
                f"{to_str(curl_symbol[0])} in Curl"
            )
            errors += 1
        if symbol.max_curl != curl_symbol[1]:
            print(
                f"{SRC_PATH}:{symbol.line_no}: max version for "
                f"symbol {symbol.name} differs: "
                f"{to_str(symbol.max_curl)} in WeeChat, "
                f"{to_str(curl_symbol[1])} in Curl"
            )
            errors += 1
    return errors


def main() -> int:
    """Check Curl symbols and return the number of errors found."""
    curl_symbols = get_curl_symbols(sys.stdin)
    if not curl_symbols:
        sys.exit("FATAL: failed to read Curl symbols on standard input")
    weechat_curl_symbols, errors = get_weechat_curl_symbols()
    errors += check_symbols(weechat_curl_symbols, curl_symbols)
    dict_err = {0: "all good!", 1: "1 error"}
    print("Curl symbols:", dict_err.get(errors, f"{errors} errors"))
    return errors


if __name__ == "__main__":
    sys.exit(min(main(), 255))