forked from yysun/Git-Source-Control-Provider
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitFileStatusTracker.cs
More file actions
496 lines (421 loc) · 17.2 KB
/
GitFileStatusTracker.cs
File metadata and controls
496 lines (421 loc) · 17.2 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
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using NGit;
using NGit.Api;
using NGit.Diff;
using NGit.Dircache;
using NGit.Revwalk;
using NGit.Storage.File;
using NGit.Treewalk;
using NGit.Treewalk.Filter;
namespace GitScc
{
public class GitFileStatusTracker : IDisposable
{
private string initFolder;
private Repository repository;
private Tree commitTree;
private GitIndex index;
//private IgnoreHandler ignoreHandler;
private Dictionary<string, GitFileStatus> cache;
public GitFileStatusTracker(string workingFolder)
{
this.cache = new Dictionary<string, GitFileStatus>();
this.initFolder = workingFolder;
Refresh();
}
public void Refresh()
{
this.cache.Clear();
this.changedFiles = null;
if (!string.IsNullOrEmpty(initFolder))
{
try
{
this.repository = Git.Open(initFolder).GetRepository();
if (this.repository != null)
{
var id = repository.Resolve(Constants.HEAD);
//var commit = repository.MapCommit(id);
//this.commitTree = (commit != null ? commit.TreeEntry : new Tree(repository));
if (id == null)
{
this.commitTree = new Tree(repository);
}
else
{
var treeId = ObjectId.FromString(repository.Open(id).GetBytes(), 5);
this.commitTree = new Tree(repository, treeId, repository.Open(treeId).GetBytes());
}
this.index = repository.GetIndex();
this.index.RereadIfNecessary();
}
}
catch (Exception ex)
{
}
}
}
public void Dispose()
{
if (this.repository != null) this.repository.Close();
}
public string GitWorkingDirectory
{
get
{
return this.repository == null ? null :
this.repository.WorkTree;
}
}
public bool HasGitRepository
{
get { return this.repository != null; }
}
public GitFileStatus GetFileStatus(string fileName)
{
if (!HasGitRepository || string.IsNullOrEmpty(fileName))
return GitFileStatus.NotControlled;
if (!this.cache.ContainsKey(fileName))
{
var status = GetFileStatusNoCache(fileName);
this.cache.Add(fileName, status);
//Debug.WriteLine(string.Format("GetFileStatus {0} - {1}", fileName, status));
return status;
}
else
{
return this.cache[fileName];
}
}
private GitFileStatus GetFileStatusNoCache(string fileName)
{
//Debug.WriteLine(string.Format("===+ GetFileStatusNoCache {0}", fileName));
var fileNameRel = GetRelativeFileName(fileName);
TreeEntry treeEntry = this.commitTree.FindBlobMember(fileNameRel);
GitIndex.Entry indexEntry = this.index.GetEntry(fileNameRel);
//the order of 'if' below is important
if (indexEntry != null)
{
if (treeEntry == null)
{
return GitFileStatus.Added;
}
if (treeEntry != null && !treeEntry.GetId().Equals(indexEntry.GetObjectId()))
{
return GitFileStatus.Staged;
}
if (!File.Exists(fileName))
{
return GitFileStatus.Deleted;
}
if (File.Exists(fileName) && indexEntry.IsModified(repository.WorkTree, true))
{
return GitFileStatus.Modified;
}
if (indexEntry.GetStage() != 0)
{
return GitFileStatus.MergeConflict;
}
if (treeEntry != null && treeEntry.GetId().Equals(indexEntry.GetObjectId()))
{
return GitFileStatus.Tracked;
}
}
else // <-- index entry == null
{
if (treeEntry != null && !(treeEntry is Tree))
{
return GitFileStatus.Removed;
}
if (File.Exists(fileName))
{
//remove the ingore check for better performance
//if (this.ignoreHandler.IsIgnored(fileName))
//{
// return GitFileStatus.Ignored;
//}
return GitFileStatus.New;
}
}
return GitFileStatus.NotControlled;
}
private string GetRelativeFileName(string fileName)
{
return GetRelativePath(repository.WorkTree, fileName);
}
/// <summary>
/// Computes relative path, where path is relative to reference_path
/// </summary>
/// <param name="reference_path"></param>
/// <param name="path"></param>
/// <returns></returns>
public static string GetRelativePath(string reference_path, string path)
{
if (reference_path == null)
throw new ArgumentNullException("reference_path");
if (path == null)
throw new ArgumentNullException("path");
//reference_path = reference_path.Replace('/', '\\');
//path = path.Replace('/', '\\');
bool isRooted = Path.IsPathRooted(reference_path) && Path.IsPathRooted(path);
if (isRooted)
{
bool isDifferentRoot = string.Compare(Path.GetPathRoot(reference_path), Path.GetPathRoot(path), true) != 0;
if (isDifferentRoot)
return path;
}
var relativePath = new StringCollection();
string[] fromDirectories = Regex.Split(reference_path, @"[/\\]+");
string[] toDirectories = Regex.Split(path, @"[/\\]+");
int length = Math.Min(fromDirectories.Length, toDirectories.Length);
int lastCommonRoot = -1;
// find common root
for (int x = 0; x < length; x++)
{
if (string.Compare(fromDirectories[x],
toDirectories[x], true) != 0)
break;
lastCommonRoot = x;
}
if (lastCommonRoot == -1)
return string.Join(Path.DirectorySeparatorChar.ToString(), toDirectories);
// add relative folders in from path
for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++)
if (fromDirectories[x].Length > 0)
relativePath.Add("..");
// add to folders to path
for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++)
relativePath.Add(toDirectories[x]);
// create relative path
string[] relativeParts = new string[relativePath.Count];
relativePath.CopyTo(relativeParts, 0);
string newPath = string.Join(Path.DirectorySeparatorChar.ToString(), relativeParts);
return newPath;
}
public byte[] GetFileContent(string fileName)
{
if (!HasGitRepository || string.IsNullOrEmpty(fileName))
return null;
fileName = GetRelativeFileName(fileName);
var entry = commitTree.FindBlobMember(fileName);
if (entry != null)
{
var blob = repository.Open(entry.GetId());
if (blob != null) return blob.GetCachedBytes();
}
return null;
}
public string CurrentBranch
{
get
{
return this.HasGitRepository ? this.repository.GetBranch() : "";
}
}
/// <summary>
/// Search Git Repository in folder and its parent folders
/// </summary>
/// <param name="folder">starting folder</param>
/// <returns>folder that has .git subfolder</returns>
public static string GetRepositoryDirectory(string folder)
{
if(string.IsNullOrWhiteSpace(folder) || !Directory.Exists(folder)) return null;
var directory = new DirectoryInfo(folder);
if (directory.GetDirectories(Constants.DOT_GIT).Length > 0)
{
return folder;
}
return directory.Parent == null ? null :
GetRepositoryDirectory(directory.Parent.FullName);
}
public override string ToString()
{
return repository == null ? "[no repo]" : this.GitWorkingDirectory;
}
/// <summary>
/// Requires absolute path
/// </summary>
/// <param name="fileName"></param>
public void UnStageFile(string fileName)
{
var fileNameRel = GetRelativeFileName(fileName);
TreeEntry treeEntry = this.commitTree.FindBlobMember(fileNameRel);
//fileName = Path.Combine(initFolder, fileName);
if (!this.HasGitRepository) return;
this.index.RereadIfNecessary();
this.index.Remove(repository.WorkTree, fileName);
if (treeEntry != null)
{
this.index.AddEntry(treeEntry);
}
this.index.Write();
this.cache[fileName] = GetFileStatusNoCache(fileName);
}
/// <summary>
/// Requires absolute path
/// </summary>
/// <param name="fileName"></param>
public void StageFile(string fileName)
{
//fileName = Path.Combine(initFolder, fileName);
if (!this.HasGitRepository) return;
this.index.RereadIfNecessary();
if (File.Exists(fileName))
{
var content = File.ReadAllBytes(fileName);
this.index.Add(repository.WorkTree, fileName, content);
}
else
{
//stage deleted
this.index.Remove(repository.WorkTree, fileName);
}
this.index.Write();
this.cache[fileName] = GetFileStatusNoCache(fileName);
}
public void RemoveFile(string fileName)
{
if (!this.HasGitRepository) return;
this.index.RereadIfNecessary();
this.index.Remove(repository.WorkTree, fileName);
this.index.Write();
this.cache[fileName] = GetFileStatusNoCache(fileName);
}
/// <summary>
/// Diff working file with last commit
/// </summary>
/// <param name="fileName">Expect relative path</param>
/// <returns></returns>
public string DiffFile(string fileName)
{
if (!this.HasGitRepository) return null;
HistogramDiff hd = new HistogramDiff();
hd.SetFallbackAlgorithm(null);
var fullName = GetFullPath(fileName);
RawText b = new RawText(File.Exists(GetFullPath(fileName)) ?
File.ReadAllBytes(fullName) : new byte[0]);
RawText a = new RawText(GetFileContent(fileName) ?? new byte[0]);
var list = hd.Diff(RawTextComparator.DEFAULT, a, b);
using (Stream mstream = new MemoryStream(),
stream = new BufferedStream(mstream))
{
DiffFormatter df = new DiffFormatter(stream);
df.Format(list, a, b);
df.Flush();
stream.Seek(0, SeekOrigin.Begin);
var ret = new StreamReader(stream).ReadToEnd();
return ret;
}
}
public string Commit(string message)
{
if (!this.HasGitRepository) return null;
if (string.IsNullOrEmpty(message))
throw new ArgumentException("Commit message must not be null or empty!", "message");
var git = new Git(this.repository);
var rev = git.Commit().SetMessage(message).Call();
Refresh();
return rev.Name;
}
public string AmendCommit(string message)
{
if (!HasGitRepository) return null;
if (string.IsNullOrEmpty(message))
throw new ArgumentException("Commit message must not be null or empty!", "message");
var git = new Git(this.repository);
var rev = git.Commit().SetAmend(true).SetMessage(message).Call();
Refresh();
return rev.Name;
}
public static void Init(string folderName)
{
var gitFolder = Path.Combine(folderName, Constants.DOT_GIT);
var repo = new FileRepository(gitFolder);
repo.Create();
var dir = Directory.CreateDirectory(gitFolder);
dir.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
}
private IEnumerable<GitFile> changedFiles;
public IEnumerable<GitFile> ChangedFiles
{
get
{
if (changedFiles == null)
{
FillCache();
changedFiles = from f in this.cache
where f.Value != GitFileStatus.Tracked &&
f.Value != GitFileStatus.NotControlled //&&
//f.Value != GitFileStatus.Deleted
select new GitFile
{
FileName = GetRelativeFileName(f.Key),
Status = f.Value,
IsStaged = f.Value == GitFileStatus.Added ||
f.Value == GitFileStatus.Staged ||
f.Value == GitFileStatus.Removed
};
}
return changedFiles;
}
}
private const int INDEX = 1;
private const int WORKDIR = 2;
public void FillCache()
{
var treeWalk = new TreeWalk(this.repository);
treeWalk.Recursive = true;
treeWalk.Filter = TreeFilter.ANY_DIFF;
var id = repository.Resolve(Constants.HEAD);
if (id != null)
{
treeWalk.AddTree(ObjectId.FromString(repository.Open(id).GetBytes(), 5)); //any better way?
}
else
{
treeWalk.AddTree(new EmptyTreeIterator());
}
treeWalk.AddTree(new DirCacheIterator(this.repository.ReadDirCache()));
treeWalk.AddTree(new FileTreeIterator(this.repository));
var filters = new TreeFilter[] { new SkipWorkTreeFilter(INDEX), new IndexDiffFilter(INDEX, WORKDIR) };
treeWalk.Filter = AndTreeFilter.Create(filters);
while (treeWalk.Next())
{
var fileName = GetFullPath(treeWalk.PathString);
if (Directory.Exists(fileName)) continue; // this excludes sub modules
var status = GetFileStatusNoCache(fileName);
this.cache[fileName] = status;
//Debug.WriteLine(string.Format("==== Fill cache for {0} <- {1}", fileName, status));
}
}
private string GetFullPath(string fileName)
{
if (string.IsNullOrWhiteSpace(fileName)) return this.GitWorkingDirectory;
return Path.Combine(this.GitWorkingDirectory, fileName.Replace("/", "\\"));
}
public string LastCommitMessage
{
get
{
if (!HasGitRepository) return null;
ObjectId headId = this.repository.Resolve(Constants.HEAD);
if (headId != null)
{
var revWalk = new RevWalk(this.repository);
revWalk.MarkStart(revWalk.LookupCommit(headId));
foreach (RevCommit c in revWalk)
{
return c.GetFullMessage();
}
}
return "";
}
}
}
}