public void TestBinaryLoggerRoundtrip()
        {
            var binLog       = GetFullPath("1.binlog");
            var binaryLogger = new BinaryLogger();

            binaryLogger.Parameters = binLog;
            MSBuild.BuildProject(s_testProject, binaryLogger);

            var build = Serialization.Read(binLog);
            var xml1  = GetFullPath("1.xml");

            Serialization.Write(build, xml1);

            Serialization.Write(build, GetFullPath("1.buildlog"));
            build = Serialization.Read(GetFullPath("1.buildlog"));
            Serialization.Write(build, GetFullPath("2.xml"));

            Assert.False(Differ.AreDifferent(xml1, GetFullPath("2.xml")));

            build = XlinqLogReader.ReadFromXml(xml1);
            Serialization.Write(build, GetFullPath("3.xml"));
            Assert.False(Differ.AreDifferent(xml1, GetFullPath("3.xml")));

            build = Serialization.Read(xml1);
            Serialization.Write(build, GetFullPath("4.xml"));

            Assert.False(Differ.AreDifferent(xml1, GetFullPath("4.xml")));
        }
Example #2
0
        void BeginBuildOperation(IEngineLogWriter logWriter, string binLogFilePath, MSBuildVerbosity verbosity, ProjectConfigurationInfo [] configurations)
        {
            // Start a new MSBuild build session, sending log to the provided writter

            RunSTA(delegate {
                BuildOperationStarted = true;
                // This property specifies the mapping between the solution configuration
                // and the project configurations
                engine.SetGlobalProperty("CurrentSolutionConfigurationContents", ProjectBuilder.GenerateSolutionConfigurationContents(configurations));
                BuildParameters parameters = new BuildParameters(engine);
                sessionLogWriter           = logWriter;
                loggerAdapter = new MSBuildLoggerAdapter(logWriter, verbosity);

                if (!string.IsNullOrEmpty(binLogFilePath))
                {
                    var binaryLogger = new BinaryLogger {
                        Parameters = binLogFilePath,
                        Verbosity  = LoggerVerbosity.Diagnostic
                    };

                    var loggers = new List <ILogger> (loggerAdapter.Loggers);
                    loggers.Add(binaryLogger);
                    parameters.Loggers = loggers;
                }
                else
                {
                    parameters.Loggers = loggerAdapter.Loggers;
                }

                BuildManager.DefaultBuildManager.BeginBuild(parameters);
            });
        }
Example #3
0
        public BuilderDependencies(BuildContext context, IBazelMsBuildLogger?buildLog = null)
        {
            PathMapper    = new PathMapper(context.Bazel.OutputBase, context.Bazel.ExecRoot);
            Cache         = new BuildCache(context.Bazel.Label, PathMapper, new Files(), context.TargetGraph);
            ProjectLoader = new ProjectLoader(context.ProjectFile, Cache, PathMapper, context.TargetGraph);
            BuildLog      = buildLog ?? new BazelMsBuildLogger(
                m =>
            {
                Console.Out.Write(m);
                Console.Out.Flush();
            },
                context.DiagnosticsEnabled ? LoggerVerbosity.Normal : LoggerVerbosity.Quiet,
                (m) => PathMapper.ToRelative(m));

            Loggers = new List <ILogger>()
            {
                BuildLog
            };
            if (context.DiagnosticsEnabled)
            {
                var path = context.OutputPath(context.Bazel.Label.Name + ".binlog");
                Debug($"added binlog {path}");
                var binlog = new BinaryLogger()
                {
                    Parameters = path
                };
                Loggers.Add(binlog);
            }

            if (context.TargetGraph != null)
            {
                Loggers.Add(new TargetGraphLogger(context.TargetGraph !, PathMapper));
            }
        }
