This repository was archived by the owner on Feb 3, 2023. It is now read-only.
forked from libgit2/libgit2sharp
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathFilter.cs
More file actions
350 lines (308 loc) · 13.3 KB
/
Copy pathFilter.cs
File metadata and controls
350 lines (308 loc) · 13.3 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
using System;
using System.Collections.Generic;
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);
private readonly string name;
private readonly IEnumerable<FilterAttributeEntry> attributes;
private readonly GitFilter gitFilter;
/// <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,
};
}
private GitWriteStream thisStream;
private GitWriteStream nextStream;
private IntPtr thisPtr;
private IntPtr nextPtr;
private FilterSource filterSource;
/// <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 change 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>
/// <returns></returns>
protected virtual int Complete(string path, string root, Stream output)
{
return 0;
}
/// <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 int Initialize()
{
return 0;
}
/// <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>
/// <returns>0 if successful and <see cref="GitErrorCode.PassThrough"/> to skip and pass through</returns>
protected virtual int Clean(string path, string root, Stream input, Stream output)
{
return (int)GitErrorCode.PassThrough;
}
/// <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>
/// <returns>0 if successful and <see cref="GitErrorCode.PassThrough"/> to skip and pass through</returns>
protected virtual int Smudge(string path, string root, Stream input, Stream output)
{
return (int)GitErrorCode.PassThrough;
}
/// <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)
{
return Initialize();
}
int StreamCreateCallback(out IntPtr git_writestream_out, GitFilter self, IntPtr payload, IntPtr filterSourcePtr, IntPtr git_writestream_next)
{
int result = 0;
try
{
Ensure.ArgumentNotZeroIntPtr(filterSourcePtr, "filterSourcePtr");
Ensure.ArgumentNotZeroIntPtr(git_writestream_next, "git_writestream_next");
thisStream = new GitWriteStream();
thisStream.close = StreamCloseCallback;
thisStream.write = StreamWriteCallback;
thisStream.free = StreamFreeCallback;
thisPtr = Marshal.AllocHGlobal(Marshal.SizeOf(thisStream));
Marshal.StructureToPtr(thisStream, thisPtr, false);
nextPtr = git_writestream_next;
nextStream = new GitWriteStream();
Marshal.PtrToStructure(nextPtr, nextStream);
filterSource = FilterSource.FromNativePtr(filterSourcePtr);
}
catch (Exception exception)
{
// unexpected failures means memory clean up required
if (thisPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(thisPtr);
thisPtr = IntPtr.Zero;
}
Proxy.giterr_set_str(GitErrorCategory.Filter, exception.Message);
result = (int)GitErrorCode.Error;
}
git_writestream_out = thisPtr;
return result;
}
int StreamCloseCallback(IntPtr stream)
{
int result = 0;
try
{
Ensure.ArgumentNotZeroIntPtr(stream, "stream");
Ensure.ArhumentIsExpectedIntPtr(stream, thisPtr, "stream");
result = nextStream.close(nextPtr);
}
catch (Exception exception)
{
Proxy.giterr_set_str(GitErrorCategory.Filter, exception.Message);
result = (int)GitErrorCode.Error;
}
return result;
}
void StreamFreeCallback(IntPtr stream)
{
try
{
Ensure.ArgumentNotZeroIntPtr(stream, "stream");
Ensure.ArhumentIsExpectedIntPtr(stream, thisPtr, "stream");
Marshal.FreeHGlobal(thisPtr);
}
catch { }
}
unsafe int StreamWriteCallback(IntPtr stream, IntPtr buffer, UIntPtr len)
{
int result = 0;
try
{
Ensure.ArgumentNotZeroIntPtr(stream, "stream");
Ensure.ArgumentNotZeroIntPtr(buffer, "buffer");
Ensure.ArhumentIsExpectedIntPtr(stream, thisPtr, "stream");
using (UnmanagedMemoryStream input = new UnmanagedMemoryStream((byte*)buffer.ToPointer(), (long)len))
using (MemoryStream output = new MemoryStream())
{
switch (filterSource.SourceMode)
{
case FilterMode.Clean:
result = Clean(filterSource.Path, filterSource.Root, input, output);
break;
case FilterMode.Smudge:
result = Smudge(filterSource.Path, filterSource.Root, input, output);
break;
default:
Proxy.giterr_set_str(GitErrorCategory.Filter, "Unexpected filter mode.");
return (int)GitErrorCode.Ambiguous;
}
if (result == (int)GitErrorCode.PassThrough)
{
input.CopyTo(output);
}
else if (result < 0)
{
return result;
}
output.Seek(0, SeekOrigin.Begin);
result = WriteToNextFilter(output);
}
}
catch (Exception exception)
{
Proxy.giterr_set_str(GitErrorCategory.Filter, exception.Message);
result = (int)GitErrorCode.Error;
}
return result;
}
private unsafe int WriteToNextFilter(MemoryStream output)
{
// 64K is optimal buffer size per https://technet.microsoft.com/en-us/library/cc938632.aspx
const int BufferSize = 64 * 1024;
int result = 0;
byte[] bytes = new byte[BufferSize];
IntPtr bytesPtr = Marshal.AllocHGlobal(BufferSize);
try
{
int read = 0;
while ((read = output.Read(bytes, 0, bytes.Length)) > 0)
{
Marshal.Copy(bytes, 0, bytesPtr, read);
if ((result = nextStream.write(nextPtr, bytesPtr, (UIntPtr)read)) < 0)
{
Proxy.giterr_set_str(GitErrorCategory.Filter, "Filter write to next stream failed");
break;
}
}
}
finally
{
Marshal.FreeHGlobal(bytesPtr);
}
return result;
}
}
}