예제 #1
0
        private void ProcessAuthor(CheckinOptions checkinOptions, TextWriter writer, GitCommit commit)
        {
            if (checkinOptions.AuthorsFilePath == null)
            {
                writer.WriteLine("Author file was not set.");
                return;
            }

            // get authors file FIXME
            AuthorsFile af = new AuthorsFile();
            TextReader  tr = new StreamReader(checkinOptions.AuthorsFilePath);

            af.Parse(tr);

            Author a = af.FindAuthor(commit.AuthorAndEmail);

            if (a == null)
            {
                checkinOptions.AuthorTfsUserId = null;
                return;
            }

            checkinOptions.AuthorTfsUserId = a.TfsUserId;
            writer.WriteLine("Commit was authored by git user {0} {1} ({2})", a.Name, a.Email, a.TfsUserId);
        }
예제 #2
0
        public async Task TestCommitingAsync()
        {
            // Init default working folder repo
            await git.InitRepoAsync();

            // Write file and check status that a file has been added
            io.WriteFile("file1.txt", "Some text 1");
            status = await git.GetStatusAsync();

            Assert.AreEqual(1, status.Added);

            // Commit and check status that staus  has no changes
            GitCommit commit1 = await git.CommitAllChangesAsync("Message 1");

            status = await git.GetStatusAsync();

            Assert.AreEqual(0, status.AllChanges);

            // Make a change to to file and check that status is 1 file modified
            io.WriteFile("file1.txt", "Some text 2");
            status = await git.GetStatusAsync();

            Assert.AreEqual(1, status.Modified);

            // Commit and verify status
            GitCommit commit2 = await git.CommitAllChangesAsync("Message 2");

            status = await git.GetStatusAsync();

            Assert.AreEqual(0, status.AllChanges);
        }
예제 #3
0
 private string GetUpdateBlockedReason(
     GitHubPullRequest pr,
     GitCommit headCommit,
     string upgradeBranchPrefix,
     GitHubProject origin)
 {
     if (pr.Head.User.Login != origin.Owner)
     {
         return($"Owner of head repo '{pr.Head.User.Login}' is not '{origin.Owner}'");
     }
     if (!pr.Head.Ref.StartsWith(upgradeBranchPrefix))
     {
         return($"Ref name '{pr.Head.Ref}' does not start with '{upgradeBranchPrefix}'");
     }
     if (headCommit.Author.Name != GitAuthorName)
     {
         return($"Head commit author '{headCommit.Author.Name}' is not '{GitAuthorName}'");
     }
     if (headCommit.Committer.Name != GitAuthorName)
     {
         return($"Head commit committer '{headCommit.Committer.Name}' is not '{GitAuthorName}'");
     }
     if (pr.Labels?.Any(IsMaestroStopUpdatesLabel) ?? false)
     {
         return($"Label `{MaestroStopUpdatesLabel}` is attached");
     }
     return(null);
 }
예제 #4
0
        public async Task TestGetCommitMessageLog()
        {
            await git.InitRepoAsync();

            io.WriteFile("file1.txt", "some text 1");
            string    message1 = "Message 1\n\nSome body text l1\nome body text l2";
            GitCommit commit1  = await git.CommitAllChangesAsync(message1);

            io.WriteFile("file2.txt", "some text 2");
            string    message2 = "Message 2";
            GitCommit commit2  = await git.CommitAllChangesAsync(message2);

            io.WriteFile("file2.txt", "some text 3");
            string    message3 = "Message 2\nsome short body";
            GitCommit commit3  = await git.CommitAllChangesAsync(message3);

            R <string> message21 = await cmd.GetCommitMessageAsync(commit1.Sha.Sha, ct);

            Assert.AreEqual(message1, message21.Value);

            R <string> message22 = await cmd.GetCommitMessageAsync(commit2.Sha.Sha, ct);

            Assert.AreEqual(message2, message22.Value);

            R <string> message23 = await cmd.GetCommitMessageAsync(commit3.Sha.Sha, ct);

            Assert.AreEqual(message3, message23.Value);
        }