Example #4
0
        public ILogger CreateBinaryLogger(BinaryLoggerParameters fileLoggerParameters)
        {
            var fileLogger = new BinaryLogger();

            fileLogger.Parameters = fileLoggerParameters.ToString();
            return(Wrap(fileLogger));
        }
        private static List <ILogger> GetLoggers(string loggerPathSuffix)
        {
            var loggers = new List <ILogger>();

            if (!_noConsoleLogger)
            {
                loggers.Add(new ConsoleLogger(LoggerVerbosity.Normal));
            }

            if (DebugBuild)
            {
                Environment.SetEnvironmentVariable("MSBUILDTARGETOUTPUTLOGGING", "true");
                Environment.SetEnvironmentVariable("MSBUILDLOGIMPORTS", "1");

                var binaryLogger = new BinaryLogger
                {
                    Parameters = $"{Path.GetFileName(loggerPathSuffix)}.binlog",
                    Verbosity  = LoggerVerbosity.Detailed
                };

                loggers.Add(binaryLogger);

                var fileLogger = new FileLogger
                {
                    Parameters = $"logfile={Path.GetFileName(loggerPathSuffix)}.log",
                    Verbosity  = LoggerVerbosity.Detailed
                };

                loggers.Add(fileLogger);
            }
            return(loggers);
        }
Example #6
0
        public void TestBinaryLoggerRoundtrip()
        {
            var originalTargetOutputLogging = Environment.GetEnvironmentVariable(MSBUILDTARGETOUTPUTLOGGING);

            try
            {
                var binaryLogger = new BinaryLogger();
                var logFilePath  = "BinaryLoggerTest.binlog";
                binaryLogger.Parameters = logFilePath;

                var mockLogger1 = new MockLogger();

                // build and log into binary logger and mockLogger1
                ObjectModelHelpers.BuildProjectExpectSuccess(s_testProject, binaryLogger, mockLogger1);

                var mockLogger2 = new MockLogger();

                var binaryLogReader = new BinaryLogReplayEventSource();
                mockLogger2.Initialize(binaryLogReader);

                // read the binary log and replay into mockLogger2
                binaryLogReader.Replay(logFilePath);

                if (File.Exists(logFilePath))
                {
                    File.Delete(logFilePath);
                }

                Assert.Equal(mockLogger1.FullLog, mockLogger2.FullLog);
            }
            finally
            {
                Environment.SetEnvironmentVariable(MSBUILDTARGETOUTPUTLOGGING, originalTargetOutputLogging);
            }
        }
        public void BinaryLoggerShouldSupportFilePathExplicitParameter()
        {
            var binaryLogger = new BinaryLogger();

            binaryLogger.Parameters = $"LogFile={_logFile}";

            ObjectModelHelpers.BuildProjectExpectSuccess(s_testProject, binaryLogger);
        }
Example #8
0
 public ProjectAnalyzer WithBinaryLog(string binaryLogFilePath = null)
 {
     _binaryLogger = new BinaryLogger
     {
         Parameters            = binaryLogFilePath ?? Path.ChangeExtension(ProjectFilePath, "binlog"),
         CollectProjectImports = BinaryLogger.ProjectImportsCollectionMode.Embed
     };
     return(this);
 }
Example #9
0
        private (ILogger, Func <string>) GetBinaryLogger()
        {
            var    binaryLogger         = new BinaryLogger();
            string binaryLoggerFilePath = Path.GetFullPath(Path.Combine(TestRoot, Guid.NewGuid().ToString() + ".binlog"));

            binaryLogger.CollectProjectImports = BinaryLogger.ProjectImportsCollectionMode.None;
            binaryLogger.Parameters            = binaryLoggerFilePath;
            return(binaryLogger, null);
        }
