如何从 dotnet build 命令获取警告

How to fetch warnings from the dotnet build command

给定一个 .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 管道应该通过,但如果出现警告,我想将它们标记为不稳定。

如果可能,我想避免 Regex 魔法。


编辑:

我不想添加标志 -warnaserror,因为那样 CI 管道将会失败,您将不知道是发生了构建错误还是代码风格不好。

您可以做的只是将 /WarnAsError 添加到您的 dotnet 构建中。

示例代码:

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 build /WarnAsError 的输出:

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

我不确定这是否适用于所有情况,但至少它会告诉您是否有警告。 希望对你有帮助