如何将 DSL 语法转换为脚本语法

How to translate DSL syntax to scripted syntax

下面是 groovy DSL 中的代码片段:

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

这对我来说很难理解,如果下面是相应的脚本语法:

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

如何将 DSL 语法转换为脚本语法?因为脚本语法对我来说更易读。

id(String) 方法在 plugins block returns a PluginDependencySpecImpl 中有方法 version(String)apply(boolean)。所以你只需要这样写:

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

工作中的模式称为 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 很好地解释了为什么这有效 here

plugins DSL应用插件的首选方法。

legacy plugins application(脚本语法)等价于:

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"

这比插件 DSL 多 多写。

Gradle 团队将其记录为遗留。因此,无论您是否喜欢新的 plugins { } 语法,遗留方法最终都会消失。