我想要在所有源代码文件中检测特定的单词或模式.例如,如果我想限制在项目中使用DateTime.Now,但如果某个团队成员在源代码中使用了它,我希望生成操作失败.
我不知道什么是正确的方法,但我可以使用VS预构建事件来实现同样的目的吗?如果没有,那么有没有人可以 bootstrap 我走上正确的道路来满足我的要求?
我想要在所有源代码文件中检测特定的单词或模式.例如,如果我想限制在项目中使用DateTime.Now,但如果某个团队成员在源代码中使用了它,我希望生成操作失败.
我不知道什么是正确的方法,但我可以使用VS预构建事件来实现同样的目的吗?如果没有,那么有没有人可以 bootstrap 我走上正确的道路来满足我的要求?
您可以通过在PreBuildEvent
中输入类似PowerShell MyPowerShellScript.ps1
的命令来执行PowerShell脚本.这些脚本包括在所有源代码文件中搜索特定的单词或模式.
请按照以下步骤操作.(示例)
$results = Get-ChildItem -Path {your project path} -Recurse | Select-String -Pattern "DateTime.Now";
if([string]::IsNullOrEmpty($results)){
Write-Host "not found specific word DateTime.Now"
}else{
Write-Host " found specific word DateTime.Now"
#other than zero (0)
exit 1
}
Note:
让您的事件操作以非零(0)代码退出.零退出代码表示操作成功;任何其他退出代码都被视为错误.
2.Enter a command like PowerShell MyPowerShellScript.ps1
.
On the Project menu->click {ProjectName} Properties (or from Solution Explorer, press Alt+Enter)->Select Build > Events.
Visual Studio通过添加PreBuildTarget和必要的MSBuild代码来修改项目文件,以执行您提供的步骤.
<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
<Exec Command="PowerShell {your project path}\pw.ps1" />
</Target>
3.Build the project and watch the output window. If it finds the specific world(DateTime.Now) in your source code files, the script exits with code 1 and the build fails.
希望它能对你有所帮助.