0

Below is the code snippet in groovy DSL:

plugins {
  id("com.github.johnrengelman.shadow") version "5.2.0"
}

that is difficult for me to understand, if below is the corresponding scripted syntax:

plugins({
  id(
      {
        "com.github.johnrengelman.shadow", 
        version("5.2.0")
      }
   )
})

How to translate a DSL syntax to scripted syntax? Because scripted syntax is more readable syntax for me.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
overexchange
  • 15,768
  • 30
  • 152
  • 347

2 Answers2

1

The id(String) method in the plugins block returns a PluginDependencySpecImpl which has the methods version(String) and apply(boolean). So you just need to write it like so:

plugins ({
  id("com.github.johnrengelman.shadow").version("5.2.0")
})

The pattern at work is called Command Chain.

Groovy lets you omit parentheses around the arguments of a method call for top-level statements. "command chain" feature extends this by allowing us to chain such parentheses-free method calls, requiring neither parentheses around arguments, nor dots between the chained calls. The general idea is that a call like a b c d will actually be equivalent to a(b).c(d). This also works with multiple arguments, closure arguments, and even named arguments.

MrHaki has a nice explanation why this works here.

Leonard Brünings
  • 12,408
  • 1
  • 46
  • 66
  • How do you know that there is dot between `id("com.github.johnrengelman.shadow")` and `version("5.2.0")`? this is the problem for me – overexchange Mar 19 '20 at 01:27
  • Read the explanation I linked from MrHaki and take a look at the links I added and then you'll see. – Leonard Brünings Mar 19 '20 at 01:29
  • How would I convert the complete script? – overexchange Mar 19 '20 at 01:34
  • 1
    You'll have to go over every block and see how it is defined, but honestly I don't recommend it, just use the official syntax like it is documented, otherwise you are just making it difficult for everyone else and you can't use examples. – Leonard Brünings Mar 19 '20 at 01:36
0

The plugins DSL is the preferred approach of applying plugins.

The legacy plugins application (scripted syntax) equivalent is:

buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "com.github.jengelman.gradle.plugins:shadow:5.2.0"
  }
}

apply plugin: "com.github.johnrengelman.shadow"

That is a lot more to write than the plugins DSL.

The Gradle team has documented this as legacy. So whether you like the new plugins { } syntax or not, the legacy method will eventually go away.

Cisco
  • 20,972
  • 5
  • 38
  • 60