简体   繁体   English

将现有的 groovy build.gradle 文件转换为基于 kotlin 的 build.gradle.kts

[英]Convert an existing groovy build.gradle file into a kotlin based build.gradle.kts

my project has two different build.gradle files written with groovy Syntax.我的项目有两个用 groovy 语法编写的不同 build.gradle 文件。 I´d like to change this groovy written gradle file into a gradle file written with Kotlin Syntax (build.gradle.kts).我想将这个 groovy 编写的 gradle 文件更改为使用 Kotlin 语法 (build.gradle.kts) 编写的 gradle 文件。

I´ll show you the root project build.gradle file.我将向您展示根项目 build.gradle 文件。

    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    //ext.kotlin_version = '1.2-M2'
    ext.kotlin_version = '1.1.51'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0-alpha01'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I tried several "ways" i found in the internet, but nothing worked.我尝试了几种在互联网上找到的“方法”,但都没有奏效。 Renaming the file, which is obviously not the Solution, didn´t help.重命名文件,这显然不是解决方案,没有帮助。 I´ve created a new build.gradle.kts file in my root project but the file isn´t shown in my project.我在我的根项目中创建了一个新的 build.gradle.kts 文件,但该文件未显示在我的项目中。 Also gradle didn´t recognize the new file. gradle 也无法识别新文件。

So my question is: How can i transform my groovy build.gradle file into a kotlin build.gradle.kts and add this new file into my existing project?所以我的问题是:如何将我的 groovy build.gradle 文件转换为 kotlin build.gradle.kts 并将这个新文件添加到我现有的项目中?

Thanks for your help.谢谢你的帮助。

Of course renaming won't help.当然,重命名无济于事。 You'll need to re-write it using Kotlin DSL.您需要使用 Kotlin DSL 重新编写它。 It is similar to Groovy, but with some differences.它类似于 Groovy,但有一些不同。 Read their docs , look at the examples .阅读他们的文档,查看示例

In your case, the issues are:在你的情况下,问题是:

  1. ext.kotlin_version is not valid Kotlin syntax, use square brackets ext.kotlin_version不是有效的 Kotlin 语法,请使用方括号
  2. All Kotlin strings use double quotes所有Kotlin 字符串都使用双引号
  3. Braces are required around parameters for most function calls (there are exceptions, like infix functions ) 大多数函数调用的参数周围都需要大括号(也有例外,例如中缀函数
  4. Slighlty different task management API.略有不同的任务管理 API。 There are different styles available.有不同的款式可供选择。 You can declare all the tasks in tasks block as strings , or use a single typed function, as in the example below.你可以声明中的所有任务tasks块作为字符串,或使用一个类型化的功能,如下面的例子。

Take a look at the converted top-level build.gradle.kts :看一下转换后的顶级build.gradle.kts

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext["kotlin_version"] = "1.1.51"
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath ("com.android.tools.build:gradle:3.1.0-alpha01")
        classpath ("org.jetbrains.kotlin:kotlin-gradle-plugin:${ext["kotlin_version"]}")
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
}

task<Delete>("clean") {
    delete(rootProject.buildDir)
}
buildscript {
    extra.apply {
      var  kotlin_version = "1.7.10"
      var  navigationVersion = "2.5.0"
      var  hilt_version = "2.42"
    }

//        .kotlin_version("1.7.10")
//    ext.navigationVersion("2.5.0")
//    ext.hilt_version("2.42")
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:7.2.1")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10")
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.5.0")
        classpath("com.google.firebase:firebase-crashlytics-gradle:2.9.1")
        classpath("com.google.gms:google-services:4.3.13")
        classpath("com.google.firebase:perf-plugin:1.4.1")
        classpath("com.google.dagger:hilt-android-gradle-plugin:2.42")
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    //    classpath("com.google.dagger:hilt-android-gradle-plugin:$extra.hilt_version")
    }
}

allprojects {
    repositories {
        gradlePluginPortal()
        mavenCentral()
        google()
        jcenter()
        maven { url  = uri("https://jitpack.io") }
        maven { url =  uri("https://cdn.veriff.me/android/") }
        flatDir {
            dirs("libs")
        }
    }
}