Example #10
0
        public void TestBinaryLoggerRoundtrip(string projectText)
        {
            var binaryLogger = new BinaryLogger();

            binaryLogger.Parameters = _logFile;

            var mockLogFromBuild = new MockLogger();

            var serialFromBuildText = new StringBuilder();
            var serialFromBuild     = new SerialConsoleLogger(Framework.LoggerVerbosity.Diagnostic, t => serialFromBuildText.Append(t), colorSet: null, colorReset: null);

            serialFromBuild.Parameters = "NOPERFORMANCESUMMARY";

            var parallelFromBuildText = new StringBuilder();
            var parallelFromBuild     = new ParallelConsoleLogger(Framework.LoggerVerbosity.Diagnostic, t => parallelFromBuildText.Append(t), colorSet: null, colorReset: null);

            parallelFromBuild.Parameters = "NOPERFORMANCESUMMARY";

            // build and log into binary logger, mock logger, serial and parallel console loggers
            ObjectModelHelpers.BuildProjectExpectSuccess(projectText, binaryLogger, mockLogFromBuild, serialFromBuild, parallelFromBuild);

            var mockLogFromPlayback = new MockLogger();

            var serialFromPlaybackText = new StringBuilder();
            var serialFromPlayback     = new SerialConsoleLogger(Framework.LoggerVerbosity.Diagnostic, t => serialFromPlaybackText.Append(t), colorSet: null, colorReset: null);

            serialFromPlayback.Parameters = "NOPERFORMANCESUMMARY";

            var parallelFromPlaybackText = new StringBuilder();
            var parallelFromPlayback     = new ParallelConsoleLogger(Framework.LoggerVerbosity.Diagnostic, t => parallelFromPlaybackText.Append(t), colorSet: null, colorReset: null);

            parallelFromPlayback.Parameters = "NOPERFORMANCESUMMARY";

            var binaryLogReader = new BinaryLogReplayEventSource();

            mockLogFromPlayback.Initialize(binaryLogReader);
            serialFromPlayback.Initialize(binaryLogReader);
            parallelFromPlayback.Initialize(binaryLogReader);

            // read the binary log and replay into mockLogger2
            binaryLogReader.Replay(_logFile);

            // the binlog will have more information than recorded by the text log
            mockLogFromPlayback.FullLog.ShouldContainWithoutWhitespace(mockLogFromBuild.FullLog);

            var serialExpected   = serialFromBuildText.ToString();
            var serialActual     = serialFromPlaybackText.ToString();
            var parallelExpected = parallelFromBuildText.ToString();
            var parallelActual   = parallelFromPlaybackText.ToString();

            serialActual.ShouldContainWithoutWhitespace(serialExpected);
            parallelActual.ShouldContainWithoutWhitespace(parallelExpected);
        }
Example #11
0
        private static async Task <Workspace?> OpenMSBuildWorkspaceAsync(
            string solutionOrProjectPath,
            WorkspaceType workspaceType,
            bool logWorkspaceWarnings,
            ILogger logger,
            CancellationToken cancellationToken,
            bool createBinaryLog = false)
        {
            var properties = new Dictionary <string, string>(StringComparer.Ordinal)
            {
                // This property ensures that XAML files will be compiled in the current AppDomain
                // rather than a separate one. Any tasks isolated in AppDomains or tasks that create
                // AppDomains will likely not work due to https://github.com/Microsoft/MSBuildLocator/issues/16.
                { "AlwaysCompileMarkupFilesInSeparateDomain", bool.FalseString },
                // This flag is used at restore time to avoid imports from packages changing the inputs to restore,
                // without this it is possible to get different results between the first and second restore.
                { "ExcludeRestorePackageImports", bool.TrueString },
            };

            var workspace = MSBuildWorkspace.Create(properties);

            Build.Framework.ILogger?binlog = null;
            if (createBinaryLog)
            {
                binlog = new BinaryLogger()
                {
                    Parameters = Path.Combine(Environment.CurrentDirectory, "formatDiagnosticLog.binlog"),
                    Verbosity  = Build.Framework.LoggerVerbosity.Diagnostic,
                };
            }

            if (workspaceType == WorkspaceType.Solution)
            {
                await workspace.OpenSolutionAsync(solutionOrProjectPath, msbuildLogger : binlog, cancellationToken : cancellationToken).ConfigureAwait(false);
            }
            else
            {
                try
                {
                    await workspace.OpenProjectAsync(solutionOrProjectPath, msbuildLogger : binlog, cancellationToken : cancellationToken).ConfigureAwait(false);
                }
                catch (InvalidOperationException)
                {
                    logger.LogError(Resources.Could_not_format_0_Format_currently_supports_only_CSharp_and_Visual_Basic_projects, solutionOrProjectPath);
                    workspace.Dispose();
                    return(null);
                }
            }

            LogWorkspaceDiagnostics(logger, logWorkspaceWarnings, workspace.Diagnostics);

            return(workspace);
        }
 public ProjectLogger(BackEndBuildTableDataSource dataSource, bool isDesignTime) :
     base(dataSource)
 {
     _logPath      = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.binlog");
     _binaryLogger = new BinaryLogger
     {
         Parameters            = _logPath,
         Verbosity             = LoggerVerbosity.Diagnostic,
         CollectProjectImports = BinaryLogger.ProjectImportsCollectionMode.None
     };
     _isDesignTime = isDesignTime;
 }
