예제 #1
0
 private static void Fail(string message, IReadOnlyCollection <ExecutableTarget> executableTargets)
 {
     ControlFlow.Fail(new StringBuilder()
                      .AppendLine(message)
                      .AppendLine()
                      .AppendLine(HelpTextService.GetTargetsText(executableTargets)).ToString());
 }
예제 #2
0
        public static void ValidateRequirements(NukeBuild build)
        {
            foreach (var target in build.ExecutionPlan)
            {
                foreach (var requirement in target.Requirements)
                {
                    if (requirement is Expression <Func <bool> > boolExpression)
                    {
                        ControlFlow.Assert(boolExpression.Compile().Invoke(), $"Target '{target.Name}' requires '{requirement.Body}'.");
                    }
                    else if (IsMemberNull(requirement.GetMemberInfo(), build, target))
                    {
                        ControlFlow.Fail($"Target '{target.Name}' requires member '{requirement.GetMemberInfo().Name}' to be not null.");
                    }
                }
            }

            var requiredMembers = InjectionUtility.GetParameterMembers(build.GetType()).Where(x => x.HasCustomAttribute <RequiredAttribute>());

            foreach (var member in requiredMembers)
            {
                if (IsMemberNull(member, build))
                {
                    ControlFlow.Fail($"Member '{member.Name}' is required to be not null.");
                }
            }
        }
예제 #3
0
        public static void ValidateRequirements(NukeBuild build, IReadOnlyCollection <ExecutableTarget> executingTargets)
        {
            foreach (var target in executingTargets)
            {
                foreach (var requirement in target.Requirements)
                {
                    if (requirement is Expression <Func <bool> > boolExpression)
                    {
                        // TODO: same as HasSkippingCondition.GetSkipReason
                        ControlFlow.Assert(boolExpression.Compile().Invoke(), $"Target '{target.Name}' requires '{requirement.Body}'.");
                    }
                    else if (IsMemberNull(requirement.GetMemberInfo(), build, target))
                    {
                        ControlFlow.Fail($"Target '{target.Name}' requires member '{requirement.GetMemberInfo().Name}' to be not null.");
                    }
                }
            }

            var requiredMembers = ValueInjectionUtility.GetInjectionMembers(build.GetType())
                                  .Select(x => x.Member)
                                  .Where(x => x.HasCustomAttribute <RequiredAttribute>());

            foreach (var member in requiredMembers)
            {
                if (IsMemberNull(member, build))
                {
                    ControlFlow.Fail($"Member '{member.Name}' is required to be not null.");
                }
            }
        }
예제 #4
0
        public static IProcess AssertZeroExitCode(
            [AssertionCondition(AssertionConditionType.IS_NOT_NULL)][CanBeNull]
            this IProcess process)
        {
            const string indentation = "   ";

            process.AssertWaitForExit();
            if (process.ExitCode != 0)
            {
                var messageBuilder = new StringBuilder()
                                     .AppendLine($"Process '{Path.GetFileName(process.FileName)}' exited with code {process.ExitCode}.")
                                     .AppendLine("Invocation:")
                                     .AppendLine($"{indentation}{process.FileName.DoubleQuoteIfNeeded()} {process.Arguments}")
                                     .AppendLine("Working directory:")
                                     .AppendLine($"{indentation}{process.WorkingDirectory}");

                var errorOutput = process.Output.Where(x => x.Type == OutputType.Err).ToList();
                if (errorOutput.Count > 0)
                {
                    messageBuilder.AppendLine("Error output:");
                    errorOutput.ForEach(x => messageBuilder.Append(indentation).AppendLine(x.Text));
                }
                else if (Logger.LogLevel <= LogLevel.Trace)
                {
                    messageBuilder.AppendLine("Standard output:");
                    process.Output.ForEach(x => messageBuilder.Append(indentation).AppendLine(x.Text));
                }

                ControlFlow.Fail(messageBuilder.ToString());
            }

            return(process);
        }