예제 #5
0
        public List <GitCommit> GetCommits()
        {
            List <Commit>    commits    = GetCommitsInternal();
            List <GitCommit> gitCommits = new List <GitCommit>();

            for (int i = 0; i < commits.Count - 1; i++)
            {
                Tree currentTree  = commits[i].Tree;
                Tree previousTree = commits[i + 1].Tree;

                Patch patch = _repository.Diff.Compare <Patch>(currentTree, previousTree);

                Console.WriteLine($"{commits[i].MessageShort}");
                GitCommit gitCommit = new GitCommit(commits[i].Sha, commits[i].MessageShort, commits[i].Author.Name, commits[i].Author.When);

                foreach (PatchEntryChanges pec in patch)
                {
                    Console.WriteLine("{0} = {1} ({2}+ and {3}-)",
                                      pec.Path,
                                      pec.LinesAdded + pec.LinesDeleted,
                                      pec.LinesAdded,
                                      pec.LinesDeleted);

                    string fileContent = GetFileContent(commits[i], pec.Path);
                    gitCommit.PatchEntryChanges.Add(new GitPatchEntryChange(pec.Path, pec.LinesAdded, pec.LinesDeleted, fileContent));
                }
                Console.WriteLine();

                gitCommits.Add(gitCommit);
            }

            return(gitCommits);
        }
예제 #6
0
        public async Task TestUncommitMergedIntoMasterCommitAsync()
        {
            await git.InitRepoAsync();

            // Make 2 commits on a file
            io.WriteFile("file1.txt", "Some text 1");
            GitCommit commit1 = await git.CommitAllChangesAsync("Message 1");

            io.WriteFile("file1.txt", "Some text 2");
            GitCommit commit2 = await git.CommitAllChangesAsync("Message 2");

            await git.BranchAsync("branch1");

            io.WriteFile("file1.txt", "Some text on branch 1");
            GitCommit commit3 = await git.CommitAllChangesAsync("Message  on branch 1");

            await git.CheckoutAsync("master");

            await git.MergeAsync("branch1");

            status = await git.GetStatusAsync();

            await git.CommitAllChangesAsync($"{status.MergeMessage} into master");

            R result = await cmd.UnCommitAsync(ct);

            Assert.AreEqual(true, result.IsOk);
        }
예제 #7
0
 public GitCommit Info(IHostingEnvironment environment, string repoName)
 {
     var repoPath = $"{environment.WebRootPath}/Repos/{repoName}";
     var gitResult = StartGit(" log -1 --numstat --date=raw", repoPath);
     var regex = new Regex(@"commit (.+)\nAuthor: (.+) <(.+)>[\n ]*Date:[\n ]*(.\d+)[ +\d]*[\n ]*(.+)[\n ]",RegexOptions.IgnoreCase);
     var match = regex.Matches(gitResult);
     if (match.Count == 0)
         return null;
     var result = new GitCommit
     {
         Hash = match[0].Groups[1].Value,
         Author = match[0].Groups[2].Value,
         AuthorEmail = match[0].Groups[3].Value,
         //Todo: fix timezones
         CommitTime = DateTimeOffset.FromUnixTimeSeconds(long.Parse(match[0].Groups[4].Value)).DateTime,
         Description = match[0].Groups[5].Value,
         Changes = new Dictionary<string, Tuple<int, int>>()
     };
     regex = new Regex(@"(\d[ \n]*\d[ \n]*.+\n)",RegexOptions.IgnoreCase);
     match = regex.Matches(gitResult);
     for (int i = 2; i < match.Count; i++)
     {
         try
         {
             var elements = match[i].Value.Split(' ', '\t');
             result.Changes[elements[2]] = new Tuple<int, int>(int.Parse(elements[0]), int.Parse(elements[1]));
         }
         catch (Exception ex)
         {
             i++;
         }
     }
     return result;
 }
 private static string GetFileContentForFilePath(string filePath, GitCommit gitCommit)
 {
     return(gitCommit
            .PatchEntryChanges
            .Single(x => x.Path == filePath)
            .FileContent);
 }
