'Using gradle project variable in buildscript scope

There is a similar question here Access project extra properties in buildscript closure

but i found a "workaround" which does not look like the optimum

I have a multi gradle project - im declaring the repository in the main gradle file using

subprojects {
 repostiories {
    maven {..}
  }
}

now i also have to set these for the build script because im using a plugin !

so again buildscript { repositories ...

Now instead of pasting the URLs twice i wanted to use a property - as i figured project.ext properties are not set during the buildscript stage thus i put them in my gradle.settings file

i couldnt set rootProject.ext.xx settings so i had to use

gradle.ext {
 mavenURLs =  [ companyURL1, companyURL2 ... etc]
}

Now i could use gradle.ext.mavenURLs in my build.gradle file

Is there a better way ? Is there a way to set the buildscript and dependency repositories for all project in one block without repeating once for buildscript and once for the dependency ?



Solution 1:[1]

def repoClosure = { RepositoryHandler repoHandler ->
    repoHandler.mavenLocal()
    repoHandler.mavenCentral()
    ['http://mycompany/repo1', 'http://mycompany/repo2'].each { mavenURL ->
        repoHandler.maven {
            url mavenURL
            credentials {
                username 'foo'
                password 'bar'
            }
        }
    }
}
project.with {
    allprojects {
        repoClosure(buildscript.repositories)
        repoClosure(repositories)
    }
}

Solution 2:[2]

Simply create my-repositories.gradle file, with content like:

def repoClosure = {
    maven {
        url uri("${rootProject.rootDir}/offline-repository")
    }
    google()
    mavenCentral()

    ['http://mycompany/repo1', 'http://mycompany/repo2'].each { mavenURL ->
        maven {
            url mavenURL
            credentials {
                username 'my-name'
                password 'my-password'
            }
        }
    }
}
project.with {
    allprojects {
        buildscript {
            ext.myVariable = "Just an example!"
            repositories(repoClosure)
        }
        repositories(repoClosure)
    }
}

Then in your build.gradle apply it, like:

buildscript {
    apply from: './my-repositories.gradle'

    ext {
        kotlin_version = '1.5.30'
    }

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

// ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2