예제 #5
0
        private static bool ShouldCopyFile(string sourceFile, string targetFile, FileExistsPolicy policy)
        {
            if (!File.Exists(targetFile))
            {
                return(true);
            }

            switch (policy)
            {
            case FileExistsPolicy.Fail:
                ControlFlow.Fail($"File '{targetFile}' already exists.");
                // ReSharper disable once HeuristicUnreachableCode
                return(false);

            case FileExistsPolicy.Skip:
                return(false);

            case FileExistsPolicy.Overwrite:
                return(true);

            case FileExistsPolicy.OverwriteIfNewer:
                return(File.GetLastWriteTimeUtc(targetFile) < File.GetLastWriteTimeUtc(sourceFile));

            default:
                throw new ArgumentOutOfRangeException(nameof(policy), policy, message: null);
            }
        }
예제 #6
0
        private static void AssertProcess(IProcess process, Xunit2Settings toolSettings)
        {
            process.AssertWaitForExit();
            switch (process.ExitCode)
            {
            case 0:
                break;

            case 1:
                ControlFlow.Fail("One or more of the tests failed.");
                break;

            case 2:
                ControlFlow.Fail(
                    "The help page was shown, either because it was requested, or because the user did not provide any command line arguments.");
                break;

            case 3:
                ControlFlow.Fail("There was a problem with one of the command line options passed to the runner.");
                break;

            case 4:
                ControlFlow.Fail(
                    "There was a problem loading one or more of the test assemblies (for example, if a 64-bit only assembly is run with the 32-bit test runner).");
                break;

            default:
                throw new NotSupportedException();
            }
        }
예제 #7
0
        public object GetCommandLineArgument(string argumentName, Type destinationType, char?separator = null)
        {
            var args  = _commandLineArgumentsProvider.Invoke();
            var index = Array.FindLastIndex(args, x => x.EqualsOrdinalIgnoreCase($"-{argumentName}"));

            if (index == -1)
            {
                return(GetDefaultValue(destinationType));
            }

            var values = args.Skip(index + 1).TakeWhile(x => !x.StartsWith("-")).ToArray();

            ControlFlow.Assert(values.Length == 1 || !separator.HasValue || values.All(x => !x.Contains(separator.Value)),
                               $"Command-line argument '{argumentName}' with value [ {values.JoinComma()} ] cannot be split with separator '{separator}'.");
            values = separator.HasValue && values.Any(x => x.Contains(separator.Value))
                ? values.SingleOrDefault()?.Split(separator.Value) ?? new string[0]
                : values;

            try
            {
                return(ConvertValues(argumentName, values, destinationType));
            }
            catch (Exception ex)
            {
                ControlFlow.Fail(
                    new[] { ex.Message, "Command-line arguments were:" }
                    .Concat(args.Select((x, i) => $"  [{i}] = {x}"))
                    .JoinNewLine());
                // ReSharper disable once HeuristicUnreachableCode
                return(null);
            }
        }
예제 #8
0
        private object ConvertCommandLineArguments(
            string argumentName,
            string[] values,
            Type destinationType,
            string[] commandLineArguments,
            char?separator = null)
        {
            ControlFlow.Assert(values.Length == 1 || !separator.HasValue || values.All(x => !x.Contains(separator.Value)),
                               $"Command-line argument '{argumentName}' with value [ {values.JoinComma()} ] cannot be split with separator '{separator}'.");
            values = separator.HasValue && values.Any(x => x.Contains(separator.Value))
                ? values.SingleOrDefault()?.Split(separator.Value) ?? new string[0]
                : values;

            try
            {
                return(ConvertValues(argumentName, values, destinationType));
            }
            catch (Exception ex)
            {
                ControlFlow.Fail(
                    new[] { ex.Message, "Command-line arguments were:" }
                    .Concat(commandLineArguments.Select((x, i) => $"  [{i}] = {x}"))
                    .JoinNewLine());
                // ReSharper disable once HeuristicUnreachableCode
                return(null);
            }
        }
