<commit_before>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoTest.Core.Messaging;
using AutoTest.Core.BuildRunners;
using AutoTest.Core.Configuration;
using AutoTest.Core.Caching;
using AutoTest.Core.Caching.Projects;
using AutoTest.Core.TestRunners;
using System.IO;
using AutoTest.Core.TestRunners.TestRunners;
using Castle.Core.Logging;
using AutoTest.Core.DebugLog;
using AutoTest.Messages;
using System.Threading;

namespace AutoTest.Core.Messaging.MessageConsumers
{
    class ProjectChangeConsumer : IOverridingConsumer<ProjectChangeMessage>
    {
        private bool _isRunning = false;
        private bool _exit = false;
        private IMessageBus _bus;
        private IGenerateBuildList _listGenerator;
        private IConfiguration _configuration;
        private IBuildRunner _buildRunner;
        private ITestRunner[] _testRunners;
		private IDetermineIfAssemblyShouldBeTested _testAssemblyValidator;
		private IOptimizeBuildConfiguration _buildOptimizer;
        private IPreProcessBuildruns[] _preBuildProcessors;
        private IPreProcessTestruns[] _preProcessors;
        private ILocateRemovedTests _removedTestLocator;
        private List<RunInfo> _abortedBuilds = new List<RunInfo>();
        private List<RunInfo> _abortedTestRuns = new List<RunInfo>();

        public bool IsRunning { get { return _isRunning; } }

        public ProjectChangeConsumer(IMessageBus bus, IGenerateBuildList listGenerator, IConfiguration configuration, IBuildRunner buildRunner, ITestRunner[] testRunners, IDetermineIfAssemblyShouldBeTested testAssemblyValidator, IOptimizeBuildConfiguration buildOptimizer, IPreProcessTestruns[] preProcessors, ILocateRemovedTests removedTestLocator, IPreProcessBuildruns[] preBuildProcessors)
        {
            _bus = bus;
            _listGenerator = listGenerator;
            _configuration = configuration;
            _buildRunner = buildRunner;
            _testRunners = testRunners;
			_testAssemblyValidator = testAssemblyValidator;
			_buildOptimizer = buildOptimizer;
            _preProcessors = preProcessors;
            _preBuildProcessors = preBuildProcessors;
            _removedTestLocator = removedTestLocator;
        }

        #region IConsumerOf<ProjectChangeMessage> Members

        public void Consume(ProjectChangeMessage message)
        {
            _isRunning = true;
            var now = DateTime.Now;
            Debug.ConsumingProjectChangeMessage(message);
            _bus.Publish(new RunStartedMessage(message.Files));
            var runReport = execute(message);
            runReport.SetTimeSpent(DateTime.Now.Subtract(now));
            _bus.Publish(new RunFinishedMessage(runReport));
            _exit = false;
            _isRunning = false;
        }

        public void Terminate()
        {
            if (!_isRunning)
                return;
            Debug.WriteDebug("Initiating termination of current run");
            _exit = true;
            while (_isRunning)
                Thread.Sleep(10);
        }

        private RunReport execute(ProjectChangeMessage message)
        {
            var runReport = new RunReport();
            try
            {
                Debug.WriteDebug("Starting project change run");
                var list = getPrioritizedList(message);
                if (!buildAll(list, runReport))
                    return runReport;
                if (_exit)
                {
                    _abortedBuilds.Clear();
                    _abortedBuilds.AddRange(list);
                    return runReport;
                }
                else
                    _abortedBuilds.Clear();
                markAllAsBuilt(list);
                testAll(list, runReport);
            }
            catch (Exception ex)
            {
                var result = new TestRunResults("", "", false, TestRunner.Any, new TestResult[] { new TestResult(TestRunner.Any, TestRunStatus.Failed, "AutoTest.Net internal error", ex.ToString()) });
                _bus.Publish(new TestRunMessage(result));
            }
            return runReport;
        }

