SlideShare une entreprise Scribd logo
1  sur  45
Télécharger pour lire hors ligne
#DevoxxMA @DevoxxMA © Sch
IDIOMATIC GRADLE
PLUGIN WRITING
Schalk W. Cronjé
ABOUT ME
Email:
Twitter / Ello : @ysb33r
ysb33r@gmail.com
Gradle plugins authored/contributed to: VFS, Asciidoctor,
JRuby family (base, jar, war etc.), GnuMake, Doxygen
ABOUT THIS PRESENTATION
Written in Asciidoctor (1.5.3.2)
Styled by asciidoctor-revealjs extension
Built using:
Gradle
gradle-asciidoctor-plugin
gradle-vfs-plugin
THE PROBLEM
There is no consistency in the way plugin authors craft extensions
to the Gradle DSL today
QUALITY ATTRIBUTES OF DSL
Readability
Consistency
Flexibility
Expressiveness
FOR BEST COMPATIBILITY
Support same JDK range as Gradle
Gradle 1.x - mininum JDK5
Gradle 2.x - minimum JDK6
Build against Gradle 2.0
Only use later versions if specific new functionality is
required.
Suggested baseline at Gradle 2.6
FOR BEST COMPATIBILITY
// build.gradle
targetCompatibility = 1.6
sourceCompatibility = 1.6
project.tasks.withType(JavaCompile) { task ->
task.sourceCompatibility = project.sourceCompatibility
task.targetCompatibility = project.targetCompatibility
}
project.tasks.withType(GroovyCompile) { task ->
task.sourceCompatibility = project.sourceCompatibility
task.targetCompatibility = project.targetCompatibility
}
// gradle/wrapper/gradle-wrapper.properties
distributionUrl=https://..../distributions/gradle-2.0-all.zip
NOMENCLATURE
Property: A public data member (A Groovy property)
Method: A standard Java/Groovy method
Attribute: A value, set or accessed via the Gradle DSL. Can
result in a public method call or property access.
User: Person authoring or executing a Gradle build script
@Input
String aProperty = 'stdValue'
@Input
void aValue(String s) { ... }
myTask {
aProperty = 'newValue'
aValue 'newValue'
}
PREFER METHODS OVER PROPERTIES
( IOW To assign or not to assign )
Methods provide more flexibility
Tend to provide better readability
Assignment is better suited towards
One-shot attribute setting
Overriding default attributes
Non-lazy evaluation
HOW NOT 2 : COLLECTION OF FILES
Typical implementation …​
class MyTask extends DefaultTask {
@InputFiles
List<File> mySources
}
leads to ugly DSL
task myTask( type: MyTask ) {
myTask = [ file('foo/bar.txt'), new File( 'bar/foo.txt') ]
}
COLLECTION OF FILES
myTask {
mySources file( 'path/foobar' )
mySources new File( 'path2/foobar' )
mySources 'file3', 'file4'
mySources { "lazy evaluate file name later on" }
}
Allow ability to:
Use strings and other objects convertible to File
Append lists
Evaluate as late as possible
Reset default values
COLLECTION OF FILES
Ignore Groovy shortcut; use three methods
class MyTask extends DefaultTask {
@InputFiles
FileCollection getDocuments() {
project.files(this.documents) // magic API method
}
void setDocuments(Object... docs) {
this.documents.clear()
this.documents.addAll(docs as List)
}
void documents(Object... docs) {
this.documents.addAll(docs as List)
}
private List<Object> documents = []
}
STYLE : TASKS
Provide a default instantiation of your new task class
Keep in mind that user would want to create additional
tasks of same type
Make it easy for them!!
KNOW YOUR ANNOTATIONS
@Input
@InputFile
@InputFiles
@InputDirectory
@OutputFile
@OutputFiles
@OutputDirectory
@OutputDirectories
@Optional
COLLECTION OF STRINGS
import org.gradle.util.CollectionUtils
Ignore Groovy shortcut; use three methods
@Input
List<String> getScriptArgs() {
// stringize() is your next magic API method
CollectionUtils.stringize(this.scriptArgs)
}
void setScriptArgs(Object... args) {
this.scriptArgs.clear()
this.scriptArgs.addAll(args as List)
}
void scriptArgs(Object... args) {
this.scriptArgs.addAll(args as List)
}
private List<Object> scriptArgs = []
HOW NOT 2 : MAPS
Typical implementation …​
class MyTask extends DefaultTask {
@Input
Map myOptions
}
leads to ugly DSL
task myTask( type: MyTask ) {
myOptions = [ prop1 : 'foo/bar.txt', prop2 : 'bar/foo.txt' ]
}
MAPS
task myTask( type: MyTask ) {
myOptions prop1 : 'foo/bar.txt', prop2 : 'bar/foo.txt'
myOptions prop3 : 'add/another'
// Explicit reset
myOptions = [:]
}
MAPS
@Input
Map getMyOptions() {
this.attrs
}
void setMyOptions(Map m) {
this.attrs=m
}
void myOptions(Map m) {
this.attrs+=m
}
private Map attrs = [:]
USER OVERRIDE LIBRARY VERSION
Ship with prefered (and tested) version of dependent
library set as default
Allow user flexibility to try a different version of such
library
Dynamically load library when needed
Still use power of Gradle’s dependency resolution
USER OVERRIDE LIBRARY VERSION
Example DSL from Asciidoctor
asciidoctorj {
version = '1.6.0-SNAPSHOT'
}
Example DSL from JRuby Base
jruby {
execVersion = '1.7.12'
}
USER OVERRIDE LIBRARY VERSION
1. Create Extension
2. Add extension object in plugin apply
3. Create custom classloader
USER OVERRIDE LIBRARY VERSION
Step 1: Create project extension
class MyExtension {
// Set the default dependent library version
String version = '1.5.0'
MyExtension(Project proj) {
project= proj
}
@PackageScope
Project project
}
USER OVERRIDE LIBRARY VERSION
Step 2: Add extension object in plugin apply
class MyPlugin implements Plugin<Project> {
void apply(Project project) {
// Create the extension & configuration
project.extensions.create('asciidoctorj',MyExtension,project)
project.configuration.maybeCreate( 'int_asciidoctorj' )
// Add dependency at the end of configuration phase
project.afterEvaluate {
project.dependencies {
int_asciidoctorj "org.asciidoctor:asciidoctorj" +
"${project.asciidoctorj.version}"
}
}
}
}
USER OVERRIDE LIBRARY VERSION (2.5+)
Step 2: Add extension object Gradle 2.5+
class MyPlugin implements Plugin<Project> {
void apply(Project project) {
// Create the extension & configuration
project.extensions.create('asciidoctorj',MyExtension,project)
def conf = configurations.maybeCreate( 'int_asciidoctorj' )
conf.defaultDependencies { deps ->
deps.add( project.dependencies.create(
"org.asciidoctor:asciidoctorj:${asciidoctorj.version}")
)
}
}
}
USER OVERRIDE LIBRARY VERSION
Step 3: Custom classloader (usually loaded from task action)
// Get all of the files in the `asciidoctorj` configuration
def urls = project.configurations.int_asciidoctorj.files.collect {
it.toURI().toURL()
}
// Create the classloader for all those files
def classLoader = new URLClassLoader(urls as URL[],
Thread.currentThread().contextClassLoader)
// Load one or more classes as required
def instance = classLoader.loadClass(
'org.asciidoctor.Asciidoctor$Factory')
NEED 2 KNOW : 'AFTEREVALUATE'
afterEvaluate adds to a list of closures to be executed
at end of configuration phase
Execution order is FIFO
Plugin author has no control over the order
STYLE : PROJECT EXTENSIONS
Treat project extensions as you would for any kind of
global configuration.
With care!
Do not make the extension configuration block a task
configuration.
Task instantiation may read defaults from extension.
Do not force extension values onto tasks
NEED 2 KNOW : PLUGINS
Plugin author has no control over order in which plugins
will be applied
Handle both cases of related plugin applied before or after
yours
EXTEND EXISTING TASK
Task type extension by inheritance is not always best
solution
Adding behaviour to existing task type better in certain
contexts
Example: jruby-jar-plugin wants to semantically
describe bootstrap files rather than force user to use
standard Copy syntax
EXTEND EXISTING TASK
jruby-jar-plugin without extension
jrubyJavaBootstrap {
// User gets exposed (unnecessarily) to the underlying task type
// Has to craft too much glue code
from( {
// @#$$!!-ugly code goes here
} )
}
jruby-jar-plugin with extension
jrubyJavaBootstrap {
// Expressing intent & context.
jruby {
initScript = 'bin/asciidoctor'
}
}
EXTEND EXISTING TASK
1. Create extension class
2. Add extension to task
3. Link extension attributes to task attributes (for caching)
EXTEND EXISTING TASK
Create extension class
class MyExtension {
String initScript
MyExtension( Task t ) {
// TODO: Add Gradle caching support
// (See later slide)
}
}
EXTEND EXISTING TASK
Add extension class to task
class MyPlugin implements Plugin<Project> {
void apply(Project project) {
Task stubTask = project.tasks.create
( name : 'jrubyJavaBootstrap', type : Copy )
stubTask.extensions.create(
'jruby',
MyExtension,
stubTask
)
}
EXTEND EXISTING TASK
Add Gradle caching support
class MyExtension {
String initScript
MyExtension( Task t ) {
// Tell the task the initScript is also a property
t.inputs.property 'jrubyInitScript' , { -> this.initScript }
}
}
NEED 2 KNOW : TASK EXTENSIONS
Good way extend existing tasks in composable way
Attributes on extensions are not cached
Changes will not cause a rebuild of the task
Do the extra work to cache and provide the user with a
better experience.
HONOUR OFFLINE
gradle --offline
The build should operate without accessing
network resources.
HONOUR OFFLINE
Unset the enabled property, if build is offline
task VfsCopy extends DefaultTask {
VfsCopy() {
enabled = !project.gradle.startParameter.isOffline()
}
}
TRICK : SAFE FILENAMES
Ability to create safe filenames on all platforms from input
data
Example: Asciidoctor output directories based upon
backend names
// WARNING: Using a very useful internal API
import org.gradle.internal.FileUtils
File outputBackendDir(final File outputDir,
final String backend) {
// FileUtils.toSafeFileName is your magic method
new File(outputDir, FileUtils.toSafeFileName(backend))
}
TRICK : SELF-REFERENCING PLUGIN
New plugin depends on functionality in the plugin
Apply plugin direct in build.gradle
apply plugin: new GroovyScriptEngine(
['src/main/groovy','src/main/resources'].
collect{ file(it).absolutePath }
.toArray(new String[2]),
project.class.classLoader
).loadScriptByName('book/SelfReferencingPlugin.groovy')
COMPATIBILITY TESTING
How can a plugin author test a plugin against multiple Gradle
versions?
COMPATIBILITY TESTING
Gradle 2.7 added TestKit
Gradle 2.9 added multi-distribution testing
TestKit still falls short in ease-of-use
(Hopefully to be corrected over future releases)
What to do for Gradle 2.0 - 2.8?
COMPATIBILITY TESTING
GradleTest plugin to the rescue
buildscript {
dependencies {
classpath "org.ysb33r.gradle:gradletest:0.5.4"
}
}
apply plugin : 'org.ysb33r.gradletest'
http://bit.ly/1LfUUU4
COMPATIBILITY TESTING
Create src/gradleTest/NameOfTest folder.
Add build.gradle
Add task runGradleTest
Add project structure
COMPATIBILITY TESTING
Add versions to main build.gradle
gradleTest {
versions '2.0', '2.2', '2.4', '2.5', '2.9'
}
Run it!
./gradlew gradleTest
THANK YOU
Keep your DSL
extensions beautiful
Don’t spring surprising
behaviour on the user
Email:
Twitter / Ello : @ysb33r
#idiomaticgradle
(devoxxma2015)
ysb33r@gmail.com
http://bit.ly/1iJmdiP

Contenu connexe

Tendances

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
Android application model
Android application modelAndroid application model
Android application model
magicshui
 

Tendances (20)

Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
The world of gradle - an introduction for developers
The world of gradle  - an introduction for developersThe world of gradle  - an introduction for developers
The world of gradle - an introduction for developers
 
GradleFX
GradleFXGradleFX
GradleFX
 
Scala and Play with Gradle
Scala and Play with GradleScala and Play with Gradle
Scala and Play with Gradle
 
[Image Results] Java Build Tools: Part 2 - A Decision Maker's Guide Compariso...
[Image Results] Java Build Tools: Part 2 - A Decision Maker's Guide Compariso...[Image Results] Java Build Tools: Part 2 - A Decision Maker's Guide Compariso...
[Image Results] Java Build Tools: Part 2 - A Decision Maker's Guide Compariso...
 
In the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: Gradle
 
Android development with Scala and SBT
Android development with Scala and SBTAndroid development with Scala and SBT
Android development with Scala and SBT
 
Gradle: The Build System you have been waiting for!
Gradle: The Build System you have been waiting for!Gradle: The Build System you have been waiting for!
Gradle: The Build System you have been waiting for!
 
Gradle - time for another build
Gradle - time for another buildGradle - time for another build
Gradle - time for another build
 
Kubernetes
KubernetesKubernetes
Kubernetes
 
OrientDB - The 2nd generation of (multi-model) NoSQL
OrientDB - The 2nd generation of  (multi-model) NoSQLOrientDB - The 2nd generation of  (multi-model) NoSQL
OrientDB - The 2nd generation of (multi-model) NoSQL
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Gradle,the new build system for android
Gradle,the new build system for androidGradle,the new build system for android
Gradle,the new build system for android
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
NetBeans Support for EcmaScript 6
NetBeans Support for EcmaScript 6NetBeans Support for EcmaScript 6
NetBeans Support for EcmaScript 6
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 
Android application model
Android application modelAndroid application model
Android application model
 
Spring & Hibernate
Spring & HibernateSpring & Hibernate
Spring & Hibernate
 

En vedette

ZOO_DIGITAL_300414 HR
ZOO_DIGITAL_300414 HRZOO_DIGITAL_300414 HR
ZOO_DIGITAL_300414 HR
Lars Clausen
 
2016 New Lighting Technology Ivan Tchakarov
2016 New Lighting Technology Ivan Tchakarov2016 New Lighting Technology Ivan Tchakarov
2016 New Lighting Technology Ivan Tchakarov
Ivan Tchakarov
 
Pritam Naik Resume
Pritam Naik ResumePritam Naik Resume
Pritam Naik Resume
pritam naik
 

En vedette (14)

Trabajo práctico ayudantía 2011
Trabajo práctico ayudantía 2011Trabajo práctico ayudantía 2011
Trabajo práctico ayudantía 2011
 
Building an Open Source, Real-Time, Billion Object Spatio-Temporal Search Pla...
Building an Open Source, Real-Time, Billion Object Spatio-Temporal Search Pla...Building an Open Source, Real-Time, Billion Object Spatio-Temporal Search Pla...
Building an Open Source, Real-Time, Billion Object Spatio-Temporal Search Pla...
 
ZOO_DIGITAL_300414 HR
ZOO_DIGITAL_300414 HRZOO_DIGITAL_300414 HR
ZOO_DIGITAL_300414 HR
 
Clivaje y elecciones de 1851 - CHILE
Clivaje y elecciones de 1851 - CHILEClivaje y elecciones de 1851 - CHILE
Clivaje y elecciones de 1851 - CHILE
 
Las plantas
Las plantasLas plantas
Las plantas
 
2016 New Lighting Technology Ivan Tchakarov
2016 New Lighting Technology Ivan Tchakarov2016 New Lighting Technology Ivan Tchakarov
2016 New Lighting Technology Ivan Tchakarov
 
Your application ever up-to-date? Go continuous delivery
Your application ever up-to-date? Go continuous deliveryYour application ever up-to-date? Go continuous delivery
Your application ever up-to-date? Go continuous delivery
 
Nuevas Tecnologias
Nuevas TecnologiasNuevas Tecnologias
Nuevas Tecnologias
 
DocDoc's Guide To Digital Marketing
DocDoc's Guide To Digital MarketingDocDoc's Guide To Digital Marketing
DocDoc's Guide To Digital Marketing
 
Pritam Naik Resume
Pritam Naik ResumePritam Naik Resume
Pritam Naik Resume
 
Gradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 versionGradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 version
 
Voxxed Belgrade 2016
Voxxed Belgrade 2016Voxxed Belgrade 2016
Voxxed Belgrade 2016
 
Java Docs
Java DocsJava Docs
Java Docs
 
Кастомная разработка в области E-Commerce
Кастомная разработка в области E-CommerceКастомная разработка в области E-Commerce
Кастомная разработка в области E-Commerce
 

Similaire à Idiomatic Gradle Plugin Writing

Gradle - small introduction
Gradle - small introductionGradle - small introduction
Gradle - small introduction
Igor Popov
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
Tino Isnich
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 

Similaire à Idiomatic Gradle Plugin Writing (20)

Gradle plugin, take control of the build
Gradle plugin, take control of the buildGradle plugin, take control of the build
Gradle plugin, take control of the build
 
Idiomatic Gradle Plugin Writing - GradleSummit 2016
Idiomatic Gradle Plugin Writing - GradleSummit 2016Idiomatic Gradle Plugin Writing - GradleSummit 2016
Idiomatic Gradle Plugin Writing - GradleSummit 2016
 
Anatomy of a Gradle plugin
Anatomy of a Gradle pluginAnatomy of a Gradle plugin
Anatomy of a Gradle plugin
 
Making the Most of Your Gradle Build
Making the Most of Your Gradle BuildMaking the Most of Your Gradle Build
Making the Most of Your Gradle Build
 
Making the Most of Your Gradle Build
Making the Most of Your Gradle BuildMaking the Most of Your Gradle Build
Making the Most of Your Gradle Build
 
Improving your Gradle builds
Improving your Gradle buildsImproving your Gradle builds
Improving your Gradle builds
 
Dependency injection in scala
Dependency injection in scalaDependency injection in scala
Dependency injection in scala
 
Gradle - small introduction
Gradle - small introductionGradle - small introduction
Gradle - small introduction
 
Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017
 
Gradle plugins, take it to the next level
Gradle plugins, take it to the next levelGradle plugins, take it to the next level
Gradle plugins, take it to the next level
 
Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017
 
Building maintainable javascript applications
Building maintainable javascript applicationsBuilding maintainable javascript applications
Building maintainable javascript applications
 
Asciidoctor, because documentation does not have to suck
Asciidoctor, because documentation does not have to suckAsciidoctor, because documentation does not have to suck
Asciidoctor, because documentation does not have to suck
 
Dart Workshop
Dart WorkshopDart Workshop
Dart Workshop
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdf
 
DocuOps & Asciidoctor in a JVM World
DocuOps & Asciidoctor in a JVM WorldDocuOps & Asciidoctor in a JVM World
DocuOps & Asciidoctor in a JVM World
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
 
Gradle in a Polyglot World
Gradle in a Polyglot WorldGradle in a Polyglot World
Gradle in a Polyglot World
 
Gradle plugins 101
Gradle plugins 101Gradle plugins 101
Gradle plugins 101
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 

Plus de Schalk Cronjé

Plus de Schalk Cronjé (20)

DocuOps & Asciidoctor
DocuOps & AsciidoctorDocuOps & Asciidoctor
DocuOps & Asciidoctor
 
What's new in Asciidoctor
What's new in AsciidoctorWhat's new in Asciidoctor
What's new in Asciidoctor
 
Probability Management
Probability ManagementProbability Management
Probability Management
 
Seeking Enligtenment - A journey of purpose rather than instruction
Seeking Enligtenment  - A journey of purpose rather than instructionSeeking Enligtenment  - A journey of purpose rather than instruction
Seeking Enligtenment - A journey of purpose rather than instruction
 
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers VersionCool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
 
Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You Test
 
Using the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM DevelopmentUsing the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM Development
 
Seeking Enligtenment - A journey of purpose rather tan instruction
Seeking Enligtenment - A journey of purpose rather tan instructionSeeking Enligtenment - A journey of purpose rather tan instruction
Seeking Enligtenment - A journey of purpose rather tan instruction
 
Beyond Estimates - Probability Management
Beyond Estimates - Probability ManagementBeyond Estimates - Probability Management
Beyond Estimates - Probability Management
 
Documentation An Engineering Problem Unsolved
Documentation  An Engineering Problem UnsolvedDocumentation  An Engineering Problem Unsolved
Documentation An Engineering Problem Unsolved
 
Death of Agile : Welcome to Value-focused Testing
Death of Agile : Welcome to Value-focused TestingDeath of Agile : Welcome to Value-focused Testing
Death of Agile : Welcome to Value-focused Testing
 
Asciidoctor in 15min
Asciidoctor in 15minAsciidoctor in 15min
Asciidoctor in 15min
 
Tree of Knowledge - About Philosophy, Unity & Testing
Tree of Knowledge - About Philosophy, Unity & TestingTree of Knowledge - About Philosophy, Unity & Testing
Tree of Knowledge - About Philosophy, Unity & Testing
 
Beyond estimates - Overview at Agile:MK
Beyond estimates - Overview at Agile:MKBeyond estimates - Overview at Agile:MK
Beyond estimates - Overview at Agile:MK
 
Groovy VFS (with 1.0 news)
Groovy VFS (with 1.0 news)Groovy VFS (with 1.0 news)
Groovy VFS (with 1.0 news)
 
Beyond estimates - Reflection on the state of Agile Forecasting
Beyond estimates - Reflection on the state of Agile ForecastingBeyond estimates - Reflection on the state of Agile Forecasting
Beyond estimates - Reflection on the state of Agile Forecasting
 
Seeking enligtenment - A journey of "Why?" rather than "How?"
Seeking enligtenment - A journey of "Why?" rather than "How?"Seeking enligtenment - A journey of "Why?" rather than "How?"
Seeking enligtenment - A journey of "Why?" rather than "How?"
 
RfC2822 for Mere Mortals
RfC2822 for Mere MortalsRfC2822 for Mere Mortals
RfC2822 for Mere Mortals
 
Groovy VFS
Groovy VFSGroovy VFS
Groovy VFS
 
Prosperity-focused Agile Technology Leadership
Prosperity-focused Agile Technology LeadershipProsperity-focused Agile Technology Leadership
Prosperity-focused Agile Technology Leadership
 

Dernier

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 

Dernier (20)

VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 

Idiomatic Gradle Plugin Writing

