Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Diff.cs « LibGit2Sharp - github.com/mono/libgit2sharp.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: bde61d7ef42d8b84d1cdbb3c32d61461073fab8a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Compat;
using LibGit2Sharp.Core.Handles;
using Environment = System.Environment;

namespace LibGit2Sharp
{
    /// <summary>
    /// Show changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, or changes between two files on disk.
    /// <para>
    ///   Copied and renamed files currently cannot be detected, as the feature is not supported by libgit2 yet.
    ///   These files will be shown as a pair of Deleted/Added files.</para>
    /// </summary>
    public class Diff
    {
        private readonly Repository repo;

        private static GitDiffOptions BuildOptions(DiffModifiers diffOptions, FilePath[] filePaths = null, MatchedPathsAggregator matchedPathsAggregator = null, CompareOptions compareOptions = null)
        {
            var options = new GitDiffOptions();

            options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_TYPECHANGE;

            compareOptions = compareOptions ?? new CompareOptions();
            options.ContextLines = (ushort)compareOptions.ContextLines;
            options.InterhunkLines = (ushort)compareOptions.InterhunkLines;

            if (diffOptions.HasFlag(DiffModifiers.IncludeUntracked))
            {
                options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNTRACKED |
                GitDiffOptionFlags.GIT_DIFF_RECURSE_UNTRACKED_DIRS |
                GitDiffOptionFlags.GIT_DIFF_SHOW_UNTRACKED_CONTENT;
            }

            if (diffOptions.HasFlag(DiffModifiers.IncludeIgnored))
            {
                options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_IGNORED |
                GitDiffOptionFlags.GIT_DIFF_RECURSE_IGNORED_DIRS;
            }

            if (diffOptions.HasFlag(DiffModifiers.IncludeUnmodified) || compareOptions.IncludeUnmodified ||
                (compareOptions.Similarity != null &&
                 (compareOptions.Similarity.RenameDetectionMode == RenameDetectionMode.CopiesHarder ||
                  compareOptions.Similarity.RenameDetectionMode == RenameDetectionMode.Exact)))
            {
                options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNMODIFIED;
            }

            if (diffOptions.HasFlag(DiffModifiers.DisablePathspecMatch))
            {
                options.Flags |= GitDiffOptionFlags.GIT_DIFF_DISABLE_PATHSPEC_MATCH;
            }

            if (matchedPathsAggregator != null)
            {
                options.NotifyCallback = matchedPathsAggregator.OnGitDiffNotify;
            }

            if (filePaths == null)
            {
                return options;
            }

            options.PathSpec = GitStrArrayIn.BuildFrom(filePaths);
            return options;
        }

        /// <summary>
        /// Needed for mocking purposes.
        /// </summary>
        protected Diff()
        { }

        internal Diff(Repository repo)
        {
            this.repo = repo;
        }

        private static readonly IDictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>> HandleRetrieverDispatcher = BuildHandleRetrieverDispatcher();

        private static IDictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>> BuildHandleRetrieverDispatcher()
        {
            return new Dictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>>
                       {
                           { DiffTargets.Index, IndexToTree },
                           { DiffTargets.WorkingDirectory, WorkdirToTree },
                           { DiffTargets.Index | DiffTargets.WorkingDirectory, WorkdirAndIndexToTree },
                       };
        }

        private static readonly IDictionary<Type, Func<DiffSafeHandle, object>> ChangesBuilders = new Dictionary<Type, Func<DiffSafeHandle, object>>
        {
            { typeof(Patch), diff => new Patch(diff) },
            { typeof(TreeChanges), diff => new TreeChanges(diff) },
            { typeof(PatchStats), diff => new PatchStats(diff) },
        };

        /// <summary>
        /// Show changes between two <see cref="Blob"/>s.
        /// </summary>
        /// <param name="oldBlob">The <see cref="Blob"/> you want to compare from.</param>
        /// <param name="newBlob">The <see cref="Blob"/> you want to compare to.</param>
        /// <param name="compareOptions">Additional options to define comparison behavior.</param>
        /// <returns>A <see cref="ContentChanges"/> containing the changes between the <paramref name="oldBlob"/> and the <paramref name="newBlob"/>.</returns>
        public virtual ContentChanges Compare(Blob oldBlob, Blob newBlob, CompareOptions compareOptions = null)
        {
            using (GitDiffOptions options = BuildOptions(DiffModifiers.None, compareOptions: compareOptions))
            {
                return new ContentChanges(repo, oldBlob, newBlob, options);
            }
        }