        private RunInfo[] getPrioritizedList(ProjectChangeMessage message)
        {
            var projectsAndDependencies = _listGenerator.Generate(getListOfChangedProjects(message));
            var list = _buildOptimizer.AssembleBuildConfiguration(projectsAndDependencies);
            list = preProcessBuildRun(list);
            list = mergeWithAbortedBuilds(list);
            return list;
        }

        private RunInfo[] mergeWithAbortedBuilds(RunInfo[] list)
        {
            return new RunInfoMerger(list).MergeWith(_abortedBuilds).ToArray();
        }

        private RunInfo[] preProcessBuildRun(RunInfo[] runInfos)
        {
            foreach (var preProcessor in _preBuildProcessors)
                runInfos = preProcessor.PreProcess(runInfos);
            return runInfos;
        }

        private void markAllAsBuilt(RunInfo[] list)
        {
            foreach (var info in list)
                info.Project.Value.HasBeenBuilt();
        }

        private string[] getListOfChangedProjects(ProjectChangeMessage message)
        {
            var projects = new List<string>();
            foreach (var file in message.Files)
                projects.Add(file.FullName);
            return projects.ToArray();
        }
		
		private bool buildAll(RunInfo[] projectList, RunReport runReport)
		{
            if (projectList.Where(x => x.ShouldBeBuilt).Select(x => x).Count() == 0)
                return true;

            Debug.WriteInfo("Running builds");
            if (_configuration.ShouldBuildSolution)
                return buildSolution(projectList, runReport);
            else
                return buildProjects(projectList, runReport);
		}

