1 /* 2 * Copyright (C) 2024 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.model.turbine 18 19 import com.google.turbine.tree.Tree.CompUnit 20 import com.google.turbine.tree.Tree.Ident 21 22 /** 23 * Extracts the package name from a provided compilation unit. 24 * 25 * @param unit The compilation unit from which to extract the package. 26 * @return The extracted package name (e.g., "com.example.project"), or an empty string if no 27 * package is present. 28 */ getPackageNamenull29internal fun getPackageName(unit: CompUnit): String { 30 val optPkg = unit.pkg() 31 val pkg = if (optPkg.isPresent()) optPkg.get() else null 32 return pkg?.let { extractNameFromIdent(it.name()) } ?: "" 33 } 34 35 /** 36 * Extracts a dot-separated name from a list of Ident objects. This is often used for constructing 37 * fully qualified names or package structures. 38 * 39 * @param identNameList The list of Ident objects representing name segments. 40 * @return The combined name with segments joined by "." (e.g., "java.util.List") 41 */ extractNameFromIdentnull42internal fun extractNameFromIdent(identNameList: List<Ident>): String { 43 val nameList = identNameList.map { it.value() } 44 return nameList.joinToString(separator = ".") 45 } 46 47 /** 48 * Extracts header comments from a source file string. Header comments are defined as any content 49 * appearing before the "package" keyword. 50 * 51 * @param source The source file string. 52 * @return The extracted header comments, or an empty string if no "package" keyword or comments are 53 * found. 54 */ getHeaderCommentsnull55internal fun getHeaderComments(source: String): String { 56 val packageIndex = source.indexOf("package") 57 // Return everything before "package" keyword 58 return if (packageIndex == -1) "" else source.substring(0, packageIndex) 59 } 60