-
Notifications
You must be signed in to change notification settings - Fork 892
/
Copy pathFilter.cs
403 lines (351 loc) · 15.9 KB
/
Filter.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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using LibGit2Sharp.Core;
namespace LibGit2Sharp
{
/// <summary>
/// A filter is a way to execute code against a file as it moves to and from the git
/// repository and into the working directory.
/// </summary>
public abstract class Filter : IEquatable<Filter>
{
private static readonly LambdaEqualityHelper<Filter> equalityHelper =
new LambdaEqualityHelper<Filter>(x => x.Name, x => x.Attributes);
// 64K is optimal buffer size per https://technet.microsoft.com/en-us/library/cc938632.aspx
private const int BufferSize = 64 * 1024;
/// <summary>
/// Initializes a new instance of the <see cref="Filter"/> class.
/// And allocates the filter natively.
/// <param name="name">The unique name with which this filtered is registered with</param>
/// <param name="attributes">A list of attributes which this filter applies to</param>
/// </summary>
protected Filter(string name, IEnumerable<FilterAttributeEntry> attributes)
{
Ensure.ArgumentNotNullOrEmptyString(name, "name");
Ensure.ArgumentNotNull(attributes, "attributes");
this.name = name;
this.attributes = attributes;
var attributesAsString = string.Join(",", this.attributes.Select(attr => attr.FilterDefinition));
gitFilter = new GitFilter
{
attributes = EncodingMarshaler.FromManaged(Encoding.UTF8, attributesAsString),
init = InitializeCallback,
stream = StreamCreateCallback,
};
}
/// <summary>
/// Finalizer called by the <see cref="GC"/>, deregisters and frees native memory associated with the registered filter in libgit2.
/// </summary>
~Filter()
{
GlobalSettings.DeregisterFilter(this);
#if LEAKS_IDENTIFYING
int activeStreamCount = activeStreams.Count;
if (activeStreamCount > 0)
{
Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} leaked {1} stream handles at finalization", GetType().Name, activeStreamCount));
}
#endif
}
private readonly string name;
private readonly IEnumerable<FilterAttributeEntry> attributes;
private readonly GitFilter gitFilter;
private readonly ConcurrentDictionary<IntPtr, StreamState> activeStreams = new ConcurrentDictionary<IntPtr, StreamState>();
/// <summary>
/// State bag used to keep necessary reference from being
/// garbage collected during filter processing.
/// </summary>
private class StreamState
{
public GitWriteStream thisStream;
public GitWriteStream nextStream;
public IntPtr thisPtr;
public IntPtr nextPtr;
public FilterSource filterSource;
public Stream output;
}
/// <summary>
/// The name that this filter was registered with
/// </summary>
public string Name
{
get { return name; }
}
/// <summary>
/// The filter filterForAttributes.
/// </summary>
public IEnumerable<FilterAttributeEntry> Attributes
{
get { return attributes; }
}
/// <summary>
/// The marshalled filter
/// </summary>
internal GitFilter GitFilter
{
get { return gitFilter; }
}
/// <summary>
/// Complete callback on filter
///
/// This optional callback will be invoked when the upstream filter is
/// closed. Gives the filter a chance to perform any final actions or
/// necissary clean up.
/// </summary>
/// <param name="path">The path of the file being filtered</param>
/// <param name="root">The path of the working directory for the owning repository</param>
/// <param name="output">Output to the downstream filter or output writer</param>
protected virtual void Complete(string path, string root, Stream output)
{ }
/// <summary>
/// Initialize callback on filter
///
/// Specified as `filter.initialize`, this is an optional callback invoked
/// before a filter is first used. It will be called once at most.
///
/// If non-NULL, the filter's `initialize` callback will be invoked right
/// before the first use of the filter, so you can defer expensive
/// initialization operations (in case the library is being used in a way
/// that doesn't need the filter.
/// </summary>
protected virtual void Initialize()
{ }
/// <summary>
/// Indicates that a filter is going to be applied for the given file for
/// the given mode.
/// </summary>
/// <param name="path">The path of the file being filtered</param>
/// <param name="root">The path of the working directory for the owning repository</param>
/// <param name="mode">The filter mode</param>
protected virtual void Create(string path, string root, FilterMode mode)
{ }
/// <summary>
/// Clean the input stream and write to the output stream.
/// </summary>
/// <param name="path">The path of the file being filtered</param>
/// <param name="root">The path of the working directory for the owning repository</param>
/// <param name="input">Input from the upstream filter or input reader</param>
/// <param name="output">Output to the downstream filter or output writer</param>
protected virtual void Clean(string path, string root, Stream input, Stream output)
{
input.CopyTo(output);
}
/// <summary>
/// Smudge the input stream and write to the output stream.
/// </summary>
/// <param name="path">The path of the file being filtered</param>
/// <param name="root">The path of the working directory for the owning repository</param>
/// <param name="input">Input from the upstream filter or input reader</param>
/// <param name="output">Output to the downstream filter or output writer</param>
protected virtual void Smudge(string path, string root, Stream input, Stream output)
{
input.CopyTo(output);
}
/// <summary>
/// Determines whether the specified <see cref="object"/> is equal to the current <see cref="Filter"/>.
/// </summary>
/// <param name="obj">The <see cref="object"/> to compare with the current <see cref="Filter"/>.</param>
/// <returns>True if the specified <see cref="object"/> is equal to the current <see cref="Filter"/>; otherwise, false.</returns>
public override bool Equals(object obj)
{
return Equals(obj as Filter);
}
/// <summary>
/// Determines whether the specified <see cref="Filter"/> is equal to the current <see cref="Filter"/>.
/// </summary>
/// <param name="other">The <see cref="Filter"/> to compare with the current <see cref="Filter"/>.</param>
/// <returns>True if the specified <see cref="Filter"/> is equal to the current <see cref="Filter"/>; otherwise, false.</returns>
public bool Equals(Filter other)
{
return equalityHelper.Equals(this, other);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return equalityHelper.GetHashCode(this);
}
/// <summary>
/// Tests if two <see cref="Filter"/> are equal.
/// </summary>
/// <param name="left">First <see cref="Filter"/> to compare.</param>
/// <param name="right">Second <see cref="Filter"/> to compare.</param>
/// <returns>True if the two objects are equal; false otherwise.</returns>
public static bool operator ==(Filter left, Filter right)
{
return Equals(left, right);
}
/// <summary>
/// Tests if two <see cref="Filter"/> are different.
/// </summary>
/// <param name="left">First <see cref="Filter"/> to compare.</param>
/// <param name="right">Second <see cref="Filter"/> to compare.</param>
/// <returns>True if the two objects are different; false otherwise.</returns>
public static bool operator !=(Filter left, Filter right)
{
return !Equals(left, right);
}
/// <summary>
/// Initialize callback on filter
///
/// Specified as `filter.initialize`, this is an optional callback invoked
/// before a filter is first used. It will be called once at most.
///
/// If non-NULL, the filter's `initialize` callback will be invoked right
/// before the first use of the filter, so you can defer expensive
/// initialization operations (in case libgit2 is being used in a way that doesn't need the filter).
/// </summary>
int InitializeCallback(IntPtr filterPointer)
{
int result = 0;
try
{
Initialize();
}
catch (Exception exception)
{
Log.Write(LogLevel.Error, "Filter.InitializeCallback exception");
Log.Write(LogLevel.Error, exception.ToString());
Proxy.git_error_set_str(GitErrorCategory.Filter, exception);
result = (int)GitErrorCode.Error;
}
return result;
}
int StreamCreateCallback(out IntPtr git_writestream_out, GitFilter self, IntPtr payload, IntPtr filterSourcePtr, IntPtr git_writestream_next)
{
int result = 0;
var state = new StreamState();
try
{
Ensure.ArgumentNotZeroIntPtr(filterSourcePtr, "filterSourcePtr");
Ensure.ArgumentNotZeroIntPtr(git_writestream_next, "git_writestream_next");
state.thisStream = new GitWriteStream();
state.thisStream.close = StreamCloseCallback;
state.thisStream.write = StreamWriteCallback;
state.thisStream.free = StreamFreeCallback;
state.thisPtr = Marshal.AllocHGlobal(Marshal.SizeOf(state.thisStream));
Marshal.StructureToPtr(state.thisStream, state.thisPtr, false);
state.nextPtr = git_writestream_next;
state.nextStream = Marshal.PtrToStructure<GitWriteStream>(state.nextPtr);
state.filterSource = FilterSource.FromNativePtr(filterSourcePtr);
state.output = new WriteStream(state.nextStream, state.nextPtr);
Create(state.filterSource.Path, state.filterSource.Root, state.filterSource.SourceMode);
if (!activeStreams.TryAdd(state.thisPtr, state))
{
// AFAICT this is a theoretical error that could only happen if we manage
// to free the stream pointer but fail to remove the dictionary entry.
throw new InvalidOperationException("Overlapping stream pointers");
}
}
catch (Exception exception)
{
// unexpected failures means memory clean up required
if (state.thisPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(state.thisPtr);
state.thisPtr = IntPtr.Zero;
}
Log.Write(LogLevel.Error, "Filter.StreamCreateCallback exception");
Log.Write(LogLevel.Error, exception.ToString());
Proxy.git_error_set_str(GitErrorCategory.Filter, exception);
result = (int)GitErrorCode.Error;
}
git_writestream_out = state.thisPtr;
return result;
}
int StreamCloseCallback(IntPtr stream)
{
int result = 0;
StreamState state;
try
{
Ensure.ArgumentNotZeroIntPtr(stream, "stream");
if (!activeStreams.TryGetValue(stream, out state))
{
throw new ArgumentException("Unknown stream pointer", nameof(stream));
}
Ensure.ArgumentIsExpectedIntPtr(stream, state.thisPtr, "stream");
using (BufferedStream outputBuffer = new BufferedStream(state.output, BufferSize))
{
Complete(state.filterSource.Path, state.filterSource.Root, outputBuffer);
}
result = state.nextStream.close(state.nextPtr);
}
catch (Exception exception)
{
Log.Write(LogLevel.Error, "Filter.StreamCloseCallback exception");
Log.Write(LogLevel.Error, exception.ToString());
Proxy.git_error_set_str(GitErrorCategory.Filter, exception);
result = (int)GitErrorCode.Error;
}
return result;
}
void StreamFreeCallback(IntPtr stream)
{
StreamState state;
try
{
Ensure.ArgumentNotZeroIntPtr(stream, "stream");
if (!activeStreams.TryRemove(stream, out state))
{
throw new ArgumentException("Double free or invalid stream pointer", nameof(stream));
}
Ensure.ArgumentIsExpectedIntPtr(stream, state.thisPtr, "stream");
Marshal.FreeHGlobal(state.thisPtr);
}
catch (Exception exception)
{
Log.Write(LogLevel.Error, "Filter.StreamFreeCallback exception");
Log.Write(LogLevel.Error, exception.ToString());
}
}
unsafe int StreamWriteCallback(IntPtr stream, IntPtr buffer, UIntPtr len)
{
int result = 0;
StreamState state;
try
{
Ensure.ArgumentNotZeroIntPtr(stream, "stream");
Ensure.ArgumentNotZeroIntPtr(buffer, "buffer");
if (!activeStreams.TryGetValue(stream, out state))
{
throw new ArgumentException("Invalid or already freed stream pointer", nameof(stream));
}
Ensure.ArgumentIsExpectedIntPtr(stream, state.thisPtr, "stream");
using (UnmanagedMemoryStream input = new UnmanagedMemoryStream((byte*)buffer.ToPointer(), (long)len))
using (BufferedStream outputBuffer = new BufferedStream(state.output, BufferSize))
{
switch (state.filterSource.SourceMode)
{
case FilterMode.Clean:
Clean(state.filterSource.Path, state.filterSource.Root, input, outputBuffer);
break;
case FilterMode.Smudge:
Smudge(state.filterSource.Path, state.filterSource.Root, input, outputBuffer);
break;
default:
Proxy.git_error_set_str(GitErrorCategory.Filter, "Unexpected filter mode.");
return (int)GitErrorCode.Ambiguous;
}
}
}
catch (Exception exception)
{
Log.Write(LogLevel.Error, "Filter.StreamWriteCallback exception");
Log.Write(LogLevel.Error, exception.ToString());
Proxy.git_error_set_str(GitErrorCategory.Filter, exception);
result = (int)GitErrorCode.Error;
}
return result;
}
}
}