Example #13
0
        private static Project LoadProject(string projectFile, string targetFramework)
        {
            var          sw     = Stopwatch.StartNew();
            BinaryLogger logger = null;

            try
            {
                var properties = new Dictionary <string, string>()
                {
                    ["Configuration"] = "Debug",
                };

                if (!string.IsNullOrEmpty(targetFramework))
                {
                    properties["TargetFramework"] = targetFramework;
                }

                var xmlReader  = XmlReader.Create(projectFile);
                var collection = new ProjectCollection();

                // Change this logger details to troubleshoot project loading details.
                collection.RegisterLogger(new Microsoft.Build.Logging.ConsoleLogger()
                {
                    Verbosity = LoggerVerbosity.Minimal
                });
                collection.RegisterLogger(logger = new BinaryLogger()
                {
                    Parameters = @"test.binlog;ProjectImports=ZipFile", Verbosity = LoggerVerbosity.Diagnostic
                });

                collection.OnlyLogCriticalEvents = false;
                var xml = Microsoft.Build.Construction.ProjectRootElement.Create(xmlReader, collection);

                // When constructing a project from an XmlReader, MSBuild cannot determine the project file path.  Setting the
                xml.FullPath = Path.GetFullPath(projectFile);

                return(new Project(
                           xml,
                           properties,
                           toolsVersion: null,
                           projectCollection: collection
                           ));
            }
            finally
            {
                logger?.Shutdown();
                Console.WriteLine($"[{sw.Elapsed}] Loaded {projectFile} for {targetFramework}");
            }
        }
Example #14
0
        /// <nodoc />
        public ExecutionLogFileTarget(BinaryLogger logFile, bool closeLogFileOnDispose = true, IReadOnlyList <int> disabledEventIds = null)
        {
            Contract.Requires(logFile != null);
            m_closeLogFileOnDispose = closeLogFileOnDispose;
            m_logFile          = logFile;
            m_disabledEventIds = disabledEventIds;

            // Disable the specified event ids (if any)
            if (m_disabledEventIds != null)
            {
                foreach (var eventId in m_disabledEventIds)
                {
                    if ((ulong)eventId <= EnumTraits <ExecutionEventId> .MaxValue)
                    {
                        DisableEvent((ExecutionEventId)eventId);
                    }
                }
            }
        }
Example #15
0
        public void TestBinaryLoggerRoundtrip()
        {
            var binaryLogger = new BinaryLogger();

            binaryLogger.Parameters = _logFile;

            var mockLogger1 = new MockLogger();

            // build and log into binary logger and mockLogger1
            ObjectModelHelpers.BuildProjectExpectSuccess(s_testProject, binaryLogger, mockLogger1);

            var mockLogger2 = new MockLogger();

            var binaryLogReader = new BinaryLogReplayEventSource();

            mockLogger2.Initialize(binaryLogReader);

            // read the binary log and replay into mockLogger2testassembly
            binaryLogReader.Replay(_logFile);

            Assert.Equal(mockLogger1.FullLog, mockLogger2.FullLog);
        }
