using System;
using System.IO;
using UnityEngine;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
namespace TapTap.Common.Editor {
///
/// 模块 SDK 生成 link.xml 构建过程
///
public abstract class SDKLinkProcessBuild : IPreprocessBuildWithReport, IPostprocessBuildWithReport {
///
/// 执行顺序
///
public abstract int callbackOrder { get; }
///
/// 生成 link.xml 路径
///
public abstract string LinkPath { get; }
///
/// 防止被裁剪的 Assembly
///
public abstract LinkedAssembly[] LinkedAssemblies { get; }
///
/// 执行平台委托
///
public abstract Func IsTargetPlatform { get; }
///
/// 构建时忽略目录,目前主要是 PC 内置浏览器 Vuplex
///
public virtual string[] BuildingIgnorePaths => null;
///
/// 构建前处理
///
///
public void OnPreprocessBuild(BuildReport report) {
if (!IsTargetPlatform.Invoke(report)) {
return;
}
Application.logMessageReceived += OnBuildError;
IgnorePaths();
string linkPath = Path.Combine(Application.dataPath, LinkPath);
LinkXMLGenerator.Generate(linkPath, LinkedAssemblies);
}
///
/// 构建后处理
///
///
public void OnPostprocessBuild(BuildReport report) {
if (!IsTargetPlatform.Invoke(report)) {
return;
}
Application.logMessageReceived -= OnBuildError;
RecoverIgnoredPaths();
string linkPath = Path.Combine(Application.dataPath, LinkPath);
LinkXMLGenerator.Delete(linkPath);
}
///
/// 错误日志回调
///
///
///
///
private void OnBuildError(string condition, string stacktrace, LogType logType) {
// TRICK: 通过捕获错误日志来监听打包错误事件
if (logType == LogType.Error) {
Application.logMessageReceived -= OnBuildError;
RecoverIgnoredPaths();
}
}
///
/// 忽略目录
///
private void IgnorePaths() {
if (BuildingIgnorePaths == null) {
return;
}
foreach (string ignorePath in BuildingIgnorePaths) {
if (!Directory.Exists(Path.Combine(Application.dataPath, ignorePath))) {
continue;
}
string ignoreName = Path.GetFileName(ignorePath);
AssetDatabase.RenameAsset(Path.Combine("Assets", ignorePath), $"{ignoreName}~");
}
}
///
/// 恢复目录
///
private void RecoverIgnoredPaths() {
if (BuildingIgnorePaths == null) {
return;
}
foreach (string ignorePath in BuildingIgnorePaths) {
if (!Directory.Exists(Path.Combine(Application.dataPath, $"{ignorePath}~"))) {
continue;
}
Directory.Move(Path.Combine(Application.dataPath, $"{ignorePath}~"),
Path.Combine(Application.dataPath, $"{ignorePath}"));
AssetDatabase.ImportAsset(Path.Combine("Assets", ignorePath));
}
}
}
}