-
Notifications
You must be signed in to change notification settings - Fork 892
/
Copy pathGlobalSettings.cs
442 lines (391 loc) · 17.6 KB
/
GlobalSettings.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using LibGit2Sharp.Core;
namespace LibGit2Sharp
{
/// <summary>
/// Global settings for libgit2 and LibGit2Sharp.
/// </summary>
public static class GlobalSettings
{
private static readonly Lazy<Version> version = new Lazy<Version>(Version.Build);
private static readonly Dictionary<Filter, FilterRegistration> registeredFilters;
private static readonly bool nativeLibraryPathAllowed;
private static LogConfiguration logConfiguration = LogConfiguration.None;
private static string nativeLibraryPath;
private static bool nativeLibraryPathLocked;
private static readonly string nativeLibraryDefaultPath = null;
static GlobalSettings()
{
bool netFX = Platform.IsRunningOnNetFramework();
bool netCore = Platform.IsRunningOnNetCore();
nativeLibraryPathAllowed = netFX || netCore;
#if NETFRAMEWORK
if (netFX)
{
// For .NET Framework apps the dependencies are deployed to lib/win32/{architecture} directory
nativeLibraryDefaultPath = Path.Combine(GetExecutingAssemblyDirectory(), "lib", "win32", Platform.ProcessorArchitecture);
}
#endif
registeredFilters = new Dictionary<Filter, FilterRegistration>();
}
#if NETFRAMEWORK
private static string GetExecutingAssemblyDirectory()
{
// Assembly.CodeBase is not actually a correctly formatted
// URI. It's merely prefixed with `file:///` and has its
// backslashes flipped. This is superior to EscapedCodeBase,
// which does not correctly escape things, and ambiguates a
// space (%20) with a literal `%20` in the path. Sigh.
var managedPath = Assembly.GetExecutingAssembly().CodeBase;
if (managedPath == null)
{
managedPath = Assembly.GetExecutingAssembly().Location;
}
else if (managedPath.StartsWith("file:///"))
{
managedPath = managedPath.Substring(8).Replace('/', '\\');
}
else if (managedPath.StartsWith("file://"))
{
managedPath = @"\\" + managedPath.Substring(7).Replace('/', '\\');
}
managedPath = Path.GetDirectoryName(managedPath);
return managedPath;
}
#endif
/// <summary>
/// Returns information related to the current LibGit2Sharp
/// library.
/// </summary>
public static Version Version => version.Value;
/// <summary>
/// Registers a new <see cref="SmartSubtransport"/> as a custom
/// smart-protocol transport with libgit2. Any Git remote with
/// the scheme registered will delegate to the given transport
/// for all communication with the server. This is not commonly
/// used: some callers may want to re-use an existing connection to
/// perform fetch / push operations to a remote.
///
/// Note that this configuration is global to an entire process
/// and does not honor application domains.
/// </summary>
/// <typeparam name="T">The type of SmartSubtransport to register</typeparam>
/// <param name="scheme">The scheme (eg "http" or "gopher") to register</param>
public static SmartSubtransportRegistration<T> RegisterSmartSubtransport<T>(string scheme)
where T : SmartSubtransport, new()
{
Ensure.ArgumentNotNull(scheme, "scheme");
var registration = new SmartSubtransportRegistration<T>(scheme);
try
{
Proxy.git_transport_register(registration.Scheme,
registration.FunctionPointer,
registration.RegistrationPointer);
}
catch (Exception)
{
registration.Free();
throw;
}
return registration;
}
/// <summary>
/// Unregisters a previously registered <see cref="SmartSubtransport"/>
/// as a custom smart-protocol transport with libgit2.
/// </summary>
/// <typeparam name="T">The type of SmartSubtransport to register</typeparam>
/// <param name="registration">The previous registration</param>
public static void UnregisterSmartSubtransport<T>(SmartSubtransportRegistration<T> registration)
where T : SmartSubtransport, new()
{
Ensure.ArgumentNotNull(registration, "registration");
Proxy.git_transport_unregister(registration.Scheme);
registration.Free();
}
/// <summary>
/// Registers a new <see cref="LogConfiguration"/> to receive
/// information logging information from libgit2 and LibGit2Sharp.
///
/// Note that this configuration is global to an entire process
/// and does not honor application domains.
/// </summary>
public static LogConfiguration LogConfiguration
{
set
{
Ensure.ArgumentNotNull(value, "value");
logConfiguration = value;
if (logConfiguration.Level == LogLevel.None)
{
Proxy.git_trace_set(0, null);
}
else
{
Proxy.git_trace_set(value.Level, value.GitTraceCallback);
Log.Write(LogLevel.Info, "Logging enabled at level {0}", value.Level);
}
}
get
{
return logConfiguration;
}
}
/// <summary>
/// Sets a path for loading native binaries on .NET Framework or .NET Core.
/// When specified, native library will first be searched under the given path.
///
/// If the library is not found it will be searched in standard search paths:
/// <see cref="DllImportSearchPath.AssemblyDirectory"/>,
/// <see cref="DllImportSearchPath.ApplicationDirectory"/> and
/// <see cref="DllImportSearchPath.SafeDirectories"/>.
/// <para>
/// This must be set before any other calls to the library,
/// and is not available on other platforms than .NET Framework and .NET Core.
/// </para>
/// </summary>
public static string NativeLibraryPath
{
get
{
if (!nativeLibraryPathAllowed)
{
throw new LibGit2SharpException("Querying the native hint path is only supported on .NET Framework and .NET Core platforms");
}
return nativeLibraryPath ?? nativeLibraryDefaultPath;
}
set
{
if (!nativeLibraryPathAllowed)
{
throw new LibGit2SharpException("Setting the native hint path is only supported on .NET Framework and .NET Core platforms");
}
if (nativeLibraryPathLocked)
{
throw new LibGit2SharpException("You cannot set the native library path after it has been loaded");
}
try
{
nativeLibraryPath = Path.GetFullPath(value);
}
catch (Exception e)
{
throw new LibGit2SharpException(e.Message);
}
}
}
internal static string GetAndLockNativeLibraryPath()
{
nativeLibraryPathLocked = true;
return nativeLibraryPath ?? nativeLibraryDefaultPath;
}
/// <summary>
/// Takes a snapshot of the currently registered filters.
/// </summary>
/// <returns>An array of <see cref="FilterRegistration"/>.</returns>
public static IEnumerable<FilterRegistration> GetRegisteredFilters()
{
lock (registeredFilters)
{
FilterRegistration[] array = new FilterRegistration[registeredFilters.Count];
registeredFilters.Values.CopyTo(array, 0);
return array;
}
}
/// <summary>
/// Register a filter globally with a default priority of 200 allowing the custom filter
/// to imitate a core Git filter driver. It will be run last on checkout and first on checkin.
/// </summary>
public static FilterRegistration RegisterFilter(Filter filter)
{
return RegisterFilter(filter, 200);
}
/// <summary>
/// Registers a <see cref="Filter"/> to be invoked when <see cref="Filter.Name"/> matches .gitattributes 'filter=name'
/// </summary>
/// <param name="filter">The filter to be invoked at run time.</param>
/// <param name="priority">The priroty of the filter to invoked.
/// A value of 0 (<see cref="FilterRegistration.FilterPriorityMin"/>) will be run first on checkout and last on checkin.
/// A value of 200 (<see cref="FilterRegistration.FilterPriorityMax"/>) will be run last on checkout and first on checkin.
/// </param>
/// <returns>A <see cref="FilterRegistration"/> object used to manage the lifetime of the registration.</returns>
public static FilterRegistration RegisterFilter(Filter filter, int priority)
{
Ensure.ArgumentNotNull(filter, "filter");
if (priority < FilterRegistration.FilterPriorityMin || priority > FilterRegistration.FilterPriorityMax)
{
throw new ArgumentOutOfRangeException(nameof(priority),
priority,
string.Format(System.Globalization.CultureInfo.InvariantCulture,
"Filter priorities must be within the inclusive range of [{0}, {1}].",
FilterRegistration.FilterPriorityMin,
FilterRegistration.FilterPriorityMax));
}
FilterRegistration registration = null;
lock (registeredFilters)
{
// if the filter has already been registered
if (registeredFilters.ContainsKey(filter))
{
throw new EntryExistsException("The filter has already been registered.", GitErrorCode.Exists, GitErrorCategory.Filter);
}
// allocate the registration object
registration = new FilterRegistration(filter, priority);
// add the filter and registration object to the global tracking list
registeredFilters.Add(filter, registration);
}
return registration;
}
/// <summary>
/// Unregisters the associated filter.
/// </summary>
/// <param name="registration">Registration object with an associated filter.</param>
public static void DeregisterFilter(FilterRegistration registration)
{
Ensure.ArgumentNotNull(registration, "registration");
lock (registeredFilters)
{
var filter = registration.Filter;
// do nothing if the filter isn't registered
if (registeredFilters.ContainsKey(filter))
{
// remove the register from the global tracking list
registeredFilters.Remove(filter);
// clean up native allocations
registration.Free();
}
}
}
internal static void DeregisterFilter(Filter filter)
{
System.Diagnostics.Debug.Assert(filter != null);
// do nothing if the filter isn't registered
if (registeredFilters.ContainsKey(filter))
{
var registration = registeredFilters[filter];
// unregister the filter
DeregisterFilter(registration);
}
}
/// <summary>
/// Get the paths under which libgit2 searches for the configuration file of a given level.
/// </summary>
/// <param name="level">The level (global/system/XDG) of the config.</param>
/// <returns>The paths that are searched</returns>
public static IEnumerable<string> GetConfigSearchPaths(ConfigurationLevel level)
{
return Proxy.git_libgit2_opts_get_search_path(level).Split(Path.PathSeparator);
}
/// <summary>
/// Set the paths under which libgit2 searches for the configuration file of a given level.
///
/// <seealso cref="RepositoryOptions"/>.
/// </summary>
/// <param name="level">The level (global/system/XDG) of the config.</param>
/// <param name="paths">
/// The new search paths to set.
/// Pass null to reset to the default.
/// The special string "$PATH" will be substituted with the current search path.
/// </param>
public static void SetConfigSearchPaths(ConfigurationLevel level, params string[] paths)
{
var pathString = (paths == null) ? null : string.Join(Path.PathSeparator.ToString(), paths);
Proxy.git_libgit2_opts_set_search_path(level, pathString);
}
/// <summary>
/// Enable or disable strict hash verification.
/// </summary>
/// <param name="enabled">true to enable strict hash verification; false otherwise.</param>
public static void SetStrictHashVerification(bool enabled)
{
Proxy.git_libgit2_opts_enable_strict_hash_verification(enabled);
}
/// <summary>
/// Enable or disable the libgit2 cache
/// </summary>
/// <param name="enabled">true to enable the cache, false otherwise</param>
public static void SetEnableCaching(bool enabled)
{
Proxy.git_libgit2_opts_set_enable_caching(enabled);
}
/// <summary>
/// Enable or disable the ofs_delta capability
/// </summary>
/// <param name="enabled">true to enable the ofs_delta capability, false otherwise</param>
public static void SetEnableOfsDelta(bool enabled)
{
Proxy.git_libgit2_opts_set_enable_ofsdelta(enabled);
}
/// <summary>
/// Enable or disable the libgit2 strict_object_creation capability
/// </summary>
/// <param name="enabled">true to enable the strict_object_creation capability, false otherwise</param>
public static void SetEnableStrictObjectCreation(bool enabled)
{
Proxy.git_libgit2_opts_set_enable_strictobjectcreation(enabled);
}
/// <summary>
/// Sets the user-agent string to be used by the HTTP(S) transport.
/// Note that "git/2.0" will be prepended for compatibility.
/// </summary>
/// <param name="userAgent">The user-agent string to use</param>
public static void SetUserAgent(string userAgent)
{
Proxy.git_libgit2_opts_set_user_agent(userAgent);
}
/// <summary>
/// Set that the given git extensions are supported by the caller.
/// </summary>
/// <remarks>
/// Extensions supported by libgit2 may be negated by prefixing them with a `!`. For example: setting extensions to { "!noop", "newext" } indicates that the caller does not want
/// to support repositories with the `noop` extension but does want to support repositories with the `newext` extension.
/// </remarks>
/// <param name="extensions">Supported extensions</param>
public static void SetExtensions(params string[] extensions)
{
Proxy.git_libgit2_opts_set_extensions(extensions);
}
/// <summary>
/// Returns the list of git extensions that are supported.
/// </summary>
/// <remarks>
/// This is the list of built-in extensions supported by libgit2 and custom extensions that have been added with `SetExtensions`. Extensions that have been negated will not be returned.
/// </remarks>
public static string[] GetExtensions()
{
return Proxy.git_libgit2_opts_get_extensions();
}
/// <summary>
/// Gets the user-agent string used by libgit2.
/// <returns>
/// The user-agent string.
/// </returns>
/// </summary>
public static string GetUserAgent()
{
return Proxy.git_libgit2_opts_get_user_agent();
}
/// <summary>
/// Gets the owner validation setting for repository directories.
/// </summary>
/// <returns></returns>
public static bool GetOwnerValidation()
{
return Proxy.git_libgit2_opts_get_owner_validation();
}
/// <summary>
/// Sets whether repository directories should be owned by the current user. The default is to validate ownership.
/// </summary>
/// <remarks>
/// Disabling owner validation can lead to security vulnerabilities (see CVE-2022-24765).
/// </remarks>
/// <param name="enabled">true to enable owner validation; otherwise, false.</param>
public static void SetOwnerValidation(bool enabled)
{
Proxy.git_libgit2_opts_set_owner_validation(enabled);
}
}
}