【问题标题】:How can I execute an ant target depending on the value of an environment variable?如何根据环境变量的值执行 ant 目标?
【发布时间】:2018-10-13 07:30:42
【问题描述】:

我想在两台不同的计算机上执行一个 ant 脚本。根据计算机的名称,应该执行两个目标之一。以下不起作用:

<project name="import" default="all">
  <property environment="env"/>    
  <target name="staging" if="${env.COMPUTERNAME}='STG'">
    <echo>executed on staging</echo>
  </target>      
  <target name="production" if="${env.COMPUTERNAME}='PRD'">
    <echo>executed on production</echo>
  </target>      
  <target name="all" depends="staging,production" description="STG or PRD"/>
</project>

据我了解,“if”只能与属性一起使用,它会检查是否设置了属性。但是有没有办法根据属性的值来制定条件?

【问题讨论】:

    标签: if-statement ant environment-variables target


    【解决方案1】:

    我建议编写一个“init”目标,为以后的构建步骤设置所需的任何条件,如果某些必需的属性未达到预期值,也会使构建失败。

    例如:

    <target name="all" depends="staging,production,init" />
    
    <target name="staging" if="staging.environment" depends="init">
        <echo message="executed on staging" />
    </target>
    
    <target name="production" if="production.environment" depends="init">
        <echo message="executed on production" />
    </target>
    
    <target name="init">
        <condition property="staging.environment">
            <equals arg1="${env.COMPUTERNAME}" arg2="STG" />
        </condition>
    
        <condition property="production.environment">
            <equals arg1="${env.COMPUTERNAME}" arg2="PRD" />
        </condition>
    
        <fail message="Neither staging nor production environment detected">
            <condition>
                <not>
                    <or>
                        <isset property="staging.environment" />
                        <isset property="production.environment" />
                    </or>
                </not>
            </condition>
        </fail>
    </target>
    

    【讨论】:

    • 嗨,我希望你的回答被评为有用,但我不允许 ;-)。所以,非常感谢你。这个解决方案对我来说很好。我仍然不明白,为什么只调用一次“init” - 有没有解释为什么它只执行一次?我已经在手册中阅读了此内容,但没有完全理解。
    • 很高兴我能帮上忙!即使您无法对答案进行评分,您仍然应该能够将您自己问题的答案标记为已接受的答案(它将用绿色复选标记标记)。关于 init 目标,在执行时,Ant 从项目目标命名的依赖关系中形成一个依赖关系树。如果多个目标共享一个依赖项,则该依赖项仅运行一次。这就是为什么使用depends 属性而不是antcall 任务来控制构建逻辑更安全、更高效的原因之一。
    猜你喜欢
    • 2015-05-21
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多