Ejemplo n.º 1
0
        public void OnBuildCreated(NukeBuild build, IReadOnlyCollection <ExecutableTarget> executableTargets)
        {
            if (BuildServerConfigurationGeneration.IsActive)
            {
                return;
            }

            var commit = GitRepository.GetCommitFromCI();

            if (commit == null)
            {
                return;
            }

            var lastLine = GitTasks.Git($"show -s --format=%B {commit}", logInvocation: false, logOutput: false)
                           .Select(x => x.Text)
                           .Where(x => !x.IsNullOrEmpty())
                           .LastOrDefault();

            if (!lastLine?.StartsWithOrdinalIgnoreCase(Prefix) ?? true)
            {
                return;
            }

            var arguments = EnvironmentInfo.ParseCommandLineArguments(lastLine.Substring(Prefix.Length).TrimStart());

            ParameterService.Instance.ArgumentsFromCommitMessageService = new ParameterService(() => arguments, () => throw new NotSupportedException());
        }
Ejemplo n.º 2
0
        public void OnBuildCreated(NukeBuild build, IReadOnlyCollection <ExecutableTarget> executableTargets)
        {
            var accessToken         = EnvironmentInfo.GetParameter <string>(nameof(EnterpriseAccessToken));
            var enterpriseDirectory = ((Build)build).ExternalRepositoriesDirectory / "enterprise";

            if (accessToken.IsNullOrEmpty())
            {
                var enterpriseProjectDirectory = enterpriseDirectory / "src" / "Nuke.Enterprise";
                FileSystemTasks.EnsureExistingDirectory(enterpriseProjectDirectory);
                File.WriteAllText(
                    enterpriseProjectDirectory / "Nuke.Enterprise.csproj",
                    @"
<Project Sdk=""Microsoft.NET.Sdk"">

  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
    <IsPackable>False</IsPackable>
  </PropertyGroup>

</Project>
");
                return;
            }

            var url = $"https://{accessToken}@github.com/nuke-build/enterprise";

            GitTasks.Git($"clone {url} {enterpriseDirectory}", logOutput: false, logInvocation: false);

            Logger.Info("Restarting with Nuke.Enterprise integration...");
            var arguments = Environment.CommandLine.Split(' ').Skip(1).JoinSpace();
            var process   = Process.Start(DotNetTasks.DotNetPath, $"run --project {BuildProjectFile} -- {arguments}");

            process.NotNull().WaitForExit();
            Environment.Exit(process.ExitCode);
        }
Ejemplo n.º 3
0
        public override object GetStaticValue()
        {
            // TODO: https://github.com/GitTools/GitVersion/issues/1097
            if (EnvironmentInfo.IsUnix && DisableOnUnix)
            {
                Logger.Warn($"{nameof(GitVersion)} is disabled on UNIX environment.");
                return(null);
            }

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

            var version = GetVersion();
            var tag     = GetTag(version);

            if (tag != null)
            {
                GitTasks.Git($"tag {tag}");
                version = GetVersion();
            }

            return(Value = version);
        }
Ejemplo n.º 4
0
    void GitCloneAndBuild(ExplorationTestDescription testDescription)
    {
        if (Framework != null && !testDescription.IsFrameworkSupported(Framework))
        {
            throw new InvalidOperationException($"The framework '{Framework}' is not listed in the project's target frameworks of {testDescription.Name}");
        }

        var depth      = testDescription.IsGitShallowCloneSupported ? "--depth 1" : "";
        var submodules = testDescription.IsGitSubmodulesRequired ? "--recurse-submodules" : "";
        var source     = ExplorationTestCloneLatest ? testDescription.GitRepositoryUrl : $"-b {testDescription.GitRepositoryTag} {testDescription.GitRepositoryUrl}";
        var target     = $"{ExplorationTestsDirectory}/{testDescription.Name}";

        var cloneCommand = $"clone -q -c advice.detachedHead=false {depth} {submodules} {source} {target}";

        GitTasks.Git(cloneCommand);

        var projectPath = $"{ExplorationTestsDirectory}/{testDescription.Name}/{testDescription.PathToUnitTestProject}";

        if (!Directory.Exists(projectPath))
        {
            throw new DirectoryNotFoundException($"Test path '{projectPath}' doesn't exist.");
        }

        DotNetBuild(
            x => x
            .SetProjectFile(projectPath)
            .SetConfiguration(BuildConfiguration)
            .SetProcessArgumentConfigurator(arguments => arguments.Add("-consoleLoggerParameters:ErrorsOnly"))
            .When(Framework != null, settings => settings.SetFramework(Framework))
            );
    }
Ejemplo n.º 5
0
    static bool ShouldBuildRelease()
    {
        const string flag = "[release skip]";

        var message = GitTasks.Git("log -1 --pretty=format:%B", logOutput: false)
                      .Select(output => output.Text)
                      .Aggregate((s, s1) => $"{s}\n{s1}");

        return(!message.Contains(flag));
    }
Ejemplo n.º 6
0
 public static bool CheckBranchExists(string branchName)
 {
     try
     {
         return(GitTasks.Git($"show-ref --heads {branchName.DoubleQuoteIfNeeded()}").Count > 0);
     }
     catch (ProcessException pe)
     {
         return(false);
     }
 }
Ejemplo n.º 7
0
 public static void TagAnnotated(string tagName, string branchOrCommitRef = null)
 {
     if (string.IsNullOrEmpty(branchOrCommitRef))
     {
         GitTasks.Git($"tag -a {tagName.DoubleQuoteIfNeeded()}");
     }
     else
     {
         GitTasks.Git($"tag -a {tagName.DoubleQuoteIfNeeded()} {branchOrCommitRef.DoubleQuoteIfNeeded()}");
     }
 }
Ejemplo n.º 8
0
    public static void Reset(ResetType type = ResetType.Default, string id = null)
    {
        var resetTypeStr = type switch
        {
            ResetType.Default => "",
            ResetType.Soft => "--soft",
            ResetType.Hard => "--hard",
            _ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
        };

        GitTasks.Git($"reset {resetTypeStr} {id.DoubleQuoteIfNeeded()}");
    }
Ejemplo n.º 9
0
 public static void CheckoutBranchOrCreateNewFrom(string branch, string branchToCreateFrom)
 {
     try
     {
         GitTasks.Git($"checkout -B {branch} --track refs/remotes/origin/{branch}");
     }
     catch (Exception)
     {
         // remote branch does not exist
         GitTasks.Git($"checkout -B {branch} --no-track refs/remotes/origin/{branchToCreateFrom}");
     }
 }
Ejemplo n.º 10
0
    public static BuildVersionInfo CalculateVersionFromGit(int buildNumber)
    {
        var desc   = GitTasks.Git("describe --tags --long --abbrev=40 --match=v*", logInvocation: false, logOutput: false).Single().Text;
        var result = Regex.Match(desc,
                                 @"^v(?<maj>\d+)\.(?<min>\d+)(\.(?<rev>\d+))?(?<pre>-\w+\d*)?-(?<num>\d+)-g(?<sha>[a-z0-9]+)$",
                                 RegexOptions.IgnoreCase)
                     .Groups;

        string GetMatch(string name) => result[name].Value;

        var major               = int.Parse(GetMatch("maj"));
        var minor               = int.Parse(GetMatch("min"));
        var optRevision         = GetMatch("rev");
        var optPreReleaseSuffix = GetMatch("pre");
        var commitsNum          = int.Parse(GetMatch("num"));
        var sha = GetMatch("sha");

        var revision        = optRevision == "" ? 0 : int.Parse(optRevision);
        var assemblyVersion = $"{major}.{minor}.{revision}.0";
        var fileVersion     = $"{major}.{minor}.{revision}.{buildNumber}";

        // If number of commits since last tag is greater than zero, we append another identifier with number of commits.
        // The produced version is larger than the last tag version.
        // If we are on a tag, we use version specified modification.
        var nugetVersion = commitsNum switch
        {
            0 => $"{major}.{minor}.{revision}{optPreReleaseSuffix}",
            var num => $"{major}.{minor}.{revision}{optPreReleaseSuffix}.{num}",
        };

        var infoVersion = commitsNum switch
        {
            0 => nugetVersion,
            _ => $"{nugetVersion}-{sha}"
        };

        return(new BuildVersionInfo
        {
            AssemblyVersion = assemblyVersion,
            FileVersion = fileVersion,
            InfoVersion = infoVersion,
            NuGetVersion = nugetVersion
        });
    }
}
Ejemplo n.º 11
0
        public static int Trigger(string[] args, [CanBeNull] AbsolutePath rootDirectory, [CanBeNull] AbsolutePath buildScript)
        {
            var repository = GitRepository.FromLocalDirectory(rootDirectory.NotNull()).NotNull("No Git repository");

            Assert.NotNull(repository.Branch, "Git repository must not be detached");
            Assert.NotEmpty(args);

            try
            {
                var messageBody = args.JoinSpace();
                GitTasks.Git($"commit --allow-empty -m {messageBody.DoubleQuote()}");
                GitTasks.Git($"push {repository.RemoteName} {repository.Head}:{repository.RemoteBranch}");
                return(0);
            }
            catch
            {
                return(1);
            }
        }
