Example #1
0
        private void ConfigureDefaultProps(ITaskSession taskSession)
        {
            taskSession.SetBuildVersion(new Version(1, 0, 0, 0));
            taskSession.SetDotnetExecutable(ExecuteDotnetTask.FindDotnetExecutable());

            var        isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            OSPlatform platform;

            if (!isWindows)
            {
                var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
                platform = isLinux ? OSPlatform.Linux : OSPlatform.OSX;
            }
            else
            {
                platform = OSPlatform.Windows;
            }

            taskSession.SetOSPlatform(platform);
            taskSession.SetNodeExecutablePath(IOExtensions.GetNodePath());
            taskSession.SetProfileFolder(IOExtensions.GetUserProfileFolder());
            taskSession.SetNpmPath(IOExtensions.GetNpmPath());
            taskSession.SetBuildDir("build");
            taskSession.SetOutputDir("output");
            taskSession.SetProductRootDir(".");

            if (isWindows)
            {
                // do windows specific tasks
            }
        }
Example #2
0
        public static void LogTargetDurations(ITaskSession session)
        {
            if (session.TargetTree == null)
            {
                return;
            }

            session.WriteInfo(String.Empty);

            SortedList <string, ITarget> sortedTargets = new SortedList <string, ITarget>();

            foreach (ITarget target in session.TargetTree.EnumerateExecutedTargets())
            {
                sortedTargets.Add(target.TargetName, target);
            }

            foreach (ITarget target in sortedTargets.Values)
            {
                if (target.TaskStopwatch.ElapsedTicks > 0)
                {
                    session.WriteInfo(
                        "Target {0} took {1} s",
                        target.TargetName,
                        (int)target.TaskStopwatch.Elapsed.TotalSeconds);
                }
            }
        }
Example #3
0
        private void ConfigureDefaultDotNetTargets(ITaskSession taskSession)
        {
            var loadSolution = taskSession.CreateTarget("load.solution")
                               .SetDescription("Load & analyze VS solution")
                               .AddTask(x => x.LoadSolutionTask())
                               .SetAsHidden();

            var cleanOutput = taskSession.CreateTarget("clean.output")
                              .SetDescription("Clean solution outputs")
                              .AddTask(x => x.CleanOutputTask())
                              .DependsOn(loadSolution);

            var prepareBuildDir = taskSession.CreateTarget("prepare.build.dir")
                                  .SetDescription("Prepare the build directory")
                                  .Do(TargetPrepareBuildDir)
                                  .SetAsHidden();

            var fetchBuildVersion = taskSession.CreateTarget("fetch.build.version")
                                    .SetDescription("Fetch the build version")
                                    .SetAsHidden();

            var generateCommonAssInfo = taskSession.CreateTarget("generate.commonassinfo")
                                        .SetDescription("Generate CommonAssemblyInfo.cs file")
                                        .DependsOn(fetchBuildVersion)
                                        .AddTask(x => x.GenerateCommonAssemblyInfoTask());

            taskSession.CreateTarget("compile")
            .SetDescription("Compile the VS solution")
            .AddTask(x => x.CompileSolutionTask())
            .DependsOn(prepareBuildDir, cleanOutput, generateCommonAssInfo);
        }
 public UpdateCenterController(IGitHubClient client, ITaskFactory taskFactory, ITaskSession taskSession, IHostingEnvironment hostingEnvironment, IApplicationLifetime applicationLifetime)
 {
     _client              = client;
     _taskFactory         = taskFactory;
     _taskSession         = taskSession;
     _hostingEnvironment  = hostingEnvironment;
     _applicationLifetime = applicationLifetime;
 }
        public int Run(ITaskSession taskSession)
        {
            try
            {
                BeforeBuildExecution(taskSession);
                RunBuild(taskSession);
                taskSession.Complete();
                AfterBuildExecution(taskSession);
                return(0);
            }
            catch (TargetNotFoundException e)
            {
                OnBuildFailed(taskSession, e);
                AfterBuildExecution(taskSession);
                if (taskSession.Args.RethrowOnException)
                {
                    throw;
                }

                taskSession.LogInfo(e.Message);
                return(3);
            }
            catch (WebApiException e)
            {
                OnBuildFailed(taskSession, e);
                AfterBuildExecution(taskSession);
                if (taskSession.Args.RethrowOnException)
                {
                    throw;
                }

                return(1);
            }
            catch (FlubuException e)
            {
                OnBuildFailed(taskSession, e);
                AfterBuildExecution(taskSession);
                if (taskSession.Args.RethrowOnException)
                {
                    throw;
                }

                taskSession.LogInfo(e.Message);
                return(1);
            }
            catch (Exception e)
            {
                OnBuildFailed(taskSession, e);
                AfterBuildExecution(taskSession);
                if (taskSession.Args.RethrowOnException)
                {
                    throw;
                }

                taskSession.LogInfo(e.ToString());
                return(2);
            }
        }
