using System; #if UNITY_EDITOR using System.Diagnostics; #endif using System.IO; namespace TyphoonFormatCSharp { /// /// 格式化 C# 文件 /// public static class FormatCSharp { private static string BAT_PATH = $"{RootPath}/csharpier_0_16_0~/run.bat"; private static string _rootPath = null; private static string RootPath { get { if (_rootPath == null) { var p = "Assets/xgame.unity.formatcsharp"; var p2 = "Packages/xgame.unity.formatcsharp"; if (Directory.Exists(p)) { _rootPath = p; } else if (Directory.Exists(p2)) { _rootPath = p2; } else { throw new Exception("找不到插件路径"); } } return _rootPath; } } /// /// 整理代码 /// /// 文件或文件夹 /// 完成回调 /// public static void Format(string fileOrDirPath, Action complete = null) { #if UNITY_EDITOR if (!File.Exists(fileOrDirPath) && !Directory.Exists(fileOrDirPath)) { throw new Exception($"找不到文件/目录:{fileOrDirPath}"); } if (File.Exists(BAT_PATH)) { var arg = Path.GetFullPath(fileOrDirPath); //执行命令 var batPath = Path.GetFullPath(BAT_PATH); var folderPath = Path.GetDirectoryName(batPath); var handler = new ExitHandler(() => complete?.Invoke()); using (Process proc = new Process()) { proc.StartInfo.FileName = batPath; proc.StartInfo.WorkingDirectory = folderPath; proc.StartInfo.Arguments = $"\"{arg}\""; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.EnableRaisingEvents = true; proc.Exited += new EventHandler((sender, e) => { handler?.Invoke(); handler.Clear(); handler = null; }); proc.Start(); proc.WaitForExit(); } } else { throw new Exception($"找不到{BAT_PATH}"); } #endif } /// /// 复制文件夹 /// private static void CopyFolder(string from, string to) { if (!Directory.Exists(to)) { Directory.CreateDirectory(to); } var info = new DirectoryInfo(from); var files = info.GetFiles("*", SearchOption.TopDirectoryOnly); var dir = info.GetDirectories("*", SearchOption.TopDirectoryOnly); foreach (var element in files) { var copyTo = $"{to}/{element.Name}"; File.Copy(element.FullName, copyTo, true); } foreach (var element in dir) { var copyDir = $"{to}/{element.Name}"; CopyFolder(element.FullName, copyDir); } } class ExitHandler { public Action OnExit; public ExitHandler(Action onExit) { OnExit = onExit; } public void Clear() { OnExit = null; } public void Invoke() { OnExit?.Invoke(); OnExit = null; } } } }