예제 #9
0
        public static void ManualToolresolvingMeandering()
        {
            string TryGetPathExe(string exe)
            {
                try
                {
                    return(ToolPathResolver.GetPathExecutable(exe));
                }
                catch
                {
                }

                return(string.Empty);
            }

            string TryGetPathToolExe(string exe)
            {
                try
                {
                    return(ToolPathResolver.TryGetEnvironmentExecutable(exe));
                }
                catch
                {
                }

                return(string.Empty);
            }

            //ToolResolver.GetPathTool(exe)

            //ToolResolver.GetPathTool("appveyor");
            //Tool myTool = ToolResolver.GetPathTool(exe)
            void TryAndGetPathEXEAndPrint(string exe)
            {
                Logger.Normal($"Trying to get exe {exe}: '{TryGetPathExe(exe)}'");
            }

            var executables = new[] { "DOES NOT EXIST", "powershell", "bash" };

            //ToolPathResolver.GetPathExecutable - get something on the path
            //vs TryGetEnvironmentExecutable             //ToolPathResolver.TryGetEnvironmentExecutable -- this will get an exe defined by an enviornment variable
            //vs ToolResolver.GetPathTool(exe) - get a tool in the user's path based on
            executables.ForEach(TryAndGetPathEXEAndPrint);
            Logger.Normal($"Comspec is set up by something on windows systems as a standard exe tool, so here is the path {TryGetPathToolExe("ComSpec")}");
            Tool git = ToolResolver.GetPathTool("git");

#pragma warning disable 168
            //just showing that ControlFlow.Fail throws an "Exception" object that is not sub-typed
            try
            {
                Tool doesNotExist = ToolResolver.GetPathTool("DOES NOT EXIST");
            }catch (Exception e) {}
            try
            {
                ControlFlow.Fail("TEST same as trying to get non existent tool with tool resolver");
            }catch (Exception e) {}
#pragma warning restore 168
        }
예제 #10
0
        private static void Handle(string[] args)
        {
            var rootDirectory = FileSystemTasks.FindParentDirectory(
                Directory.GetCurrentDirectory(),
                x => x.GetFiles(NukeBuild.ConfigurationFile).Any());

            var hasCommand = args.FirstOrDefault()?.StartsWithOrdinalIgnoreCase(c_commandPrefix.ToString()) ?? false;

            if (hasCommand)
            {
                var command = args.First().Trim(trimChar: c_commandPrefix);
                if (string.IsNullOrWhiteSpace(command))
                {
                    ControlFlow.Fail($"No command specified. Usage is: nuke {c_commandPrefix}<command> [args]");
                }

                var commandHandler = typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
                                     .SingleOrDefault(x => x.Name.EqualsOrdinalIgnoreCase(command));
                ControlFlow.Assert(commandHandler != null, $"Command '{command}' is not supported.");

                try
                {
                    commandHandler.Invoke(obj: null, parameters: new object[] { rootDirectory, args.Skip(count: 1).ToArray() });
                    return;
                }
                catch (TargetInvocationException ex)
                {
                    ControlFlow.Fail(ex.InnerException.Message);
                }
            }

            var buildScript = rootDirectory != null
                ? new DirectoryInfo(rootDirectory)
                              .EnumerateFiles($"build.{ScriptExtension}", maxDepth: 2)
                              .FirstOrDefault()?.FullName.DoubleQuoteIfNeeded()
                : null;

            if (buildScript == null)
            {
                if (UserConfirms($"Could not find {NukeBuild.ConfigurationFile} file. Do you want to setup a build?"))
                {
                    Setup(rootDirectory, new string[0]);
                }
                return;
            }

            // TODO: docker

            var arguments = args.Select(x => x.DoubleQuoteIfNeeded()).JoinSpace();
            var process   = Process.Start(
                ScriptHost,
                EnvironmentInfo.IsWin
                    ? $"-ExecutionPolicy ByPass -NoProfile -File {buildScript} {arguments}"
                    : $"{buildScript} {arguments}").NotNull();

            process.WaitForExit();
            Environment.Exit(process.ExitCode);
        }