Example #6
0
 private void AssertAllTargetDependenciesWereExecuted(ITaskSession taskSession)
 {
     if (taskSession.Args.TargetsToExecute != null && taskSession.Args.TargetsToExecute.Count > 1)
     {
         if (taskSession.Args.TargetsToExecute.Count - 1 != taskSession.TargetTree.DependenciesExecutedCount)
         {
             throw new TaskExecutionException("Wrong number of target dependencies were runned.", 3);
         }
     }
 }
 public CommandExecutor(
     CommandArguments args,
     IScriptLoader scriptLoader,
     ITaskSession taskSession,
     ILogger <CommandExecutor> log)
 {
     _args         = args;
     _scriptLoader = scriptLoader;
     _taskSession  = taskSession;
     _log          = log;
 }
Example #8
0
        public int Run(ITaskSession taskSession)
        {
            try
            {
                RunBuild(taskSession);
                taskSession.Complete();
                return(0);
            }
            catch (TargetNotFoundException e)
            {
                taskSession.OnFinish();
                if (taskSession.Args.RethrowOnException)
                {
                    throw;
                }

                taskSession.LogInfo(e.Message);
                return(3);
            }
            catch (WebApiException)
            {
                taskSession.OnFinish();
                if (taskSession.Args.RethrowOnException)
                {
                    throw;
                }

                return(1);
            }
            catch (FlubuException e)
            {
                taskSession.OnFinish();
                if (taskSession.Args.RethrowOnException)
                {
                    throw;
                }

                taskSession.LogInfo(e.Message);
                return(1);
            }
            catch (Exception ex)
            {
                taskSession.OnFinish();
                if (taskSession.Args.RethrowOnException)
                {
                    throw;
                }

                taskSession.LogInfo(ex.ToString());
                return(2);
            }
        }
        public static void SetPropertiesFromScriptArg(IBuildScript buildScript, ITaskSession taskSession)
        {
            var buildScriptType        = buildScript.GetType();
            IList <PropertyInfo> props = new List <PropertyInfo>(buildScriptType.GetProperties());

            foreach (var property in props)
            {
                var attributes = property.GetCustomAttributes <FromArgAttribute>(false).ToList();
                foreach (var fromArgAttribute in attributes)
                {
                    if (!taskSession.ScriptArgs.ContainsKey(fromArgAttribute.ArgKey))
                    {
                        continue;
                    }

                    if (property.PropertyType.GetTypeInfo().IsGenericType)
                    {
                        var propertyGenericTypeDefinition = property.PropertyType.GetGenericTypeDefinition();
                        if (propertyGenericTypeDefinition == typeof(IList <>) ||
                            propertyGenericTypeDefinition == typeof(List <>) ||
                            propertyGenericTypeDefinition == typeof(IEnumerable <>))
                        {
                            var list = taskSession.ScriptArgs[fromArgAttribute.ArgKey].Split(fromArgAttribute.Seperator)
                                       .ToList();
                            property.SetValue(buildScript, list);
                        }
                    }
                    else
                    {
                        property.SetValue(buildScript, MethodParameterModifier.ParseValueByType(taskSession.ScriptArgs[fromArgAttribute.ArgKey], property.PropertyType));
                    }
                }

                if (taskSession.ScriptArgs.ContainsKey(property.Name))
                {
                    if (property.PropertyType.GetTypeInfo().IsGenericType)
                    {
                        var propertyGenericTypeDefinition = property.PropertyType.GetGenericTypeDefinition();
                        if (propertyGenericTypeDefinition == typeof(IList <>) ||
                            propertyGenericTypeDefinition == typeof(List <>) ||
                            propertyGenericTypeDefinition == typeof(IEnumerable <>))
                        {
                            property.SetValue(buildScript, taskSession.ScriptArgs[property.Name].Split(',').ToList());
                        }
                    }
                    else
                    {
                        property.SetValue(buildScript, MethodParameterModifier.ParseValueByType(taskSession.ScriptArgs[property.Name], property.PropertyType));
                    }
                }
            }
        }
