Почему Maven Mojo не удаляет, не перемещает и не заменяет файлы - PullRequest
0 голосов
/ 22 ноября 2018

Я создал новый плагин для Majo Mojo.Я хочу переименовать некоторые сгенерированные файлы из другого плагина, заменить содержимое для некоторых файлов.

Это мой модж:

package com.mymojo.maven.plugins;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.bind.DatatypeConverter;

@Mojo(name = "versionalize")
public class VersionalizeMojo extends AbstractMojo {
    /**
     * Location of the file.
     */
    @Parameter(property = "outputDir", defaultValue = "${project.build.directory}/${project.build.finalName}", required = true)
    private File outputDirectory;

    @Parameter(property = "fileExt", defaultValue = "js|css")
    private String fileExt;

    @Parameter(property = "fileReplaceExt", defaultValue = "html|jsp|vm")
    private String fileReplaceExt;

    @Parameter(property = "excludeDir")
    private String excludeDir;

    private final String extPattern = "([^\\s]+(\\.(?i)(#))$)";

    Map<String, String> filenameMap;

    public void execute() throws MojoExecutionException, MojoFailureException {
        if (outputDirectory.exists()) {
            Path start = FileSystems.getDefault().getPath(outputDirectory.getPath());
            try {

                // create a copy of resources with md5 hashed names
                Files.walkFileTree(start, new MD5HasherFileVisitor());

                // replace all references to old files with new names
                Files.walkFileTree(start, new ReplacerFileVisitor());
            } catch (IOException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }
        } else {
            getLog().error("Not found");
        }
    }

    private class MD5HasherFileVisitor extends SimpleFileVisitor<Path> {
        Pattern pattern;

        public MD5HasherFileVisitor() {
            String regex = extPattern.replace("#", fileExt);
            pattern = Pattern.compile(regex);
            filenameMap = new HashMap<String, String>();
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Matcher matcher = pattern.matcher(file.toString());
            if (matcher.matches()) {
                try {
                    MessageDigest md = MessageDigest.getInstance("MD5");
                    md.update(Files.readAllBytes(file));
                    byte[] digest = md.digest();
                    String checksum = DatatypeConverter.printHexBinary(digest).toUpperCase();
                    String newFilename = checksum + "-" + file.getFileName();
                    Path target = FileSystems.getDefault().getPath(file.getParent().toString(), newFilename);
                    getLog().info("File:" + file + " -> " + newFilename);
                    Files.move(file, target, StandardCopyOption.ATOMIC_MOVE);
                    filenameMap.put(file.getFileName().toString(), target.getFileName().toString());
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            getLog().info("Failed: " + file);
            return FileVisitResult.CONTINUE;
        }
    }

    private class ReplacerFileVisitor extends SimpleFileVisitor<Path> {
        Pattern pattern;

        public ReplacerFileVisitor() {
            String regex = extPattern.replace("#", fileReplaceExt);
            pattern = Pattern.compile(regex);
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Matcher matcher = pattern.matcher(file.toString());
            Charset charset = StandardCharsets.UTF_8;
            if (matcher.matches()) {
                String content = new String(Files.readAllBytes(file), charset);
                for (String f : filenameMap.keySet()) {
                    content = content.replaceAll(f, filenameMap.get(f));
                }
                Files.write(file, content.getBytes(charset));
                getLog().info("Replaced: " + file.getFileName());
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            getLog().info("Failed: " + file);
            return FileVisitResult.CONTINUE;
        }
    }
}

Плагин будет использоваться следующим образом:

<plugin>
    <groupId>com.mymojo.maven.plugins</groupId>
    <artifactId>mymojo-maven-plugin</artifactId>
    <version>1.0.0</version>
    <executions>
        <execution>
            <phase>prepare-package</phase>
            <goals>
                <goal>versionalize</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Проблема, с которой я сталкиваюсь, заключается в том, что существующий файл не заменен новымсодержание.Если я пишу в новый файл, содержимое сохраняется.Я попытался удалить файл и создать новый.Но это не работает

...