xref: /aosp_15_r20/external/grpc-grpc/tools/run_tests/sanity/check_include_style.py (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1#!/usr/bin/env python3
2
3# Copyright 2021 gRPC authors.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17import os
18import re
19import sys
20
21os.chdir(os.path.join(os.path.dirname(sys.argv[0]), "../../.."))
22
23BAD_REGEXES = [
24    (r'\n#include "include/(.*)"', r"\n#include <\1>"),
25    (r'\n#include "grpc(.*)"', r"\n#include <grpc\1>"),
26]
27
28fix = sys.argv[1:] == ["--fix"]
29if fix:
30    print("FIXING!")
31
32
33def check_include_style(directory_root):
34    bad_files = []
35    for root, dirs, files in os.walk(directory_root):
36        for filename in files:
37            path = os.path.join(root, filename)
38            if os.path.splitext(path)[1] not in [".c", ".cc", ".h"]:
39                continue
40            if filename.endswith(".pb.h") or filename.endswith(".pb.c"):
41                continue
42            # Skip check for upb generated code.
43            if (
44                filename.endswith(".upb.h")
45                or filename.endswith(".upbdefs.h")
46                or filename.endswith(".upbdefs.c")
47            ):
48                continue
49            with open(path) as f:
50                text = f.read()
51            original = text
52            for regex, replace in BAD_REGEXES:
53                text = re.sub(regex, replace, text)
54            if text != original:
55                bad_files.append(path)
56                if fix:
57                    with open(path, "w") as f:
58                        f.write(text)
59    return bad_files
60
61
62all_bad_files = []
63all_bad_files += check_include_style(os.path.join("src", "core"))
64all_bad_files += check_include_style(os.path.join("src", "cpp"))
65all_bad_files += check_include_style(os.path.join("test", "core"))
66all_bad_files += check_include_style(os.path.join("test", "cpp"))
67all_bad_files += check_include_style(os.path.join("include", "grpc"))
68all_bad_files += check_include_style(os.path.join("include", "grpcpp"))
69
70if all_bad_files:
71    for f in all_bad_files:
72        print("%s has badly formed grpc system header files" % f)
73    sys.exit(1)
74