Example #10
0
        public ScriptPropertiesSetterTests()
        {
            var sp = new ServiceCollection().AddTransient <ITarget, TargetFluentInterface>()
                     .AddTransient <ICoreTaskFluentInterface, CoreTaskFluentInterface>()
                     .AddTransient <ITaskFluentInterface, TaskFluentInterface>()
                     .AddTransient <ILinuxTaskFluentInterface, LinuxTaskFluentInterface>()
                     .AddTransient <IIisTaskFluentInterface, IisTaskFluentInterface>()
                     .AddTransient <IWebApiFluentInterface, WebApiFluentInterface>()
                     .AddSingleton <IHttpClientFactory, HttpClientFactory>()
                     .BuildServiceProvider();

            _taskSession = new TaskSession(new Mock <ILogger <TaskSession> >().Object, new TargetTree(null, null), new CommandArguments(), new Mock <ITaskFactory>().Object, new FluentInterfaceFactory(sp), null, null);
        }
Example #11
0
        private void ConfigureDefaultTargets(ITaskSession taskSession)
        {
            var defaultTagets = taskSession.Properties.GetDefaultTargets();

            switch (defaultTagets)
            {
            case DefaultTargets.Dotnet:
            {
                ConfigureDefaultDotNetTargets(taskSession);
                break;
            }
            }
        }
Example #12
0
 public CommandExecutor(
     CommandArguments args,
     IScriptLoader scriptLoader,
     ITaskSession taskSession,
     IFileWrapper file,
     IPathWrapper path,
     ILogger <CommandExecutor> log)
 {
     _args         = args;
     _scriptLoader = scriptLoader;
     _taskSession  = taskSession;
     _file         = file;
     _path         = path;
     _log          = log;
 }
Example #13
0
        public static void OnBuildFinished(ITaskSession session)
        {
            session.ResetDepth();

            LogTargetDurations(session);

            session.WriteInfo(String.Empty);

            if (session.HasFailed)
            {
                session.WriteError("BUILD FAILED");
            }
            else
            {
                session.WriteInfo("BUILD SUCCESSFUL");
            }

            TimeSpan buildDuration = session.BuildStopwatch.Elapsed;

            session.WriteInfo("Build finish time: {0:g}", DateTime.Now);
            session.WriteInfo(
                "Build duration: {0:D2}:{1:D2}:{2:D2} ({3:d} seconds)",
                buildDuration.Hours,
                buildDuration.Minutes,
                buildDuration.Seconds,
                (int)buildDuration.TotalSeconds);

            bool speechDisabled = session.Properties.Get(BuildProps.SpeechDisabled, false);

            if (session.IsInteractive && !speechDisabled)
            {
                using (SpeechSynthesizer speech = new SpeechSynthesizer())
                {
                    PromptBuilder builder = new PromptBuilder(new CultureInfo("en-US"));
                    builder.StartStyle(new PromptStyle(PromptRate.Slow));
                    builder.StartStyle(new PromptStyle(PromptVolume.Loud));
                    builder.StartSentence(new CultureInfo("en-US"));
                    builder.AppendText("Build " + (session.HasFailed ? "failed." : "successful!"));
                    builder.EndSentence();
                    builder.EndStyle();
                    builder.EndStyle();
                    speech.Speak(builder);
                }
            }

            //Beeper.Beep(session.HasFailed ? MessageBeepType.Error : MessageBeepType.Ok);
        }
