1#  Copyright (C) 2023 The Android Open Source Project
2#
3#  Licensed under the Apache License, Version 2.0 (the "License");
4#  you may not use this file except in compliance with the License.
5#  You may obtain a copy of the License at
6#
7#       http://www.apache.org/licenses/LICENSE-2.0
8#
9#  Unless required by applicable law or agreed to in writing, software
10#  distributed under the License is distributed on an "AS IS" BASIS,
11#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12#  See the License for the specific language governing permissions and
13#  limitations under the License.
14
15import os
16
17rootDir = os.getenv("ANDROID_BUILD_TOP")
18
19# Method signatures to be removed.
20# Currently, only java.lang.Object methods do not need @ApiRequirements or AddedInOrBefore annotations.
21methods = {
22    "public boolean equals",
23    "public int hashCode",
24    "public String toString",
25    "protected void finalize",
26    "protected Object clone"
27}
28
29# Checks if the annotated method is a JDK method that should have its annotation removed.
30# There could be multiple annotations, so an arbitrary look-ahead of 6 lines was selected.
31def is_exempt(lines, index):
32    i = index
33    while i < len(lines) and i < index + 6:
34        for method in methods:
35            if method in lines[i]:
36                return True
37        i += 1
38    return False
39
40def delete_text_from_files(directory):
41    if not os.path.isdir(directory):
42        return
43
44    for file_name in os.listdir(directory):
45        file_path = os.path.join(directory, file_name)
46
47        if os.path.isfile(file_path):
48            remove_api_requirements(file_path)
49            delete_text_from_files(file_path)
50
51        if os.path.isdir(file_path):
52            delete_text_from_files(file_path)
53
54def remove_api_requirements(file_path):
55    with open(file_path, 'r+') as f:
56        lines = f.readlines()
57        f.seek(0)
58
59        for index, line in enumerate(lines):
60            # List of annotation string matches.
61            if any((annotation in line) for annotation in
62                   ['@ApiRequirements(', 'minCarVersion', 'minPlatformVersion',
63                    '@AddedInOrBefore(majorVersion']):
64                if is_exempt(lines, index):
65                    continue
66            f.write(line)
67
68        f.truncate()
69
70    f.close()
71
72delete_text_from_files(rootDir + "/packages/services/Car/car-lib")