/
GitPack.cs
299 lines (262 loc) · 10.9 KB
/
GitPack.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
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Text;
namespace Nerdbank.GitVersioning.ManagedGit
{
/// <summary>
/// Supports retrieving objects from a Git pack file.
/// </summary>
public class GitPack : IDisposable
{
/// <summary>
/// A delegate for methods which fetch objects from the Git object store.
/// </summary>
/// <param name="sha">
/// The Git object ID of the object to fetch.
/// </param>
/// <param name="objectType">
/// The object type of the object to fetch.
/// </param>
/// <returns>
/// A <see cref="Stream"/> which represents the requested object.
/// </returns>
public delegate Stream? GetObjectFromRepositoryDelegate(GitObjectId sha, string objectType);
private readonly Func<FileStream> packStream;
private readonly Lazy<FileStream> indexStream;
private readonly GitPackCache cache;
private MemoryMappedFile? packFile = null;
private MemoryMappedViewAccessor? accessor = null;
// Maps GitObjectIds to offets in the git pack.
private readonly Dictionary<GitObjectId, long> offsets = new Dictionary<GitObjectId, long>();
// A histogram which tracks the objects which have been retrieved from this GitPack. The key is the offset
// of the object. Used to get some insights in usage patterns.
#if DEBUG && !NETSTANDARD
private readonly Dictionary<long, int> histogram = new Dictionary<long, int>();
#endif
private Lazy<GitPackIndexReader> indexReader;
// Operating on git packfiles can potentially open a lot of streams which point to the pack file. For example,
// deltafied objects can have base objects which are in turn delafied. Opening and closing these streams has
// become a performance bottleneck. This is mitigated by pooling streams (i.e. reusing the streams after they
// are closed by the caller).
private readonly Queue<GitPackPooledStream> pooledStreams = new Queue<GitPackPooledStream>();
/// <summary>
/// Initializes a new instance of the <see cref="GitPack"/> class.
/// </summary>
/// <param name="getObjectFromRepositoryDelegate">
/// A delegate which fetches objects from the Git object store.
/// </param>
/// <param name="indexPath">
/// The full path to the index file.
/// </param>
/// <param name="packPath">
/// The full path to the pack file.
/// </param>
/// <param name="cache">
/// A <see cref="GitPackCache"/> which is used to cache <see cref="Stream"/> objects which operate
/// on the pack file.
/// </param>
public GitPack(GetObjectFromRepositoryDelegate getObjectFromRepositoryDelegate, string indexPath, string packPath, GitPackCache? cache = null)
: this(getObjectFromRepositoryDelegate, new Lazy<FileStream>(() => File.OpenRead(indexPath)), () => File.OpenRead(packPath), cache)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GitPack"/> class.
/// </summary>
/// <param name="getObjectFromRepositoryDelegate">
/// A delegate which fetches objects from the Git object store.
/// </param>
/// <param name="indexStream">
/// A function which creates a new <see cref="Stream"/> which provides read-only
/// access to the index file.
/// </param>
/// <param name="packStream">
/// A function which creates a new <see cref="Stream"/> which provides read-only
/// access to the pack file.
/// </param>
/// <param name="cache">
/// A <see cref="GitPackCache"/> which is used to cache <see cref="Stream"/> objects which operate
/// on the pack file.
/// </param>
public GitPack(GetObjectFromRepositoryDelegate getObjectFromRepositoryDelegate, Lazy<FileStream> indexStream, Func<FileStream> packStream, GitPackCache? cache = null)
{
this.GetObjectFromRepository = getObjectFromRepositoryDelegate ?? throw new ArgumentNullException(nameof(getObjectFromRepositoryDelegate));
this.indexReader = new Lazy<GitPackIndexReader>(this.OpenIndex);
this.packStream = packStream ?? throw new ArgumentException(nameof(packStream));
this.indexStream = indexStream ?? throw new ArgumentNullException(nameof(indexStream));
this.cache = cache ?? new GitPackMemoryCache();
if (IntPtr.Size > 4)
{
this.packFile = MemoryMappedFile.CreateFromFile(this.packStream(), mapName: null, 0, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen: false);
this.accessor = this.packFile.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read);
}
}
/// <summary>
/// Gets a delegate which fetches objects from the Git object store.
/// </summary>
public GetObjectFromRepositoryDelegate GetObjectFromRepository { get; private set; }
/// <summary>
/// Finds a git object using a partial object ID.
/// </summary>
/// <param name="objectId">
/// A partial object ID.
/// </param>
/// <param name="endsWithHalfByte"><inheritdoc cref="GitPackIndexReader.GetOffset(Span{byte}, bool)" path="/param[@name='endsWithHalfByte']"/></param>
/// <returns>
/// If found, a full object ID which matches the partial object ID.
/// Otherwise, <see langword="false"/>.
/// </returns>
public GitObjectId? Lookup(Span<byte> objectId, bool endsWithHalfByte = false)
{
(var _, var actualObjectId) = this.indexReader.Value.GetOffset(objectId, endsWithHalfByte);
return actualObjectId;
}
/// <summary>
/// Attempts to retrieve a Git object from this Git pack.
/// </summary>
/// <param name="objectId">
/// The Git object Id of the object to retrieve.
/// </param>
/// <param name="objectType">
/// The object type of the object to retrieve.
/// </param>
/// <param name="value">
/// If found, receives a <see cref="Stream"/> which represents the object.
/// </param>
/// <returns>
/// <see langword="true"/> if the object was found; otherwise, <see langword="false"/>.
/// </returns>
public bool TryGetObject(GitObjectId objectId, string objectType, out Stream? value)
{
var offset = this.GetOffset(objectId);
if (offset == null)
{
value = null;
return false;
}
else
{
value = this.GetObject(offset.Value, objectType);
return true;
}
}
/// <summary>
/// Gets a Git object at a specific offset.
/// </summary>
/// <param name="offset">
/// The offset of the Git object, relative to the pack file.
/// </param>
/// <param name="objectType">
/// The object type of the object to retrieve.
/// </param>
/// <returns>
/// A <see cref="Stream"/> which represents the object.
/// </returns>
public Stream GetObject(long offset, string objectType)
{
#if DEBUG && !NETSTANDARD
if (!this.histogram.TryAdd(offset, 1))
{
this.histogram[offset] += 1;
}
#endif
if (this.cache.TryOpen(offset, out Stream? stream))
{
return stream!;
}
GitPackObjectType packObjectType;
switch (objectType)
{
case "commit":
packObjectType = GitPackObjectType.OBJ_COMMIT;
break;
case "tree":
packObjectType = GitPackObjectType.OBJ_TREE;
break;
case "blob":
packObjectType = GitPackObjectType.OBJ_BLOB;
break;
default:
throw new GitException($"The object type '{objectType}' is not supported by the {nameof(GitPack)} class.");
}
var packStream = this.GetPackStream();
Stream objectStream;
try
{
objectStream = GitPackReader.GetObject(this, packStream, offset, objectType, packObjectType);
}
catch
{
packStream.Dispose();
throw;
}
return this.cache.Add(offset, objectStream);
}
/// <summary>
/// Writes cache statistics to a <see cref="StringBuilder"/>.
/// </summary>
/// <param name="builder">
/// A <see cref="StringBuilder"/> to which the cache statistics are written.
/// </param>
public void GetCacheStatistics(StringBuilder builder)
{
builder.AppendLine($"Git Pack:");
#if DEBUG && !NETSTANDARD
int histogramCount = 25;
builder.AppendLine($"Top {histogramCount} / {this.histogram.Count} items:");
foreach (var item in this.histogram.OrderByDescending(v => v.Value).Take(25))
{
builder.AppendLine($" {item.Key}: {item.Value}");
}
builder.AppendLine();
#endif
this.cache.GetCacheStatistics(builder);
}
/// <inheritdoc/>
public void Dispose()
{
if (this.indexReader.IsValueCreated)
{
this.indexReader.Value.Dispose();
}
this.accessor?.Dispose();
this.packFile?.Dispose();
this.cache.Dispose();
}
private long? GetOffset(GitObjectId objectId)
{
if (this.offsets.TryGetValue(objectId, out long cachedOffset))
{
return cachedOffset;
}
var indexReader = this.indexReader.Value;
var offset = indexReader.GetOffset(objectId);
if (offset != null)
{
this.offsets.Add(objectId, offset.Value);
}
return offset;
}
private Stream GetPackStream()
{
// On 64-bit processes, we can use Memory Mapped Streams (the address space
// will be large enough to map the entire packfile). On 32-bit processes,
// we directly access the underlying stream.
if (IntPtr.Size > 4)
{
return new MemoryMappedStream(this.accessor);
}
else
{
return this.packStream();
}
}
private GitPackIndexReader OpenIndex()
{
return new GitPackIndexMappedReader(this.indexStream.Value);
}
}
}