Example #16
0
        public void BinaryLoggerShouldNotThrowWhenMetadataCannotBeExpanded()
        {
            var binaryLogger = new BinaryLogger
            {
                Parameters = $"LogFile={_logFile}"
            };

            const string project = @"
<Project>
<ItemDefinitionGroup>
  <F>
   <MetadataFileName>a\b\%(Filename).c</MetadataFileName>
  </F>
 </ItemDefinitionGroup>
 <ItemGroup>
  <F Include=""-in &quot;x\y\z&quot;"" />
 </ItemGroup>
 <Target Name=""X"" />
</Project>";

            ObjectModelHelpers.BuildProjectExpectSuccess(project, binaryLogger);
        }
Example #17
0
        public void TestBinaryLoggerRoundtrip()
        {
            var originalTargetOutputLogging = Environment.GetEnvironmentVariable(MSBUILDTARGETOUTPUTLOGGING);

            try
            {
                var binaryLogger = new BinaryLogger();

                // with this file name, the file will be archived as as build artifact so we can inspect it later
                // this is needed to investigate an intermittent failure of this test on Ubuntu 14
                var logFilePath = "Microsoft.Build.Engine.UnitTests.dll_TestBinaryLoggerRoundtrip.binlog";
                binaryLogger.Parameters = logFilePath;

                var mockLogger1 = new MockLogger();

                // build and log into binary logger and mockLogger1
                ObjectModelHelpers.BuildProjectExpectSuccess(s_testProject, binaryLogger, mockLogger1);

                var mockLogger2 = new MockLogger();

                var binaryLogReader = new BinaryLogReplayEventSource();
                mockLogger2.Initialize(binaryLogReader);

                // read the binary log and replay into mockLogger2
                binaryLogReader.Replay(logFilePath);

                if (File.Exists(logFilePath))
                {
                    File.Delete(logFilePath);
                }

                Assert.Equal(mockLogger1.FullLog, mockLogger2.FullLog);
            }
            finally
            {
                Environment.SetEnvironmentVariable(MSBUILDTARGETOUTPUTLOGGING, originalTargetOutputLogging);
            }
        }
Example #18
0
        public void NonExistingDirectory()
        {
            string directory = Path.Combine(ObjectModelHelpers.TempProjectDir, Guid.NewGuid().ToString("N"));
            string log       = Path.Combine(directory, "build.binlog");

            Assert.False(Directory.Exists(directory));
            Assert.False(File.Exists(log));

            var binaryLogger = new BinaryLogger {
                Parameters = log
            };

            try
            {
                ObjectModelHelpers.BuildProjectExpectSuccess(s_testProject, binaryLogger);
                Assert.True(Directory.Exists(directory));
                Assert.True(File.Exists(log));
            }
            finally
            {
                ObjectModelHelpers.DeleteDirectory(directory);
            }
        }
        public void TestBinaryLoggerRoundtrip(string projectText)
        {
            var binaryLogger = new BinaryLogger();

            binaryLogger.Parameters = _logFile;

            var mockLogFromBuild = new MockLogger();

            // build and log into binary logger and mockLogger1
            ObjectModelHelpers.BuildProjectExpectSuccess(projectText, binaryLogger, mockLogFromBuild);

            var mockLogFromPlayback = new MockLogger();

            var binaryLogReader = new BinaryLogReplayEventSource();

            mockLogFromPlayback.Initialize(binaryLogReader);

            // read the binary log and replay into mockLogger2
            binaryLogReader.Replay(_logFile);

            // the binlog will have more information than recorded by the text log
            Assert.Contains(mockLogFromBuild.FullLog, mockLogFromPlayback.FullLog);
        }
