XcodePluginLayout.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. #if UNITY_EDITOR && UNITY_IOS
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text.RegularExpressions;
  7. using UnityEditor.Build;
  8. using UnityEditor.iOS.Xcode;
  9. internal static class XcodePluginLayout
  10. {
  11. private static string PackageName => AppHelpPackagePaths.Name;
  12. private static readonly string[] ExportRoots = { "Frameworks", "Libraries" };
  13. private static readonly string[] PackageFolders = { "Runtime", "ThirdParty" };
  14. internal static void Normalize(string buildPath)
  15. {
  16. string projectPath = PBXProject.GetPBXProjectPath(buildPath);
  17. var project = new PBXProject();
  18. project.ReadFromFile(projectPath);
  19. string projectText = FlattenGroups(project.WriteToString());
  20. var moves = new List<KeyValuePair<string, string>>();
  21. foreach (string root in ExportRoots)
  22. {
  23. string packagePrefix = root + "/" + PackageName + "/";
  24. foreach (string folder in PackageFolders)
  25. projectText = projectText.Replace(packagePrefix + folder + "/", root + "/");
  26. projectText = projectText.Replace(packagePrefix, root + "/");
  27. string source = Path.Combine(buildPath, root, PackageName);
  28. if (!Directory.Exists(source)) continue;
  29. foreach (string file in Directory.GetFiles(source, "*", SearchOption.AllDirectories))
  30. {
  31. string relative = file.Substring(source.Length + 1).Replace('\\', '/');
  32. foreach (string folder in PackageFolders)
  33. if (relative.StartsWith(folder + "/", StringComparison.Ordinal))
  34. {
  35. relative = relative.Substring(folder.Length + 1);
  36. break;
  37. }
  38. moves.Add(new KeyValuePair<string, string>(file, Path.Combine(buildPath, root, relative)));
  39. }
  40. }
  41. var destinations = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
  42. foreach (var move in moves)
  43. {
  44. if (!destinations.Add(move.Value) || Directory.Exists(move.Value)
  45. || (File.Exists(move.Value) && !FilesEqual(move.Key, move.Value)))
  46. throw new BuildFailedException("AppRuntimes iOS export path conflict: " + move.Value
  47. + ". Export to an empty folder or remove the conflicting plugin.");
  48. }
  49. project.ReadFromString(projectText);
  50. foreach (var move in moves)
  51. {
  52. Directory.CreateDirectory(Path.GetDirectoryName(move.Value));
  53. if (File.Exists(move.Value)) File.Delete(move.Key);
  54. else File.Move(move.Key, move.Value);
  55. }
  56. foreach (string root in ExportRoots)
  57. RemoveEmptyDirectories(Path.Combine(buildPath, root, PackageName));
  58. project.WriteToFile(projectPath);
  59. }
  60. private static string FlattenGroups(string text)
  61. {
  62. const string begin = "/* Begin PBXGroup section */";
  63. const string end = "/* End PBXGroup section */";
  64. int start = text.IndexOf(begin, StringComparison.Ordinal);
  65. int finish = text.IndexOf(end, StringComparison.Ordinal);
  66. if (start < 0 || finish < start)
  67. throw new BuildFailedException("AppRuntimes could not find Xcode project groups.");
  68. string section = text.Substring(start, finish - start);
  69. var groups = Regex.Matches(section,
  70. @"(?ms)^\t\t(?<id>[A-Fa-f0-9]{24}) /\* .*? \*/ = \{\r?\n.*?^\t\t\};\r?\n")
  71. .Cast<Match>().ToDictionary(m => m.Groups["id"].Value);
  72. var removed = new HashSet<string>();
  73. var replacements = new Dictionary<string, string>();
  74. foreach (var entry in groups)
  75. {
  76. string root = GroupPath(entry.Value.Value);
  77. if (!ExportRoots.Contains(root)) continue;
  78. string children = Children(entry.Value.Value).Groups["items"].Value;
  79. foreach (Match child in ChildReferences(children))
  80. {
  81. string id = child.Groups["id"].Value;
  82. if (!groups.TryGetValue(id, out Match package) || GroupPath(package.Value) != PackageName)
  83. continue;
  84. string promoted = Children(package.Value).Groups["items"].Value;
  85. foreach (Match nested in ChildReferences(promoted))
  86. {
  87. string nestedId = nested.Groups["id"].Value;
  88. if (groups.TryGetValue(nestedId, out Match wrapper)
  89. && PackageFolders.Contains(GroupPath(wrapper.Value)))
  90. {
  91. promoted = promoted.Replace(nested.Value, Children(wrapper.Value).Groups["items"].Value);
  92. removed.Add(nestedId);
  93. }
  94. }
  95. children = children.Replace(child.Value, promoted);
  96. removed.Add(id);
  97. }
  98. Match original = Children(entry.Value.Value);
  99. Group items = original.Groups["items"];
  100. replacements[entry.Key] = entry.Value.Value.Remove(items.Index, items.Length).Insert(items.Index, children);
  101. }
  102. foreach (var entry in groups)
  103. {
  104. if (removed.Contains(entry.Key)) section = section.Replace(entry.Value.Value, "");
  105. else if (replacements.TryGetValue(entry.Key, out string replacement))
  106. section = section.Replace(entry.Value.Value, replacement);
  107. }
  108. if (Regex.IsMatch(section, @"\bpath = ""?" + Regex.Escape(PackageName) + @"""?;"))
  109. throw new BuildFailedException("AppRuntimes could not normalize the package's Xcode groups.");
  110. return text.Substring(0, start) + section + text.Substring(finish);
  111. }
  112. private static string GroupPath(string group) =>
  113. Regex.Match(group, @"(?m)^\s*path = ""?(?<path>[^"";\r\n]+)""?;").Groups["path"].Value;
  114. private static Match Children(string group) =>
  115. Regex.Match(group, @"(?s)children = \(\r?\n(?<items>.*?)\t\t\t\);");
  116. private static MatchCollection ChildReferences(string children) =>
  117. Regex.Matches(children, @"(?m)^\t\t\t\t(?<id>[A-Fa-f0-9]{24}) /\* .*? \*/,\r?\n");
  118. private static bool FilesEqual(string first, string second)
  119. {
  120. if (Path.DirectorySeparatorChar == '\\')
  121. {
  122. first = @"\\?\" + Path.GetFullPath(first);
  123. second = @"\\?\" + Path.GetFullPath(second);
  124. }
  125. if (new FileInfo(first).Length != new FileInfo(second).Length) return false;
  126. using (var a = File.OpenRead(first))
  127. using (var b = File.OpenRead(second))
  128. {
  129. var left = new byte[81920];
  130. var right = new byte[left.Length];
  131. int count;
  132. while ((count = a.Read(left, 0, left.Length)) > 0)
  133. {
  134. int read = 0;
  135. while (read < count)
  136. {
  137. int chunk = b.Read(right, read, count - read);
  138. if (chunk == 0) return false;
  139. read += chunk;
  140. }
  141. for (int i = 0; i < count; i++)
  142. if (left[i] != right[i]) return false;
  143. }
  144. return true;
  145. }
  146. }
  147. private static void RemoveEmptyDirectories(string directory)
  148. {
  149. if (!Directory.Exists(directory)) return;
  150. foreach (string child in Directory.GetDirectories(directory)) RemoveEmptyDirectories(child);
  151. Directory.Delete(directory, false);
  152. }
  153. }
  154. #endif