Ejemplo n.º 12
0
        public static int Trigger(string[] args, [CanBeNull] AbsolutePath rootDirectory, [CanBeNull] AbsolutePath buildScript)
        {
            ControlFlow.Assert(rootDirectory != null, "No root directory found.");
            var repository = GitRepository.FromLocalDirectory(rootDirectory).NotNull("No Git repository found.");

            ControlFlow.Assert(repository.Branch != null, "Git repository must not be detached.");
            ControlFlow.Assert(args.Length > 0, "args.Length > 0");

            try
            {
                var messageBody = args.JoinSpace();
                GitTasks.Git($"commit --allow-empty -m {messageBody.DoubleQuote()}");
                GitTasks.Git($"push {repository.RemoteName} {repository.Head}:{repository.RemoteBranch}");
                return(0);
            }
            catch
            {
                return(1);
            }
        }
Ejemplo n.º 13
0
    public static List <string> CollectLogRaw(string baseLine)
    {
        var f            = Path.GetTempFileName();
        var formatString = @"%H%n%P%n%aI%n%cn <%ce>%n%s%n%n%w(0,5,5)%b%w(0,0,0)%n--%n";

        if (string.IsNullOrEmpty(baseLine))
        {
            GitTasks.Git($"log --date=iso8601-strict --pretty=tformat:{formatString.DoubleQuoteIfNeeded()} --output={f.DoubleQuoteIfNeeded()}");
        }
        else
        {
            var refLimit = $"{baseLine}..HEAD".DoubleQuoteIfNeeded();
            GitTasks.Git($"log {refLimit} --date=iso8601-strict --pretty=tformat:{formatString.DoubleQuoteIfNeeded()} --output={f.DoubleQuoteIfNeeded()}");
        }

        Logger.Info("Writing to " + f);
        var lines = File.ReadLines(f).ToList();

        File.Delete(f);
        return(lines);
    }
        VersionInfo?GetFromGit()
        {
            if (!GitTasks.GitIsDetached())
            {
                var commitCount = GitTasks.Git("rev-list HEAD --count", logOutput: false).Select(x => x.Text).Single();
                var branch      = GitTasks.GitCurrentBranch()?.Replace("refs/heads/", "").Replace("/", "-");
                var revision    = GitTasks.Git("rev-parse HEAD", logOutput: false).Select(x => x.Text).Single();

                if (!string.IsNullOrEmpty(commitCount) && !string.IsNullOrEmpty(branch) && !string.IsNullOrEmpty(revision))
                {
                    return(new VersionInfo(
                               $"{VersionMajor}.{VersionMinor}.{commitCount}.0",
                               $"{VersionMajor}.{VersionMinor}.{commitCount}.0",
                               $"{VersionMajor}.{VersionMinor}.{commitCount}.0+Branch.{branch}.Sha.{revision}",
                               IsMainBranch(branch)
                            ? $"{VersionMajor}.{VersionMinor}.{commitCount}"
                            : $"{VersionMajor}.{VersionMinor}.{commitCount}-{branch}"));
                }
            }

            return(null);
        }
