Пример #1
0
        private static string GetSchemaCompilerPath()
        {
            var schemaCompilerPath = SchemaCompilerPath;

            switch (Application.platform)
            {
            case RuntimePlatform.WindowsEditor:
                schemaCompilerPath = Path.ChangeExtension(schemaCompilerPath, ".exe");
                break;

            case RuntimePlatform.OSXEditor:
                var result = RedirectedProcess.Command("chmod")
                             .WithArgs("+x", $"\"{schemaCompilerPath}\"")
                             .InDirectory(Path.GetFullPath(Path.Combine(Application.dataPath, "..")))
                             .Run();
                if (result.ExitCode != 0)
                {
                    throw new IOException($"Failed to chmod schema compiler:{Environment.NewLine}{string.Join(Environment.NewLine, result.Stderr)}");
                }

                break;

            default:
                throw new PlatformNotSupportedException(
                          $"The {Application.platform} platform does not support code generation.");
            }

            return(schemaCompilerPath);
        }
Пример #2
0
        /// <summary>
        ///     Downloads and extracts the Core Sdk and associated libraries and tools.
        /// </summary>
        private static DownloadResult Download()
        {
            RemoveMarkerFile();

            int exitCode;

            try
            {
                EditorApplication.LockReloadAssemblies();

                using (new ShowProgressBarScope($"Installing SpatialOS libraries, version {Common.CoreSdkVersion}..."))
                {
                    exitCode = RedirectedProcess.Run(Common.DotNetBinary, ConstructArguments());
                    if (exitCode != 0)
                    {
                        Debug.LogError($"Failed to download SpatialOS Core Sdk version {Common.CoreSdkVersion}. You can use SpatialOS -> Download CoreSDK (force) to retry this.");
                    }
                    else
                    {
                        File.WriteAllText(InstallMarkerFile, string.Empty);
                    }
                }
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
            }

            return(exitCode == 0 ? DownloadResult.Success : DownloadResult.Error);
        }
Пример #3
0
        /// <summary>
        ///     Downloads and extracts the Core Sdk and associated libraries and tools.
        /// </summary>
        private static DownloadResult Download()
        {
            RemoveMarkerFile();

            int exitCode;

            try
            {
                EditorApplication.LockReloadAssemblies();

                using (new ShowProgressBarScope($"Installing SpatialOS libraries, version {Common.CoreSdkVersion}..."))
                {
                    exitCode = RedirectedProcess.Run(Common.DotNetBinary, "run", "-p", $"\"{ProjectPath}\"", "--",
                                                     $"\"{Common.SpatialBinary}\"", $"\"{Common.CoreSdkVersion}\"");
                    if (exitCode != 0)
                    {
                        Debug.LogError($"Failed to download SpatialOS Core Sdk version {Common.CoreSdkVersion}.");
                    }
                    else
                    {
                        File.WriteAllText(InstallMarkerFile, string.Empty);
                    }
                }
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
            }

            return(exitCode == 0 ? DownloadResult.Success : DownloadResult.Error);
        }
        /// <summary>
        ///     Creates the redirected process for the command.
        /// </summary>
        /// <param name="command">The filename to run.</param>
        public static RedirectedProcess Command(string command)
        {
            var redirectedProcess = new RedirectedProcess {
                command = command
            };

            return(redirectedProcess);
        }
Пример #5
0
 public static void BuildConfig()
 {
     using (new ShowProgressBarScope("Building worker configs..."))
     {
         // Run from the root of the project to build all available worker configs.
         RedirectedProcess.RunIn(SpatialProjectRootDir, Common.SpatialBinary, "build", "build-config",
                                 "--json_output");
     }
 }
Пример #6
0
        private static void Generate()
        {
            var devAuthToken              = string.Empty;
            var gdkToolsConfiguration     = GdkToolsConfiguration.GetOrCreateInstance();
            var devAuthTokenFullDir       = gdkToolsConfiguration.DevAuthTokenFullDir;
            var devAuthTokenFilePath      = gdkToolsConfiguration.DevAuthTokenFilepath;
            var devAuthTokenLifetimeHours = $"{gdkToolsConfiguration.DevAuthTokenLifetimeHours}h";

            var receivedMessage = string.Empty;

            RedirectedProcess
            .Command(Common.SpatialBinary)
            .WithArgs("project", "auth", "dev-auth-token", "create", "--description", "\"Dev Auth Token\"",
                      "--lifetime", devAuthTokenLifetimeHours, "--json_output")
            .InDirectory(Common.SpatialProjectRootDir)
            .AddOutputProcessing(message => receivedMessage = message)
            .RedirectOutputOptions(OutputRedirectBehaviour.None)
            .Run();

            try
            {
                if (Json.Deserialize(receivedMessage).TryGetValue(JsonDataKey, out var jsonData) &&
                    ((Dictionary <string, object>)jsonData).TryGetValue(TokenSecretKey, out var tokenSecret))
                {
                    devAuthToken = (string)tokenSecret;
                }
            }
            catch (Exception e)
            {
                Debug.LogError($"Unable to generate Dev Auth Token. {e.Message}");
                return;
            }

            if (!Directory.Exists(devAuthTokenFullDir))
            {
                Directory.CreateDirectory(devAuthTokenFullDir);
            }

            try
            {
                File.WriteAllText(devAuthTokenFilePath, devAuthToken);
            }
            catch (Exception e)
            {
                Debug.LogError($"Unable to save Dev Auth Token asset. {e.Message}");
                return;
            }

            Debug.Log($"Saving token {devAuthToken} to {devAuthTokenFilePath}.");
            AssetDatabase.ImportAsset(
                Path.Combine("Assets", gdkToolsConfiguration.DevAuthTokenDir, "DevAuthToken.txt"),
                ImportAssetOptions.ForceUpdate);
            AssetDatabase.Refresh();
        }
Пример #7
0
 public static void BuildConfig()
 {
     using (new ShowProgressBarScope("Building worker configs..."))
     {
         // Run from the root of the project to build all available worker configs.
         RedirectedProcess
         .Spatial("build", "build-config")
         .WithArgs("--json_output")
         .InDirectory(Common.SpatialProjectRootDir)
         .Run();
     }
 }
Пример #8
0
        public static bool TryGenerate()
        {
            var devAuthToken          = string.Empty;
            var gdkToolsConfiguration = GdkToolsConfiguration.GetOrCreateInstance();

            var devAuthTokenLifetimeHours = $"{gdkToolsConfiguration.DevAuthTokenLifetimeHours}h";

            var receivedMessage = string.Empty;

            RedirectedProcess
            .Spatial("project", "auth", "dev-auth-token", "create")
            .WithArgs("--description", "\"Dev Auth Token\"",
                      "--lifetime", devAuthTokenLifetimeHours,
                      "--json_output")
            .InDirectory(Common.SpatialProjectRootDir)
            .AddOutputProcessing(message => receivedMessage = message)
            .RedirectOutputOptions(OutputRedirectBehaviour.None)
            .Run();

            try
            {
                var deserializedMessage = Json.Deserialize(receivedMessage);
                if (deserializedMessage.TryGetValue(JsonDataKey, out var jsonData) &&
                    ((Dictionary <string, object>)jsonData).TryGetValue(JsonTokenSecretKey, out var tokenSecret))
                {
                    devAuthToken = (string)tokenSecret;
                }
                else
                {
                    if (deserializedMessage.TryGetValue(JsonErrorKey, out var errorMessage))
                    {
                        throw new Exception(errorMessage.ToString());
                    }

                    throw new Exception(string.Empty);
                }
            }
            catch (Exception e)
            {
                Debug.LogError($"Unable to generate Dev Auth Token. {e.Message}");
                return(false);
            }

            Debug.Log($"Saving token to Player Preferences.");
            PlayerPrefs.SetString(PlayerPrefDevAuthTokenKey, devAuthToken);

            if (gdkToolsConfiguration.SaveDevAuthTokenToFile)
            {
                return(SaveTokenToFile());
            }

            return(true);
        }
        private static void InstallDotnetTemplate()
        {
            var result = RedirectedProcess.Command(Common.DotNetBinary)
                         .WithArgs("new", "-i", "./")
                         .InDirectory(CodegenTemplatePath)
                         .RedirectOutputOptions(OutputRedirectBehaviour.None)
                         .Run();

            if (result.ExitCode != 0)
            {
                throw new Exception("Failed to run.");
            }
        }
        private Task <RedirectedProcessResult> RunPortForwarding()
        {
            EditorApplication.LockReloadAssemblies();

            tokenSrc = new CancellationTokenSource();
            return(RedirectedProcess.Command(Common.SpatialBinary)
                   .InDirectory(Common.SpatialProjectRootDir)
                   .WithArgs("project", "deployment", "worker", "port-forward",
                             "-d", deploymentName,
                             "-w", workerId,
                             "-p", $"{port}")
                   .RedirectOutputOptions(OutputRedirectBehaviour.None)
                   .AddOutputProcessing(line => isConnected |= line.Contains("Established tunnel"))
                   .RunAsync(tokenSrc.Token));
        }
        private static void CreateTemplate()
        {
            if (Directory.Exists(CodegenExeDirectory))
            {
                Directory.Delete(CodegenExeDirectory, recursive: true);
            }

            Directory.CreateDirectory(CodegenExeDirectory);

            var result = RedirectedProcess.Command(Common.DotNetBinary)
                         .WithArgs("new", "gdk-for-unity-codegen")
                         .InDirectory(CodegenExeDirectory)
                         .RedirectOutputOptions(OutputRedirectBehaviour.None)
                         .Run();

            if (result.ExitCode != 0)
            {
                throw new Exception("Failed to run.");
            }
        }
Пример #12
0
        private static void Generate()
        {
            try
            {
                EditorApplication.LockReloadAssemblies();

                // Ensure that all dependencies are in place.
                if (DownloadCoreSdk.TryDownload() == DownloadResult.Error)
                {
                    return;
                }

                CopySchema();

                var projectPath = Path.GetFullPath(Path.Combine(Common.GetThisPackagePath(),
                                                                CsProjectFile));

                var schemaCompilerPath =
                    Path.GetFullPath(Path.Combine(Application.dataPath, SchemaCompilerRelativePath));

                var workerJsonPath =
                    Path.GetFullPath(Path.Combine(Application.dataPath, ".."));

                switch (Application.platform)
                {
                case RuntimePlatform.WindowsEditor:
                    schemaCompilerPath = Path.ChangeExtension(schemaCompilerPath, ".exe");
                    break;

                case RuntimePlatform.LinuxEditor:
                case RuntimePlatform.OSXEditor:
                    // Ensure the schema compiler is executable.
                    var _ = RedirectedProcess.Run("chmod", "+x", schemaCompilerPath);
                    break;

                default:
                    throw new PlatformNotSupportedException(
                              $"The {Application.platform} platform does not support code generation.");
                }

                using (new ShowProgressBarScope("Generating code..."))
                {
                    var exitCode = RedirectedProcess.Run(Common.DotNetBinary,
                                                         ConstructArgs(projectPath, schemaCompilerPath, workerJsonPath));

                    if (exitCode != 0)
                    {
                        Debug.LogError("Failed to generate code.");
                    }
                    else
                    {
                        File.WriteAllText(StartupCodegenMarkerFile, string.Empty);
                    }
                }

                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
            }
        }
Пример #13
0
        private static void Generate()
        {
            try
            {
                if (!Common.CheckDependencies())
                {
                    return;
                }

                EditorApplication.LockReloadAssemblies();

                var projectPath = Path.GetFullPath(Path.Combine(Common.GetThisPackagePath(),
                                                                CsProjectFile));


                // Fix up symlinking for Mac
                if (Application.platform == RuntimePlatform.OSXEditor)
                {
                    var packageAttributes = File.GetAttributes(Common.GetThisPackagePath());
                    if (packageAttributes.HasFlag(FileAttributes.ReparsePoint))
                    {
                        var process = RedirectedProcess.Command("pwd")
                                      .WithArgs("-P")
                                      .InDirectory(Common.GetThisPackagePath())
                                      .RedirectOutputOptions(OutputRedirectBehaviour.None);

                        var result   = process.RunAsync().Result;
                        var realPath = string.Join("\n", result.Stdout).Trim();

                        projectPath = Path.GetFullPath(Path.Combine(realPath, CsProjectFile));
                    }
                }

                var schemaCompilerPath = SchemaCompilerPath;

                var workerJsonPath =
                    Path.GetFullPath(Path.Combine(Application.dataPath, ".."));

                switch (Application.platform)
                {
                case RuntimePlatform.WindowsEditor:
                    schemaCompilerPath = Path.ChangeExtension(schemaCompilerPath, ".exe");
                    break;

                case RuntimePlatform.LinuxEditor:
                case RuntimePlatform.OSXEditor:
                    RedirectedProcess.Command("chmod")
                    .WithArgs("+x", $"\"{schemaCompilerPath}\"")
                    .InDirectory(Path.GetFullPath(Path.Combine(Application.dataPath, "..")))
                    .Run();
                    break;

                default:
                    throw new PlatformNotSupportedException(
                              $"The {Application.platform} platform does not support code generation.");
                }

                using (new ShowProgressBarScope("Generating code..."))
                {
                    var errorMessage = new StringBuilder();
                    var exitCode     = RedirectedProcess.Command(Common.DotNetBinary)
                                       .WithArgs(ConstructArgs(projectPath, schemaCompilerPath, workerJsonPath))
                                       .RedirectOutputOptions(OutputRedirectBehaviour.None)
                                       .AddErrorProcessing((line) => errorMessage.Append($"\n{line}"))
                                       .AddOutputProcessing(ProcessStdOut)
                                       .Run();

                    if (exitCode != 0)
                    {
                        if (!Application.isBatchMode)
                        {
                            Debug.LogError($"Error(s) compiling schema files!{errorMessage.ToString()}");
                            EditorApplication.delayCall += () =>
                            {
                                EditorUtility.DisplayDialog("Generate Code",
                                                            "Failed to generate code from schema.\nPlease view the console for errors.",
                                                            "Close");
                            };
                        }
                    }
                    else
                    {
                        File.WriteAllText(StartupCodegenMarkerFile, string.Empty);
                    }
                }

                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
            }
        }
        private static void Generate()
        {
            try
            {
                if (!Common.CheckDependencies())
                {
                    return;
                }

                if (!File.Exists(CodegenExe))
                {
                    SetupProject();
                }

                EditorApplication.LockReloadAssemblies();

                Profiler.BeginSample("Add modules");
                UpdateModules();
                Profiler.EndSample();

                Profiler.BeginSample("Code generation");

                var schemaCompilerPath = SchemaCompilerPath;

                switch (Application.platform)
                {
                case RuntimePlatform.WindowsEditor:
                    schemaCompilerPath = Path.ChangeExtension(schemaCompilerPath, ".exe");
                    break;

                case RuntimePlatform.LinuxEditor:
                case RuntimePlatform.OSXEditor:
                    RedirectedProcess.Command("chmod")
                    .WithArgs("+x", $"\"{schemaCompilerPath}\"")
                    .InDirectory(Path.GetFullPath(Path.Combine(Application.dataPath, "..")))
                    .Run();
                    break;

                default:
                    throw new PlatformNotSupportedException(
                              $"The {Application.platform} platform does not support code generation.");
                }

                var workerJsonPath = Path.GetFullPath(Path.Combine(Application.dataPath, ".."));

                using (new ShowProgressBarScope("Generating code..."))
                {
                    var errorMessage = new StringBuilder();
                    var exitCode     = RedirectedProcess.Command(Common.DotNetBinary)
                                       .WithArgs(ConstructArgs(CodegenExe, schemaCompilerPath, workerJsonPath))
                                       .RedirectOutputOptions(OutputRedirectBehaviour.None)
                                       .AddErrorProcessing((line) => errorMessage.Append($"\n{line}"))
                                       .AddErrorProcessing(Debug.LogError)
                                       .AddOutputProcessing(ProcessStdOut)
                                       .Run();

                    if (exitCode.ExitCode != 0)
                    {
                        if (!Application.isBatchMode)
                        {
                            Debug.LogError($"Error(s) compiling schema files!{errorMessage}");
                            EditorApplication.delayCall += () =>
                            {
                                EditorUtility.DisplayDialog("Generate Code",
                                                            "Failed to generate code from schema.\nPlease view the console for errors.",
                                                            "Close");
                            };
                        }
                    }
                    else
                    {
                        File.WriteAllText(StartupCodegenMarkerFile, string.Empty);
                    }
                }

                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                Profiler.EndSample();
                EditorApplication.UnlockReloadAssemblies();
            }
        }
Пример #15
0
        private static void Generate()
        {
            try
            {
                if (!Common.CheckDependencies())
                {
                    return;
                }

                if (!File.Exists(CodegenExe))
                {
                    SetupProject();
                }

                EditorApplication.LockReloadAssemblies();

                Profiler.BeginSample("Add modules");
                UpdateModules();
                Profiler.EndSample();

                Profiler.BeginSample("Code generation");

                var schemaCompilerPath = SchemaCompilerPath;

                switch (Application.platform)
                {
                case RuntimePlatform.WindowsEditor:
                    schemaCompilerPath = Path.ChangeExtension(schemaCompilerPath, ".exe");
                    break;

                case RuntimePlatform.LinuxEditor:
                case RuntimePlatform.OSXEditor:
                    RedirectedProcess.Command("chmod")
                    .WithArgs("+x", $"\"{schemaCompilerPath}\"")
                    .InDirectory(Path.GetFullPath(Path.Combine(Application.dataPath, "..")))
                    .Run();
                    break;

                default:
                    throw new PlatformNotSupportedException(
                              $"The {Application.platform} platform does not support code generation.");
                }

                var workerJsonPath = Path.GetFullPath(Path.Combine(Application.dataPath, ".."));

                var toolsConfig      = GdkToolsConfiguration.GetOrCreateInstance();
                var loggerOutputPath = Path.GetFullPath(Path.Combine(toolsConfig.CodegenLogOutputDir, "codegen-output.log"));

                using (new ShowProgressBarScope("Generating code..."))
                {
                    ResetCodegenLogCounter();

                    var exitCode = RedirectedProcess.Command(Common.DotNetBinary)
                                   .WithArgs(ConstructArgs(CodegenExe, schemaCompilerPath, workerJsonPath, loggerOutputPath))
                                   .RedirectOutputOptions(OutputRedirectBehaviour.None)
                                   .AddOutputProcessing(ProcessDotnetOutput)
                                   .AddOutputProcessing(ProcessCodegenOutput)
                                   .Run();

                    var numWarnings = codegenLogCounts[CodegenLogLevel.Warn];
                    var numErrors   = codegenLogCounts[CodegenLogLevel.Error] + codegenLogCounts[CodegenLogLevel.Fatal];

                    if (exitCode.ExitCode != 0 || numErrors > 0)
                    {
                        if (!Application.isBatchMode)
                        {
                            Debug.LogError("Code generation failed! Please check the console for more information.");

                            EditorApplication.delayCall += () =>
                            {
                                if (File.Exists(loggerOutputPath))
                                {
                                    var option = EditorUtility.DisplayDialogComplex("Generate Code",
                                                                                    $"Code generation failed with {numWarnings} warnings and {numErrors} errors!\n\nPlease check the code generation logs for more information: {loggerOutputPath}",
                                                                                    "Open logfile",
                                                                                    "Close",
                                                                                    "");

                                    switch (option)
                                    {
                                    // Open logfile
                                    case 0:
                                        Application.OpenURL(loggerOutputPath);
                                        break;

                                    // Close
                                    case 1:
                                    // Alt
                                    case 2:
                                        break;

                                    default:
                                        throw new ArgumentOutOfRangeException("Unrecognised option");
                                    }
                                }
                                else
                                {
                                    DisplayGeneralFailure();
                                }
                            };
                        }
                    }
                    else
                    {
                        if (numWarnings > 0)
                        {
                            Debug.LogWarning($"Code generation completed successfully with {numWarnings} warnings. Please check the logs for more information: {loggerOutputPath}");
                        }
                        else
                        {
                            Debug.Log("Code generation complete!");
                        }

                        File.WriteAllText(StartupCodegenMarkerFile, string.Empty);
                    }
                }

                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                Profiler.EndSample();
                EditorApplication.UnlockReloadAssemblies();
            }
        }