예제 #9
0
        public async Task TestDiffDeletedFiletAsync()
        {
            GitDiffParser diffParser = new GitDiffParser();

            await git.InitRepoAsync();

            io.WriteFile("file1.txt", "text1");
            GitCommit commit1 = await git.CommitAllChangesAsync("Message1");

            io.DeleteFile("file1.txt");
            GitCommit commit2 = await git.CommitAllChangesAsync("Message2");

            R <string> result1 = await cmd.GetFileDiffAsync(commit1.Sha.Sha, "file1.txt", ct);

            Assert.AreEqual(true, result1.IsOk);

            CommitDiff diff1 = await diffParser.ParseAsync(commit1.Sha, result1.Value, false, false);

            Assert.IsNullOrEmpty(File.ReadAllText(diff1.LeftPath));
            Assert.AreEqual("text1\r\n", File.ReadAllText(diff1.RightPath));

            R <string> result2 = await cmd.GetFileDiffAsync(commit2.Sha.Sha, "file1.txt", ct);

            Assert.AreEqual(true, result2.IsOk);

            CommitDiff diff2 = await diffParser.ParseAsync(commit2.Sha, result2.Value, false, false);

            Assert.AreEqual("text1\r", File.ReadAllText(diff2.LeftPath));
            Assert.IsNullOrEmpty(File.ReadAllText(diff2.RightPath));
        }
예제 #10
0
        public async Task TestBranchAtCommitAsync()
        {
            await git.InitRepoAsync();

            io.WriteFile("file1.txt", "Text 1");
            var commit1 = await git.CommitAllChangesAsync("Message 1");

            io.WriteFile("file1.txt", "Text 2");
            var commit2 = await git.CommitAllChangesAsync("Message 2");

            io.WriteFile("file1.txt", "Text 3");
            var commit3 = await git.CommitAllChangesAsync("Message 3");

            await cmd.BranchFromCommitAsync("branch1", commit2.Sha.Sha, true, ct);

            io.WriteFile("file1.txt", "Text 1 on bbranch1");
            var commit4 = await git.CommitAllChangesAsync("Message 1 on branch1");

            branches = await git.GetBranchesAsync();

            branches.TryGet("branch1", out GitBranch branch);
            Assert.AreEqual(commit4.Sha, branch.TipSha);
            GitCommit parentCommit = await git.GetCommit(commit4.ParentIds.First().Id);

            Assert.AreEqual(commit2.Sha, parentCommit.Sha);
        }
예제 #11
0
        public void EqualsObjectTest()
        {
            var commit = new GitCommit()
            {
                Sha = GitObjectId.Parse(this.shaAsByteArray),
            };

            var commit2 = new GitCommit()
            {
                Sha = GitObjectId.Parse(this.shaAsByteArray),
            };

            var emptyCommit = new GitCommit()
            {
                Sha = GitObjectId.Empty,
            };

            // Must be equal to itself
            Assert.True(commit.Equals((object)commit));
            Assert.True(commit.Equals((object)commit2));

            // Not equal to null
            Assert.False(commit.Equals(null));

            // Not equal to other representations of the commit
            Assert.False(commit.Equals(this.shaAsByteArray));
            Assert.False(commit.Equals(commit.Sha));

            // Not equal to other object ids
            Assert.False(commit.Equals((object)emptyCommit));
        }
예제 #12
0
        public async Task TestDiffCommitAsync()
        {
            await git.InitRepoAsync();

            io.WriteFile("file1.txt", "text1");
            io.WriteFile("file2.txt", "text2");
            GitCommit commit1 = await git.CommitAllChangesAsync("Message1");

            io.WriteFile("file1.txt", "text12");
            io.WriteFile("file2.txt", "text22");
            GitCommit commit2 = await git.CommitAllChangesAsync("Message2");

            R <string> result = await cmd.GetCommitDiffAsync(commit1.Sha.Sha, ct);

            Assert.AreEqual(true, result.IsOk);

            CommitDiff diff = await git.ParsePatchAsync(commit1.Sha, result.Value);

            Assert.IsNotNullOrEmpty(diff.LeftText);
            Assert.IsNotNullOrEmpty(diff.RightText);

            result = await cmd.GetCommitDiffAsync(commit2.Sha.Sha, ct);

            Assert.AreEqual(true, result.IsOk);

            CommitDiff diff2 = await git.ParsePatchAsync(commit1.Sha, result.Value);

            Assert.IsNotNullOrEmpty(diff2.LeftText);
            Assert.IsNotNullOrEmpty(diff2.RightText);
        }
