有没有办法在NAnt中动态加载属性文件?

Wil*_*Joe 20 .net nant automation build

我想基于一个变量加载不同的属性文件.

基本上,如果执行dev构建使用此属性文件,如果执行测试构建使用此其他属性文件,并且如果执行生成构建,则使用第三个属性文件.

小智 26

步骤1:在NAnt脚本中定义属性以跟踪您正在构建的环境(本地,测试,生产等).

<property name="environment" value="local" />
Run Code Online (Sandbox Code Playgroud)

步骤2:如果您还没有所有目标所依赖的配置或初始化目标,则创建配置目标,并确保其他目标依赖于它.

<target name="config">
    <!-- configuration logic goes here -->
</target>

<target name="buildmyproject" depends="config">
    <!-- this target builds your project, but runs the config target first -->
</target>
Run Code Online (Sandbox Code Playgroud)

步骤3:更新配置目标以根据环境属性提取适当的属性文件.

<target name="config">
    <property name="configFile" value="${environment}.config.xml" />
    <if test="${file::exists(configFile)}">
        <echo message="Loading ${configFile}..." />
        <include buildfile="${configFile}" />
    </if>
    <if test="${not file::exists(configFile) and environment != 'local'}">
        <fail message="Configuration file '${configFile}' could not be found." />
    </if>
</target>
Run Code Online (Sandbox Code Playgroud)

注意,我喜欢允许团队成员定义他们自己的local.config.xml文件,这些文件没有提交给源代码控制.这为存储本地连接字符串或其他本地环境设置提供了一个好地方.

第4步:调用NAnt时设置环境属性,例如:

  • nant -D:environment = dev
  • nant -D:environment = test
  • nant -D:环境=生产


Tim*_*Tim 5

您可以使用该include任务在主构建文件中包含另一个构建文件(包含您的属性).任务的if属性include可以针对变量进行测试,以确定是否应该包含构建文件:

<include buildfile="devPropertyFile.build" if="${buildEnvironment == 'DEV'}"/>
<include buildfile="testPropertyFile.build" if="${buildEnvironment == 'TEST'}"/>
<include buildfile="prodPropertyFile.build" if="${buildEnvironment == 'PROD'}"/>
Run Code Online (Sandbox Code Playgroud)


Rya*_*lor 5

我有一个类似的问题,scott.caligan的答案部分解决了,但我希望人们能够设置环境并加载适当的属性文件,只需指定一个目标,如下所示:

  • 不开发
  • 没有考试
  • nant stage

您可以通过添加设置环境变量的目标来完成此操作.例如:

<target name="dev">
  <property name="environment" value="dev"/>
  <call target="importProperties" cascade="false"/>
</target>

<target name="test">
  <property name="environment" value="test"/>
  <call target="importProperties" cascade="false"/>
</target>

<target name="stage">
  <property name="environment" value="stage"/>
  <call target="importProperties" cascade="false"/>
</target>

<target name="importProperties">
  <property name="propertiesFile" value="properties.${environment}.build"/>
  <if test="${file::exists(propertiesFile)}">
    <include buildfile="${propertiesFile}"/>
  </if>
  <if test="${not file::exists(propertiesFile)}">
    <fail message="Properties file ${propertiesFile} could not be found."/>
  </if>
</target>
Run Code Online (Sandbox Code Playgroud)