File: run_presubmits.py

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (347 lines) | stat: -rwxr-xr-x 12,475 bytes parent folder | download | duplicates (3)
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
#!/usr/bin/env vpython3

# Copyright 2025 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# This script checks for issues in the following files and directories
# (including interactions between them):
#
# * `//third_party/rust/chromium_crates_io/Cargo.lock` and
# * `//third_party/rust/chromium_crates_io/gnrt_config.toml`.
# * `//third_party/rust/chromium_crates_io/patches/`.
#
# We don't surface these issues earlier (by reporting a fatal error from `gnrt
# vendor`, `gnrt gen`, `gn gen`, or failing the builds), because we want to
# avoid friction when new teams experiment with using Rust.  Some of these
# issues may also happen during the crate update rotation and in this case we
# want to allow the `tools/crate/create_update_cl.py` to continue creating CLs
# (that other script uses `git cl upload ... --bypass-hooks`).
#
# This script is typically not invoked directly, but instead is invoked as part
# of `//third_party/rust/PRESUBMIT.py`

import os
import sys
import toml

import crate_utils

GNRT_CONFIG_RELATIVE_PATH = "third_party/rust/chromium_crates_io/gnrt_config.toml"
GNRT_CONFIG_PATH = os.path.join(crate_utils.CHROMIUM_DIR,
                                GNRT_CONFIG_RELATIVE_PATH)
CARGO_TOML_RELATIVE_PATH = "third_party/rust/chromium_crates_io/Cargo.toml"
CARGO_TOML_FILEPATH = os.path.join(crate_utils.CHROMIUM_DIR,
                                   CARGO_TOML_RELATIVE_PATH)
PATCHES_DIR = os.path.join(crate_utils.CRATES_DIR, "patches")


def _GetCratesConfigDict(gnrt_config):
    if gnrt_config and isinstance(gnrt_config, dict):
        crates = gnrt_config.get("crate")
        if crates and isinstance(crates, dict):
            return crates
    return dict()


def _GetCrateConfigForCrateName(crate_name, gnrt_config):
    crates = _GetCratesConfigDict(gnrt_config)
    crate_cfg = crates.get(crate_name)
    if crate_cfg and isinstance(crate_cfg, dict):
        return crate_cfg
    return dict()


def _GetRealCrateNames(crate_ids):
    non_placeholder_crate_ids = filter(
        lambda crate_id: not crate_utils.IsPlaceholderCrate(crate_id),
        crate_ids)
    return set(
        map(crate_utils.ConvertCrateIdToCrateName, non_placeholder_crate_ids))


def _GetExtraKvForCrateName(crate_name, gnrt_config):
    crate_cfg = _GetCrateConfigForCrateName(crate_name, gnrt_config)
    extra_kv = crate_cfg.get("extra_kv")
    if extra_kv and isinstance(extra_kv, dict):
        return extra_kv
    return dict()


def _CheckTomlTableIsSorted(toml_table):
    """Checks whether the entries in `cargo_toml` are sorted.

       Returns an error message if a problem is detected.
       Returns an empty string if there are no problems.
    """
    assert isinstance(toml_table, dict)

    # The following toml:
    #
    #     ```
    #     [toml_table]
    #     bar = "4.5.6"
    #     foo = "1.2.3"
    #
    #     [toml_table.baz]
    #     version = "7.8.9"
    #     ```
    #
    # Will result in:
    #
    # * `simple_keys == ['bar', 'foo']`
    # * `elaborate_keys == ['baz']`
    simple_keys = []
    elaborate_keys = []
    first_elaborate_key = None
    for (key, value) in toml_table.items():
        if not isinstance(value, str):
            first_elaborate_key = key
        if first_elaborate_key:
            if isinstance(value, str):
                return ("Simple string entries should appear before table "
                        f"entries: `{key}` should appear after "
                        f"`{first_elaborate_key}`.")
            elaborate_keys.append(key)
        else:
            simple_keys.append(key)

    for a, b in zip(simple_keys, simple_keys[1:]):
        if a > b:
            return f"`{b}` should appear before `{a}`."
    for a, b in zip(elaborate_keys, elaborate_keys[1:]):
        if a > b:
            return f"`{b}` should appear before `{a}`."

    return ""


