1 /*
<lambda>null2  * Copyright (C) 2022 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 package com.android.tools.metalava.apilevels
17 
18 import com.android.SdkConstants
19 import com.android.SdkConstants.PLATFORM_WINDOWS
20 import java.io.File
21 
22 class ExtensionSdkJarReader() {
23 
24     companion object {
25         private val REGEX_JAR_PATH = run {
26             var pattern = ".*/(\\d+)/[^/]+/(.*)\\.jar$"
27             if (SdkConstants.currentPlatform() == PLATFORM_WINDOWS) {
28                 pattern = pattern.replace("/", "\\\\")
29             }
30             Regex(pattern)
31         }
32 
33         /**
34          * Find extension SDK jar files in an extension SDK tree.
35          *
36          * @return a mapping SDK jar file -> list of VersionAndPath objects, sorted from earliest to
37          *   last version
38          */
39         fun findExtensionSdkJarFiles(
40             root: File,
41             skipVersionsGreaterThan: Int?
42         ): Map<String, List<VersionAndPath>> {
43             val map = mutableMapOf<String, MutableList<VersionAndPath>>()
44             root
45                 .walk()
46                 .maxDepth(3)
47                 .mapNotNull { file ->
48                     REGEX_JAR_PATH.matchEntire(file.path)?.groups?.let { groups ->
49                         Triple(groups[2]!!.value, groups[1]!!.value.toInt(), file)
50                     }
51                 }
52                 .filter {
53                     if (skipVersionsGreaterThan != null) {
54                         it.second <= skipVersionsGreaterThan
55                     } else {
56                         true
57                     }
58                 }
59                 .sortedBy { it.second }
60                 .forEach {
61                     map.getOrPut(it.first) { mutableListOf() }
62                         .add(VersionAndPath(it.second, it.third))
63                 }
64             return map
65         }
66     }
67 }
68 
69 data class VersionAndPath(@JvmField val version: Int, @JvmField val path: File)
70