tasks.register("clean"){
    delete(setOf(rootProject.buildDir))
}




    import extensions.*
    import java.time.LocalDate
    import java.time.format.DateTimeFormatter.*
    
    plugins {
        id(Plugins.ANDROID_APPLICATION)
        id(Plugins.ANDROID)
        id(Plugins.PARCELIZE)
        id(Plugins.KAPT)
        id(Plugins.NAVIGATION_SAFE_ARGS)
        id(Plugins.GOOGLE_SERVICES)
        id(Plugins.CRASH_ANALYTICS)
        id(Plugins.PERFORMANCE_ANALYTICS)
        id(Plugins.DAGGER_HILT)
    }
    
    var applicationName = "abc`enter code here`"
    
    android {
        compileSdk = AndroidConfig.COMPILE_SDK
        bundle {
            language {
                enableSplit = false
            }
        }
    
        defaultConfig {
            configurations.all {
                resolutionStrategy { force(AndroidConfig.FORCE_STRATEGY) }
            }
            applicationId = AndroidConfig.APPLICATION_ID
            minSdkVersion(AndroidConfig.MIN_SDK)
            targetSdkVersion(AndroidConfig.TARGET_SDK)
            versionCode = AndroidConfig.VERSION_CODE
            versionName = AndroidConfig.VERSION_NAME
            testInstrumentationRunner = AndroidConfig.TEST_INSTRUMENTATION_RUNNER
    
            //javaCompileOptions.annotationProcessorOptions.arguments['dagger.hilt.disableModulesHaveInstallInCheck'] = 'true'
        }
    
        applicationVariants.all {
            outputs.all {
                var formattedDate = LocalDate.now()//LocalDate.now().format(ofPattern("yyyy-MM-dd"))
                var outputFileName =
                    "${applicationName}_${buildType.name}_${formattedDate}_v${defaultConfig.versionName}.apk"
            }
        }
    
        buildTypes {
            getByName("debug") {
                // minifyEnabled = "false"
                isMinifyEnabled = false
                isTestCoverageEnabled = true
                isShrinkResources = false
                isDebuggable = true
                proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro")
                testProguardFiles(getDefaultProguardFile("proguard-android.txt"),
                    "proguardTest-rules.pro")
    //            FirebasePerformance {
    //                // Set this flag to 'false' to disable @AddTrace annotation processing and
    //                // automatic HTTP/S network request monitoring
    //                // for a specific build variant at compile time.
    //                isInstrumentationEnabled = true
    //            }
            }
    
            getByName("release") {
                isMinifyEnabled = false
                isShrinkResources = false
                proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro")
                testProguardFiles(getDefaultProguardFile("proguard-android.txt"),
                    "proguardTest-rules.pro")
            }
        }
    
        buildFeatures {
            viewBinding = true
            dataBinding = true
        }
    
    //    compileOptions {
    //        sourceCompatibility = JavaVersion.VERSION_11
    //        targetCompatibility = JavaVersion.VERSION_11
    //    }
    
        compileOptions {
            sourceCompatibility = JavaVersion.VERSION_1_8
            targetCompatibility = JavaVersion.VERSION_1_8
        }
        kotlinOptions {
            jvmTarget = JavaVersion.VERSION_11.toString()
            //freeCompilerArgs= ["-Xjvm-default=compatibility"]
            freeCompilerArgs = listOf("-Xjvm-default=compatibility")
            // freecompilerargs = List( -Xjvm-default=compatibility)
        }
        flavorDimensions("mode")
    
        productFlavors {
            maybeCreate("Staging")
            maybeCreate("PreProduction")
            maybeCreate("Production")
            getByName("Staging") {
                applicationIdSuffix = ".staging"
                //versionNameSuffix = ".staging"
                
            }
            getByName("Production") {
                dimension = "mode"
                resValue("string", "app_name", "abc")
               
            }
        }
        packagingOptions {
            resources.excludes += "META-INF/DEPENDENCIES"
            resources.excludes += "META-INF/NOTICE"
            resources.excludes += "META-INF/LICENSE"
            resources.excludes += "META-INF/LICENSE.txt"
            resources.excludes += "META-INF/NOTICE.txt"
    
            //   excludes += ['META-INF/DEPENDENCIES', 'META-INF/NOTICE', 'META-INF/LICENSE', 'META-INF/LICENSE.txt', 'META-INF/NOTICE.txt']
    
        }
        dynamicFeatures += setOf(":BuyCryptoModule",":"points")
    
    }
    
    dependencies {
        //includeing file libs
        val daggerVersion = "2.42"
        implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))
        implementation(files("geetest_captcha_android_v1.7.1.1_20220308"))
        appModuleDeps()
        kaptAndroidTest("com.google.dagger:hilt-compiler:2.42")
        // For local unit tests
        testImplementation("com.google.dagger:hilt-android-testing:2.42")
        kaptTest("com.google.dagger:hilt-compiler:2.42")
        implementation(files("libs/opencsv-5.2.jar"))
        kaptAndroidTest("com.google.dagger:dagger-compiler:$daggerVersion")
        kaptTest("com.google.dagger:dagger-compiler:$daggerVersion")
        releaseImplementation("com.github.ChuckerTeam.Chucker:library-no-op:3.5.2")
    }
    kapt {
        correctErrorTypes = true
    
            arguments {
                // Make Hilt share the same definition of Components in tests instead of
                // creating a new set of Components per test class.
                arg("dagger.hilt.shareTestComponents", "true")
            }
    
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM