BuildScript.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. using UnityEditor;
  2. using UnityEngine;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Text;
  7. public partial class BuildScript
  8. {
  9. [MenuItem("Tools/Build/Build Andriod APK")]
  10. static public void BuildAndroid_ByMenu() // used by GitLab
  11. {
  12. BuildScript.pathTarget = "c:/temp/Chic.apk"; //"C:/srv/share/JenkinsBuilds/Chic/Android/Chic.apk";
  13. isRelease = true;
  14. BuildAndroid();
  15. }
  16. static public void BuildAndroid() // used by GitLab
  17. {
  18. SetCommonSettings(BuildTarget.Android);
  19. //IncrementVersionPart(incrementType);
  20. PlayerSettings.Android.keyaliasPass = KEY_STORE_PASS;
  21. PlayerSettings.Android.keystorePass = KEY_STORE_PASS;
  22. if(revisionAsInt == 0)
  23. {
  24. UnityEngine.Debug.LogError("Revision variable was not properly set, cannot make a build!");
  25. throw new Exception("invalid revision");
  26. }
  27. PlayerSettings.Android.bundleVersionCode = revisionAsInt; //
  28. //PlayerSettings.Android.bundleVersionCode = Convert.ToInt32(ObtainRevisionHeadNumber(BuildTarget.Android));
  29. PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, CombineSymbols(standartDefinedSymbols, realserverSymbol, slackSymbol));
  30. bool success = MakeBuild(pathTarget, BuildTarget.Android, isRelease ? RELEASE_MODE : DEVELOPMENT_MODE);
  31. OnBuildDone(success);
  32. }
  33. [MenuItem("Tools/Build/Build iOS XCode Project")]
  34. static public void BuildIOS_ByMenu() // used by GitLab
  35. {
  36. BuildScript.pathTarget = "c:/temp/XCodeProject"; // "C:/srv/share/JenkinsBuilds/Chic/iOS";
  37. isRelease = true;
  38. //isUnstable = true;
  39. BuildIOS();
  40. }
  41. static public void BuildIOS() // used by GitLab
  42. {
  43. SetCommonSettings(BuildTarget.iOS);
  44. //IncrementVersionPart(incrementType);
  45. PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.iOS, CombineSymbols(standartDefinedSymbols, realserverSymbol, slackSymbol));
  46. PlayerSettings.iOS.buildNumber = revisionAsString;
  47. //PlayerSettings.iOS.buildNumber = ObtainRevisionHeadNumber(BuildTarget.iOS);
  48. bool success = MakeBuild(pathTarget, BuildTarget.iOS, isRelease ? RELEASE_MODE : DEVELOPMENT_MODE);
  49. OnBuildDone(success);
  50. }
  51. static bool MakeBuild(string locationPathName, BuildTarget _buildTarget, BuildOptions buildOptions)
  52. {
  53. buildTarget = _buildTarget;
  54. //ImportJenkinsDataToResources();
  55. InitPlayerSettings();
  56. string[] scenes = FindEnabledEditorScenes();
  57. // UnityEngine.Debug.LogError("Current Directory: " + System.IO.Directory.GetCurrentDirectory());
  58. var report = BuildPipeline.BuildPlayer(scenes, locationPathName, buildTarget, buildOptions);
  59. //if (!string.IsNullOrEmpty(report.summary.ToString()))
  60. if(report.summary.totalErrors > 0) //Unity 2018 version
  61. {
  62. string msg = "BUILD FAILED!! Build Report:\n" + report.ToString(); // todo, review out the build report is displayed in Unity 2018 as it might have a useful description of the build, maybe we only show a nice build report summary in gitlab
  63. UnityEngine.Debug.LogError(msg);
  64. return false;
  65. }
  66. return true;
  67. }
  68. /*--------------------------------------------------------------------------------*/
  69. /*
  70. static public void GetCommitInfo()
  71. {
  72. ProcessStartInfo processStartInfo = new ProcessStartInfo();
  73. processStartInfo.UseShellExecute = false;
  74. processStartInfo.RedirectStandardOutput = true;
  75. processStartInfo.WorkingDirectory = pathProject;
  76. processStartInfo.Arguments = "/c svn log -l1";
  77. processStartInfo.FileName = "cmd.exe";
  78. Process svnInstance = Process.Start(processStartInfo);
  79. svnInstance.WaitForExit();
  80. svnInstance.StandardOutput.ReadLine();
  81. string response = svnInstance.StandardOutput.ReadLine();
  82. System.IO.File.WriteAllText(pathProject + "\\lastCommitInfo.txt", response);
  83. }
  84. */
  85. /*--------------------------------------------------------------------------------*/
  86. /*
  87. static void CommitVersionFiles(string _version, BuildTarget _t)
  88. {
  89. ProcessStartInfo processStartInfo = new ProcessStartInfo();
  90. processStartInfo.UseShellExecute = false;
  91. processStartInfo.RedirectStandardOutput = true;
  92. StringBuilder sb = new StringBuilder("/c svn commit -m \"Version Snapshot: ");
  93. sb.Append(_version);
  94. sb.Append("\" ");
  95. sb.Append(_t == BuildTarget.Android ? GLOBAL_VERISON_FILE_android : GLOBAL_VERISON_FILE_ios);
  96. sb.Append(" ");
  97. sb.Append(_t == BuildTarget.Android ? DISPLAYED_VERISON_FILE_android : DISPLAYED_VERISON_FILE_ios);
  98. processStartInfo.Arguments = sb.ToString();
  99. processStartInfo.FileName = "cmd.exe";
  100. Process svnInstance = Process.Start(processStartInfo);
  101. svnInstance.WaitForExit();
  102. string response = svnInstance.StandardOutput.ReadLine();
  103. UnityEngine.Debug.Log(response);
  104. }
  105. */
  106. /*--------------------------------------------------------------------------------*/
  107. static void SetCommonSettings_ForAnyProject(BuildTarget _target)
  108. {
  109. buildTarget = _target;
  110. //UnityEngine.Application.logMessageReceivedThreaded += OnLogDuringBuild;
  111. //Facebook.Unity.Settings.FacebookSettings.SelectedAppIndex = _target == BuildTarget.iOS ? 1 : 0;
  112. PlayerSettings.SplashScreen.showUnityLogo = false; // to prevent accidentally enabling
  113. ProcessCommandLineValues();
  114. //if(SVN_ARGS == "")
  115. // throw new FormatException("You should provide svn command to get revision number revision!");
  116. string versionInfo = "";
  117. string versionOriginal = "";
  118. //string versionFilePath = incrementType == VersionPartName.None ? "\\Assets\\Resources\\versionDisplayed.txt" : "\\version.txt";
  119. string versionFilePath = pathProject + "\\Assets\\Resources\\versionDisplayed.txt";
  120. try
  121. {
  122. versionOriginal = System.IO.File.ReadAllText(versionFilePath);
  123. versionInfo = versionOriginal;
  124. int iRevisionLeft = versionInfo.LastIndexOf('(');
  125. int iRevisionRight = versionInfo.LastIndexOf(')');
  126. revisionAsString = versionInfo.Substring(iRevisionLeft + 1, iRevisionRight - iRevisionLeft - 1);
  127. if(!int.TryParse(revisionAsString, out revisionAsInt)) // Will throw an error in case of "bad" revision received which is needed to stop GitLab
  128. {
  129. UnityEngine.Debug.Log("Failed to parse: revisionAsString=" + revisionAsString);
  130. throw new Exception("Failed to parse revision");
  131. }
  132. int i = versionInfo.IndexOf(' ');
  133. versionInfo = versionInfo.Substring(0, i);
  134. PlayerSettings.bundleVersion = versionInfo;
  135. if (versionInfo.Trim() == "")
  136. throw new Exception("Version file is empty!");
  137. }
  138. catch (Exception e)
  139. {
  140. UnityEngine.Debug.Log("versionFilePath = " + versionFilePath);
  141. UnityEngine.Debug.Log("version string text = " + versionOriginal);
  142. UnityEngine.Debug.LogException(e);
  143. UnityEngine.Debug.Log("Cannot make a build, see BuildScript.cs for details.");
  144. throw new Exception(e.Message);
  145. }
  146. //BuildScript.versionParts = versionInfo.Split('.');
  147. //if (incrementType == VersionPartName.None)
  148. //{
  149. // versionParts[versionParts.Length - 1] = versionParts[versionParts.Length - 1].Remove(versionParts[versionParts.Length - 1].IndexOf("(") - 1);
  150. //}
  151. PlayerSettings.applicationIdentifier = GetBundleId();
  152. PlayerSettings.productName = nameProduct;
  153. PlayerSettings.runInBackground = false;
  154. }
  155. /*
  156. private static void OnLogDuringBuild(string text, string stackTrace, LogType type)
  157. {
  158. if (type == LogType.Log)
  159. {
  160. System.Console.WriteLine(text);
  161. }
  162. else
  163. {
  164. var color = System.Console.ForegroundColor;
  165. System.Console.ForegroundColor = type == LogType.Warning ? ConsoleColor.Yellow : ConsoleColor.Red;
  166. System.Console.WriteLine(text);
  167. System.Console.ForegroundColor = color; // restor
  168. }
  169. }
  170. */
  171. static string GetSvnRevisionHeadNumber()
  172. {
  173. ProcessStartInfo processStartInfo = new ProcessStartInfo();
  174. processStartInfo.WorkingDirectory = pathProject;
  175. processStartInfo.UseShellExecute = false;
  176. processStartInfo.RedirectStandardOutput = true;
  177. processStartInfo.Arguments = "/c svn info --show-item revision --non-interactive --trust-server-cert-failures=unknown-ca " + SVN_LOGIN_ARGS;
  178. processStartInfo.FileName = "cmd.exe";
  179. Process svnInstance = Process.Start(processStartInfo);
  180. svnInstance.WaitForExit();
  181. string response = svnInstance.StandardOutput.ReadLine();
  182. response = (Convert.ToInt32(response)).ToString();
  183. return response;
  184. }
  185. static string GetBundleId()
  186. {
  187. if(buildTarget == BuildTarget.iOS)
  188. {
  189. if (isUnstable)
  190. return bundleId_iOS_Unstable;
  191. return bundleId_iOS_Stable;
  192. }
  193. else if (buildTarget == BuildTarget.Android)
  194. {
  195. return bundleId_Android;
  196. }
  197. return "com.unknown.unknown";
  198. }
  199. static void InitPlayerSettings()
  200. {
  201. PlayerSettings.productName = nameProduct;
  202. PlayerSettings.applicationIdentifier = GetBundleId();
  203. switch (buildTarget)
  204. {
  205. case BuildTarget.Android:
  206. PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, standartDefinedSymbols);
  207. EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
  208. break;
  209. case BuildTarget.StandaloneWindows64:
  210. PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone, standartDefinedSymbols);
  211. break;
  212. case BuildTarget.iOS:
  213. PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.iOS, standartDefinedSymbols);
  214. break;
  215. default:
  216. break;
  217. }
  218. }
  219. static string[] FindEnabledEditorScenes()
  220. {
  221. List<string> EditorScenes = new List<string>();
  222. foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes)
  223. {
  224. if (!scene.enabled) continue;
  225. EditorScenes.Add(scene.path);
  226. }
  227. return EditorScenes.ToArray();
  228. }
  229. static void ProcessCommandLineValues()
  230. {
  231. commandLineArgs = Environment.GetCommandLineArgs();
  232. UnityEngine.Debug.Log("Searching for command-line arguments...");
  233. var len = commandLineArgs.Length;
  234. for(int i = 0; i < len; i++)
  235. {
  236. int j = i + 1;
  237. string next = j < len ? commandLineArgs[j] : "(unknown)";
  238. string current = commandLineArgs[i];
  239. ProcessCommandLineValue(current, next);
  240. }
  241. UnityEngine.Debug.Log("Done searching for command-line arguments.");
  242. ValidateCommandLine();
  243. }
  244. private static void ValidateCommandLine()
  245. {
  246. if(string.IsNullOrEmpty(pathProject))
  247. {
  248. // remove "Assets" from end of UnityEngine.Application.dataPath...
  249. pathProject = System.IO.Directory.GetParent(UnityEngine.Application.dataPath).ToString();
  250. }
  251. if (string.IsNullOrEmpty(pathTarget))
  252. {
  253. string msg = "-targetpath \"my path\" is missing from command-line.";
  254. UnityEngine.Debug.LogError(msg);
  255. throw new Exception(msg);
  256. }
  257. }
  258. static void ProcessCommandLineValue(string current, string next)
  259. {
  260. switch(current.ToLower())
  261. {
  262. case "-targetpath":
  263. pathTarget = next;
  264. UnityEngine.Debug.Log(" -targetpath " + next);
  265. break;
  266. case "-projectpath":
  267. pathProject = next;
  268. UnityEngine.Debug.Log(" -projectpath " + next);
  269. break;
  270. case "-isrelease":
  271. isRelease = true;
  272. UnityEngine.Debug.Log(" -isRelease");
  273. break;
  274. case "-isunstable":
  275. isUnstable = true;
  276. UnityEngine.Debug.Log(" -isUnstable");
  277. break;
  278. }
  279. }
  280. static void ImportJenkinsDataToResources()
  281. {
  282. AssetDatabase.StartAssetEditing();
  283. //AssetDatabase.ImportAsset("Resources" + System.IO.Path.DirectorySeparatorChar + JenkinsData.realServerVersionFileName);
  284. //AssetDatabase.ImportAsset("Resources" + System.IO.Path.DirectorySeparatorChar + JenkinsData.jenkinsDataFileName);
  285. AssetDatabase.StopAssetEditing();
  286. System.Threading.Thread.Sleep(100); // wait a bit before refresh, in case system is slow
  287. AssetDatabase.Refresh();
  288. }
  289. static string CombineSymbols(params string[] symbols)
  290. {
  291. string finalString = string.Empty;
  292. foreach (string s in symbols)
  293. {
  294. finalString += s + ";";
  295. }
  296. return finalString;
  297. }
  298. /*--------------------------------------------------------------------------------*/
  299. }