EdmDependencyInstaller.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. using System;
  2. using System.IO;
  3. using UnityEditor;
  4. using UnityEditor.PackageManager;
  5. using UnityEditor.PackageManager.Requests;
  6. using UnityEngine;
  7. namespace GoogleMobileAds.Editor
  8. {
  9. /// <summary>
  10. /// Installs and updates Unity's External Dependency Manager
  11. /// (`com.unity.external-dependency-manager`) through the Unity Package Manager API when the
  12. /// Google Mobile Ads plugin is imported as a `.unitypackage`.
  13. ///
  14. /// On first import, and once after each plugin release that requires a different EDM version,
  15. /// the required EDM version (<see cref="EdmPackageVersion"/>) is installed. This replaces
  16. /// whatever version or source (such as a git URL) the project declared at the time. Between
  17. /// such releases the declared version is not changed, so a version the publisher sets is kept.
  18. ///
  19. /// Publishers opt out by removing the package from the Package Manager. Once a previously
  20. /// detected EDM package is found to be missing, the installer disables
  21. /// <see cref="GoogleMobileAdsSettings.EnableExternalDependencyManager"/>. An opted-out project
  22. /// is never modified again, including when the plugin is re-imported or upgraded. The setting
  23. /// is stored in `GoogleMobileAdsSettings.asset`, which the `.unitypackage` does not ship, so
  24. /// re-importing the plugin keeps it, and it is shared with the whole team and CI through
  25. /// version control.
  26. ///
  27. /// Publishers can reinstall EDM at any time by re-enabling the setting in the Google Mobile Ads
  28. /// settings.
  29. ///
  30. /// The plugin never deletes or modifies any other dependency manager already in the project,
  31. /// such as Google's legacy EDM or a publisher's custom tooling.
  32. /// </summary>
  33. internal static class EdmDependencyInstaller
  34. {
  35. internal const string EdmPackageName = "com.unity.external-dependency-manager";
  36. // Update this when a plugin release requires a newer EDM. Projects that have not opted out
  37. // are set to this version on re-import.
  38. internal const string EdmPackageVersion = "2.1.1";
  39. private const string ReinstallHint =
  40. "To reinstall it, enable \"Enable External Dependency Manager\" in " +
  41. "Assets > Google Mobile Ads > Settings.";
  42. private const string LogPrefix = "[Google Mobile Ads] ";
  43. // How many Editor ticks to wait for the settings asset to become loadable before giving up
  44. // for this Editor session.
  45. private const int MaxSettingsLoadAttempts = 100;
  46. // Pending Package Manager request, if an installation is in progress.
  47. private static AddRequest _addRequest;
  48. private static int _settingsLoadAttempts;
  49. [InitializeOnLoadMethod]
  50. private static void Initialize()
  51. {
  52. // Defer until the Editor has finished loading so the AssetDatabase is ready.
  53. _settingsLoadAttempts = 0;
  54. EditorApplication.delayCall += ApplyEdmInstallPolicy;
  55. }
  56. /// <summary>
  57. /// Called when the publisher re-enables EDM in the Google Mobile Ads settings. Enables
  58. /// the setting, then installs EDM at the
  59. /// version this plugin requires.
  60. /// </summary>
  61. internal static void ReinstallEdm()
  62. {
  63. var settings = GoogleMobileAdsSettings.LoadInstance();
  64. // Always save the setting: the settings editor has already enabled it in memory but
  65. // has not saved it.
  66. settings.EnableExternalDependencyManager = true;
  67. // Treat the reinstall like a first-time import, so that a failed or interrupted
  68. // installation is retried instead of being mistaken for a publisher removal.
  69. // `MonitorAddRequest`, or the next `ApplyEdmInstallPolicy` run once EDM is declared,
  70. // sets this again.
  71. settings.EdmPackageDetected = false;
  72. SaveSettings(settings);
  73. AddEdmPackage();
  74. }
  75. /// <summary>
  76. /// Runs on Editor load. Installs EDM at <see cref="EdmPackageVersion"/>, opts out if the
  77. /// publisher removed it, or does nothing, as decided by <see cref="EdmInstallPolicy"/>.
  78. /// </summary>
  79. private static void ApplyEdmInstallPolicy()
  80. {
  81. if (_addRequest != null || IsInstalledViaUpm())
  82. {
  83. return;
  84. }
  85. GoogleMobileAdsSettings settings;
  86. if (!TryLoadSettings(out settings))
  87. {
  88. return;
  89. }
  90. bool isDeclared;
  91. if (!TryReadIsEdmDeclared(out isDeclared))
  92. {
  93. return;
  94. }
  95. // EDM is present: remember it so a later removal can be detected.
  96. if (isDeclared && !settings.EdmPackageDetected)
  97. {
  98. settings.EdmPackageDetected = true;
  99. SaveSettings(settings);
  100. }
  101. var state = new EdmInstallPolicy.ProjectState
  102. {
  103. IsDeclared = isDeclared,
  104. EnableEdm = settings.EnableExternalDependencyManager,
  105. PackageDetected = settings.EdmPackageDetected,
  106. EdmVersionAdded = settings.AddedEdmVersion == EdmPackageVersion,
  107. };
  108. switch (EdmInstallPolicy.Decide(state))
  109. {
  110. case EdmInstallPolicy.Action.Install:
  111. AddEdmPackage();
  112. break;
  113. case EdmInstallPolicy.Action.OptOut:
  114. settings.EnableExternalDependencyManager = false;
  115. SaveSettings(settings);
  116. Debug.Log(LogPrefix + $"{EdmPackageName} was removed from the project, so " +
  117. "Unity External Dependency Manager has been disabled. " + ReinstallHint);
  118. break;
  119. case EdmInstallPolicy.Action.None:
  120. default:
  121. break;
  122. }
  123. }
  124. /// <summary>
  125. /// Loads the settings asset without risking overwriting it. While Unity is compiling or
  126. /// importing (for example right after the plugin is re-imported), or if the asset exists on
  127. /// disk but cannot be loaded yet, <see cref="ApplyEdmInstallPolicy"/> is retried on a later
  128. /// Editor tick instead of letting <see cref="GoogleMobileAdsSettings.LoadInstance"/>
  129. /// create a new, empty asset that would lose the publisher's opt-out.
  130. /// </summary>
  131. private static bool TryLoadSettings(out GoogleMobileAdsSettings settings)
  132. {
  133. settings = null;
  134. if (EditorApplication.isCompiling || EditorApplication.isUpdating)
  135. {
  136. if (++_settingsLoadAttempts < MaxSettingsLoadAttempts)
  137. {
  138. EditorApplication.delayCall += ApplyEdmInstallPolicy;
  139. }
  140. return false;
  141. }
  142. if (File.Exists(GoogleMobileAdsSettings.AssetPath))
  143. {
  144. settings = AssetDatabase.LoadAssetAtPath<GoogleMobileAdsSettings>(
  145. GoogleMobileAdsSettings.AssetPath);
  146. if (settings == null)
  147. {
  148. if (++_settingsLoadAttempts < MaxSettingsLoadAttempts)
  149. {
  150. EditorApplication.delayCall += ApplyEdmInstallPolicy;
  151. }
  152. return false;
  153. }
  154. return true;
  155. }
  156. settings = GoogleMobileAdsSettings.LoadInstance();
  157. return settings != null;
  158. }
  159. /// <summary>
  160. /// Returns true if the plugin was imported through the Unity Package Manager. In that case
  161. /// EDM is already declared as a dependency in the plugin's `package.json`.
  162. /// </summary>
  163. internal static bool IsInstalledViaUpm()
  164. {
  165. var pathUtils = ScriptableObject.CreateInstance<EditorPathUtils>();
  166. try
  167. {
  168. return pathUtils.IsPackageRootPath();
  169. }
  170. finally
  171. {
  172. UnityEngine.Object.DestroyImmediate(pathUtils);
  173. }
  174. }
  175. /// <summary>
  176. /// Adds EDM at <see cref="EdmPackageVersion"/>. If EDM is already declared, the Package
  177. /// Manager updates the declared version.
  178. /// </summary>
  179. private static void AddEdmPackage()
  180. {
  181. if (_addRequest != null)
  182. {
  183. return;
  184. }
  185. string packageSpec = $"{EdmPackageName}@{EdmPackageVersion}";
  186. Debug.Log(LogPrefix + $"Installing {packageSpec} using the Unity Package Manager.");
  187. _addRequest = Client.Add(packageSpec);
  188. EditorApplication.update += MonitorAddRequest;
  189. }
  190. private static void MonitorAddRequest()
  191. {
  192. if (_addRequest == null)
  193. {
  194. EditorApplication.update -= MonitorAddRequest;
  195. return;
  196. }
  197. if (!_addRequest.IsCompleted)
  198. {
  199. return;
  200. }
  201. EditorApplication.update -= MonitorAddRequest;
  202. if (_addRequest.Status == StatusCode.Success)
  203. {
  204. // Only record the installation once it has succeeded, so that a failed or
  205. // interrupted install is retried rather than mistaken for a publisher removal.
  206. var settings = GoogleMobileAdsSettings.LoadInstance();
  207. settings.EdmPackageDetected = true;
  208. settings.EnableExternalDependencyManager = true;
  209. settings.AddedEdmVersion = EdmPackageVersion;
  210. SaveSettings(settings);
  211. Debug.Log(LogPrefix + $"Installed {EdmPackageName} " +
  212. $"{_addRequest.Result?.version ?? EdmPackageVersion}.");
  213. }
  214. else
  215. {
  216. string error =
  217. _addRequest.Error != null ? _addRequest.Error.message : "unknown error";
  218. Debug.LogError(LogPrefix + $"Failed to install {EdmPackageName}: {error}. " +
  219. "Install it from the Package Manager.");
  220. }
  221. _addRequest = null;
  222. }
  223. /// <summary>
  224. /// Reads `Packages/manifest.json` and outputs whether EDM is declared.
  225. /// Returns false if the manifest could not be read.
  226. /// </summary>
  227. private static bool TryReadIsEdmDeclared(out bool isDeclared)
  228. {
  229. isDeclared = false;
  230. string manifestPath = Path.GetFullPath(
  231. Path.Combine(Application.dataPath, "..", "Packages", "manifest.json"));
  232. if (!File.Exists(manifestPath))
  233. {
  234. return false;
  235. }
  236. try
  237. {
  238. isDeclared = EdmInstallPolicy.IsDeclared(File.ReadAllText(manifestPath),
  239. EdmPackageName);
  240. return true;
  241. }
  242. catch (Exception ex)
  243. {
  244. Debug.LogWarning(LogPrefix + $"Unable to read {manifestPath}: {ex.Message}");
  245. return false;
  246. }
  247. }
  248. private static void SaveSettings(GoogleMobileAdsSettings settings)
  249. {
  250. EditorUtility.SetDirty(settings);
  251. AssetDatabase.SaveAssets();
  252. }
  253. }
  254. }