예제 #11
0
        private static List <TargetDefinition> GetUnfilteredExecutingTargets(NukeBuild build, IReadOnlyCollection <TargetDefinition> invokedTargets)
        {
            var vertexDictionary = build.TargetDefinitions.ToDictionary(x => x, x => new Vertex <TargetDefinition>(x));

            foreach (var pair in vertexDictionary)
            {
                pair.Value.Dependencies = pair.Key.TargetDefinitionDependencies.Select(x => vertexDictionary[x]).ToList();
            }

            var graphAsList      = vertexDictionary.Values.ToList();
            var executingTargets = new List <TargetDefinition>();

            while (graphAsList.Any())
            {
                var independents = graphAsList.Where(x => !graphAsList.Any(y => y.Dependencies.Contains(x))).ToList();
                if (EnvironmentInfo.ArgumentSwitch("strict") && independents.Count > 1)
                {
                    ControlFlow.Fail(
                        new[] { "Incomplete target definition order." }
                        .Concat(independents.Select(x => $"  - {x.Value.Name}"))
                        .JoinNewLine());
                }

                var independent = independents.FirstOrDefault();
                if (independent == null)
                {
                    var scc    = new StronglyConnectedComponentFinder <TargetDefinition>();
                    var cycles = scc.DetectCycle(graphAsList)
                                 .Cycles()
                                 .Select(x => string.Join(" -> ", x.Select(y => y.Value.Name)));

                    ControlFlow.Fail(
                        new[] { "Circular dependencies between target definitions." }
                        .Concat(independents.Select(x => $"  - {cycles}"))
                        .JoinNewLine());
                }

                graphAsList.Remove(independent);

                var targetDefinition    = independent.Value;
                var factoryDependencies = executingTargets.SelectMany(x => x.FactoryDependencies);
                var nameDependencies    = executingTargets.SelectMany(x => x.NamedDependencies);
                if (!invokedTargets.Contains(targetDefinition) &&
                    !(factoryDependencies.Contains(targetDefinition.Factory) || nameDependencies.Contains(targetDefinition.Name)))
                {
                    continue;
                }

                executingTargets.Add(targetDefinition);
            }

            executingTargets.Reverse();

            return(executingTargets);
        }
예제 #12
0
    string GetThemeVersion(string packageJsonPath)
    {
        var         json = JsonDocument.Parse(File.ReadAllText(packageJsonPath));
        JsonElement version;

        if (json.RootElement.TryGetProperty("version", out version))
        {
            return(version.GetString());
        }
        ControlFlow.Fail("No version found");
        return("");
    }
예제 #13
0
 private object ConvertValues(string parameterName, IReadOnlyCollection<string> values, Type destinationType)
 {
     try
     {
         return ConvertValues(values, destinationType);
     }
     catch (Exception ex)
     {
         ControlFlow.Fail(new[] { $"Resolving parameter '{parameterName}' failed.", ex.Message }.JoinNewLine());
         return null;
     }
 }
