MSBuild:如何获得引发的警告数量?

时间:2008-09-30 10:10:44

标签: msbuild cruisecontrol.net

有一个MSBuild脚本,包括Delphi和C#项目的数字,单元测试等。

问题是:如果警告被引发,如何标记构建失败(出于测试目的,而不是发布版本)?在自定义任务中使用LogError而不是LogWarning似乎不是一个好的选择,因为构建应尽可能多地测试(直到真正的错误)在一段时间内尽可能多地报告警告(构建项目在CruiseControl.NET中使用) )。

可能是,解决方案是创建我自己的记录器,它会在里面存储警告标志,但我找不到是否有办法在构建结束时读取这个标志?

P.S。收到警告后立即使构建失败没有问题(Delphi编译器输出由自定义任务处理,而/ warnaserror可用于C#),但所需的行为是“构建所有内容;收集所有警告;构建失败”报告所有警告,而不仅仅是关于第一个警告。

P.P.S。至于我真的不需要警告的数量,而只是它们存在的标志,我决定简化信令机制,并使用琐碎的Mutex而不是共享内存。代码如下:

using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.Threading;

namespace Intrahealth.Build.WarningLogger
{
    public sealed class WarningLoggerCheck : Task
    {
        public override bool Execute()
        {
            Log.LogMessage("WarningLoggerCheck:" + mutexName + "...");
            result = false;
            Mutex m = null;
            try
            {
                m = Mutex.OpenExisting(mutexName);
            }
            catch (WaitHandleCannotBeOpenedException)
            {
                result = true;
            }
            catch (Exception)
            {
            }

            if (result)
                Log.LogMessage("WarningLoggerCheck PASSED");
            else
                Log.LogError("Build log contains warnings. Build is FAILED");

            return result;
        }

        private bool result = true;
        [Output]
        public bool Result
        {
            get { return result; }
        }

        private string mutexName = "WarningLoggerMutex";
        public string MutexName
        {
            get { return mutexName; }
            set { mutexName = value ?? "WarningLoggerMutex"; }
        }
    }

    public class WarningLogger : Logger
    {
        internal static int warningsCount = 0;
        private string mutexName = String.Empty;
        private Mutex mutex = null;

        public override void Initialize(IEventSource eventSource)
        {
            eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);
        }

        private void SetMutex()
        {
            if (mutexName == String.Empty)
            {
                mutexName = "WarningLoggerMutex";
                if (this.Parameters != null && this.Parameters != String.Empty)
                {
                    mutexName = this.Parameters;
                }
            }

            mutex = new Mutex(false, mutexName);
        }

        void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
        {
            if (e.Message != null && e.Message.Contains("MSB3146"))
                return;
            if (e.Code != null && e.Code.Equals("MSB3146"))
                return;

            if (warningsCount == 0)
                SetMutex();
            warningsCount++;
        }
    }
}

3 个答案:

答案 0 :(得分:7)