예제 #13
0
        public void WhenGettingCommitIdentifierShouldReturnCommitHash()
        {
            var c = new GitCommit();

            c.CommitHash = "a";
            Assert.Equal("a", c.ChangesetIdentifier);
        }
        private string GetUpdateBlockedReason(
            GitHubClient client,
            GitHubPullRequest pullRequest,
            string upgradeBranchPrefix)
        {
            if (pullRequest.Head.User.Login != Origin.Owner)
            {
                return($"Owner of head repo '{pullRequest.Head.User.Login}' is not '{Origin.Owner}'");
            }
            if (!pullRequest.Head.Ref.StartsWith(upgradeBranchPrefix))
            {
                return($"Ref name '{pullRequest.Head.Ref}' does not start with '{upgradeBranchPrefix}'");
            }

            GitCommit commit = client.GetCommitAsync(Origin, pullRequest.Head.Sha).Result;

            if (commit.Author.Name != GitAuthorName)
            {
                return($"Head commit author '{commit.Author.Name}' is not '{GitAuthorName}'");
            }
            if (commit.Committer.Name != GitAuthorName)
            {
                return($"Head commit committer '{commit.Committer.Name}' is not '{GitAuthorName}'");
            }
            return(null);
        }
예제 #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CommitHistoryItemViewModel" /> class.
        /// </summary>
        /// <param name="commit">The commit the view model is related to.</param>
        public CommitHistoryItemViewModel(GitCommit commit)
        {
            GitCommit = commit;

            Gravatar = new GravatarViewModel {
                EmailAddress = GitCommit.CommitterEmail
            };
        }
예제 #16
0
        /// <inheritdoc />
        public string GetCommitMessageLong(GitCommit commit, IScheduler scheduler = null)
        {
            IList <string> result =
                this.gitProcessManager.RunGit(new[] { "log", "--format=%B", "-n 1", commit.Sha }, scheduler: scheduler).Select(
                    x => x.Trim().Trim('\r', '\n')).ToList().Wait();

            return(string.Join("\r\n", result).Trim().Trim('\r', '\n', ' '));
        }
예제 #17
0
        public void ToStringTest()
        {
            var commit = new GitCommit()
            {
                Sha = GitObjectId.Parse(this.shaAsByteArray),
            };

            Assert.Equal("Git Commit: 4e912736c27e40b389904d046dc63dc9f578117f", commit.ToString());
        }
예제 #18
0
        public void Remove(GitCommit commit)
        {
            if (commit is null)
            {
                throw new ArgumentNullException(nameof(commit));
            }

            m_AllCommits.Remove(commit.Id);
        }
 /// <inheritdoc />
 public IObservable <string> GetCommitMessagesAfterParent(GitCommit parent, IScheduler scheduler = null)
 {
     return(CurrentBranch.Select(branch => ExtractLogParameter(branch, 0, 0, GitLogOptions.None, $"{parent.Sha}..HEAD"))
            .Switch()
            .Select(x => _gitProcessManager.RunGit(x, scheduler: scheduler))
            .Switch()
            .Select(x => ConvertStringToGitCommit(x).MessageLong.Select(y => y.Trim('\r', '\n')))
            .Switch());
 }
 private static bool IsRelevantCommit(GitRepository repository, GitCommit commit, GitCommit parent, IReadOnlyList <FilterPath> filters)
 {
     return(IsRelevantCommit(
                repository,
                repository.GetTree(commit.Tree),
                parent != default ? repository.GetTree(parent.Tree) : null,
                relativePath: string.Empty,
                filters));
 }
 private CommitViewModel ConvertCommit(GitCommit gitCommit)
 {
     return(new CommitViewModel
     {
         Committer = gitCommit.Committer,
         Identifier = gitCommit.ShaId,
         Message = gitCommit.Message
     });
 }
예제 #22
0
        protected override bool TryGetOverrideMessage(GitCommit commit, [NotNullWhen(true)] out string?message)
        {
            if (m_OverrideMessages.Value.TryGetValue(commit.Id, out message))
            {
                m_Logger.LogInformation($"Commit message for commit '{commit.Id}' was overridden through filesystem. Using message from filesystem instead of commit message.");
                return(true);
            }

            return(false);
        }