예제 #14
0
        private static List <TargetDefinition> GetSortedList(
            IReadOnlyCollection <TargetDefinition> specifiedTargets,
            IReadOnlyCollection <TargetDefinition> allTargets)
        {
            var vertexDictionary = allTargets.ToDictionary(x => x, x => new Vertex <TargetDefinition>(x));

            foreach (var pair in vertexDictionary)
            {
                pair.Value.Dependencies = pair.Key.TargetDefinitionDependencies.Select(x => vertexDictionary[x]).ToList();
            }

            var graphAsList = vertexDictionary.Values.ToList();
            var result      = new List <TargetDefinition>();

            while (graphAsList.Any())
            {
                var independents = graphAsList.Where(x => !graphAsList.Any(y => y.Dependencies.Contains(x))).ToList();
                if (EnvironmentInfo.ArgumentSwitch("strict") && independents.Count > 1)
                {
                    ControlFlow.Fail(
                        new[] { "Incomplete target definition order." }
                        .Concat(independents.Select(x => $"  - {x.Value.Name}"))
                        .JoinNewLine());
                }

                var independent = independents.FirstOrDefault();
                if (independent == null)
                {
                    var scc    = new StronglyConnectedComponentFinder <TargetDefinition>();
                    var cycles = scc.DetectCycle(graphAsList)
                                 .Cycles()
                                 .Select(x => string.Join(" -> ", x.Select(y => y.Value.Name)));

                    ControlFlow.Fail(
                        new[] { "Circular dependencies between target definitions." }
                        .Concat(independents.Select(x => $"  - {cycles}"))
                        .JoinNewLine());
                }

                graphAsList.Remove(independent);

                var targetDefinition     = independent.Value;
                var executableDependency = result.SelectMany(x => x.TargetDefinitionDependencies).Contains(targetDefinition) &&
                                           !EnvironmentInfo.ArgumentSwitch("nodeps");
                if (specifiedTargets.Contains(targetDefinition) || executableDependency)
                {
                    result.Add(targetDefinition);
                }
            }

            result.Reverse();
            return(result);
        }
예제 #15
0
 private object ConvertValues(string parameterName, IReadOnlyCollection <string> values, Type destinationType)
 {
     try
     {
         return(ConvertValues(values, destinationType));
     }
     catch (Exception ex)
     {
         ControlFlow.Fail(new[] { $"Resolving parameter '{parameterName}' failed.", ex.Message }.JoinNewLine());
         // ReSharper disable once HeuristicUnreachableCode
         return(null);
     }
 }
예제 #16
0
        private static ExecutableTarget GetExecutableTarget(
            string targetName,
            IReadOnlyCollection <ExecutableTarget> executableTargets)
        {
            var executableTarget = executableTargets.SingleOrDefault(x => x.Name.EqualsOrdinalIgnoreCase(targetName));

            if (executableTarget == null)
            {
                ControlFlow.Fail($"Target with name '{targetName}' is not available.");
            }

            return(executableTarget);
        }
예제 #17
0
        private static T GetTaskResult <T> ([NotNull] Task <T> task)
        {
            try
            {
                task.Wait();
            }
            catch (Exception ex)
            {
                ControlFlow.Fail($"Could not retrieve KeyVault value. {ex.Message}");
            }

            return(task.Result);
        }
예제 #18
0
 private object Convert(string value, Type destinationType)
 {
     try
     {
         var typeConverter = TypeDescriptor.GetConverter(destinationType);
         return typeConverter.ConvertFromInvariantString(value);
     }
     catch
     {
         ControlFlow.Fail($"Value '{value}' could not be converted to '{GetName(destinationType)}'.");
         return null;
     }
 }
예제 #19
0
 private object Convert(string value, Type destinationType)
 {
     try
     {
         var typeConverter = TypeDescriptor.GetConverter(destinationType);
         return(typeConverter.ConvertFromInvariantString(value));
     }
     catch
     {
         ControlFlow.Fail($"Value '{value}' could not be converted to '{GetName(destinationType)}'.");
         // ReSharper disable once HeuristicUnreachableCode
         return(null);
     }
 }
