You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.4 KiB

  1. #nullable enable
  2. using Newtonsoft.Json;
  3. using Newtonsoft.Json.Linq;
  4. using System;
  5. using System.IO;
  6. namespace IPA.Loader.Features
  7. {
  8. internal class ConfigProviderFeature : Feature
  9. {
  10. private class DataModel
  11. {
  12. [JsonProperty("type", Required = Required.Always)]
  13. public string TypeName = "";
  14. }
  15. protected override bool Initialize(PluginMetadata meta, JObject featureData)
  16. {
  17. DataModel data;
  18. try
  19. {
  20. data = featureData.ToObject<DataModel>() ?? throw new InvalidOperationException("Feature data is null");
  21. }
  22. catch (Exception e)
  23. {
  24. InvalidMessage = $"Invalid data: {e}";
  25. return false;
  26. }
  27. Type getType;
  28. try
  29. {
  30. getType = meta.Assembly.GetType(data.TypeName);
  31. }
  32. catch (ArgumentException)
  33. {
  34. InvalidMessage = $"Invalid type name {data.TypeName}";
  35. return false;
  36. }
  37. catch (Exception e) when (e is FileNotFoundException or FileLoadException or BadImageFormatException)
  38. {
  39. string filename;
  40. switch (e)
  41. {
  42. case FileNotFoundException fn:
  43. filename = fn.FileName;
  44. goto hasFilename;
  45. case FileLoadException fl:
  46. filename = fl.FileName;
  47. goto hasFilename;
  48. case BadImageFormatException bi:
  49. filename = bi.FileName;
  50. hasFilename:
  51. InvalidMessage = $"Could not find {filename} while loading type";
  52. break;
  53. default:
  54. InvalidMessage = $"Error while loading type: {e}";
  55. break;
  56. }
  57. return false;
  58. }
  59. try
  60. {
  61. Config.Config.Register(getType);
  62. return true;
  63. }
  64. catch (Exception e)
  65. {
  66. InvalidMessage = $"Error while registering config provider: {e}";
  67. return false;
  68. }
  69. }
  70. }
  71. }