Example #20
0
        public void MessagesCanBeLoggedWhenProjectsAreCached()
        {
            using var env = TestEnvironment.Create();

            env.SetEnvironmentVariable("MSBUILDDEBUGFORCECACHING", "1");

            using var buildManager = new BuildManager();

            var binaryLogger = new BinaryLogger
            {
                Parameters = $"LogFile={_logFile}"
            };

            // To trigger #6323, there must be at least two project instances.
            var referenceProject = _env.CreateTestProjectWithFiles("reference.proj", @"
         <Project>
            <Target Name='Target2'>
               <Exec Command='echo a'/>
            </Target>
         </Project>");

            var entryProject = _env.CreateTestProjectWithFiles("entry.proj", $@"
         <Project>
            <Target Name='BuildSelf'>
               <Message Text='MessageOutputText'/>
               <MSBuild Projects='{referenceProject.ProjectFile}' Targets='Target2' />
               <MSBuild Projects='{referenceProject.ProjectFile}' Targets='Target2' /><!-- yes, again. That way it's a cached result -->
            </Target>
         </Project>");

            buildManager.Build(new BuildParameters()
            {
                Loggers = new ILogger[] { binaryLogger }
            },
                               new BuildRequestData(entryProject.ProjectFile, new Dictionary <string, string>(), null, new string[] { "BuildSelf" }, null))
            .OverallResult.ShouldBe(BuildResultCode.Success);
        }
Example #21
0
        public Task Save(string filePath)
        {
            return(Task.Run(() => {
                var eventsSource = new BuildOutputEventsSource();
                var logger = new BinaryLogger {
                    CollectProjectImports = BinaryLogger.ProjectImportsCollectionMode.None,
                    Parameters = filePath,
                    Verbosity = LoggerVerbosity.Diagnostic
                };

                try {
                    logger.Initialize(eventsSource);

                    foreach (var proj in projects)
                    {
                        switch (proj)
                        {
                        case MSBuildOutputProcessor msbop:
                            eventsSource.ProcessFile(proj.FileName);
                            break;

                        case BuildOutputProcessor bop:
                            // FIXME
                            break;

                        default:
                            continue;
                        }
                    }
                } catch (Exception ex) {
                    LoggingService.LogError($"Can't write to {filePath}: {ex.Message})");
                } finally {
                    logger.Shutdown();
                }
            }));
        }
 private NotifyOrchestratorExecutionLogTarget(BinaryLogger logger)
     : base(logger, closeLogFileOnDispose: true)
 {
     m_logger = logger;
 }
Example #23
0
        public void RoundTripLog()
        {
            BuildXLContext context = BuildXLContext.CreateInstanceForTesting();

            var pt = context.PathTable;

            string path1 = A("c", "a", "b", "c");
            var    ap1   = AbsolutePath.Create(pt, path1);
            string path2 = A("c", "d", "c", "a");
            var    ap2   = AbsolutePath.Create(pt, path2);

            string path3 = A("d", "a", "c", "a");
            var    ap3   = AbsolutePath.Create(pt, path3);

            string path3Caps = A("D", "A", "c", "a");
            var    ap3Caps   = AbsolutePath.Create(pt, path3Caps);

            int  lastTestCase0EventIteration = 0;
            int  testCase0EventIteration     = 0;
            int  expectedReadCount           = 0;
            Guid logId = Guid.NewGuid();

            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryLogger writer = new BinaryLogger(ms, context, logId, lastStaticAbsolutePathIndex: ap2.Value.Value, closeStreamOnDispose: false))
                {
                    using (var eventScope = writer.StartEvent((uint)EventId.TestCase0, workerId: 0))
                    {
                        eventScope.Writer.Write(ap1);
                        eventScope.Writer.Write("test string");
                        eventScope.Writer.Write(ap3);
                        eventScope.Writer.Write(12345);
                        expectedReadCount++;
                        lastTestCase0EventIteration++;
                    }

                    using (var eventScope = writer.StartEvent((uint)EventId.TestCase0, workerId: 0))
                    {
                        eventScope.Writer.Write("test string 2");
                        eventScope.Writer.Write(true);
                        eventScope.Writer.Write(ap3);
                        expectedReadCount++;
                        lastTestCase0EventIteration++;
                    }
                }

                ms.Position = 0;

                using (BinaryLogReader reader = new BinaryLogReader(ms, context))
                {
                    XAssert.IsTrue(reader.LogId.HasValue);
                    XAssert.AreEqual(logId, reader.LogId.Value);
                    reader.RegisterHandler((uint)EventId.TestCase0, (eventId, workerId, timestamp, eventReader) =>
                    {
                        switch (testCase0EventIteration)
                        {
                        case 0:
                            XAssert.AreEqual(ap1, eventReader.ReadAbsolutePath());
                            XAssert.AreEqual("test string", eventReader.ReadString());
                            XAssert.AreEqual(ap3, eventReader.ReadAbsolutePath());
                            XAssert.AreEqual(12345, eventReader.ReadInt32());
                            break;

                        case 1:
                            XAssert.AreEqual("test string 2", eventReader.ReadString());
                            XAssert.AreEqual(true, eventReader.ReadBoolean());
                            XAssert.AreEqual(ap3, eventReader.ReadAbsolutePath());
                            break;

                        default:
                            XAssert.Fail("Event raised unexpected number of times.");
                            break;
                        }

                        testCase0EventIteration++;
                    });

                    reader.RegisterHandler((uint)EventId.UnusedEvent, (eventId, workerId, timestamp, eventReader) =>
                    {
                        XAssert.Fail("This event should never be called.");
                    });

                    int readCount = 0;
                    BinaryLogReader.EventReadResult?readResult;
                    while ((readResult = reader.ReadEvent()) == BinaryLogReader.EventReadResult.Success)
                    {
                        XAssert.IsTrue(readCount < expectedReadCount);
                        readCount++;
                    }

                    XAssert.AreEqual(expectedReadCount, readCount);
                    XAssert.AreEqual(lastTestCase0EventIteration, testCase0EventIteration);
                    XAssert.AreEqual(BinaryLogReader.EventReadResult.EndOfStream, readResult);
                }
            }
        }