예제 #20
0
        private static IReadOnlyCollection <ExecutableTarget> GetExecutionPlanInternal(
            IReadOnlyCollection <ExecutableTarget> executableTargets,
            ICollection <ExecutableTarget> invokedTargets)
        {
            var vertexDictionary = GetVertexDictionary(executableTargets);
            var graphAsList      = vertexDictionary.Values.ToList();
            var executingTargets = new List <ExecutableTarget>();

            while (graphAsList.Any())
            {
                var independents = graphAsList.Where(x => !graphAsList.Any(y => y.Dependencies.Contains(x))).ToList();
                if (EnvironmentInfo.ArgumentSwitch("strict") && independents.Count > 1)
                {
                    ControlFlow.Fail(
                        new[] { "Incomplete target definition order." }
                        .Concat(independents.Select(x => $"  - {x.Value.Name}"))
                        .JoinNewLine());
                }

                var independent = independents.FirstOrDefault();
                if (independent == null)
                {
                    var scc    = new StronglyConnectedComponentFinder <ExecutableTarget>();
                    var cycles = scc.DetectCycle(graphAsList)
                                 .Cycles()
                                 .Select(x => string.Join(" -> ", x.Select(y => y.Value.Name)));

                    ControlFlow.Fail(
                        new[] { "Circular dependencies between target definitions." }
                        .Concat(independents.Select(x => $"  - {cycles}"))
                        .JoinNewLine());
                }

                graphAsList.Remove(independent);

                var executableTarget = independent.Value;
                if (!invokedTargets.Contains(executableTarget) &&
                    !executingTargets.SelectMany(x => x.ExecutionDependencies).Contains(executableTarget))
                {
                    continue;
                }

                executingTargets.Add(executableTarget);
            }

            executingTargets.Reverse();

            return(executingTargets);
        }
예제 #21
0
파일: Program.cs 프로젝트: olsh/nuke
        private static int Handle(string[] args, [CanBeNull] AbsolutePath rootDirectory, [CanBeNull] AbsolutePath buildScript)
        {
            var hasCommand = args.FirstOrDefault()?.StartsWithOrdinalIgnoreCase(CommandPrefix.ToString()) ?? false;

            if (hasCommand)
            {
                var command = args.First().Trim(CommandPrefix).Replace("-", string.Empty);
                if (string.IsNullOrWhiteSpace(command))
                {
                    ControlFlow.Fail($"No command specified. Usage is: nuke {CommandPrefix}<command> [args]");
                }

                var availableCommands = typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.Public);
                var commandHandler    = availableCommands
                                        .SingleOrDefault(x => x.Name.EqualsOrdinalIgnoreCase(command));
                ControlFlow.Assert(commandHandler != null,
                                   new[]
                {
                    $"Command '{command}' is not supported.",
                    "Available commands are:"
                }
                                   .Concat(availableCommands.Select(x => $"  - {x.Name}").OrderBy(x => x)).JoinNewLine());
                // TODO: add assertions about return type and parameters

                var commandArguments = new object[] { args.Skip(count: 1).ToArray(), rootDirectory, buildScript };
                return((int)commandHandler.Invoke(obj: null, commandArguments));
            }

            if (rootDirectory == null || buildScript == null)
            {
                var missingItem = rootDirectory == null
                    ? $"{Constants.NukeDirectoryName} directory/file"
                    : "build.ps1/sh files";

                return(UserConfirms($"Could not find {missingItem}. Do you want to setup a build?")
                    ? Setup(new string[0], rootDirectory, buildScript: null)
                    : 0);
            }

            // TODO: docker

            var arguments = args.Select(x => x.DoubleQuoteIfNeeded()).JoinSpace();
            var process   = Build(buildScript, arguments);

            process.WaitForExit();
            return(process.ExitCode);
        }
예제 #22
0
        public object GetEnvironmentVariable(string variableName, Type destinationType, char? separator = null)
        {
            var variables = _environmentVariablesProvider.Invoke();
            var value = variables.Contains(variableName) ? (string) variables[variableName] : null;
            if (value == null)
                return GetDefaultValue(destinationType);

            try
            {
                return ConvertValues(variableName, separator.HasValue ? value.Split(separator.Value) : new[] { value }, destinationType);
            }
            catch (Exception ex)
            {
                ControlFlow.Fail(new[] { ex.Message, "Environment variable was:", value }.JoinNewLine());
                return null;
            }
        }
