Example #1
0
        } // End Function ReadFile 


        public static string GetDiff(Repository repo, DiffEntry entry)
        {
            string strDiff = null;

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                DiffFormatter diffFormatter = new DiffFormatter(ms);
                diffFormatter.SetRepository(repo);
                diffFormatter.Format(diffFormatter.ToFileHeader(entry));

                ms.Position = 0;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(ms))
                {
                    strDiff = sr.ReadToEnd();
                }
            }

            return strDiff;
        } // End Function GetDiff
 /// <exception cref="System.IO.IOException"></exception>
 private DiffEntry FindRename(RevCommit parent, RevCommit commit, PathFilter path)
 {
     if (renameDetector == null)
     {
         return(null);
     }
     treeWalk.Filter = TreeFilter.ANY_DIFF;
     treeWalk.Reset(parent.Tree, commit.Tree);
     renameDetector.Reset();
     renameDetector.AddAll(DiffEntry.Scan(treeWalk));
     foreach (DiffEntry ent in renameDetector.Compute())
     {
         if (IsRename(ent) && ent.GetNewPath().Equals(path.GetPath()))
         {
             return(ent);
         }
     }
     return(null);
 }
Example #3
0
        public virtual void TestNoOutputStreamSet()
        {
            FilePath file = WriteTrashFile("test.txt", "a");

            NUnit.Framework.Assert.IsTrue(file.SetLastModified(file.LastModified() - 5000));
            Git git = new Git(db);

            git.Add().AddFilepattern(".").Call();
            Write(file, "b");
            IList <DiffEntry> diffs = git.Diff().Call();

            NUnit.Framework.Assert.IsNotNull(diffs);
            NUnit.Framework.Assert.AreEqual(1, diffs.Count);
            DiffEntry diff = diffs[0];

            NUnit.Framework.Assert.AreEqual(DiffEntry.ChangeType.MODIFY, diff.GetChangeType()
                                            );
            NUnit.Framework.Assert.AreEqual("test.txt", diff.GetOldPath());
            NUnit.Framework.Assert.AreEqual("test.txt", diff.GetNewPath());
        }
        public void Execute(TaskExecutionMode mode)
        {
            if (this.CancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException(this.CancellationToken);
            }

            try
            {
                SchemaCompareEndpoint sourceEndpoint = CreateSchemaCompareEndpoint(this.Parameters.SourceEndpointInfo, this.SourceConnectionString);
                SchemaCompareEndpoint targetEndpoint = CreateSchemaCompareEndpoint(this.Parameters.TargetEndpointInfo, this.TargetConnectionString);

                SchemaComparison comparison = new SchemaComparison(sourceEndpoint, targetEndpoint);

                if (this.Parameters.DeploymentOptions != null)
                {
                    comparison.Options = this.CreateSchemaCompareOptions(this.Parameters.DeploymentOptions);
                }

                this.ComparisonResult = comparison.Compare();

                // try one more time if it didn't work the first time
                if (!this.ComparisonResult.IsValid)
                {
                    this.ComparisonResult = comparison.Compare();
                }

                this.Differences = new List <DiffEntry>();
                foreach (SchemaDifference difference in this.ComparisonResult.Differences)
                {
                    DiffEntry diffEntry = CreateDiffEntry(difference, null);
                    this.Differences.Add(diffEntry);
                }
            }
            catch (Exception e)
            {
                ErrorMessage = e.Message;
                Logger.Write(TraceEventType.Error, string.Format("Schema compare operation {0} failed with exception {1}", this.OperationId, e.Message));
                throw;
            }
        }
Example #5
0
        public void LoadDiffs(string fileName)
        {
            _diffs.Clear();
            using (var zip = ZipFile.Read(fileName))
            {
                foreach (var entry in zip.Entries)
                {
                    using (var stream = new MemoryStream())
                    {
                        entry.Extract(stream);
                        stream.Seek(0, SeekOrigin.Begin);

                        using (var reader = new StreamReader(stream))
                        {
                            var diff = new DiffEntry(reader.ReadLine(), reader.ReadToEnd());
                            _diffs.Add(diff);
                        }
                    }
                }
            }
        }
