/
Index.cs
333 lines (266 loc) · 11.5 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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using LibGit2Sharp.Core;
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>, IDisposable
{
private readonly IndexSafeHandle handle;
private readonly Repository repo;
internal Index(Repository repo)
{
this.repo = repo;
int res = NativeMethods.git_repository_index(out handle, repo.Handle);
Ensure.Success(res);
}
internal IndexSafeHandle Handle
{
get { return handle; }
}
/// <summary>
/// Gets the number of <see cref = "IndexEntry" /> in the index.
/// </summary>
public int Count
{
get { return (int)NativeMethods.git_index_entrycount(handle); }
}
/// <summary>
/// Gets the <see cref = "IndexEntry" /> with the specified relative path.
/// </summary>
public IndexEntry this[string path]
{
get
{
Ensure.ArgumentNotNullOrEmptyString(path, "path");
int res = NativeMethods.git_index_find(handle, path);
if (res == (int)GitErrorCode.GIT_ENOTFOUND)
{
return null;
}
Ensure.Success(res, true);
return this[(uint)res];
}
}
private IndexEntry this[uint index]
{
get
{
IntPtr entryPtr = NativeMethods.git_index_get(handle, index);
return IndexEntry.CreateFromPtr(repo, entryPtr);
}
}
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
protected virtual void Dispose(bool disposing)
{
handle.SafeDispose();
}
#endregion
#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 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 relative path within the working directory to the file.</param>
public void Stage(string path)
{
Ensure.ArgumentNotNullOrEmptyString(path, "path");
string relativePath = BuildRelativePathFrom(repo, path);
FileStatus fileStatus = RetrieveStatus(relativePath);
if (fileStatus.Has(FileStatus.Nonexistent))
{
throw new LibGit2Exception("Can not stage '{0}'. The file does not exist.");
}
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 relative path within the working directory to the file.</param>
public void Unstage(string path)
{
Ensure.ArgumentNotNullOrEmptyString(path, "path");
string relativePath = BuildRelativePathFrom(repo, path);
FileStatus fileStatus = RetrieveStatus(relativePath);
bool doesExistInindex =
!(fileStatus.Has(FileStatus.Nonexistent) || fileStatus.Has(FileStatus.Removed) ||
fileStatus.Has(FileStatus.Untracked));
if (doesExistInindex)
{
RemoveFromIndex(relativePath);
}
bool doesExistInWorkingDirectory =
!(fileStatus.Has(FileStatus.Removed) || fileStatus.Has(FileStatus.Nonexistent) ||
fileStatus.Has(FileStatus.Missing));
RestorePotentialPreviousVersionOfHeadIntoIndex(relativePath, doesExistInWorkingDirectory);
UpdatePhysicalIndex();
}
/// <summary>
/// Moves and/or renames a file in the working directory and promotes the change to the staging area.
/// </summary>
/// <param name="sourcePath">The relative path within the working directory to the file which has to be moved/renamed.</param>
/// <param name="destinationPath">The target relative path within the working directory of the file.</param>
public void Move(string sourcePath, string destinationPath)
{
Ensure.ArgumentNotNullOrEmptyString(sourcePath, "sourcepath");
Ensure.ArgumentNotNullOrEmptyString(destinationPath, "destinationpath");
string relativeSourcePath = BuildRelativePathFrom(repo, sourcePath);
string relativeDestinationPath = BuildRelativePathFrom(repo, destinationPath);
string wd = repo.Info.WorkingDirectory;
if (Directory.Exists(Path.Combine(wd, relativeSourcePath)))
{
throw new NotImplementedException();
}
RemoveFromIndex(relativeSourcePath);
File.Move(Path.Combine(wd, relativeSourcePath), Path.Combine(wd, relativeDestinationPath));
AddToIndex(relativeDestinationPath);
UpdatePhysicalIndex();
}
/// <summary>
/// Removes a file from the working directory and promotes the removal to the staging area.
/// </summary>
/// <param name="path">The relative path within the working directory to the file.</param>
public void Remove(string path)
{
Ensure.ArgumentNotNullOrEmptyString(path, "path");
string relativePath = BuildRelativePathFrom(repo, path);
string wd = repo.Info.WorkingDirectory;
if (Directory.Exists(Path.Combine(wd, relativePath)))
{
throw new NotImplementedException();
}
RemoveFromIndex(relativePath);
File.Delete(Path.Combine(wd, relativePath));
UpdatePhysicalIndex();
}
private void AddToIndex(string relativePath)
{
relativePath = PosixPathHelper.ToPosix(relativePath);
int res = NativeMethods.git_index_add(handle, relativePath);
Ensure.Success(res);
}
private void RemoveFromIndex(string relativePath)
{
relativePath = PosixPathHelper.ToPosix(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 RestorePotentialPreviousVersionOfHeadIntoIndex(string relativePath,
bool doesExistInWorkingDirectory)
{
// TODO: Warning! Hack. Should be moved down to libgit2 (git reset HEAD filename)
TreeEntry entry = repo.Head[relativePath];
if (entry == null || entry.Type != GitObjectType.Blob)
{
return;
}
string filename = Path.Combine(repo.Info.WorkingDirectory, relativePath);
string randomFileName = null;
if (doesExistInWorkingDirectory)
{
randomFileName = Path.GetRandomFileName();
File.Move(filename, Path.Combine(repo.Info.WorkingDirectory, randomFileName));
}
File.WriteAllBytes(filename, ((Blob)(entry.Target)).Content);
AddToIndex(relativePath);
File.Delete(filename);
if (doesExistInWorkingDirectory)
{
File.Move(Path.Combine(repo.Info.WorkingDirectory, randomFileName), filename);
}
}
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 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, PosixPathHelper.ToPosix(relativePath));
if (res == (int)GitErrorCode.GIT_ENOTFOUND)
{
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 RepositoryStatus RetrieveStatus()
{
return new RepositoryStatus(repo);
}
}
}