1 /*
<lambda>null2  * Copyright 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 
17 package androidx.build.importMaven
18 
19 import java.util.function.Supplier
20 import okio.Path
21 import org.gradle.api.artifacts.Configuration
22 import org.gradle.api.internal.artifacts.ImmutableVersionConstraint
23 import org.gradle.api.internal.catalog.parser.TomlCatalogFileParser
24 import org.gradle.api.plugins.catalog.VersionCatalogPlugin.GRADLE_PLATFORM_DEPENDENCIES
25 import org.gradle.api.plugins.catalog.internal.DependenciesAwareVersionCatalogBuilder
26 import org.gradle.internal.impldep.com.google.common.collect.Interners
27 
28 /**
29  * Loads all versions from a version catalog file.
30  * see [ImportToml].
31  */
32 object ImportVersionCatalog {
33     /**
34      * Loads a gradle version file and returns all artifacts declared in it.
35      */
36     fun load(file: Path): List<String> {
37         val project = ProjectService.createProject()
38         val configurations = project.configurations.create(
39             GRADLE_PLATFORM_DEPENDENCIES
40         ) { cnf: Configuration ->
41             cnf.isVisible = false
42             cnf.isCanBeConsumed = false
43             cnf.isCanBeResolved = false
44         }
45 
46         val catalogBuilder = project.objects.newInstance(
47             DependenciesAwareVersionCatalogBuilder::class.java,
48             "loader",
49             Interners.newStrongInterner<String>(),
50             Interners.newStrongInterner< ImmutableVersionConstraint>(),
51             project.objects,
52             Supplier { error("Not supported") },
53             configurations
54         )
55         TomlCatalogFileParser.parse(
56             file.toNioPath(),
57             catalogBuilder
58         ) { error("Not supported") }
59         val built = catalogBuilder.build()
60         return built.libraryAliases.map { alias ->
61             val dep = built.getDependencyData(alias)
62             "${dep.group}:${dep.name}:${dep.version.requiredVersion}"
63         }
64     }
65 }
66