xref: /aosp_15_r20/platform_testing/libraries/flicker/utils/src/android/tools/scripts/ProtoDefToKotlinVals.kt (revision dd0948b35e70be4c0246aabd6c72554a5eb8b22a)
1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.common.scripts
18 
19 /**
20  * The purpose of this script is to aid in creating flicker representations of proto objects by
21  * transforming a property/variable from its proto definition format to its Kotlin format.
22  *
23  * Example: From a proto definition file, we have a property 'optional bool views_created = 1; ' We
24  * want the output to be 'val viewsCreated: Boolean,' This should work for multi-line input, where
25  * each line is one proto property.
26  *
27  * Usage: install kotlin on terminal and build into a jar file using the command `kotlinc
28  * proto_def_to_kotlin_vals.kt -include-runtime -d <outputFileName.jar>` then running the output jar
29  * file with `java -jar <outputFileName.jar> "<input string>"`
30  */
mapProtoTypeToKotlinTypenull31 fun mapProtoTypeToKotlinType(type: String): String? {
32     val mapOfKnownProtoToKotlinTypes =
33         mapOf("bool" to "Boolean", "int32" to "Int", "string" to "String")
34     if (mapOfKnownProtoToKotlinTypes.containsKey(type)) return mapOfKnownProtoToKotlinTypes[type]
35 
36     if (type.contains("Proto")) return type.removeSuffix("Proto")
37 
38     return type
39 }
40 
41 val snakeRegex = "_[a-zA-Z]".toRegex()
42 
snakeToLowerCamelCasenull43 fun String.snakeToLowerCamelCase(): String {
44     return snakeRegex.replace(this) { it.value.replace("_", "").uppercase() }
45 }
46 
mainnull47 fun main(args: Array<String>) {
48     val splitByNewLine = mutableListOf<String>()
49     for (arg in args) {
50         splitByNewLine.addAll(arg.split("\n")) // to work with multi-line proto properties
51     }
52     for (s in splitByNewLine) {
53         val editedS = s.trim().removePrefix("optional ")
54         // bool views_created = 1;
55         val removedNumber = editedS.split("=")[0].trim() // bool views_created
56         val splitBySpace = removedNumber.split(" ") // [bool, views_created]
57         val kotlinType = mapProtoTypeToKotlinType(splitBySpace[0])
58         val kotlinName = splitBySpace[1].snakeToLowerCamelCase()
59         println("val $kotlinName: $kotlinType,")
60     }
61 }
62