예제 #23
0
        public bool IsCommitOnSameDay(GitCommit current, GitCommit previous)
        {
            if (previous == null || current == null)
            {
                return(true);
            }
            var currentDate  = current.CommitTimeStamp;
            var previousDate = previous.CommitTimeStamp;

            return(currentDate.DayOfWeek == previousDate.DayOfWeek);
        }
예제 #24
0
        public void WhenParsingCommitWithBinaryFilesShouldGetResultsCorrectly()
        {
            var list = GetListWithContent(Resources.GitExample2);

            GitCommit commit = this.parser.Parse(list)[0];

            Assert.Single(commit.ChangesetFileChanges);
            Assert.Equal("src/dir-with-dashes/File1.cs", commit.ChangesetFileChanges[0].FileName);
            Assert.Equal(0, commit.ChangesetFileChanges[0].Added);
            Assert.Equal(0, commit.ChangesetFileChanges[0].Deleted);
        }
예제 #25
0
        private static async Task <bool> SearchCommitAtPathAsync(string filePath, string sha)
        {
            GitCommit gitCommit = await GitCommit.FindCommitAsync(filePath, sha);

            if (gitCommit != null)
            {
                s_localCache[sha] = gitCommit;
                return(true);
            }
            return(false);
        }
예제 #26
0
        public TimeSpan TimeSinceLastCommit(GitCommit current, GitCommit previous)
        {
            if (previous == null || current == null)
            {
                return(TimeSpan.MaxValue);
            }
            var currentDate  = current.CommitTimeStamp;
            var previousDate = previous.CommitTimeStamp;

            return((currentDate - previousDate).Duration());
        }
예제 #27
0
        /// <inheritdoc />
        public async Task <string> GetCommitMessages(GitCommit startCommit, CancellationToken token)
        {
            if (startCommit == null)
            {
                return(null);
            }

            var result = await this.branchManager.GetCommitMessagesAfterParent(startCommit, token);

            return(result.TrimEmptyLines());
        }
        /// <inheritdoc />
        public IObservable <string> GetCommitMessageLong(GitCommit commit, IScheduler scheduler = null)
        {
            if (commit == null)
            {
                throw new ArgumentNullException(nameof(commit));
            }

            return(_gitProcessManager.RunGit(new[] { "log", "--format=%B", "-n 1", commit.Sha }, scheduler: scheduler)
                   .Select(x => x.Trim().Trim('\r', '\n'))
                   .ToList()
                   .Select(result => string.Join("\r\n", result).Trim().Trim('\r', '\n', ' ')));
        }
예제 #29
0
        public void WhenParsingSubsequentCommitsShouldParseStatsCorrectly()
        {
            var list = GetListWithContent(Resources.GitExample1);

            GitCommit commit = this.parser.Parse(list)[1];

            Assert.Equal(2, commit.ChangesetFileChanges.Count);

            Assert.Equal(4, commit.ChangesetFileChanges[1].Added);
            Assert.Equal(3, commit.ChangesetFileChanges[1].Deleted);
            Assert.Equal("src/dir2/SomeOtherFile.cs", commit.ChangesetFileChanges[1].FileName);
        }
예제 #30
0
 public GitFileSystem(GitFileSystemParams param) : base(param)
 {
     try
     {
         this.Commit = this.Repository.FindCommitAsync(param.CommitId)._GetResult();
     }
     catch (Exception ex)
     {
         this._DisposeSafe(ex);
         throw;
     }
 }
예제 #31
0
        public void TaskCommitTest()
        {
            // create a file to commit
            string contentFile4 = dummyRepo + "\\testFile4.txt";
            using (var writer = new StreamWriter(contentFile4))
            {
                writer.WriteLine("File content for file 4");
                writer.Close();
            }

            List<string> output = Add.ExecCommand(true, null);

            GitCommit t = new GitCommit
            {
                Message = "Init commit"
            };
            t.BuildEngine = new DummyBuildEngine();

            bool result = t.Execute();
            Assert.IsTrue(result, "Execution failed");
        }