From decbb9b7c6c83fbbf608567ad2acbe322347facc Mon Sep 17 00:00:00 2001 From: argzdev Date: Thu, 1 Aug 2024 22:19:31 +0800 Subject: [PATCH 1/2] use AGP version as condition check --- .../src/GradleTemplateResolver.cs | 268 ++++++++++++------ 1 file changed, 179 insertions(+), 89 deletions(-) diff --git a/source/AndroidResolver/src/GradleTemplateResolver.cs b/source/AndroidResolver/src/GradleTemplateResolver.cs index 59875c03..00e820de 100644 --- a/source/AndroidResolver/src/GradleTemplateResolver.cs +++ b/source/AndroidResolver/src/GradleTemplateResolver.cs @@ -14,7 +14,8 @@ // limitations under the License. // -namespace GooglePlayServices { +namespace GooglePlayServices +{ using System; using System.Collections.Generic; using System.IO; @@ -28,7 +29,8 @@ namespace GooglePlayServices { /// /// Resolver which simply injects dependencies into a gradle template file. /// - internal class GradleTemplateResolver { + internal class GradleTemplateResolver + { /// /// Filename of the Custom Gradle Properties Template file. @@ -53,9 +55,12 @@ internal class GradleTemplateResolver { public static string GradleSettingsTemplatePath = Path.Combine(SettingsDialog.AndroidPluginsDir, GradleSettingsTemplatePathFilename); - public static string UnityGradleTemplatesDir { - get { - if (unityGradleTemplatesDir == null) { + public static string UnityGradleTemplatesDir + { + get + { + if (unityGradleTemplatesDir == null) + { var engineDir = PlayServicesResolver.AndroidPlaybackEngineDirectory; if (String.IsNullOrEmpty(engineDir)) return null; var gradleTemplateDir = @@ -67,8 +72,10 @@ public static string UnityGradleTemplatesDir { } private static string unityGradleTemplatesDir = null; - public static string UnityGradleSettingsTemplatePath { - get { + public static string UnityGradleSettingsTemplatePath + { + get + { return Path.Combine( UnityGradleTemplatesDir, GradleSettingsTemplatePathFilename); @@ -161,9 +168,11 @@ public static string UnityGradleSettingsTemplatePath { /// Whether current of Unity has changed the place to specify Maven repos from /// `mainTemplate.gradle` to `settingsTemplate.gradle`. /// - public static bool UnityChangeMavenRepoInSettingsTemplate { - get { - return Google.VersionHandler.GetUnityVersionMajorMinor() >= 2022.2f; + public static bool UnityChangeMavenRepoInSettingsTemplate + { + get + { + return new Dependency.VersionComparer().Compare("7.0", PlayServicesResolver.AndroidGradlePluginVersion) >= 0; } } @@ -172,19 +181,23 @@ public static bool UnityChangeMavenRepoInSettingsTemplate { /// /// Dependencies to inject. /// true if successful, false otherwise. - private static bool CopySrcAars(ICollection dependencies) { + private static bool CopySrcAars(ICollection dependencies) + { bool succeeded = true; var aarFiles = new List>(); // Copy each .srcaar file to .aar while configuring the plugin importer to ignore the // file. - foreach (var aar in LocalMavenRepository.FindAarsInLocalRepos(dependencies)) { + foreach (var aar in LocalMavenRepository.FindAarsInLocalRepos(dependencies)) + { // Only need to copy for .srcaar - if (Path.GetExtension(aar).CompareTo(".srcaar") != 0) { + if (Path.GetExtension(aar).CompareTo(".srcaar") != 0) + { continue; } var aarPath = aar; - if (FileUtils.IsUnderPackageDirectory(aar)) { + if (FileUtils.IsUnderPackageDirectory(aar)) + { // Physical paths work better for copy operations than // logical Unity paths. var physicalPackagePath = FileUtils.GetPackageDirectory(aar, @@ -205,44 +218,56 @@ private static bool CopySrcAars(ICollection dependencies) { targetFilename); bool configuredAar = File.Exists(targetFilename); - if (!configuredAar) { + if (!configuredAar) + { var error = PlayServicesResolver.CopyAssetAndLabel( aarPath, targetFilename); - if (String.IsNullOrEmpty(error)) { - try { + if (String.IsNullOrEmpty(error)) + { + try + { PluginImporter importer = (PluginImporter)AssetImporter.GetAtPath( targetFilename); importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); configuredAar = true; - } catch (Exception ex) { + } + catch (Exception ex) + { PlayServicesResolver.Log(String.Format( "Failed to disable {0} from being included by Unity's " + "internal build. {0} has been deleted and will not be " + "included in Gradle builds. ({1})", aar, ex), level: LogLevel.Error); } - } else { + } + else + { PlayServicesResolver.Log(String.Format( "Unable to copy {0} to {1}. {1} will not be included in Gradle " + "builds. Reason: {2}", aarPath, targetFilename, error), level: LogLevel.Error); } } - if (configuredAar) { + if (configuredAar) + { aarFiles.Add(new KeyValuePair(aarPath, targetFilename)); // Some versions of Unity do not mark the asset database as dirty when // plugin importer settings change so reimport the asset to synchronize // the state. AssetDatabase.ImportAsset(targetFilename, ImportAssetOptions.ForceUpdate); - } else { - if (File.Exists(targetFilename)) { + } + else + { + if (File.Exists(targetFilename)) + { AssetDatabase.DeleteAsset(targetFilename); } succeeded = false; } } - foreach (var keyValue in aarFiles) { + foreach (var keyValue in aarFiles) + { succeeded &= LocalMavenRepository.PatchPomFile(keyValue.Value, keyValue.Key); } return succeeded; @@ -251,7 +276,8 @@ private static bool CopySrcAars(ICollection dependencies) { /// /// Finds an area in a set of lines to inject a block of text. /// - private class TextFileLineInjector { + private class TextFileLineInjector + { // Token which, if found within a line, indicates where to inject the block of text if // the start / end block isn't found private Regex injectionToken; @@ -288,12 +314,14 @@ public TextFileLineInjector(string injectionToken, string endBlockLine, ICollection replacementLines, string replacementName, - string fileDescription) { + string fileDescription) + { this.injectionToken = new Regex(injectionToken); this.startBlockLine = startBlockLine; this.endBlockLine = endBlockLine; this.replacementLines = new List(); - if (replacementLines.Count > 0) { + if (replacementLines.Count > 0) + { this.replacementLines.Add(startBlockLine); this.replacementLines.AddRange(replacementLines); this.replacementLines.Add(endBlockLine); @@ -308,32 +336,43 @@ public TextFileLineInjector(string injectionToken, /// Line to process. /// Whether lines were injected. /// List of lines to emit for the specified line. - public List ProcessLine(string line, out bool injectionApplied) { + public List ProcessLine(string line, out bool injectionApplied) + { var trimmedLine = line.Trim(); var outputLines = new List { line }; bool injectBlock = false; injectionApplied = false; - if (injected) { + if (injected) + { return outputLines; } - if (!inBlock) { - if (trimmedLine.StartsWith(startBlockLine)) { + if (!inBlock) + { + if (trimmedLine.StartsWith(startBlockLine)) + { inBlock = true; outputLines.Clear(); - } else if (injectionToken.IsMatch(trimmedLine)) { + } + else if (injectionToken.IsMatch(trimmedLine)) + { injectBlock = true; } - } else { + } + else + { outputLines.Clear(); - if (trimmedLine.StartsWith(endBlockLine)) { + if (trimmedLine.StartsWith(endBlockLine)) + { inBlock = false; injectBlock = true; } } - if (injectBlock) { + if (injectBlock) + { injected = true; injectionApplied = true; - if (replacementLines.Count > 0) { + if (replacementLines.Count > 0) + { PlayServicesResolver.Log(String.Format("Adding {0} to {1}", replacementName, fileDescription), level: LogLevel.Verbose); @@ -360,11 +399,15 @@ private static bool PatchFile(string filePath, string analyticsReportUrlToken, TextFileLineInjector[] injectors, ICollection> - resolutionMeasurementParameters) { + resolutionMeasurementParameters) + { IEnumerable lines; - try { + try + { lines = File.ReadAllLines(filePath); - } catch (Exception ex) { + } + catch (Exception ex) + { PlayServicesResolver.analytics.Report( "/resolve/" + analyticsReportUrlToken + "/failed/templateunreadable", analyticsReportName + " Resolve: Failed Template Unreadable"); @@ -376,9 +419,11 @@ private static bool PatchFile(string filePath, // Lines that will be written to the output file. var outputLines = new List(); - foreach (var line in lines) { + foreach (var line in lines) + { var currentOutputLines = new List(); - foreach (var injector in injectors) { + foreach (var injector in injectors) + { bool injectionApplied = false; currentOutputLines = injector.ProcessLine(line, out injectionApplied); if (injectionApplied || currentOutputLines.Count == 0) break; @@ -389,7 +434,8 @@ private static bool PatchFile(string filePath, var inputText = String.Join("\n", (new List(lines)).ToArray()) + "\n"; var outputText = String.Join("\n", outputLines.ToArray()) + "\n"; - if (inputText == outputText) { + if (inputText == outputText) + { PlayServicesResolver.Log(String.Format("No changes to {0}", fileDescription), level: LogLevel.Verbose); return true; @@ -415,8 +461,10 @@ private static bool WriteToFile(string filePath, string analyticsReportName, string analyticsReportUrlToken, ICollection> - resolutionMeasurementParameters) { - if (!FileUtils.CheckoutFile(filePath, PlayServicesResolver.logger)) { + resolutionMeasurementParameters) + { + if (!FileUtils.CheckoutFile(filePath, PlayServicesResolver.logger)) + { PlayServicesResolver.Log( String.Format("Failed to checkout '{0}', unable to patch the file.", filePath), level: LogLevel.Error); @@ -428,15 +476,18 @@ private static bool WriteToFile(string filePath, PlayServicesResolver.Log( String.Format("Writing updated {0}", fileDescription), level: LogLevel.Verbose); - try { + try + { File.WriteAllText(filePath, outputText); PlayServicesResolver.analytics.Report( - "/resolve/"+analyticsReportUrlToken+"/success", + "/resolve/" + analyticsReportUrlToken + "/success", resolutionMeasurementParameters, analyticsReportName + " Resolve Success"); - } catch (Exception ex) { + } + catch (Exception ex) + { PlayServicesResolver.analytics.Report( - "/resolve/"+analyticsReportUrlToken+"/failed/write", + "/resolve/" + analyticsReportUrlToken + "/failed/write", analyticsReportName + " Resolve: Failed to write"); PlayServicesResolver.Log( String.Format("Unable to patch {0} ({1})", fileDescription, @@ -453,7 +504,8 @@ private static bool WriteToFile(string filePath, /// Android X is by updating the gradle properties template. /// /// true if successful, false otherwise. - public static bool InjectProperties(){ + public static bool InjectProperties() + { var resolutionMeasurementParameters = PlayServicesResolver.GetResolutionMeasurementParameters(null); PlayServicesResolver.analytics.Report( @@ -462,13 +514,13 @@ public static bool InjectProperties(){ var propertiesLines = new List(); // Lines to add Custom Gradle properties template to enable // jetifier and androidx - propertiesLines.AddRange(new [] { + propertiesLines.AddRange(new[] { "android.useAndroidX=true", "android.enableJetifier=true", }); var propertiesFileDescription = String.Format( "gradle properties template" + GradlePropertiesTemplatePath); - TextFileLineInjector[] propertiesInjectors = new [] { + TextFileLineInjector[] propertiesInjectors = new[] { new TextFileLineInjector(PropertiesInjectionLine, PropertiesStartLine, PropertiesEndLine, propertiesLines, @@ -478,7 +530,8 @@ public static bool InjectProperties(){ if (!PatchFile(GradlePropertiesTemplatePath, propertiesFileDescription, "Gradle Properties", "gradleproperties", propertiesInjectors, - resolutionMeasurementParameters)) { + resolutionMeasurementParameters)) + { PlayServicesResolver.Log( String.Format("Unable to patch " + propertiesFileDescription), level: LogLevel.Error); @@ -493,10 +546,12 @@ public static bool InjectProperties(){ /// /// Dependencies to inject. /// true if successful, false otherwise. - public static bool InjectDependencies(ICollection dependencies) { + public static bool InjectDependencies(ICollection dependencies) + { var resolutionMeasurementParameters = PlayServicesResolver.GetResolutionMeasurementParameters(null); - if (dependencies.Count > 0) { + if (dependencies.Count > 0) + { PlayServicesResolver.analytics.Report( "/resolve/gradletemplate", resolutionMeasurementParameters, "Gradle Template Resolve"); @@ -506,9 +561,12 @@ public static bool InjectDependencies(ICollection dependencies) { PlayServicesResolver.Log(String.Format("Reading {0}", fileDescription), level: LogLevel.Verbose); IEnumerable lines; - try { + try + { lines = File.ReadAllLines(GradleTemplatePath); - } catch (Exception ex) { + } + catch (Exception ex) + { PlayServicesResolver.analytics.Report( "/resolve/gradletemplate/failed/templateunreadable", "Gradle Template Resolve: Failed Template Unreadable"); @@ -524,15 +582,18 @@ public static bool InjectDependencies(ICollection dependencies) { // Determine whether dependencies should be injected. var dependenciesToken = new Regex(DependenciesToken); bool containsDeps = false; - foreach (var line in lines) { - if (dependenciesToken.IsMatch(line)) { + foreach (var line in lines) + { + if (dependenciesToken.IsMatch(line)) + { containsDeps = true; break; } } // If a dependencies token isn't present report a warning and abort. - if (!containsDeps) { + if (!containsDeps) + { PlayServicesResolver.analytics.Report( "/resolve/gradletemplate/failed/noinjectionpoint", "Gradle Template Resolve: Failed No Injection Point"); @@ -545,7 +606,8 @@ public static bool InjectDependencies(ICollection dependencies) { // Copy all srcaar files in the project to aar filenames so that they'll be included in // the Gradle build. - if (!CopySrcAars(dependencies)) { + if (!CopySrcAars(dependencies)) + { PlayServicesResolver.analytics.Report( "/resolve/gradletemplate/failed/srcaarcopy", "Gradle Template Resolve: Failed srcaar I/O"); @@ -554,11 +616,13 @@ public static bool InjectDependencies(ICollection dependencies) { var repoLines = new List(); // Optionally enable the jetifier. - if (SettingsDialog.UseJetifier && dependencies.Count > 0) { + if (SettingsDialog.UseJetifier && dependencies.Count > 0) + { // For Unity versions lower than 2019.3 add jetifier and AndroidX // properties to custom main gradle template - if (VersionHandler.GetUnityVersionMajorMinor() < 2019.3f) { - repoLines.AddRange(new [] { + if (VersionHandler.GetUnityVersionMajorMinor() < 2019.3f) + { + repoLines.AddRange(new[] { "([rootProject] + (rootProject.subprojects as List)).each {", " ext {", " it.setProperty(\"android.useAndroidX\", true)", @@ -568,11 +632,12 @@ public static bool InjectDependencies(ICollection dependencies) { }); } } - if (!UnityChangeMavenRepoInSettingsTemplate) { + if (!UnityChangeMavenRepoInSettingsTemplate) + { repoLines.AddRange(PlayServicesResolver.GradleMavenReposLines(dependencies)); } - TextFileLineInjector[] injectors = new [] { + TextFileLineInjector[] injectors = new[] { new TextFileLineInjector(ReposInjectionLine, ReposStartLine, ReposEndLine, repoLines, "Repos", fileDescription), new TextFileLineInjector(DependenciesToken, DependenciesStartLine, @@ -594,15 +659,18 @@ public static bool InjectDependencies(ICollection dependencies) { /// Inject / update dependencies in the gradle template file. /// /// true if successful, false otherwise. - public static bool InjectSettings(ICollection dependencies, out string lastError) { + public static bool InjectSettings(ICollection dependencies, out string lastError) + { if (!UnityChangeMavenRepoInSettingsTemplate || - !PlayServicesResolver.GradleTemplateEnabled) { + !PlayServicesResolver.GradleTemplateEnabled) + { // Early out since there is no need to patch settings template. lastError = ""; return true; } - if (!EnsureGradleTemplateEnabled(GradleSettingsTemplatePathFilename)) { + if (!EnsureGradleTemplateEnabled(GradleSettingsTemplatePathFilename)) + { lastError = String.Format( "Failed to auto-generate '{0}'. This is required to specify " + "additional Maven repos from Unity 2022.2. " + @@ -631,7 +699,7 @@ public static bool InjectSettings(ICollection dependencies, out stri var settingsFileDescription = String.Format( "gradle settings template " + GradleSettingsTemplatePath); - TextFileLineInjector[] settingsInjectors = new [] { + TextFileLineInjector[] settingsInjectors = new[] { new TextFileLineInjector(ReposInjectionLineInGradleSettings, ReposStartLine, ReposEndLine, GradleMavenReposLinesFromDependencies( @@ -645,7 +713,8 @@ public static bool InjectSettings(ICollection dependencies, out stri if (!PatchFile(GradleSettingsTemplatePath, settingsFileDescription, "Gradle Settings", "gradlesettings", settingsInjectors, - resolutionMeasurementParameters)) { + resolutionMeasurementParameters)) + { lastError = String.Format("Unable to patch " + settingsFileDescription); return false; } @@ -662,13 +731,15 @@ internal static IList GradleMavenReposLinesFromDependencies( ICollection dependencies, bool addMavenGoogle, bool addMavenCentral, - bool addMavenLocal) { + bool addMavenLocal) + { var lines = new List(); - if (dependencies.Count > 0) { + if (dependencies.Count > 0) + { var exportEnabled = PlayServicesResolver.GradleProjectExportEnabled; var useFullPath = ( exportEnabled && - SettingsDialog.UseFullCustomMavenRepoPathWhenExport ) || ( + SettingsDialog.UseFullCustomMavenRepoPathWhenExport) || ( !exportEnabled && SettingsDialog.UseFullCustomMavenRepoPathWhenNotExport); @@ -677,12 +748,14 @@ internal static IList GradleMavenReposLinesFromDependencies( // projectPath will point to the Unity project root directory as Unity will // generate the root Gradle project in "Temp/gradleOut" when *not* exporting a // gradle project. - if (!useFullPath) { + if (!useFullPath) + { lines.Add(String.Format( " def unityProjectPath = $/{0}**DIR_UNITYPROJECT**/$" + ".replace(\"\\\\\", \"/\")", GradleWrapper.FILE_SCHEME)); } - if(addMavenGoogle) { + if (addMavenGoogle) + { lines.Add(" maven {"); lines.Add(" url \"https://maven.google.com\""); lines.Add(" }"); @@ -690,11 +763,13 @@ internal static IList GradleMavenReposLinesFromDependencies( // Consolidate repos url from Packages folders like // "Packages/com.company.pkg1/Path/To/m2repository" and // "Packages/com.company.pkg2/Path/To/m2repository" - Dictionary< string, List > repoUriToSources = + Dictionary> repoUriToSources = new Dictionary>(); - foreach (var repoAndSources in PlayServicesResolver.GetRepos(dependencies: dependencies)) { + foreach (var repoAndSources in PlayServicesResolver.GetRepos(dependencies: dependencies)) + { string repoUri; - if (repoAndSources.Key.StartsWith(projectFileUri)) { + if (repoAndSources.Key.StartsWith(projectFileUri)) + { var relativePath = repoAndSources.Key.Substring(projectFileUri.Length + 1); // Convert "Assets", "Packages/packageid", or // "Library/PackageCache/packageid@version" prefix to local maven repo @@ -703,54 +778,69 @@ internal static IList GradleMavenReposLinesFromDependencies( var repoPath = FileUtils.PosixPathSeparators( FileUtils.ReplaceBaseAssetsOrPackagesFolder( relativePath, GooglePlayServices.SettingsDialog.LocalMavenRepoDir)); - if (!Directory.Exists(repoPath)) { + if (!Directory.Exists(repoPath)) + { repoPath = relativePath; } - if (useFullPath) { + if (useFullPath) + { // build.gradle expects file:/// URI so file separator will be "/" in anycase // and we must NOT use Path.Combine here because it will use "\" for win platforms repoUri = String.Format("\"{0}/{1}\"", projectFileUri, repoPath); - } else { + } + else + { repoUri = String.Format("(unityProjectPath + \"/{0}\")", repoPath); } - } else { + } + else + { repoUri = String.Format("\"{0}\"", repoAndSources.Key); } List sources; - if (!repoUriToSources.TryGetValue(repoUri, out sources)) { + if (!repoUriToSources.TryGetValue(repoUri, out sources)) + { sources = new List(); repoUriToSources[repoUri] = sources; } sources.Add(repoAndSources.Value); } - foreach(var kv in repoUriToSources) { + foreach (var kv in repoUriToSources) + { lines.Add(" maven {"); lines.Add(String.Format(" url {0} // {1}", kv.Key, String.Join(", ", kv.Value.ToArray()))); lines.Add(" }"); } - if (addMavenLocal) { + if (addMavenLocal) + { lines.Add(" mavenLocal()"); } - if (addMavenCentral) { + if (addMavenCentral) + { lines.Add(" mavenCentral()"); } } return lines; } - public static bool EnsureGradleTemplateEnabled(string templateName) { + public static bool EnsureGradleTemplateEnabled(string templateName) + { string templatePath = Path.Combine(SettingsDialog.AndroidPluginsDir, templateName); - if (File.Exists(templatePath)) { + if (File.Exists(templatePath)) + { return true; } string templateSourcePath = Path.Combine(UnityGradleTemplatesDir, templateName); - try { + try + { File.Copy(templateSourcePath, templatePath); - } catch (Exception e) { + } + catch (Exception e) + { PlayServicesResolver.Log(String.Format( "Unable to copy '{0}' from Unity engine folder '{1}' to this project " + "folder '{2}'. \n {3}", From dcb6104f4193c93fec74bcd748b4d4da73b9b11b Mon Sep 17 00:00:00 2001 From: argzdev Date: Thu, 1 Aug 2024 22:27:16 +0800 Subject: [PATCH 2/2] Changed format --- .../src/GradleTemplateResolver.cs | 263 ++++++------------ 1 file changed, 87 insertions(+), 176 deletions(-) diff --git a/source/AndroidResolver/src/GradleTemplateResolver.cs b/source/AndroidResolver/src/GradleTemplateResolver.cs index 00e820de..fe95f890 100644 --- a/source/AndroidResolver/src/GradleTemplateResolver.cs +++ b/source/AndroidResolver/src/GradleTemplateResolver.cs @@ -14,8 +14,7 @@ // limitations under the License. // -namespace GooglePlayServices -{ +namespace GooglePlayServices { using System; using System.Collections.Generic; using System.IO; @@ -29,8 +28,7 @@ namespace GooglePlayServices /// /// Resolver which simply injects dependencies into a gradle template file. /// - internal class GradleTemplateResolver - { + internal class GradleTemplateResolver { /// /// Filename of the Custom Gradle Properties Template file. @@ -55,12 +53,9 @@ internal class GradleTemplateResolver public static string GradleSettingsTemplatePath = Path.Combine(SettingsDialog.AndroidPluginsDir, GradleSettingsTemplatePathFilename); - public static string UnityGradleTemplatesDir - { - get - { - if (unityGradleTemplatesDir == null) - { + public static string UnityGradleTemplatesDir { + get { + if (unityGradleTemplatesDir == null) { var engineDir = PlayServicesResolver.AndroidPlaybackEngineDirectory; if (String.IsNullOrEmpty(engineDir)) return null; var gradleTemplateDir = @@ -72,10 +67,8 @@ public static string UnityGradleTemplatesDir } private static string unityGradleTemplatesDir = null; - public static string UnityGradleSettingsTemplatePath - { - get - { + public static string UnityGradleSettingsTemplatePath { + get { return Path.Combine( UnityGradleTemplatesDir, GradleSettingsTemplatePathFilename); @@ -168,8 +161,7 @@ public static string UnityGradleSettingsTemplatePath /// Whether current of Unity has changed the place to specify Maven repos from /// `mainTemplate.gradle` to `settingsTemplate.gradle`. /// - public static bool UnityChangeMavenRepoInSettingsTemplate - { + public static bool UnityChangeMavenRepoInSettingsTemplate { get { return new Dependency.VersionComparer().Compare("7.0", PlayServicesResolver.AndroidGradlePluginVersion) >= 0; @@ -181,23 +173,19 @@ public static bool UnityChangeMavenRepoInSettingsTemplate /// /// Dependencies to inject. /// true if successful, false otherwise. - private static bool CopySrcAars(ICollection dependencies) - { + private static bool CopySrcAars(ICollection dependencies) { bool succeeded = true; var aarFiles = new List>(); // Copy each .srcaar file to .aar while configuring the plugin importer to ignore the // file. - foreach (var aar in LocalMavenRepository.FindAarsInLocalRepos(dependencies)) - { + foreach (var aar in LocalMavenRepository.FindAarsInLocalRepos(dependencies)) { // Only need to copy for .srcaar - if (Path.GetExtension(aar).CompareTo(".srcaar") != 0) - { + if (Path.GetExtension(aar).CompareTo(".srcaar") != 0) { continue; } var aarPath = aar; - if (FileUtils.IsUnderPackageDirectory(aar)) - { + if (FileUtils.IsUnderPackageDirectory(aar)) { // Physical paths work better for copy operations than // logical Unity paths. var physicalPackagePath = FileUtils.GetPackageDirectory(aar, @@ -218,56 +206,44 @@ private static bool CopySrcAars(ICollection dependencies) targetFilename); bool configuredAar = File.Exists(targetFilename); - if (!configuredAar) - { + if (!configuredAar) { var error = PlayServicesResolver.CopyAssetAndLabel( aarPath, targetFilename); - if (String.IsNullOrEmpty(error)) - { - try - { + if (String.IsNullOrEmpty(error)) { + try { PluginImporter importer = (PluginImporter)AssetImporter.GetAtPath( targetFilename); importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); configuredAar = true; - } - catch (Exception ex) - { + } catch (Exception ex) { PlayServicesResolver.Log(String.Format( "Failed to disable {0} from being included by Unity's " + "internal build. {0} has been deleted and will not be " + "included in Gradle builds. ({1})", aar, ex), level: LogLevel.Error); } - } - else - { + } else { PlayServicesResolver.Log(String.Format( "Unable to copy {0} to {1}. {1} will not be included in Gradle " + "builds. Reason: {2}", aarPath, targetFilename, error), level: LogLevel.Error); } } - if (configuredAar) - { + if (configuredAar) { aarFiles.Add(new KeyValuePair(aarPath, targetFilename)); // Some versions of Unity do not mark the asset database as dirty when // plugin importer settings change so reimport the asset to synchronize // the state. AssetDatabase.ImportAsset(targetFilename, ImportAssetOptions.ForceUpdate); - } - else - { - if (File.Exists(targetFilename)) - { + } else { + if (File.Exists(targetFilename)) { AssetDatabase.DeleteAsset(targetFilename); } succeeded = false; } } - foreach (var keyValue in aarFiles) - { + foreach (var keyValue in aarFiles) { succeeded &= LocalMavenRepository.PatchPomFile(keyValue.Value, keyValue.Key); } return succeeded; @@ -276,8 +252,7 @@ private static bool CopySrcAars(ICollection dependencies) /// /// Finds an area in a set of lines to inject a block of text. /// - private class TextFileLineInjector - { + private class TextFileLineInjector { // Token which, if found within a line, indicates where to inject the block of text if // the start / end block isn't found private Regex injectionToken; @@ -314,14 +289,12 @@ public TextFileLineInjector(string injectionToken, string endBlockLine, ICollection replacementLines, string replacementName, - string fileDescription) - { + string fileDescription) { this.injectionToken = new Regex(injectionToken); this.startBlockLine = startBlockLine; this.endBlockLine = endBlockLine; this.replacementLines = new List(); - if (replacementLines.Count > 0) - { + if (replacementLines.Count > 0) { this.replacementLines.Add(startBlockLine); this.replacementLines.AddRange(replacementLines); this.replacementLines.Add(endBlockLine); @@ -336,43 +309,32 @@ public TextFileLineInjector(string injectionToken, /// Line to process. /// Whether lines were injected. /// List of lines to emit for the specified line. - public List ProcessLine(string line, out bool injectionApplied) - { + public List ProcessLine(string line, out bool injectionApplied) { var trimmedLine = line.Trim(); var outputLines = new List { line }; bool injectBlock = false; injectionApplied = false; - if (injected) - { + if (injected) { return outputLines; } - if (!inBlock) - { - if (trimmedLine.StartsWith(startBlockLine)) - { + if (!inBlock) { + if (trimmedLine.StartsWith(startBlockLine)) { inBlock = true; outputLines.Clear(); - } - else if (injectionToken.IsMatch(trimmedLine)) - { + } else if (injectionToken.IsMatch(trimmedLine)) { injectBlock = true; } - } - else - { + } else { outputLines.Clear(); - if (trimmedLine.StartsWith(endBlockLine)) - { + if (trimmedLine.StartsWith(endBlockLine)) { inBlock = false; injectBlock = true; } } - if (injectBlock) - { + if (injectBlock) { injected = true; injectionApplied = true; - if (replacementLines.Count > 0) - { + if (replacementLines.Count > 0) { PlayServicesResolver.Log(String.Format("Adding {0} to {1}", replacementName, fileDescription), level: LogLevel.Verbose); @@ -399,15 +361,11 @@ private static bool PatchFile(string filePath, string analyticsReportUrlToken, TextFileLineInjector[] injectors, ICollection> - resolutionMeasurementParameters) - { + resolutionMeasurementParameters) { IEnumerable lines; - try - { + try { lines = File.ReadAllLines(filePath); - } - catch (Exception ex) - { + } catch (Exception ex) { PlayServicesResolver.analytics.Report( "/resolve/" + analyticsReportUrlToken + "/failed/templateunreadable", analyticsReportName + " Resolve: Failed Template Unreadable"); @@ -419,11 +377,9 @@ private static bool PatchFile(string filePath, // Lines that will be written to the output file. var outputLines = new List(); - foreach (var line in lines) - { + foreach (var line in lines) { var currentOutputLines = new List(); - foreach (var injector in injectors) - { + foreach (var injector in injectors) { bool injectionApplied = false; currentOutputLines = injector.ProcessLine(line, out injectionApplied); if (injectionApplied || currentOutputLines.Count == 0) break; @@ -434,8 +390,7 @@ private static bool PatchFile(string filePath, var inputText = String.Join("\n", (new List(lines)).ToArray()) + "\n"; var outputText = String.Join("\n", outputLines.ToArray()) + "\n"; - if (inputText == outputText) - { + if (inputText == outputText) { PlayServicesResolver.Log(String.Format("No changes to {0}", fileDescription), level: LogLevel.Verbose); return true; @@ -461,10 +416,8 @@ private static bool WriteToFile(string filePath, string analyticsReportName, string analyticsReportUrlToken, ICollection> - resolutionMeasurementParameters) - { - if (!FileUtils.CheckoutFile(filePath, PlayServicesResolver.logger)) - { + resolutionMeasurementParameters) { + if (!FileUtils.CheckoutFile(filePath, PlayServicesResolver.logger)) { PlayServicesResolver.Log( String.Format("Failed to checkout '{0}', unable to patch the file.", filePath), level: LogLevel.Error); @@ -476,18 +429,15 @@ private static bool WriteToFile(string filePath, PlayServicesResolver.Log( String.Format("Writing updated {0}", fileDescription), level: LogLevel.Verbose); - try - { + try { File.WriteAllText(filePath, outputText); PlayServicesResolver.analytics.Report( - "/resolve/" + analyticsReportUrlToken + "/success", + "/resolve/"+analyticsReportUrlToken+"/success", resolutionMeasurementParameters, analyticsReportName + " Resolve Success"); - } - catch (Exception ex) - { + } catch (Exception ex) { PlayServicesResolver.analytics.Report( - "/resolve/" + analyticsReportUrlToken + "/failed/write", + "/resolve/"+analyticsReportUrlToken+"/failed/write", analyticsReportName + " Resolve: Failed to write"); PlayServicesResolver.Log( String.Format("Unable to patch {0} ({1})", fileDescription, @@ -504,8 +454,7 @@ private static bool WriteToFile(string filePath, /// Android X is by updating the gradle properties template. /// /// true if successful, false otherwise. - public static bool InjectProperties() - { + public static bool InjectProperties(){ var resolutionMeasurementParameters = PlayServicesResolver.GetResolutionMeasurementParameters(null); PlayServicesResolver.analytics.Report( @@ -514,13 +463,13 @@ public static bool InjectProperties() var propertiesLines = new List(); // Lines to add Custom Gradle properties template to enable // jetifier and androidx - propertiesLines.AddRange(new[] { + propertiesLines.AddRange(new [] { "android.useAndroidX=true", "android.enableJetifier=true", }); var propertiesFileDescription = String.Format( "gradle properties template" + GradlePropertiesTemplatePath); - TextFileLineInjector[] propertiesInjectors = new[] { + TextFileLineInjector[] propertiesInjectors = new [] { new TextFileLineInjector(PropertiesInjectionLine, PropertiesStartLine, PropertiesEndLine, propertiesLines, @@ -530,8 +479,7 @@ public static bool InjectProperties() if (!PatchFile(GradlePropertiesTemplatePath, propertiesFileDescription, "Gradle Properties", "gradleproperties", propertiesInjectors, - resolutionMeasurementParameters)) - { + resolutionMeasurementParameters)) { PlayServicesResolver.Log( String.Format("Unable to patch " + propertiesFileDescription), level: LogLevel.Error); @@ -546,12 +494,10 @@ public static bool InjectProperties() /// /// Dependencies to inject. /// true if successful, false otherwise. - public static bool InjectDependencies(ICollection dependencies) - { + public static bool InjectDependencies(ICollection dependencies) { var resolutionMeasurementParameters = PlayServicesResolver.GetResolutionMeasurementParameters(null); - if (dependencies.Count > 0) - { + if (dependencies.Count > 0) { PlayServicesResolver.analytics.Report( "/resolve/gradletemplate", resolutionMeasurementParameters, "Gradle Template Resolve"); @@ -561,12 +507,9 @@ public static bool InjectDependencies(ICollection dependencies) PlayServicesResolver.Log(String.Format("Reading {0}", fileDescription), level: LogLevel.Verbose); IEnumerable lines; - try - { + try { lines = File.ReadAllLines(GradleTemplatePath); - } - catch (Exception ex) - { + } catch (Exception ex) { PlayServicesResolver.analytics.Report( "/resolve/gradletemplate/failed/templateunreadable", "Gradle Template Resolve: Failed Template Unreadable"); @@ -582,18 +525,15 @@ public static bool InjectDependencies(ICollection dependencies) // Determine whether dependencies should be injected. var dependenciesToken = new Regex(DependenciesToken); bool containsDeps = false; - foreach (var line in lines) - { - if (dependenciesToken.IsMatch(line)) - { + foreach (var line in lines) { + if (dependenciesToken.IsMatch(line)) { containsDeps = true; break; } } // If a dependencies token isn't present report a warning and abort. - if (!containsDeps) - { + if (!containsDeps) { PlayServicesResolver.analytics.Report( "/resolve/gradletemplate/failed/noinjectionpoint", "Gradle Template Resolve: Failed No Injection Point"); @@ -606,8 +546,7 @@ public static bool InjectDependencies(ICollection dependencies) // Copy all srcaar files in the project to aar filenames so that they'll be included in // the Gradle build. - if (!CopySrcAars(dependencies)) - { + if (!CopySrcAars(dependencies)) { PlayServicesResolver.analytics.Report( "/resolve/gradletemplate/failed/srcaarcopy", "Gradle Template Resolve: Failed srcaar I/O"); @@ -616,13 +555,11 @@ public static bool InjectDependencies(ICollection dependencies) var repoLines = new List(); // Optionally enable the jetifier. - if (SettingsDialog.UseJetifier && dependencies.Count > 0) - { + if (SettingsDialog.UseJetifier && dependencies.Count > 0) { // For Unity versions lower than 2019.3 add jetifier and AndroidX // properties to custom main gradle template - if (VersionHandler.GetUnityVersionMajorMinor() < 2019.3f) - { - repoLines.AddRange(new[] { + if (VersionHandler.GetUnityVersionMajorMinor() < 2019.3f) { + repoLines.AddRange(new [] { "([rootProject] + (rootProject.subprojects as List)).each {", " ext {", " it.setProperty(\"android.useAndroidX\", true)", @@ -632,12 +569,11 @@ public static bool InjectDependencies(ICollection dependencies) }); } } - if (!UnityChangeMavenRepoInSettingsTemplate) - { + if (!UnityChangeMavenRepoInSettingsTemplate) { repoLines.AddRange(PlayServicesResolver.GradleMavenReposLines(dependencies)); } - TextFileLineInjector[] injectors = new[] { + TextFileLineInjector[] injectors = new [] { new TextFileLineInjector(ReposInjectionLine, ReposStartLine, ReposEndLine, repoLines, "Repos", fileDescription), new TextFileLineInjector(DependenciesToken, DependenciesStartLine, @@ -659,18 +595,15 @@ public static bool InjectDependencies(ICollection dependencies) /// Inject / update dependencies in the gradle template file. /// /// true if successful, false otherwise. - public static bool InjectSettings(ICollection dependencies, out string lastError) - { + public static bool InjectSettings(ICollection dependencies, out string lastError) { if (!UnityChangeMavenRepoInSettingsTemplate || - !PlayServicesResolver.GradleTemplateEnabled) - { + !PlayServicesResolver.GradleTemplateEnabled) { // Early out since there is no need to patch settings template. lastError = ""; return true; } - if (!EnsureGradleTemplateEnabled(GradleSettingsTemplatePathFilename)) - { + if (!EnsureGradleTemplateEnabled(GradleSettingsTemplatePathFilename)) { lastError = String.Format( "Failed to auto-generate '{0}'. This is required to specify " + "additional Maven repos from Unity 2022.2. " + @@ -699,7 +632,7 @@ public static bool InjectSettings(ICollection dependencies, out stri var settingsFileDescription = String.Format( "gradle settings template " + GradleSettingsTemplatePath); - TextFileLineInjector[] settingsInjectors = new[] { + TextFileLineInjector[] settingsInjectors = new [] { new TextFileLineInjector(ReposInjectionLineInGradleSettings, ReposStartLine, ReposEndLine, GradleMavenReposLinesFromDependencies( @@ -713,8 +646,7 @@ public static bool InjectSettings(ICollection dependencies, out stri if (!PatchFile(GradleSettingsTemplatePath, settingsFileDescription, "Gradle Settings", "gradlesettings", settingsInjectors, - resolutionMeasurementParameters)) - { + resolutionMeasurementParameters)) { lastError = String.Format("Unable to patch " + settingsFileDescription); return false; } @@ -731,15 +663,13 @@ internal static IList GradleMavenReposLinesFromDependencies( ICollection dependencies, bool addMavenGoogle, bool addMavenCentral, - bool addMavenLocal) - { + bool addMavenLocal) { var lines = new List(); - if (dependencies.Count > 0) - { + if (dependencies.Count > 0) { var exportEnabled = PlayServicesResolver.GradleProjectExportEnabled; var useFullPath = ( exportEnabled && - SettingsDialog.UseFullCustomMavenRepoPathWhenExport) || ( + SettingsDialog.UseFullCustomMavenRepoPathWhenExport ) || ( !exportEnabled && SettingsDialog.UseFullCustomMavenRepoPathWhenNotExport); @@ -748,14 +678,12 @@ internal static IList GradleMavenReposLinesFromDependencies( // projectPath will point to the Unity project root directory as Unity will // generate the root Gradle project in "Temp/gradleOut" when *not* exporting a // gradle project. - if (!useFullPath) - { + if (!useFullPath) { lines.Add(String.Format( " def unityProjectPath = $/{0}**DIR_UNITYPROJECT**/$" + ".replace(\"\\\\\", \"/\")", GradleWrapper.FILE_SCHEME)); } - if (addMavenGoogle) - { + if(addMavenGoogle) { lines.Add(" maven {"); lines.Add(" url \"https://maven.google.com\""); lines.Add(" }"); @@ -763,13 +691,11 @@ internal static IList GradleMavenReposLinesFromDependencies( // Consolidate repos url from Packages folders like // "Packages/com.company.pkg1/Path/To/m2repository" and // "Packages/com.company.pkg2/Path/To/m2repository" - Dictionary> repoUriToSources = + Dictionary< string, List > repoUriToSources = new Dictionary>(); - foreach (var repoAndSources in PlayServicesResolver.GetRepos(dependencies: dependencies)) - { + foreach (var repoAndSources in PlayServicesResolver.GetRepos(dependencies: dependencies)) { string repoUri; - if (repoAndSources.Key.StartsWith(projectFileUri)) - { + if (repoAndSources.Key.StartsWith(projectFileUri)) { var relativePath = repoAndSources.Key.Substring(projectFileUri.Length + 1); // Convert "Assets", "Packages/packageid", or // "Library/PackageCache/packageid@version" prefix to local maven repo @@ -778,69 +704,54 @@ internal static IList GradleMavenReposLinesFromDependencies( var repoPath = FileUtils.PosixPathSeparators( FileUtils.ReplaceBaseAssetsOrPackagesFolder( relativePath, GooglePlayServices.SettingsDialog.LocalMavenRepoDir)); - if (!Directory.Exists(repoPath)) - { + if (!Directory.Exists(repoPath)) { repoPath = relativePath; } - if (useFullPath) - { + if (useFullPath) { // build.gradle expects file:/// URI so file separator will be "/" in anycase // and we must NOT use Path.Combine here because it will use "\" for win platforms repoUri = String.Format("\"{0}/{1}\"", projectFileUri, repoPath); - } - else - { + } else { repoUri = String.Format("(unityProjectPath + \"/{0}\")", repoPath); } - } - else - { + } else { repoUri = String.Format("\"{0}\"", repoAndSources.Key); } List sources; - if (!repoUriToSources.TryGetValue(repoUri, out sources)) - { + if (!repoUriToSources.TryGetValue(repoUri, out sources)) { sources = new List(); repoUriToSources[repoUri] = sources; } sources.Add(repoAndSources.Value); } - foreach (var kv in repoUriToSources) - { + foreach(var kv in repoUriToSources) { lines.Add(" maven {"); lines.Add(String.Format(" url {0} // {1}", kv.Key, String.Join(", ", kv.Value.ToArray()))); lines.Add(" }"); } - if (addMavenLocal) - { + if (addMavenLocal) { lines.Add(" mavenLocal()"); } - if (addMavenCentral) - { + if (addMavenCentral) { lines.Add(" mavenCentral()"); } } return lines; } - public static bool EnsureGradleTemplateEnabled(string templateName) - { + public static bool EnsureGradleTemplateEnabled(string templateName) { string templatePath = Path.Combine(SettingsDialog.AndroidPluginsDir, templateName); - if (File.Exists(templatePath)) - { + if (File.Exists(templatePath)) { return true; } string templateSourcePath = Path.Combine(UnityGradleTemplatesDir, templateName); - try - { + try { File.Copy(templateSourcePath, templatePath); - } - catch (Exception e) - { + } catch (Exception e) { PlayServicesResolver.Log(String.Format( "Unable to copy '{0}' from Unity engine folder '{1}' to this project " + "folder '{2}'. \n {3}",