From 199d2ef7cb1ce64d5c65cd7824fdcaaa915a5e1a Mon Sep 17 00:00:00 2001
From: dgelessus <dgelessus@users.noreply.github.com>
Date: Mon, 7 Aug 2023 17:07:11 +0200
Subject: [PATCH] Fix sourcesJar dependency if the task doesn't exist yet

This hopefully fixes the warnings about undeclared dependencies of
sourcesJar on generateSableCCSource.
---
 .../de/hhu/stups/sablecc/gradle/SableCCPlugin.java   | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/src/main/java/de/hhu/stups/sablecc/gradle/SableCCPlugin.java b/src/main/java/de/hhu/stups/sablecc/gradle/SableCCPlugin.java
index a874cc0..d009f1c 100644
--- a/src/main/java/de/hhu/stups/sablecc/gradle/SableCCPlugin.java
+++ b/src/main/java/de/hhu/stups/sablecc/gradle/SableCCPlugin.java
@@ -5,7 +5,6 @@ import javax.inject.Inject;
 import org.gradle.api.NonNullApi;
 import org.gradle.api.Plugin;
 import org.gradle.api.Project;
-import org.gradle.api.UnknownTaskException;
 import org.gradle.api.file.Directory;
 import org.gradle.api.internal.tasks.DefaultSourceSet;
 import org.gradle.api.plugins.JavaPlugin;
@@ -63,11 +62,12 @@ public class SableCCPlugin implements Plugin<Project> {
 			// Make compileJava, processResources, and sourcesJar depend on generateSableCCSource.
 			project.getTasks().named(sourceSet.getCompileJavaTaskName(), task -> task.dependsOn(sableCCTaskName));
 			project.getTasks().named(sourceSet.getProcessResourcesTaskName(), task -> task.dependsOn(sableCCTaskName));
-			try {
-				project.getTasks().named(sourceSet.getSourcesJarTaskName(), task -> task.dependsOn(sableCCTaskName));
-			} catch (UnknownTaskException ignored) {
-				// No sourcesJar task defined, so no need to add a dependency.
-			}
+			// The sourcesJar task might not exist yet at this point,
+			// or the project might not use it at all,
+			// so we can't use .named(...) directly like for the other tasks
+			// and instead have to configure the task once it comes into existence (if at all).
+			// There's no nice way to do this right now - see https://github.com/gradle/gradle/issues/8057
+			project.getTasks().matching(task -> task.getName().equals(sourceSet.getSourcesJarTaskName())).configureEach(task -> task.dependsOn(sableCCTaskName));
 		});
 	}
 }
-- 
GitLab