Example #6
0
        private static string Path(DiffEntry difference)
        {
            switch (difference.GetChangeType())
            {
            case DiffEntry.ChangeType.ADD:
                return(difference.GetNewPath());

            case DiffEntry.ChangeType.COPY:
                return(string.Format("{0} -> {1}", difference.GetOldPath(), difference.GetNewPath()));

            case DiffEntry.ChangeType.DELETE:
                return(difference.GetOldPath());

            case DiffEntry.ChangeType.MODIFY:
                return(difference.GetOldPath());

            case DiffEntry.ChangeType.RENAME:
                return(string.Format("{0} -> {1}", difference.GetOldPath(), difference.GetNewPath()));

            default:
                return(difference.ToString());
            }
        }
        private bool IsEqual(SchemaDifference difference, DiffEntry diffEntry)
        {
            bool result = true;
            // Create a diff entry from difference and check if it matches the diff entry passed
            DiffEntry entryFromDifference = SchemaCompareUtils.CreateDiffEntry(difference, null);

            System.Reflection.PropertyInfo[] properties = diffEntry.GetType().GetProperties();
            foreach (var prop in properties)
            {
                // Don't need to check if included is the same when verifying if the difference is equal
                if (prop.Name != "Included")
                {
                    if (!((prop.GetValue(diffEntry) == null &&
                           prop.GetValue(entryFromDifference) == null) ||
                          prop.GetValue(diffEntry).SafeToString().Equals(prop.GetValue(entryFromDifference).SafeToString())))
                    {
                        return(false);
                    }
                }
            }

            return(result);
        }
Example #8
0
        public IEnumerable <FileDiff> GetFileDiffs(string newHash, string oldHash)
        {
            NGit.Repository repo = this.git.GetRepository();

            ObjectId newCommit = repo.Resolve(newHash + "^{tree}");
            ObjectId oldCommit = repo.Resolve(oldHash + "^{tree}");

            var walk = new TreeWalk(repo)
            {
                Recursive = true
            };

            walk.AddTree(oldCommit);
            walk.AddTree(newCommit);

            IEnumerable <DiffEntry> entries = DiffEntry.Scan(walk);

            var diffs = entries.Where(diff => diff.GetNewId().Name != diff.GetOldId().Name);

            return(from diffEntry in diffs
                   let diffType = ToDiffType(diffEntry.GetChangeType())
                                  let path = diffType == DiffType.Delete ? diffEntry.GetOldPath() : diffEntry.GetNewPath()
                                             select new FileDiff(path, diffType));
        }
Example #9
0
        /// <exception cref="NGit.Errors.MissingObjectException"></exception>
        /// <exception cref="NGit.Errors.IncorrectObjectTypeException"></exception>
        /// <exception cref="NGit.Errors.CorruptObjectException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        private void UpdateFollowFilter(ObjectId[] trees)
        {
            TreeWalk     tw        = pathFilter;
            FollowFilter oldFilter = (FollowFilter)tw.Filter;

            tw.Filter = TreeFilter.ANY_DIFF;
            tw.Reset(trees);
            IList <DiffEntry> files = DiffEntry.Scan(tw);
            RenameDetector    rd    = new RenameDetector(repository);

            rd.AddAll(files);
            files = rd.Compute();
            TreeFilter newFilter = oldFilter;

            foreach (DiffEntry ent in files)
            {
                if (IsRename(ent) && ent.GetNewPath().Equals(oldFilter.GetPath()))
                {
                    newFilter = FollowFilter.Create(ent.GetOldPath());
                    break;
                }
            }
            tw.Filter = newFilter;
        }
 public override void Renamed(DiffEntry diff)
 {
     diffs.AddItem(diff);
 }
