2018-06-05 00:15:18 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Collections.ObjectModel;
|
|
|
|
|
using System.IO;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Reflection;
|
|
|
|
|
|
|
|
|
|
namespace Kerobot
|
|
|
|
|
{
|
|
|
|
|
static class ModuleLoader
|
|
|
|
|
{
|
|
|
|
|
private const string LogName = nameof(ModuleLoader);
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Given the instance configuration, loads all appropriate types from file specified in it.
|
|
|
|
|
/// </summary>
|
|
|
|
|
internal static ReadOnlyCollection<ModuleBase> Load(InstanceConfig conf, Kerobot k)
|
|
|
|
|
{
|
|
|
|
|
var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + Path.DirectorySeparatorChar;
|
|
|
|
|
var modules = new List<ModuleBase>();
|
|
|
|
|
|
2018-06-06 20:54:51 +00:00
|
|
|
|
foreach (var file in conf.EnabledAssemblies)
|
2018-06-05 00:15:18 +00:00
|
|
|
|
{
|
2018-06-06 20:54:51 +00:00
|
|
|
|
Assembly a = null;
|
|
|
|
|
try
|
2018-06-05 00:15:18 +00:00
|
|
|
|
{
|
2018-06-06 20:54:51 +00:00
|
|
|
|
a = Assembly.LoadFile(path + file);
|
2018-06-05 00:15:18 +00:00
|
|
|
|
}
|
2018-06-06 20:54:51 +00:00
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
Console.WriteLine("An error occurred when attempting to load a module assembly.");
|
|
|
|
|
Console.WriteLine($"File: {file}");
|
|
|
|
|
Console.WriteLine(ex.ToString());
|
|
|
|
|
Environment.Exit(2);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
IEnumerable<ModuleBase> amods = null;
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
amods = LoadModulesFromAssembly(a, k);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
Console.WriteLine("An error occurred when attempting to create a module instance.");
|
|
|
|
|
Console.WriteLine(ex.ToString());
|
|
|
|
|
Environment.Exit(2);
|
|
|
|
|
}
|
2019-06-21 22:05:58 +00:00
|
|
|
|
modules.AddRange(amods);
|
2018-06-05 00:15:18 +00:00
|
|
|
|
}
|
2018-06-06 20:54:51 +00:00
|
|
|
|
return modules.AsReadOnly();
|
2018-06-05 00:15:18 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static IEnumerable<ModuleBase> LoadModulesFromAssembly(Assembly asm, Kerobot k)
|
|
|
|
|
{
|
|
|
|
|
var eligibleTypes = from type in asm.GetTypes()
|
|
|
|
|
where !type.IsAssignableFrom(typeof(ModuleBase))
|
|
|
|
|
where type.GetCustomAttribute<KerobotModuleAttribute>() != null
|
|
|
|
|
select type;
|
2019-06-21 22:05:58 +00:00
|
|
|
|
k.InstanceLogAsync(false, LogName, $"Scanning {asm.GetName().Name}");
|
2018-06-05 00:15:18 +00:00
|
|
|
|
|
|
|
|
|
var newmods = new List<ModuleBase>();
|
|
|
|
|
foreach (var t in eligibleTypes)
|
|
|
|
|
{
|
|
|
|
|
var mod = Activator.CreateInstance(t, k);
|
|
|
|
|
k.InstanceLogAsync(false, LogName,
|
2019-06-21 22:05:58 +00:00
|
|
|
|
$"---> Loading module {t.FullName}");
|
2018-06-05 00:15:18 +00:00
|
|
|
|
newmods.Add((ModuleBase)mod);
|
|
|
|
|
}
|
|
|
|
|
return newmods;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|