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

Abe*_*ich 5 cruisecontrol.net msbuild

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

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

可能是,解决方案是创建我自己的记录器,将内部存储警告标志,但我无法找到是否有一种方法在构建结束时读取此标志?

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

PPS至于我真的不需要警告的数量,而只是它们存在的标志,我决定简化信令机制,并使用琐碎的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++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jor*_*ira 7

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

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

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

共享内存

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

我已经创建了一个名为共享内存的包装器,它是一个更大的项目的一部分.它基本上允许将序列化类型和对象图存储在共享内存中并从共享内存中检索(包括您期望的跨进程).更大的项目是否完成是另一回事;-).

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

旋转一下.

<?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>
Run Code Online (Sandbox Code Playgroud)

如果您运行以下命令:

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MSBuild test.xml /logger:SampleLogger.dll
Run Code Online (Sandbox Code Playgroud)

这将是输出:

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
Run Code Online (Sandbox Code Playgroud)