Example #11
0
        private void ValidateSchemaCompareScriptGenerationWithExcludeIncludeResults(SchemaCompareOperation schemaCompareOperation, SchemaCompareGenerateScriptParams generateScriptParams)
        {
            schemaCompareOperation.Execute(TaskExecutionMode.Execute);

            Assert.True(schemaCompareOperation.ComparisonResult.IsValid);
            Assert.False(schemaCompareOperation.ComparisonResult.IsEqual);
            Assert.NotNull(schemaCompareOperation.ComparisonResult.Differences);

            SchemaCompareGenerateScriptOperation generateScriptOperation = new SchemaCompareGenerateScriptOperation(generateScriptParams, schemaCompareOperation.ComparisonResult);

            generateScriptOperation.Execute(TaskExecutionMode.Execute);

            string initialScript = File.ReadAllText(generateScriptParams.ScriptFilePath);

            // create Diff Entry from on Difference
            DiffEntry diff = SchemaCompareOperation.CreateDiffEntry(schemaCompareOperation.ComparisonResult.Differences.First(), null);

            int initial = schemaCompareOperation.ComparisonResult.Differences.Count();
            SchemaCompareNodeParams schemaCompareExcludeNodeParams = new SchemaCompareNodeParams()
            {
                OperationId       = schemaCompareOperation.OperationId,
                DiffEntry         = diff,
                IncludeRequest    = false,
                TaskExecutionMode = TaskExecutionMode.Execute
            };
            SchemaCompareIncludeExcludeNodeOperation nodeExcludeOperation = new SchemaCompareIncludeExcludeNodeOperation(schemaCompareExcludeNodeParams, schemaCompareOperation.ComparisonResult);

            nodeExcludeOperation.Execute(TaskExecutionMode.Execute);

            int afterExclude = schemaCompareOperation.ComparisonResult.Differences.Count();

            Assert.True(initial == afterExclude, $"Changes should be same again after excluding/including, before {initial}, now {afterExclude}");

            generateScriptOperation = new SchemaCompareGenerateScriptOperation(generateScriptParams, schemaCompareOperation.ComparisonResult);
            generateScriptOperation.Execute(TaskExecutionMode.Execute);

            string afterExcludeScript = File.ReadAllText(generateScriptParams.ScriptFilePath);

            Assert.True(initialScript.Length > afterExcludeScript.Length, $"Script should be affected (less statements) exclude operation, before {initialScript}, now {afterExcludeScript}");

            SchemaCompareNodeParams schemaCompareincludeNodeParams = new SchemaCompareNodeParams()
            {
                OperationId       = schemaCompareOperation.OperationId,
                DiffEntry         = diff,
                IncludeRequest    = true,
                TaskExecutionMode = TaskExecutionMode.Execute
            };

            SchemaCompareIncludeExcludeNodeOperation nodeIncludeOperation = new SchemaCompareIncludeExcludeNodeOperation(schemaCompareincludeNodeParams, schemaCompareOperation.ComparisonResult);

            nodeIncludeOperation.Execute(TaskExecutionMode.Execute);
            int afterInclude = schemaCompareOperation.ComparisonResult.Differences.Count();

            Assert.True(initial == afterInclude, $"Changes should be same again after excluding/including:{initial}, now {afterInclude}");

            generateScriptOperation = new SchemaCompareGenerateScriptOperation(generateScriptParams, schemaCompareOperation.ComparisonResult);
            generateScriptOperation.Execute(TaskExecutionMode.Execute);

            string afterIncludeScript = File.ReadAllText(generateScriptParams.ScriptFilePath);

            Assert.True(initialScript.Length == afterIncludeScript.Length, $"Changes should be same as inital since we included what we excluded, before {initialScript}, now {afterIncludeScript}");
        }
 private static bool IsRename(DiffEntry ent)
 {
     return(ent.GetChangeType() == DiffEntry.ChangeType.RENAME || ent.GetChangeType()
            == DiffEntry.ChangeType.COPY);
 }