Example #14
0
        public void ConfigureTargetWithExtensionTasks()
        {
            ITaskSession session = _sp.GetRequiredService <ITaskSession>();

            SimpleBuildScript bs = new SimpleBuildScript();

            bs.Run(session);

            Assert.True(session.TargetTree.HasAllTargets(new List <string>()
            {
                "extensions"
            }, out _));

            Target t = (Target)session.TargetTree.GetTarget("extensions");

            Assert.Equal(2, t.Tasks.Count);
        }
Example #15
0
        public void ConfigureTargetWithIisTasks()
        {
            ITaskSession session = _sp.GetRequiredService <ITaskSession>();

            SimpleBuildScript bs = new SimpleBuildScript();

            bs.Run(session);

            Assert.True(session.TargetTree.HasAllTargets(new List <string>()
            {
                "IIS"
            }, out _));

            Target t = (Target)session.TargetTree.GetTarget("IIS");

            Assert.Equal(2, t.TasksGroups.Count);
            Assert.Empty(t.Dependencies);
        }
Example #16
0
        public void ConfigureTargetWithExtensionTasksAndDependsOn()
        {
            ITaskSession session = _sp.GetRequiredService <ITaskSession>();

            SimpleBuildScript bs = new SimpleBuildScript();

            bs.Run(session);

            Assert.True(session.TargetTree.HasAllTargets(new List <string>()
            {
                "package"
            }, out _));

            Target t = (Target)session.TargetTree.GetTarget("package");

            Assert.Equal(4, t.Tasks.Count);

            Assert.Equal(2, t.Dependencies.Count);
            Assert.Equal("init", t.Dependencies.First().Key);
            Assert.Equal("restore", t.Dependencies.Last().Key);
        }
Example #17
0
        public void ConfigureSimpleTarget()
        {
            ITaskSession session = _sp.GetRequiredService <ITaskSession>();

            SimpleBuildScript bs = new SimpleBuildScript();

            bs.Run(session);

            Assert.True(session.TargetTree.HasAllTargets(new List <string>()
            {
                "test"
            }, out _));
            Assert.True(session.TargetTree.HasAllTargets(new List <string>()
            {
                "test1"
            }, out _));

            ITargetInternal t  = session.TargetTree.GetTarget("test");
            ITargetInternal t1 = session.TargetTree.GetTarget("test1");

            Assert.Equal(t.TargetName, t1.Dependencies.FirstOrDefault().Key);
        }
        public static List <string> GetPropertiesKeys(IBuildScript buildScript, ITaskSession taskSession)
        {
            var buildScriptType        = buildScript.GetType();
            IList <PropertyInfo> props = new List <PropertyInfo>(buildScriptType.GetProperties());
            List <string>        keys  = new List <string>();

            foreach (var property in props)
            {
                var attributes = property.GetCustomAttributes <FromArgAttribute>(false).ToList();
                if (attributes.Count == 0)
                {
                    keys.Add(property.Name);
                }
                else
                {
                    foreach (var fromArgAttribute in attributes)
                    {
                        keys.Add(fromArgAttribute.ArgKey);
                    }
                }
            }

            return(keys);
        }
