XcodePluginLayout.cs 7.8 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 const string PackageName = "come.app.runtimes";
  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. // Work on Unity's canonical serialization. Keep all file/build GUIDs, target
  20. // memberships, embed settings and per-file compiler flags intact.
  21. string projectText = FlattenGroups(project.WriteToString());
  22. var moves = new List<KeyValuePair<string, string>>();
  23. foreach (string root in ExportRoots)
  24. {
  25. string packagePrefix = root + "/" + PackageName + "/";
  26. foreach (string folder in PackageFolders)
  27. projectText = projectText.Replace(packagePrefix + folder + "/", root + "/");
  28. projectText = projectText.Replace(packagePrefix, root + "/");
  29. string source = Path.Combine(buildPath, root, PackageName);
  30. if (!Directory.Exists(source)) continue;
  31. foreach (string file in Directory.GetFiles(source, "*", SearchOption.AllDirectories))
  32. {
  33. string relative = file.Substring(source.Length + 1).Replace('\\', '/');
  34. foreach (string folder in PackageFolders)
  35. if (relative.StartsWith(folder + "/", StringComparison.Ordinal))
  36. {
  37. relative = relative.Substring(folder.Length + 1);
  38. break;
  39. }
  40. moves.Add(new KeyValuePair<string, string>(file, Path.Combine(buildPath, root, relative)));
  41. }
  42. }
  43. // Check every collision before changing the export. Identical files from
  44. // an append export are safe; different files require a clean export folder.
  45. var destinations = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
  46. foreach (var move in moves)
  47. {
  48. if (!destinations.Add(move.Value) || Directory.Exists(move.Value)
  49. || (File.Exists(move.Value) && !FilesEqual(move.Key, move.Value)))
  50. throw new BuildFailedException("AppRuntimes iOS export path conflict: " + move.Value
  51. + ". Export to an empty folder or remove the conflicting plugin.");
  52. }
  53. // Validate the rewritten project before moving any files.
  54. project.ReadFromString(projectText);
  55. foreach (var move in moves)
  56. {
  57. Directory.CreateDirectory(Path.GetDirectoryName(move.Value));
  58. if (File.Exists(move.Value)) File.Delete(move.Key); // Identical, checked above.
  59. else File.Move(move.Key, move.Value);
  60. }
  61. foreach (string root in ExportRoots)
  62. RemoveEmptyDirectories(Path.Combine(buildPath, root, PackageName));
  63. project.WriteToFile(projectPath);
  64. }
  65. private static string FlattenGroups(string text)
  66. {
  67. const string begin = "/* Begin PBXGroup section */";
  68. const string end = "/* End PBXGroup section */";
  69. int start = text.IndexOf(begin, StringComparison.Ordinal);
  70. int finish = text.IndexOf(end, StringComparison.Ordinal);
  71. if (start < 0 || finish < start)
  72. throw new BuildFailedException("AppRuntimes could not find Xcode project groups.");
  73. string section = text.Substring(start, finish - start);
  74. var groups = Regex.Matches(section,
  75. @"(?ms)^\t\t(?<id>[A-Fa-f0-9]{24}) /\* .*? \*/ = \{\r?\n.*?^\t\t\};\r?\n")
  76. .Cast<Match>().ToDictionary(m => m.Groups["id"].Value);
  77. var removed = new HashSet<string>();
  78. var replacements = new Dictionary<string, string>();
  79. foreach (var entry in groups)
  80. {
  81. string root = GroupPath(entry.Value.Value);
  82. if (!ExportRoots.Contains(root)) continue;
  83. string children = Children(entry.Value.Value).Groups["items"].Value;
  84. foreach (Match child in ChildReferences(children))
  85. {
  86. string id = child.Groups["id"].Value;
  87. if (!groups.TryGetValue(id, out Match package) || GroupPath(package.Value) != PackageName)
  88. continue;
  89. string promoted = Children(package.Value).Groups["items"].Value;
  90. foreach (Match nested in ChildReferences(promoted))
  91. {
  92. string nestedId = nested.Groups["id"].Value;
  93. if (groups.TryGetValue(nestedId, out Match wrapper)
  94. && PackageFolders.Contains(GroupPath(wrapper.Value)))
  95. {
  96. promoted = promoted.Replace(nested.Value, Children(wrapper.Value).Groups["items"].Value);
  97. removed.Add(nestedId);
  98. }
  99. }
  100. children = children.Replace(child.Value, promoted);
  101. removed.Add(id);
  102. }
  103. Match original = Children(entry.Value.Value);
  104. Group items = original.Groups["items"];
  105. replacements[entry.Key] = entry.Value.Value.Remove(items.Index, items.Length).Insert(items.Index, children);
  106. }
  107. foreach (var entry in groups)
  108. {
  109. if (removed.Contains(entry.Key)) section = section.Replace(entry.Value.Value, "");
  110. else if (replacements.TryGetValue(entry.Key, out string replacement))
  111. section = section.Replace(entry.Value.Value, replacement);
  112. }
  113. if (Regex.IsMatch(section, @"\bpath = ""?" + Regex.Escape(PackageName) + @"""?;"))
  114. throw new BuildFailedException("AppRuntimes could not normalize the package's Xcode groups.");
  115. return text.Substring(0, start) + section + text.Substring(finish);
  116. }
  117. private static string GroupPath(string group) =>
  118. Regex.Match(group, @"(?m)^\s*path = ""?(?<path>[^"";\r\n]+)""?;").Groups["path"].Value;
  119. private static Match Children(string group) =>
  120. Regex.Match(group, @"(?s)children = \(\r?\n(?<items>.*?)\t\t\t\);");
  121. private static MatchCollection ChildReferences(string children) =>
  122. Regex.Matches(children, @"(?m)^\t\t\t\t(?<id>[A-Fa-f0-9]{24}) /\* .*? \*/,\r?\n");
  123. private static bool FilesEqual(string first, string second)
  124. {
  125. // Unity's Mono FileStream needs the extended prefix for deep XCFramework paths on Windows.
  126. if (Path.DirectorySeparatorChar == '\\')
  127. {
  128. first = @"\\?\" + Path.GetFullPath(first);
  129. second = @"\\?\" + Path.GetFullPath(second);
  130. }
  131. if (new FileInfo(first).Length != new FileInfo(second).Length) return false;
  132. using (var a = File.OpenRead(first))
  133. using (var b = File.OpenRead(second))
  134. {
  135. var left = new byte[81920];
  136. var right = new byte[left.Length];
  137. int count;
  138. while ((count = a.Read(left, 0, left.Length)) > 0)
  139. {
  140. int read = 0;
  141. while (read < count)
  142. {
  143. int chunk = b.Read(right, read, count - read);
  144. if (chunk == 0) return false;
  145. read += chunk;
  146. }
  147. for (int i = 0; i < count; i++)
  148. if (left[i] != right[i]) return false;
  149. }
  150. return true;
  151. }
  152. }
  153. private static void RemoveEmptyDirectories(string directory)
  154. {
  155. if (!Directory.Exists(directory)) return;
  156. foreach (string child in Directory.GetDirectories(directory)) RemoveEmptyDirectories(child);
  157. Directory.Delete(directory, false);
  158. }
  159. }
  160. #endif