def CheckCargoTomlIsSorted(crate_toml):
    """Checks whether the entries in `cargo_toml` are sorted.

       This tries to implement a subset of ordering behavior of `cargo-sort`.

       Returns an error message if a problem is detected.
       Returns an empty string if there are no problems.
    """
    deps = crate_toml.get("dependencies", None)
    if not isinstance(deps, dict):
        return "Malformed `Cargo.toml` file?  `dependencies` is not a table."
    problem = _CheckTomlTableIsSorted(deps)
    if problem:
        return ("Please sort `[dependencies]` table in "
                f"`{CARGO_TOML_RELATIVE_PATH}`.  Example problem: {problem}")

    return ""


def CheckGnrtConfigTomlIsSorted(_crate_ids, gnrt_config):
    """Checks whether the entries in `gnrt_config.toml` are sorted.

       Returns an error message if a problem is detected.
       Returns an empty string if there are no problems.
    """
    crates = _GetCratesConfigDict(gnrt_config)
    problem = _CheckTomlTableIsSorted(crates)
    if problem:
        return ("Please sort `[crates]` table in "
                f"`{GNRT_CONFIG_RELATIVE_PATH}`.  Example problem: {problem}")

    return ""


def CheckNonapplicableGnrtConfigEntries(crate_ids, gnrt_config):
    """Checks that each crate entry in `gnrt_config.toml` corresponds
       to an actual depedency of `chromium_crates_io/Cargo.toml`.

       Returns an error message if a problem is detected.
       Returns an empty string if there are no problems.
    """
    real_crate_names = _GetRealCrateNames(crate_ids)

    crates_cfg_dict = _GetCratesConfigDict(gnrt_config)
    configured_crate_names = set(crates_cfg_dict.keys())

    nonapplicable_config_entries = configured_crate_names - real_crate_names
    if nonapplicable_config_entries:
        return (f"Some entries in `{GNRT_CONFIG_RELATIVE_PATH}` are not "
                "needed, because they don't apply to actual crates: "
                f'{", ".join(sorted(nonapplicable_config_entries))}')

    return ""


def CheckNonapplicablePatches(crate_ids, gnrt_config):
    """Checks that each directory under `chromium_crates_io/patches/`
       corresponds to an actual depedency of `chromium_crates_io/Cargo.toml`.

       Returns an error message if a problem is detected.
       Returns an empty string if there are no problems.
    """
    real_crate_names = _GetRealCrateNames(crate_ids)

    patched_crate_names = set(
        filter(lambda filename: filename != "README.md",
               os.listdir(PATCHES_DIR)))

    nonapplicable_patches = patched_crate_names - real_crate_names
    if nonapplicable_patches:
        return (f"Some files/directories under `{PATCHES_DIR}` are not "
                "needed, because they don't apply to actual crates: "
                f'{", ".join(sorted(nonapplicable_patches))}')

    return ""


def CheckNonapplicablePatches(crate_ids, gnrt_config):
    """Checks that each directory under `chromium_crates_io/patches/`
       corresponds to an actual depedency of `chromium_crates_io/Cargo.toml`.

       Returns an error message if a problem is detected.
       Returns an empty string if there are no problems.
    """
    real_crate_names = _GetRealCrateNames(crate_ids)

    patched_crate_names = set(
        filter(lambda filename: filename != "README.md",
               os.listdir(PATCHES_DIR)))

    nonapplicable_patches = patched_crate_names - real_crate_names
    if nonapplicable_patches:
        return f"Some files/directories under `{PATCHES_DIR}` are not " + \
                "needed, because they don't apply to actual crates: " + \
               f'{", ".join(sorted(nonapplicable_patches))}'

    return ""


