diff --git a/CHANGELOG.md b/CHANGELOG.md index b930378..7479219 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## [1.2.1] - 2026-10-24 + +### Added +- Picking an output folder inside another assembly definition (directly or through an `.asmref`) offers to add + the references the generated code needs to that `.asmdef`, or to give the code its own `.asmdef`. The + **Output** settings show which assembly the code compiles into, and generation warns about missing references. + +### Changed +- Restyled settings: collapsible sections, consistent label widths, options that do not apply are greyed out, + and a shared toolbar (Regenerate, Verify, Open Output Folder, Setup Wizard) with a last-run summary. Every + setting can be found through the Project Settings search. + +### Fixed +- A folder picked with **Browse** was not saved. +- `AssemblyBuilder` obsolete warning in the editor tests on Unity 6.5. + ## [1.2.0] - 2026-10-24 ### Added diff --git a/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs b/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs index 4f8fadf..d763a12 100644 --- a/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs +++ b/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs @@ -16,7 +16,7 @@ namespace Severnbli.LocalizationCodegen.Installer public static partial class Installer { public const string PackageId = "com.severnbli.localization-codegen"; - public const string Version = "1.2.0"; + public const string Version = "1.2.1"; static Installer() { diff --git a/README.md b/README.md index 99d04c3..583083b 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,7 @@ Add the scoped registry and the dependency to `Packages/manifest.json`: } ], "dependencies": { - "com.severnbli.localization-codegen": "1.2.0" + "com.severnbli.localization-codegen": "1.2.1" } } ``` @@ -319,7 +319,7 @@ Open **Project Settings > Localization Codegen**, or **Window > Localization Cod | Setting | Default | Description | |---|---|---| | Namespace | `Localization` | Namespace of generated classes. Empty or whitespace means the global namespace. | -| Output Folder | `Assets/Generated/Localization` | Must be inside `Assets`. Changing it removes generated files from the old folder. | +| Output Folder | `Assets/Generated/Localization` | Must be inside `Assets`. Changing it removes generated files from the old folder. Inside another `.asmdef`, you are offered to add the references the code needs. | | String Tables | on | Generate classes for string table collections. Disabling deletes the matching files on the next run. | | Asset Tables | on | Generate classes for asset table collections. Disabling deletes the matching files on the next run. | | Regenerate On Changes | on | Debounced automatic regeneration after table edits and external (VCS) changes. | @@ -331,7 +331,7 @@ Open **Project Settings > Localization Codegen**, or **Window > Localization Cod | Naming Convention | `Keep` | `Keep` or `PascalCase`. | | Key Separators | empty | Characters that create nested classes, e.g. `/`. | | UniTask Members | off | Also emit [`…Async` members](#unitask) returning `UniTask`. Requires UniTask. | -| Generate .asmdef | off | Write an assembly definition into the output folder. | +| Generate .asmdef | off | Write an assembly definition into the output folder, so the generated code gets its own assembly. | | Fail CI On Smart String Mismatch | off | Make `CheckBatch` fail on locale placeholder mismatches. | The window also has **Regenerate Now**, **Open Output Folder** and **Run Setup Wizard** buttons, and lists the warnings of the last run. @@ -360,7 +360,7 @@ For clean diffs, add this to `.gitattributes`: - Only files in the output folder whose first line is `// ` are created, overwritten or deleted. Don't edit generated files by hand. - A manifest in the project settings remembers the last output folder, so changing the folder or namespace does not leave duplicate types behind. -- If you move generated code into your own assembly definition, enable **Generate .asmdef**, or reference `Unity.Localization` and `com.severnbli.localization-codegen.Runtime` manually (plus `UniTask` and `com.severnbli.localization-codegen.UniTask` for UniTask members). +- If the output folder is inside one of your assembly definitions (directly or through an `.asmref`), the generated code compiles into that assembly, which must reference `com.severnbli.localization-codegen.Runtime` and `Unity.Localization` (plus `UniTask` and `com.severnbli.localization-codegen.UniTask` for UniTask members). When you pick such a folder you are asked to **Add References** to that `.asmdef` for you, or to **Use Separate .asmdef** (**Generate .asmdef**). The **Output** section keeps showing which assembly the code compiles into, and generation warns while references are missing. - The synchronous members block until the table is loaded and are not supported by Addressables on WebGL. Use [UniTask members](#unitask), or `LocalizedTables.GetStringAsync` / `GetAssetAsync`, there. - If `LocalizationSettings` are missing at runtime, generated members return the table key (and log once) instead of throwing. - The generator is editor-only; generated C# files have no runtime dependency on the generator assembly. diff --git a/Unity-Package/Assets/root/CHANGELOG.md b/Unity-Package/Assets/root/CHANGELOG.md index b930378..7479219 100644 --- a/Unity-Package/Assets/root/CHANGELOG.md +++ b/Unity-Package/Assets/root/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## [1.2.1] - 2026-10-24 + +### Added +- Picking an output folder inside another assembly definition (directly or through an `.asmref`) offers to add + the references the generated code needs to that `.asmdef`, or to give the code its own `.asmdef`. The + **Output** settings show which assembly the code compiles into, and generation warns about missing references. + +### Changed +- Restyled settings: collapsible sections, consistent label widths, options that do not apply are greyed out, + and a shared toolbar (Regenerate, Verify, Open Output Folder, Setup Wizard) with a last-run summary. Every + setting can be found through the Project Settings search. + +### Fixed +- A folder picked with **Browse** was not saved. +- `AssemblyBuilder` obsolete warning in the editor tests on Unity 6.5. + ## [1.2.0] - 2026-10-24 ### Added diff --git a/Unity-Package/Assets/root/Editor/AssemblyOwnership.cs b/Unity-Package/Assets/root/Editor/AssemblyOwnership.cs new file mode 100644 index 0000000..8beaa1c --- /dev/null +++ b/Unity-Package/Assets/root/Editor/AssemblyOwnership.cs @@ -0,0 +1,315 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using UnityEditor; +using UnityEditor.Compilation; +using UnityEngine; + +namespace Severnbli.LocalizationCodegen.Editor +{ + /// The assembly definition that generated code compiles into when the output folder lies below one. + internal sealed class OwningAssembly + { + /// Assembly name, as other asmdefs reference it. + public string Name; + + /// Project-relative path of the .asmdef, or null when an .asmref points to an unknown assembly. + public string AsmdefPath; + + /// The .asmref that adds the folder to the assembly, or null when an .asmdef owns it directly. + public string AsmrefPath; + + /// Required assemblies the asmdef does not reference yet. + public readonly List MissingReferences = new List(); + + /// False for asmdefs inside immutable packages (registry or git), which cannot be edited. + public bool IsEditable; + } + + /// Finds the assembly that owns the output folder and keeps its references in sync. + internal static class AssemblyOwnership + { + public const string RuntimeAssemblyName = "com.severnbli.localization-codegen.Runtime"; + public const string LocalizationAssemblyName = "Unity.Localization"; + const string GuidPrefix = "GUID:"; + + [Serializable] + sealed class AsmdefData + { + public string name; + public string[] references; + } + + [Serializable] + sealed class AsmrefData + { + public string reference; + } + + /// Assemblies generated code needs, for the given settings. + public static List RequiredReferences(bool uniTask) + { + var references = new List { RuntimeAssemblyName, LocalizationAssemblyName }; + if (uniTask) + { + references.Add(UniTaskSupport.RuntimeAssemblyName); + references.Add(UniTaskSupport.UniTaskAssemblyName); + } + return references; + } + + /// The references the current settings need. + public static List RequiredReferences(CodegenSettings settings) + => RequiredReferences(settings.GenerateUniTask && UniTaskSupport.IsAvailable); + + /// + /// Walks up from to Assets and returns the nearest owning assembly, or null when + /// the generated code compiles into Assembly-CSharp. skips the asmdef + /// the generator itself wrote. + /// + public static OwningAssembly Find(string folder, IList requiredReferences, string ignoredAsmdefPath = null) + { + if (string.IsNullOrEmpty(folder)) + return null; + + var ignoredFull = string.IsNullOrEmpty(ignoredAsmdefPath) ? null : Path.GetFullPath(ignoredAsmdefPath); + + for (var dir = folder.Replace('\\', '/').TrimEnd('/'); !string.IsNullOrEmpty(dir); dir = ParentFolder(dir)) + { + var full = OutputPath.ToFullPath(dir); + if (Directory.Exists(full)) + { + // Unity allows one asmdef or asmref per folder; sort so a broken project is still deterministic. + var asmdef = Directory.GetFiles(full, "*.asmdef") + .Where(f => ignoredFull == null || !string.Equals(Path.GetFullPath(f), ignoredFull, StringComparison.OrdinalIgnoreCase)) + .OrderBy(f => f, StringComparer.Ordinal) + .FirstOrDefault(); + if (asmdef != null) + return FromAsmdef(dir + "/" + Path.GetFileName(asmdef), null, requiredReferences); + + var asmref = Directory.GetFiles(full, "*.asmref").OrderBy(f => f, StringComparer.Ordinal).FirstOrDefault(); + if (asmref != null) + return FromAsmref(dir + "/" + Path.GetFileName(asmref), requiredReferences); + } + + if (dir == "Assets") + break; + } + + return null; + } + + /// + /// Reads a project-relative file. Path.GetFullPath is what maps virtual "Packages/..." paths to their real + /// location (the package cache, an embedded or a local package). + /// + static string ReadText(string assetPath) => File.ReadAllText(Path.GetFullPath(assetPath)); + + static string ParentFolder(string path) + { + var slash = path.LastIndexOf('/'); + return slash <= 0 ? null : path.Substring(0, slash); + } + + static OwningAssembly FromAsmref(string asmrefPath, IList requiredReferences) + { + var data = JsonUtility.FromJson(ReadText(asmrefPath)); + var reference = data?.reference ?? ""; + + string asmdefPath; + string name; + if (!ResolveReference(reference, out name, out asmdefPath) || asmdefPath == null) + { + // The referenced assembly does not exist; there is nothing to fix from here. + return new OwningAssembly { Name = name, AsmrefPath = asmrefPath }; + } + + return FromAsmdef(asmdefPath, asmrefPath, requiredReferences); + } + + static OwningAssembly FromAsmdef(string asmdefPath, string asmrefPath, IList requiredReferences) + { + var data = JsonUtility.FromJson(ReadText(asmdefPath)) ?? new AsmdefData(); + var owner = new OwningAssembly + { + Name = string.IsNullOrEmpty(data.name) ? Path.GetFileNameWithoutExtension(asmdefPath) : data.name, + AsmdefPath = asmdefPath, + AsmrefPath = asmrefPath, + IsEditable = IsEditable(asmdefPath) + }; + + var referenced = new HashSet(StringComparer.Ordinal); + foreach (var reference in data.references ?? Array.Empty()) + { + string name; + string ignored; + if (ResolveReference(reference, out name, out ignored)) + referenced.Add(name); + } + + foreach (var required in requiredReferences ?? Array.Empty()) + { + if (!referenced.Contains(required) && !string.Equals(required, owner.Name, StringComparison.Ordinal)) + owner.MissingReferences.Add(required); + } + + return owner; + } + + /// Resolves an asmdef reference ("Name" or "GUID:hex") to an assembly name and asmdef path. + static bool ResolveReference(string reference, out string name, out string asmdefPath) + { + name = reference; + asmdefPath = null; + if (string.IsNullOrEmpty(reference)) + return false; + + if (reference.StartsWith(GuidPrefix, StringComparison.OrdinalIgnoreCase)) + { + var path = AssetDatabase.GUIDToAssetPath(reference.Substring(GuidPrefix.Length)); + if (string.IsNullOrEmpty(path) || !File.Exists(Path.GetFullPath(path))) + return false; + + asmdefPath = path; + var data = JsonUtility.FromJson(ReadText(path)); + name = string.IsNullOrEmpty(data?.name) ? Path.GetFileNameWithoutExtension(path) : data.name; + return true; + } + + asmdefPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(reference); + return true; + } + + static bool IsEditable(string assetPath) + { + if (assetPath.StartsWith("Assets/", StringComparison.Ordinal)) + return true; + + var package = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(assetPath); + return package != null && + (package.source == UnityEditor.PackageManager.PackageSource.Embedded || + package.source == UnityEditor.PackageManager.PackageSource.Local); + } + + /// + /// Adds the missing references to the owner's asmdef, keeping its formatting. References are written as + /// GUIDs when the asmdef already uses GUID references. Returns false when nothing could be written. + /// + public static bool AddMissingReferences(OwningAssembly owner) => AddMissingReferences(owner, true); + + /// False in tests, whose asmdefs live in folders Unity does not import. + internal static bool AddMissingReferences(OwningAssembly owner, bool import) + { + if (owner == null || owner.AsmdefPath == null || !owner.IsEditable || owner.MissingReferences.Count == 0) + return false; + + var fullPath = Path.GetFullPath(owner.AsmdefPath); + var raw = File.ReadAllBytes(fullPath); + var hasBom = raw.Length >= 3 && raw[0] == 0xEF && raw[1] == 0xBB && raw[2] == 0xBF; + var json = new UTF8Encoding(false).GetString(raw, hasBom ? 3 : 0, raw.Length - (hasBom ? 3 : 0)); + + var data = JsonUtility.FromJson(json) ?? new AsmdefData(); + var useGuids = (data.references ?? Array.Empty()) + .Any(r => r.StartsWith(GuidPrefix, StringComparison.OrdinalIgnoreCase)); + + var entries = owner.MissingReferences.Select(name => useGuids ? ToGuidReference(name) : name).ToList(); + var updated = AddReferences(json, entries); + File.WriteAllText(fullPath, updated, new UTF8Encoding(hasBom)); + if (import) + AssetDatabase.ImportAsset(owner.AsmdefPath); + return true; + } + + static string ToGuidReference(string assemblyName) + { + var path = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assemblyName); + var guid = string.IsNullOrEmpty(path) ? null : AssetDatabase.AssetPathToGUID(path); + return string.IsNullOrEmpty(guid) ? assemblyName : GuidPrefix + guid; + } + + static readonly Regex s_ReferencesArray = + new Regex("(?\"references\"\\s*:\\s*)\\[(?[^\\]]*)\\]", RegexOptions.Compiled); + + /// + /// Appends to the "references" array of an asmdef, creating the array when + /// missing. Pure text editing, so indentation, line endings and every other field stay as they were. + /// + internal static string AddReferences(string json, IList references) + { + if (references == null || references.Count == 0) + return json; + + var newline = json.Contains("\r\n") ? "\r\n" : "\n"; + var quoted = references.Select(CodegenText.Literal).ToList(); + var match = s_ReferencesArray.Match(json); + + if (!match.Success) + { + // Insert the array as the first property after the opening brace. + var open = json.IndexOf('{'); + if (open < 0) + throw new FormatException("The assembly definition is not a JSON object."); + + var propertyIndent = DetectPropertyIndent(json, open); + var array = "\"references\": [" + newline + + string.Join("," + newline, quoted.Select(q => propertyIndent + propertyIndent + q)) + + newline + propertyIndent + "],"; + return json.Insert(open + 1, newline + propertyIndent + array); + } + + var items = match.Groups["items"]; + var keyIndent = LineIndent(json, match.Index); + if (items.Value.Trim().Length == 0) + { + var itemIndent = keyIndent + IndentUnit(keyIndent); + var array = "[" + newline + + string.Join("," + newline, quoted.Select(q => itemIndent + q)) + + newline + keyIndent + "]"; + return json.Substring(0, items.Index - 1) + array + json.Substring(items.Index + items.Length + 1); + } + + // Append after the last existing element, matching its layout. + var lastElementEnd = items.Index + items.Value.TrimEnd().Length; + string insertion; + if (items.Value.Contains("\n")) + { + var itemIndent = LineIndent(json, lastElementEnd - 1); + insertion = string.Concat(quoted.Select(q => "," + newline + itemIndent + q)); + } + else + { + insertion = string.Concat(quoted.Select(q => ", " + q)); + } + + return json.Insert(lastElementEnd, insertion); + } + + static string LineIndent(string text, int index) + { + var lineStart = text.LastIndexOf('\n', Math.Max(0, index - 1)) + 1; + var end = lineStart; + while (end < text.Length && (text[end] == ' ' || text[end] == '\t')) + end++; + return text.Substring(lineStart, end - lineStart); + } + + static string DetectPropertyIndent(string json, int openBrace) + { + var quote = json.IndexOf('"', openBrace); + if (quote < 0) + return " "; + var indent = LineIndent(json, quote); + return indent.Length > 0 ? indent : " "; + } + + static string IndentUnit(string keyIndent) + { + if (keyIndent.Length == 0) + return " "; + return keyIndent[0] == '\t' ? "\t" : keyIndent; + } + } +} diff --git a/Unity-Package/Assets/root/Editor/AssemblyOwnership.cs.meta b/Unity-Package/Assets/root/Editor/AssemblyOwnership.cs.meta new file mode 100644 index 0000000..eb84195 --- /dev/null +++ b/Unity-Package/Assets/root/Editor/AssemblyOwnership.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ed7ba9b9123d4d548ae5df3b05c9f919 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/Editor/CodeGenerator.cs b/Unity-Package/Assets/root/Editor/CodeGenerator.cs index f85577f..d8080af 100644 --- a/Unity-Package/Assets/root/Editor/CodeGenerator.cs +++ b/Unity-Package/Assets/root/Editor/CodeGenerator.cs @@ -99,6 +99,8 @@ public static GenerateResult Run(GenerateOptions options) var emitOptions = BuildEmitOptions(settings); if (settings.GenerateUniTask && !emitOptions.UniTask) result.Warnings.Add(UniTaskSupport.MissingMessage); + if (!settings.GenerateAsmdef) + WarnAboutOwningAssembly(folder, emitOptions, settings, result); var reader = new TableReader(emitOptions); var read = reader.Read(settings.GenerateStringTables, settings.GenerateAssetTables); @@ -293,6 +295,28 @@ static EmitOptions BuildEmitOptions(CodegenSettings settings) }; } + /// Warns when the output folder compiles into an asmdef that lacks the references the code needs. + static void WarnAboutOwningAssembly(string folder, EmitOptions options, CodegenSettings settings, GenerateResult result) + { + try + { + var owner = AssemblyOwnership.Find( + folder, AssemblyOwnership.RequiredReferences(options.UniTask), settings.LastAsmdefPath); + if (owner == null || owner.MissingReferences.Count == 0) + return; + + result.Warnings.Add( + $"The output folder belongs to the assembly '{owner.Name}', which does not reference " + + string.Join(", ", owner.MissingReferences.ToArray()) + ". The generated code will not compile " + + "until you add them (Project Settings > Localization Codegen) or enable Generate .asmdef."); + } + catch (Exception e) + { + // A broken asmdef must not stop generation; Unity reports it on its own. + result.Warnings.Add("Could not inspect the assembly that owns the output folder: " + e.Message); + } + } + static bool HasPreviousOutput(CodegenSettings settings, string currentFolderFull) { if (settings.GeneratedPaths.Length > 0) diff --git a/Unity-Package/Assets/root/Editor/CodegenSettingsProvider.cs b/Unity-Package/Assets/root/Editor/CodegenSettingsProvider.cs index be92446..72e004b 100644 --- a/Unity-Package/Assets/root/Editor/CodegenSettingsProvider.cs +++ b/Unity-Package/Assets/root/Editor/CodegenSettingsProvider.cs @@ -1,28 +1,35 @@ +using System.Collections.Generic; using UnityEditor; -using UnityEngine; namespace Severnbli.LocalizationCodegen.Editor { /// Project settings page (B5). static class CodegenSettingsProvider { + static bool s_ShowWarnings; + [SettingsProvider] static SettingsProvider Create() { return new SettingsProvider("Project/Localization Codegen", SettingsScope.Project) { label = "Localization Codegen", + keywords = new HashSet(SettingsGui.Content.Keywords()), guiHandler = _ => { - EditorGUILayout.Space(); - EditorGUILayout.HelpBox( - "Generates strongly typed C# classes from Unity Localization table collections.", - MessageType.Info); - SettingsGui.Draw(); + SettingsGui.DrawToolbar(); + using (new EditorGUILayout.VerticalScope(SettingsGui.PageStyle)) + { + EditorGUILayout.LabelField( + "Generates strongly typed C# classes from Unity Localization table collections.", + EditorStyles.wordWrappedMiniLabel); + EditorGUILayout.Space(); + + SettingsGui.DrawLastResult(ref s_ShowWarnings); + EditorGUILayout.Space(); - EditorGUILayout.Space(); - if (GUILayout.Button("Regenerate Now")) - CodeGenerator.Run(new GenerateOptions { IsAutomatic = false }); + SettingsGui.Draw(); + } } }; } diff --git a/Unity-Package/Assets/root/Editor/CodegenWindow.cs b/Unity-Package/Assets/root/Editor/CodegenWindow.cs index 367fc86..6b6ee23 100644 --- a/Unity-Package/Assets/root/Editor/CodegenWindow.cs +++ b/Unity-Package/Assets/root/Editor/CodegenWindow.cs @@ -1,4 +1,4 @@ -using UnityEditor; +using UnityEditor; using UnityEngine; namespace Severnbli.LocalizationCodegen.Editor @@ -13,102 +13,28 @@ public sealed class CodegenWindow : EditorWindow void OnEnable() { - minSize = new Vector2(400, 380); + minSize = new Vector2(420, 380); } void OnGUI() { - scroll = EditorGUILayout.BeginScrollView(scroll); - - EditorGUILayout.Space(); - EditorGUILayout.LabelField("Localization Codegen", EditorStyles.boldLabel); - EditorGUILayout.HelpBox( - "Generates strongly typed C# classes from Unity Localization table collections. " + - "Each table collection becomes a class and each key a property, e.g. Ui.PlayerName.", - MessageType.Info); - EditorGUILayout.Space(); - - EditorGUILayout.LabelField("Settings", EditorStyles.boldLabel); - SettingsGui.Draw(); - - EditorGUILayout.Space(); - if (GUILayout.Button("Regenerate Now", GUILayout.Height(28))) - { - CodeGenerator.Run(new GenerateOptions - { - IsAutomatic = false, - PromptOnMassDeletion = true - }); - } - - using (new EditorGUILayout.HorizontalScope()) - { - if (GUILayout.Button("Open Output Folder", GUILayout.Height(26))) - OpenOutputFolder(); - if (GUILayout.Button("Run Setup Wizard", GUILayout.Height(26))) - SetupWizard.Open(); - } - - DrawLastResult(); - - EditorGUILayout.EndScrollView(); - } - - void DrawLastResult() - { - var result = CodeGenerator.LastResult; - if (result == null) - return; - - EditorGUILayout.Space(); - if (!result.Success) - { - EditorGUILayout.HelpBox( - string.IsNullOrEmpty(result.Error) ? "Generation failed." : result.Error, - MessageType.Error); - } - else - { - EditorGUILayout.HelpBox( - $"Last run: {result.Total} table class file(s) – {result.Written} written, " + - $"{result.Deleted} deleted, {result.Unchanged} unchanged.", - MessageType.Info); - } + SettingsGui.DrawToolbar(); - if (result.Warnings.Count == 0) - return; - - showWarnings = EditorGUILayout.Foldout(showWarnings, $"Warnings ({result.Warnings.Count})", true); - if (!showWarnings) - return; - - using (new EditorGUI.IndentLevelScope()) + scroll = EditorGUILayout.BeginScrollView(scroll); + using (new EditorGUILayout.VerticalScope(SettingsGui.PageStyle)) { - foreach (var warning in result.Warnings) - EditorGUILayout.LabelField(warning, EditorStyles.wordWrappedLabel); - } - } + EditorGUILayout.LabelField( + "Generates strongly typed C# classes from Unity Localization table collections: each " + + "collection becomes a class and each key a member, e.g. Ui.PlayerName.", + EditorStyles.wordWrappedMiniLabel); + EditorGUILayout.Space(); - static void OpenOutputFolder() - { - string folder; - string error; - if (!OutputPath.TryNormalize(CodegenSettings.instance.OutputFolder, out folder, out error)) - { - EditorUtility.DisplayDialog("Localization Codegen", error, "OK"); - return; - } + SettingsGui.DrawLastResult(ref showWarnings); + EditorGUILayout.Space(); - if (AssetDatabase.IsValidFolder(folder)) - { - var asset = AssetDatabase.LoadAssetAtPath(folder); - Selection.activeObject = asset; - EditorGUIUtility.PingObject(asset); - } - else - { - EditorUtility.RevealInFinder(Application.dataPath); + SettingsGui.Draw(); } + EditorGUILayout.EndScrollView(); } } } diff --git a/Unity-Package/Assets/root/Editor/SettingsGui.cs b/Unity-Package/Assets/root/Editor/SettingsGui.cs index 6cbb3fd..6e00da2 100644 --- a/Unity-Package/Assets/root/Editor/SettingsGui.cs +++ b/Unity-Package/Assets/root/Editor/SettingsGui.cs @@ -1,23 +1,138 @@ -using UnityEditor; +using System.Collections.Generic; +using System.IO; +using UnityEditor; using UnityEngine; namespace Severnbli.LocalizationCodegen.Editor { + /// Settings UI shared by the Project Settings page, the editor window and the setup wizard. static class SettingsGui { + const float LabelWidth = 220f; + const string FoldoutPrefKey = "LocalizationCodegen.Settings.Foldout."; + + /// Every label and tooltip, also used as search keywords for the Project Settings page. + internal static class Content + { + public static readonly GUIContent OutputSection = new GUIContent("Output"); + public static readonly GUIContent TablesSection = new GUIContent("Tables"); + public static readonly GUIContent MembersSection = new GUIContent("Generated Members"); + public static readonly GUIContent NamingSection = new GUIContent("Naming"); + public static readonly GUIContent AdvancedSection = new GUIContent("Advanced"); + + public static readonly GUIContent Namespace = new GUIContent("Namespace", + "Namespace of the generated classes. Leave empty for the global namespace."); + public static readonly GUIContent OutputFolder = new GUIContent("Output Folder", + "Folder (inside Assets) where generated .g.cs files are written."); + public static readonly GUIContent Browse = new GUIContent("Browse…", "Pick a folder inside Assets."); + + public static readonly GUIContent StringTables = new GUIContent("String Tables", + "Generate classes for string table collections. Disabling this deletes the matching generated files on the next run."); + public static readonly GUIContent AssetTables = new GUIContent("Asset Tables", + "Generate classes for asset table collections. Disabling this deletes the matching generated files on the next run."); + public static readonly GUIContent AutoRegenerate = new GUIContent("Regenerate On Changes", + "Automatically regenerate when table collections or entries change."); + + public static readonly GUIContent SmartStrings = new GUIContent("Smart Strings", + "Generate methods with parameters for smart string entries. Off keeps the 1.0 behaviour."); + public static readonly GUIContent SmartParamTypes = new GUIContent("Smart Parameter Types", + "Object uses object for every named parameter. Inferred uses int for plural and IEnumerable for list."); + public static readonly GUIContent References = new GUIContent("Generate Reference Members", + "Emit a nested Ref class with LocalizedString / LocalizedAsset references that follow locale changes."); + public static readonly GUIContent UniTask = new GUIContent("UniTask Members", + "Also emit ...Async members that return UniTask and accept a CancellationToken. Requires UniTask (com.cysharp.unitask)."); + public static readonly GUIContent XmlDocs = new GUIContent("XML Documentation", + "Emit XML doc comments containing the default locale text."); + + public static readonly GUIContent Naming = new GUIContent("Naming Convention", + "Keep preserves the 1.0 names. PascalCase turns 'player name' into 'PlayerName'."); + public static readonly GUIContent KeySeparators = new GUIContent("Key Separators", + "Optional characters that create nested classes, e.g. '/' makes 'Menu/Start' become Menu.Start."); + public static readonly GUIContent RuntimeAlias = new GUIContent("Use Runtime Alias", + "Reference the runtime helper through one file-level alias (__LT) instead of repeating the fully qualified name on every member."); + + public static readonly GUIContent GenerateAsmdef = new GUIContent("Generate .asmdef", + "Write an assembly definition into the output folder, so the generated code gets its own assembly."); + public static readonly GUIContent FailOnMismatch = new GUIContent("Fail CI On Smart String Mismatch", + "Make CheckBatch exit with a non-zero code when locales use different smart string placeholders."); + + public static IEnumerable Keywords() + { + foreach (var field in typeof(Content).GetFields()) + { + var content = field.GetValue(null) as GUIContent; + if (content != null && !string.IsNullOrEmpty(content.text)) + yield return content.text; + } + } + } + + static GUIStyle s_SectionBody; + static GUIStyle s_PageStyle; + + /// Page margins matching Unity's own settings pages. + public static GUIStyle PageStyle => s_PageStyle ?? (s_PageStyle = new GUIStyle + { + padding = new RectOffset(10, 10, 8, 8) + }); + + static GUIStyle SectionBody => s_SectionBody ?? (s_SectionBody = new GUIStyle + { + padding = new RectOffset(14, 4, 2, 6) + }); + public static bool Draw() { var s = CodegenSettings.instance; s.EnsureMigrated(); var oldSmartStrings = s.SmartStrings; + var oldLabelWidth = EditorGUIUtility.labelWidth; + EditorGUIUtility.labelWidth = LabelWidth; EditorGUI.BeginChangeCheck(); - EditorGUILayout.LabelField("Generated Code", EditorStyles.boldLabel); + Section("output", Content.OutputSection, () => DrawOutput(s)); + Section("tables", Content.TablesSection, () => DrawTables(s)); + Section("members", Content.MembersSection, () => DrawMembers(s)); + Section("naming", Content.NamingSection, () => DrawNaming(s)); + Section("advanced", Content.AdvancedSection, () => DrawAdvanced(s)); - s.Namespace = EditorGUILayout.DelayedTextField( - new GUIContent("Namespace", "Namespace of the generated classes. Leave empty for the global namespace."), - s.Namespace); + var changed = EditorGUI.EndChangeCheck(); + EditorGUIUtility.labelWidth = oldLabelWidth; + + if (changed) + { + s.SaveSettings(); + CodegenHooks.MarkDirtyExternal(); + + if (oldSmartStrings == SmartStringMode.Off && s.SmartStrings != SmartStringMode.Off) + CodeGenerator.LogPropertyToMethodChanges(); + } + + return changed; + } + + /// A collapsible section whose open state is remembered per user. + static void Section(string id, GUIContent title, System.Action body) + { + var key = FoldoutPrefKey + id; + var expanded = EditorPrefs.GetBool(key, true); + var nowExpanded = EditorGUILayout.BeginFoldoutHeaderGroup(expanded, title); + if (nowExpanded != expanded) + EditorPrefs.SetBool(key, nowExpanded); + + if (nowExpanded) + { + using (new EditorGUILayout.VerticalScope(SectionBody)) + body(); + } + + EditorGUILayout.EndFoldoutHeaderGroup(); + } + + static void DrawOutput(CodegenSettings s) + { + s.Namespace = EditorGUILayout.DelayedTextField(Content.Namespace, s.Namespace); var normalized = NamespaceUtil.Normalize(s.Namespace); if (normalized == null) @@ -33,104 +148,209 @@ public static bool Draw() using (new EditorGUILayout.HorizontalScope()) { - s.OutputFolder = EditorGUILayout.DelayedTextField( - new GUIContent("Output Folder", "Folder (inside Assets) where generated .g.cs files are written."), - s.OutputFolder); - if (GUILayout.Button("...", GUILayout.Width(30))) + var previous = s.OutputFolder; + s.OutputFolder = EditorGUILayout.DelayedTextField(Content.OutputFolder, s.OutputFolder); + if (s.OutputFolder != previous) + OnOutputFolderChanged(); + if (GUILayout.Button(Content.Browse, EditorStyles.miniButton, GUILayout.Width(70))) PickOutputFolder(s); } string folder; string folderError; if (!OutputPath.TryNormalize(s.OutputFolder, out folder, out folderError)) - EditorGUILayout.HelpBox(folderError, MessageType.Warning); + { + EditorGUILayout.HelpBox(folderError, MessageType.Error); + } else if (OutputPath.HasEditorSegment(folder)) + { EditorGUILayout.HelpBox( "The folder 'Editor' is part of the path. Generated runtime classes will compile into the editor " + "assembly and will not be available in player builds.", MessageType.Warning); + } + else + { + DrawOwningAssembly(s, folder); + } + } - EditorGUILayout.Space(); - EditorGUILayout.LabelField("Tables", EditorStyles.boldLabel); - - s.GenerateStringTables = EditorGUILayout.Toggle( - new GUIContent("String Tables", - "Generate classes for string table collections. Disabling this deletes the matching generated files on the next run."), - s.GenerateStringTables); - s.GenerateAssetTables = EditorGUILayout.Toggle( - new GUIContent("Asset Tables", - "Generate classes for asset table collections. Disabling this deletes the matching generated files on the next run."), - s.GenerateAssetTables); - s.AutoRegenerate = EditorGUILayout.Toggle( - new GUIContent("Regenerate On Changes", "Automatically regenerate when table collections or entries change."), - s.AutoRegenerate); - - EditorGUILayout.Space(); - EditorGUILayout.LabelField("Code Style", EditorStyles.boldLabel); - - s.UseRuntimeAlias = EditorGUILayout.Toggle( - new GUIContent("Use Runtime Alias", - "Reference the runtime helper through one file-level alias (__LT) instead of repeating the fully qualified name on every member."), - s.UseRuntimeAlias); - s.GenerateReferences = EditorGUILayout.Toggle( - new GUIContent("Generate Reference Members", - "Emit a nested Ref class with LocalizedString / LocalizedAsset references."), - s.GenerateReferences); - s.GenerateXmlDocs = EditorGUILayout.Toggle( - new GUIContent("XML Documentation", - "Emit XML doc comments containing the default locale text."), - s.GenerateXmlDocs); - - s.SmartStrings = (SmartStringMode)EditorGUILayout.EnumPopup( - new GUIContent("Smart Strings", - "Generate methods with parameters for smart string entries. Off keeps the 1.0 behaviour."), - s.SmartStrings); - s.SmartParamTypes = (SmartParamTypeMode)EditorGUILayout.EnumPopup( - new GUIContent("Smart Parameter Types", - "Object uses object for every named parameter. Inferred uses int for plural and IEnumerable for list."), - s.SmartParamTypes); - s.Naming = (NamingConvention)EditorGUILayout.EnumPopup( - new GUIContent("Naming Convention", - "Keep preserves the 1.0 names. PascalCase turns 'player name' into 'PlayerName'."), - s.Naming); - s.KeySeparators = EditorGUILayout.TextField( - new GUIContent("Key Separators", - "Optional characters that create nested classes, e.g. '/' makes 'Menu/Start' become Menu.Start."), - s.KeySeparators); - s.GenerateUniTask = EditorGUILayout.Toggle( - new GUIContent("UniTask Members", - "Also emit ...Async members that return UniTask and accept a CancellationToken. Requires UniTask (com.cysharp.unitask)."), - s.GenerateUniTask); - if (s.GenerateUniTask && !UniTaskSupport.IsAvailable) - EditorGUILayout.HelpBox(UniTaskSupport.MissingMessage, MessageType.Warning); + // --------------------------------------------------------------------------------------------------- + // Owning assembly definition + // --------------------------------------------------------------------------------------------------- - EditorGUILayout.Space(); - EditorGUILayout.LabelField("Advanced", EditorStyles.boldLabel); + static string s_OwnerCacheKey; + static OwningAssembly s_OwnerCache; + static bool s_ProjectChangeHooked; - s.GenerateAsmdef = EditorGUILayout.Toggle( - new GUIContent("Generate .asmdef", - "Write an assembly definition into the output folder so it can be placed below folders owned by another asmdef."), - s.GenerateAsmdef); - s.FailOnSmartStringMismatch = EditorGUILayout.Toggle( - new GUIContent("Fail CI On Smart String Mismatch", - "Make CheckBatch exit with a non-zero code when locales use different smart string placeholders."), - s.FailOnSmartStringMismatch); + /// The owning assembly of the configured folder, cached until the project or settings change. + static OwningAssembly CurrentOwner(CodegenSettings s, string folder) + { + if (!s_ProjectChangeHooked) + { + s_ProjectChangeHooked = true; + EditorApplication.projectChanged += () => s_OwnerCacheKey = null; + } - var changed = EditorGUI.EndChangeCheck(); - if (changed) + var required = AssemblyOwnership.RequiredReferences(s); + var key = folder + "|" + s.GenerateAsmdef + "|" + s.LastAsmdefPath + "|" + string.Join(",", required); + if (key != s_OwnerCacheKey) + { + s_OwnerCacheKey = key; + s_OwnerCache = s.GenerateAsmdef ? null : AssemblyOwnership.Find(folder, required, s.LastAsmdefPath); + } + return s_OwnerCache; + } + + static void DrawOwningAssembly(CodegenSettings s, string folder) + { + var owner = CurrentOwner(s, folder); + if (owner == null) + return; + + if (owner.MissingReferences.Count == 0) + { + EditorGUILayout.HelpBox($"Generated code compiles into the assembly '{owner.Name}'.", MessageType.Info); + return; + } + + EditorGUILayout.HelpBox(OwnerProblem(owner), MessageType.Warning); + using (new EditorGUILayout.HorizontalScope()) + { + GUILayout.FlexibleSpace(); + using (new EditorGUI.DisabledScope(!owner.IsEditable)) + { + if (GUILayout.Button("Add References", EditorStyles.miniButtonLeft)) + ApplyOwnerChoice(s, owner, addReferences: true); + } + if (GUILayout.Button("Use Separate .asmdef", EditorStyles.miniButtonRight)) + ApplyOwnerChoice(s, owner, addReferences: false); + } + } + + static string OwnerProblem(OwningAssembly owner) + { + var location = owner.AsmdefPath ?? "an unknown assembly definition"; + var via = owner.AsmrefPath != null ? $" through '{owner.AsmrefPath}'" : ""; + var text = $"The output folder belongs to the assembly '{owner.Name}' ({location}){via}. Generated code " + + "compiles into it, but it does not reference:\n- " + + string.Join("\n- ", owner.MissingReferences.ToArray()); + if (!owner.IsEditable) + text += "\n\nThat assembly definition is read-only, so use a separate .asmdef or another folder."; + return text; + } + + static void OnOutputFolderChanged() + { + // Dialogs cannot open in the middle of an IMGUI layout pass. + if (!Application.isBatchMode) + EditorApplication.delayCall += PromptForOwningAssembly; + } + + /// Asks how to make the generated code compile when the folder lies below another asmdef. + internal static void PromptForOwningAssembly() + { + var s = CodegenSettings.instance; + string folder; + string error; + if (s.GenerateAsmdef || !OutputPath.TryNormalize(s.OutputFolder, out folder, out error)) + return; + + var owner = AssemblyOwnership.Find(folder, AssemblyOwnership.RequiredReferences(s), s.LastAsmdefPath); + if (owner == null || owner.MissingReferences.Count == 0) + return; + + if (!owner.IsEditable) { + if (EditorUtility.DisplayDialog("Localization Codegen", OwnerProblem(owner), + "Use Separate .asmdef", "Not Now")) + ApplyOwnerChoice(s, owner, addReferences: false); + return; + } + + var choice = EditorUtility.DisplayDialogComplex( + "Localization Codegen", + OwnerProblem(owner) + $"\n\nAdd the missing references to {Path.GetFileName(owner.AsmdefPath)}, " + + "or give the generated code its own .asmdef?", + "Add References", + "Not Now", + "Use Separate .asmdef"); + + if (choice == 0) + ApplyOwnerChoice(s, owner, addReferences: true); + else if (choice == 2) + ApplyOwnerChoice(s, owner, addReferences: false); + } + + static void ApplyOwnerChoice(CodegenSettings s, OwningAssembly owner, bool addReferences) + { + if (addReferences) + { + if (AssemblyOwnership.AddMissingReferences(owner)) + Debug.Log($"[Localization Codegen] Added {string.Join(", ", owner.MissingReferences.ToArray())} " + + $"to {owner.AsmdefPath}."); + } + else + { + s.GenerateAsmdef = true; s.SaveSettings(); CodegenHooks.MarkDirtyExternal(); + } - if (oldSmartStrings == SmartStringMode.Off && s.SmartStrings != SmartStringMode.Off) - CodeGenerator.LogPropertyToMethodChanges(); + s_OwnerCacheKey = null; + } + + static void DrawTables(CodegenSettings s) + { + s.GenerateStringTables = EditorGUILayout.Toggle(Content.StringTables, s.GenerateStringTables); + s.GenerateAssetTables = EditorGUILayout.Toggle(Content.AssetTables, s.GenerateAssetTables); + s.AutoRegenerate = EditorGUILayout.Toggle(Content.AutoRegenerate, s.AutoRegenerate); + + if (!s.GenerateStringTables && !s.GenerateAssetTables) + EditorGUILayout.HelpBox("Both table kinds are off, so nothing will be generated.", MessageType.Warning); + } + + static void DrawMembers(CodegenSettings s) + { + s.SmartStrings = (SmartStringMode)EditorGUILayout.EnumPopup(Content.SmartStrings, s.SmartStrings); + using (new EditorGUI.DisabledScope(s.SmartStrings == SmartStringMode.Off)) + using (new EditorGUI.IndentLevelScope()) + { + s.SmartParamTypes = (SmartParamTypeMode)EditorGUILayout.EnumPopup(Content.SmartParamTypes, s.SmartParamTypes); } - return changed; + // MethodsAndRefs always emits the Ref class, so the toggle is shown as on and locked. + var refsForced = s.SmartStrings == SmartStringMode.MethodsAndRefs; + using (new EditorGUI.DisabledScope(refsForced)) + { + var value = EditorGUILayout.Toggle(Content.References, s.GenerateReferences || refsForced); + if (!refsForced) + s.GenerateReferences = value; + } + + s.GenerateUniTask = EditorGUILayout.Toggle(Content.UniTask, s.GenerateUniTask); + if (s.GenerateUniTask && !UniTaskSupport.IsAvailable) + EditorGUILayout.HelpBox(UniTaskSupport.MissingMessage, MessageType.Warning); + + s.GenerateXmlDocs = EditorGUILayout.Toggle(Content.XmlDocs, s.GenerateXmlDocs); + } + + static void DrawNaming(CodegenSettings s) + { + s.Naming = (NamingConvention)EditorGUILayout.EnumPopup(Content.Naming, s.Naming); + s.KeySeparators = EditorGUILayout.TextField(Content.KeySeparators, s.KeySeparators); + s.UseRuntimeAlias = EditorGUILayout.Toggle(Content.RuntimeAlias, s.UseRuntimeAlias); + } + + static void DrawAdvanced(CodegenSettings s) + { + s.GenerateAsmdef = EditorGUILayout.Toggle(Content.GenerateAsmdef, s.GenerateAsmdef); + s.FailOnSmartStringMismatch = EditorGUILayout.Toggle(Content.FailOnMismatch, s.FailOnSmartStringMismatch); } static void PickOutputFolder(CodegenSettings s) { + var previous = s.OutputFolder; var dataPath = (Application.dataPath ?? "").Replace('\\', '/').TrimEnd('/'); var picked = EditorUtility.OpenFolderPanel("Output Folder", dataPath, ""); if (string.IsNullOrEmpty(picked)) @@ -156,10 +376,97 @@ static void PickOutputFolder(CodegenSettings s) "OK"); } + // ExitGUI throws, so Draw never reaches its change check: save here. + if (s.OutputFolder != previous) + { + s.SaveSettings(); + CodegenHooks.MarkDirtyExternal(); + OnOutputFolderChanged(); + } + GUI.FocusControl(null); GUIUtility.ExitGUI(); } + /// Generation actions, drawn as an editor toolbar. + public static void DrawToolbar() + { + using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar)) + { + if (GUILayout.Button("Regenerate", EditorStyles.toolbarButton)) + CodeGenerator.Run(new GenerateOptions { IsAutomatic = false, PromptOnMassDeletion = true }); + if (GUILayout.Button("Verify", EditorStyles.toolbarButton)) + EditorApplication.ExecuteMenuItem("Tools/Localization Codegen/Verify (Dry run)"); + + GUILayout.FlexibleSpace(); + + if (GUILayout.Button("Open Output Folder", EditorStyles.toolbarButton)) + OpenOutputFolder(); + if (GUILayout.Button("Setup Wizard", EditorStyles.toolbarButton)) + SetupWizard.Open(); + } + } + + /// Summary of the last run, with its warnings in a foldout. + public static void DrawLastResult(ref bool showWarnings) + { + var result = CodeGenerator.LastResult; + if (result == null) + { + EditorGUILayout.HelpBox("Not generated in this session yet.", MessageType.None); + return; + } + + if (!result.Success) + { + EditorGUILayout.HelpBox( + string.IsNullOrEmpty(result.Error) ? "Generation failed." : result.Error, + MessageType.Error); + } + else + { + EditorGUILayout.HelpBox( + $"Last run: {result.Total} table class file(s) – {result.Written} written, " + + $"{result.Deleted} deleted, {result.Unchanged} unchanged.", + result.Warnings.Count > 0 ? MessageType.Warning : MessageType.Info); + } + + if (result.Warnings.Count == 0) + return; + + showWarnings = EditorGUILayout.Foldout(showWarnings, $"Warnings ({result.Warnings.Count})", true); + if (!showWarnings) + return; + + using (new EditorGUI.IndentLevelScope()) + { + foreach (var warning in result.Warnings) + EditorGUILayout.LabelField(warning, EditorStyles.wordWrappedLabel); + } + } + + static void OpenOutputFolder() + { + string folder; + string error; + if (!OutputPath.TryNormalize(CodegenSettings.instance.OutputFolder, out folder, out error)) + { + EditorUtility.DisplayDialog("Localization Codegen", error, "OK"); + return; + } + + if (AssetDatabase.IsValidFolder(folder)) + { + var asset = AssetDatabase.LoadAssetAtPath(folder); + Selection.activeObject = asset; + EditorGUIUtility.PingObject(asset); + } + else + { + EditorUtility.RevealInFinder(Application.dataPath); + } + } + public static bool IsOutputFolderValid(out string reason) => OutputPath.TryNormalize(CodegenSettings.instance.OutputFolder, out _, out reason); diff --git a/Unity-Package/Assets/root/README.md b/Unity-Package/Assets/root/README.md index 99d04c3..583083b 100644 --- a/Unity-Package/Assets/root/README.md +++ b/Unity-Package/Assets/root/README.md @@ -134,7 +134,7 @@ Add the scoped registry and the dependency to `Packages/manifest.json`: } ], "dependencies": { - "com.severnbli.localization-codegen": "1.2.0" + "com.severnbli.localization-codegen": "1.2.1" } } ``` @@ -319,7 +319,7 @@ Open **Project Settings > Localization Codegen**, or **Window > Localization Cod | Setting | Default | Description | |---|---|---| | Namespace | `Localization` | Namespace of generated classes. Empty or whitespace means the global namespace. | -| Output Folder | `Assets/Generated/Localization` | Must be inside `Assets`. Changing it removes generated files from the old folder. | +| Output Folder | `Assets/Generated/Localization` | Must be inside `Assets`. Changing it removes generated files from the old folder. Inside another `.asmdef`, you are offered to add the references the code needs. | | String Tables | on | Generate classes for string table collections. Disabling deletes the matching files on the next run. | | Asset Tables | on | Generate classes for asset table collections. Disabling deletes the matching files on the next run. | | Regenerate On Changes | on | Debounced automatic regeneration after table edits and external (VCS) changes. | @@ -331,7 +331,7 @@ Open **Project Settings > Localization Codegen**, or **Window > Localization Cod | Naming Convention | `Keep` | `Keep` or `PascalCase`. | | Key Separators | empty | Characters that create nested classes, e.g. `/`. | | UniTask Members | off | Also emit [`…Async` members](#unitask) returning `UniTask`. Requires UniTask. | -| Generate .asmdef | off | Write an assembly definition into the output folder. | +| Generate .asmdef | off | Write an assembly definition into the output folder, so the generated code gets its own assembly. | | Fail CI On Smart String Mismatch | off | Make `CheckBatch` fail on locale placeholder mismatches. | The window also has **Regenerate Now**, **Open Output Folder** and **Run Setup Wizard** buttons, and lists the warnings of the last run. @@ -360,7 +360,7 @@ For clean diffs, add this to `.gitattributes`: - Only files in the output folder whose first line is `// ` are created, overwritten or deleted. Don't edit generated files by hand. - A manifest in the project settings remembers the last output folder, so changing the folder or namespace does not leave duplicate types behind. -- If you move generated code into your own assembly definition, enable **Generate .asmdef**, or reference `Unity.Localization` and `com.severnbli.localization-codegen.Runtime` manually (plus `UniTask` and `com.severnbli.localization-codegen.UniTask` for UniTask members). +- If the output folder is inside one of your assembly definitions (directly or through an `.asmref`), the generated code compiles into that assembly, which must reference `com.severnbli.localization-codegen.Runtime` and `Unity.Localization` (plus `UniTask` and `com.severnbli.localization-codegen.UniTask` for UniTask members). When you pick such a folder you are asked to **Add References** to that `.asmdef` for you, or to **Use Separate .asmdef** (**Generate .asmdef**). The **Output** section keeps showing which assembly the code compiles into, and generation warns while references are missing. - The synchronous members block until the table is loaded and are not supported by Addressables on WebGL. Use [UniTask members](#unitask), or `LocalizedTables.GetStringAsync` / `GetAssetAsync`, there. - If `LocalizationSettings` are missing at runtime, generated members return the table key (and log once) instead of throwing. - The generator is editor-only; generated C# files have no runtime dependency on the generator assembly. diff --git a/Unity-Package/Assets/root/Tests/Editor/AssemblyOwnershipTests.cs b/Unity-Package/Assets/root/Tests/Editor/AssemblyOwnershipTests.cs new file mode 100644 index 0000000..c5f2c5f --- /dev/null +++ b/Unity-Package/Assets/root/Tests/Editor/AssemblyOwnershipTests.cs @@ -0,0 +1,284 @@ +using System; +using System.IO; +using System.Text; +using NUnit.Framework; +using UnityEditor; +using UnityEditor.Compilation; +using UnityEngine; + +namespace Severnbli.LocalizationCodegen.Editor.Tests +{ + public class AssemblyOwnershipTests + { + // Unity ignores folders ending with '~', so these asmdefs are never imported or compiled. + const string Root = "Assets/__LocalizationCodegenAsmdefTests~"; + + static readonly string[] s_Required = + { + AssemblyOwnership.RuntimeAssemblyName, + AssemblyOwnership.LocalizationAssemblyName + }; + + [Serializable] + sealed class AsmdefJson + { + public string name; + public string[] references; + public bool autoReferenced; + } + + [SetUp] + public void SetUp() + { + DeleteRoot(); + Directory.CreateDirectory(Root); + } + + [TearDown] + public void TearDown() + { + DeleteRoot(); + } + + static void DeleteRoot() + { + if (Directory.Exists(Root)) + Directory.Delete(Root, true); + } + + static string WriteFile(string path, string content, bool bom = false) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)); + File.WriteAllText(path, content, new UTF8Encoding(bom)); + return path; + } + + static string RuntimeGuid() + { + var path = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(AssemblyOwnership.RuntimeAssemblyName); + Assert.IsNotNull(path, "The runtime asmdef must be resolvable."); + return AssetDatabase.AssetPathToGUID(path); + } + + // --------------------------------------------------------------------------------------------------- + // Text editing + // --------------------------------------------------------------------------------------------------- + + [Test] + public void AddReferences_AppendsToAMultiLineArray() + { + const string json = + "{\n \"name\": \"Game\",\n \"references\": [\n \"Unity.TextMeshPro\"\n ],\n \"autoReferenced\": true\n}\n"; + + var updated = AssemblyOwnership.AddReferences(json, new[] { "A", "B" }); + + Assert.AreEqual( + "{\n \"name\": \"Game\",\n \"references\": [\n \"Unity.TextMeshPro\",\n \"A\",\n \"B\"\n ],\n \"autoReferenced\": true\n}\n", + updated); + } + + [Test] + public void AddReferences_FillsAnEmptyArray() + { + const string json = "{\n \"name\": \"Game\",\n \"references\": [],\n \"autoReferenced\": true\n}\n"; + + var updated = AssemblyOwnership.AddReferences(json, new[] { "A" }); + + Assert.AreEqual( + "{\n \"name\": \"Game\",\n \"references\": [\n \"A\"\n ],\n \"autoReferenced\": true\n}\n", + updated); + } + + [Test] + public void AddReferences_CreatesTheArrayWhenMissing() + { + const string json = "{\n \"name\": \"Game\"\n}\n"; + + var updated = AssemblyOwnership.AddReferences(json, new[] { "A" }); + + Assert.AreEqual("{\n \"references\": [\n \"A\"\n ],\n \"name\": \"Game\"\n}\n", updated); + var parsed = JsonUtility.FromJson(updated); + Assert.AreEqual("Game", parsed.name); + CollectionAssert.AreEqual(new[] { "A" }, parsed.references); + } + + [Test] + public void AddReferences_KeepsASingleLineArrayOnOneLine() + { + const string json = "{ \"name\": \"Game\", \"references\": [\"X\"] }"; + + Assert.AreEqual( + "{ \"name\": \"Game\", \"references\": [\"X\", \"A\"] }", + AssemblyOwnership.AddReferences(json, new[] { "A" })); + } + + [Test] + public void AddReferences_KeepsCrLfAndTabs() + { + const string json = "{\r\n\t\"name\": \"Game\",\r\n\t\"references\": []\r\n}"; + + var updated = AssemblyOwnership.AddReferences(json, new[] { "A" }); + + Assert.AreEqual("{\r\n\t\"name\": \"Game\",\r\n\t\"references\": [\r\n\t\t\"A\"\r\n\t]\r\n}", updated); + } + + [Test] + public void AddReferences_DoesNotTouchOtherArraysOrFields() + { + const string json = + "{\n \"name\": \"Game\",\n \"references\": [\n \"X\"\n ],\n \"includePlatforms\": [],\n" + + " \"versionDefines\": [\n {\n \"name\": \"com.unity.ugui\",\n \"expression\": \"\",\n" + + " \"define\": \"HAS_UGUI\"\n }\n ]\n}\n"; + + var updated = AssemblyOwnership.AddReferences(json, new[] { "A" }); + + StringAssert.Contains("\"X\",\n \"A\"\n ],\n \"includePlatforms\": [],", updated); + StringAssert.Contains("\"name\": \"com.unity.ugui\"", updated); + var parsed = JsonUtility.FromJson(updated); + Assert.AreEqual("Game", parsed.name); + CollectionAssert.AreEqual(new[] { "X", "A" }, parsed.references); + } + + // --------------------------------------------------------------------------------------------------- + // Lookup + // --------------------------------------------------------------------------------------------------- + + [Test] + public void Find_ReturnsNull_WhenNoAsmdefOwnsTheFolder() + { + Assert.IsNull(AssemblyOwnership.Find(Root + "/Generated/Localization", s_Required)); + } + + [Test] + public void Find_ReturnsTheNearestAsmdefAndItsMissingReferences() + { + WriteFile(Root + "/Game/Game.asmdef", "{ \"name\": \"Game\", \"references\": [\"Unity.Localization\"] }"); + WriteFile(Root + "/Game/Ui/Game.Ui.asmdef", "{ \"name\": \"Game.Ui\", \"references\": [] }"); + + // The folder does not exist yet; the lookup still walks up from it. + var owner = AssemblyOwnership.Find(Root + "/Game/Ui/Generated", s_Required); + + Assert.IsNotNull(owner); + Assert.AreEqual("Game.Ui", owner.Name); + Assert.AreEqual(Root + "/Game/Ui/Game.Ui.asmdef", owner.AsmdefPath); + Assert.IsNull(owner.AsmrefPath); + Assert.IsTrue(owner.IsEditable); + CollectionAssert.AreEqual(s_Required, owner.MissingReferences); + + var outer = AssemblyOwnership.Find(Root + "/Game/Generated", s_Required); + Assert.AreEqual("Game", outer.Name); + CollectionAssert.AreEqual(new[] { AssemblyOwnership.RuntimeAssemblyName }, outer.MissingReferences); + } + + [Test] + public void Find_SkipsTheAsmdefWrittenByTheGenerator() + { + var generated = WriteFile(Root + "/Out/Localization.Generated.asmdef", "{ \"name\": \"Localization.Generated\" }"); + + Assert.IsNull(AssemblyOwnership.Find(Root + "/Out", s_Required, Path.GetFullPath(generated))); + Assert.IsNotNull(AssemblyOwnership.Find(Root + "/Out", s_Required)); + } + + [Test] + public void Find_ResolvesGuidReferences() + { + WriteFile(Root + "/Game/Game.asmdef", + "{ \"name\": \"Game\", \"references\": [\"GUID:" + RuntimeGuid() + "\", \"Unity.Localization\"] }"); + + var owner = AssemblyOwnership.Find(Root + "/Game", s_Required); + + CollectionAssert.IsEmpty(owner.MissingReferences); + } + + [Test] + public void Find_FollowsAnAsmrefByNameAndByGuid() + { + WriteFile(Root + "/ByName/Extension.asmref", "{ \"reference\": \"" + AssemblyOwnership.RuntimeAssemblyName + "\" }"); + WriteFile(Root + "/ByGuid/Extension.asmref", "{ \"reference\": \"GUID:" + RuntimeGuid() + "\" }"); + + foreach (var folder in new[] { "ByName", "ByGuid" }) + { + var owner = AssemblyOwnership.Find(Root + "/" + folder, s_Required); + + Assert.IsNotNull(owner, folder); + Assert.AreEqual(AssemblyOwnership.RuntimeAssemblyName, owner.Name, folder); + Assert.AreEqual(Root + "/" + folder + "/Extension.asmref", owner.AsmrefPath, folder); + StringAssert.EndsWith(".asmdef", owner.AsmdefPath, folder); + // The runtime asmdef references Unity.Localization and is the other required assembly itself. + CollectionAssert.IsEmpty(owner.MissingReferences, folder); + } + } + + [Test] + public void Find_ReportsAnAsmrefToAnUnknownAssembly() + { + WriteFile(Root + "/Broken/Broken.asmref", "{ \"reference\": \"Does.Not.Exist\" }"); + + var owner = AssemblyOwnership.Find(Root + "/Broken", s_Required); + + Assert.AreEqual("Does.Not.Exist", owner.Name); + Assert.IsNull(owner.AsmdefPath); + Assert.IsFalse(AssemblyOwnership.AddMissingReferences(owner, false)); + } + + [Test] + public void RequiredReferences_IncludeUniTaskOnlyWhenRequested() + { + CollectionAssert.AreEqual(s_Required, AssemblyOwnership.RequiredReferences(false)); + CollectionAssert.AreEqual( + new[] + { + AssemblyOwnership.RuntimeAssemblyName, + AssemblyOwnership.LocalizationAssemblyName, + UniTaskSupport.RuntimeAssemblyName, + UniTaskSupport.UniTaskAssemblyName + }, + AssemblyOwnership.RequiredReferences(true)); + } + + // --------------------------------------------------------------------------------------------------- + // Writing + // --------------------------------------------------------------------------------------------------- + + [Test] + public void AddMissingReferences_WritesNamesAndKeepsTheBom() + { + var path = WriteFile(Root + "/Game/Game.asmdef", + "{\n \"name\": \"Game\",\n \"references\": []\n}\n", bom: true); + var owner = AssemblyOwnership.Find(Root + "/Game", s_Required); + + Assert.IsTrue(AssemblyOwnership.AddMissingReferences(owner, false)); + + var bytes = File.ReadAllBytes(path); + Assert.AreEqual(new byte[] { 0xEF, 0xBB, 0xBF }, new[] { bytes[0], bytes[1], bytes[2] }, "The BOM must be kept."); + CollectionAssert.IsEmpty(AssemblyOwnership.Find(Root + "/Game", s_Required).MissingReferences); + StringAssert.Contains("\"" + AssemblyOwnership.RuntimeAssemblyName + "\"", File.ReadAllText(path)); + } + + [Test] + public void AddMissingReferences_UsesGuidsWhenTheAsmdefDoes() + { + var path = WriteFile(Root + "/Game/Game.asmdef", + "{\n \"name\": \"Game\",\n \"references\": [\n \"GUID:" + RuntimeGuid() + "\"\n ]\n}\n"); + var owner = AssemblyOwnership.Find(Root + "/Game", s_Required); + CollectionAssert.AreEqual(new[] { AssemblyOwnership.LocalizationAssemblyName }, owner.MissingReferences); + + Assert.IsTrue(AssemblyOwnership.AddMissingReferences(owner, false)); + + var references = JsonUtility.FromJson(File.ReadAllText(path)).references; + Assert.AreEqual(2, references.Length); + StringAssert.StartsWith("GUID:", references[1]); + CollectionAssert.IsEmpty(AssemblyOwnership.Find(Root + "/Game", s_Required).MissingReferences); + } + + [Test] + public void AddMissingReferences_DoesNothingWhenComplete() + { + WriteFile(Root + "/Game/Game.asmdef", + "{ \"name\": \"Game\", \"references\": [\"" + AssemblyOwnership.RuntimeAssemblyName + "\", \"Unity.Localization\"] }"); + var owner = AssemblyOwnership.Find(Root + "/Game", s_Required); + + Assert.IsFalse(AssemblyOwnership.AddMissingReferences(owner, false)); + } + } +} diff --git a/Unity-Package/Assets/root/Tests/Editor/AssemblyOwnershipTests.cs.meta b/Unity-Package/Assets/root/Tests/Editor/AssemblyOwnershipTests.cs.meta new file mode 100644 index 0000000..14a53a0 --- /dev/null +++ b/Unity-Package/Assets/root/Tests/Editor/AssemblyOwnershipTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 54c6f07e93f0485aaeb5cc5b41b702e0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs b/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs index c4f9687..236f29c 100644 --- a/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs +++ b/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs @@ -63,6 +63,9 @@ static IEnumerator Compile(bool uniTask) } } + // AssemblyBuilder is obsolete from Unity 6.5 (CS0618) but still the only in-editor way to compile with + // Unity's own compiler and references; replace it once Unity ships the Roslyn-based alternative. +#pragma warning disable CS0618 var builder = new AssemblyBuilder(Path.Combine(folder, "CompileCheck.dll"), sources.ToArray()) { referencesOptions = ReferencesOptions.UseEngineModules, @@ -79,6 +82,8 @@ static IEnumerator Compile(bool uniTask) } }; +#pragma warning restore CS0618 + CompilerMessage[] messages = null; builder.buildFinished += (_, result) => messages = result; diff --git a/Unity-Package/Assets/root/package.json b/Unity-Package/Assets/root/package.json index 97f6479..f068154 100644 --- a/Unity-Package/Assets/root/package.json +++ b/Unity-Package/Assets/root/package.json @@ -10,7 +10,7 @@ "Generation", "Code Generation" ], - "version": "1.2.0", + "version": "1.2.1", "unity": "2021.3", "description": "C# classes and properties generator from Unity Localization tables", "documentationUrl": "https://github.com/Severnbli/localization-codegen/blob/main/README.md",