I fetched the spring framework source code from github by using git clone command. When I build the source code by using gradle build in the source code directory,it takes a long time to download dependencies and compile the java code,but failed with an exception.The output is below.
:spring-webmvc-portlet:sourcesJar UP-TO-DATE
:spring-webmvc-tiles2:javadoc SKIPPED
:spring-webmvc-tiles2:javadocJar SKIPPED
:spring-webmvc-tiles2:sourcesJar SKIPPED
:spring-websocket:javadoc UP-TO-DATE
:spring-websocket:javadocJar UP-TO-DATE
:spring-websocket:sourcesJar UP-TO-DATE
:distZip
FAILURE: Build failed with an exception.
* What went wrong:
Failed to capture snapshot of input files for task 'distZip' during up-to-date c
heck. See stacktrace for details.
> java.io.FileNotFoundException: C:\Users\yuqing\workspace\spring-framework\buil
d\distributions\spring-framework-4.3.0.BUILD-SNAPSHOT-schema.zip
* Try:
Run with --info or --debug option to get more log output.
* Exception is:
org.gradle.api.UncheckedIOException: Failed to capture snapshot of input files f
or task 'distZip' during up-to-date check. See stacktrace for details.
at org.gradle.api.internal.changedetection.rules.TaskUpToDateState.<init
>(TaskUpToDateState.java:60)
at org.gradle.api.internal.changedetection.changes.DefaultTaskArtifactSt
ateRepository$TaskArtifactStateImpl.getStates(DefaultTaskArtifactStateRepository
.java:132)
at org.gradle.api.internal.changedetection.changes.DefaultTaskArtifactSt
ateRepository$TaskArtifactStateImpl.isUpToDate(DefaultTaskArtifactStateRepositor
y.java:70)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.exec
ute(SkipUpToDateTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execut
e(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecu
ter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter
.execute(SkipTaskWithNoActionsExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execut
e(SkipOnlyIfTaskExecuter.java:53)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter
.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTa
skWorker.execute(DefaultTaskGraphExecuter.java:203)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTa
skWorker.execute(DefaultTaskGraphExecuter.java:185)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorW
orker.processTask(AbstractTaskPlanExecutor.java:66)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorW
orker.run(AbstractTaskPlanExecutor.java:50)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(Defaul
tTaskPlanExecutor.java:25)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(Defau
ltTaskGraphExecuter.java:110)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTask
ExecutionAction.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecute
r.java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExec
uter.java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecu
ter.java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildEx
ecutionAction.java:32)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecute
r.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecute
r.java:30)
at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLa
uncher.java:154)
at org.gradle.internal.Factories$1.create(Factories.java:22)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(Defaul
tBuildOperationExecutor.java:90)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(Defaul
tBuildOperationExecutor.java:52)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(Default
GradleLauncher.java:151)
at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGra
dleLauncher.java:32)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradl
eLauncher.java:99)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradl
eLauncher.java:93)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(Defaul
tBuildOperationExecutor.java:90)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(Defaul
tBuildOperationExecutor.java:62)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradle
Launcher.java:93)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLaun
cher.java:82)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildCon
....
Caused by: org.gradle.api.UncheckedIOException: java.io.FileNotFoundException: C
:\Users\yuqing\workspace\spring-framework\build\distributions\spring-framework-4
.3.0.BUILD-SNAPSHOT-schema.zip (系统找不到指定的文件。)
at org.gradle.internal.hash.HashUtil.createHash(HashUtil.java:39)
at org.gradle.api.internal.hash.DefaultHasher.hash(DefaultHasher.java:24
)
at org.gradle.api.internal.changedetection.state.CachingFileSnapshotter.
snapshot(CachingFileSnapshotter.java:57)
at org.gradle.api.internal.changedetection.state.CachingFileSnapshotter.
snapshot(CachingFileSnapshotter.java:46)
at org.gradle.api.internal.changedetection.state.CachingFileSnapshotter.
snapshot(CachingFileSnapshotter.java:29)
at org.gradle.api.internal.changedetection.state.DefaultFileCollectionSn
apshotter$1.run(DefaultFileCollectionSnapshotter.java:70)
at org.gradle.internal.Factories$1.create(Factories.java:22)
at org.gradle.cache.internal.DefaultCacheAccess.useCache(DefaultCacheAcc
ess.java:192)
at org.gradle.cache.internal.DefaultCacheAccess.useCache(DefaultCacheAcc
ess.java:175)
at org.gradle.cache.internal.DefaultPersistentDirectoryStore.useCache(De
faultPersistentDirectoryStore.java:106)
at org.gradle.cache.internal.DefaultCacheFactory$ReferenceTrackingCache.
useCache(DefaultCacheFactory.java:187)
at org.gradle.api.internal.changedetection.state.DefaultTaskArtifactStat
eCacheAccess.useCache(DefaultTaskArtifactStateCacheAccess.java:60)
at org.gradle.api.internal.changedetection.state.DefaultFileCollectionSn
apshotter.snapshot(DefaultFileCollectionSnapshotter.java:62)
at org.gradle.api.internal.changedetection.rules.TaskUpToDateState.<init
>(TaskUpToDateState.java:56)
... 57 more
Caused by: java.io.FileNotFoundException: C:\Users\yuqing\workspace\spring-frame
work\build\distributions\spring-framework-4.3.0.BUILD-SNAPSHOT-schema.zip
at org.gradle.internal.hash.HashUtil.createHash(HashUtil.java:34)
... 70 more
BUILD FAILED
Total time: 20.861 secs
The error indicates the file spring-framework-4.3.0.BUILD-SNAPSHOT-schema.zip not found.I wondered why this file is not found,it should be created by distZip task but it doesn't.
I have googled this problem but not found any question about this.
I have resovled this problem,the devil is path separator.Because this command runs on windows.
Modify schemaZip task definition from
task schemaZip(type: Zip) {
group = "Distribution"
baseName = "spring-framework"
classifier = "schema"
description = "Builds -${classifier} archive containing all " +
"XSDs for deployment at http://springframework.org/schema."
duplicatesStrategy 'exclude'
moduleProjects.each { subproject ->
def Properties schemas = new Properties();
subproject.sourceSets.main.resources.find {
it.path.endsWith("META-INF/spring.schemas")
}?.withInputStream { schemas.load(it) }
for (def key : schemas.keySet()) {
def shortName = key.replaceAll(/http.*schema.(.*).spring-.*/, '$1')
assert shortName != key
File xsdFile = subproject.sourceSets.main.resources.find {
it.path.endsWith(schemas.get(key))
}
assert xsdFile != null
into (shortName) {
from xsdFile.path
}
}
}
}
to
task schemaZip(type: Zip) {
group = "Distribution"
baseName = "spring-framework"
classifier = "schema"
description = "Builds -${classifier} archive containing all " +
"XSDs for deployment at http://springframework.org/schema."
duplicatesStrategy 'exclude'
moduleProjects.each { subproject ->
def Properties schemas = new Properties();
subproject.sourceSets.main.resources.find {
it.path.endsWith("META-INF\\spring.schemas")
}?.withInputStream { schemas.load(it) }
for (def key : schemas.keySet()) {
def shortName = key.replaceAll(/http.*schema.(.*).spring-.*/, '$1')
assert shortName != key
File xsdFile = subproject.sourceSets.main.resources.find {
it.path.endsWith(schemas.get(key).replaceAll('\\/','\\\\'))
}
assert xsdFile != null
into (shortName) {
from xsdFile.path
}
}
}
}
Related
My IntelliJ IDEA plugin is based on official Jet Brains template, however Java one, not Kotlin.
Solving the error Failed to apply plugin 'org.jetbrains.intellij', I have updated the Gradle from 7.2 to 7.3. Then, trying to build the project, I have got the error
Val cannot be reassigned
(I'll append the detailed output in the end of this question).
I have checked the Gradle 5.0 causes error Val cannot be reassigned when using Kotlin DSL in buid.gradle.kts issue on GitHub. There, the cause was the classDirectories field which hase become read-only. But when I have tried to search the classDirectories in my projet, there was not the search results.
Maybe the solution will be obvious for advanced Gradle users, but Gradle/Java/Kotlin is not my specialization while I need to create the plugins for IntelliJ IDEA.
Appendix
Output with stack trace
11:58:14: Executing 'buildPlugin --stacktrace'...
> Configure project :
[gradle-intellij-plugin :] Gradle IntelliJ Plugin is outdated: 1.12.0. Update `org.jetbrains.intellij` to: 1.13.0
e: D:\IntelliJ IDEA\InHouseDevelopment\YamatoDaiwaES_Extensions\IDEsPlugins\IntelliJ_IDEA\build.gradle.kts:49:5: Val cannot be reassigned
e: D:\IntelliJ IDEA\InHouseDevelopment\YamatoDaiwaES_Extensions\IDEsPlugins\IntelliJ_IDEA\build.gradle.kts:49:15: Type mismatch: inferred type is String but Property<String> was expected
e: D:\IntelliJ IDEA\InHouseDevelopment\YamatoDaiwaES_Extensions\IDEsPlugins\IntelliJ_IDEA\build.gradle.kts:50:5: Val cannot be reassigned
e: D:\IntelliJ IDEA\InHouseDevelopment\YamatoDaiwaES_Extensions\IDEsPlugins\IntelliJ_IDEA\build.gradle.kts:50:14: Type mismatch: inferred type is List<???> but ListProperty<String> was expected
FAILURE: Build failed with an exception.
* Where:
Build file 'D:\IntelliJ IDEA\InHouseDevelopment\YamatoDaiwaES_Extensions\IDEsPlugins\IntelliJ_IDEA\build.gradle.kts' line: 49
* What went wrong:
Script compilation errors:
Line 49: version = properties("pluginVersion")
^ Val cannot be reassigned
Line 49: version = properties("pluginVersion")
^ Type mismatch: inferred type is String but Property<String> was expected
Line 50: groups = emptyList()
^ Val cannot be reassigned
Line 50: groups = emptyList()
^ Type mismatch: inferred type is List<???> but ListProperty<String> was expected
4 errors
* Try:
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
* Exception is:
ScriptCompilationException(errors=[ScriptCompilationError(message=Val cannot be reassigned, location=C:\Users\Takeshi Tokugawa\.gradle\.tmp\gradle-kotlin-dsl-2962856697602439688.tmp\build.gradle.kts (49:5)), ScriptCompilationError(message=Type mismatch: inferred type is String but Property<String> was expected, location=C:\Users\Takeshi Tokugawa\.gradle\.tmp\gradle-kotlin-dsl-2962856697602439688.tmp\build.gradle.kts (49:15)), ScriptCompilationError(message=Val cannot be reassigned, location=C:\Users\Takeshi Tokugawa\.gradle\.tmp\gradle-kotlin-dsl-2962856697602439688.tmp\build.gradle.kts (50:5)), ScriptCompilationError(message=Type mismatch: inferred type is List<???> but ListProperty<String> was expected, location=C:\Users\Takeshi Tokugawa\.gradle\.tmp\gradle-kotlin-dsl-2962856697602439688.tmp\build.gradle.kts (50:14))])
at org.gradle.kotlin.dsl.support.KotlinCompilerKt.compileKotlinScriptModuleTo(KotlinCompiler.kt:187)
at org.gradle.kotlin.dsl.support.KotlinCompilerKt.compileKotlinScriptToDirectory(KotlinCompiler.kt:148)
// ...
* Get more help at https://help.gradle.org
BUILD FAILED in 1s
11:58:15: Execution finished 'buildPlugin --stacktrace'.
build.gradle.kts
import io.gitlab.arturbosch.detekt.Detekt
import org.jetbrains.changelog.markdownToHTML
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
fun properties(key: String) = project.findProperty(key).toString()
plugins {
// Java support
id("java")
// Kotlin support
id("org.jetbrains.kotlin.jvm") version "1.7.10"
// gradle-intellij-plugin - read more: https://github.com/JetBrains/gradle-intellij-plugin
id("org.jetbrains.intellij") version "1.12.0"
// gradle-changelog-plugin - read more: https://github.com/JetBrains/gradle-changelog-plugin
id("org.jetbrains.changelog") version "1.3.0"
// detekt linter - read more: https://detekt.github.io/detekt/gradle.html
id("io.gitlab.arturbosch.detekt") version "1.17.1"
// ktlint linter - read more: https://github.com/JLLeitschuh/ktlint-gradle
id("org.jlleitschuh.gradle.ktlint") version "10.0.0"
}
group = properties("pluginGroup")
version = properties("pluginVersion")
// Configure project's dependencies
repositories {
mavenCentral()
}
dependencies {
detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.17.1")
}
// Configure gradle-intellij-plugin plugin.
// Read more: https://github.com/JetBrains/gradle-intellij-plugin
intellij {
pluginName.set(properties("pluginName"))
version.set(properties("platformVersion"))
type.set(properties("platformType"))
downloadSources.set(properties("platformDownloadSources").toBoolean())
updateSinceUntilBuild.set(true)
// Plugin Dependencies. Uses `platformPlugins` property from the gradle.properties file.
plugins.set(properties("platformPlugins").split(',').map(String::trim).filter(String::isNotEmpty))
}
// Configure gradle-changelog-plugin plugin.
// Read more: https://github.com/JetBrains/gradle-changelog-plugin
changelog {
version = properties("pluginVersion")
groups = emptyList()
}
// Configure detekt plugin.
// Read more: https://detekt.github.io/detekt/kotlindsl.html
detekt {
config = files("./detekt-config.yml")
buildUponDefaultConfig = true
reports {
html.enabled = false
xml.enabled = false
txt.enabled = false
}
}
tasks {
// Set the compatibility versions to 1.8
withType<JavaCompile> {
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
}
withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
withType<Detekt> {
jvmTarget = "1.8"
}
patchPluginXml {
version.set(properties("pluginVersion"))
sinceBuild.set(properties("pluginSinceBuild"))
untilBuild.set(properties("pluginUntilBuild"))
// Extract the <!-- Plugin description --> section from README.md and provide for the plugin's manifest
pluginDescription.set(
File(projectDir, "README.md").readText().lines().run {
val start = "<!-- Plugin description -->"
val end = "<!-- Plugin description end -->"
if (!containsAll(listOf(start, end))) {
throw GradleException("Plugin description section not found in README.md:\n$start ... $end")
}
subList(indexOf(start) + 1, indexOf(end))
}.joinToString("\n").run { markdownToHTML(this) }
)
// Get the latest available change notes from the changelog file
changeNotes.set(provider { changelog.getLatest().toHTML() })
}
runPluginVerifier {
ideVersions.set(properties("pluginVerifierIdeVersions").split(',').map(String::trim).filter(String::isNotEmpty))
}
publishPlugin {
dependsOn("patchChangelog")
token.set(System.getenv("PUBLISH_TOKEN"))
// pluginVersion is based on the SemVer (https://semver.org) and supports pre-release labels, like 2.1.7-alpha.3
// Specify pre-release label to publish the plugin in a custom Release Channel automatically. Read more:
// https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel
channels.set(listOf(properties("pluginVersion").split('-').getOrElse(1) { "default" }.split('.').first()))
}
}
I have jenkinsfile and I want to set defaultValue on the imageTag dynamically, which I'm fetching from the pom file.
Here is the file:
def gr
pipeline {
agent any
image = readMavenPom().getParent().getVersion()
parameters {
string(name: 'imageTag', defaultValue: image, description: 'Docker image tag')
}
stages {
stage('Environment') {
steps {
script {
gr = load 'src/ci/script.groovy';
echo("Using imageTag: ${params.imageTag}")
}
}
}
}
I'm getting an error:
startup failed: WorkflowScript: 10: Not a valid section definition:
"image = readMavenPom().getParent().getVersion()". Some extra
configuration is required. # line 10, column 5.
image = readMavenPom().getParent().getVersion()
^
1 error
at
org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
at
org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)
at
org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
at
org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
at
org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
at
groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
at
groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688) at
groovy.lang.GroovyShell.parse(GroovyShell.java:700) at
org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:142)
at
org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:127)
at
org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:571)
at
org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:523)
at
org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:337)
at
hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:429) Finished: FAILURE
I found this solution and it works, but the main idea was setting defaultValue dynamically directly on parameter
stage('Environment') {
steps {
script {
gr = load 'src/ci/script.groovy';
version = readMavenPom().getParent().getVersion()
if (!params.imageTag) {
imageTag = version
}
echo("Using imageTag: ${imageTag}")
}
}
}
I am trying to publish Lambda zip file to s3- s3://my-aws-lambda/<projectName>/[release|SNAPSHOT]/. The task defined below, publishToS3 fails with the message
Caused by: java.io.FileNotFoundException: /Users/me/my-lambda/build/distributions
when I run
./gradlew clean build -x test -x release
Appreciate any help. Thanks.
task buildZip(type: Zip) {
from compileJava
from processResources
into('lib') {
from configurations.runtimeClasspath
}
}
task publishToS3(type: Exec, dependsOn: buildZip) {
onlyIf { file("${project.buildDir}/distributions").exist() }
def artifacts = new FileNameByRegexFinder().getFileNames("${project.buildDir}/distributions", /.*\.zip/)
assert artifacts.size() == 1
def isSnapShot = artifacts[0].endsWith('-SNAPSHOT.zip')
def releaseCmd = ("aws s3 cp " +
"${artifacts[0]} " +
"s3://my-aws-lambdas/${project.name}/${isSnapShot ? 'SNAPSHOT' : 'release'}/ ").trim().tokenize(' ') as List
workingDir "${project.buildDir}/distributions"
commandLine releaseCmd
}
build.dependsOn buildZip
If you are on UNIX environment, you can use the find command to search the files and use it's output.
task scanFiles() {
def a= "find ${project.buildDir} -name *.zip".execute().text
String[] files=a.split('\n')
if(files.length == 1){
println("We'v got a file :"+a)
}
else if(files.length ==0){
println("We've not no files ")
}
else{
println("We've got multiple files\n"+a)
}
}
I am working on a Gradle script where I need to read the local.properties file and use the values in the properties file in build.gradle. I am doing it in the below manner. I ran the below script and it is now throwing an error, but it is also not doing anything like creating, deleting, and copying the file. I tried to print the value of the variable and it is showing the correct value.
Can someone let me know if this is the correct way to do this? I think the other way is to define everything in the gradle.properties and use it in the build.gradle. Can someone let me know how could I access the properties in build.gradle from build.properties?
build.gradle file:
apply plugin: 'java'
// Set the group for publishing
group = 'com.true.test'
/**
* Initializing GAVC settings
*/
def buildProperties = new Properties()
file("version.properties").withInputStream {
stream -> buildProperties.load(stream)
}
// If jenkins build, add the jenkins build version to the version. Else add snapshot version to the version.
def env = System.getenv()
if (env["BUILD_NUMBER"]) buildProperties.test+= ".${env["BUILD_NUMBER"]}"
version = buildProperties.test
println "${version}"
// Name is set in the settings.gradle file
group = "com.true.test"
version = buildProperties.test
println "Building ${project.group}:${project.name}:${project.version}"
Properties properties = new Properties()
properties.load(project.file('build.properties').newDataInputStream())
def folderDir = properties.getProperty('build.dir')
def configDir = properties.getProperty('config.dir')
def baseDir = properties.getProperty('base.dir')
def logDir = properties.getProperty('log.dir')
def deployDir = properties.getProperty('deploy.dir')
def testsDir = properties.getProperty('tests.dir')
def packageDir = properties.getProperty('package.dir')
def wrapperDir = properties.getProperty('wrapper.dir')
sourceCompatibility = 1.7
compileJava.options.encoding = 'UTF-8'
repositories {
maven { url "http://arti.oven.c:9000/release" }
}
task swipe(type: Delete) {
println "Delete $projectDir/${folderDir}"
delete "$projectDir/$folderDir"
delete "$projectDir/$logDir"
delete "$projectDir/$deployDir"
delete "$projectDir/$packageDir"
delete "$projectDir/$testsDir"
mkdir("$projectDir/${folderDir}")
mkdir("projectDir/${logDir}")
mkdir("projectDir/${deployDir}")
mkdir("projectDir/${packageDir}")
mkdir("projectDir/${testsDir}")
}
task prepConfigs(type: Copy, overwrite:true, dependsOn: swipe) {
println "The name of ${projectDir}/${folderDir} and ${projectDir}/${configDir}"
from('${projectDir}/${folderDir}')
into('${projectDir}/$configDir}')
include('*.xml')
}
build.properties file:
# -----------------------------------------------------------------
# General Settings
# -----------------------------------------------------------------
application.name = Admin
project.name = Hello Cool
# -----------------------------------------------------------------
# ant build directories
# -----------------------------------------------------------------
sandbox.dir = ${projectDir}/../..
reno.root.dir=${sandbox.dir}/Reno
ant.dir = ${projectDir}/ant
build.dir = ${ant.dir}/build
log.dir = ${ant.dir}/logs
config.dir = ${ant.dir}/configs
deploy.dir = ${ant.dir}/deploy
static.dir = ${ant.dir}/static
package.dir = ${ant.dir}/package
tests.dir = ${ant.dir}/tests
tests.logs.dir = ${tests.dir}/logs
external.dir = ${sandbox.dir}/FlexCommon/External
external.lib.dir = ${external.dir}/libs
If using the default gradle.properties file, you can access the properties directly from within your build.gradle file:
gradle.properties:
applicationName=Admin
projectName=Hello Cool
build.gradle:
task printProps {
doFirst {
println applicationName
println projectName
}
}
If you need to access a custom file, or access properties which include . in them (as it appears you need to do), you can do the following in your build.gradle file:
def props = new Properties()
file("build.properties").withInputStream { props.load(it) }
task printProps {
doFirst {
println props.getProperty("application.name")
println props.getProperty("project.name")
}
}
Take a look at this section of the Gradle documentation for more information.
Edit
If you'd like to dynamically set up some of these properties (as mentioned in a comment below), you can create a properties.gradle file (the name isn't important) and require it in your build.gradle script.
properties.gradle:
ext {
subPath = "some/sub/directory"
fullPath = "$projectDir/$subPath"
}
build.gradle
apply from: 'properties.gradle'
// prints the full expanded path
println fullPath
We can use a separate file (config.groovy in my case) to abstract out all the configuration.
In this example, we're using three environments viz.,
dev
test
prod
which has properties serverName, serverPort and resources. Here we're expecting that the third property resources may be same in multiple environments and so we've abstracted out that logic and overridden in the specific environment wherever necessary:
config.groovy
resources {
serverName = 'localhost'
serverPort = '8090'
}
environments {
dev {
serverName = 'http://localhost'
serverPort = '8080'
}
test {
serverName = 'http://www.testserver.com'
serverPort = '5211'
resources {
serverName = 'resources.testserver.com'
}
}
prod {
serverName = 'http://www.productionserver.com'
serverPort = '80'
resources {
serverName = 'resources.productionserver.com'
serverPort = '80'
}
}
}
Once the properties file is ready, we can use the following in build.gradle to load these settings:
build.gradle
loadProperties()
def loadProperties() {
def environment = hasProperty('env') ? env : 'dev'
println "Current Environment: " + environment
def configFile = file('config.groovy')
def config = new ConfigSlurper(environment).parse(configFile.toURL())
project.ext.config = config
}
task printProperties {
println "serverName: $config.serverName"
println "serverPort: $config.serverPort"
println "resources.serverName: $config.resources.serverName"
println "resources.serverPort: $config.resources.serverPort"
}
Let's run these with different set of inputs:
gradle -q printProperties
Current Environment: dev
serverName: http://localhost
serverPort: 8080
resources.serverName: localhost
resources.serverPort: 8090
gradle -q -Penv=dev printProperties
Current Environment: dev
serverName: http://localhost
serverPort: 8080
resources.serverName: localhost
resources.serverPort: 8090
gradle -q -Penv=test printProperties
Current Environment: test
serverName: http://www.testserver.com
serverPort: 5211
resources.serverName: resources.testserver.com
resources.serverPort: 8090
gradle -q -Penv=prod printProperties
Current Environment: prod
serverName: http://www.productionserver.com
serverPort: 80
resources.serverName: resources.productionserver.com
resources.serverPort: 80
Another way... in build.gradle:
Add :
classpath 'org.flywaydb:flyway-gradle-plugin:3.1'
And this :
def props = new Properties()
file("src/main/resources/application.properties").withInputStream { props.load(it) }
apply plugin: 'flyway'
flyway {
url = props.getProperty("spring.datasource.url")
user = props.getProperty("spring.datasource.username")
password = props.getProperty("spring.datasource.password")
schemas = ['db_example']
}
This is for Kotlin DSL (build.gradle.kts):
import java.util.*
// ...
val properties = Properties().apply {
load(rootProject.file("my-local.properties").reader())
}
val prop = properties["myPropName"]
In Android projects (when applying the android plugin) you can also do this:
import com.android.build.gradle.internal.cxx.configure.gradleLocalProperties
// ...
val properties = gradleLocalProperties(rootDir)
val prop = properties["propName"]
Just had this issue come up today. We found the following worked both locally and in our pipeline:
In build.gradle:
try {
apply from: 'path/name_of_external_props_file.properties'
} catch (Exception e) {}
This way when an external props file which shouldn't get committed to Git or whatever (as in our case) you are using is not found in the pipeline, this 'apply from:' won't throw an error in it. In our use case we have a file with a userid and password that should not get committed to Git. Aside from the problem of file-reading: we found that the variables we had declared in the external file, maven_user and maven_pass, had in fact to be declared in gradle.properties. That is they simply needed to be mentioned as in:
projectName=Some_project_name
version=1.x.y
maven_user=
maven_pass=
We also found that in the external file we had to put single-quotes around these values too or Gradle got confused. So the external file looked like this:
maven_user='abc123'
maven_pass='fghifh7435bvibry9y99ghhrhg9539y5398'
instead of this:
maven_user=abc123
maven_pass=fghifh7435bvibry9y99ghhrhg9539y5398
That's all we had to do and we were fine. I hope this may help others.
I am trying to create multiple start script files through gradle. But somehow one particular start script file is getting duplicated.
startScripts.enabled = false
run.enabled = false
def createScript(project, mainClass, name) {
project.tasks.create(name: name, type: CreateStartScripts) {
outputDir = new File(project.buildDir, 'scripts')
mainClassName = mainClass
applicationName = name
classpath = jar.outputs.files + project.configurations.runtime
doLast {
def windowsScriptFile = file getWindowsScript()
def unixScriptFile = file getUnixScript()
windowsScriptFile.text = windowsScriptFile.text.replace('%APP_HOME%\\lib\\conf', '%APP_HOME%\\conf')
unixScriptFile.text = unixScriptFile.text.replace('$APP_HOME/lib/conf', '$APP_HOME/conf')
}
}
project.tasks[name].dependsOn(project.jar)
project.applicationDistribution.with {
into("bin") {
from(project.tasks[name])
fileMode = 0755
}
}
}
// Call this for each Main class you want to expose with an app script
createScript(project, 'com.main.A', 'A')
createScript(project, 'com.main.B', 'B')
in bin directory I can see,
A.sh
A.sh
A.bat
A.bat
B.sh
B.bat
What am I missing here? How to fix this?
Thank you for help.
I solved this problem. Actually it was a mistake from my side and thanks to #Opal. I somehow forgot to delete 'mainClassName="com.main.A"' line from the header.
Also I have to add
distZip {
duplicatesStrategy = 'exclude'
}