AFAIK MSBuild没有内置支持来检索构建脚本的给定点的警告计数。但是,您可以按照以下步骤来实现此目标:

  1. 创建一个侦听警告事件并计算警告数量的自定义记录器
  2. 创建一个公开[Output] WarningCount属性
  3. 的自定义任务
  4. 自定义任务以某种方式从自定义记录器
  5. 获取警告计数的值

    最困难的一步是第3步。为此,有几个选项,您可以在IPC - Inter Process Comunication下自由搜索它们。下面是一个如何实现这一目标的工作示例。每个项目都是不同的类库

    <强>共享内存

    http://weblogs.asp.net/rosherove/archive/2003/05/01/6295.aspx

      

    我为named创建了一个包装器   共享内存是一部分   更大的项目。它基本上允许   序列化类型和对象图   存储在共享中并从共享中检索   记忆(包括你所期望的   跨进程)。是否更大   项目永远完成是另一个   问题; - )。

    <强> SampleLogger

    实现跟踪警告计数的自定义记录器。

    namespace SampleLogger
    {
        using System;
        using Microsoft.Build.Utilities;
        using Microsoft.Build.Framework;
        using DM.SharedMemory;
    
        public class MySimpleLogger : Logger
        {
            private Segment s;
            private int warningCount;
    
            public override void Initialize(IEventSource eventSource)
            {
                eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);
    
                this.s = new Segment("MSBuildMetadata", SharedMemoryCreationFlag.Create, 65535);
                this.s.SetData(this.warningCount.ToString());
            }
    
            void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
            {
                this.warningCount++;
                this.s.SetData(this.warningCount.ToString());
            }
    
            public override void Shutdown()
            {
                this.s.Dispose();
                base.Shutdown();
            }
        }
    }
    

    <强> SampleTasks

    实现自定义任务,该任务读取MSbuild项目中引发的警告数。自定义任务从类库 SampleLogger 中实现的自定义记录器写入的共享内存中读取。

    namespace SampleTasks
    {
        using System;
        using Microsoft.Build.Utilities;
        using Microsoft.Build.Framework;
        using DM.SharedMemory;
    
        public class BuildMetadata : Task
        {
            public int warningCount;
    
            [Output]
            public int WarningCount
            {
                get
                {
                    Segment s = new Segment("MSBuildMetadata", SharedMemoryCreationFlag.Attach, 0);
                    int warningCount = Int32.Parse(s.GetData() as string);
                    return warningCount;
                }
            }
    
            public override bool Execute()
            {
                return true;
            }
        }
    }
    

    旋转。

    <?xml version="1.0" encoding="UTF-8"?>
    <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Main">
        <UsingTask TaskName="BuildMetadata" AssemblyFile="F:\temp\SampleLogger\bin\debug\SampleTasks.dll" />
    
        <Target Name="Main">
            <Warning Text="Sample warning #1" />
            <Warning Text="Sample warning #2" />
    
            <BuildMetadata>
                <Output
                    TaskParameter="WarningCount"
                    PropertyName="WarningCount" />
            </BuildMetadata>
    
            <Error Text="A total of $(WarningCount) warning(s) were raised." Condition="$(WarningCount) > 0" />
        </Target>
    </Project>
    

    如果您运行以下命令:

    c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MSBuild test.xml /logger:SampleLogger.dll
    

    这将是输出:

    Microsoft (R) Build Engine Version 2.0.50727.3053
    [Microsoft .NET Framework, Version 2.0.50727.3053]
    Copyright (C) Microsoft Corporation 2005. All rights reserved.
    
    Build started 30-09-2008 13:04:39.
    __________________________________________________
    Project "F:\temp\SampleLogger\bin\debug\test.xml" (default targets):
    
    Target Main:
        F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #1
        F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #2
        F:\temp\SampleLogger\bin\debug\test.xml(15,3): error : A total of 2 warning(s) were raised.
    Done building target "Main" in project "test.xml" -- FAILED.
    
    Done building project "test.xml" -- FAILED.
    
    Build FAILED.
    F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #1
    F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #2
    F:\temp\SampleLogger\bin\debug\test.xml(15,3): error : A total of 2 warning(s) were raised.
        2 Warning(s)
        1 Error(s)
    
    Time Elapsed 00:00:00.01
    

答案 1 :(得分:1)

C#编译器(csc.exe)有一个/ warnaserror开关将警告视为错误并使构建失败。这也可以作为.csproj文件中的设置使用。我认为德尔福有类似的能力。

答案 2 :(得分:1)

msbuild.exe %~nx1 /t:Rebuild /p:Configuration=Release >> %MrB-BUILDLOG%
findstr /r /c:"[1-9][0-9]* Error(s)" >> %MrB-BUILDLOG%
if not errorlevel 1 (
   echo ERROR: sending notification email for build errors in '%~nx1'. >> %MrB-BUILDLOG%
) else (
   findstr /r /c:"[1-9][0-9]* Warning(s)" >> %MrB-BUILDLOG%
   if not errorlevel 1 (
       echo ERROR: sending notification email for build warnings in '%~nx1'. >>

%MRB-BUILDLOG%        )其他(           echo成功构建'%~nx1'。 &GT;&GT; %MRB-BUILDLOG%        )     )