PackageManagerProvider.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System.IO;
  2. using System.Linq;
  3. using UnityEngine;
  4. using Newtonsoft.Json;
  5. using System.Collections.Generic;
  6. namespace LLM.Editor.Analysis
  7. {
  8. /// <summary>
  9. /// Provides a list of all packages currently installed in the project
  10. /// by reading the package manifest and lock files.
  11. /// </summary>
  12. public class PackageManagerProvider : IContextProvider
  13. {
  14. private class ManifestFile
  15. {
  16. public Dictionary<string, string> dependencies;
  17. }
  18. private class LockFile
  19. {
  20. public Dictionary<string, PackageLock> dependencies;
  21. }
  22. private class PackageLock
  23. {
  24. public string version;
  25. public int depth;
  26. public string source;
  27. }
  28. public class PackageInfo
  29. {
  30. public string name;
  31. public string version;
  32. public string source;
  33. }
  34. public object GetContext(Object target, string qualifier)
  35. {
  36. var lockJsonPath = Path.Combine(Application.dataPath, "..", "Packages", "packages-lock.json");
  37. var manifestJsonPath = Path.Combine(Application.dataPath, "..", "Packages", "manifest.json");
  38. if (File.Exists(lockJsonPath))
  39. {
  40. try
  41. {
  42. var json = File.ReadAllText(lockJsonPath);
  43. var lockFile = JsonConvert.DeserializeObject<LockFile>(json);
  44. var packages = lockFile.dependencies.Select(kvp => new PackageInfo
  45. {
  46. name = kvp.Key,
  47. version = kvp.Value.version,
  48. source = kvp.Value.source
  49. }).ToList();
  50. return packages;
  51. }
  52. catch (System.Exception e)
  53. {
  54. return $"Error parsing packages-lock.json: {e.Message}";
  55. }
  56. }
  57. if (File.Exists(manifestJsonPath))
  58. {
  59. try
  60. {
  61. var json = File.ReadAllText(manifestJsonPath);
  62. var manifestFile = JsonConvert.DeserializeObject<ManifestFile>(json);
  63. var packages = manifestFile.dependencies.Select(kvp => new PackageInfo
  64. {
  65. name = kvp.Key,
  66. version = kvp.Value,
  67. source = "manifest"
  68. }).ToList();
  69. return packages;
  70. }
  71. catch (System.Exception e)
  72. {
  73. return $"Error parsing manifest.json: {e.Message}";
  74. }
  75. }
  76. return "Error: Could not find 'packages-lock.json' or 'manifest.json' in the Packages folder.";
  77. }
  78. }
  79. }