Ejemplo n.º 15
0
 public static void GitAdd(bool addUntracked, params string[] refs)
 {
     GitTasks.Git($"add {(addUntracked ? "--all" : string.Empty)} {refs.JoinSpace()}");
 }
Ejemplo n.º 16
0
 public static void MergeOurs(string branchName)
 {
     GitTasks.Git($"merge -s ours {branchName.DoubleQuoteIfNeeded()}");
 }
Ejemplo n.º 17
0
    public static void Merge(string branchName, bool allowFF = false)
    {
        var disableFastForwardArg = allowFF ? "" : "--no-ff";

        GitTasks.Git($"merge {disableFastForwardArg} {branchName.DoubleQuoteIfNeeded()}");
    }
Ejemplo n.º 18
0
    public static void DeleteBranch(string branchName, bool force = false)
    {
        var forceArg = force ? "-f" : "";

        GitTasks.Git($"branch -d {forceArg} {branchName.DoubleQuoteIfNeeded()}");
    }
Ejemplo n.º 19
0
 public static void ResetBranch(string branchName, string commitRef)
 {
     GitTasks.Git($"branch -f {branchName.DoubleQuoteIfNeeded()} {commitRef.DoubleQuoteIfNeeded()}");
 }
Ejemplo n.º 20
0
 public static void Commit(string message, bool all = false)
 {
     GitTasks.Git($"commit -a -m {message.DoubleQuoteIfNeeded()}");
 }
