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.tools.metalava.apilevels 18 19 import com.google.gson.GsonBuilder 20 import java.io.File 21 import java.io.PrintStream 22 23 /** 24 * Handles converting an [Api] to a JSON version history file. 25 * 26 * @param apiVersionNames The names of the API versions, ordered starting from version 1. 27 */ 28 internal class ApiJsonPrinter(private val apiVersionNames: List<String>) { 29 /** Writes the [api] as JSON to the [outputFile] */ printnull30 fun print(api: Api, outputFile: File) { 31 val gson = GsonBuilder().disableHtmlEscaping().create() 32 val json = api.toJson() 33 val printStream = PrintStream(outputFile) 34 gson.toJson(json, printStream) 35 } 36 <lambda>null37 private fun Api.toJson() = classes.map { it.toJson() } 38 toJsonnull39 private fun ApiClass.toJson() = 40 toJson("class") + 41 mapOf( 42 "methods" to methods.map { it.toJson("method") }, <lambda>null43 "fields" to fields.map { it.toJson("field") } 44 ) 45 toJsonnull46 private fun ApiElement.toJson(elementType: String) = 47 mapOf( 48 elementType to name, 49 "addedIn" to nameForVersion(since), 50 "deprecatedIn" to 51 if (isDeprecated) { 52 nameForVersion(deprecatedIn) 53 } else { 54 null 55 } 56 ) 57 58 // Indexing is offset by 1 because 0 is not a valid API level nameForVersionnull59 private fun nameForVersion(level: Int) = apiVersionNames[level - 1] 60 } 61