Example #13
0
        public virtual void CommitSubmoduleUpdate()
        {
            Git git = new Git(db);

            WriteTrashFile("file.txt", "content");
            git.Add().AddFilepattern("file.txt").Call();
            RevCommit commit = git.Commit().SetMessage("create file").Call();

            WriteTrashFile("file.txt", "content2");
            git.Add().AddFilepattern("file.txt").Call();
            RevCommit           commit2 = git.Commit().SetMessage("edit file").Call();
            SubmoduleAddCommand command = new SubmoduleAddCommand(db);
            string path = "sub";

            command.SetPath(path);
            string uri = db.Directory.ToURI().ToString();

            command.SetURI(uri);
            Repository repo = command.Call();

            NUnit.Framework.Assert.IsNotNull(repo);
            AddRepoToClose(repo);
            SubmoduleWalk generator = SubmoduleWalk.ForIndex(db);

            NUnit.Framework.Assert.IsTrue(generator.Next());
            NUnit.Framework.Assert.AreEqual(path, generator.GetPath());
            NUnit.Framework.Assert.AreEqual(commit2, generator.GetObjectId());
            NUnit.Framework.Assert.AreEqual(uri, generator.GetModulesUrl());
            NUnit.Framework.Assert.AreEqual(path, generator.GetModulesPath());
            NUnit.Framework.Assert.AreEqual(uri, generator.GetConfigUrl());
            Repository subModRepo = generator.GetRepository();

            AddRepoToClose(subModRepo);
            NUnit.Framework.Assert.IsNotNull(subModRepo);
            NUnit.Framework.Assert.AreEqual(commit2, repo.Resolve(Constants.HEAD));
            RevCommit submoduleAddCommit = git.Commit().SetMessage("submodule add").SetOnly(path
                                                                                            ).Call();

            NUnit.Framework.Assert.IsNotNull(submoduleAddCommit);
            RefUpdate update = repo.UpdateRef(Constants.HEAD);

            update.SetNewObjectId(commit);
            NUnit.Framework.Assert.AreEqual(RefUpdate.Result.FORCED, update.ForceUpdate());
            RevCommit submoduleEditCommit = git.Commit().SetMessage("submodule add").SetOnly(
                path).Call();

            NUnit.Framework.Assert.IsNotNull(submoduleEditCommit);
            TreeWalk walk = new TreeWalk(db);

            walk.AddTree(submoduleAddCommit.Tree);
            walk.AddTree(submoduleEditCommit.Tree);
            walk.Filter = TreeFilter.ANY_DIFF;
            IList <DiffEntry> diffs = DiffEntry.Scan(walk);

            NUnit.Framework.Assert.AreEqual(1, diffs.Count);
            DiffEntry subDiff = diffs[0];

            NUnit.Framework.Assert.AreEqual(FileMode.GITLINK, subDiff.GetOldMode());
            NUnit.Framework.Assert.AreEqual(FileMode.GITLINK, subDiff.GetNewMode());
            NUnit.Framework.Assert.AreEqual(commit2, subDiff.GetOldId().ToObjectId());
            NUnit.Framework.Assert.AreEqual(commit, subDiff.GetNewId().ToObjectId());
            NUnit.Framework.Assert.AreEqual(path, subDiff.GetNewPath());
            NUnit.Framework.Assert.AreEqual(path, subDiff.GetOldPath());
        }
