Beispiel #1
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);
        }
Beispiel #2
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());
        }
        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);
        }
Beispiel #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))
            );
    }
Beispiel #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));
    }
Beispiel #6
0
    public bool EnsureNoUncommittedChanges()
    {
        if (!GitTasks.GitHasCleanWorkingCopy())
        {
            throw new Exception(
                      "There are uncommitted changes in the working tree. Please commit or remove these before proceeding.");
        }

        return(true);
    }
Beispiel #7
0
 public static bool CheckBranchExists(string branchName)
 {
     try
     {
         return(GitTasks.Git($"show-ref --heads {branchName.DoubleQuoteIfNeeded()}").Count > 0);
     }
     catch (ProcessException pe)
     {
         return(false);
     }
 }
Beispiel #8
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()}");
     }
 }
Beispiel #9
0
        async Task CloneWord2VecNetRepo(string outputDir, ITestOutputHelper output)
        {
            // If the repo already exists, we delete it and extract it again.
            string word2VecNetRepoRootDir = GetWord2VecNetRepoRootDir(outputDir);

            FileTasks.DeleteDirectory(word2VecNetRepoRootDir, output);

            await GitTasks.Clone(Word2VecNetRepoUrl, word2VecNetRepoRootDir, output);

            await GitTasks.Checkout(Word2VecNetCommitSha1Id, output, word2VecNetRepoRootDir);
        }
Beispiel #10
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()}");
    }
 private string GetBranch()
 {
     return
         (AppVeyor.Instance?.RepositoryBranch ??
          Bitrise.Instance?.GitBranch ??
          GitLab.Instance?.CommitRefName ??
          Jenkins.Instance?.GitBranch ??
          TeamCity.Instance?.BranchName ??
          TeamServices.Instance?.SourceBranchName ??
          Travis.Instance?.Branch ??
          GitTasks.GitCurrentBranch());
 }
Beispiel #12
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}");
     }
 }
Beispiel #13
0
 private string GetBranch()
 {
     return
         (AppVeyor.Instance?.RepositoryBranch ??
          Bitrise.Instance?.GitBranch ??
          GitLab.Instance?.CommitRefName ??
          Jenkins.Instance?.GitBranch ??
          Jenkins.Instance?.BranchName ??
          TeamCity.Instance?.BranchName ??
          AzurePipelines.Instance?.SourceBranchName ??
          TravisCI.Instance?.Branch ??
          GitHubActions.Instance?.GitHubRef ??
          GitTasks.GitCurrentBranch());
 }
    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
        });
    }
}
Beispiel #15
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);
            }
        }
Beispiel #16
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);
            }
        }
Beispiel #17
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);
        }
Beispiel #19
0
 public static void DeleteTag(string tagName)
 {
     GitTasks.Git($"tag -d {tagName.DoubleQuoteIfNeeded()}");
 }
Beispiel #20
0
 void CommitGit(CustomVersion newVersion, CustomVersion oldVersion)
 {
     GitTasks.Git($"commit -a -m \"Change version from {oldVersion} to {newVersion}\"");
     GitTasks.Git($"tag v{newVersion.ToGitTag()}");
 }
Beispiel #21
0
 public static void CommitAmend()
 {
     GitTasks.Git($"commit --amend -C HEAD");
 }
Beispiel #22
0
    public static void Merge(string branchName, bool allowFF = false)
    {
        var disableFastForwardArg = allowFF ? "" : "--no-ff";

        GitTasks.Git($"merge {disableFastForwardArg} {branchName.DoubleQuoteIfNeeded()}");
    }
Beispiel #23
0
 public static void MergeOurs(string branchName)
 {
     GitTasks.Git($"merge -s ours {branchName.DoubleQuoteIfNeeded()}");
 }
Beispiel #24
0
 public static void ResetBranch(string branchName, string commitRef)
 {
     GitTasks.Git($"branch -f {branchName.DoubleQuoteIfNeeded()} {commitRef.DoubleQuoteIfNeeded()}");
 }
Beispiel #25
0
    public static void DeleteBranch(string branchName, bool force = false)
    {
        var forceArg = force ? "-f" : "";

        GitTasks.Git($"branch -d {forceArg} {branchName.DoubleQuoteIfNeeded()}");
    }
Beispiel #26
0
    public static void Checkout(string branchName, bool force = false)
    {
        var forceArg = force ? "-f" : "";

        GitTasks.Git($"checkout {forceArg} {branchName.DoubleQuoteIfNeeded()}");
    }
Beispiel #27
0
 public static void CheckoutDetached(string branchName)
 {
     GitTasks.Git($"checkout --detach {branchName.DoubleQuoteIfNeeded()}");
 }
Beispiel #28
0
 public static void Commit(string message, bool all = false)
 {
     GitTasks.Git($"commit -a -m {message.DoubleQuoteIfNeeded()}");
 }
Beispiel #29
0
 public static void Add(string file)
 {
     GitTasks.Git($"add {file.DoubleQuoteIfNeeded()}");
 }
Beispiel #30
0
 public static bool CheckUncommittedChanges()
 {
     return(GitTasks.GitHasCleanWorkingCopy());
 }