Example #19
0
        private void RunBuild(ITaskSession taskSession)
        {
            ConfigureDefaultProps(taskSession);

            ConfigureBuildProperties(taskSession);

            ConfigureDefaultTargets(taskSession);

            ScriptProperties.SetPropertiesFromScriptArg(this, taskSession);

            TargetCreator.CreateTargetFromMethodAttributes(this, taskSession);

            ConfigureTargets(taskSession);

            var targetsInfo = ParseCmdLineArgs(taskSession, taskSession.TargetTree);

            if (targetsInfo.targetsToRun == null || targetsInfo.targetsToRun.Count == 0)
            {
                var defaultTargets = taskSession.TargetTree.DefaultTargets;
                targetsInfo.targetsToRun = new List <string>();
                if (defaultTargets != null && defaultTargets.Count != 0)
                {
                    foreach (var defaultTarget in defaultTargets)
                    {
                        targetsInfo.targetsToRun.Add(defaultTarget.TargetName);
                    }
                }
                else
                {
                    targetsInfo.targetsToRun.Add("help");
                }
            }

            taskSession.Start(s =>
            {
                foreach (var target in s.TargetTree.EnumerateExecutedTargets())
                {
                    var targt = target as Target;

                    if (targt?.TaskStopwatch.ElapsedTicks > 0)
                    {
                        s.LogInfo($"Target {target.TargetName} took {(int)targt.TaskStopwatch.Elapsed.TotalSeconds} s");
                    }
                }

                if (taskSession.Args.DryRun)
                {
                    s.LogInfo("DRY RUN PERFORMED");
                }
                else if (!targetsInfo.unknownTarget)
                {
                    s.LogInfo(s.HasFailed ? "BUILD FAILED" : "BUILD SUCCESSFUL");
                }
            });

            //// specific target help
            if (targetsInfo.targetsToRun.Count == 2 && targetsInfo.targetsToRun[1].Equals("help", StringComparison.OrdinalIgnoreCase))
            {
                taskSession.TargetTree.RunTargetHelp(taskSession, targetsInfo.targetsToRun[0]);
                return;
            }

            if (targetsInfo.targetsToRun.Count == 1 || !taskSession.Args.ExecuteTargetsInParallel)
            {
                if (targetsInfo.targetsToRun[0].Equals("help", StringComparison.OrdinalIgnoreCase))
                {
                    taskSession.TargetTree.ScriptArgsHelp = ScriptProperties.GetPropertiesHelp(this);
                }

                BeforeTargetExecution(taskSession);
                foreach (var targetToRun in targetsInfo.targetsToRun)
                {
                    taskSession.TargetTree.RunTarget(taskSession, targetToRun);
                }

                AfterTargetExecution(taskSession);
            }
            else
            {
                taskSession.LogInfo("Running target's in parallel.");
                var tasks = new List <Task>();
                BeforeTargetExecution(taskSession);
                foreach (var targetToRun in targetsInfo.targetsToRun)
                {
                    tasks.Add(taskSession.TargetTree.RunTargetAsync(taskSession, targetToRun));
                }

                Task.WaitAll(tasks.ToArray());
                AfterTargetExecution(taskSession);
            }

            if (targetsInfo.unknownTarget)
            {
                throw new TargetNotFoundException($"Target {string.Join(" and ", targetsInfo.notFoundTargets)} not found.");
            }

            AssertAllTargetDependenciesWereExecuted(taskSession);
        }
Example #20
0
 public ReportsController(IHostingEnvironment hostingEnvironment, ITaskFactory taskFactory, ITaskSession taskSession)
 {
     _hostingEnvironment = hostingEnvironment;
     _taskFactory        = taskFactory;
     _taskSession        = taskSession;
 }
Example #21
0
 protected virtual void OnBuildFailed(ITaskSession session, Exception ex)
 {
 }
