/
Index.cs
507 lines (413 loc) · 18.9 KB
/
Index.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Compat;
using LibGit2Sharp.Core.Handles;
namespace LibGit2Sharp
{
/// <summary>
/// The Index is a staging area between the Working directory and the Repository.
/// It's used to prepare and aggregate the changes that will be part of the next commit.
/// </summary>
public class Index : IEnumerable<IndexEntry>
{
private readonly IndexSafeHandle handle;
private readonly Repository repo;
/// <summary>
/// Needed for mocking purposes.
/// </summary>
protected Index()
{ }
internal Index(Repository repo)
{
this.repo = repo;
Ensure.Success(NativeMethods.git_repository_index(out handle, repo.Handle));
repo.RegisterForCleanup(handle);
}
internal Index(Repository repo, string indexPath)
{
this.repo = repo;
Ensure.Success(NativeMethods.git_index_open(out handle, indexPath));
NativeMethods.git_repository_set_index(repo.Handle, handle);
repo.RegisterForCleanup(handle);
}
internal IndexSafeHandle Handle
{
get { return handle; }
}
/// <summary>
/// Gets the number of <see cref = "IndexEntry" /> in the index.
/// </summary>
public virtual int Count
{
get { return (int)NativeMethods.git_index_entrycount(handle); }
}
/// <summary>
/// Gets the <see cref = "IndexEntry" /> with the specified relative path.
/// </summary>
public virtual IndexEntry this[string path]
{
get
{
Ensure.ArgumentNotNullOrEmptyString(path, "path");
int res = NativeMethods.git_index_find(handle, path);
if (res == (int)GitErrorCode.NotFound)
{
return null;
}
Ensure.Success(res, true);
return this[(uint)res];
}
}
private IndexEntry this[uint index]
{
get
{
IndexEntrySafeHandle entryHandle = NativeMethods.git_index_get(handle, index);
return IndexEntry.CreateFromPtr(repo, entryHandle);
}
}
#region IEnumerable<IndexEntry> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>An <see cref = "IEnumerator{T}" /> object that can be used to iterate through the collection.</returns>
public virtual IEnumerator<IndexEntry> GetEnumerator()
{
for (uint i = 0; i < Count; i++)
{
yield return this[i];
}
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>An <see cref = "IEnumerator" /> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
/// <summary>
/// Promotes to the staging area the latest modifications of a file in the working directory (addition, updation or removal).
/// </summary>
/// <param name = "path">The path of the file within the working directory.</param>
public virtual void Stage(string path)
{
Ensure.ArgumentNotNull(path, "path");
Stage(new[] { path });
}
/// <summary>
/// Promotes to the staging area the latest modifications of a collection of files in the working directory (addition, updation or removal).
/// </summary>
/// <param name = "paths">The collection of paths of the files within the working directory.</param>
public virtual void Stage(IEnumerable<string> paths)
{
//TODO: Stage() should support following use cases:
// - Recursively staging the content of a directory
IEnumerable<KeyValuePair<string, FileStatus>> batch = PrepareBatch(paths);
foreach (KeyValuePair<string, FileStatus> kvp in batch)
{
if (Directory.Exists(kvp.Key))
{
throw new NotImplementedException();
}
if (!kvp.Value.Has(FileStatus.Nonexistent))
{
continue;
}
throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Can not stage '{0}'. The file does not exist.", kvp.Key));
}
foreach (KeyValuePair<string, FileStatus> kvp in batch)
{
string relativePath = kvp.Key;
FileStatus fileStatus = kvp.Value;
if (fileStatus.Has(FileStatus.Missing))
{
RemoveFromIndex(relativePath);
}
else
{
AddToIndex(relativePath);
}
}
UpdatePhysicalIndex();
}
/// <summary>
/// Removes from the staging area all the modifications of a file since the latest commit (addition, updation or removal).
/// </summary>
/// <param name = "path">The path of the file within the working directory.</param>
public virtual void Unstage(string path)
{
Ensure.ArgumentNotNull(path, "path");
Unstage(new[] { path });
}
/// <summary>
/// Removes from the staging area all the modifications of a collection of file since the latest commit (addition, updation or removal).
/// </summary>
/// <param name = "paths">The collection of paths of the files within the working directory.</param>
public virtual void Unstage(IEnumerable<string> paths)
{
repo.Reset("HEAD", paths);
}
/// <summary>
/// Moves and/or renames a file in the working directory and promotes the change to the staging area.
/// </summary>
/// <param name = "sourcePath">The path of the file within the working directory which has to be moved/renamed.</param>
/// <param name = "destinationPath">The target path of the file within the working directory.</param>
public virtual void Move(string sourcePath, string destinationPath)
{
Move(new[] { sourcePath }, new[] { destinationPath });
}
/// <summary>
/// Moves and/or renames a collection of files in the working directory and promotes the changes to the staging area.
/// </summary>
/// <param name = "sourcePaths">The paths of the files within the working directory which have to be moved/renamed.</param>
/// <param name = "destinationPaths">The target paths of the files within the working directory.</param>
public virtual void Move(IEnumerable<string> sourcePaths, IEnumerable<string> destinationPaths)
{
Ensure.ArgumentNotNull(sourcePaths, "sourcePaths");
Ensure.ArgumentNotNull(destinationPaths, "destinationPaths");
//TODO: Move() should support following use cases:
// - Moving a file under a directory ('file' and 'dir' -> 'dir/file')
// - Moving a directory (and its content) under another directory ('dir1' and 'dir2' -> 'dir2/dir1/*')
//TODO: Move() should throw when:
// - Moving a directory under a file
IDictionary<Tuple<string, FileStatus>, Tuple<string, FileStatus>> batch = PrepareBatch(sourcePaths, destinationPaths);
if (batch.Count == 0)
{
throw new ArgumentNullException("sourcePaths");
}
foreach (KeyValuePair<Tuple<string, FileStatus>, Tuple<string, FileStatus>> keyValuePair in batch)
{
string sourcePath = keyValuePair.Key.Item1;
string destPath = keyValuePair.Value.Item1;
if (Directory.Exists(sourcePath) || Directory.Exists(destPath))
{
throw new NotImplementedException();
}
FileStatus sourceStatus = keyValuePair.Key.Item2;
if (sourceStatus.HasAny(new[] { FileStatus.Nonexistent, FileStatus.Removed, FileStatus.Untracked, FileStatus.Missing }))
{
throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unable to move file '{0}'. Its current status is '{1}'.", sourcePath, sourceStatus));
}
FileStatus desStatus = keyValuePair.Value.Item2;
if (desStatus.HasAny(new[] { FileStatus.Nonexistent, FileStatus.Missing }))
{
continue;
}
throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unable to overwrite file '{0}'. Its current status is '{1}'.", destPath, desStatus));
}
string wd = repo.Info.WorkingDirectory;
foreach (KeyValuePair<Tuple<string, FileStatus>, Tuple<string, FileStatus>> keyValuePair in batch)
{
string from = keyValuePair.Key.Item1;
string to = keyValuePair.Value.Item1;
RemoveFromIndex(from);
File.Move(Path.Combine(wd, from), Path.Combine(wd, to));
AddToIndex(to);
}
UpdatePhysicalIndex();
}
/// <summary>
/// Removes a file from the working directory and promotes the removal to the staging area.
/// <para>
/// If the file has already been deleted from the working directory, this method will only deal
/// with promoting the removal to the staging area.
/// </para>
/// </summary>
/// <param name = "path">The path of the file within the working directory.</param>
public virtual void Remove(string path)
{
Ensure.ArgumentNotNull(path, "path");
Remove(new[] { path });
}
/// <summary>
/// Removes a collection of files from the working directory and promotes the removal to the staging area.
/// <para>
/// If a file has already been deleted from the working directory, this method will only deal
/// with promoting the removal to the staging area.
/// </para>
/// </summary>
/// <param name = "paths">The collection of paths of the files within the working directory.</param>
public virtual void Remove(IEnumerable<string> paths)
{
//TODO: Remove() should support following use cases:
// - Removing a directory and its content
IEnumerable<KeyValuePair<string, FileStatus>> batch = PrepareBatch(paths);
foreach (KeyValuePair<string, FileStatus> keyValuePair in batch)
{
if (Directory.Exists(keyValuePair.Key))
{
throw new NotImplementedException();
}
if (!keyValuePair.Value.HasAny(new[] { FileStatus.Nonexistent, FileStatus.Removed, FileStatus.Modified, FileStatus.Untracked }))
{
continue;
}
throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unable to remove file '{0}'. Its current status is '{1}'.", keyValuePair.Key, keyValuePair.Value));
}
string wd = repo.Info.WorkingDirectory;
foreach (KeyValuePair<string, FileStatus> keyValuePair in batch)
{
RemoveFromIndex(keyValuePair.Key);
if (File.Exists(Path.Combine(wd, keyValuePair.Key)))
{
File.Delete(Path.Combine(wd, keyValuePair.Key));
}
}
UpdatePhysicalIndex();
}
private IEnumerable<KeyValuePair<string, FileStatus>> PrepareBatch(IEnumerable<string> paths)
{
Ensure.ArgumentNotNull(paths, "paths");
IDictionary<string, FileStatus> dic = new Dictionary<string, FileStatus>();
foreach (string path in paths)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentException("At least one provided path is either null or empty.", "paths");
}
string relativePath = BuildRelativePathFrom(repo, path);
FileStatus fileStatus = RetrieveStatus(relativePath);
dic.Add(relativePath, fileStatus);
}
if (dic.Count == 0)
{
throw new ArgumentException("No path has been provided.", "paths");
}
return dic;
}
private IDictionary<Tuple<string, FileStatus>, Tuple<string, FileStatus>> PrepareBatch(IEnumerable<string> leftPaths, IEnumerable<string> rightPaths)
{
IDictionary<Tuple<string, FileStatus>, Tuple<string, FileStatus>> dic = new Dictionary<Tuple<string, FileStatus>, Tuple<string, FileStatus>>();
IEnumerator<string> leftEnum = leftPaths.GetEnumerator();
IEnumerator<string> rightEnum = rightPaths.GetEnumerator();
while (Enumerate(leftEnum, rightEnum))
{
Tuple<string, FileStatus> from = BuildFrom(leftEnum.Current);
Tuple<string, FileStatus> to = BuildFrom(rightEnum.Current);
dic.Add(from, to);
}
return dic;
}
private Tuple<string, FileStatus> BuildFrom(string path)
{
string relativePath = BuildRelativePathFrom(repo, path);
return new Tuple<string, FileStatus>(relativePath, RetrieveStatus(relativePath));
}
private static bool Enumerate(IEnumerator<string> leftEnum, IEnumerator<string> rightEnum)
{
bool isLeftEoF = leftEnum.MoveNext();
bool isRightEoF = rightEnum.MoveNext();
if (isLeftEoF == isRightEoF)
{
return isLeftEoF;
}
throw new ArgumentException("The collection of paths are of different lengths.");
}
private void AddToIndex(string relativePath)
{
int res = NativeMethods.git_index_add(handle, relativePath);
Ensure.Success(res);
}
private void RemoveFromIndex(string relativePath)
{
int res = NativeMethods.git_index_find(handle, relativePath);
Ensure.Success(res, true);
res = NativeMethods.git_index_remove(handle, res);
Ensure.Success(res);
}
private void UpdatePhysicalIndex()
{
int res = NativeMethods.git_index_write(handle);
Ensure.Success(res);
}
private static string BuildRelativePathFrom(Repository repo, string path)
{
//TODO: To be removed when libgit2 natively implements this
if (!Path.IsPathRooted(path))
{
return path;
}
string normalizedPath = Path.GetFullPath(path);
if (!normalizedPath.StartsWith(repo.Info.WorkingDirectory, StringComparison.Ordinal))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
"Unable to process file '{0}'. This file is not located under the working directory of the repository ('{1}').",
normalizedPath, repo.Info.WorkingDirectory));
}
return normalizedPath.Substring(repo.Info.WorkingDirectory.Length);
}
/// <summary>
/// Retrieves the state of a file in the working directory, comparing it against the staging area and the latest commmit.
/// </summary>
/// <param name = "filePath">The relative path within the working directory to the file.</param>
/// <returns>A <see cref = "FileStatus" /> representing the state of the <paramref name = "filePath" /> parameter.</returns>
public virtual FileStatus RetrieveStatus(string filePath)
{
Ensure.ArgumentNotNullOrEmptyString(filePath, "filePath");
string relativePath = BuildRelativePathFrom(repo, filePath);
FileStatus status;
int res = NativeMethods.git_status_file(out status, repo.Handle, relativePath);
if (res == (int)GitErrorCode.NotFound)
{
return FileStatus.Nonexistent;
}
Ensure.Success(res);
return status;
}
/// <summary>
/// Retrieves the state of all files in the working directory, comparing them against the staging area and the latest commmit.
/// </summary>
/// <returns>A <see cref = "RepositoryStatus" /> holding the state of all the files.</returns>
public virtual RepositoryStatus RetrieveStatus()
{
return new RepositoryStatus(repo);
}
internal void ReplaceContentWithTree(Tree tree)
{
using (var nativeTree = new ObjectSafeWrapper(tree.Id, repo))
{
int res = NativeMethods.git_index_read_tree(Handle, nativeTree.ObjectPtr, IntPtr.Zero);
Ensure.Success(res);
UpdatePhysicalIndex();
}
}
internal void Reset(TreeChanges changes)
{
foreach (TreeEntryChanges treeEntryChanges in changes)
{
switch (treeEntryChanges.Status)
{
case ChangeKind.Added:
RemoveFromIndex(treeEntryChanges.Path);
continue;
case ChangeKind.Deleted:
/* Fall through */
case ChangeKind.Modified:
ReplaceIndexEntryWith(treeEntryChanges);
continue;
default:
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Entry '{0}' bears an unexpected ChangeKind '{1}'", treeEntryChanges.Path, treeEntryChanges.Status));
}
}
UpdatePhysicalIndex();
}
private void ReplaceIndexEntryWith(TreeEntryChanges treeEntryChanges)
{
var indexEntry = new GitIndexEntry
{
Mode = (uint)treeEntryChanges.OldMode,
oid = treeEntryChanges.OldOid.Oid,
Path = FilePathMarshaler.FromManaged(treeEntryChanges.OldPath),
};
Ensure.Success(NativeMethods.git_index_add2(handle, indexEntry));
Marshal.FreeHGlobal(indexEntry.Path);
}
}
}