-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathClaudeCodeControl.Diff.cs
More file actions
1022 lines (891 loc) · 36.5 KB
/
ClaudeCodeControl.Diff.cs
File metadata and controls
1022 lines (891 loc) · 36.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* *******************************************************************************************************************
* Application: ClaudeCodeExtension
*
* Autor: Daniel Carvalho Liedke
*
* Copyright © Daniel Carvalho Liedke 2026
* Usage and reproduction in any manner whatsoever without the written permission of Daniel Carvalho Liedke is strictly forbidden.
*
* Purpose: Diff viewer integration - file change tracking and diff window management
*
* *******************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using ClaudeCodeVS.Diff;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Threading;
namespace ClaudeCodeVS
{
public partial class ClaudeCodeControl
{
#region Fields
/// <summary>
/// Tracks file changes in the workspace
/// </summary>
private FileChangeTracker _fileChangeTracker;
/// <summary>
/// Reference to the diff viewer tool window
/// </summary>
private DiffViewerToolWindow _diffViewerWindow;
/// <summary>
/// Flag to track if diff tracking is currently active
/// </summary>
private bool _isDiffTrackingActive;
/// <summary>
/// Guard to prevent auto-reset recursion
/// </summary>
private bool _isAutoResetting;
/// <summary>
/// Prevents repeated git status checks in a short time window
/// </summary>
private DateTime _lastGitStatusCheckUtc = DateTime.MinValue;
/// <summary>
/// Last repository root used for git status checks
/// </summary>
private string _lastGitStatusRepoRoot;
/// <summary>
/// Current git repository root (set when diff tracking starts)
/// </summary>
private string _gitRepositoryRoot;
/// <summary>
/// Cached clean state result from the last git status check
/// </summary>
private bool _lastGitStatusClean;
/// <summary>
/// Throttle window for git status checks in milliseconds
/// </summary>
private const int GitStatusThrottleMs = 5000;
/// <summary>
/// Timeout for git status command in milliseconds
/// </summary>
private const int GitStatusTimeoutMs = 8000;
private const int GitShowTimeoutMs = 8000;
private const int MaxGitFileBytes = 4 * 1024 * 1024;
/// <summary>
/// Tracks if reset handler is already wired
/// </summary>
private bool _diffViewerResetSubscribed;
/// <summary>
/// Tracks if visibility handler is already wired
/// </summary>
private bool _diffViewerVisibilitySubscribed;
/// <summary>
/// Periodic poll timer to detect changes via git status
/// </summary>
private DispatcherTimer _gitStatusPollTimer;
/// <summary>
/// Guard to prevent re-entrant poll timer ticks
/// </summary>
private bool _isPolling;
/// <summary>
/// Poll interval for git status checks in milliseconds (used instead of FileSystemWatcher for git repos)
/// </summary>
private const int GitStatusPollIntervalMs = 3000;
#endregion
#region Diff Tracking Methods
/// <summary>
/// Initializes the file change tracker
/// </summary>
private void InitializeDiffTracking()
{
if (_fileChangeTracker == null)
{
_fileChangeTracker = new FileChangeTracker();
}
}
/// <summary>
/// Ensures diff tracking is active for the current workspace (git repos only)
/// </summary>
private async Task EnsureDiffTrackingStartedAsync(bool openWindow)
{
try
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
string workspaceDir = await GetWorkspaceDirectoryAsync();
if (string.IsNullOrEmpty(workspaceDir))
{
_gitRepositoryRoot = null;
return;
}
// Only support git repositories
string repoRoot = FindGitRepositoryRoot(workspaceDir);
if (string.IsNullOrEmpty(repoRoot))
{
_gitRepositoryRoot = null;
return;
}
_gitRepositoryRoot = repoRoot;
InitializeDiffTracking();
if (!_isDiffTrackingActive)
{
// Git repo: apply git baseline (reads only changed files from git)
string repoRootCopy = repoRoot;
await System.Threading.Tasks.Task.Run(() => TryApplyGitBaseline(repoRootCopy));
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
_isDiffTrackingActive = true;
}
// Ensure tracking is active if window is visible
if (_diffViewerWindow != null && _diffViewerWindow.IsWindowVisible)
{
EnsureGitStatusPollTimer();
}
if (openWindow)
{
await OpenDiffViewerWindowAsync();
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error starting diff tracking: {ex.Message}");
}
}
/// <summary>
/// Handles file changes event from the tracker
/// </summary>
private void OnFilesChanged(object sender, FileChangesEventArgs e)
{
try
{
// Refresh diff view on UI thread
ThreadHelper.JoinableTaskFactory.Run(async () =>
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
await RefreshDiffViewAsync();
});
}
catch (Exception ex)
{
Debug.WriteLine($"Error handling file changes: {ex.Message}");
}
}
/// <summary>
/// Refreshes the diff viewer with current changes
/// </summary>
private async Task RefreshDiffViewAsync()
{
try
{
if (_fileChangeTracker == null)
return;
// Run heavy file operations and diff computation on background thread
var tracker = _fileChangeTracker;
var changedFiles = await System.Threading.Tasks.Task.Run(() =>
{
var files = tracker.GetChangedFiles();
DiffComputer.ComputeDiffs(files);
return files;
});
// Switch to UI thread for the rest
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (!_isAutoResetting && _isDiffTrackingActive && changedFiles.Count > 0)
{
bool shouldAutoReset = await ShouldAutoResetDiffBaselineAsync();
if (shouldAutoReset)
{
await ResetDiffBaselineAsync(true, true, false, false, null, false);
return;
}
}
if (_diffViewerWindow?.DiffViewerControl != null)
{
_diffViewerWindow.DiffViewerControl.UpdateChangedFiles(changedFiles);
// Hide reset baseline button for git repos (always use git baseline)
_diffViewerWindow.DiffViewerControl.SetResetBaselineVisible(false);
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error refreshing diff view: {ex.Message}");
}
}
/// <summary>
/// Opens or shows the diff viewer tool window
/// </summary>
private async Task OpenDiffViewerWindowAsync()
{
try
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
await EnsureDiffViewerWindowAsync(true);
}
catch (Exception ex)
{
Debug.WriteLine($"Error opening diff viewer window: {ex.Message}");
}
}
private async Task EnsureDiffViewerWindowAsync(bool showWindow)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
// Get the package that provides the tool window
var vsPackage = await GetPackageAsync();
if (vsPackage == null)
{
return;
}
bool createWindow = showWindow;
_diffViewerWindow = vsPackage.FindToolWindow(typeof(DiffViewerToolWindow), 0, createWindow) as DiffViewerToolWindow;
if (_diffViewerWindow?.Frame == null)
{
if (createWindow)
{
}
return;
}
if (_diffViewerWindow.DiffViewerControl != null && !_diffViewerResetSubscribed)
{
_diffViewerWindow.DiffViewerControl.ResetRequested += OnDiffViewerResetRequested;
_diffViewerResetSubscribed = true;
}
if (!_diffViewerVisibilitySubscribed)
{
_diffViewerWindow.VisibilityChanged += OnDiffViewerVisibilityChanged;
_diffViewerVisibilitySubscribed = true;
}
// Only start polling if window is visible
if (_diffViewerWindow.IsWindowVisible)
{
EnsureGitStatusPollTimer();
}
// Hide reset baseline button for git repos (always use git baseline)
if (_diffViewerWindow.DiffViewerControl != null)
{
_diffViewerWindow.DiffViewerControl.SetResetBaselineVisible(false);
}
if (showWindow)
{
var windowFrame = (IVsWindowFrame)_diffViewerWindow.Frame;
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());
}
}
/// <summary>
/// Opens the Changes view, expands all files, and enables auto-scroll
/// Called when a prompt is sent with auto-open changes enabled
/// </summary>
private async Task AutoOpenChangesViewAsync()
{
// Open the diff viewer window
await EnsureDiffViewerWindowAsync(true);
// Enable auto-scroll and expand all files
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (_diffViewerWindow?.DiffViewerControl != null)
{
_diffViewerWindow.DiffViewerControl.EnableAutoScrollAndExpandAll();
}
}
private void EnsureGitStatusPollTimer()
{
if (_gitStatusPollTimer != null)
return;
_gitStatusPollTimer = new DispatcherTimer(DispatcherPriority.Background)
{
Interval = TimeSpan.FromMilliseconds(GitStatusPollIntervalMs)
};
_gitStatusPollTimer.Tick += OnGitStatusPollTimerTick;
_gitStatusPollTimer.Start();
}
private void StopGitStatusPollTimer()
{
if (_gitStatusPollTimer == null)
return;
_gitStatusPollTimer.Stop();
_gitStatusPollTimer.Tick -= OnGitStatusPollTimerTick;
_gitStatusPollTimer = null;
}
private void OnGitStatusPollTimerTick(object sender, EventArgs e)
{
if (_isAutoResetting || !_isDiffTrackingActive || _isPolling)
return;
_isPolling = true;
#pragma warning disable VSSDK007, VSTHRD110 // Intentionally fire-and-forget; reentrancy guarded by _isPolling
ThreadHelper.JoinableTaskFactory.RunAsync(async () =>
{
try
{
bool shouldAutoReset = await ShouldAutoResetDiffBaselineAsync();
if (shouldAutoReset)
{
await ResetDiffBaselineAsync(true, true, false, false, null, true);
}
else
{
// Re-apply git baseline to pick up any new files, then refresh view
string repoRoot = _gitRepositoryRoot;
if (!string.IsNullOrEmpty(repoRoot))
{
await System.Threading.Tasks.Task.Run(() => TryApplyGitBaseline(repoRoot));
}
await RefreshDiffViewAsync();
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error in git status poll: {ex.Message}");
}
finally
{
_isPolling = false;
}
});
#pragma warning restore VSSDK007, VSTHRD110
}
/// <summary>
/// Gets the extension package instance
/// </summary>
private async Task<AsyncPackage> GetPackageAsync()
{
try
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
var shell = Package.GetGlobalService(typeof(SVsShell)) as IVsShell;
if (shell == null)
return null;
var packageGuid = new Guid(ClaudeCodeExtension.ClaudeCodeExtensionPackage.PackageGuidString);
shell.IsPackageLoaded(ref packageGuid, out IVsPackage vsPackage);
if (vsPackage == null)
{
shell.LoadPackage(ref packageGuid, out vsPackage);
}
return vsPackage as AsyncPackage;
}
catch (Exception ex)
{
Debug.WriteLine($"Error getting package: {ex.Message}");
return null;
}
}
/// <summary>
/// Handles the View Changes button click
/// </summary>
private void ViewChangesButton_Click(object sender, RoutedEventArgs e)
{
ThreadHelper.JoinableTaskFactory.Run(async () =>
{
try
{
await EnsureDiffTrackingStartedAsync(true);
// If tracking is active, refresh the view
if (_isDiffTrackingActive)
{
await RefreshDiffViewAsync();
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error in ViewChangesButton_Click: {ex.Message}");
}
});
}
/// <summary>
/// Updates the visibility of the View Changes button based on git availability
/// </summary>
private async Task UpdateViewChangesButtonVisibilityAsync()
{
try
{
string workspaceDir = await GetWorkspaceDirectoryAsync();
string repoRoot = FindGitRepositoryRoot(workspaceDir);
bool isGitRepo = !string.IsNullOrEmpty(repoRoot);
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (ViewChangesButton != null)
{
ViewChangesButton.Visibility = isGitRepo ? Visibility.Visible : Visibility.Collapsed;
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error updating ViewChangesButton visibility: {ex.Message}");
}
}
private void OnDiffViewerResetRequested(object sender, EventArgs e)
{
ThreadHelper.JoinableTaskFactory.Run(async () =>
{
try
{
// Use git baseline when resetting to properly track changes relative to HEAD
await ResetDiffBaselineAsync(true, false, true, true, null, true);
}
catch (Exception ex)
{
Debug.WriteLine($"Error in OnDiffViewerResetRequested: {ex.Message}");
MessageBox.Show("Failed to reset code changes baseline.", "Claude Code", MessageBoxButton.OK, MessageBoxImage.Error);
}
});
}
private void OnDiffViewerVisibilityChanged(object sender, bool isVisible)
{
if (isVisible)
{
// Window became visible - resume tracking and force refresh
EnsureGitStatusPollTimer();
// Force a refresh to catch any changes that occurred while hidden
ThreadHelper.JoinableTaskFactory.Run(async () =>
{
try
{
if (_isAutoResetting)
return;
// Refresh baseline from git when the window is activated
await ResetDiffBaselineAsync(true, false, false, false, null, true);
}
catch (Exception ex)
{
Debug.WriteLine($"Error refreshing diff view on visibility change: {ex.Message}");
}
});
}
else
{
// Window hidden - pause tracking to save resources
StopGitStatusPollTimer();
}
}
private async Task ResetDiffBaselineAsync(bool refreshView, bool isAutoReset, bool showErrors, bool startTracking, string workspaceDirOverride, bool useGitBaseline)
{
try
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
string workspaceDir = workspaceDirOverride ?? await GetEffectiveWorkspaceDirectoryAsync();
if (string.IsNullOrEmpty(workspaceDir) || !System.IO.Directory.Exists(workspaceDir))
{
if (showErrors)
{
MessageBox.Show("Could not determine workspace directory to reset changes.", "Claude Code", MessageBoxButton.OK, MessageBoxImage.Warning);
}
return;
}
// Only support git repositories
string repoRoot = FindGitRepositoryRoot(workspaceDir);
if (string.IsNullOrEmpty(repoRoot))
{
return;
}
InitializeDiffTracking();
_isAutoResetting = isAutoReset;
// Git repo: apply git baseline (reads only changed files from git)
if (useGitBaseline)
{
string repoRootCopy = repoRoot;
await System.Threading.Tasks.Task.Run(() => TryApplyGitBaseline(repoRootCopy));
}
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (startTracking)
{
_isDiffTrackingActive = true;
}
// Hide reset baseline button for git repos (always use git baseline)
if (_diffViewerWindow?.DiffViewerControl != null)
{
_diffViewerWindow.DiffViewerControl.SetResetBaselineVisible(false);
}
// Ensure tracking is active if window is visible
if (_diffViewerWindow != null && _diffViewerWindow.IsWindowVisible)
{
EnsureGitStatusPollTimer();
}
if (refreshView)
{
await RefreshDiffViewAsync();
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error resetting diff baseline: {ex.Message}");
if (showErrors)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
MessageBox.Show("Failed to reset code changes baseline.", "Claude Code", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
finally
{
_isAutoResetting = false;
}
}
private async Task<bool> ShouldAutoResetDiffBaselineAsync()
{
try
{
string workspaceDir = await GetEffectiveWorkspaceDirectoryAsync();
if (string.IsNullOrEmpty(workspaceDir) || workspaceDir.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase))
return false;
string repoRoot = FindGitRepositoryRoot(workspaceDir);
if (string.IsNullOrEmpty(repoRoot))
return false;
return IsGitRepositoryClean(repoRoot);
}
catch (Exception ex)
{
Debug.WriteLine($"Error checking git clean state: {ex.Message}");
return false;
}
}
private async Task<string> GetEffectiveWorkspaceDirectoryAsync()
{
string workspaceDir = _lastWorkspaceDirectory;
if (!string.IsNullOrEmpty(workspaceDir))
{
string documentsDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (!string.Equals(workspaceDir, documentsDir, StringComparison.OrdinalIgnoreCase))
{
return workspaceDir;
}
}
string resolved = await GetWorkspaceDirectoryAsync();
return string.IsNullOrEmpty(resolved) ? workspaceDir : resolved;
}
private string FindGitRepositoryRoot(string startDirectory)
{
if (string.IsNullOrEmpty(startDirectory))
return null;
try
{
var current = new System.IO.DirectoryInfo(startDirectory);
while (current != null)
{
string gitPath = System.IO.Path.Combine(current.FullName, ".git");
if (System.IO.Directory.Exists(gitPath) || System.IO.File.Exists(gitPath))
{
return current.FullName;
}
current = current.Parent;
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error finding git repository root: {ex.Message}");
}
return null;
}
private bool IsGitRepositoryClean(string repoRoot)
{
if (string.IsNullOrEmpty(repoRoot))
return false;
var now = DateTime.UtcNow;
if (string.Equals(repoRoot, _lastGitStatusRepoRoot, StringComparison.OrdinalIgnoreCase) &&
(now - _lastGitStatusCheckUtc).TotalMilliseconds < GitStatusThrottleMs)
{
return _lastGitStatusClean;
}
bool isClean = false;
try
{
var processStart = new ProcessStartInfo
{
FileName = "git",
Arguments = "status --porcelain",
WorkingDirectory = repoRoot,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
StandardOutputEncoding = Encoding.UTF8,
StandardErrorEncoding = Encoding.UTF8
};
using (var process = Process.Start(processStart))
{
if (process != null)
{
string output = process.StandardOutput.ReadToEnd();
bool exited = process.WaitForExit(GitStatusTimeoutMs);
if (!exited)
{
try
{
process.Kill();
}
catch
{
// Ignore failures on kill
}
}
if (process.ExitCode == 0)
{
isClean = string.IsNullOrWhiteSpace(output);
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error running git status: {ex.Message}");
}
_lastGitStatusCheckUtc = now;
_lastGitStatusRepoRoot = repoRoot;
_lastGitStatusClean = isClean;
return isClean;
}
private bool TryApplyGitBaseline(string repoRoot)
{
try
{
if (string.IsNullOrEmpty(repoRoot))
return false;
if (!Directory.Exists(repoRoot))
return false;
string statusOutput = RunGitCommand(repoRoot, "status --porcelain=v1 -z", GitStatusTimeoutMs);
if (string.IsNullOrEmpty(statusOutput))
{
// No changes - clear the tracker to show empty state
_fileChangeTracker.Clear();
return true;
}
var originalContents = new System.Collections.Concurrent.ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var createdFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var deletedFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// Collect all files that need their original content fetched
var filesToFetch = new List<(string fullPath, string relativePath, bool isDeleted)>();
foreach (var entry in ParseGitStatusEntries(statusOutput))
{
if (entry.IsRenameOrCopy)
{
string oldFullPath = BuildFullPath(repoRoot, entry.Path);
string newFullPath = BuildFullPath(repoRoot, entry.NewPath);
// Track files under the git repository root
if (IsPathUnderDirectory(oldFullPath, repoRoot) && _fileChangeTracker.IsTrackablePath(oldFullPath))
{
filesToFetch.Add((oldFullPath, entry.Path, false));
}
if (IsPathUnderDirectory(newFullPath, repoRoot) && _fileChangeTracker.IsTrackablePath(newFullPath))
{
lock (createdFiles)
{
createdFiles.Add(newFullPath);
}
}
continue;
}
string fullPath = BuildFullPath(repoRoot, entry.Path);
// Track files under the git repository root (not just workspace directory)
if (!IsPathUnderDirectory(fullPath, repoRoot) || !_fileChangeTracker.IsTrackablePath(fullPath))
continue;
if (entry.IsUntracked || entry.IsAdded)
{
lock (createdFiles)
{
createdFiles.Add(fullPath);
}
continue;
}
if (entry.IsDeleted)
{
filesToFetch.Add((fullPath, entry.Path, true));
lock (deletedFiles)
{
deletedFiles.Add(fullPath);
}
continue;
}
if (entry.IsModified || entry.IsTypeChanged || entry.IsUnmerged)
{
filesToFetch.Add((fullPath, entry.Path, false));
}
}
// Fetch original contents in parallel for better performance
if (filesToFetch.Count > 0)
{
var parallelOptions = new System.Threading.Tasks.ParallelOptions
{
MaxDegreeOfParallelism = Math.Min(filesToFetch.Count, Environment.ProcessorCount * 2)
};
System.Threading.Tasks.Parallel.ForEach(filesToFetch, parallelOptions, fileInfo =>
{
string original = ReadGitFile(repoRoot, fileInfo.relativePath);
if (original != null)
{
originalContents[fileInfo.fullPath] = original;
}
else
{
// Even if we can't get original content, still track the file
// Use empty string so it shows as "all lines added" in the diff
originalContents[fileInfo.fullPath] = string.Empty;
Debug.WriteLine($"Could not read git HEAD content for: {fileInfo.relativePath}");
}
});
}
if (originalContents.Count == 0 && createdFiles.Count == 0 && deletedFiles.Count == 0)
{
// No trackable changes - clear the tracker to show empty state
_fileChangeTracker.Clear();
return true;
}
_fileChangeTracker.SetBaseline(repoRoot, originalContents, createdFiles, deletedFiles);
return true;
}
catch (Exception ex)
{
Debug.WriteLine($"Error applying git baseline: {ex.Message}");
return false;
}
}
private string RunGitCommand(string workingDirectory, string arguments, int timeoutMs)
{
try
{
var processStart = new ProcessStartInfo
{
FileName = "git",
Arguments = arguments,
WorkingDirectory = workingDirectory,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
StandardOutputEncoding = Encoding.UTF8,
StandardErrorEncoding = Encoding.UTF8
};
using (var process = Process.Start(processStart))
{
if (process == null)
return null;
string output = process.StandardOutput.ReadToEnd();
bool exited = process.WaitForExit(timeoutMs);
if (!exited)
{
try
{
process.Kill();
}
catch
{
// Ignore failures on kill
}
return null;
}
if (process.ExitCode != 0)
return null;
return output;
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error running git command: {ex.Message}");
return null;
}
}
private string ReadGitFile(string repoRoot, string relativePath)
{
if (string.IsNullOrEmpty(relativePath))
return null;
string gitPath = relativePath.Replace("\\", "/");
string output = RunGitCommand(repoRoot, $"show HEAD:{gitPath}", GitShowTimeoutMs);
if (output != null && output.Length > MaxGitFileBytes)
{
return null;
}
return output;
}
private static string BuildFullPath(string repoRoot, string relativePath)
{
if (string.IsNullOrEmpty(relativePath))
return relativePath;
string normalized = relativePath.Replace('/', Path.DirectorySeparatorChar);
return Path.GetFullPath(Path.Combine(repoRoot, normalized));
}
private static bool IsPathUnderDirectory(string path, string directory)
{
if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(directory))
return false;
string fullPath = Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
string fullDirectory = Path.GetFullPath(directory).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
return fullPath.StartsWith(fullDirectory, StringComparison.OrdinalIgnoreCase);
}
private static IEnumerable<GitStatusEntry> ParseGitStatusEntries(string output)
{
if (string.IsNullOrEmpty(output))
yield break;
string[] parts = output.Split('\0');
for (int i = 0; i < parts.Length; i++)
{
string part = parts[i];
if (string.IsNullOrEmpty(part))
continue;
if (part.Length < 3)
continue;
string status = part.Substring(0, 2);
string path = part.Substring(3);
bool isRenameOrCopy = status.IndexOf('R') >= 0 || status.IndexOf('C') >= 0;
if (isRenameOrCopy && i + 1 < parts.Length)
{
string newPath = parts[++i];
yield return new GitStatusEntry(status, path, newPath);
}
else
{
yield return new GitStatusEntry(status, path, null);
}
}
}
private sealed class GitStatusEntry
{
public GitStatusEntry(string status, string path, string newPath)
{
Status = status;
Path = path;
NewPath = newPath;
}
public string Status { get; }
public string Path { get; }
public string NewPath { get; }
public bool IsRenameOrCopy => Status.IndexOf('R') >= 0 || Status.IndexOf('C') >= 0;
public bool IsUntracked => Status == "??";
public bool IsAdded => Status.IndexOf('A') >= 0;
public bool IsDeleted => Status.IndexOf('D') >= 0;
public bool IsModified => Status.IndexOf('M') >= 0;
public bool IsTypeChanged => Status.IndexOf('T') >= 0;
public bool IsUnmerged => Status.IndexOf('U') >= 0;
}
/// <summary>
/// Cleans up diff tracking resources
/// </summary>
private void CleanupDiffTracking()
{
ThreadHelper.ThrowIfNotOnUIThread();
try
{
if (_fileChangeTracker != null)
{
_fileChangeTracker.Dispose();
_fileChangeTracker = null;
}
if (_diffViewerWindow != null)
{
if (_diffViewerVisibilitySubscribed)
{
_diffViewerWindow.VisibilityChanged -= OnDiffViewerVisibilityChanged;
}
// Close the diff viewer window
try
{
if (_diffViewerWindow.Frame is IVsWindowFrame windowFrame)
{
windowFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);