1 /*
2  * Copyright (C) 2019 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.ndkports
18 
19 import java.io.File
20 
21 data class NdkVersion(
22     val major: Int,
23     val minor: Int,
24     val build: Int,
25     val qualifier: String?
26 ) {
27     companion object {
28         private val pkgRevisionRegex = Regex("""^Pkg.Revision\s*=\s*(\S+)$""")
29         private val versionRegex = Regex("""^(\d+).(\d+).(\d+)(?:-(\S+))?$""")
30 
fromStringnull31         private fun fromString(versionString: String): NdkVersion {
32             val match = versionRegex.find(versionString)
33             require(match != null) { "Invalid version string" }
34             val (major, minor, build, qualifier) = match.destructured
35             return NdkVersion(
36                 major.toInt(),
37                 minor.toInt(),
38                 build.toInt(),
39                 qualifier.takeIf { match.groups[4] != null }
40             )
41         }
42 
fromSourcePropertiesTextnull43         fun fromSourcePropertiesText(text: String): NdkVersion {
44             for (line in text.lines().map { it.trim() }) {
45                 pkgRevisionRegex.find(line)?.let {
46                     return fromString(it.groups.last()!!.value)
47                 }
48             }
49             throw RuntimeException(
50                 "Did not find Pkg.Revision in source.properties"
51             )
52         }
53 
fromNdknull54         fun fromNdk(ndk: File): NdkVersion = fromSourcePropertiesText(
55             ndk.resolve("source.properties").readText()
56         )
57     }
58 }