예제 #23
0
    private async Task InstallPlatformAsync(string platformVersion)
    {
        if (NeedToInstallPlatform(platformVersion))
        {
            Logger.Info($"Installing platform {platformVersion}");
            var platformRelease = await GithubManager.GetPlatformRelease(platformVersion);

            var platformAssetUrl = platformRelease.Assets.FirstOrDefault().BrowserDownloadUrl;
            var platformZip      = TemporaryDirectory / "platform.zip";
            if (string.IsNullOrEmpty(platformAssetUrl))
            {
                ControlFlow.Fail($"No platform's assets found with tag {platformVersion}");
            }
            await HttpTasks.HttpDownloadFileAsync(platformAssetUrl, platformZip);

            CompressionTasks.Uncompress(platformZip, RootDirectory);
        }
    }
예제 #24
0
        public object GetEnvironmentVariable(string variableName, Type destinationType, char?separator)
        {
            if (!Variables.TryGetValue(variableName, out var value))
            {
                return(GetDefaultValue(destinationType));
            }

            try
            {
                return(ConvertValues(variableName, separator.HasValue ? value.Split(separator.Value) : new[] { value }, destinationType));
            }
            catch (Exception ex)
            {
                ControlFlow.Fail(new[] { ex.Message, "Environment variable was:", value }.JoinNewLine());
                // ReSharper disable once HeuristicUnreachableCode
                return(null);
            }
        }
예제 #25
0
        public static string Decrypt(string cipherText, byte[] password, string name)
        {
            try
            {
                var cipherBytes = Convert.FromBase64String(cipherText.Remove(startIndex: 0, count: 3));

                using var ms = new MemoryStream();
                using var cs = GetCryptoStream(ms, password, x => x.CreateDecryptor());
                cs.Write(cipherBytes, offset: 0, cipherBytes.Length);
                cs.Close();

                return(Encoding.UTF8.GetString(ms.ToArray()));
            }
            catch
            {
                ControlFlow.Fail($"Could not decrypt '{name}' with provided password.");
                return(null);
            }
        }
예제 #26
0
 public static void Compress(string directory, string archiveFile, Predicate <FileInfo> filter = null)
 {
     if (archiveFile.EndsWithAny(".zip"))
     {
         CompressZip(directory, archiveFile, filter);
     }
     else if (archiveFile.EndsWithAny(".tar.gz", ".tgz"))
     {
         CompressTarGZip(directory, archiveFile, filter);
     }
     else if (archiveFile.EndsWithAny(".tar.bz2", ".tbz2", ".tbz"))
     {
         CompressTarBZip2(directory, archiveFile, filter);
     }
     else
     {
         ControlFlow.Fail($"Unknown archive extension for archive '{Path.GetFileName(archiveFile)}'");
     }
 }
예제 #27
0
 public static void Uncompress(string archiveFile, string directory)
 {
     if (archiveFile.EndsWithAny(".zip"))
     {
         UncompressZip(archiveFile, directory);
     }
     else if (archiveFile.EndsWithAny(".tar.gz", ".tgz"))
     {
         UncompressTarGZip(archiveFile, directory);
     }
     else if (archiveFile.EndsWithAny(".tar.bz2", ".tbz2", ".tbz"))
     {
         UncompressTarBZip2(archiveFile, directory);
     }
     else
     {
         ControlFlow.Fail($"Unknown archive extension for archive '{Path.GetFileName(archiveFile)}'");
     }
 }