def CheckExplicitAllowUnsafeForAllCrates(crate_ids, gnrt_config):
    """Checks that `gnrt_config.toml` has `allow_unsafe = ...` for each crate.

       Returns an error message if a problem is detected.
       Returns an empty string if there are no problems.
    """
    result = []
    for crate_id in sorted(crate_ids):
        crate_name = crate_utils.ConvertCrateIdToCrateName(crate_id)

        # Ignore the root package and placeholder crates.
        if crate_name == "chromium": continue
        if crate_utils.IsPlaceholderCrate(crate_id): continue

        # Ignore crates that specify `allow_unsafe`.
        extra_kv = _GetExtraKvForCrateName(crate_name, gnrt_config)
        if "allow_unsafe" in extra_kv:
            continue

        # Report a problem for all other crates.
        if not result:  # Is is the **first** problematic `crate_name`?
            result.append("ERROR: Please ensure that `gnrt_config.toml` "
                          "explicitly specifies `allow_unsafe = ...` for all "
                          "crates that `chromium_crates_io` depends on.  "
                          "This helps `//third_party/rust/OWNERS` to check at "
                          "a glance if a given crate contains `unsafe` Rust "
                          "code.")
            result.append("")
        result += [
            f"    [crate.{crate_name}.extra_kv]",
            f"    allow_unsafe = false (or true if needed)",
        ]

    return "\n".join(result)


def CheckMultiversionCrates(crate_ids, gnrt_config):
    """Checks that a bug tracks each crate with multiple versions.

       This check has been discussed in https://crbug.com/404867240.  Having 2
       or more different versions of a crate in Chromium's dependency tree is
       undesirable in general.  So we want to detect when a 2nd version is
       imported, and require opening a bug + recording the bug in
       `gnrt_config.toml` for the given crate.

       Returns an error message if a problem is detected.
       Returns an empty string if there are no problems.
    """

    # Group `crate_id`s by their `crate_name`.
    crate_name_to_list_of_crate_ids = dict()
    for crate_id in crate_ids:
        crate_name = crate_utils.ConvertCrateIdToCrateName(crate_id)
        if crate_name not in crate_name_to_list_of_crate_ids:
            crate_name_to_list_of_crate_ids[crate_name] = []
        crate_name_to_list_of_crate_ids[crate_name] += [crate_id]

    result = []
    for (crate_name, crate_ids) in crate_name_to_list_of_crate_ids.items():
        # Ignore crates where we depend only on a single version.
        if len(crate_ids) == 1:
            continue

        # Ignore crates that already have a bug to track cleaning up a
        # multiversion situation.
        extra_kv = _GetExtraKvForCrateName(crate_name, gnrt_config)
        if "multiversion_cleanup_bug" in extra_kv:
            continue

        # Report a problem for other multiversion crates.
        if not result:  # Is is the **first** problematic `crate_name`?
            result.append("ERROR: Transitive dependency graph includes "
                          "multiple versions of the same crate.  Please "
                          "open a bug to track removing one of the "
                          "versions and put a link to the bug into "
                          "`gnrt_config.toml` like this:")
            result.append("")

        result += [
            f"    # TODO: Remove multiple versions of the `{crate_name}` crate:",
            f"    # {', '.join(sorted(crate_ids))}",
            f"    [crate.{crate_name}.extra_kv]",
            f'    multiversion_cleanup_bug = "https://crbug.com/<bug number>"\n',
        ]

    return "\n".join(result)


def main():
    success = True

    def CheckResult(result):
        nonlocal success
        if result:
            if not success:
                # Add a separator if this is a 2nd, 3rd, or later problem.
                print()
                print("-" * 72)
                print()
            success = False
            print(result)

    with open(CARGO_TOML_FILEPATH) as f:
        cargo_toml = toml.load(f)
        result = CheckCargoTomlIsSorted(cargo_toml)
        CheckResult(result)

    crate_ids = crate_utils.GetCurrentCrateIds()
    gnrt_config = toml.load(open(GNRT_CONFIG_PATH))

    def RunChecks(check_impl):
        nonlocal crate_ids
        nonlocal gnrt_config
        result = check_impl(crate_ids, gnrt_config)
        CheckResult(result)

    RunChecks(CheckGnrtConfigTomlIsSorted)
    RunChecks(CheckExplicitAllowUnsafeForAllCrates)
    RunChecks(CheckMultiversionCrates)
    RunChecks(CheckNonapplicableGnrtConfigEntries)
    RunChecks(CheckNonapplicablePatches)

    if success:
        return 0
    else:
        return -1


if __name__ == '__main__':
    sys.exit(main())