Ejemplo n.º 1
0
        /// <summary>
        /// Obtains information from a local git repository. Auto-injection can be utilized via <see cref="GitRepositoryAttribute"/>.
        /// </summary>
        public static GitRepository FromLocalDirectory(string directory)
        {
            var rootDirectory = FileSystemTasks.FindParentDirectory(directory, x => x.GetDirectories(".git").Any());

            ControlFlow.Assert(rootDirectory != null, $"Could not find git directory for '{directory}'.");
            var gitDirectory = Path.Combine(rootDirectory, ".git");

            var head   = GetHead(gitDirectory);
            var branch = ((Host.Instance as IBuildServer)?.Branch ?? GetHeadIfAttached(head))?.TrimStart("refs/heads/").TrimStart("origin/");
            var commit = (Host.Instance as IBuildServer)?.Commit ?? GetCommitFromHead(gitDirectory, head);
            var tags   = GetTagsFromCommit(gitDirectory, commit);

            var(remoteName, remoteBranch)       = GetRemoteNameAndBranch(gitDirectory, branch);
            var(protocol, endpoint, identifier) = GetRemoteConnectionFromConfig(gitDirectory, remoteName ?? FallbackRemoteName);

            return(new GitRepository(
                       protocol,
                       endpoint,
                       identifier,
                       branch,
                       rootDirectory,
                       head,
                       commit,
                       tags,
                       remoteName,
                       remoteBranch));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Obtains information from a local git repository. Auto-injection can be utilized via <see cref="GitRepositoryAttribute"/>.
        /// </summary>
        public static GitRepository FromLocalDirectory(string directory)
        {
            var rootDirectory = FileSystemTasks.FindParentDirectory(directory, x => x.GetDirectories(".git").Any());
            var gitDirectory  = Path.Combine(rootDirectory.NotNull($"No parent Git directory for '{directory}'"), ".git");

            var head   = GetHead(gitDirectory);
            var branch = (GetBranchFromCI() ?? GetHeadIfAttached(head))?.TrimStart("refs/heads/").TrimStart("origin/");
            var commit = GetCommitFromCI() ?? GetCommitFromHead(gitDirectory, head);
            var tags   = GetTagsFromCommit(gitDirectory, commit);

            var(remoteName, remoteBranch)       = GetRemoteNameAndBranch(gitDirectory, branch);
            var(protocol, endpoint, identifier) = GetRemoteConnectionFromConfig(gitDirectory, remoteName ?? FallbackRemoteName);

            return(new GitRepository(
                       protocol,
                       endpoint,
                       identifier,
                       branch,
                       rootDirectory,
                       head,
                       commit,
                       tags,
                       remoteName,
                       remoteBranch));
        }
Ejemplo n.º 3
0
        private static PathConstruction.AbsolutePath GetRootDirectory()
        {
            var parameterValue = ParameterService.Instance.GetParameter(() => RootDirectory);

            if (parameterValue != null)
            {
                return(parameterValue);
            }

            if (ParameterService.Instance.GetParameter <bool>(() => RootDirectory))
            {
                return((PathConstruction.AbsolutePath)EnvironmentInfo.WorkingDirectory);
            }

            var rootDirectory = (PathConstruction.AbsolutePath)FileSystemTasks.FindParentDirectory(
                EnvironmentInfo.WorkingDirectory,
                x => x.GetFiles(ConfigurationFileName).Any());

            ControlFlow.Assert(rootDirectory != null,
                               new[]
            {
                $"Could not locate '{ConfigurationFileName}' file while walking up from '{EnvironmentInfo.WorkingDirectory}'.",
                "Either create the file to mark the root directory, or use the --root parameter."
            }.JoinNewLine());

            return(rootDirectory);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Obtains information from a local git repository. Auto-injection can be utilized via <see cref="GitRepositoryAttribute"/>.
        /// </summary>
        public static GitRepository FromLocalDirectory(string directory, string branch = null, string remote = "origin")
        {
            var rootDirectory = FileSystemTasks.FindParentDirectory(directory, x => x.GetDirectories(".git").Any());

            ControlFlow.Assert(rootDirectory != null, $"Could not find root directory for '{directory}'.");
            var gitDirectory = Path.Combine(rootDirectory, ".git");

            var headFile = Path.Combine(gitDirectory, "HEAD");

            ControlFlow.Assert(File.Exists(headFile), $"File.Exists({headFile})");
            var headFileContent = File.ReadAllLines(headFile);
            var head            = headFileContent.First();
            var branchMatch     = Regex.Match(head, "^ref: refs/heads/(?<branch>.*)");

            var configFile        = Path.Combine(gitDirectory, "config");
            var configFileContent = File.ReadAllLines(configFile);
            var url = configFileContent
                      .Select(x => x.Trim())
                      .SkipWhile(x => x != $"[remote \"{remote}\"]")
                      .Skip(count: 1)
                      .TakeWhile(x => !x.StartsWith("["))
                      .SingleOrDefault(x => x.StartsWithOrdinalIgnoreCase("url = "))
                      ?.Split('=')[1];

            ControlFlow.Assert(url != null, $"Could not parse remote URL for '{remote}'.");

            var(endpoint, identifier) = ParseUrl(url);

            return(new GitRepository(
                       endpoint,
                       identifier,
                       rootDirectory,
                       head,
                       branch ?? (branchMatch.Success ? branchMatch.Groups["branch"].Value : null)));
        }
Ejemplo n.º 5
0
        public static int Setup(string[] args, [CanBeNull] AbsolutePath rootDirectory, [CanBeNull] AbsolutePath buildScript)
        {
            PrintInfo();
            Logging.Configure();
            Telemetry.SetupBuild();

            AnsiConsole.WriteLine();
            AnsiConsole.MarkupLine("[bold]Let's setup a new build![/]");
            AnsiConsole.WriteLine();

            #region Basic

            var nukeLatestReleaseVersion    = NuGetPackageResolver.GetLatestPackageVersion(NukeCommonPackageId, includePrereleases: false);
            var nukeLatestPrereleaseVersion = NuGetPackageResolver.GetLatestPackageVersion(NukeCommonPackageId, includePrereleases: true);
            var nukeLatestLocalVersion      = NuGetPackageResolver.GetGlobalInstalledPackage(NukeCommonPackageId, version: null, packagesConfigFile: null)
                                              ?.Version.ToString();

            if (rootDirectory == null)
            {
                var rootDirectoryItems = new[] { ".git", ".svn" };
                rootDirectory = (AbsolutePath)FileSystemTasks.FindParentDirectory(
                    WorkingDirectory,
                    x => rootDirectoryItems.Any(y => x.GetFileSystemInfos(y, SearchOption.TopDirectoryOnly).Any()));
            }

            if (rootDirectory == null)
            {
                Host.Warning("Could not find root directory. Falling back to working directory ...");
                rootDirectory = WorkingDirectory;
            }
            ShowInput("deciduous_tree", "Root directory", rootDirectory);

            var targetPlatform = !GetParameter <bool>("boot")
                ? PLATFORM_NETCORE
                : PromptForChoice("What runtime should be used?",
                                  (PLATFORM_NETCORE, ".NET Core SDK"),
                                  (PLATFORM_NETFX, ".NET Framework/Mono"));

            var targetFramework = targetPlatform == PLATFORM_NETFX
                ? FRAMEWORK_NETFX
                : FRAMEWORK_NETCORE;

            var projectFormat = targetPlatform == PLATFORM_NETCORE
                ? FORMAT_SDK
                : PromptForChoice("What project format should be used?",
                                  (FORMAT_SDK, "SDK-based Format: requires .NET Core SDK"),
                                  (FORMAT_LEGACY, "Legacy Format: supported by all MSBuild/Mono versions"));

            ShowInput("nut_and_bolt", "Build runtime", $"{(targetPlatform == PLATFORM_NETCORE ? ".NET" : ".NET Framework")} ({targetFramework})");

            var buildProjectName = PromptForInput("How should the project be named?", "_build");
            ClearPreviousLine();
            ShowInput("bookmark", "Build project name", buildProjectName);

            var buildProjectRelativeDirectory = PromptForInput("Where should the project be located?", "./build");
            ClearPreviousLine();
            ShowInput("round_pushpin", "Build project location", buildProjectRelativeDirectory);

            var nukeVersion = PromptForChoice("Which Nuke.Common version should be used?",
                                              new[]
Ejemplo n.º 6
0
 internal static AbsolutePath TryGetRootDirectoryFrom(string startDirectory, bool includeLegacy = true)
 {
     return((AbsolutePath)FileSystemTasks.FindParentDirectory(
                startDirectory,
                predicate: x =>
                x.GetDirectories(NukeDirectoryName).Any() ||
                includeLegacy && x.GetFiles(NukeFileName).Any()));
 }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
0
        private static void Setup([CanBeNull] string rootDirectory, string[] args)
        {
            #region Basic

            var nukeLatestLocalVersion      = NuGetPackageResolver.GetGlobalInstalledPackage("Nuke.Common", version: null)?.Version.ToString();
            var nukeLatestReleaseVersion    = NuGetPackageResolver.GetLatestPackageVersion("Nuke.Common", includePrereleases: false);
            var nukeLatestPrereleaseVersion = NuGetPackageResolver.GetLatestPackageVersion("Nuke.Common", includePrereleases: true);

            if (rootDirectory == null)
            {
                var rootDirectoryItems = new[] { ".git", ".svn" };
                rootDirectory = FileSystemTasks.FindParentDirectory(
                    EnvironmentInfo.WorkingDirectory,
                    x => rootDirectoryItems.Any(y => x.GetFileSystemInfos(y, SearchOption.TopDirectoryOnly).Any()));
            }

            if (rootDirectory == null)
            {
                Logger.Warn("Could not find root directory. Falling back to working directory.");
                rootDirectory = EnvironmentInfo.WorkingDirectory;
            }

            var solutionFile = ConsoleHelper.PromptForChoice(
                "Which solution should be the default?",
                options: new DirectoryInfo(rootDirectory)
                .EnumerateFiles("*", SearchOption.AllDirectories)
                .Where(x => x.FullName.EndsWithOrdinalIgnoreCase(".sln"))
                .OrderByDescending(x => x.FullName)
                .Select(x => (x, GetRelativePath(rootDirectory, x.FullName)))
                .Concat((null, "None")).ToArray())?.FullName;
            var solutionDirectory = solutionFile != null?Path.GetDirectoryName(solutionFile) : null;

            var targetPlatform = ConsoleHelper.PromptForChoice("How should the build project be bootstrapped?",
                                                               (PLATFORM_NETCORE, ".NET Core SDK"),
                                                               (PLATFORM_NETFX, ".NET Framework/Mono"));

            var targetFramework = targetPlatform == PLATFORM_NETFX
                ? FRAMEWORK_NET461
                : ConsoleHelper.PromptForChoice("What target framework should be used?",
                                                (FRAMEWORK_NETCOREAPP2, FRAMEWORK_NETCOREAPP2),
                                                (FRAMEWORK_NET461, FRAMEWORK_NET461));

            var projectFormat = targetPlatform == PLATFORM_NETCORE
                ? FORMAT_SDK
                : ConsoleHelper.PromptForChoice("What format should the build project use?",
                                                (FORMAT_SDK, "SDK-based Format: requires .NET Core SDK"),
                                                (FORMAT_LEGACY, "Legacy Format: supported by all MSBuild/Mono versions"));

            var nukeVersion = ConsoleHelper.PromptForChoice("Which NUKE version should be used?",
                                                            new[]
Ejemplo n.º 9
0
        protected FileSystemDependentTest(ITestOutputHelper testOutputHelper)
        {
            TestOutputHelper = testOutputHelper;

            TestName = ((ITest)testOutputHelper.GetType()
                        .GetField("test", BindingFlags.NonPublic | BindingFlags.Instance).NotNull()
                        .GetValue(testOutputHelper)).TestCase.TestMethod.Method.Name;

            ExecutionDirectory   = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).NotNull();
            RootDirectory        = FileSystemTasks.FindParentDirectory(ExecutionDirectory, x => x.GetFiles(".nuke").Any());
            TestProjectDirectory = FileSystemTasks.FindParentDirectory(ExecutionDirectory, x => x.GetFiles("*.csproj").Any());
            TestTempDirectory    = Path.Combine(ExecutionDirectory, "temp", $"{GetType().Name}.{TestName}");

            FileSystemTasks.EnsureCleanDirectory(TestTempDirectory);
        }
Ejemplo n.º 10
0
        /// <inheritdoc />
        public override object?GetValue(MemberInfo member, object instance)
        {
            var rootDirectory = FileSystemTasks.FindParentDirectory(
                NukeBuild.RootDirectory,
                x => x.GetDirectories(".git").Any()
                );

            if (rootDirectory != null)
            {
                return(base.GetValue(member, instance));
            }

            Logger.Warn("No git repository found, GitRepository will not be available.");
            return(null);
        }
Ejemplo n.º 11
0
        private static int Setup(string[] args, [CanBeNull] string rootDirectory, [CanBeNull] string buildScript)
        {
            PrintInfo();

            #region Basic

            var nukeLatestReleaseVersion    = NuGetPackageResolver.GetLatestPackageVersion("Nuke.Common", includePrereleases: false);
            var nukeLatestPrereleaseVersion = NuGetPackageResolver.GetLatestPackageVersion("Nuke.Common", includePrereleases: true);
            var nukeLatestLocalVersion      = NuGetPackageResolver.GetGlobalInstalledPackage("Nuke.Common", version: null, packagesConfigFile: null)
                                              ?.Version.ToString();

            if (rootDirectory == null)
            {
                var rootDirectoryItems = new[] { ".git", ".svn" };
                rootDirectory = FileSystemTasks.FindParentDirectory(
                    WorkingDirectory,
                    x => rootDirectoryItems.Any(y => x.GetFileSystemInfos(y, SearchOption.TopDirectoryOnly).Any()));
            }

            if (rootDirectory == null)
            {
                Logger.Warn("Could not find root directory. Falling back to working directory.");
                rootDirectory = WorkingDirectory;
            }

            var buildProjectName   = PromptForInput("How should the build project be named?", "_build");
            var buildDirectoryName = PromptForInput("Where should the build project be located?", "./build");

            var targetPlatform = !GetParameter <bool>("boot")
                ? PLATFORM_NETCORE
                : PromptForChoice("What bootstrapping method should be used?",
                                  (PLATFORM_NETCORE, ".NET Core SDK"),
                                  (PLATFORM_NETFX, ".NET Framework/Mono"));

            var targetFramework = targetPlatform == PLATFORM_NETFX
                ? FRAMEWORK_NETFX
                : FRAMEWORK_NETCORE;

            var projectFormat = targetPlatform == PLATFORM_NETCORE
                ? FORMAT_SDK
                : PromptForChoice("What project format should be used?",
                                  (FORMAT_SDK, "SDK-based Format: requires .NET Core SDK"),
                                  (FORMAT_LEGACY, "Legacy Format: supported by all MSBuild/Mono versions"));

            var nukeVersion = PromptForChoice("Which NUKE version should be used?",
                                              new[]
Ejemplo n.º 12
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());
        }
Ejemplo n.º 13
0
        private static int Main(string[] args)
        {
            try
            {
                var rootDirectory = FileSystemTasks.FindParentDirectory(
                    Directory.GetCurrentDirectory(),
                    x => x.GetFiles(NukeBuild.ConfigurationFileName).Any());

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

                return(Handle(args, rootDirectory, buildScript));
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
                return(1);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Obtains information from a local git repository. Auto-injection can be utilized via <see cref="GitRepositoryAttribute"/>.
        /// </summary>
        public static GitRepository FromLocalDirectory(string directory, string branch = null, string remote = null)
        {
            var rootDirectory = FileSystemTasks.FindParentDirectory(directory, x => x.GetDirectories(".git").Any());

            ControlFlow.Assert(rootDirectory != null, $"Could not find git directory for '{directory}'.");
            var gitDirectory = Path.Combine(rootDirectory, ".git");

            var(protocol, endpoint, identifier) = GetRemoteFromConfig(gitDirectory, remote ?? "origin");
            var head   = GetHead(gitDirectory);
            var commit = GetCommitFromCI() ?? GetCommitFromHead(gitDirectory, head);
            var tags   = GetTagsFromCommit(gitDirectory, commit);

            return(new GitRepository(
                       protocol,
                       endpoint,
                       identifier,
                       branch ?? (GetBranchFromCI() ?? GetBranchFromHead(head)).TrimStart("refs/heads/").TrimStart("origin/"),
                       rootDirectory,
                       head,
                       commit,
                       tags));
        }
Ejemplo n.º 15
0
 internal static PathConstruction.AbsolutePath TryGetRootDirectoryFrom(string startDirectory)
 {
     return((PathConstruction.AbsolutePath)FileSystemTasks.FindParentDirectory(
                startDirectory,
                predicate: x => x.GetFiles(ConfigurationFileName).Any()));
 }