-
-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathGitLoaderContext.cs
80 lines (66 loc) · 2.93 KB
/
GitLoaderContext.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
// This code originally copied from https://github.com/dotnet/sourcelink/tree/c092238370e0437eb95722f28c79273244dc7f1a/src/Microsoft.Build.Tasks.Git
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#if NETCOREAPP
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using RuntimeEnvironment = Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment;
namespace Nerdbank.GitVersioning
{
internal class GitLoaderContext : AssemblyLoadContext
{
public static readonly GitLoaderContext Instance = new GitLoaderContext();
protected override Assembly Load(AssemblyName assemblyName)
{
var path = Path.Combine(Path.GetDirectoryName(typeof(GitLoaderContext).Assembly.Location), assemblyName.Name + ".dll");
return File.Exists(path)
? LoadFromAssemblyPath(path)
: Default.LoadFromAssemblyName(assemblyName);
}
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
var modulePtr = IntPtr.Zero;
if (unmanagedDllName.StartsWith("git2-", StringComparison.Ordinal) ||
unmanagedDllName.StartsWith("libgit2-", StringComparison.Ordinal))
{
var directory = GetNativeLibraryDirectory();
var extension = GetNativeLibraryExtension();
if (!unmanagedDllName.EndsWith(extension, StringComparison.Ordinal))
{
unmanagedDllName += extension;
}
var nativeLibraryPath = Path.Combine(directory, unmanagedDllName);
if (!File.Exists(nativeLibraryPath))
{
nativeLibraryPath = Path.Combine(directory, "lib" + unmanagedDllName);
}
modulePtr = LoadUnmanagedDllFromPath(nativeLibraryPath);
}
return (modulePtr != IntPtr.Zero) ? modulePtr : base.LoadUnmanagedDll(unmanagedDllName);
}
internal static string GetNativeLibraryDirectory()
{
var dir = Path.GetDirectoryName(typeof(GitLoaderContext).Assembly.Location);
return Path.Combine(dir, "..", "runtimes", RuntimeIdMap.GetNativeLibraryDirectoryName(RuntimeEnvironment.GetRuntimeIdentifier()), "native");
}
private static string GetNativeLibraryExtension()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return ".dll";
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return ".dylib";
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return ".so";
}
throw new PlatformNotSupportedException();
}
}
}
#endif