Пример #16
0
        private static void Generate()
        {
            try
            {
                EditorApplication.LockReloadAssemblies();

                // Ensure that all dependencies are in place.
                if (DownloadCoreSdk.TryDownload() == DownloadResult.Error)
                {
                    return;
                }

                CopySchema(SchemaRootDir);

                var projectPath = Path.GetFullPath(Path.Combine(Common.GetThisPackagePath(),
                                                                CsProjectFile));

                var schemaCompilerPath =
                    Path.GetFullPath(Path.Combine(Application.dataPath, SchemaCompilerRelativePath));

                switch (Application.platform)
                {
                case RuntimePlatform.WindowsEditor:
                    schemaCompilerPath = Path.ChangeExtension(schemaCompilerPath, ".exe");
                    break;

                case RuntimePlatform.LinuxEditor:
                case RuntimePlatform.OSXEditor:
                    // Ensure the schema compiler is executable.
                    var _ = RedirectedProcess.Run("chmod", "+x", schemaCompilerPath);
                    break;

                default:
                    throw new PlatformNotSupportedException(
                              $"The {Application.platform} platform does not support code generation.");
                }

                using (new ShowProgressBarScope("Generating code..."))
                {
                    var exitCode = RedirectedProcess.Run(Common.DotNetBinary, "run", "-p", $"\"{projectPath}\"", "--",
                                                         $"--schema-path=\"{SchemaRootDir}\"",
                                                         $"--schema-path={SchemaStandardLibraryDir}",
                                                         $"--json-dir={ImprobableJsonDir}",
                                                         $"--native-output-dir={AssetsGeneratedSourceDir}",
                                                         $"--schema-compiler-path=\"{schemaCompilerPath}\"");

                    if (exitCode != 0)
                    {
                        Debug.LogError("Failed to generate code.");
                    }
                }

                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
            }
        }
