为什么Maven Mojo不删除,移动或替换文件

时间:2018-11-22 13:57:07

标签: maven mojo

我创建了一个新的Maven 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>

我面临的问题是现有文件未替换为新内容。如果我写入新文件,则内容正在保存。我尝试删除该文件并创建一个新文件。但这不起作用

0 个答案:

没有答案