Example #22
0
        /// <summary>
        /// Searches methods with Target attribute in specified type and creates targets.
        /// </summary>
        /// <param name="buildScriptType"></param>
        /// <param name="taskSession"></param>
        public static void CreateTargetFromMethodAttributes(IBuildScript buildScript, ITaskSession taskSession)
        {
            #if !NETSTANDARD1_6
            var buildScriptType = buildScript.GetType();
            var methods         = buildScriptType.GetRuntimeMethods().Where(x => x.DeclaringType == buildScriptType).ToList();
            foreach (var methodInfo in methods)
            {
                var attributes = methodInfo.GetCustomAttributes <TargetAttribute>(false).ToList();

                if (attributes.Count == 0)
                {
                    continue;
                }

                foreach (var attribute in attributes)
                {
                    var methodParameters = methodInfo.GetParameters().ToList();

                    if (methodParameters.Count == 0)
                    {
                        throw new ScriptException($"Failed to create target '{attribute.TargetName}'. Method '{methodInfo.Name}' must have atleast one parameter which must be of type '{nameof(ITarget)}'");
                    }

                    if (methodParameters[0].ParameterType != typeof(ITarget))
                    {
                        throw new ScriptException($"Failed to create target '{attribute.TargetName}' first parameter in method '{methodInfo.Name}' must be of type '{nameof(ITarget)}'");
                    }

                    var target = taskSession.CreateTarget(attribute.TargetName);
                    var attributeParamaters = new List <object>()
                    {
                        target
                    };

                    attributeParamaters.AddRange(attribute.MethodParameters);

                    if (methodParameters.Count != attributeParamaters.Count)
                    {
                        throw new ScriptException($"Failed to create target '{attribute.TargetName}'. Method parameters {methodInfo.Name} do not match count of attribute parametrs.");
                    }

                    for (int i = 0; i < methodParameters.Count; i++)
                    {
                        if (i != 0 && methodParameters[i].ParameterType != attributeParamaters[i].GetType())
                        {
                            throw new ScriptException($"Failed to create target '{attribute.TargetName}'. Attribute parameter {i + 1.ToString()} does not match '{methodInfo.Name}' method parameter {i + 1.ToString()}. Expected {methodParameters[i].ParameterType} Actual: {attributeParamaters[i].GetType()}");
                        }
                    }

                    var parameterInfos = methodInfo.GetParameters();
                    for (int i = 0; i < parameterInfos.Length; i++)
                    {
                        ParameterInfo parameter       = parameterInfos[i];
                        var           paramAttributes = parameter.GetCustomAttributes <FromArgAttribute>(false).ToList();
                        foreach (var fromArgAttribute in paramAttributes)
                        {
                            if (!taskSession.Args.ScriptArguments.ContainsKey(fromArgAttribute.ArgKey))
                            {
                                continue;
                            }

                            attributeParamaters[i] = MethodParameterModifier.ParseValueByType(taskSession.Args.ScriptArguments[fromArgAttribute.ArgKey], parameter.ParameterType);
                        }

                        if (taskSession.Args.ScriptArguments.ContainsKey(parameter.Name))
                        {
                            object parsedValue = MethodParameterModifier.ParseValueByType(taskSession.Args.ScriptArguments[parameter.Name], parameter.ParameterType);
                            attributeParamaters[i] = parsedValue;
                        }
                    }

                    methodInfo.Invoke(buildScript, attributeParamaters.ToArray());
                }
            }
#endif
        }
Example #23
0
 protected virtual void AfterBuildExecution(ITaskSession session)
 {
     session.TargetTree.LogBuildSummary(session);
 }