Ejemplo n.º 21
0
 public static void CheckoutDetached(string branchName)
 {
     GitTasks.Git($"checkout --detach {branchName.DoubleQuoteIfNeeded()}");
 }
Ejemplo n.º 22
0
 public static void GitCommit(params string[] message)
 {
     GitTasks.Git($"commit {message.Aggregate(string.Empty, (x, y) => $"{x}-m \"{y}\" ").TrimEnd()}");
 }
Ejemplo n.º 23
0
 public static void DeleteTag(string tagName)
 {
     GitTasks.Git($"tag -d {tagName.DoubleQuoteIfNeeded()}");
 }
Ejemplo n.º 24
0
 public static void Push(string remoteName, string branchName)
 {
     GitTasks.Git($"push {remoteName.DoubleQuoteIfNeeded()} {branchName.DoubleQuoteIfNeeded()}");
 }
Ejemplo n.º 25
0
 public static void PushTag(string remoteName, string tagName)
 {
     GitTasks.Git($"push --tags {remoteName.DoubleQuoteIfNeeded()} {tagName.DoubleQuoteIfNeeded()}");
 }
Ejemplo n.º 26
0
 void CommitGit(CustomVersion newVersion, CustomVersion oldVersion)
 {
     GitTasks.Git($"commit -a -m \"Change version from {oldVersion} to {newVersion}\"");
     GitTasks.Git($"tag v{newVersion.ToGitTag()}");
 }
Ejemplo n.º 27
0
    public static void Checkout(string branchName, bool force = false)
    {
        var forceArg = force ? "-f" : "";

        GitTasks.Git($"checkout {forceArg} {branchName.DoubleQuoteIfNeeded()}");
    }
Ejemplo n.º 28
0
 public static void Add(string file)
 {
     GitTasks.Git($"add {file.DoubleQuoteIfNeeded()}");
 }
Ejemplo n.º 29
0
 public static void CommitAmend()
 {
     GitTasks.Git($"commit --amend -C HEAD");
 }