Example #24
0
 public EventWrapper(BinaryLogger binaryLogger)
 {
     BinaryLogger = binaryLogger;
     BinaryLogger.Initialize(this);
 }
Example #25
0
 /// <summary>
 /// Clones the execution log target with the same backing binary logger but against a different worker id
 /// </summary>
 private ExecutionLogFileTarget(BinaryLogger logFile, uint workerId, IReadOnlyList <int> disabledEventIds)
     : this(logFile, closeLogFileOnDispose : false, disabledEventIds : disabledEventIds)
 {
     m_workerId = workerId;
 }
Example #26
0
        private void AnyEvent(object sender, BuildEventArgs args)
        {
            if (args.BuildEventContext.EvaluationId == BuildEventContext.InvalidEvaluationId)
            {
                return;
            }

            switch (args)
            {
            case ProjectEvaluationStartedEventArgs evaluationStarted:
            {
                if (!DataSource.IsLogging || evaluationStarted.ProjectFile == "(null)")
                {
                    return;
                }

                var logPath      = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.binlog");
                var binaryLogger = new BinaryLogger
                {
                    Parameters            = logPath,
                    Verbosity             = LoggerVerbosity.Diagnostic,
                    CollectProjectImports = BinaryLogger.ProjectImportsCollectionMode.None
                };
                var wrapper = new EventWrapper(binaryLogger);
                var build   = new Build(evaluationStarted.ProjectFile, Array.Empty <string>(), Array.Empty <string>(),
                                        BuildType.Evaluation, args.Timestamp);
                _evaluations[evaluationStarted.BuildEventContext.EvaluationId] = new Evaluation
                {
                    Wrapper = wrapper,
                    Build   = build,
                    LogPath = logPath
                };
                wrapper.RaiseEvent(sender, args);
                DataSource.AddEntry(build);
            }
            break;

            case ProjectEvaluationFinishedEventArgs _:
            {
                if (_evaluations.TryGetValue(args.BuildEventContext.EvaluationId, out var evaluation))
                {
                    evaluation.Build.Finish(true, args.Timestamp);
                    evaluation.Wrapper.RaiseEvent(sender, args);
                    evaluation.Wrapper.BinaryLogger.Shutdown();
                    evaluation.Build.SetLogPath(GetLogPath(evaluation.Build));
                    Copy(evaluation.LogPath, evaluation.Build.LogPath);
                    DataSource.NotifyChange();
                }
            }
            break;

            default:
            {
                if (_evaluations.TryGetValue(args.BuildEventContext.EvaluationId, out var evaluation))
                {
                    evaluation.Wrapper.RaiseEvent(sender, args);
                }
            }
            break;
            }
        }