Example #24
0
        private void RunBuild(ITaskSession taskSession)
        {
            ConfigureDefaultProps(taskSession);

            ConfigureBuildProperties(taskSession);

            ConfigureDefaultTargets(taskSession);

            ScriptProperties.SetPropertiesFromScriptArg(this, taskSession);

            TargetCreator.CreateTargetFromMethodAttributes(this, taskSession);

            ConfigureTargets(taskSession);

            (List <string> targetsToRun, bool unknownTarget, List <string> notFoundTargets)targetsInfo =
                default((List <string> targetsToRun, bool unknownTarget, List <string> notFoundTargets));
            bool runInTerminalMode;
            ConsoleHintedInput inputReader = null;

            if (!taskSession.Args.InteractiveMode)
            {
                runInTerminalMode = false;

                targetsInfo = ParseCmdLineArgs(taskSession.Args.MainCommands, taskSession.TargetTree);
                taskSession.UnknownTarget = targetsInfo.unknownTarget;
                if (targetsInfo.targetsToRun == null || targetsInfo.targetsToRun.Count == 0)
                {
                    var defaultTargets = taskSession.TargetTree.DefaultTargets;
                    targetsInfo.targetsToRun = new List <string>();
                    if (defaultTargets != null && defaultTargets.Count != 0)
                    {
                        foreach (var defaultTarget in defaultTargets)
                        {
                            targetsInfo.targetsToRun.Add(defaultTarget.TargetName);
                        }
                    }
                    else
                    {
                        targetsInfo.targetsToRun.Add("help");
                    }
                }
            }
            else
            {
                runInTerminalMode = true;
                var source       = new Dictionary <char, IReadOnlyCollection <string> >();
                var propertyKeys = ScriptProperties.GetPropertiesKeys(this, taskSession);
                propertyKeys.Add("-parallel");
                propertyKeys.Add("-dryrun");
                propertyKeys.Add("-noColor");
                source.Add('-', propertyKeys);

                inputReader = new ConsoleHintedInput(taskSession.TargetTree.GetTargetNames().ToList(), source);
                taskSession.TargetTree.RunTarget(taskSession, "help.onlyTargets");
                taskSession.LogInfo(" ");
            }

            do
            {
                if (runInTerminalMode)
                {
                    var commandLine            = inputReader.ReadHintedLine();
                    var app                    = new CommandLineApplication(false);
                    IFlubuCommandParser parser = new FlubuCommandParser(app, null);
                    var args                   = parser.Parse(commandLine.Split(' ')
                                                              .Where(x => !string.IsNullOrWhiteSpace(x))
                                                              .Select(x => x.Trim()).ToArray());
                    targetsInfo            = ParseCmdLineArgs(args.MainCommands, taskSession.TargetTree);
                    taskSession.ScriptArgs = args.ScriptArguments;
                    ScriptProperties.SetPropertiesFromScriptArg(this, taskSession);

                    if (args.MainCommands[0].Equals("exit", StringComparison.OrdinalIgnoreCase) ||
                        args.MainCommands[0].Equals("quit", StringComparison.OrdinalIgnoreCase) ||
                        args.MainCommands[0].Equals("x", StringComparison.OrdinalIgnoreCase) ||
                        args.MainCommands[0].Equals("q", StringComparison.OrdinalIgnoreCase))
                    {
                        break;
                    }
                }

                taskSession.Start();

                //// specific target help
                if (targetsInfo.targetsToRun.Count == 2 &&
                    targetsInfo.targetsToRun[1].Equals("help", StringComparison.OrdinalIgnoreCase))
                {
                    taskSession.TargetTree.RunTargetHelp(taskSession, targetsInfo.targetsToRun[0]);
                    return;
                }

                if (targetsInfo.targetsToRun.Count == 1 || !taskSession.Args.ExecuteTargetsInParallel)
                {
                    if (targetsInfo.targetsToRun[0].Equals("help", StringComparison.OrdinalIgnoreCase))
                    {
                        taskSession.TargetTree.ScriptArgsHelp = ScriptProperties.GetPropertiesHelp(this);
                    }

                    BeforeTargetExecution(taskSession);
                    foreach (var targetToRun in targetsInfo.targetsToRun)
                    {
                        taskSession.TargetTree.RunTarget(taskSession, targetToRun);
                    }

                    AfterTargetExecution(taskSession);
                }
                else
                {
                    taskSession.LogInfo("Running target's in parallel.");
                    var tasks = new List <Task>();
                    BeforeTargetExecution(taskSession);
                    foreach (var targetToRun in targetsInfo.targetsToRun)
                    {
                        tasks.Add(taskSession.TargetTree.RunTargetAsync(taskSession, targetToRun, true));
                    }

                    Task.WaitAll(tasks.ToArray());
                    AfterTargetExecution(taskSession);
                }

                if (targetsInfo.unknownTarget)
                {
                    var targetNotFoundMsg = $"Target {string.Join(" and ", targetsInfo.notFoundTargets)} not found.";
                    if (taskSession.Args.InteractiveMode)
                    {
                        taskSession.LogInfo(targetNotFoundMsg);
                    }
                    else
                    {
                        throw new TargetNotFoundException(targetNotFoundMsg);
                    }
                }

                AssertAllTargetDependenciesWereExecuted(taskSession);
            }while (runInTerminalMode);
        }
        private void RunBuild(ITaskSession taskSession)
        {
            ConfigureDefaultProps(taskSession);

            ConfigureBuildProperties(taskSession);

            ConfigureDefaultTargets(taskSession);

            ScriptProperties.SetPropertiesFromScriptArg(this, taskSession);

            TargetCreator.CreateTargetFromMethodAttributes(this, taskSession);

            ConfigureTargets(taskSession);

            var targetsInfo = ParseCmdLineArgs(taskSession, taskSession.TargetTree);

            taskSession.UnknownTarget = targetsInfo.unknownTarget;
            if (targetsInfo.targetsToRun == null || targetsInfo.targetsToRun.Count == 0)
            {
                var defaultTargets = taskSession.TargetTree.DefaultTargets;
                targetsInfo.targetsToRun = new List <string>();
                if (defaultTargets != null && defaultTargets.Count != 0)
                {
                    foreach (var defaultTarget in defaultTargets)
                    {
                        targetsInfo.targetsToRun.Add(defaultTarget.TargetName);
                    }
                }
                else
                {
                    targetsInfo.targetsToRun.Add("help");
                }
            }

            taskSession.Start();

            //// specific target help
            if (targetsInfo.targetsToRun.Count == 2 &&
                targetsInfo.targetsToRun[1].Equals("help", StringComparison.OrdinalIgnoreCase))
            {
                taskSession.TargetTree.RunTargetHelp(taskSession, targetsInfo.targetsToRun[0]);
                return;
            }

            if (targetsInfo.targetsToRun.Count == 1 || !taskSession.Args.ExecuteTargetsInParallel)
            {
                if (targetsInfo.targetsToRun[0].Equals("help", StringComparison.OrdinalIgnoreCase))
                {
                    taskSession.TargetTree.ScriptArgsHelp = ScriptProperties.GetPropertiesHelp(this);
                }

                BeforeTargetExecution(taskSession);
                foreach (var targetToRun in targetsInfo.targetsToRun)
                {
                    taskSession.TargetTree.RunTarget(taskSession, targetToRun);
                }

                AfterTargetExecution(taskSession);
            }
            else
            {
                taskSession.LogInfo("Running target's in parallel.");
                var tasks = new List <Task>();
                BeforeTargetExecution(taskSession);
                foreach (var targetToRun in targetsInfo.targetsToRun)
                {
                    tasks.Add(taskSession.TargetTree.RunTargetAsync(taskSession, targetToRun));
                }

                Task.WaitAll(tasks.ToArray());
                AfterTargetExecution(taskSession);
            }

            if (targetsInfo.unknownTarget)
            {
                throw new TargetNotFoundException(
                          $"Target {string.Join(" and ", targetsInfo.notFoundTargets)} not found.");
            }

            AssertAllTargetDependenciesWereExecuted(taskSession);
        }