예제 #28
0
        private static int Handle(string[] args, [CanBeNull] string rootDirectory, [CanBeNull] string buildScript)
        {
            var hasCommand = args.FirstOrDefault()?.StartsWithOrdinalIgnoreCase(c_commandPrefix.ToString()) ?? false;

            if (hasCommand)
            {
                var command = args.First().Trim(c_commandPrefix);
                if (string.IsNullOrWhiteSpace(command))
                {
                    ControlFlow.Fail($"No command specified. Usage is: nuke {c_commandPrefix}<command> [args]");
                }

                var commandHandler = typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
                                     .SingleOrDefault(x => x.Name.EqualsOrdinalIgnoreCase(command));
                ControlFlow.Assert(commandHandler != null, $"Command '{command}' is not supported.");
                // TODO: add assertions about return type and parameters

                var commandArguments = new object[] { args.Skip(count: 1).ToArray(), rootDirectory, buildScript };
                return((int)commandHandler.Invoke(obj: null, commandArguments));
            }

            if (rootDirectory == null || buildScript == null)
            {
                var missingFile = rootDirectory == null
                    ? Constants.ConfigurationFileName
                    : "build.ps1/sh";

                return(UserConfirms($"Could not find {missingFile} file. Do you want to setup a build?")
                    ? Setup(new string[0], rootDirectory, buildScript: null)
                    : 0);
            }

            // TODO: docker

            Logger.Normal($"NUKE Global Tool {typeof(Program).Assembly.GetInformationalText()}");

            var arguments = args.Select(x => x.DoubleQuoteIfNeeded()).JoinSpace();
            var process   = Build(buildScript, arguments);

            process.WaitForExit();
            return(process.ExitCode);
        }
예제 #29
0
        private static void Handle(string[] args)
        {
            var hasCommand = args.FirstOrDefault()?.StartsWithOrdinalIgnoreCase("!") ?? false;

            if (hasCommand)
            {
                var command = args.First().Trim(trimChar: '!');
                if (string.IsNullOrWhiteSpace(command))
                {
                    ControlFlow.Fail("No command specified. Usage is: nuke !<command> [args]");
                }

                var arguments = args.Skip(count: 1).JoinSpace();
                if (command.EqualsOrdinalIgnoreCase("setup"))
                {
                    Setup(arguments);
                    return;
                }

                ControlFlow.Fail($"Command '{command}' is not supported.");
            }

            var currentDirectory = new DirectoryInfo(Directory.GetCurrentDirectory());
            var rootDirectory    = FileSystemTasks.FindParentDirectory(currentDirectory, x => x.GetFiles(NukeBuild.ConfigurationFile).Any());
            var buildScript      = rootDirectory?
                                   .EnumerateFiles($"build.{ScriptExtension}", maxDepth: 2)
                                   .FirstOrDefault()?.FullName;

            if (buildScript == null)
            {
                if (UserConfirms($"Could not find {NukeBuild.ConfigurationFile} file. Do you want to setup a build?"))
                {
                    Setup();
                }
                return;
            }

            // TODO: docker
            RunScript(buildScript, args.Select(x => x.DoubleQuoteIfNeeded()).JoinSpace());
        }
예제 #30
0
        private async Task <bool> DownloadExternalFile(string file, int timeout)
        {
            try
            {
                var lines = File.ReadAllLines(file).Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
                ControlFlow.Assert(lines.Count == 1, $"External file '{file}' must contain single URI.");

                var uriString = lines.FirstOrDefault();
                if (!Uri.TryCreate(uriString, UriKind.Absolute, out var uri))
                {
                    ControlFlow.Fail($"Could not parse '{uriString}' from external file '{file}'.");
                }

                var outputFile = file.Substring(0, file.Length - 4);
                await HttpTasks.HttpDownloadFileAsync(uri.AbsolutePath, outputFile);

                BuildEngine.LogMessageEvent(new BuildMessageEventArgs(
                                                $"Successfully downloaded external file '{outputFile}' from '{uri}'.",
                                                helpKeyword: null,
                                                senderName: typeof(ExternalFilesTask).FullName,
                                                importance: MessageImportance.Normal));

                return(true);
            }
            catch (Exception exception)
            {
                BuildEngine.LogErrorEvent(new BuildErrorEventArgs(
                                              subcategory: "Build",
                                              code: null,
                                              file: file,
                                              lineNumber: 0,
                                              columnNumber: 0,
                                              endLineNumber: 0,
                                              endColumnNumber: 0,
                                              message: exception.Message,
                                              helpKeyword: null,
                                              senderName: typeof(ExternalFilesTask).FullName));
                return(false);
            }
        }