简体   繁体   中英

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. I´d like to change this groovy written gradle file into a gradle file written with Kotlin Syntax (build.gradle.kts).

I´ll show you the root project build.gradle file.

    // 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. Also gradle didn´t recognize the new file.

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?

Thanks for your help.

Of course renaming won't help. You'll need to re-write it using Kotlin DSL. It is similar to Groovy, but with some differences. 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
  2. All Kotlin strings use double quotes
  3. Braces are required around parameters for most function calls (there are exceptions, like infix functions )
  4. Slighlty different task management 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.

Take a look at the converted top-level 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")
            }
    
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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