  • 1. #DevoxxMA @DevoxxMA © Sch IDIOMATIC GRADLE PLUGIN WRITING Schalk W. Cronjé
  • 2. ABOUT ME Email: Twitter / Ello : @ysb33r ysb33r@gmail.com Gradle plugins authored/contributed to: VFS, Asciidoctor, JRuby family (base, jar, war etc.), GnuMake, Doxygen
  • 3. ABOUT THIS PRESENTATION Written in Asciidoctor (1.5.3.2) Styled by asciidoctor-revealjs extension Built using: Gradle gradle-asciidoctor-plugin gradle-vfs-plugin
  • 4. THE PROBLEM There is no consistency in the way plugin authors craft extensions to the Gradle DSL today
  • 5. QUALITY ATTRIBUTES OF DSL Readability Consistency Flexibility Expressiveness
  • 6. FOR BEST COMPATIBILITY Support same JDK range as Gradle Gradle 1.x - mininum JDK5 Gradle 2.x - minimum JDK6 Build against Gradle 2.0 Only use later versions if specific new functionality is required. Suggested baseline at Gradle 2.6
  • 7. FOR BEST COMPATIBILITY // build.gradle targetCompatibility = 1.6 sourceCompatibility = 1.6 project.tasks.withType(JavaCompile) { task -> task.sourceCompatibility = project.sourceCompatibility task.targetCompatibility = project.targetCompatibility } project.tasks.withType(GroovyCompile) { task -> task.sourceCompatibility = project.sourceCompatibility task.targetCompatibility = project.targetCompatibility } // gradle/wrapper/gradle-wrapper.properties distributionUrl=https://..../distributions/gradle-2.0-all.zip
  • 8. NOMENCLATURE Property: A public data member (A Groovy property) Method: A standard Java/Groovy method Attribute: A value, set or accessed via the Gradle DSL. Can result in a public method call or property access. User: Person authoring or executing a Gradle build script @Input String aProperty = 'stdValue' @Input void aValue(String s) { ... } myTask { aProperty = 'newValue' aValue 'newValue' }
  • 9. PREFER METHODS OVER PROPERTIES ( IOW To assign or not to assign ) Methods provide more flexibility Tend to provide better readability Assignment is better suited towards One-shot attribute setting Overriding default attributes Non-lazy evaluation
  • 10. HOW NOT 2 : COLLECTION OF FILES Typical implementation …​ class MyTask extends DefaultTask { @InputFiles List<File> mySources } leads to ugly DSL task myTask( type: MyTask ) { myTask = [ file('foo/bar.txt'), new File( 'bar/foo.txt') ] }
  • 11. COLLECTION OF FILES myTask { mySources file( 'path/foobar' ) mySources new File( 'path2/foobar' ) mySources 'file3', 'file4' mySources { "lazy evaluate file name later on" } } Allow ability to: Use strings and other objects convertible to File Append lists Evaluate as late as possible Reset default values
  • 12. COLLECTION OF FILES Ignore Groovy shortcut; use three methods class MyTask extends DefaultTask { @InputFiles FileCollection getDocuments() { project.files(this.documents) // magic API method } void setDocuments(Object... docs) { this.documents.clear() this.documents.addAll(docs as List) } void documents(Object... docs) { this.documents.addAll(docs as List) } private List<Object> documents = [] }
  • 13. STYLE : TASKS Provide a default instantiation of your new task class Keep in mind that user would want to create additional tasks of same type Make it easy for them!!
  • 15. COLLECTION OF STRINGS import org.gradle.util.CollectionUtils Ignore Groovy shortcut; use three methods @Input List<String> getScriptArgs() { // stringize() is your next magic API method CollectionUtils.stringize(this.scriptArgs) } void setScriptArgs(Object... args) { this.scriptArgs.clear() this.scriptArgs.addAll(args as List) } void scriptArgs(Object... args) { this.scriptArgs.addAll(args as List) } private List<Object> scriptArgs = []
  • 16. HOW NOT 2 : MAPS Typical implementation …​ class MyTask extends DefaultTask { @Input Map myOptions } leads to ugly DSL task myTask( type: MyTask ) { myOptions = [ prop1 : 'foo/bar.txt', prop2 : 'bar/foo.txt' ] }
  • 17. MAPS task myTask( type: MyTask ) { myOptions prop1 : 'foo/bar.txt', prop2 : 'bar/foo.txt' myOptions prop3 : 'add/another' // Explicit reset myOptions = [:] }
  • 18. MAPS @Input Map getMyOptions() { this.attrs } void setMyOptions(Map m) { this.attrs=m } void myOptions(Map m) { this.attrs+=m } private Map attrs = [:]
  • 19. USER OVERRIDE LIBRARY VERSION Ship with prefered (and tested) version of dependent library set as default Allow user flexibility to try a different version of such library Dynamically load library when needed Still use power of Gradle’s dependency resolution
  • 20. USER OVERRIDE LIBRARY VERSION Example DSL from Asciidoctor asciidoctorj { version = '1.6.0-SNAPSHOT' } Example DSL from JRuby Base jruby { execVersion = '1.7.12' }
  • 21. USER OVERRIDE LIBRARY VERSION 1. Create Extension 2. Add extension object in plugin apply 3. Create custom classloader
  • 22. USER OVERRIDE LIBRARY VERSION Step 1: Create project extension class MyExtension { // Set the default dependent library version String version = '1.5.0' MyExtension(Project proj) { project= proj } @PackageScope Project project }
  • 23. USER OVERRIDE LIBRARY VERSION Step 2: Add extension object in plugin apply class MyPlugin implements Plugin<Project> { void apply(Project project) { // Create the extension & configuration project.extensions.create('asciidoctorj',MyExtension,project) project.configuration.maybeCreate( 'int_asciidoctorj' ) // Add dependency at the end of configuration phase project.afterEvaluate { project.dependencies { int_asciidoctorj "org.asciidoctor:asciidoctorj" + "${project.asciidoctorj.version}" } } } }
  • 24. USER OVERRIDE LIBRARY VERSION (2.5+) Step 2: Add extension object Gradle 2.5+ class MyPlugin implements Plugin<Project> { void apply(Project project) { // Create the extension & configuration project.extensions.create('asciidoctorj',MyExtension,project) def conf = configurations.maybeCreate( 'int_asciidoctorj' ) conf.defaultDependencies { deps -> deps.add( project.dependencies.create( "org.asciidoctor:asciidoctorj:${asciidoctorj.version}") ) } } }
  • 25. USER OVERRIDE LIBRARY VERSION Step 3: Custom classloader (usually loaded from task action) // Get all of the files in the `asciidoctorj` configuration def urls = project.configurations.int_asciidoctorj.files.collect { it.toURI().toURL() } // Create the classloader for all those files def classLoader = new URLClassLoader(urls as URL[], Thread.currentThread().contextClassLoader) // Load one or more classes as required def instance = classLoader.loadClass( 'org.asciidoctor.Asciidoctor$Factory')
  • 26. NEED 2 KNOW : 'AFTEREVALUATE' afterEvaluate adds to a list of closures to be executed at end of configuration phase Execution order is FIFO Plugin author has no control over the order
  • 27. STYLE : PROJECT EXTENSIONS Treat project extensions as you would for any kind of global configuration. With care! Do not make the extension configuration block a task configuration. Task instantiation may read defaults from extension. Do not force extension values onto tasks
  • 28. NEED 2 KNOW : PLUGINS Plugin author has no control over order in which plugins will be applied Handle both cases of related plugin applied before or after yours
  • 29. EXTEND EXISTING TASK Task type extension by inheritance is not always best solution Adding behaviour to existing task type better in certain contexts Example: jruby-jar-plugin wants to semantically describe bootstrap files rather than force user to use standard Copy syntax
  • 30. EXTEND EXISTING TASK jruby-jar-plugin without extension jrubyJavaBootstrap { // User gets exposed (unnecessarily) to the underlying task type // Has to craft too much glue code from( { // @#$$!!-ugly code goes here } ) } jruby-jar-plugin with extension jrubyJavaBootstrap { // Expressing intent & context. jruby { initScript = 'bin/asciidoctor' } }
  • 31. EXTEND EXISTING TASK 1. Create extension class 2. Add extension to task 3. Link extension attributes to task attributes (for caching)
  • 32. EXTEND EXISTING TASK Create extension class class MyExtension { String initScript MyExtension( Task t ) { // TODO: Add Gradle caching support // (See later slide) } }
  • 33. EXTEND EXISTING TASK Add extension class to task class MyPlugin implements Plugin<Project> { void apply(Project project) { Task stubTask = project.tasks.create ( name : 'jrubyJavaBootstrap', type : Copy ) stubTask.extensions.create( 'jruby', MyExtension, stubTask ) }
  • 34. EXTEND EXISTING TASK Add Gradle caching support class MyExtension { String initScript MyExtension( Task t ) { // Tell the task the initScript is also a property t.inputs.property 'jrubyInitScript' , { -> this.initScript } } }
  • 35. NEED 2 KNOW : TASK EXTENSIONS Good way extend existing tasks in composable way Attributes on extensions are not cached Changes will not cause a rebuild of the task Do the extra work to cache and provide the user with a better experience.
  • 36. HONOUR OFFLINE gradle --offline The build should operate without accessing network resources.
  • 37. HONOUR OFFLINE Unset the enabled property, if build is offline task VfsCopy extends DefaultTask { VfsCopy() { enabled = !project.gradle.startParameter.isOffline() } }
  • 38. TRICK : SAFE FILENAMES Ability to create safe filenames on all platforms from input data Example: Asciidoctor output directories based upon backend names // WARNING: Using a very useful internal API import org.gradle.internal.FileUtils File outputBackendDir(final File outputDir, final String backend) { // FileUtils.toSafeFileName is your magic method new File(outputDir, FileUtils.toSafeFileName(backend)) }
  • 39. TRICK : SELF-REFERENCING PLUGIN New plugin depends on functionality in the plugin Apply plugin direct in build.gradle apply plugin: new GroovyScriptEngine( ['src/main/groovy','src/main/resources']. collect{ file(it).absolutePath } .toArray(new String[2]), project.class.classLoader ).loadScriptByName('book/SelfReferencingPlugin.groovy')
  • 40. COMPATIBILITY TESTING How can a plugin author test a plugin against multiple Gradle versions?
  • 41. COMPATIBILITY TESTING Gradle 2.7 added TestKit Gradle 2.9 added multi-distribution testing TestKit still falls short in ease-of-use (Hopefully to be corrected over future releases) What to do for Gradle 2.0 - 2.8?
  • 42. COMPATIBILITY TESTING GradleTest plugin to the rescue buildscript { dependencies { classpath "org.ysb33r.gradle:gradletest:0.5.4" } } apply plugin : 'org.ysb33r.gradletest' http://bit.ly/1LfUUU4
  • 43. COMPATIBILITY TESTING Create src/gradleTest/NameOfTest folder. Add build.gradle Add task runGradleTest Add project structure
  • 44. COMPATIBILITY TESTING Add versions to main build.gradle gradleTest { versions '2.0', '2.2', '2.4', '2.5', '2.9' } Run it! ./gradlew gradleTest
  • 45. THANK YOU Keep your DSL extensions beautiful Don’t spring surprising behaviour on the user Email: Twitter / Ello : @ysb33r #idiomaticgradle (devoxxma2015) ysb33r@gmail.com http://bit.ly/1iJmdiP