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 15# This script will find the instances where assertPlatformVersionAtLeast does not exist or has the wrong version and add the correct version. 16# Usage: python add_assertPlatformVersionAtLeast.py /ssd/udc-dev 17 18import os 19import sys 20import subprocess 21 22platformVersion_import_statement = "import static com.android.car.internal.util.VersionUtils.assertPlatformVersionAtLeastU;\n" 23 24rootDir = os.getenv("ANDROID_BUILD_TOP") 25if rootDir is None or rootDir == "": 26 # env variable is not set. Then use the arg passed as Git root 27 rootDir = sys.argv[1] 28 29java_cmd= "java -jar " + rootDir + "/packages/services/Car/tools/GenericCarApiBuilder" \ 30 "/GenericCarApiBuilder.jar " \ 31 "--platform-version-assertion-check " \ 32 "--root-dir " + rootDir 33 34output = subprocess.check_output(java_cmd, shell=True).decode('utf-8').strip().split("\n") 35 36import_added = [] 37new_lines = dict() 38 39apis = dict() 40 41for api in output: 42 tokens = api.strip().split("|") 43 line_number, filepath = int(tokens[1].strip()), tokens[2].strip() 44 45 if filepath not in apis: 46 apis[filepath] = [] 47 48 apis[filepath].append(line_number) 49 50 51for filepath, line_numbers in apis.items(): 52 apis[filepath] = sorted(apis[filepath]) 53 54for filepath, api_line_numbers in apis.items(): 55 for line_number in api_line_numbers: 56 # Check how much we need to offset the new_lines by 57 if filepath not in new_lines: 58 new_lines[filepath] = 0 59 60 new_lines[filepath] += 1 61 62 line_number = line_number + new_lines[filepath] - 2 63 64 with open(filepath, "r") as f: 65 lines = f.readlines() 66 67 # Add assertPlatformVersionAtLeastU wherever it is missing. 68 line = lines[line_number] 69 indent_spaces = len(line) - len(line.lstrip()) 70 lines.insert(line_number, indent_spaces * " " + "assertPlatformVersionAtLeastU();\n") 71 72 for i, line in enumerate(lines): 73 if line.startswith("import") and filepath not in import_added: 74 lines.insert(i, platformVersion_import_statement) 75 import_added.append(filepath) 76 new_lines[filepath] += 1 77 break 78 79 with open(filepath, "w") as file: 80 for line in lines: 81 file.write(line) 82