Ant:重命名文件以包含其 MD5 [英] Ant: Rename files to include their MD5
问题描述
对于熟悉 ant 的人来说,这个问题可能非常简单,到目前为止我只使用了其中的基础知识.
The question is likely VERY trivial for anyone familiar with ant, of which I only use the basics thus far.
我知道如何重命名文件,例如我已经在用了:
<copy todir="build/css/">
<fileset dir="css/">
<include name="*.css"/>
</fileset>
<globmapper from="*.css" to="*-min.css"/>
</copy>
我知道如何计算 MD5:
<checksum file="foo.bar" property="foobarMD5"/>
我不知道如何将第二个包含在第一个中,重命名所有这些文件以包含它们的 MD5 - 目的是用作网络浏览器缓存破坏者.另一个缓存破坏选项,附加?[something]"并不好,正如一些谷歌网站管理员页面所解释的那样,将 MD5 作为名称的一部分更好.
I don't know how to include the second into the first, to rename all those files to include their MD5 - the purpose is to serve as webbrowser cache buster. The other cache-busting option, to append "?[something]" is not as good, as is explained on some Google webmaster pages, having the MD5 as part of the name is better.
推荐答案
您无需包含 ant contrib
即可执行此操作.我必须在工作中实现这一点,并且出于安全原因不允许引入该扩展.我找到的解决方案是这样的:
You could do this without having to include ant contrib
. I had to implement this for work and was not allowed to introduce that extension for security reasons. The solution I came to was this:
<target name="appendMD5">
<copy todir="teststack">
<fileset dir="css/" includes="**/*.css"/>
<scriptmapper language="javascript"><![CDATA[
var File = Java.type('java.io.File');
var Files = Java.type('java.nio.file.Files');
var MessageDigest = Java.type('java.security.MessageDigest');
var DatatypeConverter = Java.type('javax.xml.bind.DatatypeConverter');
var buildDir = MyProject.getProperty('builddir');
var md5Digest = MessageDigest.getInstance('MD5');
var file = new File(buildDir, source);
var fileContents = FIles.readAllBytes(file.toPath());
var hash = DatatypeConverter.printHexBinary(md5Digest.digest(fileContents));
var baseName = source.substring(0, source.lastIndexOf('.'));
var extension = source.substring(source.lastIndexOf('.'));
self.addMappedName(baseName + '-' + hash + extension);
]]></scriptmapper>
</copy>
</target>
值得注意的是,我是为 Java 8 编写的,但经过一些细微的调整,它可以在 Java 7 上运行.遗憾的是,如果不付出更多努力,这将不适用于早期版本的 Java.
It is worth noting that I wrote this for Java 8 but with some minor tweaks it could work on Java 7. Sadly this won't work for earlier versions of Java without more effort.
这篇关于Ant:重命名文件以包含其 MD5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!