Example #27
0
        public MSBuildResult Run(
            ProjectConfigurationInfo[] configurations, IEngineLogWriter logWriter, MSBuildVerbosity verbosity, string binLogFilePath,
            string[] runTargets, string[] evaluateItems, string[] evaluateProperties, Dictionary <string, string> globalProperties, int taskId)
        {
            if (runTargets == null || runTargets.Length == 0)
            {
                throw new ArgumentException("runTargets is empty");
            }

            MSBuildResult result = null;

            BuildEngine.RunSTA(taskId, delegate {
                Project project = null;
                Dictionary <string, string> originalGlobalProperties = null;

                MSBuildLoggerAdapter loggerAdapter;

                if (buildEngine.BuildOperationStarted)
                {
                    loggerAdapter = buildEngine.StartProjectSessionBuild(logWriter);
                }
                else
                {
                    loggerAdapter = new MSBuildLoggerAdapter(logWriter, verbosity);
                    if (!string.IsNullOrEmpty(binLogFilePath))
                    {
                        var binaryLogger = new BinaryLogger {
                            Parameters = binLogFilePath,
                            Verbosity  = LoggerVerbosity.Diagnostic
                        };
                        loggerAdapter.AddLogger(binaryLogger);
                    }
                }

                try {
                    project = SetupProject(configurations);

                    if (globalProperties != null)
                    {
                        originalGlobalProperties = new Dictionary <string, string> ();
                        foreach (var p in project.GlobalProperties)
                        {
                            originalGlobalProperties [p.Key] = p.Value;
                        }
                        if (globalProperties != null)
                        {
                            foreach (var p in globalProperties)
                            {
                                project.SetGlobalProperty(p.Key, p.Value);
                            }
                        }
                    }

                    // Building the project will create items and alter properties, so we use a new instance
                    var pi = project.CreateProjectInstance();

                    Build(pi, runTargets, loggerAdapter.Loggers);

                    result = new MSBuildResult(loggerAdapter.BuildResult.ToArray());

                    if (evaluateProperties != null)
                    {
                        foreach (var name in evaluateProperties)
                        {
                            var prop = pi.GetProperty(name);
                            result.Properties [name] = prop != null? prop.EvaluatedValue : null;
                        }
                    }

                    if (evaluateItems != null)
                    {
                        foreach (var name in evaluateItems)
                        {
                            var grp  = pi.GetItems(name);
                            var list = new List <MSBuildEvaluatedItem> ();
                            foreach (var item in grp)
                            {
                                var evItem = new MSBuildEvaluatedItem(name, UnescapeString(item.EvaluatedInclude));
                                foreach (var metadataName in item.MetadataNames)
                                {
                                    evItem.Metadata [metadataName] = UnescapeString(item.GetMetadataValue(metadataName));
                                }
                                list.Add(evItem);
                            }
                            result.Items[name] = list.ToArray();
                        }
                    }
                } catch (Microsoft.Build.Exceptions.InvalidProjectFileException ex) {
                    var r = new MSBuildTargetResult(
                        file, false, ex.ErrorSubcategory, ex.ErrorCode, ex.ProjectFile,
                        ex.LineNumber, ex.ColumnNumber, ex.EndLineNumber, ex.EndColumnNumber,
                        ex.BaseMessage, ex.HelpKeyword);
                    loggerAdapter.LogWriteLine(r.ToString());
                    result = new MSBuildResult(new [] { r });
                } finally {
                    if (buildEngine.BuildOperationStarted)
                    {
                        buildEngine.EndProjectSessionBuild();
                    }
                    else
                    {
                        loggerAdapter.Dispose();
                    }

                    if (project != null && globalProperties != null)
                    {
                        foreach (var p in globalProperties)
                        {
                            project.RemoveGlobalProperty(p.Key);
                        }
                        foreach (var p in originalGlobalProperties)
                        {
                            project.SetGlobalProperty(p.Key, p.Value);
                        }
                    }
                }
            });
            return(result);
        }