Below are two tasks hello & printProperties in build.gradle:
task('hello', {
description("Hey student! Run this one :D")
group("Our demo")
doLast({println("Hello World!")})
}
)
plugins({
id('java')
})
ext({
springVersion = "3.1.0.RELEASE"
emailNotification = "build#master.org"
})
sourceSets.all({ ext.purpose = null })
sourceSets({
main({
purpose = "production"
})
test({
purpose = "test"
})
plugin({
purpose = "production"
})
})
task('printProperties', {
doLast({
println(springVersion)
println(emailNotification)
sourceSets.matching({ it.purpose == "production" }.each({ println it.name }))
})
})
that gives error:
> startup failed:
build file '/../../build.gradle': 8:
only buildscript {} and other plugins {} script blocks are allowed before plugins {} blocks, no other statements are allowed
Why plugins({id('java')}) give groovy scripted syntax error?
It's answered here : https://stackoverflow.com/a/48611069/1250435
Whenever you write a build.gradle script and use the new plugins
script block, you need to put it as first block in the file. The only
exceptions from this rule are other plugins blocks or the special
buildScript block, which always must go first.
Related
I have a lambda function that is written in nodejs (using AWS nodejs SDK) and we are using gradle (build.gradle) to package and deploy that to AWS.
Deployment is working fine but when I am trying to update tags on this Lambda and redeploying then the new tags are not being applied to that function.
So if I am deploying Lambda using build.gradle first time with TAG A then its working fine (By first time I mean when I am creating a new Lambda) and tag is being applied and I can see that on AWS Console. But when I am re-deploying it again by adding another tag "TAG B" then the new tag is not being applied and it is not updating the existing Lambda tags. Any idea or suggestion what I am doing wrong? Thanks
Below is the section of build.gradle file where I am applying the tags for Lambda.
createOrUpdateFunction {
handler = 'index.handler'
role = cfo.DataDigestContentSearchLambdaIamRoleArn
runtime = 'python3.7'
timeout = 10
tags = [
tagA: 'data-team',
tagB: 'someValue'
]
Here is the complete build.gradle file
import com.amazonaws.services.lambda.model.TagResourceRequest
apply plugin: 'com.abc.gradle.nodejs.yarn'
apply plugin: 'com.abc.gradle.aws.lambda.deployment'
apply from: rootProject.file('gradle/yarn-webpacked-lambda.gradle')
nodejs {
packaging {
name = '#abc/data-fulfillment-facebook-lambda'
dependency project(':core:js')
dependency project(':platforms:facebook:js:core')
dependency '#abc/data-ingest-api', abc_INGEST_SEMVER
dependency '#abc/data-ingest-core', abc_INGEST_SEMVER
dependency 'aws-sdk', AWS_SEMVER
}
}
webpackPackageJson.dependencies << ['fb': FB_SEMVER]
lambdaRepository {
artifactName = 'data-fulfillment-facebook'
}
lambda {
functionName = "${config.aws.target.envPrefix}-${lambdaRepository.artifactName}"
}
def cfo = cloudformation.outputs as Map<String, String>
createOrUpdateFunction {
handler = 'index.handler'
role = cfo.DataFulfillmentFacebookLambdaIamRoleArn
runtime = 'nodejs12.x'
memorySize = 256
timeout = 30
tags = [
team: 'data-team',
name: 'someName'
]
environmentAsMap << [
FACEBOOK_LEDGER_TABLE_NAME: cfo.DataFulfillmentLedgerTableName,
INSTAGRAM_DISCOVERY_TOKEN_SECRET: cfo.DataFulfillmentInstagramDiscoveryTokenSecretName
]
}
task registerTaskProcessor(type: RegisterTaskProcessorTask) {
client 'target'
tableName = cfo.DataFulfillmentTaskProcessorRegistryV2TableName
entryName = 'facebook'
rules << [regex: ['^facebook', [var: 'task.type']]]
type = 'lambda-dispatch'
params << [functionName: lambda.functionName, qualifier: 'live']
}
I'm using JIB (not super relevant) and I want to pass in variables from command line in my deployment script.
I append using -PinputTag=${DOCKER_TAG} -PbuildEnv=nonprod in my gradle command, which is cool. But when it's missing, I want that ternary to kick in.
I'm getting the error:
Could not get unknown property 'inputTag' for project ':webserver' of type org.gradle.api.Project.
def inputTag = inputTag ?: 'latest'
def buildEnv = buildEnv ?: 'nonprod'
jib {
container {
mainClass = 'com.example.hi'
}
to {
image = 'image/cool-image'
tags = ['latest', inputTag]
}
container {
creationTime = 'USE_CURRENT_TIMESTAMP'
ports = ['8080']
jvmFlags = ['-Dspring.profiles.active=' + buildEnv]
}
}
Found Solution
def inputTag = project.hasProperty('inputTag') ? project.property('inputTag') : 'latest'
def buildEnv = project.hasProperty('buildEnv') ? project.property('buildEnv') : 'nonprod'
This seems to be working, is this the best way?
How about this?
image = 'image/cool-image:' + (project.findProperty('inputTag') ?: 'latest')
Note jib.to.tags are additional tags. jib.to.image = 'image/cool-image' already implies image/cool-image:latest, so no need to duplicate latest in jib.to.tags.
I am trying to apply a plugin on a project that is a company specific findbugs plugin. In my Parent gradle project I have the following:
dependencies {
findbugs 'com.google.code.findbugs.findbugs:3.0.1'
findbugs configurations.findbugsPlugins.dependencies
// Here we specify the findbugsPlugins
findbugsPlugins 'com.company.common.company-findbugs-plugin:1.01'
}
task findbugs(type: FindBugs) {
classes = fileTree(project.rootDir.absolutePath).include("**/*.class");
source = fileTree(project.rootDir.absolutePath).include("**/*.java");
classpath = files()
pluginClasspath = project.configurations.findbugsPlugins
findbugs {
toolVersion = "3.0.1"
sourceSets = [sourceSets.main]
ignoreFailures = true
reportsDir = file("$project.buildDir/findbugsReports")
effort = "max"
reportLevel = "high"
includeFilter = file("$rootProject.projectDir/include.xml")
excludeFilter = file("$rootProject.projectDir/exclude.xml")
}
tasks.withType(FindBugs) {
reports {
xml.enabled = false
html.enabled = true
}
}
}
However, when I build the project, the build fails with an exception reporting:
Could not resolve all dependencies for configuration ':findbugsPlugins'.
> Could not find com.company.common.company-findbugs-plugin:1.01:.
Searched in the following locations:
http://artifactory.company.com:8081/artifactory/repo/com/company/common/company-findbugs-plugin/1.01//1.01-.pom
http://artifactory.company.com:8081/artifactory/repo/com/company/common/company-findbugs-plugin/1.01//1.01-.jar
Required by:
com.company.project:ProjectName1.0.4
Any reason why gradle is adding the version twice at the end of the path?
You have incorrectly defined the Gradle dependency, colon is missing between GroupId and ArtifactId:
'com.google.code.findbugs:findbugs:3.0.1'
and the same most likely applies for
'com.company.common:company-findbugs-plugin:1.01'
In my gradle script I've been able to successfully read properties like this:
def environment = hasProperty('env') ? env : 'dev'
Using this I can execute a build script like this:
gradlew clean assemble -Penv=prod
My issue comes in when I tried moving this to an init.gradle file. The file is recognized and I'm able to use other properties that I define in the script, however I'm not able to get any from the command line. How can I do this?
My init.gradle file:
allprojects {
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.+'
}
}
project.ext['nexusDomainName'] = 'https://example.com/nexus'
project.ext['compileSdkVersion'] = 19
project.ext['buildToolsVersion'] = "19"
project.ext['minSdkVersion'] = 8
project.ext['targetSdkVersion'] = 19
project.ext['sourceCompatibility'] = '1.7'
project.ext['targetCompatibility'] = '1.7'
//hasProperty('release') is always false
project.ext['archiveType'] = hasProperty('release') ? '' : '-SNAPSHOT'
project.ext['archiveUrl'] = hasProperty('release') ? "$nexusDomainName/content/repositories/releases/" : "$nexusDomainName/content/repositories/snapshots/"
// This buildEnv property won't read either
project.ext['buildEnv'] = hasProperty('env') ? env : 'dev'
println "prepping for $buildEnv"
project.ext['archivesBaseNameSuffix'] = (project.ext['buildEnv'] == 'stage' || project.ext['buildEnv'] == 'dev') ? '-' + project.ext['buildEnv'] : ''
repositories {
mavenLocal()
maven {
credentials {
username 'username'
password 'password'
}
url "$nexusDomainName/content/groups/public/"
}
mavenCentral()
}
}
-P sets a project property, which isn't immediately available in an init script. (You can access projects and their properties from an init script, but that access will be deferred until the projects have been created.) However, using a system property (-D) should work.
Is it possible to listen to CTRL+C when a groovy script is run from the command line ?
I have a script that creates some files. If interrupted I want to delete them from disk and then terminate.
Possible?
UPDATE 1:
Derived from #tim_yates answer:
def withInteruptionListener = { Closure cloj, Closure onInterrupt ->
def thread = { onInterrupt?.call() } as Thread
Runtime.runtime.addShutdownHook (thread)
cloj();
Runtime.runtime.removeShutdownHook (thread)
}
withInteruptionListener ({
println "Do this"
sleep(3000)
throw new java.lang.RuntimeException("Just to see that this is also taken care of")
}, {
println "Interupted! Clean up!"
})
The following should work:
CLEANUP_REQUIRED = true
Runtime.runtime.addShutdownHook {
println "Shutting down..."
if( CLEANUP_REQUIRED ) {
println "Cleaning up..."
}
}
(1..10).each {
sleep( 1000 )
}
CLEANUP_REQUIRED = false
As you can see, (as #DaveNewton points out), "Shutting down..." will be printed when the user presses CTRL-C, or the process finishes normally, so you'd need some method of detecting whether cleanup is required
Update
For the sake of curiosity, here is how you would do it using the unsupported sun.misc classes:
import sun.misc.Signal
import sun.misc.SignalHandler
def oldHandler
oldHandler = Signal.handle( new Signal("INT"), [ handle:{ sig ->
println "Caught SIGINT"
if( oldHandler ) oldHandler.handle( sig )
} ] as SignalHandler );
(1..10).each {
sleep( 1000 )
}
But obviously, those classes can't be recommended as they might disappear/change/move
I am not much into groovy script but i have a link that have some examples and says catching ctrl+c.....hope that helps http://pleac.sourceforge.net/pleac_groovy/processmanagementetc.html