1
|
// Kerbal Development tools.
|
2
|
// Author: [email protected]
|
3
|
// This software is distributed under Public domain license.
|
4
|
using System;
|
5
|
using System.Collections.Generic;
|
6
|
using System.Reflection;
|
7
|
using UnityEngine;
|
8
|
|
9
|
[KSPAddon(KSPAddon.Startup.Instantly, true)]
|
10
|
public class AddonVersionDependancyBinder : MonoBehaviour {
|
11
|
/// <summary>Local cache of redirects done so far. Used to speedup assembly resolutions since what
|
12
|
/// has failed once will likely keep failing thru the game.</summary>
|
13
|
static readonly Dictionary<string, Assembly> bindingRedirect = new Dictionary<string, Assembly>();
|
14
|
|
15
|
void Awake() {
|
16
|
// Ensure there is only one listener added.
|
17
|
AppDomain.CurrentDomain.AssemblyResolve -= MyResolveEventHandler;
|
18
|
AppDomain.CurrentDomain.AssemblyResolve += MyResolveEventHandler;
|
19
|
}
|
20
|
|
21
|
/// <summary>Triggers when framework fails to resolve an assembly.</summary>
|
22
|
/// <remarks>Since KSP versioning engine verifies addons dependencies this failure may only happen
|
23
|
/// if a dependency assembly has been upgarded to a higher version. This code tries to load the
|
24
|
/// assembly without version specified, and just checks if the found assembly has greater version.
|
25
|
/// <param name="sender"></param>
|
26
|
/// <param name="args"></param>
|
27
|
/// <returns></returns>
|
28
|
static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
|
29
|
// Return cached version if exists.
|
30
|
Assembly result = null;
|
31
|
if (bindingRedirect.TryGetValue(args.Name, out result)) {
|
32
|
return result;
|
33
|
}
|
34
|
// Try finding asssembly by name ignoring the version info.
|
35
|
var targetAssemblyName = new AssemblyName(args.Name);
|
36
|
var targetAssemblyVersion = targetAssemblyName.Version;
|
37
|
targetAssemblyName.Version = null;
|
38
|
try {
|
39
|
result = Assembly.Load(targetAssemblyName);
|
40
|
if (result.GetName().Version >= targetAssemblyVersion) {
|
41
|
Debug.LogFormat("ADDON BINDER: Create binding redirect: {0} => {1}",
|
42
|
args.Name, result.FullName);
|
43
|
} else {
|
44
|
Debug.LogWarningFormat(
|
45
|
"ADDON BINDER: Ingoring binding redirect due to incompatible versions: {0} => {1}",
|
46
|
args.Name, result.FullName);
|
47
|
result = null;
|
48
|
}
|
49
|
} catch (Exception) {
|
50
|
Debug.LogErrorFormat("ADDON BINDER: Cannot resolve assembly: {0}", targetAssemblyName);
|
51
|
}
|
52
|
bindingRedirect.Add(args.Name, result);
|
53
|
return result;
|
54
|
}
|
55
|
}
|