        private bool buildProjects(RunInfo[] projectList, RunReport runReport)
        {
            var indirectlyBuilt = new List<string>();
            foreach (var file in projectList)
            {
                if (file.ShouldBeBuilt)<commit_msg>Oups, never called the build post processing<commit_after>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoTest.Core.Messaging;
using AutoTest.Core.BuildRunners;
using AutoTest.Core.Configuration;
using AutoTest.Core.Caching;
using AutoTest.Core.Caching.Projects;
using AutoTest.Core.TestRunners;
using System.IO;
using AutoTest.Core.TestRunners.TestRunners;
using Castle.Core.Logging;
using AutoTest.Core.DebugLog;
using AutoTest.Messages;
using System.Threading;

namespace AutoTest.Core.Messaging.MessageConsumers
{
    class ProjectChangeConsumer : IOverridingConsumer<ProjectChangeMessage>
    {
        private bool _isRunning = false;
        private bool _exit = false;
        private IMessageBus _bus;
        private IGenerateBuildList _listGenerator;
        private IConfiguration _configuration;
        private IBuildRunner _buildRunner;
        private ITestRunner[] _testRunners;
		private IDetermineIfAssemblyShouldBeTested _testAssemblyValidator;
		private IOptimizeBuildConfiguration _buildOptimizer;
        private IPreProcessBuildruns[] _preBuildProcessors;
        private IPreProcessTestruns[] _preProcessors;
        private ILocateRemovedTests _removedTestLocator;
        private List<RunInfo> _abortedBuilds = new List<RunInfo>();
        private List<RunInfo> _abortedTestRuns = new List<RunInfo>();

        public bool IsRunning { get { return _isRunning; } }

        public ProjectChangeConsumer(IMessageBus bus, IGenerateBuildList listGenerator, IConfiguration configuration, IBuildRunner buildRunner, ITestRunner[] testRunners, IDetermineIfAssemblyShouldBeTested testAssemblyValidator, IOptimizeBuildConfiguration buildOptimizer, IPreProcessTestruns[] preProcessors, ILocateRemovedTests removedTestLocator, IPreProcessBuildruns[] preBuildProcessors)
        {
            _bus = bus;
            _listGenerator = listGenerator;
            _configuration = configuration;
            _buildRunner = buildRunner;
            _testRunners = testRunners;
			_testAssemblyValidator = testAssemblyValidator;
			_buildOptimizer = buildOptimizer;
            _preProcessors = preProcessors;
            _preBuildProcessors = preBuildProcessors;
            _removedTestLocator = removedTestLocator;
        }

        #region IConsumerOf<ProjectChangeMessage> Members

        public void Consume(ProjectChangeMessage message)
        {
            _isRunning = true;
            var now = DateTime.Now;
            Debug.ConsumingProjectChangeMessage(message);
            _bus.Publish(new RunStartedMessage(message.Files));
            var runReport = execute(message);
            runReport.SetTimeSpent(DateTime.Now.Subtract(now));
            _bus.Publish(new RunFinishedMessage(runReport));
            _exit = false;
            _isRunning = false;
        }

        public void Terminate()
        {
            if (!_isRunning)
                return;
            Debug.WriteDebug("Initiating termination of current run");
            _exit = true;
            while (_isRunning)
                Thread.Sleep(10);
        }

        private RunReport execute(ProjectChangeMessage message)
        {
            var runReport = new RunReport();
            try
            {
                Debug.WriteDebug("Starting project change run");
                var list = getPrioritizedList(message);
                if (!buildAll(list, runReport))
                    return runReport;
                if (_exit)
                {
                    _abortedBuilds.Clear();
                    _abortedBuilds.AddRange(list);
                    return runReport;
                }
                else
                    _abortedBuilds.Clear();
                markAllAsBuilt(list);
                testAll(list, runReport);
            }
            catch (Exception ex)
            {
                var result = new TestRunResults("", "", false, TestRunner.Any, new TestResult[] { new TestResult(TestRunner.Any, TestRunStatus.Failed, "AutoTest.Net internal error", ex.ToString()) });
                _bus.Publish(new TestRunMessage(result));
            }
            return runReport;
        }

        private RunInfo[] getPrioritizedList(ProjectChangeMessage message)
        {
            var projectsAndDependencies = _listGenerator.Generate(getListOfChangedProjects(message));
            var list = _buildOptimizer.AssembleBuildConfiguration(projectsAndDependencies);
            list = preProcessBuildRun(list);
            list = mergeWithAbortedBuilds(list);
            return list;
        }

        private RunInfo[] mergeWithAbortedBuilds(RunInfo[] list)
        {
            return new RunInfoMerger(list).MergeWith(_abortedBuilds).ToArray();
        }

        private RunInfo[] preProcessBuildRun(RunInfo[] runInfos)
        {
            foreach (var preProcessor in _preBuildProcessors)
                runInfos = preProcessor.PreProcess(runInfos);
            return runInfos;
        }

        private RunInfo[] postProcessBuildRuns(RunInfo[] runInfos)
        {
            foreach (var preProcessor in _preBuildProcessors)
                runInfos = preProcessor.PostProcess(runInfos);
            return runInfos;
        }

        private void markAllAsBuilt(RunInfo[] list)
        {
            foreach (var info in list)
                info.Project.Value.HasBeenBuilt();
        }

        private string[] getListOfChangedProjects(ProjectChangeMessage message)
        {
            var projects = new List<string>();
            foreach (var file in message.Files)
                projects.Add(file.FullName);
            return projects.ToArray();
        }
		
		private bool buildAll(RunInfo[] projectList, RunReport runReport)
		{
            if (projectList.Where(x => x.ShouldBeBuilt).Select(x => x).Count() == 0)
                return true;

            Debug.WriteInfo("Running builds");
            bool result = false;
            if (_configuration.ShouldBuildSolution)
                result = buildSolution(projectList, runReport);
            else
                result = buildProjects(projectList, runReport);
            projectList = postProcessBuildRuns(projectList);
            return result;
		}

        private bool buildProjects(RunInfo[] projectList, RunReport runReport)
        {
            var indirectlyBuilt = new List<string>();
            foreach (var file in projectList)
            {
                if (file.ShouldBeBuilt)
{'fraction_non_alphanumeric': 0.0741447891805887, 'fraction_numerical': 0.00047732696897374703, 'mean_word_length': 2.27711157455683, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5045082', 'n_tokens_mistral': 3229, 'n_tokens_neox': 3097, 'n_words': 685}