有没有办法在NAnt中动态加载属性文件?
时间:2020-03-05 18:57:09 来源:igfitidea点击:
我想基于一个变量加载不同的属性文件。
基本上,如果进行开发构建,则使用该属性文件;如果进行测试构建,则使用此其他属性文件;如果进行生产构建,则使用第三个属性文件。
解决方案
回答
我做这种事情的方法是根据使用nant任务的构建类型包括单独的构建文件。可能的替代方法是在nantcontrib中使用iniread任务。
回答
我们可以使用" include"任务在主构建文件中包含另一个构建文件(包含属性)。 include任务的if属性可以对一个变量进行测试,以确定是否应该包含构建文件:
<include buildfile="devPropertyFile.build" if="${buildEnvironment == 'DEV'}"/> <include buildfile="testPropertyFile.build" if="${buildEnvironment == 'TEST'}"/> <include buildfile="prodPropertyFile.build" if="${buildEnvironment == 'PROD'}"/>
回答
步骤1:在NAnt脚本中定义一个属性,以跟踪要构建的环境(本地,测试,生产等)。
<property name="environment" value="local" />
步骤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>
步骤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>
注意,我希望允许团队成员定义自己的local.config.xml文件,这些文件不会提交给源代码管理。这提供了一个存储本地连接字符串或者其他本地环境设置的好地方。
第4步:在调用NAnt时设置环境属性,例如:
- 南特-D:environment = dev
- nant -D:environment =测试
- nant -D:environment =生产
回答
我有一个类似的问题,来自scott.caligan的答案部分解决了,但是我希望人们仅通过指定一个目标就可以设置环境并加载适当的属性文件,如下所示:
- 南特开发
- 南特测试
- 南特阶段
我们可以通过添加设置环境变量的目标来实现。例如:
<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>