This is an automated email from the ASF dual-hosted git repository. lukaszlenart pushed a commit to branch feat/WW-5864-struts-maven-plugin-watch in repository https://gitbox.apache.org/repos/asf/struts.git
commit bbe0e55344d82e95cb0b08a5f647d6a44b990071 Author: Lukasz Lenart <[email protected]> AuthorDate: Sat Nov 14 08:51:04 2026 +0100 WW-5864 feat(tools): add the struts:watch goal Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --- tools/struts-maven-plugin/pom.xml | 5 + .../org/apache/struts2/maven/watch/WatchMojo.java | 168 +++++++++++++++++++++ .../apache/struts2/maven/watch/WatchMojoTest.java | 117 ++++++++++++++ 3 files changed, 290 insertions(+) diff --git a/tools/struts-maven-plugin/pom.xml b/tools/struts-maven-plugin/pom.xml index 44809796e..a685b2816 100644 --- a/tools/struts-maven-plugin/pom.xml +++ b/tools/struts-maven-plugin/pom.xml @@ -96,6 +96,11 @@ <artifactId>junit</artifactId> <scope>test</scope> </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <scope>test</scope> + </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> diff --git a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java new file mode 100644 index 000000000..4dbaae7fd --- /dev/null +++ b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java @@ -0,0 +1,168 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +import org.apache.maven.execution.MavenSession; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.project.MavenProject; +import org.apache.maven.shared.filtering.MavenResourcesFiltering; + +import javax.inject.Inject; +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.function.BooleanSupplier; +import java.util.function.Function; + +@Mojo(name = "watch", defaultPhase = LifecyclePhase.PROCESS_RESOURCES, threadSafe = true) +public class WatchMojo extends AbstractMojo { + + static final String MULTI_MODULE_MESSAGE = + "struts:watch supports a single module; run it in the module that owns the resources, e.g. -pl <module>"; + + /** + * Milliseconds between scans of the resource directories. + */ + @Parameter(property = "struts.watch.pollInterval", defaultValue = "500") + long pollInterval = 500; + + /** + * Run the watcher on a daemon thread and return, so it can be bound to a lifecycle phase. + * Requires struts.watch=true to do anything. + */ + @Parameter(property = "struts.watch.background", defaultValue = "false") + boolean background; + + /** + * Switches background watching on. Consulted only when background is true. + */ + @Parameter(property = "struts.watch", defaultValue = "false") + boolean enabled; + + /** + * Seconds after which a blocking run stops; 0 means run until interrupted. + */ + @Parameter(property = "struts.watch.timeout", defaultValue = "0") + long timeout; + + @Parameter(defaultValue = "${project}", readonly = true, required = true) + MavenProject project; + + @Parameter(defaultValue = "${session}", readonly = true, required = true) + MavenSession session; + + @Inject + MavenResourcesFiltering resourcesFiltering; + + @Override + public void execute() throws MojoFailureException { + if (!shouldRun()) { + getLog().debug("struts:watch is in background mode and struts.watch is not true; not watching"); + return; + } + checkSingleModule(); + + Path basedir = project.getBasedir().toPath(); + Path outputDirectory = new File(project.getBuild().getOutputDirectory()).toPath(); + for (String warning : new StrutsReloadInspector(outputDirectory).warnings()) { + getLog().warn(warning); + } + + ResourcesPluginSettings settings = ResourcesPluginSettings.from( + ResourcesPluginSettings.effectiveResourcesConfiguration(project), + project.getProperties().getProperty("project.build.sourceEncoding")); + List<WatchedRoot> roots = project.getResources().stream() + .map(resource -> WatchedRoot.of(resource, basedir)) + .toList(); + ResourceScanner scanner = new ResourceScanner(roots, settings.isAddDefaultExcludes()); + FilteringResourcePusher filteringPusher = + new FilteringResourcePusher(resourcesFiltering, project, session, settings, outputDirectory); + ResourcePusher pusher = loggingPusher(filteringPusher, basedir); + + pushStaleOutputs(scanner.scan(), filteringPusher::outputPathOf, pusher); + + List<Path> filterFiles = project.getBuild().getFilters().stream() + .map(filter -> basedir.resolve(filter)) + .toList(); + ResourceWatcher watcher = new ResourceWatcher(scanner, pusher, filterFiles, + message -> getLog().debug(message), (message, e) -> getLog().error(message, e)); + watcher.start(); + + Duration interval = Duration.ofMillis(pollInterval); + if (background) { + Thread thread = new Thread(() -> watcher.run(interval, () -> true), "struts-watch"); + thread.setDaemon(true); + thread.start(); + getLog().info("Watching " + roots.size() + " resource root(s) in the background"); + return; + } + getLog().info("Watching " + roots.size() + " resource root(s); press Ctrl+C to stop"); + long deadline = timeout > 0 ? System.nanoTime() + Duration.ofSeconds(timeout).toNanos() : 0; + BooleanSupplier keepRunning = () -> deadline == 0 || System.nanoTime() - deadline < 0; + watcher.run(interval, keepRunning); + } + + boolean shouldRun() { + return !background || enabled; + } + + void checkSingleModule() throws MojoFailureException { + if (session.getProjects().size() > 1) { + throw new MojoFailureException(MULTI_MODULE_MESSAGE); + } + } + + static void pushStaleOutputs(Map<SourceFile, FileStamp> scan, Function<SourceFile, Path> outputPathOf, + ResourcePusher pusher) { + for (Map.Entry<SourceFile, FileStamp> entry : scan.entrySet()) { + File output = outputPathOf.apply(entry.getKey()).toFile(); + if (!output.isFile() || output.lastModified() < entry.getValue().lastModified()) { + try { + pusher.push(entry.getKey()); + } catch (IOException | RuntimeException e) { + throw new IllegalStateException("Cannot push " + entry.getKey().relativePath(), e); + } + } + } + } + + private ResourcePusher loggingPusher(FilteringResourcePusher delegate, Path basedir) { + return new ResourcePusher() { + @Override + public void push(SourceFile file) throws IOException { + delegate.push(file); + getLog().info("pushed " + file.relativePath() + " -> " + + basedir.relativize(delegate.outputPathOf(file))); + } + + @Override + public void delete(SourceFile file) throws IOException { + delegate.delete(file); + getLog().info("deleted " + file.relativePath()); + } + }; + } +} diff --git a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java new file mode 100644 index 000000000..799d672e8 --- /dev/null +++ b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java @@ -0,0 +1,117 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.struts2.maven.watch; + +import org.apache.maven.execution.MavenSession; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.project.MavenProject; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class WatchMojoTest { + + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + + @Test + public void backgroundWithoutEnabledDoesNotRun() { + WatchMojo mojo = new WatchMojo(); + mojo.background = true; + mojo.enabled = false; + assertThat(mojo.shouldRun()).isFalse(); + } + + @Test + public void backgroundWithEnabledRuns() { + WatchMojo mojo = new WatchMojo(); + mojo.background = true; + mojo.enabled = true; + assertThat(mojo.shouldRun()).isTrue(); + } + + @Test + public void blockingAlwaysRuns() { + WatchMojo mojo = new WatchMojo(); + mojo.background = false; + mojo.enabled = false; + assertThat(mojo.shouldRun()).isTrue(); + } + + @Test + public void multiModuleSessionFailsWithGuidance() { + WatchMojo mojo = new WatchMojo(); + MavenSession session = mock(MavenSession.class); + when(session.getProjects()).thenReturn(List.of(new MavenProject(), new MavenProject())); + mojo.session = session; + assertThatThrownBy(mojo::checkSingleModule) + .isInstanceOf(MojoFailureException.class) + .hasMessageContaining("-pl <module>"); + } + + @Test + public void staleOutputsArePushedAtStart() throws Exception { + Path src = temp.newFolder("src").toPath(); + Path out = temp.newFolder("out").toPath(); + File stale = write(src.resolve("stale.txt"), 2000); + File fresh = write(src.resolve("fresh.txt"), 1000); + File missing = write(src.resolve("missing.txt"), 1000); + write(out.resolve("stale.txt"), 1000); + write(out.resolve("fresh.txt"), 2000); + + WatchedRoot root = new WatchedRoot(src, List.of(), List.of(), null, false); + Map<SourceFile, FileStamp> scan = new LinkedHashMap<>(); + for (File f : List.of(stale, fresh, missing)) { + scan.put(new SourceFile(root, f.getName()), new FileStamp(f.lastModified(), f.length())); + } + List<String> pushed = new ArrayList<>(); + ResourcePusher pusher = new ResourcePusher() { + public void push(SourceFile file) { + pushed.add(file.relativePath()); + } + + public void delete(SourceFile file) { + } + }; + + WatchMojo.pushStaleOutputs(scan, file -> out.resolve(file.relativePath()), pusher); + + assertThat(pushed).containsExactlyInAnyOrder("stale.txt", "missing.txt"); + } + + private File write(Path path, long lastModified) throws Exception { + Files.writeString(path, "x"); + File file = path.toFile(); + assertThat(file.setLastModified(lastModified)).isTrue(); + return file; + } +}
