/
GitTfsRemote.cs
1105 lines (971 loc) · 46.9 KB
/
GitTfsRemote.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using GitTfs.Commands;
using GitTfs.Core.TfsInterop;
using GitTfs.Util;
namespace GitTfs.Core
{
public class GitTfsRemote : IGitTfsRemote
{
private static readonly Regex isInDotGit = new Regex("(?:^|/)\\.git(?:/|$)", RegexOptions.Compiled);
private readonly Globals _globals;
private readonly RemoteOptions _remoteOptions;
private readonly ConfigProperties _properties;
private int? firstChangesetId;
private int? maxChangesetId;
private string maxCommitHash;
private bool isTfsAuthenticated;
public RemoteInfo RemoteInfo { get; private set; }
public GitTfsRemote(RemoteInfo info, IGitRepository repository, RemoteOptions remoteOptions, Globals globals,
ITfsHelper tfsHelper, ConfigProperties properties)
{
_remoteOptions = remoteOptions;
_globals = globals;
_properties = properties;
Tfs = tfsHelper;
Repository = repository;
RemoteInfo = info;
Id = info.Id;
TfsUrl = info.Url;
TfsRepositoryPath = info.Repository;
TfsUsername = info.Username;
TfsPassword = info.Password;
Aliases = (info.Aliases ?? Enumerable.Empty<string>()).ToArray();
IgnoreRegexExpression = info.IgnoreRegex;
IgnoreExceptRegexExpression = info.IgnoreExceptRegex;
GitIgnorePath = _remoteOptions.GitIgnorePath ?? info.GitIgnorePath;
UseGitIgnore = !_remoteOptions.NoGitIgnore && (_remoteOptions.UseGitIgnore || IsGitIgnoreSupportEnabled());
Autotag = info.Autotag;
IsSubtree = CheckSubtree();
}
private bool IsGitIgnoreSupportEnabled()
{
var isGitIgnoreSupportDisabled = true;
var value = Repository.GetConfig<string>(GitTfsConstants.DisableGitignoreSupport, null);
bool disableGitignoreSupport;
if (value != null && bool.TryParse(value, out disableGitignoreSupport))
isGitIgnoreSupportDisabled = disableGitignoreSupport;
return !isGitIgnoreSupportDisabled;
}
private bool CheckSubtree()
{
var m = GitTfsConstants.RemoteSubtreeRegex.Match(Id);
if (m.Success)
{
OwningRemoteId = m.Groups["owner"].Value;
Prefix = m.Groups["prefix"].Value;
return true;
}
return false;
}
public void EnsureTfsAuthenticated()
{
if (isTfsAuthenticated)
return;
Tfs.EnsureAuthenticated();
isTfsAuthenticated = true;
}
public bool IsDerived
{
get { return false; }
}
public int? GetFirstChangeset()
{
return firstChangesetId;
}
public void SetFirstChangeset(int? changesetId)
{
Trace.WriteLine($"Set first changeset in branch to C{changesetId}");
firstChangesetId = changesetId;
}
public bool IsSubtree { get; private set; }
public bool IsSubtreeOwner
{
get
{
return TfsRepositoryPath == null;
}
}
public string Id { get; set; }
public string TfsUrl
{
get { return Tfs.Url; }
set { Tfs.Url = value; }
}
private string[] Aliases { get; set; }
public bool Autotag { get; set; }
public string TfsUsername
{
get { return Tfs.Username; }
set { Tfs.Username = value; }
}
public string TfsPassword
{
get { return Tfs.Password; }
set { Tfs.Password = value; }
}
public string TfsRepositoryPath { get; set; }
/// <summary>
/// Gets the TFS server-side paths of all subtrees of this remote.
/// Valid if the remote has subtrees, which occurs when <see cref="TfsRepositoryPath"/> is null.
/// </summary>
public string[] TfsSubtreePaths
{
get
{
if (tfsSubtreePaths == null)
tfsSubtreePaths = Repository.GetSubtrees(this).Select(x => x.TfsRepositoryPath).ToArray();
return tfsSubtreePaths;
}
}
private string[] tfsSubtreePaths = null;
public string IgnoreRegexExpression { get; set; }
public string IgnoreExceptRegexExpression { get; set; }
public string GitIgnorePath { get; set; }
public bool UseGitIgnore { get; set; }
public IGitRepository Repository { get; set; }
public ITfsHelper Tfs { get; set; }
public string OwningRemoteId { get; private set; }
public string Prefix { get; private set; }
public bool ExportMetadatas { get; set; }
public Dictionary<string, IExportWorkItem> ExportWorkitemsMapping { get; set; }
public int MaxChangesetId
{
get { InitHistory(); return maxChangesetId.Value; }
set { maxChangesetId = value; }
}
public string MaxCommitHash
{
get { InitHistory(); return maxCommitHash; }
set { maxCommitHash = value; }
}
private TfsChangesetInfo GetTfsChangesetById(int id)
{
return Repository.GetTfsChangesetById(RemoteRef, id);
}
private void InitHistory()
{
if (maxChangesetId == null)
{
var mostRecentUpdate = Repository.GetLastParentTfsCommits(RemoteRef).FirstOrDefault();
if (mostRecentUpdate != null)
{
MaxCommitHash = mostRecentUpdate.GitCommit;
MaxChangesetId = mostRecentUpdate.ChangesetId;
}
else
{
MaxChangesetId = 0;
// Manage the special case where a .gitignore has been committed
var gitCommit = Repository.GetCommit(RemoteRef);
if (gitCommit != null)
{
MaxCommitHash = gitCommit.Sha;
}
}
}
}
private const string WorkspaceDirectory = "~w";
private string WorkingDirectory
{
get
{
var dir = Repository.GetConfig(GitTfsConstants.WorkspaceConfigKey);
if (IsSubtree)
{
if (dir != null)
{
return Path.Combine(dir, Prefix);
}
//find the relative path to the owning remote
return Ext.CombinePaths(_globals.GitDir, WorkspaceDirectory, OwningRemoteId, Prefix);
}
return dir ?? DefaultWorkingDirectory;
}
}
private string DefaultWorkingDirectory
{
get
{
return Path.Combine(_globals.GitDir, WorkspaceDirectory);
}
}
public void CleanupWorkspace()
{
Tfs.CleanupWorkspaces(WorkingDirectory);
}
public void CleanupWorkspaceDirectory()
{
try
{
if (Directory.Exists(WorkingDirectory))
{
var allFiles = Directory.EnumerateFiles(WorkingDirectory, "*", SearchOption.AllDirectories);
foreach (var file in allFiles)
File.SetAttributes(file, File.GetAttributes(file) & ~FileAttributes.ReadOnly);
Directory.Delete(WorkingDirectory, true);
}
}
catch (Exception ex)
{
Trace.WriteLine("CleanupWorkspaceDirectory: " + ex.Message);
}
}
public bool ShouldSkip(string path)
{
return IsInDotGit(path) || IsIgnored(path);
}
public bool IsIgnored(string path)
{
return Ignorance.IsIncluded(path) || IsPathIgnored(path);
}
private bool IsPathIgnored(string path)
{
return UseGitIgnore && Repository.IsPathIgnored(path);
}
private Bouncer _ignorance;
private Bouncer Ignorance
{
get
{
if (_ignorance == null)
{
_ignorance = new Bouncer();
_ignorance.Include(IgnoreRegexExpression);
_ignorance.Include(_remoteOptions.IgnoreRegex);
_ignorance.Exclude(IgnoreExceptRegexExpression);
_ignorance.Exclude(_remoteOptions.ExceptRegex);
}
return _ignorance;
}
}
public bool IsInDotGit(string path)
{
return isInDotGit.IsMatch(path);
}
public string GetPathInGitRepo(string tfsPath)
{
if (tfsPath == null) return null;
if (!IsSubtreeOwner)
{
if (!tfsPath.StartsWith(TfsRepositoryPath, StringComparison.InvariantCultureIgnoreCase)) return null;
if (TfsRepositoryPath == GitTfsConstants.TfsRoot)
{
tfsPath = tfsPath.Substring(TfsRepositoryPath.Length);
}
else
{
if (tfsPath.Length > TfsRepositoryPath.Length && tfsPath[TfsRepositoryPath.Length] != '/')
return null;
tfsPath = tfsPath.Substring(TfsRepositoryPath.Length);
}
}
else
{
//look through the subtrees
var p = _globals.Repository.GetSubtrees(this)
.Where(x => x.IsSubtree)
.FirstOrDefault(x => tfsPath.StartsWith(x.TfsRepositoryPath, StringComparison.InvariantCultureIgnoreCase)
&& (tfsPath.Length == x.TfsRepositoryPath.Length || tfsPath[x.TfsRepositoryPath.Length] == '/'));
if (p == null) return null;
tfsPath = p.GetPathInGitRepo(tfsPath);
//we must prepend the prefix in order to get the correct directory
if (tfsPath.StartsWith("/"))
tfsPath = p.Prefix + tfsPath;
else
tfsPath = p.Prefix + "/" + tfsPath;
}
while (tfsPath.StartsWith("/"))
tfsPath = tfsPath.Substring(1);
return tfsPath;
}
public class FetchResult : IFetchResult
{
public bool IsSuccess { get; set; }
public int LastFetchedChangesetId { get; set; }
public int NewChangesetCount { get; set; }
public string ParentBranchTfsPath { get; set; }
public bool IsProcessingRenameChangeset { get; set; }
public string LastParentCommitBeforeRename { get; set; }
}
public IFetchResult Fetch(bool stopOnFailMergeCommit = false, int lastChangesetIdToFetch = -1, IRenameResult renameResult = null)
{
return FetchWithMerge(-1, stopOnFailMergeCommit, lastChangesetIdToFetch, renameResult);
}
public IFetchResult FetchWithMerge(int mergeChangesetId, bool stopOnFailMergeCommit = false, IRenameResult renameResult = null, params string[] parentCommitsHashes)
{
return FetchWithMerge(mergeChangesetId, stopOnFailMergeCommit, -1, renameResult, parentCommitsHashes);
}
public IFetchResult FetchWithMerge(int mergeChangesetId, bool stopOnFailMergeCommit = false, int lastChangesetIdToFetch = -1, IRenameResult renameResult = null, params string[] parentCommitsHashes)
{
var fetchResult = new FetchResult { IsSuccess = true, NewChangesetCount = 0 };
var latestChangesetId = GetLatestChangesetId();
if (lastChangesetIdToFetch != -1)
latestChangesetId = Math.Min(latestChangesetId, lastChangesetIdToFetch);
// TFS 2010 doesn't like when we ask for history past its last changeset.
if (MaxChangesetId >= latestChangesetId)
return fetchResult;
bool fetchRetrievedChangesets;
do
{
var fetchedChangesets = FetchChangesets(true, lastChangesetIdToFetch);
var objects = BuildEntryDictionary();
fetchRetrievedChangesets = false;
foreach (var changeset in fetchedChangesets)
{
fetchRetrievedChangesets = true;
fetchResult.NewChangesetCount++;
if (lastChangesetIdToFetch > 0 && changeset.Summary.ChangesetId > lastChangesetIdToFetch)
return fetchResult;
string parentCommitSha = null;
if (changeset.IsMergeChangeset && !ProcessMergeChangeset(changeset, stopOnFailMergeCommit, ref parentCommitSha))
{
fetchResult.NewChangesetCount--; // Merge wasn't successful - so don't count the changeset we found
fetchResult.IsSuccess = false;
return fetchResult;
}
var parentSha = (renameResult != null && renameResult.IsProcessingRenameChangeset) ? renameResult.LastParentCommitBeforeRename : MaxCommitHash;
var isFirstCommitInRepository = (parentSha == null);
var log = Apply(parentSha, changeset, objects);
if (changeset.IsRenameChangeset && !isFirstCommitInRepository)
{
if (renameResult == null || !renameResult.IsProcessingRenameChangeset)
{
fetchResult.IsProcessingRenameChangeset = true;
fetchResult.LastParentCommitBeforeRename = MaxCommitHash;
return fetchResult;
}
renameResult.IsProcessingRenameChangeset = false;
renameResult.LastParentCommitBeforeRename = null;
}
if (parentCommitSha != null)
log.CommitParents.Add(parentCommitSha);
if (changeset.Summary.ChangesetId == mergeChangesetId)
{
foreach (var parent in parentCommitsHashes)
log.CommitParents.Add(parent);
}
var commitSha = ProcessChangeset(changeset, log);
fetchResult.LastFetchedChangesetId = changeset.Summary.ChangesetId;
// set commit sha for added git objects
foreach (var commit in objects)
{
if (commit.Value.Commit == null)
commit.Value.Commit = commitSha;
}
DoGcIfNeeded();
}
} while (fetchRetrievedChangesets && latestChangesetId > fetchResult.LastFetchedChangesetId);
return fetchResult;
}
private Dictionary<string, GitObject> BuildEntryDictionary()
{
return new Dictionary<string, GitObject>(StringComparer.InvariantCultureIgnoreCase);
}
private bool ProcessMergeChangeset(ITfsChangeset changeset, bool stopOnFailMergeCommit, ref string parentCommit)
{
if (!IsIgnoringBranches())
{
var parentChangesetId = Tfs.FindMergeChangesetParent(TfsRepositoryPath, changeset.Summary.ChangesetId, this);
if (parentChangesetId < 1) // Handle missing merge parent info
{
if (stopOnFailMergeCommit)
{
return false;
}
Trace.TraceInformation("warning: this changeset " + changeset.Summary.ChangesetId +
" is a merge changeset. But git-tfs is unable to determine the parent changeset.");
return true;
}
var shaParent = Repository.FindCommitHashByChangesetId(parentChangesetId);
if (shaParent == null)
{
string omittedParentBranch;
shaParent = FindMergedRemoteAndFetch(parentChangesetId, stopOnFailMergeCommit, out omittedParentBranch);
changeset.OmittedParentBranch = omittedParentBranch;
}
if (shaParent != null)
{
parentCommit = shaParent;
}
else
{
if (stopOnFailMergeCommit)
return false;
Trace.TraceInformation("warning: this changeset " + changeset.Summary.ChangesetId +
" is a merge changeset. But git-tfs failed to find and fetch the parent changeset "
+ parentChangesetId + ". Parent changeset will be ignored...");
}
}
else
{
Trace.TraceInformation("info: this changeset " + changeset.Summary.ChangesetId +
" is a merge changeset. But was not treated as is because of your git setting...");
changeset.OmittedParentBranch = ";C" + changeset.Summary.ChangesetId;
}
return true;
}
public bool IsIgnoringBranches()
{
var value = Repository.GetConfig<string>(GitTfsConstants.IgnoreBranches, null);
bool isIgnoringBranches;
if (value != null && bool.TryParse(value, out isIgnoringBranches))
return isIgnoringBranches;
Trace.TraceInformation("warning: no value found for branch management setting '" + GitTfsConstants.IgnoreBranches +
"'...");
var isIgnoringBranchesDetected = Repository.ReadAllTfsRemotes().Count() < 2;
Trace.TraceInformation("=> Branch support " + (isIgnoringBranchesDetected ? "disabled!" : "enabled!"));
if (isIgnoringBranchesDetected)
Trace.TraceInformation(" if you want to enable branch support, use the command:" + Environment.NewLine
+ " git config --local " + GitTfsConstants.IgnoreBranches + " false");
_globals.Repository.SetConfig(GitTfsConstants.IgnoreBranches, isIgnoringBranchesDetected);
return isIgnoringBranchesDetected;
}
private string ProcessChangeset(ITfsChangeset changeset, LogEntry log)
{
if (ExportMetadatas)
{
if (changeset.Summary.Workitems.Any())
{
var workItems = TranslateWorkItems(changeset.Summary.Workitems.Select(wi => new ExportWorkItem(wi)));
if (workItems != null)
{
log.Log += "\nWorkitems:";
foreach (var workItem in workItems)
{
log.Log += "\n#" + workItem.Id + " " + workItem.Title;
}
}
}
if (!string.IsNullOrWhiteSpace(changeset.Summary.PolicyOverrideComment))
log.Log += "\n" + GitTfsConstants.GitTfsPolicyOverrideCommentPrefix + " " + changeset.Summary.PolicyOverrideComment;
foreach (var checkinNote in changeset.Summary.CheckinNotes)
{
if (!string.IsNullOrWhiteSpace(checkinNote.Name) && !string.IsNullOrWhiteSpace(checkinNote.Value))
log.Log += "\n" + GitTfsConstants.GitTfsPrefix + "-" + CamelCaseToDelimitedStringConverter.Convert(checkinNote.Name, "-") + ": " + checkinNote.Value;
}
}
var commitSha = Commit(log);
UpdateTfsHead(commitSha, changeset.Summary.ChangesetId);
StringBuilder metadatas = new StringBuilder();
if (changeset.Summary.Workitems.Any())
{
string workitemNote = "Workitems:\n";
foreach (var workitem in changeset.Summary.Workitems)
{
var workitemId = workitem.Id.ToString();
var workitemUrl = workitem.Url;
if (ExportMetadatas && ExportWorkitemsMapping.Count != 0)
{
if (ExportWorkitemsMapping.ContainsKey(workitemId))
{
var oldWorkitemId = workitemId;
workitemId = ExportWorkitemsMapping[workitemId].Id;
workitemUrl = workitemUrl.Replace(oldWorkitemId, workitemId);
}
}
workitemNote += string.Format("[{0}] {1}\n {2}\n", workitemId, workitem.Title, workitemUrl);
}
metadatas.Append(workitemNote);
}
if (!string.IsNullOrWhiteSpace(changeset.Summary.PolicyOverrideComment))
metadatas.Append("\nPolicy Override Comment: " + changeset.Summary.PolicyOverrideComment);
foreach (var checkinNote in changeset.Summary.CheckinNotes)
{
if (!string.IsNullOrWhiteSpace(checkinNote.Name) && !string.IsNullOrWhiteSpace(checkinNote.Value))
metadatas.Append("\n" + checkinNote.Name + ": " + checkinNote.Value);
}
if (!string.IsNullOrWhiteSpace(changeset.OmittedParentBranch))
metadatas.Append("\nOmitted parent branch: " + changeset.OmittedParentBranch);
if (metadatas.Length != 0)
Repository.CreateNote(commitSha, metadatas.ToString(), log.AuthorName, log.AuthorEmail, log.Date);
return commitSha;
}
private IEnumerable<IExportWorkItem> TranslateWorkItems(IEnumerable<IExportWorkItem> workItemsOriginal)
{
if (ExportWorkitemsMapping.Count == 0)
return workItemsOriginal;
List<IExportWorkItem> workItemsTranslated = new List<IExportWorkItem>();
if (workItemsOriginal == null)
return workItemsTranslated;
foreach (var oldWorkItemId in workItemsOriginal)
{
IExportWorkItem translatedWorkItem = null;
if (oldWorkItemId != null && !ExportWorkitemsMapping.TryGetValue(oldWorkItemId.Id, out translatedWorkItem))
translatedWorkItem = oldWorkItemId;
if (translatedWorkItem != null)
workItemsTranslated.Add(translatedWorkItem);
}
return workItemsTranslated;
}
private string FindRootRemoteAndFetch(int parentChangesetId, IRenameResult renameResult = null)
{
string omittedParentBranch;
return FindRemoteAndFetch(parentChangesetId, false, false, renameResult, out omittedParentBranch);
}
private string FindMergedRemoteAndFetch(int parentChangesetId, bool stopOnFailMergeCommit, out string omittedParentBranch)
{
return FindRemoteAndFetch(parentChangesetId, false, true, null, out omittedParentBranch);
}
private string FindRemoteAndFetch(int parentChangesetId, bool stopOnFailMergeCommit, bool mergeChangeset, IRenameResult renameResult, out string omittedParentBranch)
{
var tfsRemote = FindOrInitTfsRemoteOfChangeset(parentChangesetId, mergeChangeset, renameResult, out omittedParentBranch);
if (tfsRemote != null && string.Compare(tfsRemote.TfsRepositoryPath, TfsRepositoryPath, StringComparison.InvariantCultureIgnoreCase) != 0)
{
Trace.TraceInformation("\tFetching from dependent TFS remote '{0}'...", tfsRemote.Id);
try
{
var fetchResult = ((GitTfsRemote)tfsRemote).FetchWithMerge(-1, stopOnFailMergeCommit, parentChangesetId, renameResult);
}
finally
{
Trace.WriteLine("Cleaning...");
tfsRemote.CleanupWorkspaceDirectory();
if (tfsRemote.Repository.IsBare)
tfsRemote.Repository.UpdateRef(GitRepository.ShortToLocalName(tfsRemote.Id), tfsRemote.MaxCommitHash);
}
return Repository.FindCommitHashByChangesetId(parentChangesetId);
}
return null;
}
private IGitTfsRemote FindOrInitTfsRemoteOfChangeset(int parentChangesetId, bool mergeChangeset, IRenameResult renameResult, out string omittedParentBranch)
{
omittedParentBranch = null;
IGitTfsRemote tfsRemote;
IChangeset parentChangeset = Tfs.GetChangeset(parentChangesetId);
//I think you want something that uses GetPathInGitRepo and ShouldSkip. See TfsChangeset.Apply.
//Don't know if there is a way to extract remote tfs repository path from changeset datas! Should be better!!!
var remote = Repository.ReadAllTfsRemotes().FirstOrDefault(r => parentChangeset.Changes.Any(c => r.GetPathInGitRepo(c.Item.ServerItem) != null));
if (remote != null)
tfsRemote = remote;
else
{
// If the changeset has created multiple folders, the expected branch folder will not always be the first
// so we scan all the changes of type folder to try to detect the first one which is a branch.
// In most cases it will change nothing: the first folder is the good one
IBranchObject tfsBranch = null;
string tfsPath = null;
var allBranches = Tfs.GetBranches(true);
foreach (var change in parentChangeset.Changes)
{
tfsPath = change.Item.ServerItem;
tfsPath = tfsPath.EndsWith("/") ? tfsPath : tfsPath + "/";
tfsBranch = allBranches.SingleOrDefault(b => tfsPath.StartsWith(b.Path.EndsWith("/") ? b.Path : b.Path + "/"));
if (tfsBranch != null)
{
// we found a branch, we stop here
break;
}
}
var filterRegex = Repository.GetConfig(GitTfsConstants.IgnoreBranchesRegex);
if (mergeChangeset && tfsBranch != null && !string.IsNullOrEmpty(filterRegex)
&& Regex.IsMatch(tfsBranch.Path, filterRegex, RegexOptions.IgnoreCase))
{
Trace.TraceInformation("warning: skip filtered branch for path " + tfsBranch.Path + " (regex:" + filterRegex + ")");
tfsRemote = null;
omittedParentBranch = tfsBranch.Path + ";C" + parentChangesetId;
}
else if (mergeChangeset && tfsBranch != null &&
string.Equals(Repository.GetConfig(GitTfsConstants.IgnoreNotInitBranches), true.ToString(), StringComparison.InvariantCultureIgnoreCase))
{
Trace.TraceInformation("warning: skip not initialized branch for path " + tfsBranch.Path);
tfsRemote = null;
omittedParentBranch = tfsBranch.Path + ";C" + parentChangesetId;
}
else if (tfsBranch == null)
{
Trace.TraceInformation("error: branch not found. Verify that all the folders have been converted to branches (or something else :().\n\tpath {0}", tfsPath);
tfsRemote = null;
omittedParentBranch = ";C" + parentChangesetId;
}
else
{
tfsRemote = InitTfsRemoteOfChangeset(tfsBranch, parentChangeset.ChangesetId, renameResult);
if (tfsRemote == null)
omittedParentBranch = tfsBranch.Path + ";C" + parentChangesetId;
}
}
return tfsRemote;
}
private IGitTfsRemote InitTfsRemoteOfChangeset(IBranchObject tfsBranch, int parentChangesetId, IRenameResult renameResult = null)
{
if (tfsBranch.IsRoot)
{
return InitTfsBranch(_remoteOptions, tfsBranch.Path);
}
var branchesDatas = Tfs.GetRootChangesetForBranch(tfsBranch.Path, parentChangesetId);
IGitTfsRemote remote = null;
foreach (var branch in branchesDatas)
{
var rootChangesetId = branch.SourceBranchChangesetId;
remote = InitBranch(_remoteOptions, tfsBranch.Path, rootChangesetId, true);
if (remote == null)
{
Trace.TraceInformation("warning: root commit not found corresponding to changeset " + rootChangesetId);
Trace.TraceInformation("=> continuing anyway by creating a branch without parent...");
return InitTfsBranch(_remoteOptions, tfsBranch.Path);
}
if (branch.IsRenamedBranch)
{
try
{
remote.Fetch(renameResult: renameResult);
}
finally
{
Trace.WriteLine("Cleaning...");
remote.CleanupWorkspaceDirectory();
if (remote.Repository.IsBare)
remote.Repository.UpdateRef(GitRepository.ShortToLocalName(remote.Id), remote.MaxCommitHash);
}
}
}
return remote;
}
public void QuickFetch(int changesetId, bool ignoreRestricted, bool printRestrictionHint)
{
try
{
ITfsChangeset changeset;
if (changesetId < 0)
changeset = GetLatestChangeset();
else
changeset = Tfs.GetChangeset(changesetId, this);
quickFetch(changeset);
}
catch (Exception ex)
{
Trace.WriteLine("Quick fetch failed: " + ex.Message);
if (!IgnoreException(ex.Message, ignoreRestricted, printRestrictionHint))
throw;
}
}
private void quickFetch(ITfsChangeset changeset)
{
var log = CopyTree(MaxCommitHash, changeset);
UpdateTfsHead(Commit(log), changeset.Summary.ChangesetId);
DoGcIfNeeded();
}
private IEnumerable<ITfsChangeset> FetchChangesets(bool byLots, int lastVersion = -1)
{
int lowerBoundChangesetId;
// If we're starting at the Root side of a branch commit (e.g. C1), but there ar
// invalid commits between C1 and the actual branch side of the commit operation
// (e.g. a Folder with the branch name was created [C2] and then deleted [C3],
// then the root-side was branched [C4; C1 --branch--> C4]), this will detecte
// only the folder creation and deletion operations due to the lowerBound being
// detected as the root-side of the commit +1 (C1+1=C2) instead of referencing
// the branch-side of the branching operation [C4].
if (_properties.InitialChangeset.HasValue || firstChangesetId.HasValue)
{
var firstChangesetInBranch = Math.Max(_properties.InitialChangeset ?? int.MinValue, firstChangesetId ?? int.MinValue);
lowerBoundChangesetId = Math.Max(MaxChangesetId + 1, firstChangesetInBranch);
}
else
lowerBoundChangesetId = MaxChangesetId + 1;
Trace.WriteLine(RemoteRef + ": Getting changesets from " + lowerBoundChangesetId +
" to " + lastVersion + " ...", "info");
if (!IsSubtreeOwner)
return Tfs.GetChangesets(TfsRepositoryPath, lowerBoundChangesetId, this, lastVersion, byLots);
return _globals.Repository.GetSubtrees(this)
.SelectMany(x => Tfs.GetChangesets(x.TfsRepositoryPath, lowerBoundChangesetId, x, lastVersion, byLots))
.OrderBy(x => x.Summary.ChangesetId);
}
public ITfsChangeset GetChangeset(int changesetId)
{
return Tfs.GetChangeset(changesetId, this);
}
private ITfsChangeset GetLatestChangeset()
{
if (!string.IsNullOrEmpty(TfsRepositoryPath))
return Tfs.GetLatestChangeset(this);
var changesetId = _globals.Repository.GetSubtrees(this).Select(x => Tfs.GetLatestChangeset(x)).Max(x => x.Summary.ChangesetId);
return GetChangeset(changesetId);
}
private int GetLatestChangesetId()
{
if (!string.IsNullOrEmpty(TfsRepositoryPath))
return Tfs.GetLatestChangesetId(this);
return _globals.Repository.GetSubtrees(this).Select(x => Tfs.GetLatestChangesetId(x)).Max();
}
public void UpdateTfsHead(string commitHash, int changesetId)
{
MaxCommitHash = commitHash;
MaxChangesetId = changesetId;
Repository.UpdateRef(RemoteRef, MaxCommitHash, "C" + MaxChangesetId);
if (Autotag)
Repository.UpdateRef(TagPrefix + "C" + MaxChangesetId, MaxCommitHash);
LogCurrentMapping();
}
private void LogCurrentMapping()
{
Trace.TraceInformation("C" + MaxChangesetId + " = " + MaxCommitHash);
}
private string TagPrefix
{
get { return "refs/tags/tfs/" + Id + "/"; }
}
public string RemoteRef
{
get { return "refs/remotes/tfs/" + Id; }
}
private void DoGcIfNeeded()
{
Trace.WriteLine("GC Countdown: " + _globals.GcCountdown);
if (--_globals.GcCountdown < 0)
{
_globals.GcCountdown = _globals.GcPeriod;
Repository.GarbageCollect(true, "Try running it after git-tfs is finished.");
}
}
private LogEntry Apply(string parent, ITfsChangeset changeset, IDictionary<string, GitObject> entries)
{
return Apply(parent, changeset, entries, null);
}
private LogEntry Apply(string parent, ITfsChangeset changeset, Action<Exception> ignorableErrorHandler)
{
return Apply(parent, changeset, BuildEntryDictionary(), ignorableErrorHandler);
}
private LogEntry Apply(string parent, ITfsChangeset changeset, IDictionary<string, GitObject> entries, Action<Exception> ignorableErrorHandler)
{
LogEntry result = null;
WithWorkspace(changeset.Summary, workspace =>
{
var treeBuilder = workspace.Remote.Repository.GetTreeBuilder(parent);
result = changeset.Apply(parent, treeBuilder, workspace, entries, ignorableErrorHandler);
result.Tree = treeBuilder.GetTree();
});
if (!string.IsNullOrEmpty(parent)) result.CommitParents.Add(parent);
return result;
}
private LogEntry CopyTree(string lastCommit, ITfsChangeset changeset)
{
LogEntry result = null;
WithWorkspace(changeset.Summary, workspace =>
{
var treeBuilder = workspace.Remote.Repository.GetTreeBuilder(lastCommit);
result = changeset.CopyTree(treeBuilder, workspace);
result.Tree = treeBuilder.GetTree();
});
if (!string.IsNullOrEmpty(lastCommit)) result.CommitParents.Add(lastCommit);
return result;
}
private string Commit(LogEntry logEntry)
{
logEntry.Log = BuildCommitMessage(logEntry.Log, logEntry.ChangesetId);
return Repository.Commit(logEntry).Sha;
}
private string BuildCommitMessage(string tfsCheckinComment, int changesetId)
{
var builder = new StringWriter();
builder.WriteLine(tfsCheckinComment);
builder.WriteLine(GitTfsConstants.TfsCommitInfoFormat,
TfsUrl, TfsRepositoryPath, changesetId);
return builder.ToString();
}
public void Unshelve(string shelvesetOwner, string shelvesetName, string destinationBranch, Action<Exception> ignorableErrorHandler, bool force)
{
var destinationRef = GitRepository.ShortToLocalName(destinationBranch);
if (Repository.HasRef(destinationRef))
throw new GitTfsException("ERROR: Destination branch (" + destinationBranch + ") already exists!");
var shelvesetChangeset = Tfs.GetShelvesetData(this, shelvesetOwner, shelvesetName);
var parentId = shelvesetChangeset.BaseChangesetId;
var ch = GetTfsChangesetById(parentId);
string rootCommit;
if (ch == null)
{
if (!force)
throw new GitTfsException("ERROR: Parent changeset C" + parentId + " not found.", new[]
{
"Try fetching the latest changes from TFS",
"Try applying the shelveset on the currently checkouted commit using the '--force' option"
}
);
Trace.TraceInformation("warning: Parent changeset C" + parentId + " not found."
+ " Trying to apply the shelveset on the current commit...");
rootCommit = Repository.GetCurrentCommit();
}
else
{
rootCommit = ch.GitCommit;
}
var log = Apply(rootCommit, shelvesetChangeset, ignorableErrorHandler);
var commit = Commit(log);
Repository.UpdateRef(destinationRef, commit, "Shelveset " + shelvesetName + " from " + shelvesetOwner);
}
public void Shelve(string shelvesetName, string head, TfsChangesetInfo parentChangeset, CheckinOptions options, bool evaluateCheckinPolicies)
{
WithWorkspace(parentChangeset, workspace => Shelve(shelvesetName, head, parentChangeset, options, evaluateCheckinPolicies, workspace));
}
public bool HasShelveset(string shelvesetName)
{
return Tfs.HasShelveset(shelvesetName);
}
private void Shelve(string shelvesetName, string head, TfsChangesetInfo parentChangeset, CheckinOptions options, bool evaluateCheckinPolicies, ITfsWorkspace workspace)
{
PendChangesToWorkspace(head, parentChangeset.GitCommit, workspace);
workspace.Shelve(shelvesetName, evaluateCheckinPolicies, options, () => Repository.GetCommitMessage(head, parentChangeset.GitCommit));
}
public int CheckinTool(string head, TfsChangesetInfo parentChangeset)
{
var changeset = 0;
WithWorkspace(parentChangeset, workspace => changeset = CheckinTool(head, parentChangeset, workspace));
return changeset;
}
private int CheckinTool(string head, TfsChangesetInfo parentChangeset, ITfsWorkspace workspace)
{
PendChangesToWorkspace(head, parentChangeset.GitCommit, workspace);
return workspace.CheckinTool(() => Repository.GetCommitMessage(head, parentChangeset.GitCommit));
}
private void PendChangesToWorkspace(string head, string parent, ITfsWorkspaceModifier workspace)
{
using (var tidyWorkspace = new DirectoryTidier(workspace, () => GetLatestChangeset().GetFullTree()))
{
foreach (var change in Repository.GetChangedFiles(parent, head))
{
change.Apply(tidyWorkspace);
}
}
}
public int Checkin(string head, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null)
{
var changeset = 0;
WithWorkspace(parentChangeset, workspace => changeset = Checkin(head, parentChangeset.GitCommit, workspace, options, sourceTfsPath));
return changeset;
}
public int Checkin(string head, string parent, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null)
{
var changeset = 0;
WithWorkspace(parentChangeset, workspace => changeset = Checkin(head, parent, workspace, options, sourceTfsPath));
return changeset;
}
private void WithWorkspace(TfsChangesetInfo parentChangeset, Action<ITfsWorkspace> action)
{
//are there any subtrees?
var subtrees = _globals.Repository.GetSubtrees(this);
if (subtrees.Any())
{
Tfs.WithWorkspace(WorkingDirectory, this, subtrees.Select(x => new Tuple<string, string>(x.TfsRepositoryPath, x.Prefix)), parentChangeset, action);
}
else
{
Tfs.WithWorkspace(WorkingDirectory, this, parentChangeset, action);
}
}
private int Checkin(string head, string parent, ITfsWorkspace workspace, CheckinOptions options, string sourceTfsPath)
{
PendChangesToWorkspace(head, parent, workspace);
if (!string.IsNullOrWhiteSpace(sourceTfsPath))
workspace.Merge(sourceTfsPath, TfsRepositoryPath);
return workspace.Checkin(options, () => Repository.GetCommitMessage(head, parent));
}
public bool MatchesUrlAndRepositoryPath(string tfsUrl, string tfsRepositoryPath)
{
if (!MatchesTfsUrl(tfsUrl))
return false;
if (TfsRepositoryPath == null)
return tfsRepositoryPath == null;
return TfsRepositoryPath.Equals(tfsRepositoryPath, StringComparison.OrdinalIgnoreCase);
}
public void DeleteShelveset(string shelvesetName)
{