From 284493e995276e9914fa441a7debbb87e3d89885 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 14:24:15 +0000 Subject: [PATCH 01/18] Update all projects to use C# 7.3 --- GitDiffMargin.Commands/GitDiffMargin.Commands.csproj | 1 + GitDiffMargin.Extension/GitDiffMargin.Extension.csproj | 1 + .../GitDiffMargin.LegacyCommands.csproj | 1 + GitDiffMargin.Unit.Tests/GitDiffMargin.Unit.Tests.csproj | 1 + GitDiffMargin/GitDiffMargin.csproj | 3 +-- 5 files changed, 5 insertions(+), 2 deletions(-) diff --git a/GitDiffMargin.Commands/GitDiffMargin.Commands.csproj b/GitDiffMargin.Commands/GitDiffMargin.Commands.csproj index 387a29e..3478af2 100644 --- a/GitDiffMargin.Commands/GitDiffMargin.Commands.csproj +++ b/GitDiffMargin.Commands/GitDiffMargin.Commands.csproj @@ -21,6 +21,7 @@ DEBUG;TRACE prompt 4 + 7.3 pdbonly diff --git a/GitDiffMargin.Extension/GitDiffMargin.Extension.csproj b/GitDiffMargin.Extension/GitDiffMargin.Extension.csproj index 34a73f0..f555772 100644 --- a/GitDiffMargin.Extension/GitDiffMargin.Extension.csproj +++ b/GitDiffMargin.Extension/GitDiffMargin.Extension.csproj @@ -26,6 +26,7 @@ DEBUG;TRACE prompt 4 + 7.3 pdbonly diff --git a/GitDiffMargin.LegacyCommands/GitDiffMargin.LegacyCommands.csproj b/GitDiffMargin.LegacyCommands/GitDiffMargin.LegacyCommands.csproj index 657b4eb..7a65cd0 100644 --- a/GitDiffMargin.LegacyCommands/GitDiffMargin.LegacyCommands.csproj +++ b/GitDiffMargin.LegacyCommands/GitDiffMargin.LegacyCommands.csproj @@ -20,6 +20,7 @@ DEBUG;TRACE prompt 4 + 7.3 pdbonly diff --git a/GitDiffMargin.Unit.Tests/GitDiffMargin.Unit.Tests.csproj b/GitDiffMargin.Unit.Tests/GitDiffMargin.Unit.Tests.csproj index 245fb0b..52c047e 100644 --- a/GitDiffMargin.Unit.Tests/GitDiffMargin.Unit.Tests.csproj +++ b/GitDiffMargin.Unit.Tests/GitDiffMargin.Unit.Tests.csproj @@ -24,6 +24,7 @@ prompt 4 false + 7.3 pdbonly diff --git a/GitDiffMargin/GitDiffMargin.csproj b/GitDiffMargin/GitDiffMargin.csproj index 691b25a..572ad33 100644 --- a/GitDiffMargin/GitDiffMargin.csproj +++ b/GitDiffMargin/GitDiffMargin.csproj @@ -31,6 +31,7 @@ prompt 4 false + 7.3 pdbonly @@ -58,10 +59,8 @@ - - - - - - - - - - - - - - - - - - + + + + + Git Diff Margin + Git Diff Margin displays live changes of the currently edited file on Visual Studio 2012+ margin and scroll bar. + https://github.com/laurentkempe/GitDiffMargin + License.md + http://visualstudiogallery.msdn.microsoft.com/cf49cf30-2ca6-4ea0-b7cc-6a8e0dadc1a8 + https://github.com/laurentkempe/GitDiffMargin/releases/tag/v3.8.0 + Resources/GitDiffMargin-Thumb.png + Resources/GitDiffMargin-Preview.png + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/GitDiffMargin.LegacyCommands/LegacyCommandHandlerTextViewCreationListener.cs b/GitDiffMargin.LegacyCommands/LegacyCommandHandlerTextViewCreationListener.cs index a425cc8..216d685 100644 --- a/GitDiffMargin.LegacyCommands/LegacyCommandHandlerTextViewCreationListener.cs +++ b/GitDiffMargin.LegacyCommands/LegacyCommandHandlerTextViewCreationListener.cs @@ -1,22 +1,23 @@ -namespace GitDiffMargin.LegacyCommands -{ - using System.ComponentModel.Composition; - using Microsoft.VisualStudio.Editor; - using Microsoft.VisualStudio.Shell; - using Microsoft.VisualStudio.Text.Editor; - using Microsoft.VisualStudio.TextManager.Interop; - using Microsoft.VisualStudio.Utilities; +using System.ComponentModel.Composition; +using Microsoft.VisualStudio.Editor; +using Microsoft.VisualStudio.Shell; +using Microsoft.VisualStudio.Text.Editor; +using Microsoft.VisualStudio.TextManager.Interop; +using Microsoft.VisualStudio.Utilities; +namespace GitDiffMargin.LegacyCommands +{ [Export(typeof(IVsTextViewCreationListener))] [ContentType("text")] [TextViewRole(PredefinedTextViewRoles.Editable)] internal class LegacyCommandHandlerTextViewCreationListener : IVsTextViewCreationListener { - private readonly SVsServiceProvider _serviceProvider; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; + private readonly SVsServiceProvider _serviceProvider; [ImportingConstructor] - public LegacyCommandHandlerTextViewCreationListener(SVsServiceProvider serviceProvider, IVsEditorAdaptersFactoryService editorAdaptersFactoryService) + public LegacyCommandHandlerTextViewCreationListener(SVsServiceProvider serviceProvider, + IVsEditorAdaptersFactoryService editorAdaptersFactoryService) { _serviceProvider = serviceProvider; _editorAdaptersFactoryService = editorAdaptersFactoryService; @@ -28,9 +29,9 @@ public void VsTextViewCreated(IVsTextView textViewAdapter) if (textView == null) return; - GitDiffMarginCommandHandler filter = new GitDiffMarginCommandHandler(textViewAdapter, _editorAdaptersFactoryService, textView); + var filter = new GitDiffMarginCommandHandler(textViewAdapter, _editorAdaptersFactoryService, textView); filter.Enabled = true; textView.Properties.AddProperty(typeof(GitDiffMarginCommandHandler), filter); } } -} +} \ No newline at end of file diff --git a/GitDiffMargin.LegacyCommands/Properties/AssemblyInfo.cs b/GitDiffMargin.LegacyCommands/Properties/AssemblyInfo.cs index 280e953..ccab4ad 100644 --- a/GitDiffMargin.LegacyCommands/Properties/AssemblyInfo.cs +++ b/GitDiffMargin.LegacyCommands/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -34,4 +33,4 @@ // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.8.0.0")] [assembly: AssemblyFileVersion("3.8.0.0")] -[assembly: AssemblyInformationalVersion("3.8.0.0")] +[assembly: AssemblyInformationalVersion("3.8.0.0")] \ No newline at end of file diff --git a/GitDiffMargin.Unit.Tests/Git/GitDiffParserTests.cs b/GitDiffMargin.Unit.Tests/Git/GitDiffParserTests.cs index 926effc..12b2e21 100644 --- a/GitDiffMargin.Unit.Tests/Git/GitDiffParserTests.cs +++ b/GitDiffMargin.Unit.Tests/Git/GitDiffParserTests.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using GitDiffMargin.Git; using NUnit.Framework; @@ -43,8 +42,8 @@ index b8a4c69..e73b080 100644 + bool IsDependencyThroughReference { get; } */ - private const string FirstGitDiff = -@"diff --git a/skye-editor/Sources/skyeEditor/Core/Model/Dependency/IModelDependency.cs b/skye-editor/Sources/skyeEditor/Core/Model/Dependency/IModelDependency.cs + private const string FirstGitDiff = + @"diff --git a/skye-editor/Sources/skyeEditor/Core/Model/Dependency/IModelDependency.cs b/skye-editor/Sources/skyeEditor/Core/Model/Dependency/IModelDependency.cs index b8a4c69..e73b080 100644 --- a/skye-editor/Sources/skyeEditor/Core/Model/Dependency/IModelDependency.cs +++ b/skye-editor/Sources/skyeEditor/Core/Model/Dependency/IModelDependency.cs @@ -71,8 +70,8 @@ index b8a4c69..e73b080 100644 + bool IsDependencyThroughReference { get; } * "; - private const string SecondGitDiff = -@"diff --git a/skye-editor/Sources/skyeEditor/Core/Model/Dependency/ModelDependency.cs b/skye-editor/Sources/skyeEditor/Core/Model/Dependency/ModelDependency.cs + private const string SecondGitDiff = + @"diff --git a/skye-editor/Sources/skyeEditor/Core/Model/Dependency/ModelDependency.cs b/skye-editor/Sources/skyeEditor/Core/Model/Dependency/ModelDependency.cs index 157e930..571aa23 100644 --- a/skye-editor/Sources/skyeEditor/Core/Model/Dependency/ModelDependency.cs +++ b/skye-editor/Sources/skyeEditor/Core/Model/Dependency/ModelDependency.cs @@ -114,8 +113,8 @@ index 157e930..571aa23 100644 private const string EmptyGitDiff = ""; - private const string ThirdGitDiff = -@"diff --git a/README.md b/README.md + private const string ThirdGitDiff = + @"diff --git a/README.md b/README.md index 8bb01f5..51495f9 100644 --- a/README.md +++ b/README.md @@ -124,8 +123,8 @@ index 8bb01f5..51495f9 100644 +# Hubot 2 "; - private const string DiffOfADeleteOfThreeLines = -@"diff --git a/note.txt b/note.txt + private const string DiffOfADeleteOfThreeLines = + @"diff --git a/note.txt b/note.txt index e91ba58..e2dbef0 100644 --- a/note.txt +++ b/note.txt @@ -134,8 +133,8 @@ index e91ba58..e2dbef0 100644 -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor;"; - private const string DiffFromLibGit = -@"diff --git a/ConsoleApplication1/Class1.cs b/ConsoleApplication1/Class1.cs + private const string DiffFromLibGit = + @"diff --git a/ConsoleApplication1/Class1.cs b/ConsoleApplication1/Class1.cs index 6f4c525..a42139b 100644 --- a/ConsoleApplication1/Class1.cs +++ b/ConsoleApplication1/Class1.cs @@ -156,270 +155,274 @@ index 6f4c525..a42139b 100644 "; [Test] - public void Parse_DiffFromLibGit_Expect5HunkRangeInfos() + public void GetHunkNewFile_DeleteDiff_ExpectHunkNewFile() { //Arrange - var gitDiffParser = new GitDiffParser(DiffFromLibGit, 0); - + var gitDiffParser = new GitDiffParser(DiffOfADeleteOfThreeLines, 0); + //Act - var hunkRangeInfos = gitDiffParser.Parse().ToList(); + var hunkOriginalFile = + gitDiffParser.GetHunkOriginalFile(gitDiffParser.GetUnifiedFormatHunkLines().First().Item1); //Assert - hunkRangeInfos.Count.ShouldBe(5); + hunkOriginalFile.ShouldBe("7,3"); } [Test] - public void Parse_DiffFromLibGit_ExpectFirstHunkRangeToBeDeletion() + public void GetHunkNewFile_WithOneHunk_ExpectHunkNewFile() { //Arrange - var gitDiffParser = new GitDiffParser(DiffFromLibGit, 0); - + var gitDiffParser = new GitDiffParser(FirstGitDiff, 0); + //Act - var hunkRangeInfos = gitDiffParser.Parse().ToList(); + var hunkOriginalFile = + gitDiffParser.GetHunkOriginalFile(gitDiffParser.GetUnifiedFormatHunkLines().First().Item1); //Assert - hunkRangeInfos[0].IsDeletion.ShouldBe(true); - hunkRangeInfos[0].IsAddition.ShouldBe(false); - hunkRangeInfos[0].IsModification.ShouldBe(false); + hunkOriginalFile.ShouldBe("41,0"); } [Test] - public void Parse_DiffFromLibGit_ExpectSecondHunkRangeToBeModification() + public void GetHunkOriginalFile_DeleteDiff_ExpectHunkOriginalFile() { //Arrange - var gitDiffParser = new GitDiffParser(DiffFromLibGit, 0); - + var gitDiffParser = new GitDiffParser(DiffOfADeleteOfThreeLines, 0); + //Act - var hunkRangeInfos = gitDiffParser.Parse().ToList(); + var hunkOriginalFile = + gitDiffParser.GetHunkNewFile(gitDiffParser.GetUnifiedFormatHunkLines().First().Item1); //Assert - hunkRangeInfos[1].IsDeletion.ShouldBe(false); - hunkRangeInfos[1].IsAddition.ShouldBe(false); - hunkRangeInfos[1].IsModification.ShouldBe(true); + hunkOriginalFile.ShouldBe("6,0"); } [Test] - public void Parse_DiffFromLibGit_ExpectSecondHunkRangeOriginalText() + public void GetHunkOriginalFile_WithOneHunk_ExpectHunkOriginalFile() { //Arrange - var gitDiffParser = new GitDiffParser(DiffFromLibGit, 0); - + var gitDiffParser = new GitDiffParser(FirstGitDiff, 0); + //Act - var hunkRangeInfos = gitDiffParser.Parse().ToList(); + var hunkOriginalFile = + gitDiffParser.GetHunkNewFile(gitDiffParser.GetUnifiedFormatHunkLines().First().Item1); //Assert - hunkRangeInfos[1].OriginalText.ShouldBe(new List {" class Class1"}); + hunkOriginalFile.ShouldBe("42,20"); } [Test] - public void Parse_DiffFromLibGit_ExpectThirdHunkRangeToBeAddition() + public void GetUnifiedFormatHunkLine_DeleteDiff_ExpectedHunkLine() { //Arrange - var gitDiffParser = new GitDiffParser(DiffFromLibGit, 0); - + var gitDiffParser = new GitDiffParser(DiffOfADeleteOfThreeLines, 0); + //Act - var hunkRangeInfos = gitDiffParser.Parse().ToList(); + var unifiedFormatHunk = gitDiffParser.GetUnifiedFormatHunkLines().ToList(); //Assert - hunkRangeInfos[2].IsDeletion.ShouldBe(false); - hunkRangeInfos[2].IsAddition.ShouldBe(true); - hunkRangeInfos[2].IsModification.ShouldBe(false); + unifiedFormatHunk[0].Item1.ShouldBe("@@ -7,3 +6,0 @@ using GitDiffMargin.Git;"); } [Test] - public void Parse_DiffFromLibGit_ExpectFourthHunkRangeToBeDeletion() + public void GetUnifiedFormatHunkLine_WithOneHunk_ExpectHunkLine() { //Arrange - var gitDiffParser = new GitDiffParser(DiffFromLibGit, 0); - + var gitDiffParser = new GitDiffParser(FirstGitDiff, 0); + //Act - var hunkRangeInfos = gitDiffParser.Parse().ToList(); + var unifiedFormatHunk = gitDiffParser.GetUnifiedFormatHunkLines().ToList(); //Assert - hunkRangeInfos[3].IsDeletion.ShouldBe(true); - hunkRangeInfos[3].IsAddition.ShouldBe(false); - hunkRangeInfos[3].IsModification.ShouldBe(false); + unifiedFormatHunk[0].Item1.ShouldBe("@@ -41,0 +42,20 @@ namespace skyeEditor.Core.Model.Dependency"); } [Test] - public void Parse_DiffFromLibGit_ExpectFifthHunkRangeToBeAddition() + public void GetUnifiedFormatHunkLine_WithTwoHunk_ExpectHunkLine() { //Arrange - var gitDiffParser = new GitDiffParser(DiffFromLibGit, 0); - + var gitDiffParser = new GitDiffParser(SecondGitDiff, 0); + //Act - var hunkRangeInfos = gitDiffParser.Parse().ToList(); + var unifiedFormatHunk = gitDiffParser.GetUnifiedFormatHunkLines().ToList(); //Assert - hunkRangeInfos[4].IsDeletion.ShouldBe(false); - hunkRangeInfos[4].IsAddition.ShouldBe(true); - hunkRangeInfos[4].IsModification.ShouldBe(false); + unifiedFormatHunk[0].Item1.ShouldBe("@@ -68,2 +67,0 @@ namespace skyeEditor.Core.Model.Dependency"); + unifiedFormatHunk[1].Item1.ShouldBe("@@ -170,0 +169,27 @@ namespace skyeEditor.Core.Model.Dependency"); + unifiedFormatHunk[2].Item1.ShouldBe("@@ -185,2 +209,0 @@ namespace skyeEditor.Core.Model.Dependency"); } [Test] - public void Parse_EmptyGitDiff_Expect0HunkRangeInfos() + public void Parse_DiffFromLibGit_Expect5HunkRangeInfos() { //Arrange - var gitDiffParser = new GitDiffParser(EmptyGitDiff, 0); - + var gitDiffParser = new GitDiffParser(DiffFromLibGit, 0); + //Act var hunkRangeInfos = gitDiffParser.Parse().ToList(); //Assert - hunkRangeInfos.Count.ShouldBe(0); + hunkRangeInfos.Count.ShouldBe(5); } [Test] - public void Parse_WithOneHunk_ExpectHunkRanges() + public void Parse_DiffFromLibGit_ExpectFifthHunkRangeToBeAddition() { //Arrange - var gitDiffParser = new GitDiffParser(FirstGitDiff, 0); - + var gitDiffParser = new GitDiffParser(DiffFromLibGit, 0); + //Act - var hunkRanges = gitDiffParser.Parse().ToList(); + var hunkRangeInfos = gitDiffParser.Parse().ToList(); //Assert - hunkRanges[0].OriginalHunkRange.StartingLineNumber.ShouldBe(40); - hunkRanges[0].OriginalHunkRange.NumberOfLines.ShouldBe(0); - hunkRanges[0].NewHunkRange.StartingLineNumber.ShouldBe(41); - hunkRanges[0].NewHunkRange.NumberOfLines.ShouldBe(20); + hunkRangeInfos[4].IsDeletion.ShouldBe(false); + hunkRangeInfos[4].IsAddition.ShouldBe(true); + hunkRangeInfos[4].IsModification.ShouldBe(false); } - + [Test] - public void Parse_WithOneHunkWithoutLineCount_ExpectHunkRanges() + public void Parse_DiffFromLibGit_ExpectFirstHunkRangeToBeDeletion() { //Arrange - var gitDiffParser = new GitDiffParser(ThirdGitDiff, 0); - + var gitDiffParser = new GitDiffParser(DiffFromLibGit, 0); + //Act - var hunkRanges = gitDiffParser.Parse().ToList(); + var hunkRangeInfos = gitDiffParser.Parse().ToList(); //Assert - hunkRanges[0].OriginalHunkRange.StartingLineNumber.ShouldBe(0); - hunkRanges[0].OriginalHunkRange.NumberOfLines.ShouldBe(1); - hunkRanges[0].NewHunkRange.StartingLineNumber.ShouldBe(0); - hunkRanges[0].NewHunkRange.NumberOfLines.ShouldBe(1); + hunkRangeInfos[0].IsDeletion.ShouldBe(true); + hunkRangeInfos[0].IsAddition.ShouldBe(false); + hunkRangeInfos[0].IsModification.ShouldBe(false); } [Test] - public void Parse_WithThreeHunk_ExpectHunkRanges() + public void Parse_DiffFromLibGit_ExpectFourthHunkRangeToBeDeletion() { //Arrange - var gitDiffParser = new GitDiffParser(SecondGitDiff, 0); - + var gitDiffParser = new GitDiffParser(DiffFromLibGit, 0); + //Act - var hunkRanges = gitDiffParser.Parse().ToList(); + var hunkRangeInfos = gitDiffParser.Parse().ToList(); //Assert - hunkRanges[0].OriginalHunkRange.StartingLineNumber.ShouldBe(67); - hunkRanges[0].OriginalHunkRange.NumberOfLines.ShouldBe(2); - hunkRanges[0].NewHunkRange.StartingLineNumber.ShouldBe(66); - hunkRanges[0].NewHunkRange.NumberOfLines.ShouldBe(0); - - hunkRanges[1].OriginalHunkRange.StartingLineNumber.ShouldBe(169); - hunkRanges[1].OriginalHunkRange.NumberOfLines.ShouldBe(0); - hunkRanges[1].NewHunkRange.StartingLineNumber.ShouldBe(168); - hunkRanges[1].NewHunkRange.NumberOfLines.ShouldBe(27); - - hunkRanges[2].OriginalHunkRange.StartingLineNumber.ShouldBe(184); - hunkRanges[2].OriginalHunkRange.NumberOfLines.ShouldBe(2); - hunkRanges[2].NewHunkRange.StartingLineNumber.ShouldBe(208); - hunkRanges[2].NewHunkRange.NumberOfLines.ShouldBe(0); + hunkRangeInfos[3].IsDeletion.ShouldBe(true); + hunkRangeInfos[3].IsAddition.ShouldBe(false); + hunkRangeInfos[3].IsModification.ShouldBe(false); } [Test] - public void GetUnifiedFormatHunkLine_WithOneHunk_ExpectHunkLine() + public void Parse_DiffFromLibGit_ExpectSecondHunkRangeOriginalText() { //Arrange - var gitDiffParser = new GitDiffParser(FirstGitDiff, 0); - + var gitDiffParser = new GitDiffParser(DiffFromLibGit, 0); + //Act - var unifiedFormatHunk = gitDiffParser.GetUnifiedFormatHunkLines().ToList(); + var hunkRangeInfos = gitDiffParser.Parse().ToList(); //Assert - unifiedFormatHunk[0].Item1.ShouldBe("@@ -41,0 +42,20 @@ namespace skyeEditor.Core.Model.Dependency"); + hunkRangeInfos[1].OriginalText.ShouldBe(new List {" class Class1"}); } [Test] - public void GetUnifiedFormatHunkLine_DeleteDiff_ExpectedHunkLine() + public void Parse_DiffFromLibGit_ExpectSecondHunkRangeToBeModification() { //Arrange - var gitDiffParser = new GitDiffParser(DiffOfADeleteOfThreeLines, 0); + var gitDiffParser = new GitDiffParser(DiffFromLibGit, 0); //Act - var unifiedFormatHunk = gitDiffParser.GetUnifiedFormatHunkLines().ToList(); + var hunkRangeInfos = gitDiffParser.Parse().ToList(); //Assert - unifiedFormatHunk[0].Item1.ShouldBe("@@ -7,3 +6,0 @@ using GitDiffMargin.Git;"); + hunkRangeInfos[1].IsDeletion.ShouldBe(false); + hunkRangeInfos[1].IsAddition.ShouldBe(false); + hunkRangeInfos[1].IsModification.ShouldBe(true); } [Test] - public void GetUnifiedFormatHunkLine_WithTwoHunk_ExpectHunkLine() + public void Parse_DiffFromLibGit_ExpectThirdHunkRangeToBeAddition() { //Arrange - var gitDiffParser = new GitDiffParser(SecondGitDiff, 0); - + var gitDiffParser = new GitDiffParser(DiffFromLibGit, 0); + //Act - List>> unifiedFormatHunk = gitDiffParser.GetUnifiedFormatHunkLines().ToList(); + var hunkRangeInfos = gitDiffParser.Parse().ToList(); //Assert - unifiedFormatHunk[0].Item1.ShouldBe("@@ -68,2 +67,0 @@ namespace skyeEditor.Core.Model.Dependency"); - unifiedFormatHunk[1].Item1.ShouldBe("@@ -170,0 +169,27 @@ namespace skyeEditor.Core.Model.Dependency"); - unifiedFormatHunk[2].Item1.ShouldBe("@@ -185,2 +209,0 @@ namespace skyeEditor.Core.Model.Dependency"); + hunkRangeInfos[2].IsDeletion.ShouldBe(false); + hunkRangeInfos[2].IsAddition.ShouldBe(true); + hunkRangeInfos[2].IsModification.ShouldBe(false); } [Test] - public void GetHunkOriginalFile_WithOneHunk_ExpectHunkOriginalFile() + public void Parse_EmptyGitDiff_Expect0HunkRangeInfos() { //Arrange - var gitDiffParser = new GitDiffParser(FirstGitDiff, 0); - + var gitDiffParser = new GitDiffParser(EmptyGitDiff, 0); + //Act - string hunkOriginalFile = gitDiffParser.GetHunkNewFile(gitDiffParser.GetUnifiedFormatHunkLines().First().Item1); + var hunkRangeInfos = gitDiffParser.Parse().ToList(); //Assert - hunkOriginalFile.ShouldBe("42,20"); + hunkRangeInfos.Count.ShouldBe(0); } [Test] - public void GetHunkNewFile_WithOneHunk_ExpectHunkNewFile() + public void Parse_WithOneHunk_ExpectHunkRanges() { //Arrange var gitDiffParser = new GitDiffParser(FirstGitDiff, 0); - + //Act - string hunkOriginalFile = gitDiffParser.GetHunkOriginalFile(gitDiffParser.GetUnifiedFormatHunkLines().First().Item1); + var hunkRanges = gitDiffParser.Parse().ToList(); //Assert - hunkOriginalFile.ShouldBe("41,0"); + hunkRanges[0].OriginalHunkRange.StartingLineNumber.ShouldBe(40); + hunkRanges[0].OriginalHunkRange.NumberOfLines.ShouldBe(0); + hunkRanges[0].NewHunkRange.StartingLineNumber.ShouldBe(41); + hunkRanges[0].NewHunkRange.NumberOfLines.ShouldBe(20); } [Test] - public void GetHunkOriginalFile_DeleteDiff_ExpectHunkOriginalFile() + public void Parse_WithOneHunkWithoutLineCount_ExpectHunkRanges() { //Arrange - var gitDiffParser = new GitDiffParser(DiffOfADeleteOfThreeLines, 0); + var gitDiffParser = new GitDiffParser(ThirdGitDiff, 0); //Act - var hunkOriginalFile = gitDiffParser.GetHunkNewFile(gitDiffParser.GetUnifiedFormatHunkLines().First().Item1); + var hunkRanges = gitDiffParser.Parse().ToList(); //Assert - hunkOriginalFile.ShouldBe("6,0"); + hunkRanges[0].OriginalHunkRange.StartingLineNumber.ShouldBe(0); + hunkRanges[0].OriginalHunkRange.NumberOfLines.ShouldBe(1); + hunkRanges[0].NewHunkRange.StartingLineNumber.ShouldBe(0); + hunkRanges[0].NewHunkRange.NumberOfLines.ShouldBe(1); } [Test] - public void GetHunkNewFile_DeleteDiff_ExpectHunkNewFile() + public void Parse_WithThreeHunk_ExpectHunkRanges() { //Arrange - var gitDiffParser = new GitDiffParser(DiffOfADeleteOfThreeLines, 0); + var gitDiffParser = new GitDiffParser(SecondGitDiff, 0); //Act - var hunkOriginalFile = gitDiffParser.GetHunkOriginalFile(gitDiffParser.GetUnifiedFormatHunkLines().First().Item1); + var hunkRanges = gitDiffParser.Parse().ToList(); //Assert - hunkOriginalFile.ShouldBe("7,3"); + hunkRanges[0].OriginalHunkRange.StartingLineNumber.ShouldBe(67); + hunkRanges[0].OriginalHunkRange.NumberOfLines.ShouldBe(2); + hunkRanges[0].NewHunkRange.StartingLineNumber.ShouldBe(66); + hunkRanges[0].NewHunkRange.NumberOfLines.ShouldBe(0); + + hunkRanges[1].OriginalHunkRange.StartingLineNumber.ShouldBe(169); + hunkRanges[1].OriginalHunkRange.NumberOfLines.ShouldBe(0); + hunkRanges[1].NewHunkRange.StartingLineNumber.ShouldBe(168); + hunkRanges[1].NewHunkRange.NumberOfLines.ShouldBe(27); + + hunkRanges[2].OriginalHunkRange.StartingLineNumber.ShouldBe(184); + hunkRanges[2].OriginalHunkRange.NumberOfLines.ShouldBe(2); + hunkRanges[2].NewHunkRange.StartingLineNumber.ShouldBe(208); + hunkRanges[2].NewHunkRange.NumberOfLines.ShouldBe(0); } } // ReSharper restore InconsistentNaming -} +} \ No newline at end of file diff --git a/GitDiffMargin.Unit.Tests/Git/HunkRangeInfoTests.cs b/GitDiffMargin.Unit.Tests/Git/HunkRangeInfoTests.cs index 53d9b27..47747f8 100644 --- a/GitDiffMargin.Unit.Tests/Git/HunkRangeInfoTests.cs +++ b/GitDiffMargin.Unit.Tests/Git/HunkRangeInfoTests.cs @@ -19,16 +19,17 @@ public HunkRangeInfoTests(int contextLines) _contextLines = contextLines; } - private readonly int _contextLines = 0; + private readonly int _contextLines; [Test] public void IsAddition_AllDiffLinesWithStartsWithPlusSign_ExpectedTrue() { //Arrange - var hunkRangeInfo = new HunkRangeInfo(new HunkRange("-41,0", _contextLines), new HunkRange("+42,20", _contextLines), new List { "+ ", "+ " }.ToArray()); + var hunkRangeInfo = new HunkRangeInfo(new HunkRange("-41,0", _contextLines), + new HunkRange("+42,20", _contextLines), new List {"+ ", "+ "}.ToArray()); //Act - bool isAddition = hunkRangeInfo.IsAddition; + var isAddition = hunkRangeInfo.IsAddition; //Assert isAddition.ShouldBe(true); @@ -38,78 +39,91 @@ public void IsAddition_AllDiffLinesWithStartsWithPlusSign_ExpectedTrue() public void IsAddition_NotAllDiffLinesStartsWithPlusSign_ExpectedFalse() { //Arrange - var hunkRangeInfo = new HunkRangeInfo(new HunkRange("-41,0", _contextLines), new HunkRange("+42,20", _contextLines), new List { "+ ", "- " }.ToArray()); + var hunkRangeInfo = new HunkRangeInfo(new HunkRange("-41,0", _contextLines), + new HunkRange("+42,20", _contextLines), new List {"+ ", "- "}.ToArray()); //Act - bool isAddition = hunkRangeInfo.IsAddition; + var isAddition = hunkRangeInfo.IsAddition; //Assert isAddition.ShouldBe(false); } [Test] - public void IsModification_DiffLinesStartsWithPlusSignAndWithMinus_ExpectedTrue() + public void IsDeletion_3DeletedLines_ExpectTrue() { //Arrange - var hunkRangeInfo = new HunkRangeInfo(new HunkRange("-41,0", _contextLines), new HunkRange("+42,20", _contextLines), new List { "+ ", "- " }.ToArray()); + var hunkRangeInfo = new HunkRangeInfo(new HunkRange("-7,3", _contextLines), + new HunkRange("+6,0", _contextLines), + new List + { + "-using Microsoft.VisualStudio.Shell;", "-using Microsoft.VisualStudio.Text;", + "-using Microsoft.VisualStudio.Text.Editor;" + }.ToArray()); //Act - bool isModification = hunkRangeInfo.IsModification; + var isDeletion = hunkRangeInfo.IsDeletion; //Assert - isModification.ShouldBe(true); + isDeletion.ShouldBe(true); } [Test] - public void OriginalText_1NewLineAnd1OriginalLine_ExpectedOriginalText() + public void IsModification_DiffLinesStartsWithPlusSignAndWithMinus_ExpectedTrue() { //Arrange - var hunkRangeInfo = new HunkRangeInfo(new HunkRange("-41,0", _contextLines), new HunkRange("+42,20", _contextLines), new List { "+New Text", "-Original Text" }.ToArray()); + var hunkRangeInfo = new HunkRangeInfo(new HunkRange("-41,0", _contextLines), + new HunkRange("+42,20", _contextLines), new List {"+ ", "- "}.ToArray()); //Act - string originalText = hunkRangeInfo.OriginalText[0]; + var isModification = hunkRangeInfo.IsModification; //Assert - originalText.ShouldBe("Original Text"); + isModification.ShouldBe(true); } [Test] - public void OriginalText_1NewLineAnd1OriginalLineWithLeadingSpaces_ExpectedOriginalText() + public void OriginalText_1NewLineAnd1OriginalLine_ExpectedOriginalText() { //Arrange - var hunkRangeInfo = new HunkRangeInfo(new HunkRange("-41,0", _contextLines), new HunkRange("+42,20", _contextLines), new List { "+ New Text", "- Original Text" }.ToArray()); + var hunkRangeInfo = new HunkRangeInfo(new HunkRange("-41,0", _contextLines), + new HunkRange("+42,20", _contextLines), new List {"+New Text", "-Original Text"}.ToArray()); //Act - string originalText = hunkRangeInfo.OriginalText[0]; + var originalText = hunkRangeInfo.OriginalText[0]; //Assert - originalText.ShouldBe(" Original Text"); + originalText.ShouldBe("Original Text"); } [Test] - public void OriginalText_1NewLineAnd1OriginalLineWithLeadingSpacesAndInvertedOrder_ExpectedOriginalText() + public void OriginalText_1NewLineAnd1OriginalLineWithLeadingSpaces_ExpectedOriginalText() { //Arrange - var hunkRangeInfo = new HunkRangeInfo(new HunkRange("-18", _contextLines), new HunkRange("+18", _contextLines), new List { "- it++; // this is just a comment", "+ it--;" }.ToArray()); + var hunkRangeInfo = new HunkRangeInfo(new HunkRange("-41,0", _contextLines), + new HunkRange("+42,20", _contextLines), + new List {"+ New Text", "- Original Text"}.ToArray()); //Act - var originalText = hunkRangeInfo.OriginalText; + var originalText = hunkRangeInfo.OriginalText[0]; //Assert - originalText[0].ShouldBe(" it++; // this is just a comment"); + originalText.ShouldBe(" Original Text"); } [Test] - public void IsDeletion_3DeletedLines_ExpectTrue() + public void OriginalText_1NewLineAnd1OriginalLineWithLeadingSpacesAndInvertedOrder_ExpectedOriginalText() { //Arrange - var hunkRangeInfo = new HunkRangeInfo(new HunkRange("-7,3", _contextLines), new HunkRange("+6,0", _contextLines), new List { "-using Microsoft.VisualStudio.Shell;", "-using Microsoft.VisualStudio.Text;", "-using Microsoft.VisualStudio.Text.Editor;" }.ToArray()); + var hunkRangeInfo = new HunkRangeInfo(new HunkRange("-18", _contextLines), + new HunkRange("+18", _contextLines), + new List {"- it++; // this is just a comment", "+ it--;"}.ToArray()); //Act - var isDeletion = hunkRangeInfo.IsDeletion; + var originalText = hunkRangeInfo.OriginalText; //Assert - isDeletion.ShouldBe(true); + originalText[0].ShouldBe(" it++; // this is just a comment"); } } diff --git a/GitDiffMargin.Unit.Tests/Git/HunkRangeTests.cs b/GitDiffMargin.Unit.Tests/Git/HunkRangeTests.cs index 74e7e89..148b6fb 100644 --- a/GitDiffMargin.Unit.Tests/Git/HunkRangeTests.cs +++ b/GitDiffMargin.Unit.Tests/Git/HunkRangeTests.cs @@ -9,6 +9,18 @@ namespace GitDiffMargin.Unit.Tests.Git [TestFixture] public class HunkRangeTests { + [Test] + public void HunkRange_HunkNewFileWith3AsContextLines_ExpectHunkNewFile() + { + //Arrange + //Act + var hunkRange = new HunkRange(@"12,11", 3); + + //Assert + hunkRange.StartingLineNumber.ShouldBe(14); + hunkRange.NumberOfLines.ShouldBe(5); + } + [Test] public void HunkRange_HunkOriginalFile_ExpectHunkOriginalFile() { @@ -45,18 +57,6 @@ public void HunkRange_ValidHunk_ExpectHunkNewFile() hunkRange.NumberOfLines.ShouldBe(20); } - [Test] - public void HunkRange_HunkNewFileWith3AsContextLines_ExpectHunkNewFile() - { - //Arrange - //Act - var hunkRange = new HunkRange(@"12,11", 3); - - //Assert - hunkRange.StartingLineNumber.ShouldBe(14); - hunkRange.NumberOfLines.ShouldBe(5); - } - [Test] public void NumberOfLines_HunkWithoutLineNumber_ExpectDefaultTo1LineNumber() { @@ -85,4 +85,4 @@ public void StartingLineNumber_HunkWithoutLineNumber_ExpectLineNumber() } // ReSharper restore InconsistentNaming -} +} \ No newline at end of file diff --git a/GitDiffMargin.Unit.Tests/Properties/AssemblyInfo.cs b/GitDiffMargin.Unit.Tests/Properties/AssemblyInfo.cs index a1d43c5..eefc69b 100644 --- a/GitDiffMargin.Unit.Tests/Properties/AssemblyInfo.cs +++ b/GitDiffMargin.Unit.Tests/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -33,4 +32,4 @@ // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/GitDiffMargin/Core/BackgroundParser.cs b/GitDiffMargin/Core/BackgroundParser.cs index 6138314..bb8a1c7 100644 --- a/GitDiffMargin/Core/BackgroundParser.cs +++ b/GitDiffMargin/Core/BackgroundParser.cs @@ -32,20 +32,17 @@ namespace GitDiffMargin.Core { public abstract class BackgroundParser : IDisposable { - private readonly WeakReference _textBuffer; private readonly TaskScheduler _taskScheduler; - private readonly ITextDocumentFactoryService _textDocumentFactoryService; + private readonly WeakReference _textBuffer; private readonly Timer _timer; - - private TimeSpan _reparseDelay; - private DateTimeOffset _lastEdit; private bool _dirty; + private DateTimeOffset _lastEdit; private int _parsing; - private bool _disposed; - public event EventHandler ParseComplete; + private TimeSpan _reparseDelay; - protected BackgroundParser(ITextBuffer textBuffer, TaskScheduler taskScheduler, ITextDocumentFactoryService textDocumentFactoryService) + protected BackgroundParser(ITextBuffer textBuffer, TaskScheduler taskScheduler, + ITextDocumentFactoryService textDocumentFactoryService) { if (textBuffer == null) throw new ArgumentNullException("textBuffer"); @@ -56,7 +53,7 @@ protected BackgroundParser(ITextBuffer textBuffer, TaskScheduler taskScheduler, _textBuffer = new WeakReference(textBuffer); _taskScheduler = taskScheduler; - _textDocumentFactoryService = textDocumentFactoryService; + TextDocumentFactoryService = textDocumentFactoryService; textBuffer.PostChanged += TextBufferPostChanged; @@ -66,32 +63,17 @@ protected BackgroundParser(ITextBuffer textBuffer, TaskScheduler taskScheduler, _lastEdit = DateTimeOffset.MinValue; } - public ITextBuffer TextBuffer - { - get - { - return _textBuffer.Target; - } - } + public ITextBuffer TextBuffer => _textBuffer.Target; - public bool Disposed - { - get - { - return _disposed; - } - } + public bool Disposed { get; private set; } public TimeSpan ReparseDelay { - get - { - return _reparseDelay; - } + get => _reparseDelay; set { - TimeSpan originalDelay = _reparseDelay; + var originalDelay = _reparseDelay; try { _reparseDelay = value; @@ -104,27 +86,17 @@ public TimeSpan ReparseDelay } } + public virtual string Name => string.Empty; + + protected ITextDocumentFactoryService TextDocumentFactoryService { get; } + public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } - public virtual string Name - { - get - { - return string.Empty; - } - } - - protected ITextDocumentFactoryService TextDocumentFactoryService - { - get - { - return _textDocumentFactoryService; - } - } + public event EventHandler ParseComplete; public void RequestParse(bool forceReparse) { @@ -135,14 +107,14 @@ protected virtual void Dispose(bool disposing) { if (disposing) { - ITextBuffer textBuffer = TextBuffer; + var textBuffer = TextBuffer; if (textBuffer != null) textBuffer.PostChanged -= TextBufferPostChanged; _timer.Dispose(); } - _disposed = true; + Disposed = true; } protected abstract void ReParseImpl(); @@ -159,8 +131,8 @@ protected virtual void OnParseComplete(ParseResultEventArgs e) protected void MarkDirty(bool resetTimer) { - this._dirty = true; - this._lastEdit = DateTimeOffset.Now; + _dirty = true; + _lastEdit = DateTimeOffset.Now; if (resetTimer) _timer.Change(_reparseDelay, _reparseDelay); @@ -191,10 +163,10 @@ private void TryReparse(bool forceReparse) return; if (Interlocked.CompareExchange(ref _parsing, 1, 0) == 0) - { try { - Task task = Task.Factory.StartNew(ReParse, CancellationToken.None, TaskCreationOptions.None, _taskScheduler); + var task = Task.Factory.StartNew(ReParse, CancellationToken.None, TaskCreationOptions.None, + _taskScheduler); task.ContinueWith(_ => _parsing = 0); } catch @@ -202,7 +174,6 @@ private void TryReparse(bool forceReparse) _parsing = 0; throw; } - } } private void ReParse() @@ -219,4 +190,4 @@ private void ReParse() } } } -} +} \ No newline at end of file diff --git a/GitDiffMargin/Core/DiffParseResultEventArgs.cs b/GitDiffMargin/Core/DiffParseResultEventArgs.cs index 282a51d..dab3406 100644 --- a/GitDiffMargin/Core/DiffParseResultEventArgs.cs +++ b/GitDiffMargin/Core/DiffParseResultEventArgs.cs @@ -15,12 +15,6 @@ public DiffParseResultEventArgs(ITextSnapshot snapshot, TimeSpan elapsedTime, Li _diff = diff; } - public IEnumerable Diff - { - get - { - return _diff; - } - } + public IEnumerable Diff => _diff; } } \ No newline at end of file diff --git a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs index 19bcdf7..22724cb 100644 --- a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs +++ b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs @@ -12,13 +12,14 @@ namespace GitDiffMargin.Core { public class DiffUpdateBackgroundParser : BackgroundParser { - private readonly FileSystemWatcher _watcher; private readonly IGitCommands _commands; - private readonly ITextDocument _textDocument; private readonly ITextBuffer _documentBuffer; private readonly string _originalPath; + private readonly ITextDocument _textDocument; + private readonly FileSystemWatcher _watcher; - internal DiffUpdateBackgroundParser(ITextBuffer textBuffer, ITextBuffer documentBuffer, string originalPath, TaskScheduler taskScheduler, ITextDocumentFactoryService textDocumentFactoryService, IGitCommands commands) + internal DiffUpdateBackgroundParser(ITextBuffer textBuffer, ITextBuffer documentBuffer, string originalPath, + TaskScheduler taskScheduler, ITextDocumentFactoryService textDocumentFactoryService, IGitCommands commands) : base(textBuffer, taskScheduler, textDocumentFactoryService) { _documentBuffer = documentBuffer; @@ -46,6 +47,8 @@ internal DiffUpdateBackgroundParser(ITextBuffer textBuffer, ITextBuffer document } } + public override string Name => "Git Diff Analyzer"; + private void HandleFileSystemChanged(object sender, FileSystemEventArgs e) { Action action = @@ -78,18 +81,7 @@ private void ProcessFileSystemChange(FileSystemEventArgs e) private void OnFileActionOccurred(object sender, TextDocumentFileActionEventArgs e) { - if ((e.FileActionType & FileActionTypes.ContentSavedToDisk) != 0) - { - MarkDirty(true); - } - } - - public override string Name - { - get - { - return "Git Diff Analyzer"; - } + if ((e.FileActionType & FileActionTypes.ContentSavedToDisk) != 0) MarkDirty(true); } protected override void ReParseImpl() @@ -119,14 +111,8 @@ protected override void Dispose(bool disposing) if (disposing) { - if (_textDocument != null) - { - _textDocument.FileActionOccurred -= OnFileActionOccurred; - } - if (_watcher != null) - { - _watcher.Dispose(); - } + if (_textDocument != null) _textDocument.FileActionOccurred -= OnFileActionOccurred; + if (_watcher != null) _watcher.Dispose(); } } } diff --git a/GitDiffMargin/Core/HunksChangedEventArgs.cs b/GitDiffMargin/Core/HunksChangedEventArgs.cs index 56781f6..ab55096 100644 --- a/GitDiffMargin/Core/HunksChangedEventArgs.cs +++ b/GitDiffMargin/Core/HunksChangedEventArgs.cs @@ -6,19 +6,11 @@ namespace GitDiffMargin.Core { public class HunksChangedEventArgs : EventArgs { - private readonly IEnumerable _hunks; - public HunksChangedEventArgs(IEnumerable hunks) { - _hunks = hunks; + Hunks = hunks; } - public IEnumerable Hunks - { - get - { - return _hunks; - } - } + public IEnumerable Hunks { get; } } -} +} \ No newline at end of file diff --git a/GitDiffMargin/Core/IMarginCore.cs b/GitDiffMargin/Core/IMarginCore.cs index bb1ad71..f9b0cc0 100644 --- a/GitDiffMargin/Core/IMarginCore.cs +++ b/GitDiffMargin/Core/IMarginCore.cs @@ -9,10 +9,6 @@ namespace GitDiffMargin.Core { internal interface IMarginCore { - event EventHandler BrushesChanged; - - event EventHandler HunksChanged; - IWpfTextView TextView { get; } string OriginalPath { get; } IGitCommands GitCommands { get; } @@ -29,6 +25,9 @@ internal interface IMarginCore double EditorChangeLeft { get; } double EditorChangeWidth { get; } double ScrollChangeWidth { get; } + event EventHandler BrushesChanged; + + event EventHandler HunksChanged; void MoveToChange(int lineNumber); bool RollBack(HunkRangeInfo hunkRangeInfo); ITextDocument GetTextDocument(); diff --git a/GitDiffMargin/Core/MarginCore.cs b/GitDiffMargin/Core/MarginCore.cs index a7c6443..64d483e 100644 --- a/GitDiffMargin/Core/MarginCore.cs +++ b/GitDiffMargin/Core/MarginCore.cs @@ -13,36 +13,37 @@ namespace GitDiffMargin.Core { internal sealed class MarginCore : IMarginCore, IDisposable { - private readonly IWpfTextView _textView; - private readonly IClassificationFormatMap _classificationFormatMap; private readonly IEditorFormatMap _editorFormatMap; - private readonly IGitCommands _gitCommands; private readonly DiffUpdateBackgroundParser _parser; private Brush _additionBrush; - private Brush _modificationBrush; - private Brush _removedBrush; private bool _isDisposed; + private Brush _modificationBrush; + private Brush _removedBrush; - public MarginCore(IWpfTextView textView, string originalPath, ITextDocumentFactoryService textDocumentFactoryService, IClassificationFormatMapService classificationFormatMapService, IEditorFormatMapService editorFormatMapService, IGitCommands gitCommands) + public MarginCore(IWpfTextView textView, string originalPath, + ITextDocumentFactoryService textDocumentFactoryService, + IClassificationFormatMapService classificationFormatMapService, + IEditorFormatMapService editorFormatMapService, IGitCommands gitCommands) { - _textView = textView; + TextView = textView; _classificationFormatMap = classificationFormatMapService.GetClassificationFormatMap(textView); _editorFormatMap = editorFormatMapService.GetEditorFormatMap(textView); _editorFormatMap.FormatMappingChanged += HandleFormatMappingChanged; - _gitCommands = gitCommands; + GitCommands = gitCommands; - _parser = new DiffUpdateBackgroundParser(textView.TextBuffer, textView.TextDataModel.DocumentBuffer, originalPath, TaskScheduler.Default, textDocumentFactoryService, GitCommands); + _parser = new DiffUpdateBackgroundParser(textView.TextBuffer, textView.TextDataModel.DocumentBuffer, + originalPath, TaskScheduler.Default, textDocumentFactoryService, GitCommands); _parser.ParseComplete += HandleParseComplete; _parser.RequestParse(false); - _textView.Closed += (sender, e) => + TextView.Closed += (sender, e) => { _editorFormatMap.FormatMappingChanged -= HandleFormatMappingChanged; _parser.ParseComplete -= HandleParseComplete; @@ -51,27 +52,22 @@ public MarginCore(IWpfTextView textView, string originalPath, ITextDocumentFacto UpdateBrushes(); } - public IWpfTextView TextView + public void Dispose() { - get - { - return _textView; - } - } + if (_isDisposed) + return; - public string OriginalPath - { - get; - } + _isDisposed = true; - public IGitCommands GitCommands - { - get - { - return _gitCommands; - } + _parser.Dispose(); } + public IWpfTextView TextView { get; } + + public string OriginalPath { get; } + + public IGitCommands GitCommands { get; } + public FontFamily FontFamily { get @@ -132,7 +128,7 @@ public Brush Background get { if (_classificationFormatMap.DefaultTextProperties.BackgroundBrushEmpty) - return _textView.Background; + return TextView.Background; return _classificationFormatMap.DefaultTextProperties.BackgroundBrush; } @@ -143,51 +139,23 @@ public Brush Foreground get { if (_classificationFormatMap.DefaultTextProperties.ForegroundBrushEmpty) - return (Brush)Application.Current.Resources[VsBrushes.ToolWindowTextKey]; + return (Brush) Application.Current.Resources[VsBrushes.ToolWindowTextKey]; return _classificationFormatMap.DefaultTextProperties.ForegroundBrush; } } - public Brush AdditionBrush - { - - get - { - return _additionBrush ?? Brushes.Transparent; - } - } + public Brush AdditionBrush => _additionBrush ?? Brushes.Transparent; - public Brush ModificationBrush - { - get - { - return _modificationBrush ?? Brushes.Transparent; - } - } + public Brush ModificationBrush => _modificationBrush ?? Brushes.Transparent; - public Brush RemovedBrush - { - get - { - return _removedBrush ?? Brushes.Transparent; - } - } + public Brush RemovedBrush => _removedBrush ?? Brushes.Transparent; - public double EditorChangeLeft - { - get { return 2.5; } - } + public double EditorChangeLeft => 2.5; - public double EditorChangeWidth - { - get { return 5.0; } - } + public double EditorChangeWidth => 5.0; - public double ScrollChangeWidth - { - get { return 3.0; } - } + public double ScrollChangeWidth => 3.0; public event EventHandler BrushesChanged; @@ -195,84 +163,20 @@ public double ScrollChangeWidth public void MoveToChange(int lineNumber) { - var diffLine = _textView.TextSnapshot.GetLineFromLineNumber(lineNumber); + var diffLine = TextView.TextSnapshot.GetLineFromLineNumber(lineNumber); - _textView.VisualElement.Focus(); - _textView.Caret.MoveTo(diffLine.Start); - _textView.ViewScroller.EnsureSpanVisible(diffLine.ExtentIncludingLineBreak, + TextView.VisualElement.Focus(); + TextView.Caret.MoveTo(diffLine.Start); + TextView.ViewScroller.EnsureSpanVisible(diffLine.ExtentIncludingLineBreak, EnsureSpanVisibleOptions.AlwaysCenter); } - private void CheckBeginInvokeOnUi(Action action) - { - if (_textView.VisualElement.Dispatcher.CheckAccess()) - { - action(); - } - else - { - _textView.VisualElement.Dispatcher.BeginInvoke(action); - } - } - - private void HandleFormatMappingChanged(object sender, FormatItemsEventArgs e) - { - if (e.ChangedItems.Contains(DiffFormatNames.Addition) - || e.ChangedItems.Contains(DiffFormatNames.Modification) - || e.ChangedItems.Contains(DiffFormatNames.Removed)) - { - UpdateBrushes(); - } - } - - private void UpdateBrushes() - { - _additionBrush = GetBrush(_editorFormatMap.GetProperties(DiffFormatNames.Addition)); - _modificationBrush = GetBrush(_editorFormatMap.GetProperties(DiffFormatNames.Modification)); - _removedBrush = GetBrush(_editorFormatMap.GetProperties(DiffFormatNames.Removed)); - OnBrushesChanged(EventArgs.Empty); - } - - private void OnBrushesChanged(EventArgs e) - { - var t = BrushesChanged; - if (t != null) - t(this, e); - } - - private static Brush GetBrush(ResourceDictionary properties) - { - if (properties == null) - return Brushes.Transparent; - - if (properties.Contains(EditorFormatDefinition.BackgroundColorId)) - { - var color = (Color)properties[EditorFormatDefinition.BackgroundColorId]; - var brush = new SolidColorBrush(color); - if (brush.CanFreeze) - { - brush.Freeze(); - } - return brush; - } - if (properties.Contains(EditorFormatDefinition.BackgroundBrushId)) - { - var brush = (Brush)properties[EditorFormatDefinition.BackgroundBrushId]; - if (brush.CanFreeze) - { - brush.Freeze(); - } - return brush; - } - - return Brushes.Transparent; - } public bool RollBack(HunkRangeInfo hunkRangeInfo) { if (hunkRangeInfo.SuppressRollback) return false; - var snapshot = _textView.TextSnapshot; + var snapshot = TextView.TextSnapshot; if (snapshot != snapshot.TextBuffer.CurrentSnapshot) return false; @@ -288,24 +192,27 @@ public bool RollBack(HunkRangeInfo hunkRangeInfo) else { var startLine = snapshot.GetLineFromLineNumber(hunkRangeInfo.NewHunkRange.StartingLineNumber); - var endLine = snapshot.GetLineFromLineNumber(hunkRangeInfo.NewHunkRange.StartingLineNumber + hunkRangeInfo.NewHunkRange.NumberOfLines - 1); + var endLine = snapshot.GetLineFromLineNumber( + hunkRangeInfo.NewHunkRange.StartingLineNumber + hunkRangeInfo.NewHunkRange.NumberOfLines - 1); newSpan = Span.FromBounds(startLine.Start.Position, endLine.EndIncludingLineBreak.Position); } if (hunkRangeInfo.IsAddition) { var startLine = snapshot.GetLineFromLineNumber(hunkRangeInfo.NewHunkRange.StartingLineNumber); - var endLine = snapshot.GetLineFromLineNumber(hunkRangeInfo.NewHunkRange.StartingLineNumber + hunkRangeInfo.NewHunkRange.NumberOfLines - 1); + var endLine = snapshot.GetLineFromLineNumber( + hunkRangeInfo.NewHunkRange.StartingLineNumber + hunkRangeInfo.NewHunkRange.NumberOfLines - 1); edit.Delete(Span.FromBounds(startLine.Start.Position, endLine.EndIncludingLineBreak.Position)); } else { var lineBreak = snapshot.GetLineFromLineNumber(0).GetLineBreakText(); - if (String.IsNullOrEmpty(lineBreak)) + if (string.IsNullOrEmpty(lineBreak)) lineBreak = Environment.NewLine; - var originalText = String.Join(lineBreak, hunkRangeInfo.OriginalText); - if (hunkRangeInfo.NewHunkRange.StartingLineNumber + hunkRangeInfo.NewHunkRange.NumberOfLines != snapshot.LineCount) + var originalText = string.Join(lineBreak, hunkRangeInfo.OriginalText); + if (hunkRangeInfo.NewHunkRange.StartingLineNumber + hunkRangeInfo.NewHunkRange.NumberOfLines != + snapshot.LineCount) originalText += lineBreak; edit.Replace(newSpan, originalText); @@ -320,7 +227,7 @@ public bool RollBack(HunkRangeInfo hunkRangeInfo) public ITextDocument GetTextDocument() { ITextDocument document; - _textView.TextDataModel.DocumentBuffer.Properties.TryGetProperty(typeof(ITextDocument), out document); + TextView.TextDataModel.DocumentBuffer.Properties.TryGetProperty(typeof(ITextDocument), out document); return document; } @@ -329,6 +236,60 @@ public void FocusTextView() TextView.VisualElement.Focus(); } + private void CheckBeginInvokeOnUi(Action action) + { + if (TextView.VisualElement.Dispatcher.CheckAccess()) + action(); + else + TextView.VisualElement.Dispatcher.BeginInvoke(action); + } + + private void HandleFormatMappingChanged(object sender, FormatItemsEventArgs e) + { + if (e.ChangedItems.Contains(DiffFormatNames.Addition) + || e.ChangedItems.Contains(DiffFormatNames.Modification) + || e.ChangedItems.Contains(DiffFormatNames.Removed)) + UpdateBrushes(); + } + + private void UpdateBrushes() + { + _additionBrush = GetBrush(_editorFormatMap.GetProperties(DiffFormatNames.Addition)); + _modificationBrush = GetBrush(_editorFormatMap.GetProperties(DiffFormatNames.Modification)); + _removedBrush = GetBrush(_editorFormatMap.GetProperties(DiffFormatNames.Removed)); + OnBrushesChanged(EventArgs.Empty); + } + + private void OnBrushesChanged(EventArgs e) + { + var t = BrushesChanged; + if (t != null) + t(this, e); + } + + private static Brush GetBrush(ResourceDictionary properties) + { + if (properties == null) + return Brushes.Transparent; + + if (properties.Contains(EditorFormatDefinition.BackgroundColorId)) + { + var color = (Color) properties[EditorFormatDefinition.BackgroundColorId]; + var brush = new SolidColorBrush(color); + if (brush.CanFreeze) brush.Freeze(); + return brush; + } + + if (properties.Contains(EditorFormatDefinition.BackgroundBrushId)) + { + var brush = (Brush) properties[EditorFormatDefinition.BackgroundBrushId]; + if (brush.CanFreeze) brush.Freeze(); + return brush; + } + + return Brushes.Transparent; + } + private void HandleParseComplete(object sender, ParseResultEventArgs e) { var diffResult = e as DiffParseResultEventArgs; @@ -343,15 +304,5 @@ private void OnHunksChanged(IEnumerable hunkRangeInfos) if (t != null) t(this, new HunksChangedEventArgs(hunkRangeInfos)); } - - public void Dispose() - { - if (_isDisposed) - return; - - _isDisposed = true; - - _parser.Dispose(); - } } } \ No newline at end of file diff --git a/GitDiffMargin/Core/ParseResultEventArgs.cs b/GitDiffMargin/Core/ParseResultEventArgs.cs index f252bf1..4e1071e 100644 --- a/GitDiffMargin/Core/ParseResultEventArgs.cs +++ b/GitDiffMargin/Core/ParseResultEventArgs.cs @@ -40,16 +40,8 @@ public ParseResultEventArgs(ITextSnapshot snapshot, TimeSpan elapsedTime) ElapsedTime = elapsedTime; } - public ITextSnapshot Snapshot - { - get; - private set; - } + public ITextSnapshot Snapshot { get; } - public TimeSpan? ElapsedTime - { - get; - private set; - } + public TimeSpan? ElapsedTime { get; } } -} +} \ No newline at end of file diff --git a/GitDiffMargin/Core/WeakReference.cs b/GitDiffMargin/Core/WeakReference.cs index 3c233fd..4b1859e 100644 --- a/GitDiffMargin/Core/WeakReference.cs +++ b/GitDiffMargin/Core/WeakReference.cs @@ -47,15 +47,9 @@ protected WeakReference(SerializationInfo info, StreamingContext context) public new T Target { - get - { - return (T)base.Target; - } + get => (T) base.Target; - set - { - base.Target = value; - } + set => base.Target = value; } } -} +} \ No newline at end of file diff --git a/GitDiffMargin/DiffMarginBase.cs b/GitDiffMargin/DiffMarginBase.cs index dff0fb9..da95c77 100644 --- a/GitDiffMargin/DiffMarginBase.cs +++ b/GitDiffMargin/DiffMarginBase.cs @@ -11,10 +11,8 @@ internal abstract class DiffMarginBase : Canvas, IWpfTextViewMargin { protected readonly ITextView TextView; private bool _isDisposed; - protected DiffMarginViewModelBase ViewModel; protected UserControl UserControl; - - protected abstract string MarginName { get; } + protected DiffMarginViewModelBase ViewModel; protected DiffMarginBase(ITextView textView) { @@ -24,17 +22,14 @@ protected DiffMarginBase(ITextView textView) TextView.LayoutChanged += OnLayoutChanged; } + protected abstract string MarginName { get; } + public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } - protected virtual void Dispose(bool disposing) - { - _isDisposed = true; - } - public ITextViewMargin GetTextViewMargin(string marginName) { return string.Equals(marginName, MarginName, StringComparison.OrdinalIgnoreCase) ? this : null; @@ -49,13 +44,7 @@ public double MarginSize } } - public bool Enabled - { - get - { - return TextView.Options.IsSelectionMarginEnabled(); - } - } + public bool Enabled => TextView.Options.IsSelectionMarginEnabled(); public FrameworkElement VisualElement { @@ -66,12 +55,14 @@ public FrameworkElement VisualElement } } + protected virtual void Dispose(bool disposing) + { + _isDisposed = true; + } + private void HandleOptionChanged(object sender, EditorOptionChangedEventArgs e) { - if (!_isDisposed && e.OptionId == GitDiffMarginTextViewOptions.DiffMarginName) - { - UpdateVisibility(); - } + if (!_isDisposed && e.OptionId == GitDiffMarginTextViewOptions.DiffMarginName) UpdateVisibility(); } private void UpdateVisibility() diff --git a/GitDiffMargin/DiffMarginFactoryBase.cs b/GitDiffMargin/DiffMarginFactoryBase.cs index b409429..b2599e0 100644 --- a/GitDiffMargin/DiffMarginFactoryBase.cs +++ b/GitDiffMargin/DiffMarginFactoryBase.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ComponentModel.Composition; using System.IO; using System.Security; @@ -7,25 +7,21 @@ using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; -using Path = System.IO.Path; namespace GitDiffMargin { internal abstract class DiffMarginFactoryBase : IWpfTextViewMarginProvider { - [Import] - internal ITextDocumentFactoryService TextDocumentFactoryService { get; private set; } + [Import] internal ITextDocumentFactoryService TextDocumentFactoryService { get; private set; } - [Import] - internal IClassificationFormatMapService ClassificationFormatMapService { get; private set; } + [Import] internal IClassificationFormatMapService ClassificationFormatMapService { get; private set; } - [Import] - internal IEditorFormatMapService EditorFormatMapService { get; private set; } + [Import] internal IEditorFormatMapService EditorFormatMapService { get; private set; } - [Import] - internal IGitCommands GitCommands { get; private set; } + [Import] internal IGitCommands GitCommands { get; private set; } - public abstract IWpfTextViewMargin CreateMargin(IWpfTextViewHost wpfTextViewHost, IWpfTextViewMargin marginContainer); + public abstract IWpfTextViewMargin CreateMargin(IWpfTextViewHost wpfTextViewHost, + IWpfTextViewMargin marginContainer); protected IMarginCore TryGetMarginCore(IWpfTextViewHost textViewHost) { @@ -35,8 +31,8 @@ protected IMarginCore TryGetMarginCore(IWpfTextViewHost textViewHost) // play nice with other source control providers ITextView textView = textViewHost.TextView; - ITextDataModel textDataModel = textView != null ? textView.TextDataModel : null; - ITextBuffer documentBuffer = textDataModel != null ? textDataModel.DocumentBuffer : null; + var textDataModel = textView != null ? textView.TextDataModel : null; + var documentBuffer = textDataModel != null ? textDataModel.DocumentBuffer : null; if (documentBuffer == null) return null; @@ -44,11 +40,11 @@ protected IMarginCore TryGetMarginCore(IWpfTextViewHost textViewHost) if (!TextDocumentFactoryService.TryGetTextDocument(documentBuffer, out textDocument)) return null; - var fullPath= GetFullPath(textDocument.FilePath); + var fullPath = GetFullPath(textDocument.FilePath); if (fullPath == null) return null; - if (!GitCommands.TryGetOriginalPath(fullPath, out string originalPath)) + if (!GitCommands.TryGetOriginalPath(fullPath, out var originalPath)) return null; var repositoryPath = GitCommands.GetGitRepository(fullPath, originalPath); @@ -56,7 +52,8 @@ protected IMarginCore TryGetMarginCore(IWpfTextViewHost textViewHost) return null; return textViewHost.TextView.Properties.GetOrCreateSingletonProperty( - () => new MarginCore(textViewHost.TextView, originalPath, TextDocumentFactoryService, ClassificationFormatMapService, EditorFormatMapService, GitCommands)); + () => new MarginCore(textViewHost.TextView, originalPath, TextDocumentFactoryService, + ClassificationFormatMapService, EditorFormatMapService, GitCommands)); } private static string GetFullPath(string filename) diff --git a/GitDiffMargin/EditorDiffMargin.cs b/GitDiffMargin/EditorDiffMargin.cs index 641383e..68aae2c 100644 --- a/GitDiffMargin/EditorDiffMargin.cs +++ b/GitDiffMargin/EditorDiffMargin.cs @@ -1,4 +1,4 @@ -#region using +#region using using GitDiffMargin.Core; using GitDiffMargin.Git; @@ -18,11 +18,6 @@ internal sealed class EditorDiffMargin : DiffMarginBase public const string MarginNameConst = "EditorDiffMargin"; - protected override string MarginName - { - get { return MarginNameConst; } - } - internal EditorDiffMargin(IWpfTextView textView, IMarginCore marginCore) : base(textView) { @@ -31,6 +26,8 @@ internal EditorDiffMargin(IWpfTextView textView, IMarginCore marginCore) UserControl = new EditorDiffMarginControl {DataContext = ViewModel, Width = MarginWidth}; } + protected override string MarginName => MarginNameConst; + private void UpdateDiffDimensions(DiffViewModel diffViewModel, HunkRangeInfo hunkRangeInfo) { if (TextView.IsClosed) @@ -48,11 +45,7 @@ private void UpdateDiffDimensions(DiffViewModel diffViewModel, HunkRangeInfo hun private bool? UpdateNormalDiffDimensions(DiffViewModel diffViewModel, HunkRangeInfo hunkRangeInfo) { - if (hunkRangeInfo.NewHunkRange.NumberOfLines <= 0) - { - // if visible, it would have been as a deletion - return false; - } + if (hunkRangeInfo.NewHunkRange.NumberOfLines <= 0) return false; var snapshot = TextView.TextBuffer.CurrentSnapshot; @@ -62,9 +55,7 @@ private void UpdateDiffDimensions(DiffViewModel diffViewModel, HunkRangeInfo hun || startLineNumber >= snapshot.LineCount || endLineNumber < 0 || endLineNumber >= snapshot.LineCount) - { return false; - } var startLine = snapshot.GetLineFromLineNumber(startLineNumber); var endLine = snapshot.GetLineFromLineNumber(endLineNumber); @@ -82,17 +73,9 @@ private void UpdateDiffDimensions(DiffViewModel diffViewModel, HunkRangeInfo hun if (startLineView == null || endLineView == null) return false; - if (TextView.TextViewLines.LastVisibleLine.EndIncludingLineBreak < startLineView.Start) - { - // starts after the last visible line - return false; - } + if (TextView.TextViewLines.LastVisibleLine.EndIncludingLineBreak < startLineView.Start) return false; - if (TextView.TextViewLines.FirstVisibleLine.Start > endLineView.EndIncludingLineBreak) - { - // ends before the first visible line - return false; - } + if (TextView.TextViewLines.FirstVisibleLine.Start > endLineView.EndIncludingLineBreak) return false; double startTop; switch (startLineView.VisibilityState) @@ -139,11 +122,7 @@ private void UpdateDiffDimensions(DiffViewModel diffViewModel, HunkRangeInfo hun private bool? UpdateDeletedDiffDimensions(DiffViewModel diffViewModel, HunkRangeInfo hunkRangeInfo) { - if (hunkRangeInfo.NewHunkRange.NumberOfLines != 0) - { - // unexpected number of lines for a deletion hunk - return false; - } + if (hunkRangeInfo.NewHunkRange.NumberOfLines != 0) return false; var snapshot = TextView.TextBuffer.CurrentSnapshot; @@ -163,17 +142,9 @@ private void UpdateDiffDimensions(DiffViewModel diffViewModel, HunkRangeInfo hun if (followingLineView == null) return false; - if (TextView.TextViewLines.LastVisibleLine.EndIncludingLineBreak < followingLineView.Start) - { - // starts after the last visible line - return false; - } + if (TextView.TextViewLines.LastVisibleLine.EndIncludingLineBreak < followingLineView.Start) return false; - if (TextView.TextViewLines.FirstVisibleLine.Start > followingLineView.EndIncludingLineBreak) - { - // ends before the first visible line - return false; - } + if (TextView.TextViewLines.FirstVisibleLine.Start > followingLineView.EndIncludingLineBreak) return false; double followingTop; switch (followingLineView.VisibilityState) @@ -194,9 +165,9 @@ private void UpdateDiffDimensions(DiffViewModel diffViewModel, HunkRangeInfo hun return false; } - double center = followingTop; - double height = TextView.LineHeight; - diffViewModel.Top = center - (height / 2.0); + var center = followingTop; + var height = TextView.LineHeight; + diffViewModel.Top = center - height / 2.0; diffViewModel.Height = TextView.LineHeight; return true; } diff --git a/GitDiffMargin/EditorDiffMarginFactory.cs b/GitDiffMargin/EditorDiffMarginFactory.cs index 9b5d180..7b2bb3d 100644 --- a/GitDiffMargin/EditorDiffMarginFactory.cs +++ b/GitDiffMargin/EditorDiffMarginFactory.cs @@ -8,7 +8,7 @@ namespace GitDiffMargin { - [Export(typeof (IWpfTextViewMarginProvider))] + [Export(typeof(IWpfTextViewMarginProvider))] [Name(EditorDiffMargin.MarginNameConst)] [Order(After = PredefinedMarginNames.Spacer, Before = PredefinedMarginNames.Outlining)] [MarginContainer(PredefinedMarginNames.LeftSelection)] @@ -16,7 +16,8 @@ namespace GitDiffMargin [TextViewRole(PredefinedTextViewRoles.Editable)] internal sealed class EditorDiffMarginFactory : DiffMarginFactoryBase { - public override IWpfTextViewMargin CreateMargin(IWpfTextViewHost textViewHost, IWpfTextViewMargin containerMargin) + public override IWpfTextViewMargin CreateMargin(IWpfTextViewHost textViewHost, + IWpfTextViewMargin containerMargin) { var marginCore = TryGetMarginCore(textViewHost); if (marginCore == null) diff --git a/GitDiffMargin/Git/GitCommands.cs b/GitDiffMargin/Git/GitCommands.cs index 06a0101..5e7f6f9 100644 --- a/GitDiffMargin/Git/GitCommands.cs +++ b/GitDiffMargin/Git/GitCommands.cs @@ -7,22 +7,15 @@ using LibGit2Sharp; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; +using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; -using __VSDIFFSERVICEOPTIONS = Microsoft.VisualStudio.Shell.Interop.__VSDIFFSERVICEOPTIONS; -using __VSENUMPROJFLAGS = Microsoft.VisualStudio.Shell.Interop.__VSENUMPROJFLAGS; -using IEnumHierarchies = Microsoft.VisualStudio.Shell.Interop.IEnumHierarchies; -using IVsDifferenceService = Microsoft.VisualStudio.Shell.Interop.IVsDifferenceService; -using IVsHierarchy = Microsoft.VisualStudio.Shell.Interop.IVsHierarchy; -using IVsProject = Microsoft.VisualStudio.Shell.Interop.IVsProject; -using IVsSolution = Microsoft.VisualStudio.Shell.Interop.IVsSolution; -using SVsDifferenceService = Microsoft.VisualStudio.Shell.Interop.SVsDifferenceService; -using SVsSolution = Microsoft.VisualStudio.Shell.Interop.SVsSolution; namespace GitDiffMargin.Git { [Export(typeof(IGitCommands))] public class GitCommands : IGitCommands { + private const int ContextLines = 0; private readonly SVsServiceProvider _serviceProvider; [ImportingConstructor] @@ -31,9 +24,8 @@ public GitCommands(SVsServiceProvider serviceProvider) _serviceProvider = serviceProvider; } - private const int ContextLines = 0; - - public IEnumerable GetGitDiffFor(ITextDocument textDocument, string originalPath, ITextSnapshot snapshot) + public IEnumerable GetGitDiffFor(ITextDocument textDocument, string originalPath, + ITextSnapshot snapshot) { var filename = textDocument.FilePath; var repositoryPath = GetGitRepository(Path.GetFullPath(filename), ref originalPath); @@ -47,27 +39,14 @@ public IEnumerable GetGitDiffFor(ITextDocument textDocument, stri yield break; var retrieveStatus = repo.RetrieveStatus(originalPath); - if (retrieveStatus == FileStatus.Nonexistent) - { - // this occurs if a file within the repository itself (not the working copy) is opened. - yield break; - } + if (retrieveStatus == FileStatus.Nonexistent) yield break; - if ((retrieveStatus & FileStatus.Ignored) != 0) - { - // pointless to show diffs for ignored files - yield break; - } + if ((retrieveStatus & FileStatus.Ignored) != 0) yield break; if (retrieveStatus == FileStatus.Unaltered && !textDocument.IsDirty && Path.GetFullPath(filename) == originalPath) - { - // Truly unaltered. The `IsDirty` check isn't valid for cases where the textDocument is a view of a - // temporary copy of the file, since the temporary copy could have been made using unsaved changes - // and still appear "not dirty". yield break; - } var content = GetCompleteContent(textDocument, snapshot); if (content == null) yield break; @@ -83,7 +62,8 @@ public IEnumerable GetGitDiffFor(ITextDocument textDocument, stri bool suppressRollback; Blob blob; - if ((retrieveStatus & FileStatus.NewInWorkdir) != 0 || (retrieveStatus & FileStatus.NewInIndex) != 0) + if ((retrieveStatus & FileStatus.NewInWorkdir) != 0 || + (retrieveStatus & FileStatus.NewInIndex) != 0) { suppressRollback = true; @@ -97,18 +77,19 @@ public IEnumerable GetGitDiffFor(ITextDocument textDocument, stri { suppressRollback = false; - Commit from = repo.Head.Tip; - TreeEntry fromEntry = from[relativeFilepath]; + var from = repo.Head.Tip; + var fromEntry = from[relativeFilepath]; if (fromEntry == null) { // try again using case-insensitive comparison - Tree tree = from.Tree; - foreach (string segment in relativeFilepath.Split(Path.DirectorySeparatorChar)) + var tree = from.Tree; + foreach (var segment in relativeFilepath.Split(Path.DirectorySeparatorChar)) { if (tree == null) yield break; - fromEntry = tree.FirstOrDefault(i => string.Equals(segment, i.Name, StringComparison.OrdinalIgnoreCase)); + fromEntry = tree.FirstOrDefault(i => + string.Equals(segment, i.Name, StringComparison.OrdinalIgnoreCase)); if (fromEntry == null) yield break; @@ -121,35 +102,17 @@ public IEnumerable GetGitDiffFor(ITextDocument textDocument, stri yield break; } - var treeChanges = repo.Diff.Compare(blob, newBlob, new CompareOptions { ContextLines = ContextLines, InterhunkLines = 0 }); + var treeChanges = repo.Diff.Compare(blob, newBlob, + new CompareOptions {ContextLines = ContextLines, InterhunkLines = 0}); var gitDiffParser = new GitDiffParser(treeChanges.Patch, ContextLines, suppressRollback); var hunkRangeInfos = gitDiffParser.Parse(); - foreach (var hunkRangeInfo in hunkRangeInfos) - { - yield return hunkRangeInfo; - } + foreach (var hunkRangeInfo in hunkRangeInfos) yield return hunkRangeInfo; } } } - private static byte[] GetCompleteContent(ITextDocument textDocument, ITextSnapshot snapshot) - { - var currentText = snapshot.GetText(); - - var content = textDocument.Encoding.GetBytes(currentText); - - var preamble = textDocument.Encoding.GetPreamble(); - if (preamble.Length == 0) return content; - - var completeContent = new byte[preamble.Length + content.Length]; - Buffer.BlockCopy(preamble, 0, completeContent, 0, preamble.Length); - Buffer.BlockCopy(content, 0, completeContent, preamble.Length, content.Length); - - return completeContent; - } - public void StartExternalDiff(ITextDocument textDocument, string originalPath) { if (textDocument == null || string.IsNullOrEmpty(textDocument.FilePath)) return; @@ -161,13 +124,13 @@ public void StartExternalDiff(ITextDocument textDocument, string originalPath) using (var repo = new Repository(repositoryPath)) { - string workingDirectory = repo.Info.WorkingDirectory; - string relativePath = originalPath; + var workingDirectory = repo.Info.WorkingDirectory; + var relativePath = originalPath; if (relativePath.StartsWith(workingDirectory, StringComparison.OrdinalIgnoreCase)) relativePath = relativePath.Substring(workingDirectory.Length); // the name of the object in the database - string objectName = Path.GetFileName(filename); + var objectName = Path.GetFileName(filename); Blob oldBlob = null; var indexEntry = repo.Index[relativePath]; @@ -179,17 +142,19 @@ public void StartExternalDiff(ITextDocument textDocument, string originalPath) var tempFileName = Path.GetTempFileName(); if (oldBlob != null) - File.WriteAllText(tempFileName, oldBlob.GetContentText(new FilteringOptions(relativePath)), GetEncoding(filename)); + File.WriteAllText(tempFileName, oldBlob.GetContentText(new FilteringOptions(relativePath)), + GetEncoding(filename)); - IVsDifferenceService differenceService = _serviceProvider.GetService(typeof(SVsDifferenceService)) as IVsDifferenceService; - string leftFileMoniker = tempFileName; + var differenceService = + _serviceProvider.GetService(typeof(SVsDifferenceService)) as IVsDifferenceService; + var leftFileMoniker = tempFileName; // The difference service will automatically load the text from the file open in the editor, even if // it has changed. Don't use the original path here. - string rightFileMoniker = filename; + var rightFileMoniker = filename; - string actualFilename = objectName; - string tempPrefix = Path.GetRandomFileName().Substring(0, 5); - string caption = string.Format("{0}_{1} vs. {1}", tempPrefix, actualFilename); + var actualFilename = objectName; + var tempPrefix = Path.GetRandomFileName().Substring(0, 5); + var caption = string.Format("{0}_{1} vs. {1}", tempPrefix, actualFilename); string tooltip = null; @@ -217,19 +182,20 @@ public void StartExternalDiff(ITextDocument textDocument, string originalPath) leftLabel = string.Format("{0}@{1}", objectName, repo.Head.Tip.Sha.Substring(0, 7)); } - string rightLabel = originalPath; + var rightLabel = originalPath; string inlineLabel = null; string roles = null; - __VSDIFFSERVICEOPTIONS grfDiffOptions = __VSDIFFSERVICEOPTIONS.VSDIFFOPT_LeftFileIsTemporary; - differenceService.OpenComparisonWindow2(leftFileMoniker, rightFileMoniker, caption, tooltip, leftLabel, rightLabel, inlineLabel, roles, (uint)grfDiffOptions); + var grfDiffOptions = __VSDIFFSERVICEOPTIONS.VSDIFFOPT_LeftFileIsTemporary; + differenceService.OpenComparisonWindow2(leftFileMoniker, rightFileMoniker, caption, tooltip, leftLabel, + rightLabel, inlineLabel, roles, (uint) grfDiffOptions); // Since the file is marked as temporary, we can delete it now File.Delete(tempFileName); } } - /// + /// public bool TryGetOriginalPath(string path, out string originalPath) { originalPath = null; @@ -242,13 +208,13 @@ public bool TryGetOriginalPath(string path, out string originalPath) return true; } - /// + /// public bool IsGitRepository(string path, string originalPath) { return GetGitRepository(path, originalPath) != null; } - /// + /// public string GetGitRepository(string path, string originalPath) { if (originalPath == null) @@ -257,6 +223,42 @@ public string GetGitRepository(string path, string originalPath) return GetGitRepository(path, ref originalPath); } + /// + public string GetGitWorkingCopy(string path, string originalPath) + { + if (originalPath == null) + throw new ArgumentNullException(nameof(originalPath)); + + var repositoryPath = GetGitRepository(path, originalPath); + if (repositoryPath == null) + return null; + + using (var repository = new Repository(repositoryPath)) + { + var workingDirectory = repository.Info.WorkingDirectory; + if (workingDirectory == null) + return null; + + return Path.GetFullPath(workingDirectory); + } + } + + private static byte[] GetCompleteContent(ITextDocument textDocument, ITextSnapshot snapshot) + { + var currentText = snapshot.GetText(); + + var content = textDocument.Encoding.GetBytes(currentText); + + var preamble = textDocument.Encoding.GetPreamble(); + if (preamble.Length == 0) return content; + + var completeContent = new byte[preamble.Length + content.Length]; + Buffer.BlockCopy(preamble, 0, completeContent, 0, preamble.Length); + Buffer.BlockCopy(content, 0, completeContent, preamble.Length, content.Length); + + return completeContent; + } + private string GetGitRepository(string path, ref string originalPath) { if (originalPath == null) @@ -280,51 +282,24 @@ private string GetGitRepository(string path, ref string originalPath) return Repository.Discover(Path.GetFullPath(originalPath)); } - /// - public string GetGitWorkingCopy(string path, string originalPath) - { - if (originalPath == null) - throw new ArgumentNullException(nameof(originalPath)); - - var repositoryPath = GetGitRepository(path, originalPath); - if (repositoryPath == null) - return null; - - using (Repository repository = new Repository(repositoryPath)) - { - string workingDirectory = repository.Info.WorkingDirectory; - if (workingDirectory == null) - return null; - - return Path.GetFullPath(workingDirectory); - } - } - - static Encoding GetEncoding(string file) + private static Encoding GetEncoding(string file) { if (File.Exists(file)) { var encoding = Encoding.UTF8; - if (HasPreamble(file, encoding)) - { - return encoding; - } + if (HasPreamble(file, encoding)) return encoding; } return Encoding.Default; } - static bool HasPreamble(string file, Encoding encoding) + private static bool HasPreamble(string file, Encoding encoding) { using (var stream = File.OpenRead(file)) { foreach (var b in encoding.GetPreamble()) - { if (b != stream.ReadByte()) - { return false; - } - } } return true; @@ -335,35 +310,32 @@ private string AdjustPath(string fullPath) // Right now the only adjustment is for CPS-based project systems which open their project files in a // temporary location. There are several of these, such as .csproj, .vbproj, .shproj, and .fsproj, and more // could appear in the future. - if (!fullPath.EndsWith("proj", StringComparison.Ordinal)) - { - return fullPath; - } + if (!fullPath.EndsWith("proj", StringComparison.Ordinal)) return fullPath; // CPS will open the file in %TEMP%\{random name}\{ProjectFileName} - string directoryName = Path.GetDirectoryName(fullPath); + var directoryName = Path.GetDirectoryName(fullPath); if (string.IsNullOrEmpty(directoryName)) return fullPath; directoryName = Path.GetDirectoryName(directoryName); - if (!Path.GetTempPath().Equals(directoryName + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + if (!Path.GetTempPath().Equals(directoryName + Path.DirectorySeparatorChar, + StringComparison.OrdinalIgnoreCase)) return fullPath; - IVsSolution solution = _serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution; + var solution = _serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution; if (solution == null) return fullPath; - if (!ErrorHandler.Succeeded(solution.GetProjectEnum((uint)__VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION, Guid.Empty, out IEnumHierarchies ppenum)) + if (!ErrorHandler.Succeeded(solution.GetProjectEnum((uint) __VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION, + Guid.Empty, out var ppenum)) || ppenum == null) - { return fullPath; - } - List projectFiles = new List(); - IVsHierarchy[] hierarchies = new IVsHierarchy[1]; + var projectFiles = new List(); + var hierarchies = new IVsHierarchy[1]; while (true) { - int hr = ppenum.Next((uint)hierarchies.Length, hierarchies, out uint fetched); + var hr = ppenum.Next((uint) hierarchies.Length, hierarchies, out var fetched); if (!ErrorHandler.Succeeded(hr)) return fullPath; @@ -372,7 +344,8 @@ private string AdjustPath(string fullPath) if (!(hierarchies[0] is IVsProject project)) continue; - if (!ErrorHandler.Succeeded(project.GetMkDocument((uint)VSConstants.VSITEMID.Root, out string projectFilePath))) + if (!ErrorHandler.Succeeded(project.GetMkDocument((uint) VSConstants.VSITEMID.Root, + out var projectFilePath))) continue; if (!Path.GetFileName(projectFilePath).Equals(Path.GetFileName(fullPath), StringComparison.Ordinal)) @@ -381,34 +354,28 @@ private string AdjustPath(string fullPath) projectFiles.Add(projectFilePath); } - if (hr != VSConstants.S_OK) - { - // No more projects - break; - } + if (hr != VSConstants.S_OK) break; } switch (projectFiles.Count) { - case 0: - // No matching project file found in solution - return fullPath; + case 0: + // No matching project file found in solution + return fullPath; - case 1: - // Exactly one matching project file found in solution - return projectFiles[0]; + case 1: + // Exactly one matching project file found in solution + return projectFiles[0]; - default: - // Multiple project files found in solution; try to find one with a matching file size - long desiredSize = new FileInfo(fullPath).Length; - foreach (var projectFilePath in projectFiles) - { - if (File.Exists(projectFilePath) && new FileInfo(projectFilePath).Length == desiredSize) - return projectFilePath; - } + default: + // Multiple project files found in solution; try to find one with a matching file size + var desiredSize = new FileInfo(fullPath).Length; + foreach (var projectFilePath in projectFiles) + if (File.Exists(projectFilePath) && new FileInfo(projectFilePath).Length == desiredSize) + return projectFilePath; - // No results found - return fullPath; + // No results found + return fullPath; } } } diff --git a/GitDiffMargin/Git/GitDiffParser.cs b/GitDiffMargin/Git/GitDiffParser.cs index 382468a..cac0f24 100644 --- a/GitDiffMargin/Git/GitDiffParser.cs +++ b/GitDiffMargin/Git/GitDiffParser.cs @@ -6,8 +6,8 @@ namespace GitDiffMargin.Git { public class GitDiffParser { - private readonly string _gitDiff; private readonly int _contextLines; + private readonly string _gitDiff; private readonly bool _suppressRollback; public GitDiffParser(string gitDiff, int contextLines) @@ -24,9 +24,10 @@ public GitDiffParser(string gitDiff, int contextLines, bool suppressRollback) public IEnumerable Parse() { - return from hunkLine in GetUnifiedFormatHunkLines() - where !string.IsNullOrEmpty(hunkLine.Item1) - select new HunkRangeInfo(new HunkRange(GetHunkOriginalFile(hunkLine.Item1), _contextLines), new HunkRange(GetHunkNewFile(hunkLine.Item1), _contextLines), hunkLine.Item2, _suppressRollback); + return from hunkLine in GetUnifiedFormatHunkLines() + where !string.IsNullOrEmpty(hunkLine.Item1) + select new HunkRangeInfo(new HunkRange(GetHunkOriginalFile(hunkLine.Item1), _contextLines), + new HunkRange(GetHunkNewFile(hunkLine.Item1), _contextLines), hunkLine.Item2, _suppressRollback); } public IEnumerable>> GetUnifiedFormatHunkLines() @@ -38,9 +39,10 @@ public IEnumerable>> GetUnifiedFormatHunkLines var splitHunks = SplitHunks(withoutHeader).ToList(); - return splitHunks.Any() ? - splitHunks.Select(splitHunk => new Tuple>(splitHunk[0], splitHunk.Skip(1).TakeWhile((s, i) => i < splitHunk.Count))) : - Enumerable.Empty>>(); + return splitHunks.Any() + ? splitHunks.Select(splitHunk => new Tuple>(splitHunk[0], + splitHunk.Skip(1).TakeWhile((s, i) => i < splitHunk.Count))) + : Enumerable.Empty>>(); } private static IEnumerable> SplitHunks(List lines) @@ -51,7 +53,6 @@ private static IEnumerable> SplitHunks(List lines) var hunks = new List(); foreach (var line in lines) - { if (line.StartsWith("@@")) { if (firstHunk) @@ -70,7 +71,6 @@ private static IEnumerable> SplitHunks(List lines) { hunks.Add(line); } - } yield return new List(hunks); } @@ -82,7 +82,8 @@ public string GetHunkOriginalFile(string hunkLine) public string GetHunkNewFile(string hunkLine) { - return hunkLine.Split(new[] { "@@ -", " +" }, StringSplitOptions.RemoveEmptyEntries).ToArray()[1].Split(' ')[0]; + return hunkLine.Split(new[] {"@@ -", " +"}, StringSplitOptions.RemoveEmptyEntries).ToArray()[1] + .Split(' ')[0]; } } } \ No newline at end of file diff --git a/GitDiffMargin/Git/HunkRange.cs b/GitDiffMargin/Git/HunkRange.cs index f9a7b86..c8c6a81 100644 --- a/GitDiffMargin/Git/HunkRange.cs +++ b/GitDiffMargin/Git/HunkRange.cs @@ -7,18 +7,17 @@ public HunkRange(string hunkRange, int contextLines) if (hunkRange.Contains(",")) { var hunkParts = hunkRange.Split(','); - StartingLineNumber = int.Parse(hunkParts[0]) -1 + contextLines; - NumberOfLines = int.Parse(hunkParts[1]) - (2 * contextLines); + StartingLineNumber = int.Parse(hunkParts[0]) - 1 + contextLines; + NumberOfLines = int.Parse(hunkParts[1]) - 2 * contextLines; } else { StartingLineNumber = int.Parse(hunkRange) - 1 + contextLines; NumberOfLines = 1; } - } - public int StartingLineNumber { get; private set; } - public int NumberOfLines { get; private set; } + public int StartingLineNumber { get; } + public int NumberOfLines { get; } } } \ No newline at end of file diff --git a/GitDiffMargin/Git/HunkRangeInfo.cs b/GitDiffMargin/Git/HunkRangeInfo.cs index c3f96c0..d3cd4b8 100644 --- a/GitDiffMargin/Git/HunkRangeInfo.cs +++ b/GitDiffMargin/Git/HunkRangeInfo.cs @@ -9,37 +9,37 @@ namespace GitDiffMargin.Git { public class HunkRangeInfo { - private List DiffLines { get; set; } - public HunkRangeInfo(HunkRange originaleHunkRange, HunkRange newHunkRange, IEnumerable diffLines) : this(originaleHunkRange, newHunkRange, diffLines, false) { } - public HunkRangeInfo(HunkRange originaleHunkRange, HunkRange newHunkRange, IEnumerable diffLines, bool suppressRollback) + public HunkRangeInfo(HunkRange originaleHunkRange, HunkRange newHunkRange, IEnumerable diffLines, + bool suppressRollback) { OriginalHunkRange = originaleHunkRange; NewHunkRange = newHunkRange; DiffLines = diffLines.ToList(); SuppressRollback = suppressRollback; - + IsAddition = DiffLines.All(s => s.StartsWith("+") || s.StartsWith("\\") || string.IsNullOrWhiteSpace(s)); IsDeletion = DiffLines.All(s => s.StartsWith("-") || s.StartsWith("\\") || string.IsNullOrWhiteSpace(s)); IsModification = !IsAddition && !IsDeletion; if (IsDeletion || IsModification) - { - OriginalText = DiffLines.Where(s => s.StartsWith("-")).Select(s => s.Remove(0, 1).TrimEnd('\n').TrimEnd('\r')).ToList(); - } + OriginalText = DiffLines.Where(s => s.StartsWith("-")) + .Select(s => s.Remove(0, 1).TrimEnd('\n').TrimEnd('\r')).ToList(); } - public HunkRange OriginalHunkRange { get; private set; } - public HunkRange NewHunkRange { get; private set; } - public List OriginalText { get; private set; } - public bool SuppressRollback { get; private set; } + private List DiffLines { get; } + + public HunkRange OriginalHunkRange { get; } + public HunkRange NewHunkRange { get; } + public List OriginalText { get; } + public bool SuppressRollback { get; } - public bool IsAddition { get; private set; } - public bool IsModification { get; private set; } - public bool IsDeletion { get; private set; } + public bool IsAddition { get; } + public bool IsModification { get; } + public bool IsDeletion { get; } } } \ No newline at end of file diff --git a/GitDiffMargin/Git/IGitCommands.cs b/GitDiffMargin/Git/IGitCommands.cs index f7d681d..7c9494a 100644 --- a/GitDiffMargin/Git/IGitCommands.cs +++ b/GitDiffMargin/Git/IGitCommands.cs @@ -9,62 +9,75 @@ namespace GitDiffMargin.Git { internal interface IGitCommands { - IEnumerable GetGitDiffFor(ITextDocument textDocument, string originalPath, ITextSnapshot snapshot); + IEnumerable GetGitDiffFor(ITextDocument textDocument, string originalPath, + ITextSnapshot snapshot); void StartExternalDiff(ITextDocument textDocument, string originalPath); /// - /// Attempts to gets the original file path for the specified path. + /// Attempts to gets the original file path for the specified path. /// /// - /// In some (detectable) cases, documents are opened through a temporary copy of the file rather than - /// opening the original file directly. To preserve Git diff functionality in these cases, the original path is - /// detected and used for diff operations. + /// + /// In some (detectable) cases, documents are opened through a temporary copy of the file rather than + /// opening the original file directly. To preserve Git diff functionality in these cases, the original path is + /// detected and used for diff operations. + /// /// /// The path of a document opened in the editor. - /// The original path of the document in a source-controlled working copy; otherwise, - /// this is just set to . - /// if the resulting was located (even if it - /// matches ; otherwise, . + /// + /// The original path of the document in a source-controlled working copy; otherwise, + /// this is just set to . + /// + /// + /// if the resulting was located (even if it + /// matches ; otherwise, . + /// bool TryGetOriginalPath(string path, out string originalPath); /// - /// Determines if a file or directory is located within a Git repository. + /// Determines if a file or directory is located within a Git repository. /// /// The path to the file or directory. /// The original path of the file in a source-controlled working copy. /// - /// if is a valid path of a file or directory located within a - /// Git repository; otherwise, . + /// if is a valid path of a file or directory located within a + /// Git repository; otherwise, . /// bool IsGitRepository(string path, string originalPath); /// - /// Gets the absolute path to the folder containing the Git repository database for a specified path. + /// Gets the absolute path to the folder containing the Git repository database for a specified path. /// /// The path to the file or directory within the repository. /// The original path of the file in a source-controlled working copy. /// - /// The absolute path to folder containing the repository database for . - /// -or- - /// if is not a path to a file or directory within a Git - /// repository. + /// The absolute path to folder containing the repository database for . + /// -or- + /// + /// if is not a path to a file or directory within a Git + /// repository. + /// /// string GetGitRepository(string path, string originalPath); /// - /// Gets the root of the working copy of the Git repository containing . + /// Gets the root of the working copy of the Git repository containing . /// /// The path to the file or directory. /// The original path of the file in a source-controlled working copy. /// - /// The absolute path to the root of the working copy of the Git repository containing - /// . - /// -or- - /// if the Git repository is bare. - /// -or- - /// if is not a path to a file or directory within the - /// working copy of a Git repository. + /// + /// The absolute path to the root of the working copy of the Git repository containing + /// . + /// + /// -or- + /// if the Git repository is bare. + /// -or- + /// + /// if is not a path to a file or directory within the + /// working copy of a Git repository. + /// /// string GetGitWorkingCopy(string path, string originalPath); } diff --git a/GitDiffMargin/GitDiffMarginCommand.cs b/GitDiffMargin/GitDiffMarginCommand.cs index f56b439..cabb33c 100644 --- a/GitDiffMargin/GitDiffMarginCommand.cs +++ b/GitDiffMargin/GitDiffMarginCommand.cs @@ -1,7 +1,7 @@ -namespace GitDiffMargin -{ - using System.Runtime.InteropServices; +using System.Runtime.InteropServices; +namespace GitDiffMargin +{ [Guid(GitDiffMarginCommandHandler.GitDiffMarginCommandSet)] public enum GitDiffMarginCommand { @@ -14,6 +14,6 @@ public enum GitDiffMarginCommand GitDiffToolbar = 100, - GitDiffToolbarGroup = 150, + GitDiffToolbarGroup = 150 } } \ No newline at end of file diff --git a/GitDiffMargin/GitDiffMarginCommandHandler.cs b/GitDiffMargin/GitDiffMarginCommandHandler.cs index 7480306..4f44728 100644 --- a/GitDiffMargin/GitDiffMarginCommandHandler.cs +++ b/GitDiffMargin/GitDiffMarginCommandHandler.cs @@ -1,18 +1,15 @@ +using System; +using System.Linq; +using GitDiffMargin.ViewModel; +using Microsoft.VisualStudio.Editor; +using Microsoft.VisualStudio.OLE.Interop; +using Microsoft.VisualStudio.Text.Editor; +using Microsoft.VisualStudio.TextManager.Interop; +using Tvl.VisualStudio.Shell; +using Tvl.VisualStudio.Text; + namespace GitDiffMargin { - using System; - using System.Linq; - using System.Windows.Input; - using GalaSoft.MvvmLight.Command; - using GitDiffMargin.ViewModel; - using Microsoft.VisualStudio.Editor; - using Microsoft.VisualStudio.Text.Editor; - using Tvl.VisualStudio.Shell; - using Tvl.VisualStudio.Text; - using IVsTextView = Microsoft.VisualStudio.TextManager.Interop.IVsTextView; - using OLECMDEXECOPT = Microsoft.VisualStudio.OLE.Interop.OLECMDEXECOPT; - using OLECMDF = Microsoft.VisualStudio.OLE.Interop.OLECMDF; - internal sealed class GitDiffMarginCommandHandler : TextViewCommandFilter { internal const string GitDiffMarginCommandSet = "691DB887-6D82-46A9-B0AF-407C7F0E39BE"; @@ -20,7 +17,8 @@ internal sealed class GitDiffMarginCommandHandler : TextViewCommandFilter private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; private readonly ITextView _textView; - public GitDiffMarginCommandHandler(IVsTextView textViewAdapter, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ITextView textView) + public GitDiffMarginCommandHandler(IVsTextView textViewAdapter, + IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ITextView textView) : base(textViewAdapter) { if (editorAdaptersFactoryService == null) @@ -32,62 +30,65 @@ public GitDiffMarginCommandHandler(IVsTextView textViewAdapter, IVsEditorAdapter _textView = textView; } - protected override OLECMDF QueryCommandStatus(ref Guid commandGroup, uint commandId, OleCommandText oleCommandText) + protected override OLECMDF QueryCommandStatus(ref Guid commandGroup, uint commandId, + OleCommandText oleCommandText) { if (commandGroup == typeof(GitDiffMarginCommand).GUID) - { - switch ((GitDiffMarginCommand)commandId) + switch ((GitDiffMarginCommand) commandId) { - case GitDiffMarginCommand.ShowPopup: + case GitDiffMarginCommand.ShowPopup: { - EditorDiffMarginViewModel viewModel; - if (!TryGetMarginViewModel(out viewModel)) - return 0; - - var diffViewModel = GetCurrentDiffViewModel(viewModel); - - if (diffViewModel != null) - return OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; - else + EditorDiffMarginViewModel viewModel; + if (!TryGetMarginViewModel(out viewModel)) + return 0; + + var diffViewModel = GetCurrentDiffViewModel(viewModel); + + if (diffViewModel != null) + return OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; return OLECMDF.OLECMDF_SUPPORTED; - } - case GitDiffMarginCommand.PreviousChange: - case GitDiffMarginCommand.NextChange: + } + case GitDiffMarginCommand.PreviousChange: + case GitDiffMarginCommand.NextChange: { EditorDiffMarginViewModel viewModel; if (!TryGetMarginViewModel(out viewModel)) return 0; // First look for a diff already showing a popup - EditorDiffViewModel diffViewModel = viewModel.DiffViewModels.OfType().FirstOrDefault(i => i.ShowPopup); + var diffViewModel = viewModel.DiffViewModels.OfType() + .FirstOrDefault(i => i.ShowPopup); if (diffViewModel != null) { - RelayCommand command = (GitDiffMarginCommand)commandId == GitDiffMarginCommand.NextChange ? viewModel.NextChangeCommand : viewModel.PreviousChangeCommand; + var command = (GitDiffMarginCommand) commandId == GitDiffMarginCommand.NextChange + ? viewModel.NextChangeCommand + : viewModel.PreviousChangeCommand; if (command.CanExecute(diffViewModel)) return OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; - else - return OLECMDF.OLECMDF_SUPPORTED; + return OLECMDF.OLECMDF_SUPPORTED; } diffViewModel = GetDiffViewModelToMoveTo(commandId, viewModel); if (diffViewModel != null) return OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; - else - return OLECMDF.OLECMDF_SUPPORTED; + return OLECMDF.OLECMDF_SUPPORTED; } - case GitDiffMarginCommand.RollbackChange: - case GitDiffMarginCommand.CopyOldText: + case GitDiffMarginCommand.RollbackChange: + case GitDiffMarginCommand.CopyOldText: { EditorDiffMarginViewModel viewModel; if (!TryGetMarginViewModel(out viewModel)) return 0; - EditorDiffViewModel diffViewModel = viewModel.DiffViewModels.OfType().FirstOrDefault(i => i.ShowPopup); + var diffViewModel = viewModel.DiffViewModels.OfType() + .FirstOrDefault(i => i.ShowPopup); if (diffViewModel != null) { - ICommand command = (GitDiffMarginCommand)commandId == GitDiffMarginCommand.RollbackChange ? diffViewModel.RollbackCommand : diffViewModel.CopyOldTextCommand; + var command = (GitDiffMarginCommand) commandId == GitDiffMarginCommand.RollbackChange + ? diffViewModel.RollbackCommand + : diffViewModel.CopyOldTextCommand; if (command.CanExecute(diffViewModel)) return OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; } @@ -96,7 +97,7 @@ protected override OLECMDF QueryCommandStatus(ref Guid commandGroup, uint comman return OLECMDF.OLECMDF_SUPPORTED; } - case GitDiffMarginCommand.ShowDiff: + case GitDiffMarginCommand.ShowDiff: { EditorDiffMarginViewModel viewModel; if (!TryGetMarginViewModel(out viewModel)) @@ -104,53 +105,52 @@ protected override OLECMDF QueryCommandStatus(ref Guid commandGroup, uint comman if (viewModel.DiffViewModels.Any()) return OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; - else - return OLECMDF.OLECMDF_SUPPORTED; + return OLECMDF.OLECMDF_SUPPORTED; } - case GitDiffMarginCommand.GitDiffToolbar: - case GitDiffMarginCommand.GitDiffToolbarGroup: - // these aren't actually commands, but IDs of the command bars and groups - break; - - default: - break; + case GitDiffMarginCommand.GitDiffToolbar: + case GitDiffMarginCommand.GitDiffToolbarGroup: + // these aren't actually commands, but IDs of the command bars and groups + break; } - } return 0; } - protected override bool HandlePreExec(ref Guid commandGroup, uint commandId, OLECMDEXECOPT executionOptions, IntPtr pvaIn, IntPtr pvaOut) + protected override bool HandlePreExec(ref Guid commandGroup, uint commandId, OLECMDEXECOPT executionOptions, + IntPtr pvaIn, IntPtr pvaOut) { if (commandGroup == typeof(GitDiffMarginCommand).GUID) { EditorDiffMarginViewModel viewModel = null; EditorDiffViewModel diffViewModel = null; if (TryGetMarginViewModel(out viewModel)) - diffViewModel = viewModel.DiffViewModels.OfType().FirstOrDefault(i => i.ShowPopup); + diffViewModel = viewModel.DiffViewModels.OfType() + .FirstOrDefault(i => i.ShowPopup); - switch ((GitDiffMarginCommand)commandId) + switch ((GitDiffMarginCommand) commandId) { - case GitDiffMarginCommand.ShowPopup: - { - diffViewModel = GetCurrentDiffViewModel(viewModel); - - if (diffViewModel != null) + case GitDiffMarginCommand.ShowPopup: { - diffViewModel.ShowPopup = true; - return true; - } + diffViewModel = GetCurrentDiffViewModel(viewModel); - return false; - } - case GitDiffMarginCommand.PreviousChange: - case GitDiffMarginCommand.NextChange: + if (diffViewModel != null) + { + diffViewModel.ShowPopup = true; + return true; + } + + return false; + } + case GitDiffMarginCommand.PreviousChange: + case GitDiffMarginCommand.NextChange: { if (viewModel == null) return false; - RelayCommand command = (GitDiffMarginCommand)commandId == GitDiffMarginCommand.NextChange ? viewModel.NextChangeCommand : viewModel.PreviousChangeCommand; + var command = (GitDiffMarginCommand) commandId == GitDiffMarginCommand.NextChange + ? viewModel.NextChangeCommand + : viewModel.PreviousChangeCommand; // First look for a diff already showing a popup if (diffViewModel != null) @@ -167,34 +167,33 @@ protected override bool HandlePreExec(ref Guid commandGroup, uint commandId, OLE return true; } - case GitDiffMarginCommand.RollbackChange: - case GitDiffMarginCommand.CopyOldText: + case GitDiffMarginCommand.RollbackChange: + case GitDiffMarginCommand.CopyOldText: { if (diffViewModel == null) return false; - ICommand command = (GitDiffMarginCommand)commandId == GitDiffMarginCommand.RollbackChange ? diffViewModel.RollbackCommand : diffViewModel.CopyOldTextCommand; + var command = (GitDiffMarginCommand) commandId == GitDiffMarginCommand.RollbackChange + ? diffViewModel.RollbackCommand + : diffViewModel.CopyOldTextCommand; command.Execute(diffViewModel); return true; } - case GitDiffMarginCommand.ShowDiff: + case GitDiffMarginCommand.ShowDiff: { if (diffViewModel == null) return false; - ICommand command = diffViewModel.ShowDifferenceCommand; + var command = diffViewModel.ShowDifferenceCommand; command.Execute(diffViewModel); return true; } - case GitDiffMarginCommand.GitDiffToolbar: - case GitDiffMarginCommand.GitDiffToolbarGroup: - // these aren't actually commands, but IDs of the command bars and groups - break; - - default: - break; + case GitDiffMarginCommand.GitDiffToolbar: + case GitDiffMarginCommand.GitDiffToolbarGroup: + // these aren't actually commands, but IDs of the command bars and groups + break; } } @@ -205,27 +204,30 @@ private EditorDiffViewModel GetDiffViewModelToMoveTo(uint commandId, DiffMarginV { var lineNumber = _textView.Caret.Position.BufferPosition.GetContainingLine().LineNumber; - return (GitDiffMarginCommand) commandId == GitDiffMarginCommand.NextChange ? - viewModel.DiffViewModels.OfType().FirstOrDefault(model => model.LineNumber > lineNumber) : - viewModel.DiffViewModels.OfType().LastOrDefault(model => model.LineNumber < lineNumber); + return (GitDiffMarginCommand) commandId == GitDiffMarginCommand.NextChange + ? viewModel.DiffViewModels.OfType() + .FirstOrDefault(model => model.LineNumber > lineNumber) + : viewModel.DiffViewModels.OfType() + .LastOrDefault(model => model.LineNumber < lineNumber); } private EditorDiffViewModel GetCurrentDiffViewModel(DiffMarginViewModelBase viewModel) { var caretLineNumber = _textView.Caret.Position.BufferPosition.GetContainingLine().LineNumber; - return viewModel.DiffViewModels.OfType().FirstOrDefault(diff => diff.IsLineNumberBetweenDiff(caretLineNumber)); + return viewModel.DiffViewModels.OfType() + .FirstOrDefault(diff => diff.IsLineNumberBetweenDiff(caretLineNumber)); } private bool TryGetMarginViewModel(out EditorDiffMarginViewModel viewModel) { viewModel = null; - IWpfTextViewHost textViewHost = _editorAdaptersFactoryService.GetWpfTextViewHost(TextViewAdapter); + var textViewHost = _editorAdaptersFactoryService.GetWpfTextViewHost(TextViewAdapter); if (textViewHost == null) return false; - EditorDiffMargin margin = textViewHost.GetTextViewMargin(EditorDiffMargin.MarginNameConst) as EditorDiffMargin; + var margin = textViewHost.GetTextViewMargin(EditorDiffMargin.MarginNameConst) as EditorDiffMargin; if (margin == null) return false; @@ -233,4 +235,4 @@ private bool TryGetMarginViewModel(out EditorDiffMarginViewModel viewModel) return viewModel != null; } } -} +} \ No newline at end of file diff --git a/GitDiffMargin/GitDiffMarginPackage.cs b/GitDiffMargin/GitDiffMarginPackage.cs index caa268d..631159b 100644 --- a/GitDiffMargin/GitDiffMarginPackage.cs +++ b/GitDiffMargin/GitDiffMarginPackage.cs @@ -1,15 +1,12 @@ -namespace GitDiffMargin -{ - using System; - using System.Runtime.InteropServices; - using Microsoft.VisualStudio.Shell; +using System.Runtime.InteropServices; +using Microsoft.VisualStudio.Shell; +namespace GitDiffMargin +{ [PackageRegistration(UseManagedResourcesOnly = true)] [Guid("F82C1EF6-3B52-425E-BC28-4934E6073A32")] - [ProvideMenuResource("Menus.ctmenu", 1)] - public class GitDiffMarginPackage : Package { } -} +} \ No newline at end of file diff --git a/GitDiffMargin/GitDiffMarginTextViewOptions.cs b/GitDiffMargin/GitDiffMarginTextViewOptions.cs index a90d153..ab86daa 100644 --- a/GitDiffMargin/GitDiffMarginTextViewOptions.cs +++ b/GitDiffMargin/GitDiffMarginTextViewOptions.cs @@ -7,6 +7,5 @@ public static class GitDiffMarginTextViewOptions public const string DiffMarginName = EditorDiffMargin.MarginNameConst + "/DiffMarginName"; public static readonly EditorOptionKey DiffMarginId = new EditorOptionKey(DiffMarginName); - } -} +} \ No newline at end of file diff --git a/GitDiffMargin/Properties/AssemblyInfo.cs b/GitDiffMargin/Properties/AssemblyInfo.cs index d72f3f6..eb54d62 100644 --- a/GitDiffMargin/Properties/AssemblyInfo.cs +++ b/GitDiffMargin/Properties/AssemblyInfo.cs @@ -8,7 +8,9 @@ // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Git Diff Margin")] -[assembly: AssemblyDescription("Git Diff Margin displays live changes of the currently edited file on Visual Studio margin and scroll bar.")] +[assembly: + AssemblyDescription( + "Git Diff Margin displays live changes of the currently edited file on Visual Studio margin and scroll bar.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Laurent Kempé")] [assembly: AssemblyProduct("Git Diff Margin")] @@ -52,5 +54,9 @@ Version = "1.0.0.0", CodeBase = "$PackageFolder$\\Tvl.VisualStudio.Text.Utility.10.dll")] -[assembly: InternalsVisibleTo("GitDiffMargin.Commands, PublicKey=00240000048000009400000006020000002400005253413100040000010001007df3fa608a609f848a39944defc0b31e504b3e84fc5c7cd6008277f4c323cc8332ce97434c483558e43fb4d6b5c6e4c4ddb3711dabafef0e79bda1f02d49621c7bc1da4b6847707f70417455e6b76cb27c08f4d32ad29a20233124023b809d2be10d3b0a003edeee23c0d8758b384103a18c95ba323c63a451052d84dc7672d0")] -[assembly: InternalsVisibleTo("GitDiffMargin.LegacyCommands, PublicKey=00240000048000009400000006020000002400005253413100040000010001007df3fa608a609f848a39944defc0b31e504b3e84fc5c7cd6008277f4c323cc8332ce97434c483558e43fb4d6b5c6e4c4ddb3711dabafef0e79bda1f02d49621c7bc1da4b6847707f70417455e6b76cb27c08f4d32ad29a20233124023b809d2be10d3b0a003edeee23c0d8758b384103a18c95ba323c63a451052d84dc7672d0")] +[assembly: + InternalsVisibleTo( + "GitDiffMargin.Commands, PublicKey=00240000048000009400000006020000002400005253413100040000010001007df3fa608a609f848a39944defc0b31e504b3e84fc5c7cd6008277f4c323cc8332ce97434c483558e43fb4d6b5c6e4c4ddb3711dabafef0e79bda1f02d49621c7bc1da4b6847707f70417455e6b76cb27c08f4d32ad29a20233124023b809d2be10d3b0a003edeee23c0d8758b384103a18c95ba323c63a451052d84dc7672d0")] +[assembly: + InternalsVisibleTo( + "GitDiffMargin.LegacyCommands, PublicKey=00240000048000009400000006020000002400005253413100040000010001007df3fa608a609f848a39944defc0b31e504b3e84fc5c7cd6008277f4c323cc8332ce97434c483558e43fb4d6b5c6e4c4ddb3711dabafef0e79bda1f02d49621c7bc1da4b6847707f70417455e6b76cb27c08f4d32ad29a20233124023b809d2be10d3b0a003edeee23c0d8758b384103a18c95ba323c63a451052d84dc7672d0")] \ No newline at end of file diff --git a/GitDiffMargin/ScrollDiffMargin.cs b/GitDiffMargin/ScrollDiffMargin.cs index 3c12fa7..9584e0c 100644 --- a/GitDiffMargin/ScrollDiffMargin.cs +++ b/GitDiffMargin/ScrollDiffMargin.cs @@ -9,28 +9,26 @@ namespace GitDiffMargin { internal sealed class ScrollDiffMargin : DiffMarginBase { - private readonly IVerticalScrollBar _scrollBar; private const double MarginWidth = 4.0; public const string MarginNameConst = "ScrollDiffMargin"; - - protected override string MarginName - { - get { return MarginNameConst; } - } + private readonly IVerticalScrollBar _scrollBar; internal ScrollDiffMargin(IWpfTextView textView, IMarginCore marginCore, IWpfTextViewMargin containerMargin) : base(textView) { var scrollBarMargin = containerMargin.GetTextViewMargin(PredefinedMarginNames.VerticalScrollBar); // ReSharper disable once SuspiciousTypeConversion.Global - _scrollBar = (IVerticalScrollBar)scrollBarMargin; + _scrollBar = (IVerticalScrollBar) scrollBarMargin; ViewModel = new ScrollDiffMarginViewModel(marginCore, UpdateDiffDimensions); - UserControl = new ScrollDiffMarginControl { DataContext = ViewModel, Width = MarginWidth, MaxWidth = MarginWidth, MinWidth = MarginWidth}; + UserControl = new ScrollDiffMarginControl + {DataContext = ViewModel, Width = MarginWidth, MaxWidth = MarginWidth, MinWidth = MarginWidth}; } + protected override string MarginName => MarginNameConst; + private void UpdateDiffDimensions(DiffViewModel diffViewModel, HunkRangeInfo hunkRangeInfo) { if (TextView.IsClosed) @@ -45,9 +43,7 @@ private void UpdateDiffDimensions(DiffViewModel diffViewModel, HunkRangeInfo hun || startLineNumber >= snapshot.LineCount || endLineNumber < 0 || endLineNumber >= snapshot.LineCount) - { return; - } var startLine = snapshot.GetLineFromLineNumber(startLineNumber); var endLine = snapshot.GetLineFromLineNumber(endLineNumber); @@ -58,7 +54,8 @@ private void UpdateDiffDimensions(DiffViewModel diffViewModel, HunkRangeInfo hun var mapBottom = _scrollBar.Map.GetCoordinateAtBufferPosition(endLine.End) + 0.5; diffViewModel.Top = Math.Round(_scrollBar.GetYCoordinateOfScrollMapPosition(mapTop)) - 2.0; - diffViewModel.Height = Math.Round(_scrollBar.GetYCoordinateOfScrollMapPosition(mapBottom)) - diffViewModel.Top + 2.0; + diffViewModel.Height = Math.Round(_scrollBar.GetYCoordinateOfScrollMapPosition(mapBottom)) - + diffViewModel.Top + 2.0; } } } \ No newline at end of file diff --git a/GitDiffMargin/ScrollDiffMarginFactory2012.cs b/GitDiffMargin/ScrollDiffMarginFactory2012.cs index 3394cab..eddff97 100644 --- a/GitDiffMargin/ScrollDiffMarginFactory2012.cs +++ b/GitDiffMargin/ScrollDiffMarginFactory2012.cs @@ -13,7 +13,8 @@ namespace GitDiffMargin [Order(After = PredefinedMarginNames.VerticalScrollBar)] internal sealed class ScrollDiffMarginFactory2012 : DiffMarginFactoryBase { - public override IWpfTextViewMargin CreateMargin(IWpfTextViewHost textViewHost, IWpfTextViewMargin containerMargin) + public override IWpfTextViewMargin CreateMargin(IWpfTextViewHost textViewHost, + IWpfTextViewMargin containerMargin) { // Visual Studio uses assembly binding redirection for the Shell assembly. if (typeof(ErrorHandler).Assembly.GetName().Version.Major >= 12) @@ -26,4 +27,4 @@ public override IWpfTextViewMargin CreateMargin(IWpfTextViewHost textViewHost, I return new ScrollDiffMargin(textViewHost.TextView, marginCore, containerMargin); } } -} +} \ No newline at end of file diff --git a/GitDiffMargin/ScrollDiffMarginFactory2013.cs b/GitDiffMargin/ScrollDiffMarginFactory2013.cs index 9662408..a881c0f 100644 --- a/GitDiffMargin/ScrollDiffMarginFactory2013.cs +++ b/GitDiffMargin/ScrollDiffMarginFactory2013.cs @@ -16,7 +16,8 @@ namespace GitDiffMargin [Order(Before = "OverviewSourceImageMargin")] internal sealed class ScrollDiffMarginFactory2013 : DiffMarginFactoryBase { - public override IWpfTextViewMargin CreateMargin(IWpfTextViewHost textViewHost, IWpfTextViewMargin containerMargin) + public override IWpfTextViewMargin CreateMargin(IWpfTextViewHost textViewHost, + IWpfTextViewMargin containerMargin) { // Visual Studio uses assembly binding redirection for the Shell assembly. if (typeof(ErrorHandler).Assembly.GetName().Version.Major < 12) @@ -29,4 +30,4 @@ public override IWpfTextViewMargin CreateMargin(IWpfTextViewHost textViewHost, I return new ScrollDiffMargin(textViewHost.TextView, marginCore, containerMargin); } } -} +} \ No newline at end of file diff --git a/GitDiffMargin/View/EditorDiffMarginControl.xaml b/GitDiffMargin/View/EditorDiffMarginControl.xaml index 9cce565..39564f1 100644 --- a/GitDiffMargin/View/EditorDiffMarginControl.xaml +++ b/GitDiffMargin/View/EditorDiffMarginControl.xaml @@ -13,13 +13,14 @@ mc:Ignorable="d"> - - - - - - - + + + + + + + @@ -42,25 +43,25 @@ - - + + - - + \ No newline at end of file diff --git a/GitDiffMargin/View/EditorDiffMarginControl.xaml.cs b/GitDiffMargin/View/EditorDiffMarginControl.xaml.cs index 0348c2b..fb46e51 100644 --- a/GitDiffMargin/View/EditorDiffMarginControl.xaml.cs +++ b/GitDiffMargin/View/EditorDiffMarginControl.xaml.cs @@ -11,7 +11,7 @@ namespace GitDiffMargin.View { /// - /// Interaction logic for EditorDiffMarginControl.xaml + /// Interaction logic for EditorDiffMarginControl.xaml /// public partial class EditorDiffMarginControl { @@ -27,6 +27,8 @@ public EditorDiffMarginControl() InitializeComponent(); } + public static CustomPopupPlacementCallback CustomPopupPlacementCallback => CustomPopupPlacementCallbackImpl; + private void Button_Click(object sender, RoutedEventArgs e) { ClickWaitTimer.Tag = sender as Button; @@ -41,7 +43,7 @@ private void Button_MouseDoubleClick(object sender, MouseButtonEventArgs e) e.Handled = true; var button = sender as Button; - var editorDiffViewModel = (EditorDiffViewModel)button?.DataContext; + var editorDiffViewModel = (EditorDiffViewModel) button?.DataContext; editorDiffViewModel?.ShowDifferenceCommand.Execute(null); } @@ -69,9 +71,8 @@ private static void DoubleClick(object sender, EventArgs e) editorDiffViewModel?.ShowPopUpCommand.Execute(editorDiffMarginViewModel); } - public static CustomPopupPlacementCallback CustomPopupPlacementCallback => CustomPopupPlacementCallbackImpl; - - private static CustomPopupPlacement[] CustomPopupPlacementCallbackImpl(Size popupSize, Size targetSize, Point offset) + private static CustomPopupPlacement[] CustomPopupPlacementCallbackImpl(Size popupSize, Size targetSize, + Point offset) { var verticalPlacement = new CustomPopupPlacement(offset, PopupPrimaryAxis.Vertical); var horizontalPlacement = new CustomPopupPlacement(offset, PopupPrimaryAxis.Horizontal); diff --git a/GitDiffMargin/View/PopupKeyboardBehavior.cs b/GitDiffMargin/View/PopupKeyboardBehavior.cs index 4c49acc..ecedeb8 100644 --- a/GitDiffMargin/View/PopupKeyboardBehavior.cs +++ b/GitDiffMargin/View/PopupKeyboardBehavior.cs @@ -38,7 +38,7 @@ public class PopupAllowKeyboardInput public static bool GetIsEnabled(DependencyObject d) { - return (bool)d.GetValue(IsEnabledProperty); + return (bool) d.GetValue(IsEnabledProperty); } public static void SetIsEnabled(DependencyObject d, bool value) @@ -48,7 +48,7 @@ public static void SetIsEnabled(DependencyObject d, bool value) private static void IsEnabledChanged(DependencyObject sender, DependencyPropertyChangedEventArgs ea) { - EnableKeyboardInput((Popup)sender, (bool)ea.NewValue); + EnableKeyboardInput((Popup) sender, (bool) ea.NewValue); } private static void EnableKeyboardInput(Popup popup, bool enabled) diff --git a/GitDiffMargin/View/ScrollDiffMarginControl.xaml b/GitDiffMargin/View/ScrollDiffMarginControl.xaml index 11eb1bb..9e066c9 100644 --- a/GitDiffMargin/View/ScrollDiffMarginControl.xaml +++ b/GitDiffMargin/View/ScrollDiffMarginControl.xaml @@ -11,63 +11,63 @@ Width="4" MinWidth="4" MaxWidth="4"> - - - - - - - - - - - - - - - - - - - - - + + + + + + + - - - - - - - - - - - - - - + + + + + + + \ No newline at end of file diff --git a/GitDiffMargin/View/ScrollDiffMarginControl.xaml.cs b/GitDiffMargin/View/ScrollDiffMarginControl.xaml.cs index 42eb859..ac11365 100644 --- a/GitDiffMargin/View/ScrollDiffMarginControl.xaml.cs +++ b/GitDiffMargin/View/ScrollDiffMarginControl.xaml.cs @@ -1,9 +1,7 @@ -using System.Windows.Controls; - -namespace GitDiffMargin.View +namespace GitDiffMargin.View { /// - /// Interaction logic for ScrollDiffMarginControl.xaml + /// Interaction logic for ScrollDiffMarginControl.xaml /// public partial class ScrollDiffMarginControl { @@ -12,4 +10,4 @@ public ScrollDiffMarginControl() InitializeComponent(); } } -} +} \ No newline at end of file diff --git a/GitDiffMargin/ViewModel/DiffMarginViewModelBase.cs b/GitDiffMargin/ViewModel/DiffMarginViewModelBase.cs index 3f53261..5573e3b 100644 --- a/GitDiffMargin/ViewModel/DiffMarginViewModelBase.cs +++ b/GitDiffMargin/ViewModel/DiffMarginViewModelBase.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using GalaSoft.MvvmLight; @@ -24,24 +23,18 @@ protected DiffMarginViewModelBase(IMarginCore marginCore) MarginCore.HunksChanged += HandleHunksChanged; } - public ObservableCollection DiffViewModels { get; private set; } + public ObservableCollection DiffViewModels { get; } public void RefreshDiffViewModelPositions() { - foreach (var diffViewModel in DiffViewModels) - { - diffViewModel.RefreshPosition(); - } + foreach (var diffViewModel in DiffViewModels) diffViewModel.RefreshPosition(); } protected virtual void HandleHunksChanged(object sender, HunksChangedEventArgs e) { DiffViewModels.Clear(); - foreach (var diffViewModel in e.Hunks.Select(CreateDiffViewModel)) - { - DiffViewModels.Add(diffViewModel); - } + foreach (var diffViewModel in e.Hunks.Select(CreateDiffViewModel)) DiffViewModels.Add(diffViewModel); } protected abstract DiffViewModel CreateDiffViewModel(HunkRangeInfo hunkRangeInfo); diff --git a/GitDiffMargin/ViewModel/DiffViewModel.cs b/GitDiffMargin/ViewModel/DiffViewModel.cs index 95e0b6e..ec133c0 100644 --- a/GitDiffMargin/ViewModel/DiffViewModel.cs +++ b/GitDiffMargin/ViewModel/DiffViewModel.cs @@ -1,6 +1,6 @@ using System; using System.Windows; -using System.Windows.Media; +using System.Windows.Media; using GalaSoft.MvvmLight; using GitDiffMargin.Core; using GitDiffMargin.Git; @@ -9,14 +9,15 @@ namespace GitDiffMargin.ViewModel { internal abstract class DiffViewModel : ViewModelBase { - private double _height; - private double _top; + private readonly Action _updateDiffDimensions; protected readonly HunkRangeInfo HunkRangeInfo; protected readonly IMarginCore MarginCore; - private readonly Action _updateDiffDimensions; + private double _height; private bool _isVisible; + private double _top; - protected DiffViewModel(HunkRangeInfo hunkRangeInfo, IMarginCore marginCore, Action updateDiffDimensions) + protected DiffViewModel(HunkRangeInfo hunkRangeInfo, IMarginCore marginCore, + Action updateDiffDimensions) { HunkRangeInfo = hunkRangeInfo; MarginCore = marginCore; @@ -27,7 +28,7 @@ protected DiffViewModel(HunkRangeInfo hunkRangeInfo, IMarginCore marginCore, Act public double Height { - get { return _height; } + get => _height; set { _height = value; @@ -37,7 +38,7 @@ public double Height public double Top { - get { return _top; } + get => _top; set { _top = value; @@ -45,45 +46,33 @@ public double Top } } - public virtual double Width - { - get - { - return MarginCore.EditorChangeWidth; - } - } + public virtual double Width => MarginCore.EditorChangeWidth; - public Thickness Margin - { - get - { - return new Thickness(MarginCore.EditorChangeLeft, 0, 0, 0); - } - } + public Thickness Margin => new Thickness(MarginCore.EditorChangeLeft, 0, 0, 0); - public bool IsDeletion { get { return HunkRangeInfo.IsDeletion;} } + public bool IsDeletion => HunkRangeInfo.IsDeletion; public Brush DiffBrush { get { - if (HunkRangeInfo.IsAddition) - { - return MarginCore.AdditionBrush; - } + if (HunkRangeInfo.IsAddition) return MarginCore.AdditionBrush; return HunkRangeInfo.IsModification ? MarginCore.ModificationBrush : MarginCore.RemovedBrush; } } - public int LineNumber { get { return HunkRangeInfo.NewHunkRange.StartingLineNumber; } } + public int LineNumber => HunkRangeInfo.NewHunkRange.StartingLineNumber; public int NumberOfLines { get { return HunkRangeInfo.NewHunkRange.NumberOfLines; } } public virtual bool IsVisible { - get { return _isVisible; } - set { _isVisible = value; - RaisePropertyChanged(() => IsVisible);} + get => _isVisible; + set + { + _isVisible = value; + RaisePropertyChanged(() => IsVisible); + } } public void RefreshPosition() diff --git a/GitDiffMargin/ViewModel/EditorDiffMarginViewModel.cs b/GitDiffMargin/ViewModel/EditorDiffMarginViewModel.cs index a52b39a..1fe5df9 100644 --- a/GitDiffMargin/ViewModel/EditorDiffMarginViewModel.cs +++ b/GitDiffMargin/ViewModel/EditorDiffMarginViewModel.cs @@ -13,10 +13,11 @@ namespace GitDiffMargin.ViewModel internal class EditorDiffMarginViewModel : DiffMarginViewModelBase { private readonly Action _updateDiffDimensions; - private RelayCommand _previousChangeCommand; private RelayCommand _nextChangeCommand; + private RelayCommand _previousChangeCommand; - internal EditorDiffMarginViewModel(IMarginCore marginCore, Action updateDiffDimensions) : + internal EditorDiffMarginViewModel(IMarginCore marginCore, + Action updateDiffDimensions) : base(marginCore) { if (updateDiffDimensions == null) @@ -25,15 +26,13 @@ internal EditorDiffMarginViewModel(IMarginCore marginCore, Action PreviousChangeCommand - { - get { return _previousChangeCommand ?? (_previousChangeCommand = new RelayCommand(PreviousChange, PreviousChangeCanExecute)); } - } + public RelayCommand PreviousChangeCommand => + _previousChangeCommand ?? (_previousChangeCommand = + new RelayCommand(PreviousChange, PreviousChangeCanExecute)); - public RelayCommand NextChangeCommand - { - get { return _nextChangeCommand ?? (_nextChangeCommand = new RelayCommand(NextChange, NextChangeCanExecute)); } - } + public RelayCommand NextChangeCommand => + _nextChangeCommand ?? + (_nextChangeCommand = new RelayCommand(NextChange, NextChangeCanExecute)); public void FocusTextView() { @@ -47,7 +46,7 @@ private bool PreviousChangeCanExecute(DiffViewModel currentEditorDiffViewModel) private bool NextChangeCanExecute(DiffViewModel currentEditorDiffViewModel) { - return DiffViewModels.IndexOf(currentEditorDiffViewModel) < (DiffViewModels.Count - 1); + return DiffViewModels.IndexOf(currentEditorDiffViewModel) < DiffViewModels.Count - 1; } private void PreviousChange(DiffViewModel currentEditorDiffViewModel) @@ -63,11 +62,11 @@ private void NextChange(DiffViewModel currentEditorDiffViewModel) public void MoveToChange(DiffViewModel currentDiffViewModel, int indexModifier) { var diffViewModelIndex = DiffViewModels.IndexOf(currentDiffViewModel) + indexModifier; - var diffViewModel = DiffViewModels[diffViewModelIndex]; + var diffViewModel = DiffViewModels[diffViewModelIndex]; MarginCore.MoveToChange(diffViewModel.LineNumber); - ((EditorDiffViewModel)currentDiffViewModel).ShowPopup = false; + ((EditorDiffViewModel) currentDiffViewModel).ShowPopup = false; } protected override void HandleHunksChanged(object sender, HunksChangedEventArgs e) diff --git a/GitDiffMargin/ViewModel/EditorDiffViewModel.cs b/GitDiffMargin/ViewModel/EditorDiffViewModel.cs index 945c71e..05b7470 100644 --- a/GitDiffMargin/ViewModel/EditorDiffViewModel.cs +++ b/GitDiffMargin/ViewModel/EditorDiffViewModel.cs @@ -10,9 +10,9 @@ using GitDiffMargin.Core; using GitDiffMargin.Git; using Microsoft.VisualStudio; +using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; -using IOleCommandTarget = Microsoft.VisualStudio.OLE.Interop.IOleCommandTarget; #endregion @@ -20,17 +20,20 @@ namespace GitDiffMargin.ViewModel { internal class EditorDiffViewModel : DiffViewModel { + private ICommand _copyOldTextCommand; + + private EditorDiffMarginViewModel _diffMarginViewModel; private bool _isDiffTextVisible; - private bool _showPopup; private bool _reverted; - private ICommand _copyOldTextCommand; private ICommand _rollbackCommand; - private ICommand _showPopUpCommand; - private EditorDiffMarginViewModel _diffMarginViewModel; + private ICommand _showDifferenceCommand; + private bool _showPopup; + private ICommand _showPopUpCommand; private IVsToolbarTrayHost _toolbarTrayHost; - internal EditorDiffViewModel(HunkRangeInfo hunkRangeInfo, IMarginCore marginCore, Action updateDiffDimensions) + internal EditorDiffViewModel(HunkRangeInfo hunkRangeInfo, IMarginCore marginCore, + Action updateDiffDimensions) : base(hunkRangeInfo, marginCore, updateDiffDimensions) { ShowPopup = false; @@ -42,61 +45,15 @@ internal EditorDiffViewModel(HunkRangeInfo hunkRangeInfo, IMarginCore marginCore UpdateDimensions(); } - private bool GetIsDiffTextVisible() - { - return HunkRangeInfo.IsDeletion || HunkRangeInfo.IsModification; - } - - private string GetDiffText() - { - if (HunkRangeInfo.OriginalText != null && HunkRangeInfo.OriginalText.Any()) - { - return HunkRangeInfo.IsModification || HunkRangeInfo.IsDeletion ? String.Join(Environment.NewLine, HunkRangeInfo.OriginalText) : string.Empty; - } - - return string.Empty; - } - - protected override void UpdateDimensions() - { - if (_reverted) return; + public FontFamily FontFamily => MarginCore.FontFamily; - base.UpdateDimensions(); - } + public FontStretch FontStretch => MarginCore.FontStretch; - public FontFamily FontFamily - { - get { return MarginCore.FontFamily; } - } + public FontStyle FontStyle => MarginCore.FontStyle; - public FontStretch FontStretch - { - get { return MarginCore.FontStretch; } - } - - public FontStyle FontStyle - { - get - { - return MarginCore.FontStyle; - } - } - - public FontWeight FontWeight - { - get - { - return MarginCore.FontWeight; - } - } + public FontWeight FontWeight => MarginCore.FontWeight; - public double FontSize - { - get - { - return MarginCore.FontSize; - } - } + public double FontSize => MarginCore.FontSize; //public double MaxWidth //{ @@ -114,26 +71,13 @@ public double FontSize // } //} - public Brush Background - { - get - { - return MarginCore.Background; - } - } + public Brush Background => MarginCore.Background; - public Brush Foreground - { - get - { - return MarginCore.Foreground; - } - } + public Brush Foreground => MarginCore.Foreground; - public ICommand ShowPopUpCommand - { - get { return _showPopUpCommand ?? (_showPopUpCommand = new RelayCommand(ShowPopUp)); } - } + public ICommand ShowPopUpCommand => _showPopUpCommand ?? + (_showPopUpCommand = + new RelayCommand(ShowPopUp)); public object ToolBarTray { @@ -148,7 +92,7 @@ public object ToolBarTray object uiObject; ErrorHandler.ThrowOnFailure(toolbarTray.GetUIObject(out uiObject)); - IVsUIWpfElement wpfElement = uiObject as IVsUIWpfElement; + var wpfElement = uiObject as IVsUIWpfElement; object frameworkElement; ErrorHandler.ThrowOnFailure(wpfElement.GetFrameworkElement(out frameworkElement)); @@ -159,23 +103,26 @@ public object ToolBarTray public bool ShowPopup { - get { return _showPopup; } + get => _showPopup; set { if (value == _showPopup) return; _showPopup = value; if (value) { - IVsUIShell4 uiShell = Package.GetGlobalService(typeof(SVsUIShell)) as IVsUIShell4; + var uiShell = Package.GetGlobalService(typeof(SVsUIShell)) as IVsUIShell4; if (uiShell != null) { - IOleCommandTarget commandTarget = MarginCore.TextView.Properties.GetProperty(typeof(GitDiffMarginCommandHandler)); + IOleCommandTarget commandTarget = + MarginCore.TextView.Properties.GetProperty( + typeof(GitDiffMarginCommandHandler)); IVsToolbarTrayHost toolbarTrayHost; ErrorHandler.ThrowOnFailure(uiShell.CreateToolbarTray(commandTarget, out toolbarTrayHost)); - Guid toolBarGuid = typeof(GitDiffMarginCommand).GUID; - ErrorHandler.ThrowOnFailure(toolbarTrayHost.AddToolbar(ref toolBarGuid, (int)GitDiffMarginCommand.GitDiffToolbar)); + var toolBarGuid = typeof(GitDiffMarginCommand).GUID; + ErrorHandler.ThrowOnFailure(toolbarTrayHost.AddToolbar(ref toolBarGuid, + (int) GitDiffMarginCommand.GitDiffToolbar)); _toolbarTrayHost = toolbarTrayHost; } @@ -192,11 +139,11 @@ public bool ShowPopup } } - public string DiffText { get; private set; } + public string DiffText { get; } public bool IsDiffTextVisible { - get { return _isDiffTextVisible; } + get => _isDiffTextVisible; set { if (value == _isDiffTextVisible) return; @@ -205,35 +152,48 @@ public bool IsDiffTextVisible } } - private ICommand _showDifferenceCommand; + public ICommand ShowDifferenceCommand => _showDifferenceCommand ?? + (_showDifferenceCommand = new RelayCommand(ShowDifference, + ShowDifferenceCanExecute)); - public ICommand ShowDifferenceCommand + public ICommand CopyOldTextCommand => _copyOldTextCommand ?? + (_copyOldTextCommand = + new RelayCommand(CopyOldText, CopyOldTextCanExecute)); + + public ICommand RollbackCommand => + _rollbackCommand ?? (_rollbackCommand = new RelayCommand(Rollback, RollbackCanExecute)); + + private bool GetIsDiffTextVisible() { - get { return _showDifferenceCommand ?? (_showDifferenceCommand = new RelayCommand(ShowDifference, ShowDifferenceCanExecute)); } + return HunkRangeInfo.IsDeletion || HunkRangeInfo.IsModification; } - private bool ShowDifferenceCanExecute() + private string GetDiffText() { - return HunkRangeInfo.IsModification || HunkRangeInfo.IsDeletion || HunkRangeInfo.IsAddition; + if (HunkRangeInfo.OriginalText != null && HunkRangeInfo.OriginalText.Any()) + return HunkRangeInfo.IsModification || HunkRangeInfo.IsDeletion + ? string.Join(Environment.NewLine, HunkRangeInfo.OriginalText) + : string.Empty; + + return string.Empty; } - private void ShowDifference() + protected override void UpdateDimensions() { - var document = MarginCore.GetTextDocument(); - if (document != null) - { - MarginCore.GitCommands.StartExternalDiff(document, MarginCore.OriginalPath); - } + if (_reverted) return; + + base.UpdateDimensions(); } - public ICommand CopyOldTextCommand + private bool ShowDifferenceCanExecute() { - get { return _copyOldTextCommand ?? (_copyOldTextCommand = new RelayCommand(CopyOldText, CopyOldTextCanExecute)); } + return HunkRangeInfo.IsModification || HunkRangeInfo.IsDeletion || HunkRangeInfo.IsAddition; } - public ICommand RollbackCommand + private void ShowDifference() { - get { return _rollbackCommand ?? (_rollbackCommand = new RelayCommand(Rollback, RollbackCanExecute)); } + var document = MarginCore.GetTextDocument(); + if (document != null) MarginCore.GitCommands.StartExternalDiff(document, MarginCore.OriginalPath); } private bool CopyOldTextCanExecute() diff --git a/GitDiffMargin/ViewModel/ScrollDiffMarginViewModel.cs b/GitDiffMargin/ViewModel/ScrollDiffMarginViewModel.cs index f7726b7..8194469 100644 --- a/GitDiffMargin/ViewModel/ScrollDiffMarginViewModel.cs +++ b/GitDiffMargin/ViewModel/ScrollDiffMarginViewModel.cs @@ -8,7 +8,8 @@ internal class ScrollDiffMarginViewModel : DiffMarginViewModelBase { private readonly Action _updateDiffDimensions; - internal ScrollDiffMarginViewModel(IMarginCore marginCore, Action updateDiffDimensions) : + internal ScrollDiffMarginViewModel(IMarginCore marginCore, + Action updateDiffDimensions) : base(marginCore) { if (updateDiffDimensions == null) diff --git a/GitDiffMargin/ViewModel/ScrollDiffViewModel.cs b/GitDiffMargin/ViewModel/ScrollDiffViewModel.cs index 1dc9a22..bfa50eb 100644 --- a/GitDiffMargin/ViewModel/ScrollDiffViewModel.cs +++ b/GitDiffMargin/ViewModel/ScrollDiffViewModel.cs @@ -6,7 +6,8 @@ namespace GitDiffMargin.ViewModel { internal sealed class ScrollDiffViewModel : DiffViewModel { - internal ScrollDiffViewModel(HunkRangeInfo hunkRangeInfo, IMarginCore marginCore, Action updateDiffDimensions) + internal ScrollDiffViewModel(HunkRangeInfo hunkRangeInfo, IMarginCore marginCore, + Action updateDiffDimensions) : base(hunkRangeInfo, marginCore, updateDiffDimensions) { UpdateDimensions(); @@ -14,17 +15,10 @@ internal ScrollDiffViewModel(HunkRangeInfo hunkRangeInfo, IMarginCore marginCore public override bool IsVisible { - get { return true; } + get => true; set { } } - public override double Width - { - get - { - return MarginCore.ScrollChangeWidth; - } - } - + public override double Width => MarginCore.ScrollChangeWidth; } } \ No newline at end of file From 712fa20ee8069c2cbee109e47377b70331f8de5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 14:27:38 +0000 Subject: [PATCH 03/18] Use nameof in place of string --- GitDiffMargin/Core/BackgroundParser.cs | 10 +++++----- GitDiffMargin/GitDiffMarginCommandHandler.cs | 4 ++-- GitDiffMargin/ViewModel/DiffMarginViewModelBase.cs | 2 +- GitDiffMargin/ViewModel/EditorDiffMarginViewModel.cs | 2 +- GitDiffMargin/ViewModel/ScrollDiffMarginViewModel.cs | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/GitDiffMargin/Core/BackgroundParser.cs b/GitDiffMargin/Core/BackgroundParser.cs index bb8a1c7..683f6c0 100644 --- a/GitDiffMargin/Core/BackgroundParser.cs +++ b/GitDiffMargin/Core/BackgroundParser.cs @@ -1,4 +1,4 @@ -/* The MIT License +/* The MIT License * * Copyright (c) 2013 Sam Harwell, Tunnel Vision Labs, LLC * @@ -45,11 +45,11 @@ protected BackgroundParser(ITextBuffer textBuffer, TaskScheduler taskScheduler, ITextDocumentFactoryService textDocumentFactoryService) { if (textBuffer == null) - throw new ArgumentNullException("textBuffer"); + throw new ArgumentNullException(nameof(textBuffer)); if (taskScheduler == null) - throw new ArgumentNullException("taskScheduler"); + throw new ArgumentNullException(nameof(taskScheduler)); if (textDocumentFactoryService == null) - throw new ArgumentNullException("textDocumentFactoryService"); + throw new ArgumentNullException(nameof(textDocumentFactoryService)); _textBuffer = new WeakReference(textBuffer); _taskScheduler = taskScheduler; @@ -122,7 +122,7 @@ protected virtual void Dispose(bool disposing) protected virtual void OnParseComplete(ParseResultEventArgs e) { if (e == null) - throw new ArgumentNullException("e"); + throw new ArgumentNullException(nameof(e)); var t = ParseComplete; if (t != null) diff --git a/GitDiffMargin/GitDiffMarginCommandHandler.cs b/GitDiffMargin/GitDiffMarginCommandHandler.cs index 4f44728..9e8fda6 100644 --- a/GitDiffMargin/GitDiffMarginCommandHandler.cs +++ b/GitDiffMargin/GitDiffMarginCommandHandler.cs @@ -22,9 +22,9 @@ public GitDiffMarginCommandHandler(IVsTextView textViewAdapter, : base(textViewAdapter) { if (editorAdaptersFactoryService == null) - throw new ArgumentNullException("editorAdaptersFactoryService"); + throw new ArgumentNullException(nameof(editorAdaptersFactoryService)); if (textView == null) - throw new ArgumentNullException("textView"); + throw new ArgumentNullException(nameof(textView)); _editorAdaptersFactoryService = editorAdaptersFactoryService; _textView = textView; diff --git a/GitDiffMargin/ViewModel/DiffMarginViewModelBase.cs b/GitDiffMargin/ViewModel/DiffMarginViewModelBase.cs index 5573e3b..fac679a 100644 --- a/GitDiffMargin/ViewModel/DiffMarginViewModelBase.cs +++ b/GitDiffMargin/ViewModel/DiffMarginViewModelBase.cs @@ -14,7 +14,7 @@ internal abstract class DiffMarginViewModelBase : ViewModelBase protected DiffMarginViewModelBase(IMarginCore marginCore) { if (marginCore == null) - throw new ArgumentNullException("marginCore"); + throw new ArgumentNullException(nameof(marginCore)); MarginCore = marginCore; diff --git a/GitDiffMargin/ViewModel/EditorDiffMarginViewModel.cs b/GitDiffMargin/ViewModel/EditorDiffMarginViewModel.cs index 1fe5df9..382d0bf 100644 --- a/GitDiffMargin/ViewModel/EditorDiffMarginViewModel.cs +++ b/GitDiffMargin/ViewModel/EditorDiffMarginViewModel.cs @@ -21,7 +21,7 @@ internal EditorDiffMarginViewModel(IMarginCore marginCore, base(marginCore) { if (updateDiffDimensions == null) - throw new ArgumentNullException("updateDiffDimensions"); + throw new ArgumentNullException(nameof(updateDiffDimensions)); _updateDiffDimensions = updateDiffDimensions; } diff --git a/GitDiffMargin/ViewModel/ScrollDiffMarginViewModel.cs b/GitDiffMargin/ViewModel/ScrollDiffMarginViewModel.cs index 8194469..093c694 100644 --- a/GitDiffMargin/ViewModel/ScrollDiffMarginViewModel.cs +++ b/GitDiffMargin/ViewModel/ScrollDiffMarginViewModel.cs @@ -13,7 +13,7 @@ internal ScrollDiffMarginViewModel(IMarginCore marginCore, base(marginCore) { if (updateDiffDimensions == null) - throw new ArgumentNullException("updateDiffDimensions"); + throw new ArgumentNullException(nameof(updateDiffDimensions)); _updateDiffDimensions = updateDiffDimensions; } From 165872d26bd51a78c9d2038aea0d8f715b928323 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 14:30:05 +0000 Subject: [PATCH 04/18] Join null check with assignement --- GitDiffMargin/Core/BackgroundParser.cs | 10 +++------- GitDiffMargin/GitDiffMarginCommandHandler.cs | 9 ++------- GitDiffMargin/ViewModel/DiffMarginViewModelBase.cs | 5 +---- GitDiffMargin/ViewModel/EditorDiffMarginViewModel.cs | 5 +---- GitDiffMargin/ViewModel/ScrollDiffMarginViewModel.cs | 5 +---- 5 files changed, 8 insertions(+), 26 deletions(-) diff --git a/GitDiffMargin/Core/BackgroundParser.cs b/GitDiffMargin/Core/BackgroundParser.cs index 683f6c0..ceeeaae 100644 --- a/GitDiffMargin/Core/BackgroundParser.cs +++ b/GitDiffMargin/Core/BackgroundParser.cs @@ -46,14 +46,10 @@ protected BackgroundParser(ITextBuffer textBuffer, TaskScheduler taskScheduler, { if (textBuffer == null) throw new ArgumentNullException(nameof(textBuffer)); - if (taskScheduler == null) - throw new ArgumentNullException(nameof(taskScheduler)); - if (textDocumentFactoryService == null) - throw new ArgumentNullException(nameof(textDocumentFactoryService)); - _textBuffer = new WeakReference(textBuffer); - _taskScheduler = taskScheduler; - TextDocumentFactoryService = textDocumentFactoryService; + + _taskScheduler = taskScheduler ?? throw new ArgumentNullException(nameof(taskScheduler)); + TextDocumentFactoryService = textDocumentFactoryService ?? throw new ArgumentNullException(nameof(textDocumentFactoryService)); textBuffer.PostChanged += TextBufferPostChanged; diff --git a/GitDiffMargin/GitDiffMarginCommandHandler.cs b/GitDiffMargin/GitDiffMarginCommandHandler.cs index 9e8fda6..5b877fd 100644 --- a/GitDiffMargin/GitDiffMarginCommandHandler.cs +++ b/GitDiffMargin/GitDiffMarginCommandHandler.cs @@ -21,13 +21,8 @@ public GitDiffMarginCommandHandler(IVsTextView textViewAdapter, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ITextView textView) : base(textViewAdapter) { - if (editorAdaptersFactoryService == null) - throw new ArgumentNullException(nameof(editorAdaptersFactoryService)); - if (textView == null) - throw new ArgumentNullException(nameof(textView)); - - _editorAdaptersFactoryService = editorAdaptersFactoryService; - _textView = textView; + _editorAdaptersFactoryService = editorAdaptersFactoryService ?? throw new ArgumentNullException(nameof(editorAdaptersFactoryService)); + _textView = textView ?? throw new ArgumentNullException(nameof(textView)); } protected override OLECMDF QueryCommandStatus(ref Guid commandGroup, uint commandId, diff --git a/GitDiffMargin/ViewModel/DiffMarginViewModelBase.cs b/GitDiffMargin/ViewModel/DiffMarginViewModelBase.cs index fac679a..583305a 100644 --- a/GitDiffMargin/ViewModel/DiffMarginViewModelBase.cs +++ b/GitDiffMargin/ViewModel/DiffMarginViewModelBase.cs @@ -13,10 +13,7 @@ internal abstract class DiffMarginViewModelBase : ViewModelBase protected DiffMarginViewModelBase(IMarginCore marginCore) { - if (marginCore == null) - throw new ArgumentNullException(nameof(marginCore)); - - MarginCore = marginCore; + MarginCore = marginCore ?? throw new ArgumentNullException(nameof(marginCore)); DiffViewModels = new ObservableCollection(); diff --git a/GitDiffMargin/ViewModel/EditorDiffMarginViewModel.cs b/GitDiffMargin/ViewModel/EditorDiffMarginViewModel.cs index 382d0bf..c7cf93e 100644 --- a/GitDiffMargin/ViewModel/EditorDiffMarginViewModel.cs +++ b/GitDiffMargin/ViewModel/EditorDiffMarginViewModel.cs @@ -20,10 +20,7 @@ internal EditorDiffMarginViewModel(IMarginCore marginCore, Action updateDiffDimensions) : base(marginCore) { - if (updateDiffDimensions == null) - throw new ArgumentNullException(nameof(updateDiffDimensions)); - - _updateDiffDimensions = updateDiffDimensions; + _updateDiffDimensions = updateDiffDimensions ?? throw new ArgumentNullException(nameof(updateDiffDimensions)); } public RelayCommand PreviousChangeCommand => diff --git a/GitDiffMargin/ViewModel/ScrollDiffMarginViewModel.cs b/GitDiffMargin/ViewModel/ScrollDiffMarginViewModel.cs index 093c694..14e399e 100644 --- a/GitDiffMargin/ViewModel/ScrollDiffMarginViewModel.cs +++ b/GitDiffMargin/ViewModel/ScrollDiffMarginViewModel.cs @@ -12,10 +12,7 @@ internal ScrollDiffMarginViewModel(IMarginCore marginCore, Action updateDiffDimensions) : base(marginCore) { - if (updateDiffDimensions == null) - throw new ArgumentNullException(nameof(updateDiffDimensions)); - - _updateDiffDimensions = updateDiffDimensions; + _updateDiffDimensions = updateDiffDimensions ?? throw new ArgumentNullException(nameof(updateDiffDimensions)); } protected override DiffViewModel CreateDiffViewModel(HunkRangeInfo hunkRangeInfo) From 94ecf03bdb982b30aa19febab5187ae570e2eeb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 14:42:30 +0000 Subject: [PATCH 05/18] Use null propagation --- GitDiffMargin/Core/BackgroundParser.cs | 9 ++++----- GitDiffMargin/Core/DiffUpdateBackgroundParser.cs | 4 ++-- GitDiffMargin/Core/MarginCore.cs | 10 +++------- GitDiffMargin/GitDiffMarginCommandHandler.cs | 7 +++---- GitDiffMargin/View/EditorDiffMarginControl.xaml.cs | 9 ++------- 5 files changed, 14 insertions(+), 25 deletions(-) diff --git a/GitDiffMargin/Core/BackgroundParser.cs b/GitDiffMargin/Core/BackgroundParser.cs index ceeeaae..7be727a 100644 --- a/GitDiffMargin/Core/BackgroundParser.cs +++ b/GitDiffMargin/Core/BackgroundParser.cs @@ -49,7 +49,8 @@ protected BackgroundParser(ITextBuffer textBuffer, TaskScheduler taskScheduler, _textBuffer = new WeakReference(textBuffer); _taskScheduler = taskScheduler ?? throw new ArgumentNullException(nameof(taskScheduler)); - TextDocumentFactoryService = textDocumentFactoryService ?? throw new ArgumentNullException(nameof(textDocumentFactoryService)); + TextDocumentFactoryService = textDocumentFactoryService ?? + throw new ArgumentNullException(nameof(textDocumentFactoryService)); textBuffer.PostChanged += TextBufferPostChanged; @@ -115,14 +116,12 @@ protected virtual void Dispose(bool disposing) protected abstract void ReParseImpl(); - protected virtual void OnParseComplete(ParseResultEventArgs e) + protected void OnParseComplete(ParseResultEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); - var t = ParseComplete; - if (t != null) - t(this, e); + ParseComplete?.Invoke(this, e); } protected void MarkDirty(bool resetTimer) diff --git a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs index 22724cb..6aeb901 100644 --- a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs +++ b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Diagnostics; using System.IO; using System.Linq; @@ -112,7 +112,7 @@ protected override void Dispose(bool disposing) if (disposing) { if (_textDocument != null) _textDocument.FileActionOccurred -= OnFileActionOccurred; - if (_watcher != null) _watcher.Dispose(); + _watcher?.Dispose(); } } } diff --git a/GitDiffMargin/Core/MarginCore.cs b/GitDiffMargin/Core/MarginCore.cs index 64d483e..399e96e 100644 --- a/GitDiffMargin/Core/MarginCore.cs +++ b/GitDiffMargin/Core/MarginCore.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Windows; @@ -262,9 +262,7 @@ private void UpdateBrushes() private void OnBrushesChanged(EventArgs e) { - var t = BrushesChanged; - if (t != null) - t(this, e); + BrushesChanged?.Invoke(this, e); } private static Brush GetBrush(ResourceDictionary properties) @@ -300,9 +298,7 @@ private void HandleParseComplete(object sender, ParseResultEventArgs e) private void OnHunksChanged(IEnumerable hunkRangeInfos) { - var t = HunksChanged; - if (t != null) - t(this, new HunksChangedEventArgs(hunkRangeInfos)); + HunksChanged?.Invoke(this, new HunksChangedEventArgs(hunkRangeInfos)); } } } \ No newline at end of file diff --git a/GitDiffMargin/GitDiffMarginCommandHandler.cs b/GitDiffMargin/GitDiffMarginCommandHandler.cs index 5b877fd..a060c91 100644 --- a/GitDiffMargin/GitDiffMarginCommandHandler.cs +++ b/GitDiffMargin/GitDiffMarginCommandHandler.cs @@ -21,7 +21,8 @@ public GitDiffMarginCommandHandler(IVsTextView textViewAdapter, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ITextView textView) : base(textViewAdapter) { - _editorAdaptersFactoryService = editorAdaptersFactoryService ?? throw new ArgumentNullException(nameof(editorAdaptersFactoryService)); + _editorAdaptersFactoryService = editorAdaptersFactoryService ?? + throw new ArgumentNullException(nameof(editorAdaptersFactoryService)); _textView = textView ?? throw new ArgumentNullException(nameof(textView)); } @@ -219,10 +220,8 @@ private bool TryGetMarginViewModel(out EditorDiffMarginViewModel viewModel) viewModel = null; var textViewHost = _editorAdaptersFactoryService.GetWpfTextViewHost(TextViewAdapter); - if (textViewHost == null) - return false; - var margin = textViewHost.GetTextViewMargin(EditorDiffMargin.MarginNameConst) as EditorDiffMargin; + var margin = textViewHost?.GetTextViewMargin(EditorDiffMargin.MarginNameConst) as EditorDiffMargin; if (margin == null) return false; diff --git a/GitDiffMargin/View/EditorDiffMarginControl.xaml.cs b/GitDiffMargin/View/EditorDiffMarginControl.xaml.cs index fb46e51..4ab6f04 100644 --- a/GitDiffMargin/View/EditorDiffMarginControl.xaml.cs +++ b/GitDiffMargin/View/EditorDiffMarginControl.xaml.cs @@ -3,10 +3,8 @@ using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; -using System.Windows.Media; using System.Windows.Threading; using GitDiffMargin.ViewModel; -using Microsoft.VisualStudio.Shell.Interop; namespace GitDiffMargin.View { @@ -82,12 +80,9 @@ private static CustomPopupPlacement[] CustomPopupPlacementCallbackImpl(Size popu private void Popup_OnOpened(object sender, EventArgs e) { var popup = sender as Popup; - if (popup == null) return; + var contentControl = popup?.FindName("Commands") as ContentControl; - var contentControl = (ContentControl)popup.FindName("Commands"); - if (contentControl == null) return; - - contentControl.Focus(); + contentControl?.Focus(); } } } \ No newline at end of file From ec22983ca6d17fe5cf5279f59a2b21df31104c57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 14:51:41 +0000 Subject: [PATCH 06/18] Inline out variable declaration --- GitDiffMargin/Core/DiffUpdateBackgroundParser.cs | 3 +-- GitDiffMargin/Core/MarginCore.cs | 4 ++-- GitDiffMargin/DiffMarginFactoryBase.cs | 6 ++---- GitDiffMargin/GitDiffMarginCommandHandler.cs | 15 +++++---------- GitDiffMargin/ViewModel/EditorDiffViewModel.cs | 14 +++++--------- 5 files changed, 15 insertions(+), 27 deletions(-) diff --git a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs index 6aeb901..f2c2452 100644 --- a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs +++ b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs @@ -91,8 +91,7 @@ protected override void ReParseImpl() var stopwatch = Stopwatch.StartNew(); var snapshot = TextBuffer.CurrentSnapshot; - ITextDocument textDocument; - if (!TextDocumentFactoryService.TryGetTextDocument(_documentBuffer, out textDocument)) return; + if (!TextDocumentFactoryService.TryGetTextDocument(_documentBuffer, out var textDocument)) return; var diff = _commands.GetGitDiffFor(textDocument, _originalPath, snapshot); var result = new DiffParseResultEventArgs(snapshot, stopwatch.Elapsed, diff.ToList()); diff --git a/GitDiffMargin/Core/MarginCore.cs b/GitDiffMargin/Core/MarginCore.cs index 399e96e..df38a88 100644 --- a/GitDiffMargin/Core/MarginCore.cs +++ b/GitDiffMargin/Core/MarginCore.cs @@ -226,8 +226,8 @@ public bool RollBack(HunkRangeInfo hunkRangeInfo) public ITextDocument GetTextDocument() { - ITextDocument document; - TextView.TextDataModel.DocumentBuffer.Properties.TryGetProperty(typeof(ITextDocument), out document); + TextView.TextDataModel.DocumentBuffer.Properties.TryGetProperty(typeof(ITextDocument), + out ITextDocument document); return document; } diff --git a/GitDiffMargin/DiffMarginFactoryBase.cs b/GitDiffMargin/DiffMarginFactoryBase.cs index b2599e0..414d815 100644 --- a/GitDiffMargin/DiffMarginFactoryBase.cs +++ b/GitDiffMargin/DiffMarginFactoryBase.cs @@ -25,8 +25,7 @@ public abstract IWpfTextViewMargin CreateMargin(IWpfTextViewHost wpfTextViewHost protected IMarginCore TryGetMarginCore(IWpfTextViewHost textViewHost) { - MarginCore marginCore; - if (textViewHost.TextView.Properties.TryGetProperty(typeof(MarginCore), out marginCore)) + if (textViewHost.TextView.Properties.TryGetProperty(typeof(MarginCore), out MarginCore marginCore)) return marginCore; // play nice with other source control providers @@ -36,8 +35,7 @@ protected IMarginCore TryGetMarginCore(IWpfTextViewHost textViewHost) if (documentBuffer == null) return null; - ITextDocument textDocument; - if (!TextDocumentFactoryService.TryGetTextDocument(documentBuffer, out textDocument)) + if (!TextDocumentFactoryService.TryGetTextDocument(documentBuffer, out var textDocument)) return null; var fullPath = GetFullPath(textDocument.FilePath); diff --git a/GitDiffMargin/GitDiffMarginCommandHandler.cs b/GitDiffMargin/GitDiffMarginCommandHandler.cs index a060c91..055c1ce 100644 --- a/GitDiffMargin/GitDiffMarginCommandHandler.cs +++ b/GitDiffMargin/GitDiffMarginCommandHandler.cs @@ -34,8 +34,7 @@ protected override OLECMDF QueryCommandStatus(ref Guid commandGroup, uint comman { case GitDiffMarginCommand.ShowPopup: { - EditorDiffMarginViewModel viewModel; - if (!TryGetMarginViewModel(out viewModel)) + if (!TryGetMarginViewModel(out var viewModel)) return 0; var diffViewModel = GetCurrentDiffViewModel(viewModel); @@ -47,8 +46,7 @@ protected override OLECMDF QueryCommandStatus(ref Guid commandGroup, uint comman case GitDiffMarginCommand.PreviousChange: case GitDiffMarginCommand.NextChange: { - EditorDiffMarginViewModel viewModel; - if (!TryGetMarginViewModel(out viewModel)) + if (!TryGetMarginViewModel(out var viewModel)) return 0; // First look for a diff already showing a popup @@ -74,8 +72,7 @@ protected override OLECMDF QueryCommandStatus(ref Guid commandGroup, uint comman case GitDiffMarginCommand.RollbackChange: case GitDiffMarginCommand.CopyOldText: { - EditorDiffMarginViewModel viewModel; - if (!TryGetMarginViewModel(out viewModel)) + if (!TryGetMarginViewModel(out var viewModel)) return 0; var diffViewModel = viewModel.DiffViewModels.OfType() @@ -95,8 +92,7 @@ protected override OLECMDF QueryCommandStatus(ref Guid commandGroup, uint comman case GitDiffMarginCommand.ShowDiff: { - EditorDiffMarginViewModel viewModel; - if (!TryGetMarginViewModel(out viewModel)) + if (!TryGetMarginViewModel(out var viewModel)) return 0; if (viewModel.DiffViewModels.Any()) @@ -118,9 +114,8 @@ protected override bool HandlePreExec(ref Guid commandGroup, uint commandId, OLE { if (commandGroup == typeof(GitDiffMarginCommand).GUID) { - EditorDiffMarginViewModel viewModel = null; EditorDiffViewModel diffViewModel = null; - if (TryGetMarginViewModel(out viewModel)) + if (TryGetMarginViewModel(out var viewModel)) diffViewModel = viewModel.DiffViewModels.OfType() .FirstOrDefault(i => i.ShowPopup); diff --git a/GitDiffMargin/ViewModel/EditorDiffViewModel.cs b/GitDiffMargin/ViewModel/EditorDiffViewModel.cs index 05b7470..f0c831f 100644 --- a/GitDiffMargin/ViewModel/EditorDiffViewModel.cs +++ b/GitDiffMargin/ViewModel/EditorDiffViewModel.cs @@ -1,4 +1,4 @@ -#region using +#region using using System; using System.Linq; @@ -86,16 +86,13 @@ public object ToolBarTray if (_toolbarTrayHost == null) return null; - IVsUIElement toolbarTray; - ErrorHandler.ThrowOnFailure(_toolbarTrayHost.GetToolbarTray(out toolbarTray)); + ErrorHandler.ThrowOnFailure(_toolbarTrayHost.GetToolbarTray(out var toolbarTray)); - object uiObject; - ErrorHandler.ThrowOnFailure(toolbarTray.GetUIObject(out uiObject)); + ErrorHandler.ThrowOnFailure(toolbarTray.GetUIObject(out var uiObject)); var wpfElement = uiObject as IVsUIWpfElement; - object frameworkElement; - ErrorHandler.ThrowOnFailure(wpfElement.GetFrameworkElement(out frameworkElement)); + ErrorHandler.ThrowOnFailure(wpfElement.GetFrameworkElement(out var frameworkElement)); return frameworkElement; } @@ -117,8 +114,7 @@ public bool ShowPopup MarginCore.TextView.Properties.GetProperty( typeof(GitDiffMarginCommandHandler)); - IVsToolbarTrayHost toolbarTrayHost; - ErrorHandler.ThrowOnFailure(uiShell.CreateToolbarTray(commandTarget, out toolbarTrayHost)); + ErrorHandler.ThrowOnFailure(uiShell.CreateToolbarTray(commandTarget, out var toolbarTrayHost)); var toolBarGuid = typeof(GitDiffMarginCommand).GUID; ErrorHandler.ThrowOnFailure(toolbarTrayHost.AddToolbar(ref toolBarGuid, From 1e6cea58d02cffdcf1f71c07bddf7af1b3f6ee15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 14:53:53 +0000 Subject: [PATCH 07/18] Convert to ?: operator --- GitDiffMargin/EditorDiffMargin.cs | 6 +----- GitDiffMargin/Git/GitCommands.cs | 8 ++------ 2 files changed, 3 insertions(+), 11 deletions(-) diff --git a/GitDiffMargin/EditorDiffMargin.cs b/GitDiffMargin/EditorDiffMargin.cs index 68aae2c..f69a393 100644 --- a/GitDiffMargin/EditorDiffMargin.cs +++ b/GitDiffMargin/EditorDiffMargin.cs @@ -33,11 +33,7 @@ private void UpdateDiffDimensions(DiffViewModel diffViewModel, HunkRangeInfo hun if (TextView.IsClosed) return; - bool? visible; - if (diffViewModel.IsDeletion) - visible = UpdateDeletedDiffDimensions(diffViewModel, hunkRangeInfo); - else - visible = UpdateNormalDiffDimensions(diffViewModel, hunkRangeInfo); + var visible = diffViewModel.IsDeletion ? UpdateDeletedDiffDimensions(diffViewModel, hunkRangeInfo) : UpdateNormalDiffDimensions(diffViewModel, hunkRangeInfo); if (visible.HasValue) diffViewModel.IsVisible = visible.Value; diff --git a/GitDiffMargin/Git/GitCommands.cs b/GitDiffMargin/Git/GitCommands.cs index 5e7f6f9..65805c5 100644 --- a/GitDiffMargin/Git/GitCommands.cs +++ b/GitDiffMargin/Git/GitCommands.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; @@ -162,12 +162,8 @@ public void StartExternalDiff(ITextDocument textDocument, string originalPath) if (indexEntry != null) { // determine if the file has been staged - string revision; var stagedMask = FileStatus.NewInIndex | FileStatus.ModifiedInIndex; - if ((repo.RetrieveStatus(relativePath) & stagedMask) != 0) - revision = "index"; - else - revision = repo.Head.Tip.Sha.Substring(0, 7); + var revision = (repo.RetrieveStatus(relativePath) & stagedMask) != 0 ? "index" : repo.Head.Tip.Sha.Substring(0, 7); leftLabel = string.Format("{0}@{1}", objectName, revision); } From 5980b7a90836109bdce76f03acd44db3e95c1176 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 14:58:21 +0000 Subject: [PATCH 08/18] Convert to return statement --- GitDiffMargin.Commands/ShimCommandHandler.cs | 9 ++- GitDiffMargin/Core/MarginCore.cs | 78 +++++--------------- GitDiffMargin/EditorDiffMarginFactory.cs | 6 +- GitDiffMargin/Git/GitCommands.cs | 8 +- GitDiffMargin/ScrollDiffMarginFactory2012.cs | 6 +- GitDiffMargin/ScrollDiffMarginFactory2013.cs | 6 +- 6 files changed, 33 insertions(+), 80 deletions(-) diff --git a/GitDiffMargin.Commands/ShimCommandHandler.cs b/GitDiffMargin.Commands/ShimCommandHandler.cs index 289c849..9cc7f01 100644 --- a/GitDiffMargin.Commands/ShimCommandHandler.cs +++ b/GitDiffMargin.Commands/ShimCommandHandler.cs @@ -1,4 +1,4 @@ -using System; +using System; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.OLE.Interop; @@ -28,9 +28,10 @@ public virtual CommandState GetCommandState(T args) ErrorHandler.ThrowOnFailure(GetCommandTarget(args).QueryStatus(_commandSet, 1, command, IntPtr.Zero)); if ((command[0].cmdf & (uint) OLECMDF.OLECMDF_SUPPORTED) == 0) return CommandState.Unspecified; - if ((command[0].cmdf & (uint) OLECMDF.OLECMDF_ENABLED) == 0) - return CommandState.Unavailable; - return CommandState.Available; + + return (command[0].cmdf & (uint) OLECMDF.OLECMDF_ENABLED) == 0 + ? CommandState.Unavailable + : CommandState.Available; } public virtual bool ExecuteCommand(T args, CommandExecutionContext executionContext) diff --git a/GitDiffMargin/Core/MarginCore.cs b/GitDiffMargin/Core/MarginCore.cs index df38a88..823406e 100644 --- a/GitDiffMargin/Core/MarginCore.cs +++ b/GitDiffMargin/Core/MarginCore.cs @@ -68,71 +68,29 @@ public void Dispose() public IGitCommands GitCommands { get; } - public FontFamily FontFamily - { - get - { - if (_classificationFormatMap.DefaultTextProperties.TypefaceEmpty) - return new FontFamily("Consolas"); - - return _classificationFormatMap.DefaultTextProperties.Typeface.FontFamily; - } - } - - public FontStretch FontStretch - { - get - { - if (_classificationFormatMap.DefaultTextProperties.TypefaceEmpty) - return FontStretches.Normal; - - return _classificationFormatMap.DefaultTextProperties.Typeface.Stretch; - } - } - - public FontStyle FontStyle - { - get - { - if (_classificationFormatMap.DefaultTextProperties.TypefaceEmpty) - return FontStyles.Normal; - - return _classificationFormatMap.DefaultTextProperties.Typeface.Style; - } - } + public FontFamily FontFamily => _classificationFormatMap.DefaultTextProperties.TypefaceEmpty + ? new FontFamily("Consolas") + : _classificationFormatMap.DefaultTextProperties.Typeface.FontFamily; - public FontWeight FontWeight - { - get - { - if (_classificationFormatMap.DefaultTextProperties.TypefaceEmpty) - return FontWeights.Normal; + public FontStretch FontStretch => _classificationFormatMap.DefaultTextProperties.TypefaceEmpty + ? FontStretches.Normal + : _classificationFormatMap.DefaultTextProperties.Typeface.Stretch; - return _classificationFormatMap.DefaultTextProperties.Typeface.Weight; - } - } - - public double FontSize - { - get - { - if (_classificationFormatMap.DefaultTextProperties.FontRenderingEmSizeEmpty) - return 12.0; + public FontStyle FontStyle => _classificationFormatMap.DefaultTextProperties.TypefaceEmpty + ? FontStyles.Normal + : _classificationFormatMap.DefaultTextProperties.Typeface.Style; - return _classificationFormatMap.DefaultTextProperties.FontRenderingEmSize; - } - } + public FontWeight FontWeight => _classificationFormatMap.DefaultTextProperties.TypefaceEmpty + ? FontWeights.Normal + : _classificationFormatMap.DefaultTextProperties.Typeface.Weight; - public Brush Background - { - get - { - if (_classificationFormatMap.DefaultTextProperties.BackgroundBrushEmpty) - return TextView.Background; + public double FontSize => _classificationFormatMap.DefaultTextProperties.FontRenderingEmSizeEmpty + ? 12.0 + : _classificationFormatMap.DefaultTextProperties.FontRenderingEmSize; - return _classificationFormatMap.DefaultTextProperties.BackgroundBrush; - } - } + public Brush Background => _classificationFormatMap.DefaultTextProperties.BackgroundBrushEmpty + ? TextView.Background + : _classificationFormatMap.DefaultTextProperties.BackgroundBrush; public Brush Foreground { diff --git a/GitDiffMargin/EditorDiffMarginFactory.cs b/GitDiffMargin/EditorDiffMarginFactory.cs index 7b2bb3d..7ac630c 100644 --- a/GitDiffMargin/EditorDiffMarginFactory.cs +++ b/GitDiffMargin/EditorDiffMarginFactory.cs @@ -1,4 +1,4 @@ -#region using +#region using using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text.Editor; @@ -20,10 +20,8 @@ public override IWpfTextViewMargin CreateMargin(IWpfTextViewHost textViewHost, IWpfTextViewMargin containerMargin) { var marginCore = TryGetMarginCore(textViewHost); - if (marginCore == null) - return null; - return new EditorDiffMargin(textViewHost.TextView, marginCore); + return marginCore == null ? null : new EditorDiffMargin(textViewHost.TextView, marginCore); } } } \ No newline at end of file diff --git a/GitDiffMargin/Git/GitCommands.cs b/GitDiffMargin/Git/GitCommands.cs index 65805c5..21391b2 100644 --- a/GitDiffMargin/Git/GitCommands.cs +++ b/GitDiffMargin/Git/GitCommands.cs @@ -163,7 +163,9 @@ public void StartExternalDiff(ITextDocument textDocument, string originalPath) { // determine if the file has been staged var stagedMask = FileStatus.NewInIndex | FileStatus.ModifiedInIndex; - var revision = (repo.RetrieveStatus(relativePath) & stagedMask) != 0 ? "index" : repo.Head.Tip.Sha.Substring(0, 7); + var revision = (repo.RetrieveStatus(relativePath) & stagedMask) != 0 + ? "index" + : repo.Head.Tip.Sha.Substring(0, 7); leftLabel = string.Format("{0}@{1}", objectName, revision); } @@ -232,10 +234,8 @@ public string GetGitWorkingCopy(string path, string originalPath) using (var repository = new Repository(repositoryPath)) { var workingDirectory = repository.Info.WorkingDirectory; - if (workingDirectory == null) - return null; - return Path.GetFullPath(workingDirectory); + return workingDirectory == null ? null : Path.GetFullPath(workingDirectory); } } diff --git a/GitDiffMargin/ScrollDiffMarginFactory2012.cs b/GitDiffMargin/ScrollDiffMarginFactory2012.cs index eddff97..ff24fcc 100644 --- a/GitDiffMargin/ScrollDiffMarginFactory2012.cs +++ b/GitDiffMargin/ScrollDiffMarginFactory2012.cs @@ -1,4 +1,4 @@ -using System.ComponentModel.Composition; +using System.ComponentModel.Composition; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; @@ -21,10 +21,8 @@ public override IWpfTextViewMargin CreateMargin(IWpfTextViewHost textViewHost, return null; var marginCore = TryGetMarginCore(textViewHost); - if (marginCore == null) - return null; - return new ScrollDiffMargin(textViewHost.TextView, marginCore, containerMargin); + return marginCore == null ? null : new ScrollDiffMargin(textViewHost.TextView, marginCore, containerMargin); } } } \ No newline at end of file diff --git a/GitDiffMargin/ScrollDiffMarginFactory2013.cs b/GitDiffMargin/ScrollDiffMarginFactory2013.cs index a881c0f..66e5c8f 100644 --- a/GitDiffMargin/ScrollDiffMarginFactory2013.cs +++ b/GitDiffMargin/ScrollDiffMarginFactory2013.cs @@ -1,4 +1,4 @@ -using System.ComponentModel.Composition; +using System.ComponentModel.Composition; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; @@ -24,10 +24,8 @@ public override IWpfTextViewMargin CreateMargin(IWpfTextViewHost textViewHost, return null; var marginCore = TryGetMarginCore(textViewHost); - if (marginCore == null) - return null; - return new ScrollDiffMargin(textViewHost.TextView, marginCore, containerMargin); + return marginCore == null ? null : new ScrollDiffMargin(textViewHost.TextView, marginCore, containerMargin); } } } \ No newline at end of file From 0a5b2934681ba0f0beff1c87352aecf7a4b4dc3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 15:01:27 +0000 Subject: [PATCH 09/18] Use pattern matching --- GitDiffMargin/Core/MarginCore.cs | 5 +---- GitDiffMargin/Git/GitCommands.cs | 3 +-- GitDiffMargin/GitDiffMarginCommandHandler.cs | 3 +-- GitDiffMargin/View/EditorDiffMarginControl.xaml.cs | 3 +-- GitDiffMargin/ViewModel/EditorDiffViewModel.cs | 3 +-- 5 files changed, 5 insertions(+), 12 deletions(-) diff --git a/GitDiffMargin/Core/MarginCore.cs b/GitDiffMargin/Core/MarginCore.cs index 823406e..88ca503 100644 --- a/GitDiffMargin/Core/MarginCore.cs +++ b/GitDiffMargin/Core/MarginCore.cs @@ -248,10 +248,7 @@ private static Brush GetBrush(ResourceDictionary properties) private void HandleParseComplete(object sender, ParseResultEventArgs e) { - var diffResult = e as DiffParseResultEventArgs; - if (diffResult == null) return; - - CheckBeginInvokeOnUi(() => OnHunksChanged(diffResult.Diff)); + if (e is DiffParseResultEventArgs diffResult) CheckBeginInvokeOnUi(() => OnHunksChanged(diffResult.Diff)); } private void OnHunksChanged(IEnumerable hunkRangeInfos) diff --git a/GitDiffMargin/Git/GitCommands.cs b/GitDiffMargin/Git/GitCommands.cs index 21391b2..32d532c 100644 --- a/GitDiffMargin/Git/GitCommands.cs +++ b/GitDiffMargin/Git/GitCommands.cs @@ -318,8 +318,7 @@ private string AdjustPath(string fullPath) StringComparison.OrdinalIgnoreCase)) return fullPath; - var solution = _serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution; - if (solution == null) + if (!(_serviceProvider.GetService(typeof(SVsSolution)) is IVsSolution solution)) return fullPath; if (!ErrorHandler.Succeeded(solution.GetProjectEnum((uint) __VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION, diff --git a/GitDiffMargin/GitDiffMarginCommandHandler.cs b/GitDiffMargin/GitDiffMarginCommandHandler.cs index 055c1ce..afd775d 100644 --- a/GitDiffMargin/GitDiffMarginCommandHandler.cs +++ b/GitDiffMargin/GitDiffMarginCommandHandler.cs @@ -216,8 +216,7 @@ private bool TryGetMarginViewModel(out EditorDiffMarginViewModel viewModel) var textViewHost = _editorAdaptersFactoryService.GetWpfTextViewHost(TextViewAdapter); - var margin = textViewHost?.GetTextViewMargin(EditorDiffMargin.MarginNameConst) as EditorDiffMargin; - if (margin == null) + if (!(textViewHost?.GetTextViewMargin(EditorDiffMargin.MarginNameConst) is EditorDiffMargin margin)) return false; viewModel = margin.VisualElement.DataContext as EditorDiffMarginViewModel; diff --git a/GitDiffMargin/View/EditorDiffMarginControl.xaml.cs b/GitDiffMargin/View/EditorDiffMarginControl.xaml.cs index 4ab6f04..23a436d 100644 --- a/GitDiffMargin/View/EditorDiffMarginControl.xaml.cs +++ b/GitDiffMargin/View/EditorDiffMarginControl.xaml.cs @@ -62,8 +62,7 @@ private static void DoubleClick(object sender, EventArgs e) var button = ClickWaitTimer.Tag as Button; - var editorDiffMarginViewModel = button?.Tag as EditorDiffMarginViewModel; - if (editorDiffMarginViewModel == null) return; + if (!(button?.Tag is EditorDiffMarginViewModel editorDiffMarginViewModel)) return; var editorDiffViewModel = button.DataContext as EditorDiffViewModel; editorDiffViewModel?.ShowPopUpCommand.Execute(editorDiffMarginViewModel); diff --git a/GitDiffMargin/ViewModel/EditorDiffViewModel.cs b/GitDiffMargin/ViewModel/EditorDiffViewModel.cs index f0c831f..498c1e6 100644 --- a/GitDiffMargin/ViewModel/EditorDiffViewModel.cs +++ b/GitDiffMargin/ViewModel/EditorDiffViewModel.cs @@ -107,8 +107,7 @@ public bool ShowPopup _showPopup = value; if (value) { - var uiShell = Package.GetGlobalService(typeof(SVsUIShell)) as IVsUIShell4; - if (uiShell != null) + if (Package.GetGlobalService(typeof(SVsUIShell)) is IVsUIShell4 uiShell) { IOleCommandTarget commandTarget = MarginCore.TextView.Properties.GetProperty( From f42936bcb9e0c4552366330398905095311559a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 15:02:50 +0000 Subject: [PATCH 10/18] Convert delegate to local function --- .../Core/DiffUpdateBackgroundParser.cs | 24 +++++++++---------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs index f2c2452..ab08e21 100644 --- a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs +++ b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs @@ -51,21 +51,19 @@ internal DiffUpdateBackgroundParser(ITextBuffer textBuffer, ITextBuffer document private void HandleFileSystemChanged(object sender, FileSystemEventArgs e) { - Action action = - () => + void HandleFileSystemChanged() + { + try { - try - { - ProcessFileSystemChange(e); - } - catch (Exception ex) - { - if (ErrorHandler.IsCriticalException(ex)) - throw; - } - }; + ProcessFileSystemChange(e); + } + catch (Exception ex) + { + if (ErrorHandler.IsCriticalException(ex)) throw; + } + } - Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); + Task.Factory.StartNew(HandleFileSystemChanged, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); } private void ProcessFileSystemChange(FileSystemEventArgs e) From f160567e2137835193cb0a196ece03876fef7fa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 15:04:35 +0000 Subject: [PATCH 11/18] Introduce optional parameters --- GitDiffMargin/Git/GitDiffParser.cs | 7 +------ GitDiffMargin/Git/HunkRangeInfo.cs | 7 +------ 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/GitDiffMargin/Git/GitDiffParser.cs b/GitDiffMargin/Git/GitDiffParser.cs index cac0f24..26f7493 100644 --- a/GitDiffMargin/Git/GitDiffParser.cs +++ b/GitDiffMargin/Git/GitDiffParser.cs @@ -10,12 +10,7 @@ public class GitDiffParser private readonly string _gitDiff; private readonly bool _suppressRollback; - public GitDiffParser(string gitDiff, int contextLines) - : this(gitDiff, contextLines, false) - { - } - - public GitDiffParser(string gitDiff, int contextLines, bool suppressRollback) + public GitDiffParser(string gitDiff, int contextLines, bool suppressRollback = false) { _gitDiff = gitDiff; _contextLines = contextLines; diff --git a/GitDiffMargin/Git/HunkRangeInfo.cs b/GitDiffMargin/Git/HunkRangeInfo.cs index d3cd4b8..3362fc8 100644 --- a/GitDiffMargin/Git/HunkRangeInfo.cs +++ b/GitDiffMargin/Git/HunkRangeInfo.cs @@ -9,13 +9,8 @@ namespace GitDiffMargin.Git { public class HunkRangeInfo { - public HunkRangeInfo(HunkRange originaleHunkRange, HunkRange newHunkRange, IEnumerable diffLines) - : this(originaleHunkRange, newHunkRange, diffLines, false) - { - } - public HunkRangeInfo(HunkRange originaleHunkRange, HunkRange newHunkRange, IEnumerable diffLines, - bool suppressRollback) + bool suppressRollback = false) { OriginalHunkRange = originaleHunkRange; NewHunkRange = newHunkRange; From 6a3891e744ba71f5db99026a08f648c7e8c5e4ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 15:15:32 +0000 Subject: [PATCH 12/18] Invert if statement to reduce nesting --- GitDiffMargin/Core/BackgroundParser.cs | 25 +- .../Core/DiffUpdateBackgroundParser.cs | 45 ++-- GitDiffMargin/Core/MarginCore.cs | 19 +- GitDiffMargin/Git/GitCommands.cs | 20 +- GitDiffMargin/GitDiffMarginCommandHandler.cs | 242 +++++++++--------- GitDiffMargin/View/PopupKeyboardBehavior.cs | 51 ++-- 6 files changed, 195 insertions(+), 207 deletions(-) diff --git a/GitDiffMargin/Core/BackgroundParser.cs b/GitDiffMargin/Core/BackgroundParser.cs index 7be727a..0ed94f4 100644 --- a/GitDiffMargin/Core/BackgroundParser.cs +++ b/GitDiffMargin/Core/BackgroundParser.cs @@ -157,18 +157,19 @@ private void TryReparse(bool forceReparse) if (DateTimeOffset.Now - _lastEdit < ReparseDelay) return; - if (Interlocked.CompareExchange(ref _parsing, 1, 0) == 0) - try - { - var task = Task.Factory.StartNew(ReParse, CancellationToken.None, TaskCreationOptions.None, - _taskScheduler); - task.ContinueWith(_ => _parsing = 0); - } - catch - { - _parsing = 0; - throw; - } + if (Interlocked.CompareExchange(ref _parsing, 1, 0) != 0) return; + + try + { + var task = Task.Factory.StartNew(ReParse, CancellationToken.None, TaskCreationOptions.None, + _taskScheduler); + task.ContinueWith(_ => _parsing = 0); + } + catch + { + _parsing = 0; + throw; + } } private void ReParse() diff --git a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs index ab08e21..6afb54b 100644 --- a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs +++ b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs @@ -26,25 +26,23 @@ internal DiffUpdateBackgroundParser(ITextBuffer textBuffer, ITextBuffer document _commands = commands; ReparseDelay = TimeSpan.FromMilliseconds(500); - if (TextDocumentFactoryService.TryGetTextDocument(_documentBuffer, out _textDocument)) - { - _originalPath = originalPath; - if (_commands.IsGitRepository(_textDocument.FilePath, _originalPath)) - { - _textDocument.FileActionOccurred += OnFileActionOccurred; - - var repositoryDirectory = _commands.GetGitRepository(_textDocument.FilePath, _originalPath); - if (repositoryDirectory != null) - { - _watcher = new FileSystemWatcher(repositoryDirectory); - _watcher.Changed += HandleFileSystemChanged; - _watcher.Created += HandleFileSystemChanged; - _watcher.Deleted += HandleFileSystemChanged; - _watcher.Renamed += HandleFileSystemChanged; - _watcher.EnableRaisingEvents = true; - } - } - } + if (!TextDocumentFactoryService.TryGetTextDocument(_documentBuffer, out _textDocument)) return; + + _originalPath = originalPath; + + if (!_commands.IsGitRepository(_textDocument.FilePath, _originalPath)) return; + + _textDocument.FileActionOccurred += OnFileActionOccurred; + + var repositoryDirectory = _commands.GetGitRepository(_textDocument.FilePath, _originalPath); + if (repositoryDirectory == null) return; + + _watcher = new FileSystemWatcher(repositoryDirectory); + _watcher.Changed += HandleFileSystemChanged; + _watcher.Created += HandleFileSystemChanged; + _watcher.Deleted += HandleFileSystemChanged; + _watcher.Renamed += HandleFileSystemChanged; + _watcher.EnableRaisingEvents = true; } public override string Name => "Git Diff Analyzer"; @@ -106,11 +104,10 @@ protected override void Dispose(bool disposing) { base.Dispose(disposing); - if (disposing) - { - if (_textDocument != null) _textDocument.FileActionOccurred -= OnFileActionOccurred; - _watcher?.Dispose(); - } + if (!disposing) return; + + if (_textDocument != null) _textDocument.FileActionOccurred -= OnFileActionOccurred; + _watcher?.Dispose(); } } } \ No newline at end of file diff --git a/GitDiffMargin/Core/MarginCore.cs b/GitDiffMargin/Core/MarginCore.cs index 88ca503..74cf536 100644 --- a/GitDiffMargin/Core/MarginCore.cs +++ b/GitDiffMargin/Core/MarginCore.cs @@ -225,25 +225,26 @@ private void OnBrushesChanged(EventArgs e) private static Brush GetBrush(ResourceDictionary properties) { - if (properties == null) - return Brushes.Transparent; - - if (properties.Contains(EditorFormatDefinition.BackgroundColorId)) + Brush GetBrush() { - var color = (Color) properties[EditorFormatDefinition.BackgroundColorId]; - var brush = new SolidColorBrush(color); + var brush = (Brush) properties[EditorFormatDefinition.BackgroundBrushId]; if (brush.CanFreeze) brush.Freeze(); return brush; } - if (properties.Contains(EditorFormatDefinition.BackgroundBrushId)) + Brush GetSolidColorBrush() { - var brush = (Brush) properties[EditorFormatDefinition.BackgroundBrushId]; + var color = (Color) properties[EditorFormatDefinition.BackgroundColorId]; + var brush = new SolidColorBrush(color); if (brush.CanFreeze) brush.Freeze(); return brush; } - return Brushes.Transparent; + if (properties == null) return Brushes.Transparent; + + if (properties.Contains(EditorFormatDefinition.BackgroundColorId)) return GetSolidColorBrush(); + + return properties.Contains(EditorFormatDefinition.BackgroundBrushId) ? GetBrush() : Brushes.Transparent; } private void HandleParseComplete(object sender, ParseResultEventArgs e) diff --git a/GitDiffMargin/Git/GitCommands.cs b/GitDiffMargin/Git/GitCommands.cs index 32d532c..1c863a6 100644 --- a/GitDiffMargin/Git/GitCommands.cs +++ b/GitDiffMargin/Git/GitCommands.cs @@ -197,13 +197,11 @@ public void StartExternalDiff(ITextDocument textDocument, string originalPath) public bool TryGetOriginalPath(string path, out string originalPath) { originalPath = null; - if (GetGitRepository(path, ref originalPath) == null) - { - originalPath = path; - return false; - } + if (GetGitRepository(path, ref originalPath) != null) return true; + + originalPath = path; + return false; - return true; } /// @@ -280,13 +278,9 @@ private string GetGitRepository(string path, ref string originalPath) private static Encoding GetEncoding(string file) { - if (File.Exists(file)) - { - var encoding = Encoding.UTF8; - if (HasPreamble(file, encoding)) return encoding; - } - - return Encoding.Default; + return File.Exists(file) + ? (HasPreamble(file, Encoding.UTF8) ? Encoding.UTF8 : Encoding.Default) + : Encoding.Default; } private static bool HasPreamble(string file, Encoding encoding) diff --git a/GitDiffMargin/GitDiffMarginCommandHandler.cs b/GitDiffMargin/GitDiffMarginCommandHandler.cs index afd775d..6138dff 100644 --- a/GitDiffMargin/GitDiffMarginCommandHandler.cs +++ b/GitDiffMargin/GitDiffMarginCommandHandler.cs @@ -29,163 +29,159 @@ public GitDiffMarginCommandHandler(IVsTextView textViewAdapter, protected override OLECMDF QueryCommandStatus(ref Guid commandGroup, uint commandId, OleCommandText oleCommandText) { - if (commandGroup == typeof(GitDiffMarginCommand).GUID) - switch ((GitDiffMarginCommand) commandId) + if (commandGroup != typeof(GitDiffMarginCommand).GUID) return 0; + switch ((GitDiffMarginCommand) commandId) + { + case GitDiffMarginCommand.ShowPopup: { - case GitDiffMarginCommand.ShowPopup: - { - if (!TryGetMarginViewModel(out var viewModel)) - return 0; + if (!TryGetMarginViewModel(out var viewModel)) + return 0; - var diffViewModel = GetCurrentDiffViewModel(viewModel); + var diffViewModel = GetCurrentDiffViewModel(viewModel); - if (diffViewModel != null) - return OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; - return OLECMDF.OLECMDF_SUPPORTED; - } - case GitDiffMarginCommand.PreviousChange: - case GitDiffMarginCommand.NextChange: + if (diffViewModel != null) + return OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; + return OLECMDF.OLECMDF_SUPPORTED; + } + case GitDiffMarginCommand.PreviousChange: + case GitDiffMarginCommand.NextChange: + { + if (!TryGetMarginViewModel(out var viewModel)) + return 0; + + // First look for a diff already showing a popup + var diffViewModel = viewModel.DiffViewModels.OfType() + .FirstOrDefault(i => i.ShowPopup); + if (diffViewModel != null) { - if (!TryGetMarginViewModel(out var viewModel)) - return 0; - - // First look for a diff already showing a popup - var diffViewModel = viewModel.DiffViewModels.OfType() - .FirstOrDefault(i => i.ShowPopup); - if (diffViewModel != null) - { - var command = (GitDiffMarginCommand) commandId == GitDiffMarginCommand.NextChange - ? viewModel.NextChangeCommand - : viewModel.PreviousChangeCommand; - if (command.CanExecute(diffViewModel)) - return OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; - return OLECMDF.OLECMDF_SUPPORTED; - } - - diffViewModel = GetDiffViewModelToMoveTo(commandId, viewModel); - - if (diffViewModel != null) + var command = (GitDiffMarginCommand) commandId == GitDiffMarginCommand.NextChange + ? viewModel.NextChangeCommand + : viewModel.PreviousChangeCommand; + if (command.CanExecute(diffViewModel)) return OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; return OLECMDF.OLECMDF_SUPPORTED; } - case GitDiffMarginCommand.RollbackChange: - case GitDiffMarginCommand.CopyOldText: - { - if (!TryGetMarginViewModel(out var viewModel)) - return 0; - - var diffViewModel = viewModel.DiffViewModels.OfType() - .FirstOrDefault(i => i.ShowPopup); - if (diffViewModel != null) - { - var command = (GitDiffMarginCommand) commandId == GitDiffMarginCommand.RollbackChange - ? diffViewModel.RollbackCommand - : diffViewModel.CopyOldTextCommand; - if (command.CanExecute(diffViewModel)) - return OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; - } - - // This command only works when a popup is open - return OLECMDF.OLECMDF_SUPPORTED; - } + diffViewModel = GetDiffViewModelToMoveTo(commandId, viewModel); - case GitDiffMarginCommand.ShowDiff: - { - if (!TryGetMarginViewModel(out var viewModel)) - return 0; + if (diffViewModel != null) + return OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; + return OLECMDF.OLECMDF_SUPPORTED; + } - if (viewModel.DiffViewModels.Any()) - return OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; - return OLECMDF.OLECMDF_SUPPORTED; - } + case GitDiffMarginCommand.RollbackChange: + case GitDiffMarginCommand.CopyOldText: + { + if (!TryGetMarginViewModel(out var viewModel)) + return 0; + + var diffViewModel = viewModel.DiffViewModels.OfType() + .FirstOrDefault(i => i.ShowPopup); + if (diffViewModel == null) return OLECMDF.OLECMDF_SUPPORTED; + + var command = (GitDiffMarginCommand) commandId == GitDiffMarginCommand.RollbackChange + ? diffViewModel.RollbackCommand + : diffViewModel.CopyOldTextCommand; + if (command.CanExecute(diffViewModel)) + return OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; + + // This command only works when a popup is open + return OLECMDF.OLECMDF_SUPPORTED; + } + + case GitDiffMarginCommand.ShowDiff: + { + if (!TryGetMarginViewModel(out var viewModel)) + return 0; - case GitDiffMarginCommand.GitDiffToolbar: - case GitDiffMarginCommand.GitDiffToolbarGroup: - // these aren't actually commands, but IDs of the command bars and groups - break; + if (viewModel.DiffViewModels.Any()) + return OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED; + return OLECMDF.OLECMDF_SUPPORTED; } + case GitDiffMarginCommand.GitDiffToolbar: + case GitDiffMarginCommand.GitDiffToolbarGroup: + // these aren't actually commands, but IDs of the command bars and groups + break; + } + return 0; } protected override bool HandlePreExec(ref Guid commandGroup, uint commandId, OLECMDEXECOPT executionOptions, IntPtr pvaIn, IntPtr pvaOut) { - if (commandGroup == typeof(GitDiffMarginCommand).GUID) - { - EditorDiffViewModel diffViewModel = null; - if (TryGetMarginViewModel(out var viewModel)) - diffViewModel = viewModel.DiffViewModels.OfType() - .FirstOrDefault(i => i.ShowPopup); + if (commandGroup != typeof(GitDiffMarginCommand).GUID) return false; - switch ((GitDiffMarginCommand) commandId) - { - case GitDiffMarginCommand.ShowPopup: - { - diffViewModel = GetCurrentDiffViewModel(viewModel); - - if (diffViewModel != null) - { - diffViewModel.ShowPopup = true; - return true; - } - - return false; - } - case GitDiffMarginCommand.PreviousChange: - case GitDiffMarginCommand.NextChange: - { - if (viewModel == null) - return false; + EditorDiffViewModel diffViewModel = null; + if (TryGetMarginViewModel(out var viewModel)) + diffViewModel = viewModel.DiffViewModels.OfType() + .FirstOrDefault(i => i.ShowPopup); - var command = (GitDiffMarginCommand) commandId == GitDiffMarginCommand.NextChange - ? viewModel.NextChangeCommand - : viewModel.PreviousChangeCommand; + switch ((GitDiffMarginCommand) commandId) + { + case GitDiffMarginCommand.ShowPopup: + { + diffViewModel = GetCurrentDiffViewModel(viewModel); - // First look for a diff already showing a popup - if (diffViewModel != null) - { - command.Execute(diffViewModel); - return true; - } + if (diffViewModel == null) return false; - diffViewModel = GetDiffViewModelToMoveTo(commandId, viewModel); + diffViewModel.ShowPopup = true; + return true; - if (diffViewModel == null) return false; + } + case GitDiffMarginCommand.PreviousChange: + case GitDiffMarginCommand.NextChange: + { + if (viewModel == null) + return false; - viewModel.MoveToChange(diffViewModel, 0); - return true; - } + var command = (GitDiffMarginCommand) commandId == GitDiffMarginCommand.NextChange + ? viewModel.NextChangeCommand + : viewModel.PreviousChangeCommand; - case GitDiffMarginCommand.RollbackChange: - case GitDiffMarginCommand.CopyOldText: + // First look for a diff already showing a popup + if (diffViewModel != null) { - if (diffViewModel == null) - return false; - - var command = (GitDiffMarginCommand) commandId == GitDiffMarginCommand.RollbackChange - ? diffViewModel.RollbackCommand - : diffViewModel.CopyOldTextCommand; command.Execute(diffViewModel); return true; } - case GitDiffMarginCommand.ShowDiff: - { - if (diffViewModel == null) - return false; + diffViewModel = GetDiffViewModelToMoveTo(commandId, viewModel); - var command = diffViewModel.ShowDifferenceCommand; - command.Execute(diffViewModel); - return true; - } + if (diffViewModel == null) return false; + + viewModel.MoveToChange(diffViewModel, 0); + return true; + } + + case GitDiffMarginCommand.RollbackChange: + case GitDiffMarginCommand.CopyOldText: + { + if (diffViewModel == null) + return false; + + var command = (GitDiffMarginCommand) commandId == GitDiffMarginCommand.RollbackChange + ? diffViewModel.RollbackCommand + : diffViewModel.CopyOldTextCommand; + command.Execute(diffViewModel); + return true; + } - case GitDiffMarginCommand.GitDiffToolbar: - case GitDiffMarginCommand.GitDiffToolbarGroup: - // these aren't actually commands, but IDs of the command bars and groups - break; + case GitDiffMarginCommand.ShowDiff: + { + if (diffViewModel == null) + return false; + + var command = diffViewModel.ShowDifferenceCommand; + command.Execute(diffViewModel); + return true; } + + case GitDiffMarginCommand.GitDiffToolbar: + case GitDiffMarginCommand.GitDiffToolbarGroup: + // these aren't actually commands, but IDs of the command bars and groups + break; } return false; diff --git a/GitDiffMargin/View/PopupKeyboardBehavior.cs b/GitDiffMargin/View/PopupKeyboardBehavior.cs index ecedeb8..ee2e777 100644 --- a/GitDiffMargin/View/PopupKeyboardBehavior.cs +++ b/GitDiffMargin/View/PopupKeyboardBehavior.cs @@ -1,24 +1,24 @@ -/* The MIT License - * - * Copyright (C) 2013 Mike Ward (http://mike-ward.net) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is furnished to do - * so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. +/* The MIT License + * + * Copyright (C) 2013 Mike Ward (http://mike-ward.net) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is furnished to do + * so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. */ using System.Windows; @@ -61,11 +61,10 @@ private static void EnableKeyboardInput(Popup popup, bool enabled) popup.Child.Focusable = true; popup.Child.IsVisibleChanged += (o, ea) => { - if (popup.Child.IsVisible) - { - element = Keyboard.FocusedElement; - Keyboard.Focus(popup.Child); - } + if (!popup.Child.IsVisible) return; + + element = Keyboard.FocusedElement; + Keyboard.Focus(popup.Child); }; }; } From 32aec687565f9a6f09d5924a332c84a93140c4cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 15:16:35 +0000 Subject: [PATCH 13/18] Merge conditional ?: expression into contional access --- GitDiffMargin/DiffMarginFactoryBase.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GitDiffMargin/DiffMarginFactoryBase.cs b/GitDiffMargin/DiffMarginFactoryBase.cs index 414d815..deb6ad7 100644 --- a/GitDiffMargin/DiffMarginFactoryBase.cs +++ b/GitDiffMargin/DiffMarginFactoryBase.cs @@ -30,8 +30,8 @@ protected IMarginCore TryGetMarginCore(IWpfTextViewHost textViewHost) // play nice with other source control providers ITextView textView = textViewHost.TextView; - var textDataModel = textView != null ? textView.TextDataModel : null; - var documentBuffer = textDataModel != null ? textDataModel.DocumentBuffer : null; + var textDataModel = textView?.TextDataModel; + var documentBuffer = textDataModel?.DocumentBuffer; if (documentBuffer == null) return null; From 5b15edd7b6a235fbe7bb9df47fca78e34b6402be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 15:21:48 +0000 Subject: [PATCH 14/18] Simplify code --- GitDiffMargin/ViewModel/DiffViewModel.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/GitDiffMargin/ViewModel/DiffViewModel.cs b/GitDiffMargin/ViewModel/DiffViewModel.cs index ec133c0..c2c9605 100644 --- a/GitDiffMargin/ViewModel/DiffViewModel.cs +++ b/GitDiffMargin/ViewModel/DiffViewModel.cs @@ -63,8 +63,6 @@ public Brush DiffBrush public int LineNumber => HunkRangeInfo.NewHunkRange.StartingLineNumber; - public int NumberOfLines { get { return HunkRangeInfo.NewHunkRange.NumberOfLines; } } - public virtual bool IsVisible { get => _isVisible; @@ -82,12 +80,14 @@ public void RefreshPosition() public bool IsLineNumberBetweenDiff(int lineNumber) { + var numberOfLines = HunkRangeInfo.NewHunkRange.NumberOfLines; + var diffStartLine = LineNumber; - var diffEndLine = diffStartLine + NumberOfLines - 1; + var diffEndLine = diffStartLine + numberOfLines - 1; if (IsDeletion) { - diffEndLine = diffStartLine + NumberOfLines + 2; + diffEndLine = diffStartLine + numberOfLines + 2; } return lineNumber >= diffStartLine && lineNumber <= diffEndLine; From b5bd9ced8c587e9f309d3f6eb0d97d629e2511ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 15:26:06 +0000 Subject: [PATCH 15/18] Use string interpolation --- GitDiffMargin/Git/GitCommands.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GitDiffMargin/Git/GitCommands.cs b/GitDiffMargin/Git/GitCommands.cs index 1c863a6..68cf5ec 100644 --- a/GitDiffMargin/Git/GitCommands.cs +++ b/GitDiffMargin/Git/GitCommands.cs @@ -167,7 +167,7 @@ public void StartExternalDiff(ITextDocument textDocument, string originalPath) ? "index" : repo.Head.Tip.Sha.Substring(0, 7); - leftLabel = string.Format("{0}@{1}", objectName, revision); + leftLabel = $"{objectName}@{revision}"; } else if (oldBlob != null) { @@ -177,7 +177,7 @@ public void StartExternalDiff(ITextDocument textDocument, string originalPath) else { // we just compared to head - leftLabel = string.Format("{0}@{1}", objectName, repo.Head.Tip.Sha.Substring(0, 7)); + leftLabel = $"{objectName}@{repo.Head.Tip.Sha.Substring(0, 7)}"; } var rightLabel = originalPath; From 4a8971534ea642065e8c67ce33e6e7983ac9a318 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 15:57:46 +0000 Subject: [PATCH 16/18] Remove useless ParseResultEventArgs class --- GitDiffMargin/Core/BackgroundParser.cs | 4 +- .../Core/DiffParseResultEventArgs.cs | 7 +-- .../Core/DiffUpdateBackgroundParser.cs | 5 +- GitDiffMargin/Core/MarginCore.cs | 2 +- GitDiffMargin/Core/ParseResultEventArgs.cs | 47 ------------------- GitDiffMargin/GitDiffMargin.csproj | 1 - 6 files changed, 8 insertions(+), 58 deletions(-) delete mode 100644 GitDiffMargin/Core/ParseResultEventArgs.cs diff --git a/GitDiffMargin/Core/BackgroundParser.cs b/GitDiffMargin/Core/BackgroundParser.cs index 0ed94f4..4fe72f3 100644 --- a/GitDiffMargin/Core/BackgroundParser.cs +++ b/GitDiffMargin/Core/BackgroundParser.cs @@ -93,7 +93,7 @@ public void Dispose() GC.SuppressFinalize(this); } - public event EventHandler ParseComplete; + public event EventHandler ParseComplete; public void RequestParse(bool forceReparse) { @@ -116,7 +116,7 @@ protected virtual void Dispose(bool disposing) protected abstract void ReParseImpl(); - protected void OnParseComplete(ParseResultEventArgs e) + protected void OnParseComplete(DiffParseResultEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); diff --git a/GitDiffMargin/Core/DiffParseResultEventArgs.cs b/GitDiffMargin/Core/DiffParseResultEventArgs.cs index dab3406..a28aed2 100644 --- a/GitDiffMargin/Core/DiffParseResultEventArgs.cs +++ b/GitDiffMargin/Core/DiffParseResultEventArgs.cs @@ -1,16 +1,13 @@ -using System; using System.Collections.Generic; using GitDiffMargin.Git; -using Microsoft.VisualStudio.Text; namespace GitDiffMargin.Core { - public class DiffParseResultEventArgs : ParseResultEventArgs + public class DiffParseResultEventArgs { private readonly List _diff; - public DiffParseResultEventArgs(ITextSnapshot snapshot, TimeSpan elapsedTime, List diff) - : base(snapshot, elapsedTime) + public DiffParseResultEventArgs(List diff) { _diff = diff; } diff --git a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs index 6afb54b..37c8ab7 100644 --- a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs +++ b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs @@ -61,7 +61,8 @@ void HandleFileSystemChanged() } } - Task.Factory.StartNew(HandleFileSystemChanged, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); + Task.Factory.StartNew(HandleFileSystemChanged, CancellationToken.None, TaskCreationOptions.None, + TaskScheduler.Default); } private void ProcessFileSystemChange(FileSystemEventArgs e) @@ -90,7 +91,7 @@ protected override void ReParseImpl() if (!TextDocumentFactoryService.TryGetTextDocument(_documentBuffer, out var textDocument)) return; var diff = _commands.GetGitDiffFor(textDocument, _originalPath, snapshot); - var result = new DiffParseResultEventArgs(snapshot, stopwatch.Elapsed, diff.ToList()); + var result = new DiffParseResultEventArgs(diff.ToList()); OnParseComplete(result); } catch (InvalidOperationException) diff --git a/GitDiffMargin/Core/MarginCore.cs b/GitDiffMargin/Core/MarginCore.cs index 74cf536..133cba3 100644 --- a/GitDiffMargin/Core/MarginCore.cs +++ b/GitDiffMargin/Core/MarginCore.cs @@ -247,7 +247,7 @@ Brush GetSolidColorBrush() return properties.Contains(EditorFormatDefinition.BackgroundBrushId) ? GetBrush() : Brushes.Transparent; } - private void HandleParseComplete(object sender, ParseResultEventArgs e) + private void HandleParseComplete(object sender, DiffParseResultEventArgs e) { if (e is DiffParseResultEventArgs diffResult) CheckBeginInvokeOnUi(() => OnHunksChanged(diffResult.Diff)); } diff --git a/GitDiffMargin/Core/ParseResultEventArgs.cs b/GitDiffMargin/Core/ParseResultEventArgs.cs deleted file mode 100644 index 4e1071e..0000000 --- a/GitDiffMargin/Core/ParseResultEventArgs.cs +++ /dev/null @@ -1,47 +0,0 @@ -/* The MIT License - * - * Copyright (c) 2013 Sam Harwell, Tunnel Vision Labs, LLC - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -using System; -using Microsoft.VisualStudio.Text; - -namespace GitDiffMargin.Core -{ - public class ParseResultEventArgs : EventArgs - { - public ParseResultEventArgs(ITextSnapshot snapshot) - { - Snapshot = snapshot; - } - - public ParseResultEventArgs(ITextSnapshot snapshot, TimeSpan elapsedTime) - { - Snapshot = snapshot; - ElapsedTime = elapsedTime; - } - - public ITextSnapshot Snapshot { get; } - - public TimeSpan? ElapsedTime { get; } - } -} \ No newline at end of file diff --git a/GitDiffMargin/GitDiffMargin.csproj b/GitDiffMargin/GitDiffMargin.csproj index 572ad33..18ddc88 100644 --- a/GitDiffMargin/GitDiffMargin.csproj +++ b/GitDiffMargin/GitDiffMargin.csproj @@ -94,7 +94,6 @@ - From dfaa74e3eac997f22672418d8473e1cf0633da47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 15:59:32 +0000 Subject: [PATCH 17/18] Delete unused local variable --- GitDiffMargin/Core/DiffUpdateBackgroundParser.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs index 37c8ab7..2b8c9ea 100644 --- a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs +++ b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; @@ -85,8 +84,6 @@ protected override void ReParseImpl() { try { - var stopwatch = Stopwatch.StartNew(); - var snapshot = TextBuffer.CurrentSnapshot; if (!TextDocumentFactoryService.TryGetTextDocument(_documentBuffer, out var textDocument)) return; From 77f43c5adac692f91a4027f421e1b373d88fa799 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Kemp=C3=A9?= Date: Sat, 25 Aug 2018 16:01:57 +0000 Subject: [PATCH 18/18] Remove property Name which is never used --- GitDiffMargin/Core/BackgroundParser.cs | 2 -- GitDiffMargin/Core/DiffUpdateBackgroundParser.cs | 2 -- 2 files changed, 4 deletions(-) diff --git a/GitDiffMargin/Core/BackgroundParser.cs b/GitDiffMargin/Core/BackgroundParser.cs index 4fe72f3..2bd9f02 100644 --- a/GitDiffMargin/Core/BackgroundParser.cs +++ b/GitDiffMargin/Core/BackgroundParser.cs @@ -83,8 +83,6 @@ public TimeSpan ReparseDelay } } - public virtual string Name => string.Empty; - protected ITextDocumentFactoryService TextDocumentFactoryService { get; } public void Dispose() diff --git a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs index 2b8c9ea..d41036c 100644 --- a/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs +++ b/GitDiffMargin/Core/DiffUpdateBackgroundParser.cs @@ -44,8 +44,6 @@ internal DiffUpdateBackgroundParser(ITextBuffer textBuffer, ITextBuffer document _watcher.EnableRaisingEvents = true; } - public override string Name => "Git Diff Analyzer"; - private void HandleFileSystemChanged(object sender, FileSystemEventArgs e) { void HandleFileSystemChanged()