我想用Ant在源文件中搜索一个字符串.(如果在我的源文件中找到某些字符串,我希望我的构建失败).
所以,我应该能够递归地搜索文件集中的某个字符串.
我已经发现我可以使用loadfile任务来检查是否在一个文件中找到了字符串模式.但这似乎只对单个文件有效且合理.
另一方面,replace task将提供递归搜索和替换.我想我可以在构建之前做到这一点,并用可能破坏构建的东西替换我的字符串,但我想知道是否有更清洁的解决方案?
br,Touko
mar*_*ton 16
您可以考虑使用文件集选择器来执行此操作.选择器允许您根据内容,大小,可编辑性等选择文件.您可以将选择器与基于名称的包含和排除或模式集组合在一起.
以下是一个例子.第二个文件集派生自第一个文件集,其中一个选择器只匹配文件内容.对于更复杂的匹配,有containsregexp选择器.结果是文件集仅包含与字符串匹配的文件.然后使用具有resourcecount条件的失败任务来使构建失败,除非该文件集为空.
<property name="src.dir" value="src" />
<property name="search.string" value="BAD" />
<fileset id="existing" dir="${src.dir}">
<patternset id="files">
<!-- includes/excludes for your source here -->
</patternset>
</fileset>
<fileset id="matches" dir="${src.dir}">
<patternset refid="files" />
<contains text="${search.string}" />
</fileset>
<fail message="Found '${search.string}' in one or more files in '${src.dir}'">
<condition>
<resourcecount when="greater" count="0" refid="matches" />
</condition>
</fail>
Run Code Online (Sandbox Code Playgroud)
(旧答案):如果调整或重用文件集可能会有问题,这里是一个相对简单的替代方案的说明.
我们的想法是复制文件,然后用复制文件中的某个标志值替换您要搜索的字符串.这将更新任何匹配文件的上次修改时间.uptodate然后,该任务可用于查找受影响的文件.最后,除非没有文件匹配,否则你可以fail构建.
<property name="src.dir" value="src" />
<property name="work.dir" value="work" />
<property name="search.string" value="BAD" />
<delete dir="${work.dir}" />
<mkdir dir="${work.dir}" />
<fileset dir="${src.dir}" id="src.files">
<include name="*.txt" />
</fileset>
<copy todir="${work.dir}" preservelastmodified="true">
<fileset refid="src.files" />
</copy>
<fileset dir="${work.dir}" id="work.files">
<include name="*.txt" />
</fileset>
<replaceregexp match="${search.string}"
replace="FOUND_${search.string}">
<fileset refid="work.files" />
</replaceregexp>
<uptodate property="files.clean">
<srcfiles refid="work.files" />
<regexpmapper from="(.*)" to="${basedir}/${src.dir}/\1" />
</uptodate>
<fail message="Found '${search.string}' in one or more files in dir '${src.dir}'"
unless="files.clean" />
Run Code Online (Sandbox Code Playgroud)