gpt4 book ai didi

java - Gradle:如何在 Gradle 插件中导出项目目录路径?

转载 作者:行者123 更新时间:2023-12-01 20:07:23 26 4
gpt4 key购买 nike

Gradle v2.9(旧版,我们即将升级)

我正在尝试按照 Writing Gradle Plugins 创建一个 Gradle 插件。我怎样才能让插件“派生”项目的顶级目录,即 build.gradle 文件所在的位置?如果插件创建一个 hello 任务,我希望它执行此操作

$ pwd
/some_path/project1
$ ls
build.gradle gradlew gradle gradle.properties src
$ ./gradlew hello
Hello /some_path/project1

最佳答案

根据成员的评论,我能够做到这一点

根据评论,我在代码中执行了此操作

package org.example.greeting;

import org.gradle.api.Plugin;
import org.gradle.api.Project;

public class GreetingPlugin implements Plugin<Project> {
public void apply(Project project) {
project.getTasks().create("hello", Greeting.class, (task) -> {
task.setMessage("Hello");
task.setRecipient("World");
// Added this line per comments from members
task.setProjectDir(project);
});
}
}

...还有...

包org.example.greeting;

import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.Project;
import java.io.*;

public class Greeting extends DefaultTask {
private String message;
private String recipient;
private File projectDir;
private Project project;

public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }

public String getRecipient() { return recipient; }
public void setRecipient(String recipient) { this.recipient = recipient; }

public File getProjectDir() { return projectDir; }
public void setProjectDir(File projectDir) { this.projectDir = projectDir; }

public Project getProject() { return project; }
public void setProject(Project project) { this.project = project; }

@TaskAction
void sayGreeting() {
System.out.printf("%s, %s, %s!\n", getProject().getRootDir().toString(), getMessage(), getRecipient());
}
}

现在可以使用了。

关于java - Gradle:如何在 Gradle 插件中导出项目目录路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58981630/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com