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.

79 lines
2.4 KiB

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