Example #14
0
        /// <exception cref="System.IO.IOException"></exception>
        private bool ProcessMerge(Candidate n)
        {
            int pCnt = n.GetParentCount();

            for (int pIdx = 0; pIdx < pCnt; pIdx++)
            {
                RevCommit parent = n.GetParent(pIdx);
                if (parent.Has(SEEN))
                {
                    continue;
                }
                revPool.ParseHeaders(parent);
            }
            // If any single parent exactly matches the merge, follow only
            // that one parent through history.
            ObjectId[] ids = null;
            for (int pIdx_1 = 0; pIdx_1 < pCnt; pIdx_1++)
            {
                RevCommit parent = n.GetParent(pIdx_1);
                if (parent.Has(SEEN))
                {
                    continue;
                }
                if (!Find(parent, n.sourcePath))
                {
                    continue;
                }
                if (!(n is Candidate.ReverseCandidate) && idBuf.Equals(n.sourceBlob))
                {
                    n.sourceCommit = parent;
                    Push(n);
                    return(false);
                }
                if (ids == null)
                {
                    ids = new ObjectId[pCnt];
                }
                ids[pIdx_1] = idBuf.ToObjectId();
            }
            // If rename detection is enabled, search for any relevant names.
            DiffEntry[] renames = null;
            if (renameDetector != null)
            {
                renames = new DiffEntry[pCnt];
                for (int pIdx_2 = 0; pIdx_2 < pCnt; pIdx_2++)
                {
                    RevCommit parent = n.GetParent(pIdx_2);
                    if (parent.Has(SEEN))
                    {
                        continue;
                    }
                    if (ids != null && ids[pIdx_2] != null)
                    {
                        continue;
                    }
                    DiffEntry r = FindRename(parent, n.sourceCommit, n.sourcePath);
                    if (r == null)
                    {
                        continue;
                    }
                    if (n is Candidate.ReverseCandidate)
                    {
                        if (ids == null)
                        {
                            ids = new ObjectId[pCnt];
                        }
                        ids[pCnt] = r.GetOldId().ToObjectId();
                    }
                    else
                    {
                        if (0 == r.GetOldId().PrefixCompare(n.sourceBlob))
                        {
                            // A 100% rename without any content change can also
                            // skip directly to the parent. Note this bypasses an
                            // earlier parent that had the path (above) but did not
                            // have an exact content match. For performance reasons
                            // we choose to follow the one parent over trying to do
                            // possibly both parents.
                            n.sourceCommit = parent;
                            n.sourcePath   = PathFilter.Create(r.GetOldPath());
                            Push(n);
                            return(false);
                        }
                    }
                    renames[pIdx_2] = r;
                }
            }
            // Construct the candidate for each parent.
            Candidate[] parents = new Candidate[pCnt];
            for (int pIdx_3 = 0; pIdx_3 < pCnt; pIdx_3++)
            {
                RevCommit parent = n.GetParent(pIdx_3);
                if (parent.Has(SEEN))
                {
                    continue;
                }
                Candidate p;
                if (renames != null && renames[pIdx_3] != null)
                {
                    p             = n.Create(parent, PathFilter.Create(renames[pIdx_3].GetOldPath()));
                    p.renameScore = renames[pIdx_3].GetScore();
                    p.sourceBlob  = renames[pIdx_3].GetOldId().ToObjectId();
                }
                else
                {
                    if (ids != null && ids[pIdx_3] != null)
                    {
                        p            = n.Create(parent, n.sourcePath);
                        p.sourceBlob = ids[pIdx_3];
                    }
                    else
                    {
                        continue;
                    }
                }
                EditList editList;
                if (n is Candidate.ReverseCandidate && p.sourceBlob.Equals(n.sourceBlob))
                {
                    // This special case happens on ReverseCandidate forks.
                    p.sourceText = n.sourceText;
                    editList     = new EditList(0);
                }
                else
                {
                    p.LoadText(reader);
                    editList = diffAlgorithm.Diff(textComparator, p.sourceText, n.sourceText);
                }
                if (editList.IsEmpty())
                {
                    // Ignoring whitespace (or some other special comparator) can
                    // cause non-identical blobs to have an empty edit list. In
                    // a case like this push the parent alone.
                    if (n is Candidate.ReverseCandidate)
                    {
                        parents[pIdx_3] = p;
                        continue;
                    }
                    p.regionList = n.regionList;
                    Push(p);
                    return(false);
                }
                p.TakeBlame(editList, n);
                // Only remember this parent candidate if there is at least
                // one region that was blamed on the parent.
                if (p.regionList != null)
                {
                    // Reverse blame requires inverting the regions. This puts
                    // the regions the parent deleted from us into the parent,
                    // and retains the common regions to look at other parents
                    // for deletions.
                    if (n is Candidate.ReverseCandidate)
                    {
                        Region r = p.regionList;
                        p.regionList = n.regionList;
                        n.regionList = r;
                    }
                    parents[pIdx_3] = p;
                }
            }
            if (n is Candidate.ReverseCandidate)
            {
                // On a reverse blame report all deletions found in the children,
                // and pass on to them a copy of our region list.
                Candidate resultHead = null;
                Candidate resultTail = null;
                for (int pIdx_2 = 0; pIdx_2 < pCnt; pIdx_2++)
                {
                    Candidate p = parents[pIdx_2];
                    if (p == null)
                    {
                        continue;
                    }
                    if (p.regionList != null)
                    {
                        Candidate r = p.Copy(p.sourceCommit);
                        if (resultTail != null)
                        {
                            resultTail.queueNext = r;
                            resultTail           = r;
                        }
                        else
                        {
                            resultHead = r;
                            resultTail = r;
                        }
                    }
                    if (n.regionList != null)
                    {
                        p.regionList = n.regionList.DeepCopy();
                        Push(p);
                    }
                }
                if (resultHead != null)
                {
                    return(Result(resultHead));
                }
                return(false);
            }
            // Push any parents that are still candidates.
            for (int pIdx_4 = 0; pIdx_4 < pCnt; pIdx_4++)
            {
                if (parents[pIdx_4] != null)
                {
                    Push(parents[pIdx_4]);
                }
            }
            if (n.regionList != null)
            {
                return(Result(n));
            }
            return(false);
        }
Example #15
0
 /// <summary>
 /// Called whenever a diff was found that is actually a rename or copy of a
 /// file.
 /// </summary>
 /// <remarks>
 /// Called whenever a diff was found that is actually a rename or copy of a
 /// file.
 /// </remarks>
 /// <param name="entry">the entry representing the rename/copy</param>
 public abstract void Renamed(DiffEntry entry);
Example #16
0
 private SchemaDifference FindDifference(IEnumerable <SchemaDifference> differences, DiffEntry diffEntry)
 {
     foreach (var difference in differences)
     {
         if (IsEqual(difference, diffEntry))
         {
             return(difference);
         }
         else
         {
             var childDiff = FindDifference(difference.Children, diffEntry);
             if (childDiff != null)
             {
                 return(childDiff);
             }
         }
     }
     return(null);
 }