如何在 ANT 构建中在多个目标 'depends' 属性 中使用一个目标?

How to use one target in multiple targets' 'depends' property in ANT build?

我正在使用 ANT build 进行部署过程。为此,我遵循以下几点,

  1. Created five targets in ANT named 'initiate.deploy' (to initiate deployment), 'svn.checkout' (checkout source from SVN into workspace) , 'generate.ear' (EAR generation) and 'deploy.ear' (deploy EAR into Server), 'clean.workspace' (Cleaning workspace dirtory).
  2. The target 'initiate.deploy' is my default target.
  3. I need to clean the workspace directory before 'svn.checkout' target and after 'deploy.ear' target.
  4. I put 'clean.workspace' target in 'depends' property of 'svn.checkout' target and in 'initiate.deploy' target.

我的代码:

    <target name="initiate.deploy" description="Initiate deployment" depends="svn.checkout, generate.ear, deploy.ear, clean.workspace">
        ..........................
    </target>

    <target name="svn.checkout" description="SVN checkout" depends ="clean.workspace">
        ..........................
    </target>

但是目标 'clean.workspace' 只在 'svn.checkout' 之前执行一次,而不是在 'deploy.ear' 目标之后执行。

构建序列创建如下。

Build sequence for target(s) 'initiate.deploy' is [clean.workspace, svn.checkout, check.workSpace, update.property.file, generate.ear, deploy.ear, initiate.deploy]

在 ANT 构建中如何在多个目标中使用一个目标''depends'属性?

Ant documentation 中所述:

In a chain of dependencies stretching back from a given target such as D above, each target gets executed only once, even when more than one target depends on it.

我的理解是,这是为了避免依赖关系图中的循环。

因此,您需要修改目标,例如从 initiate.deploy 的依赖项中删除 clean.workspace 并通过 antcall 任务显式调用它:

<target name="initiate.deploy" description="Initiate deployment" depends="svn.checkout, generate.ear, deploy.ear">
    ..........................
    <antcall target="clean.workspace" />
</target>

<target name="svn.checkout" description="SVN checkout" depends ="clean.workspace">
    ..........................
</target>

更新:

如评论中所述,antcall 任务将在新的 Ant 项目中启动调用的目标,这会产生不希望的开销。为避免这种行为,可以将目标包装为 macrodef 并将其作为任何其他目标中的任务调用。然后,您可以更改调用的目标,使其调用新的 macrodef,以使其作为其他任务的依赖项可用:

<target name="initiate.deploy" description="Initiate deployment" depends="svn.checkout, generate.ear, deploy.ear">
    ..........................
    <clean.workspace.macro />
</target>

<target name="svn.checkout" description="SVN checkout" depends ="clean.workspace">
    ..........................
</target>

<target name="clean.workspace">
    <clean.workspace.macro />
</target>

<macrodef name="clean.workspace.macro">
   <sequential>
        <!-- do the workspace cleanup -->
        ..........................
   </sequential>
</macrodef>