Пример #17
0
        private static void Generate()
        {
            try
            {
                if (!Common.CheckDependencies())
                {
                    return;
                }

                if (!File.Exists(CodegenExe))
                {
                    SetupProject();
                }

                EditorApplication.LockReloadAssemblies();

                Profiler.BeginSample("Add modules");
                UpdateModules();
                Profiler.EndSample();

                Profiler.BeginSample("Code generation");

                using (new ShowProgressBarScope("Generating code..."))
                {
                    ResetCodegenLogCounter();

                    var toolsConfig      = GdkToolsConfiguration.GetOrCreateInstance();
                    var loggerOutputPath = toolsConfig.DefaultCodegenLogPath;

                    var exitCode = RedirectedProcess.Command(Common.DotNetBinary)
                                   .WithArgs("run", "-p", $"\"{CodegenExe}\"")
                                   .RedirectOutputOptions(OutputRedirectBehaviour.None)
                                   .AddOutputProcessing(ProcessDotnetOutput)
                                   .AddOutputProcessing(ProcessCodegenOutput)
                                   .Run();

                    var numWarnings = codegenLogCounts[CodegenLogLevel.Warn];
                    var numErrors   = codegenLogCounts[CodegenLogLevel.Error] + codegenLogCounts[CodegenLogLevel.Fatal];

                    if (exitCode.ExitCode != 0 || numErrors > 0)
                    {
                        if (!Application.isBatchMode)
                        {
                            Debug.LogError("Code generation failed! Please check the console for more information.");

                            EditorApplication.delayCall += () =>
                            {
                                if (File.Exists(loggerOutputPath))
                                {
                                    var option = EditorUtility.DisplayDialogComplex("Generate Code",
                                                                                    $"Code generation failed with {numWarnings} warnings and {numErrors} errors!{Environment.NewLine}{Environment.NewLine}"
                                                                                    + $"Please check the code generation logs for more information: {loggerOutputPath}",
                                                                                    "Open logfile",
                                                                                    "Close",
                                                                                    "");

                                    switch (option)
                                    {
                                    // Open logfile
                                    case 0:
                                        Application.OpenURL(loggerOutputPath);
                                        break;

                                    // Close
                                    case 1:
                                    // Alt
                                    case 2:
                                        break;

                                    default:
                                        throw new ArgumentOutOfRangeException(nameof(option), "Unrecognised option");
                                    }
                                }
                                else
                                {
                                    DisplayGeneralFailure();
                                }
                            };
                        }
                    }
                    else
                    {
                        if (numWarnings > 0)
                        {
                            Debug.LogWarning($"Code generation completed successfully with {numWarnings} warnings. Please check the logs for more information: {loggerOutputPath}");
                        }
                        else
                        {
                            Debug.Log("Code generation complete!");
                        }

                        File.WriteAllText(StartupCodegenMarkerFile, string.Empty);
                    }
                }

                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                Profiler.EndSample();
                EditorApplication.UnlockReloadAssemblies();
            }
        }
Пример #18
0
        private static void Generate()
        {
            try
            {
                EditorApplication.LockReloadAssemblies();

                // Ensure that all dependencies are in place.
                if (DownloadCoreSdk.TryDownload() == DownloadResult.Error)
                {
                    return;
                }

                CopySchema();

                var projectPath = Path.GetFullPath(Path.Combine(Common.GetThisPackagePath(),
                                                                CsProjectFile));

                var schemaCompilerPath =
                    Path.GetFullPath(Path.Combine(Application.dataPath, SchemaCompilerRelativePath));

                var workerJsonPath =
                    Path.GetFullPath(Path.Combine(Application.dataPath, ".."));

                switch (Application.platform)
                {
                case RuntimePlatform.WindowsEditor:
                    schemaCompilerPath = Path.ChangeExtension(schemaCompilerPath, ".exe");
                    break;

                case RuntimePlatform.LinuxEditor:
                case RuntimePlatform.OSXEditor:
                    // Ensure the schema compiler is executable.
                    var _ = RedirectedProcess.Command("chmod").WithArgs("+x", $"\"{schemaCompilerPath}\"").Run();
                    break;

                default:
                    throw new PlatformNotSupportedException(
                              $"The {Application.platform} platform does not support code generation.");
                }

                using (new ShowProgressBarScope("Generating code..."))
                {
                    var exitCode = RedirectedProcess.Command(Common.DotNetBinary)
                                   .WithArgs(ConstructArgs(projectPath, schemaCompilerPath, workerJsonPath))
                                   .RedirectOutputOptions(OutputRedirectBehaviour.None)
                                   .AddErrorProcessing(Debug.LogError)
                                   .AddOutputProcessing(ProcessStdOut)
                                   .Run();

                    if (exitCode != 0)
                    {
                        if (!Application.isBatchMode)
                        {
                            EditorApplication.delayCall += () =>
                            {
                                EditorUtility.DisplayDialog("Generate Code",
                                                            "Failed to generate code from schema.\nPlease view the console for errors.",
                                                            "Close");
                            };
                        }
                    }
                    else
                    {
                        File.WriteAllText(StartupCodegenMarkerFile, string.Empty);
                    }
                }

                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
            }
        }