Example #26
0
 private static void OnBuildFinished(ITaskSession session)
 {
 }
Example #27
0
        public int Run(ITaskSession taskSession)
        {
            try
            {
                BeforeBuildExecution(taskSession);
                RunBuild(taskSession);
                taskSession.Complete();
                AfterBuildExecution(taskSession);
                return(0);
            }
            catch (TargetNotFoundException e)
            {
                taskSession.ResetDepth();
                OnBuildFailed(taskSession, e);
                AfterBuildExecution(taskSession);
                if (taskSession.Args.RethrowOnException)
                {
                    throw;
                }

                taskSession.LogError(e.Message);
                return(3);
            }
            catch (WebApiException e)
            {
                taskSession.ResetDepth();
                OnBuildFailed(taskSession, e);
                AfterBuildExecution(taskSession);
                if (taskSession.Args.RethrowOnException)
                {
                    throw;
                }

                return(1);
            }
            catch (FlubuException e)
            {
                taskSession.ResetDepth();
                OnBuildFailed(taskSession, e);

                if (!taskSession.Args.RethrowOnException)
                {
#if !NETSTANDARD1_6
                    taskSession.LogError($"ERROR: {e.Message}", Color.Red);
#else
                    taskSession.LogError($"error: {e.Message}");
#endif
                }

                AfterBuildExecution(taskSession);
                if (taskSession.Args.RethrowOnException)
                {
                    throw;
                }

                return(1);
            }
            catch (Exception e)
            {
                taskSession.ResetDepth();
                OnBuildFailed(taskSession, e);

                if (!taskSession.Args.RethrowOnException)
                {
#if !NETSTANDARD1_6
                    taskSession.LogError($"ERROR: {e}", Color.Red);
#else
                    taskSession.LogError($"error: {e}");
#endif
                }

                AfterBuildExecution(taskSession);
                if (taskSession.Args.RethrowOnException)
                {
                    throw;
                }

                return(2);
            }
        }