fix(gradle-plugin): use AGP APIs to configure logsender on debuggable variants

This commit is contained in:
Akash Yadav
2023-08-31 15:52:27 +05:30
parent 1dc537feda
commit 72b383971d
32 changed files with 922 additions and 93 deletions
+12 -28
View File
@@ -222,38 +222,22 @@ tasks.create("generateInitScript") {
it.write(
"""
initscript {
repositories {
maven {
mavenCentral()
// Add snapshots repository for AndroidIDE CI builds
url "https://s01.oss.sonatype.org/content/repositories/snapshots/"
repositories {
maven {
mavenCentral()
google()
// Add snapshots repository for AndroidIDE CI builds
url "https://s01.oss.sonatype.org/content/repositories/snapshots/"
}
}
}
dependencies {
classpath '${BuildConfig.packageName}:gradle-plugin:${downloadVersion}'
}
}
gradle.settingsEvaluated { settings ->
settings.dependencyResolutionManagement.repositories {
// For release builds
mavenCentral()
// For AndroidIDE CI builds
maven { url "https://s01.oss.sonatype.org/content/repositories/snapshots/" }
}
}
gradle.projectsLoaded {
rootProject.subprojects.forEach {sub ->
sub.afterEvaluate {
sub.apply plugin: com.itsaky.androidide.gradle.AndroidIDEGradlePlugin
dependencies {
classpath '${BuildConfig.packageName}:gradle-plugin:${downloadVersion}'
}
}
}
apply plugin: com.itsaky.androidide.gradle.AndroidIDEInitScriptPlugin
"""
.trimIndent()
)
+1
View File
@@ -39,6 +39,7 @@ tasks.create("generateBuildInfo") {
comment = "//",
candidates =
arrayOf(
"PACKAGE_NAME" to BuildConfig.packageName,
"MVN_GROUP_ID" to BuildConfig.packageName,
"VERSION_NAME" to rootProject.version.toString(),
"VERSION_NAME_SIMPLE" to rootProject.simpleVersionName,
@@ -19,6 +19,9 @@ package com.itsaky.androidide.buildinfo;
public class BuildInfo {
// ---------- Basic info -----------------
public static final String PACKAGE_NAME = "@@PACKAGE_NAME@@";
// ---------- Version info ----------------
public static final String MVN_GROUP_ID = "@@MVN_GROUP_ID@@";
+33 -2
View File
@@ -23,9 +23,24 @@ plugins {
description = "Gradle Plugin for projects that are built with AndroidIDE"
tasks.named<Test>("test") {
useJUnitPlatform()
}
tasks.withType<Test> {
dependsOn("publishToMavenLocal")
}
dependencies {
implementation(projects.buildInfo)
implementation(libs.tooling.agp)
implementation(libs.tooling.agpApi)
testImplementation(gradleTestKit())
testImplementation(libs.tests.junit.jupiter)
testImplementation(libs.tests.google.truth)
testImplementation(projects.shared)
testRuntimeOnly(libs.tests.junit.platformLauncher)
}
gradlePlugin {
@@ -33,12 +48,28 @@ gradlePlugin {
vcsUrl.set(ProjectConfig.REPO_URL)
plugins {
create("initScriptPlugin") {
id = "${BuildConfig.packageName}.init.gradle"
implementationClass = "${BuildConfig.packageName}.gradle.AndroidIDEInitScriptPlugin"
displayName = "AndroidIDE Init Script Gradle Plugin"
description = "Init script Gradle plugin for projects that are built with AndroidIDE"
tags.set(setOf("androidide", "init"))
}
create("gradlePlugin") {
id = "${BuildConfig.packageName}.gradle"
implementationClass = "${BuildConfig.packageName}.gradle.AndroidIDEGradlePlugin"
displayName = "AndroidIDE Gradle Plugin"
description = "Gradle plugin for projects that are built with AndroidIDE"
tags.set(setOf("androidide"))
tags.set(setOf("androidide", "gradle"))
}
create("logsenderPlugin") {
id = "${BuildConfig.packageName}.logsender.gradle"
implementationClass = "${BuildConfig.packageName}.gradle.LogSenderPlugin"
displayName = "AndroidIDE LogSender Gradle Plugin"
description = "Gradle plugin for applying LogSender-specific configuration to projects that are built with AndroidIDE"
tags.set(setOf("androidide", "logsender"))
}
}
}
@@ -27,10 +27,14 @@ import org.gradle.api.Project
class AndroidIDEGradlePlugin : Plugin<Project> {
override fun apply(target: Project) {
ideLog("Applying ${javaClass.simpleName}")
target.run {
if (plugins.hasPlugin("com.android.application")) {
plugins.apply(LogSenderPlugin::class.java)
check(plugins.hasPlugin(APP_PLUGIN)) {
"${javaClass.simpleName} can only be applied to Android application projects"
}
plugins.apply(LogSenderPlugin::class.java)
}
}
}
@@ -0,0 +1,98 @@
/*
* This file is part of AndroidIDE.
*
* AndroidIDE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidIDE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidIDE. If not, see <https://www.gnu.org/licenses/>.
*/
package com.itsaky.androidide.gradle
import com.itsaky.androidide.buildinfo.BuildInfo
import org.gradle.api.Plugin
import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.api.initialization.Settings
import org.gradle.api.invocation.Gradle
import java.net.URI
/**
* Plugin for the AndroidIDE's Gradle Init Script.
*
* @author Akash Yadav
*/
class AndroidIDEInitScriptPlugin : Plugin<Gradle> {
companion object {
/**
* Property that is set in tests to indicate that the subprojects must be configured to use `mavenLocal()` instead of
* `mavenCentral()` and maven snapshots repository.
*
* **This is an internal property and should not be manually set by users.**
*/
private const val PROPERTY_ENABLE_MAVEN_LOCAL = "androidide.plugins.internal.testing.enableMavenLocal"
}
override fun apply(target: Gradle) {
ideLog("Applying ${javaClass.simpleName}")
target.settingsEvaluated { settings ->
val isMavenLocalEnabled = settings.startParameter.run {
projectProperties.containsKey(PROPERTY_ENABLE_MAVEN_LOCAL)
&& projectProperties[PROPERTY_ENABLE_MAVEN_LOCAL].toString().toBoolean()
}
settings.addDependencyRepositories(isMavenLocalEnabled)
}
target.projectsLoaded { gradle ->
gradle.rootProject.subprojects.forEach { sub ->
sub.buildscript.dependencies.apply {
add("classpath", ideDependency("gradle-plugin"))
}
sub.afterEvaluate {
sub.pluginManager.apply("${BuildInfo.PACKAGE_NAME}.gradle")
}
}
}
}
@Suppress("UnstableApiUsage")
private fun Settings.addDependencyRepositories(isMavenLocalEnabled: Boolean) {
dependencyResolutionManagement.run {
repositories.configureRepositories(isMavenLocalEnabled)
}
pluginManagement.apply {
repositories.configureRepositories(isMavenLocalEnabled)
}
}
private fun RepositoryHandler.configureRepositories(isMavenLocalEnabled: Boolean) {
if (!isMavenLocalEnabled) {
// For release builds
mavenCentral()
// For AndroidIDE CI builds
maven { repository ->
repository.url = URI.create(
"https://s01.oss.sonatype.org/content/repositories/snapshots/"
)
}
} else {
// maven local has been enabled explicitly
mavenLocal()
}
// for AGP API dependency
google()
}
}
@@ -17,9 +17,7 @@
package com.itsaky.androidide.gradle
import com.android.build.api.variant.AndroidComponentsExtension
import com.android.build.gradle.AppExtension
import com.itsaky.androidide.buildinfo.BuildInfo
import com.android.build.api.variant.ApplicationAndroidComponentsExtension
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.util.concurrent.TimeUnit
@@ -32,47 +30,54 @@ import java.util.concurrent.TimeUnit
class LogSenderPlugin : Plugin<Project> {
companion object {
private const val LOGSENDER_DEPENDENCY_ARTIFACT = "logsender"
private const val LOGSENDER_DEPENDENCY =
"${BuildInfo.MVN_GROUP_ID}:${LOGSENDER_DEPENDENCY_ARTIFACT}:${BuildInfo.VERSION_NAME_DOWNLOAD}"
}
override fun apply(target: Project) {
ideLog("Applying ${javaClass.simpleName}")
target.run {
check(plugins.hasPlugin(APP_PLUGIN)) {
"${javaClass.simpleName} can only be applied to Android application projects."
}
val debuggableBuilds = hashSetOf<String>()
(extensions.getByName(
"androidComponents") as ApplicationAndroidComponentsExtension).apply {
val appExtension = extensions.getByType(AppExtension::class.java)
appExtension.buildTypes.forEach {
if (it.isDebuggable) {
logger.debug("Found debuggable build type : '${it.name}'")
debuggableBuilds.add(it.name)
}
}
finalizeDsl { appExtension ->
logger.warn("On finalize DSL")
logger.debug("Found ${debuggableBuilds.size} debuggable builds in project '${project.path}': $debuggableBuilds")
val debuggableBuilds = hashSetOf<String>()
if (debuggableBuilds.isEmpty()) {
logger.warn("No debuggable builds found in project '${project.path}'")
return@run
}
appExtension.buildTypes.forEach {
if (it.isDebuggable) {
logger.debug("Found debuggable build type : '${it.name}'")
debuggableBuilds.add(it.name)
}
}
val androidComponents = extensions.getByType(AndroidComponentsExtension::class.java)
androidComponents.onVariants { variant ->
val buildType = variant.buildType ?: return@onVariants
if (buildType in debuggableBuilds) {
logger.info(
"Adding LogSender dependency ('${LOGSENDER_DEPENDENCY}')" +
" to variant '${variant.name}' of project '${project.path}'"
)
logger.debug(
"Found ${debuggableBuilds.size} debuggable builds in project '${project.path}': $debuggableBuilds")
variant.runtimeConfiguration.apply {
resolutionStrategy.cacheChangingModulesFor(0, TimeUnit.SECONDS)
dependencies.add(project.dependencies.create(LOGSENDER_DEPENDENCY))
if (debuggableBuilds.isEmpty()) {
logger.warn("No debuggable builds found in project '${project.path}'")
}
onVariants { variant ->
logger.warn("on variant -> ${variant.name} ${variant.buildType}")
val buildType = variant.buildType ?: return@onVariants
if (buildType in debuggableBuilds) {
logger.info(
"Adding LogSender dependency ('${LOGSENDER_DEPENDENCY_ARTIFACT}')" +
" to variant '${variant.name}' of project '${project.path}'"
)
variant.runtimeConfiguration.apply {
resolutionStrategy.cacheChangingModulesFor(0, TimeUnit.SECONDS)
dependencies.add(project.dependencies.ideDependency(LOGSENDER_DEPENDENCY_ARTIFACT))
}
}
}
}
}
@@ -17,8 +17,21 @@
package com.itsaky.androidide.gradle
import com.itsaky.androidide.buildinfo.BuildInfo
import org.gradle.api.Project
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.dsl.DependencyHandler
/**
* @author Akash Yadav
*/
const val APP_PLUGIN = "com.android.application"
const val APP_PLUGIN = "com.android.application"
fun Project.ideDependency(artifact: String): Dependency {
return dependencies.ideDependency(artifact)
}
fun DependencyHandler.ideDependency(artifact: String): Dependency {
return create("${BuildInfo.MVN_GROUP_ID}:${artifact}:${BuildInfo.VERSION_NAME_DOWNLOAD}")
}
@@ -0,0 +1,22 @@
/*
* This file is part of AndroidIDE.
*
* AndroidIDE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidIDE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidIDE. If not, see <https://www.gnu.org/licenses/>.
*/
package com.itsaky.androidide.gradle
internal fun ideLog(message: String) {
System.err.println("[AndroidIDE] $message")
}
@@ -0,0 +1,54 @@
/*
* This file is part of AndroidIDE.
*
* AndroidIDE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidIDE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidIDE. If not, see <https://www.gnu.org/licenses/>.
*/
package com.itsaky.androidide.gradle
import com.google.common.truth.Truth.assertThat
import com.itsaky.androidide.utils.FileProvider
import org.gradle.testkit.runner.GradleRunner
import org.junit.jupiter.api.Test
import kotlin.io.path.pathString
/**
* @author Akash Yadav
*/
class AndroidIDEInitScriptPluginTest {
@Test
fun `test init script plugin is applied`() {
val projectRoot = openProject()
val initScript = FileProvider.testHomeDir().resolve(".androidide/init/androidide.init.gradle")
val runner = GradleRunner.create()
.withProjectDir(projectRoot.toFile())
.withPluginClasspath()
.withArguments(
":app:tasks", // run any task, as long as it applies the plugins
"--init-script", initScript.pathString,
"-Pandroidide.plugins.internal.testing.enableMavenLocal=true", // plugins should be published to maven local first
"--stacktrace"
)
writeInitScript(initScript.toFile(), runner.pluginClasspath)
val result = runner.build()
assertThat(result.output).contains(
"[AndroidIDE] Applying ${AndroidIDEInitScriptPlugin::class.java.simpleName}"
)
}
}
@@ -0,0 +1,62 @@
/*
* This file is part of AndroidIDE.
*
* AndroidIDE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AndroidIDE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AndroidIDE. If not, see <https://www.gnu.org/licenses/>.
*/
package com.itsaky.androidide.gradle
import com.itsaky.androidide.utils.FileProvider
import java.io.File
import java.nio.file.Path
import kotlin.io.path.pathString
internal fun writeInitScript(file: File, deps: List<File>) {
file.parentFile.mkdirs()
val root = FileProvider.projectRoot().pathString
val depsString = deps.filter { it.absolutePath.startsWith(root) }
.joinToString(separator = System.lineSeparator()) {
val isDir = it.isDirectory
"classpath ${if (isDir) "files" else "files"}(\"${it}\")"
}
file.bufferedWriter().use {
it.write("""
initscript {
dependencies {
// make sure the init script plugin is in classpath
$depsString
}
}
apply plugin: com.itsaky.androidide.gradle.AndroidIDEInitScriptPlugin
""".trimIndent())
}
}
internal fun openProject(vararg plugins: String): Path {
val projectRoot = FileProvider.projectRoot()
.resolve("gradle-plugin/src/test/resources/sample-project")
val buildGradle = projectRoot.resolve("app/build.gradle.kts").toFile()
val pluginsText = plugins.joinToString(separator = "\n") { "id(\"$it\")" }
buildGradle.parentFile.resolve("${buildGradle.name}.in")
.readText()
.replace("@@PLUGINS@@", pluginsText)
.also {
buildGradle.writeText(it)
}
return projectRoot
}
+83
View File
@@ -0,0 +1,83 @@
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
/bin/
/gen/
/out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# Gradle files
.gradle/
/build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
@@ -0,0 +1,2 @@
/build
build.gradle.kts
@@ -0,0 +1,49 @@
plugins {
id("com.android.application")
@@PLUGINS@@
}
android {
namespace = "com.example.myapplication2"
compileSdk = 33
buildToolsVersion = "33.0.2"
defaultConfig {
applicationId = "com.example.myapplication2"
minSdk = 21
targetSdk = 33
versionCode = 1
versionName = "1.0"
vectorDrawables {
useSupportLibrary = true
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
buildTypes {
release {
isMinifyEnabled = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
buildFeatures {
viewBinding = true
}
}
dependencies {
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
implementation("com.google.android.material:material:1.9.0")
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android">
<application android:label="@string/app_name"/>
</manifest>
@@ -0,0 +1,20 @@
<!--
~ This file is part of AndroidIDE.
~
~ AndroidIDE is free software: you can redistribute it and/or modify
~ it under the terms of the GNU General Public License as published by
~ the Free Software Foundation, either version 3 of the License, or
~ (at your option) any later version.
~
~ AndroidIDE is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of
~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
~ GNU General Public License for more details.
~
~ You should have received a copy of the GNU General Public License
~ along with AndroidIDE. If not, see <https://www.gnu.org/licenses/>.
-->
<resources>
<string name="app_name">Sample app</string>
</resources>
@@ -1,9 +0,0 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id("com.android.application") version "7.2.0" apply false
id("com.android.library") version "7.2.0" apply false
}
tasks.register<Delete>("clean") {
delete(rootProject.buildDir)
}
@@ -0,0 +1,23 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx512m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
Binary file not shown.
@@ -0,0 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+244
View File
@@ -0,0 +1,244 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+92
View File
@@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@@ -0,0 +1,17 @@
pluginManagement {
repositories {
google()
mavenCentral()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "Sample App"
include(":app")
+4 -1
View File
@@ -2,6 +2,7 @@
agp = "8.0.2"
agp-tooling = "8.1.0"
gradle-tooling = "8.1.1"
junit-jupiter = "5.7.1"
kotlin = "1.8.21"
tree-sitter = "3.2.0"
editor = "0.21.1-5c3385c-SNAPSHOT"
@@ -101,6 +102,8 @@ git-jgit = { module = "org.eclipse.jgit:org.eclipse.jgit", version = "3.7.1.2015
# Tests
tests-junit = { module = "junit:junit", version = "4.13.2" }
tests-junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit-jupiter" }
tests-junit-platformLauncher = { module = "org.junit.platform:junit-platform-launcher" }
tests-google-truth = { module = "com.google.truth:truth", version = "1.1.5" }
tests-robolectric = { module = "org.robolectric:robolectric", version = "4.10.3" }
tests-androidx-test-core = { module = "androidx.test:core", version = "1.5.0" }
@@ -113,7 +116,7 @@ tests-mockito-kotlin = { module = "org.mockito.kotlin:mockito-kotlin", version =
tests-mockk = { module = "io.mockk:mockk", version = "1.13.5" }
# Tooling
tooling-agp = { module="com.android.tools.build:gradle", version.ref = "agp-tooling" }
tooling-agpApi = { module="com.android.tools.build:gradle-api", version.ref = "agp-tooling" }
tooling-builderModel = { module="com.android.tools.build:builder-model", version.ref = "agp-tooling" }
tooling-gradleApi = { module="org.gradle:gradle-tooling-api", version.ref = "gradle-tooling" }
tooling-slf4j = { module = "org.slf4j:slf4j-api", version = "2.0.7" }
@@ -49,9 +49,11 @@ class FileProvider {
}
}
@JvmStatic fun currentDir(): Path = Paths.get(System.getProperty("user.dir")!!)
@JvmStatic
fun currentDir(): Path = Paths.get(System.getProperty("user.dir")!!)
@JvmStatic fun implModule(): Path = projectRoot().resolve("subprojects/tooling-api-impl")
@JvmStatic
fun implModule(): Path = projectRoot().resolve("subprojects/tooling-api-impl")
@JvmStatic
fun projectRoot(): Path =
@@ -59,7 +61,14 @@ class FileProvider {
"Unable to file project root. Check if '${PROJECT_ROOT_FILE}' file exists in the project root directory."
}
@JvmStatic fun testProjectRoot(): Path = projectRoot().resolve("tests/test-project")
@JvmStatic
private fun testsDir(): Path = projectRoot().resolve("tests")
@JvmStatic
fun testHomeDir(): Path = testsDir().resolve("test-home")
@JvmStatic
fun testProjectRoot(): Path = testsDir().resolve("test-project")
/**
* Get the path to the 'resources' directory.
@@ -82,7 +91,8 @@ class FileProvider {
return resources().resolve("${name}_template.$extension").normalize()
}
@JvmStatic fun contents(file: Path): StringBuilder = StringBuilder(file.readText())
@JvmStatic
fun contents(file: Path): StringBuilder = StringBuilder(file.readText())
}
}
+1
View File
@@ -0,0 +1 @@
/test-home
+1 -2
View File
@@ -1,2 +1 @@
model.jar
plugin.jar
/init
@@ -1,3 +0,0 @@
subprojects {
apply plugin: 'idea'
}
@@ -1,11 +0,0 @@
import com.itsaky.androidide.tooling.plugin.AndroidIDEToolingApiPlugin
initscript {
dependencies {
classpath files ("D:/Projects/AndroidStudioProjects/AndroidIDE/build-tools/tooling-api-impl/./src/test/test-home/.androidide/init/model.jar")
}
}
allprojects {
apply plugin: AndroidIDEToolingApiPlugin
}
Binary file not shown.
Binary file not shown.