        /// <summary>
        /// Show changes between two <see cref="Tree"/>s.
        /// </summary>
        /// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param>
        /// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param>
        /// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
        /// <param name="explicitPathsOptions">
        /// If set, the passed <paramref name="paths"/> will be treated as explicit paths.
        /// Use these options to determine how unmatched explicit paths should be handled.
        /// </param>
        /// <param name="compareOptions">Additional options to define patch generation behavior.</param>
        /// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns>
        public virtual T Compare<T>(Tree oldTree, Tree newTree, IEnumerable<string> paths = null, ExplicitPathsOptions explicitPathsOptions = null,
            CompareOptions compareOptions = null) where T : class
        {
            Func<DiffSafeHandle, object> builder;

            if (!ChangesBuilders.TryGetValue(typeof (T), out builder))
            {
                throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture,
                    "Unexpected type '{0}' passed to Compare. Supported values are either '{1}' or '{2}'.", typeof (T),
                    typeof (TreeChanges), typeof (Patch)));
            }

            var comparer = TreeToTree(repo);
            ObjectId oldTreeId = oldTree != null ? oldTree.Id : null;
            ObjectId newTreeId = newTree != null ? newTree.Id : null;
            var diffOptions = DiffModifiers.None;

            if (explicitPathsOptions != null)
            {
                diffOptions |= DiffModifiers.DisablePathspecMatch;

                if (explicitPathsOptions.ShouldFailOnUnmatchedPath ||
                    explicitPathsOptions.OnUnmatchedPath != null)
                {
                    diffOptions |= DiffModifiers.IncludeUnmodified;
                }
            }

