给定一个.Net C#项目,我想检查构建是否包含警告。运行命令时
dotnet build -consoleloggerparameters:"Summary;Verbosity=normal" -m -p:"WarnLevel=5;EnforceCodeStyleInBuild=true" -t:"clean,build"
我得到预期输出
Build succeeded.
2 Warning(s)
0 Error(s)
但是退出代码是0,所以我如何知道该构建是否包含警告?
我创建了一个shell脚本来处理
#!/bin/bash
dotnet build -consoleloggerparameters:"Summary;Verbosity=normal" -m -p:"WarnLevel=5;EnforceCodeStyleInBuild=true" -t:"clean,build"
if [ $? -eq 0 ]
then
echo ">>> Success"
else
echo ">>> Contains warnings or errors"
fi
read
但是,我如何扩展脚本以检查是否成功构建并发出警告呢?配置的CI管道应该通过,但如果出现警告,我希望将其标记为不稳定。
如果可能的话,我想避开雷格斯魔术。
编辑:
我不想添加标志-warnaserror
,因为这样CI管道将失败,您将不知道是发生了构建错误还是代码样式不好。
您只需在您的dotnet构建中添加/WarnAsError即可。
示例代码:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
int x = 0;
}
}
}
dotnet构建的输出:
dotnet build
Microsoft (R) Build Engine version 16.10.0+4242f381a for .NET
Copyright (C) Microsoft Corporation. All rights reserved.
Determining projects to restore...
All projects are up-to-date for restore.
Program.cs(10,17): warning CS0219: The variable 'x' is assigned but its value is never used [ConsoleApp1.csproj]
ConsoleApp1 -> ConsoleApp1.dll
Build succeeded.
Program.cs(10,17): warning CS0219: The variable 'x' is assigned but its value is never used [ConsoleApp1.csproj]
1 Warning(s)
0 Error(s)
Time Elapsed 00:00:00.79
dotnet构建/警告错误的输出:
dotnet build /WarnAsError
Microsoft (R) Build Engine version 16.10.0+4242f381a for .NET
Copyright (C) Microsoft Corporation. All rights reserved.
Determining projects to restore...
Restored ConsoleApp1.csproj (in 60 ms).
Program.cs(10,17): error CS0219: The variable 'x' is assigned but its value is never used [ConsoleApp1.csproj]
ConsoleApp1 -> ConsoleApp1.dll
Build FAILED.
Program.cs(10,17): error CS0219: The variable 'x' is assigned but its value is never used [ConsoleApp1.csproj]
0 Warning(s)
1 Error(s)
Time Elapsed 00:00:01.00
编辑:OP请求在发出警告时不要使构建失败。
你可以尝试将警告写入一个文件,然后计算该文件中的行数。
示例:
我取了上面的代码,并添加了几个变量:
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
现在,当我编译时,我得到了5个警告。现在我把这个添加到我的dotnet构建中:
$warningsFile = "SomeFile.log"
dotnet build -fl1 "/flp1:logFile=$warningsFile;warningsonly"
之后,我可以简单地计算该文件中的行数。使用powershell:
gc $warningsFile | Measure-Object -Line
结果:
Lines Words Characters Property
----- ----- ---------- --------
5
我不确定这是否在所有情况下都有效,但至少它会告诉你是否有警告。希望这能帮助你