            using (DiffSafeHandle diff = BuildDiffList(oldTreeId, newTreeId, comparer,
                diffOptions, paths, explicitPathsOptions, compareOptions))
            {
                return (T)builder(diff);
            }
        }

        /// <summary>
        /// Show changes between a <see cref="Tree"/> and the Index, the Working Directory, or both.
        /// <para>
        /// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/>
        /// or <see cref="Patch"/> type as the generic parameter.
        /// </para>
        /// </summary>
        /// <param name="oldTree">The <see cref="Tree"/> to compare from.</param>
        /// <param name="diffTargets">The targets to compare to.</param>
        /// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
        /// <param name="explicitPathsOptions">
        /// If set, the passed <paramref name="paths"/> will be treated as explicit paths.
        /// Use these options to determine how unmatched explicit paths should be handled.
        /// </param>
        /// <param name="compareOptions">Additional options to define patch generation behavior.</param>
        /// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or
        /// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam>
        /// <returns>A <typeparamref name="T"/> containing the changes between the <see cref="Tree"/> and the selected target.</returns>
        public virtual T Compare<T>(Tree oldTree, DiffTargets diffTargets, IEnumerable<string> paths = null,
            ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) where T : class
        {
            Func<DiffSafeHandle, object> builder;

            if (!ChangesBuilders.TryGetValue(typeof (T), out builder))
            {
                throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture,
                    "Unexpected type '{0}' passed to Compare. Supported values are either '{1}' or '{2}'.", typeof (T),
                    typeof (TreeChanges), typeof (Patch)));
            }

            var comparer = HandleRetrieverDispatcher[diffTargets](repo);
            ObjectId oldTreeId = oldTree != null ? oldTree.Id : null;

            DiffModifiers diffOptions = diffTargets.HasFlag(DiffTargets.WorkingDirectory)
                ? DiffModifiers.IncludeUntracked
                : DiffModifiers.None;

            if (explicitPathsOptions != null)
            {
                diffOptions |= DiffModifiers.DisablePathspecMatch;

                if (explicitPathsOptions.ShouldFailOnUnmatchedPath ||
                    explicitPathsOptions.OnUnmatchedPath != null)
                {
                    diffOptions |= DiffModifiers.IncludeUnmodified;
                }
            }

            using (DiffSafeHandle diff = BuildDiffList(oldTreeId, null, comparer,
                diffOptions, paths, explicitPathsOptions, compareOptions))
            {
                return (T)builder(diff);
            }
        }

        /// <summary>
        /// Show changes between the working directory and the index.
        /// <para>
        /// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/>
        /// or <see cref="Patch"/> type as the generic parameter.
        /// </para>
        /// </summary>
        /// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
        /// <param name="includeUntracked">If true, include untracked files from the working dir as additions. Otherwise ignore them.</param>
        /// <param name="explicitPathsOptions">
        /// If set, the passed <paramref name="paths"/> will be treated as explicit paths.
        /// Use these options to determine how unmatched explicit paths should be handled.
        /// </param>
        /// <param name="compareOptions">Additional options to define patch generation behavior.</param>
        /// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or
        /// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam>
        /// <returns>A <typeparamref name="T"/> containing the changes between the working directory and the index.</returns>
        public virtual T Compare<T>(IEnumerable<string> paths = null, bool includeUntracked = false, ExplicitPathsOptions explicitPathsOptions = null,
            CompareOptions compareOptions = null) where T : class
        {
            return Compare<T>(includeUntracked ? DiffModifiers.IncludeUntracked : DiffModifiers.None, paths, explicitPathsOptions);
        }

        internal virtual T Compare<T>(DiffModifiers diffOptions, IEnumerable<string> paths = null,
                                     ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) where T : class
        {
            Func<DiffSafeHandle, object> builder;

            if (!ChangesBuilders.TryGetValue(typeof (T), out builder))
            {
                throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture,
                    "Unexpected type '{0}' passed to Compare. Supported values are either '{1}' or '{2}'.", typeof (T),
                    typeof (TreeChanges), typeof (Patch)));
            }

            var comparer = WorkdirToIndex(repo);

            if (explicitPathsOptions != null)
            {
                diffOptions |= DiffModifiers.DisablePathspecMatch;

                if (explicitPathsOptions.ShouldFailOnUnmatchedPath ||
                    explicitPathsOptions.OnUnmatchedPath != null)
                {
                    diffOptions |= DiffModifiers.IncludeUnmodified;
                }
            }

            using (DiffSafeHandle diff = BuildDiffList(null, null, comparer,
                diffOptions, paths, explicitPathsOptions, compareOptions))
            {
                return (T)builder(diff);
            }
        }

        internal delegate DiffSafeHandle TreeComparisonHandleRetriever(ObjectId oldTreeId, ObjectId newTreeId, GitDiffOptions options);

        private static TreeComparisonHandleRetriever TreeToTree(Repository repo)
        {
            return (oh, nh, o) => Proxy.git_diff_tree_to_tree(repo.Handle, oh, nh, o);
        }

        private static TreeComparisonHandleRetriever WorkdirToIndex(Repository repo)
        {
            return (oh, nh, o) => Proxy.git_diff_index_to_workdir(repo.Handle, repo.Index.Handle, o);
        }

        private static TreeComparisonHandleRetriever WorkdirToTree(Repository repo)
        {
            return (oh, nh, o) => Proxy.git_diff_tree_to_workdir(repo.Handle, oh, o);
        }

        private static TreeComparisonHandleRetriever WorkdirAndIndexToTree(Repository repo)
        {
            TreeComparisonHandleRetriever comparisonHandleRetriever = (oh, nh, o) =>
            {
                DiffSafeHandle diff = null, diff2 = null;

                try
                {
                    diff = Proxy.git_diff_tree_to_index(repo.Handle, repo.Index.Handle, oh, o);
                    diff2 = Proxy.git_diff_index_to_workdir(repo.Handle, repo.Index.Handle, o);
                    Proxy.git_diff_merge(diff, diff2);
                }
                catch
                {
                    diff.SafeDispose();
                    throw;
                }
                finally
                {
                    diff2.SafeDispose();
                }

                return diff;
            };

            return comparisonHandleRetriever;
        }

        private static TreeComparisonHandleRetriever IndexToTree(Repository repo)
        {
            return (oh, nh, o) => Proxy.git_diff_tree_to_index(repo.Handle, repo.Index.Handle, oh, o);
        }

        private DiffSafeHandle BuildDiffList(ObjectId oldTreeId, ObjectId newTreeId, TreeComparisonHandleRetriever comparisonHandleRetriever,
            DiffModifiers diffOptions, IEnumerable<string> paths, ExplicitPathsOptions explicitPathsOptions,
            CompareOptions compareOptions)
        {
            var matchedPaths = new MatchedPathsAggregator();
            var filePaths = repo.ToFilePaths(paths);

            using (GitDiffOptions options = BuildOptions(diffOptions, filePaths, matchedPaths, compareOptions))
            {
                var diffList = comparisonHandleRetriever(oldTreeId, newTreeId, options);

                try
                {
                    if (explicitPathsOptions != null)
                    {
                        DispatchUnmatchedPaths(explicitPathsOptions, filePaths, matchedPaths);
                    }
                }
                catch
                {
                    diffList.Dispose();
                    throw;
                }

                DetectRenames(diffList, compareOptions);

                return diffList;
            }
        }

        private void DetectRenames(DiffSafeHandle diffList, CompareOptions compareOptions)
        {
            var similarityOptions = (compareOptions == null) ? null : compareOptions.Similarity;
            if (similarityOptions == null ||
                similarityOptions.RenameDetectionMode == RenameDetectionMode.Default)
            {
                Proxy.git_diff_find_similar(diffList, null);
                return;
            }

            if (similarityOptions.RenameDetectionMode == RenameDetectionMode.None)
            {
                return;
            }

            var opts = new GitDiffFindOptions
            {
                RenameThreshold = (ushort)similarityOptions.RenameThreshold,
                RenameFromRewriteThreshold = (ushort)similarityOptions.RenameFromRewriteThreshold,
                CopyThreshold = (ushort)similarityOptions.CopyThreshold,
                BreakRewriteThreshold = (ushort)similarityOptions.BreakRewriteThreshold,
                RenameLimit = (UIntPtr)similarityOptions.RenameLimit,
            };

            switch (similarityOptions.RenameDetectionMode)
            {
                case RenameDetectionMode.Exact:
                    opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_EXACT_MATCH_ONLY |
                                 GitDiffFindFlags.GIT_DIFF_FIND_RENAMES |
                                 GitDiffFindFlags.GIT_DIFF_FIND_COPIES |
                                 GitDiffFindFlags.GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED;
                    break;
                case RenameDetectionMode.Renames:
                    opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES;
                    break;
                case RenameDetectionMode.Copies:
                    opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES |
                                 GitDiffFindFlags.GIT_DIFF_FIND_COPIES;
                    break;
                case RenameDetectionMode.CopiesHarder:
                    opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES |
                                 GitDiffFindFlags.GIT_DIFF_FIND_COPIES |
                                 GitDiffFindFlags.GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED;
                    break;
            }

            if (!compareOptions.IncludeUnmodified)
            {
                opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_REMOVE_UNMODIFIED;
            }

            switch (similarityOptions.WhitespaceMode)
            {
                case WhitespaceMode.DontIgnoreWhitespace:
                    opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_DONT_IGNORE_WHITESPACE;
                    break;
                case WhitespaceMode.IgnoreLeadingWhitespace:
                    opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_IGNORE_LEADING_WHITESPACE;
                    break;
                case WhitespaceMode.IgnoreAllWhitespace:
                    opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_IGNORE_WHITESPACE;
                    break;
            }

            Proxy.git_diff_find_similar(diffList, opts);
        }

        private static void DispatchUnmatchedPaths(ExplicitPathsOptions explicitPathsOptions,
                                                       IEnumerable<FilePath> filePaths,
                                                       IEnumerable<FilePath> matchedPaths)
        {
            List<FilePath> unmatchedPaths = (filePaths != null ?
                filePaths.Except(matchedPaths) : Enumerable.Empty<FilePath>()).ToList();

            if (!unmatchedPaths.Any())
            {
                return;
            }

            if (explicitPathsOptions.OnUnmatchedPath != null)
            {
                unmatchedPaths.ForEach(filePath => explicitPathsOptions.OnUnmatchedPath(filePath.Native));
            }

            if (explicitPathsOptions.ShouldFailOnUnmatchedPath)
            {
                throw new UnmatchedPathException(BuildUnmatchedPathsMessage(unmatchedPaths));
            }
        }

        private static string BuildUnmatchedPathsMessage(List<FilePath> unmatchedPaths)
        {
            var message = new StringBuilder("There were some unmatched paths:" + Environment.NewLine);
            unmatchedPaths.ForEach(filePath => message.AppendFormat("- {0}{1}", filePath.Native, Environment.NewLine));

            return message.ToString();
        }
    }
}