diff --git a/CHANGELOG.md b/CHANGELOG.md index facfebf..b930378 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## [1.2.0] - 2026-10-24 + +### Added +- Optional UniTask support. Enable **UniTask Members** to emit a `...Async` method returning `UniTask` next to + every string and asset member, with a `CancellationToken` and the same smart string parameters. +- `LocalizedTablesUniTask` (`GetStringAsync`, `GetAssetAsync`) and the `LocalizedString.GetLocalizedStringUniTask()` + extension in the optional `com.severnbli.localization-codegen.UniTask` assembly, which compiles only when UniTask + (`com.cysharp.unitask`) is installed or `LOCALIZATION_CODEGEN_UNITASK` is defined. +- Editor tests compile the generated code with Unity's compiler, with warnings as errors. + +### Fixed +- `Ref` members of asset table entries did not compile: `LocalizedSprite`, `LocalizedAsset` and the other + localized asset types have no `(table, entry)` constructor. + ## [1.1.1] - 2026-10-24 ### Fixed diff --git a/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs b/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs index 6605419..4f8fadf 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.1.1"; + public const string Version = "1.2.0"; static Installer() { diff --git a/README.md b/README.md index 593d64b..f4e5741 100644 --- a/README.md +++ b/README.md @@ -19,22 +19,34 @@ Unity 2021.3+ + + UniTask optional + MIT License

+

+ Quick start • + Installation • + Usage • + Settings • + CI • + Changelog +

+ --- ## Overview -Localization Codegen reads your [Unity Localization](https://docs.unity3d.com/Packages/com.unity.localization@1.5/manual/index.html) table collections and generates plain C# classes for them — one static class per collection, one property per key. No runtime reflection, no string lookups in your game code, and full autocomplete plus compile-time safety. +Localization Codegen reads your [Unity Localization](https://docs.unity3d.com/Packages/com.unity.localization@1.5/manual/index.html) table collections and generates plain C# classes for them — one static class per collection, one member per key. No runtime reflection, no string lookups in your game code, and full autocomplete plus compile-time safety. ```csharp // Before -label.text = localizationDatabase.GetLocalizedString("Ui", "HelloWorld"); +label.text = LocalizationSettings.StringDatabase.GetLocalizedString("Ui", "HelloWorld"); // After label.text = Ui.HelloWorld; @@ -42,10 +54,32 @@ label.text = Ui.HelloWorld; | Feature | Description | |---|---| -| 🪄 **First-run wizard** | A setup wizard opens automatically after the package is first imported | -| 🧩 **Typed access** | One static class per string or asset table collection, one property per key | -| 🔁 **Automatic regeneration** | Regenerates when table collections, tables or entries change | -| 🛠️ **Editor tooling** | Dedicated window with manual regeneration and settings | +| 🧩 **Typed access** | One static class per string or asset table collection, one member per key | +| 💬 **Smart strings** | Entries with placeholders become methods with typed positional and named parameters | +| 🔗 **Reference members** | Optional `Ref` class with `LocalizedString` / `LocalizedAsset` references that follow locale changes | +| ⚡ **UniTask** | Optional `…Async` members returning `UniTask`, with cancellation | +| 🔁 **Automatic regeneration** | Debounced regeneration after table edits, including changes pulled from version control | +| 🧪 **CI ready** | Batch mode entry points to regenerate, or to fail when generated code is out of date | +| 🪄 **First-run wizard** | A setup wizard opens after the package is first imported | + +## Quick start + +1. Install the package with [OpenUPM](#option-1--openupm-recommended): + + ```bash + openupm add com.severnbli.localization-codegen + ``` + +2. Finish the setup wizard. It picks a namespace and an output folder and runs the first generation. +3. Use the generated classes: + + ```csharp + using Localization; + + label.text = Ui.HelloWorld; + ``` + +Edit your tables as usual — the classes regenerate on their own. ## Installation @@ -78,6 +112,7 @@ The package is published on [OpenUPM](https://openupm.com/packages/com.severnbli 3. Switch back to Unity. The package resolves, compiles, and the setup wizard opens. +> [!TIP] > `openupm add` handles the scoped registry, dependency resolution and `manifest.json` changes for you. You can also add the package from **Window > Package Manager** if the OpenUPM registry is already configured.
@@ -99,7 +134,7 @@ Add the scoped registry and the dependency to `Packages/manifest.json`: } ], "dependencies": { - "com.severnbli.localization-codegen": "1.1.1" + "com.severnbli.localization-codegen": "1.2.0" } } ``` @@ -149,24 +184,32 @@ This variant bypasses Package Manager, so **versioning is manual**: |---|---| | Unity | 2021.3 or newer | | `com.unity.localization` | 1.5.x (automatic with the UPM variants, manual with the standard `.unitypackage`) | +| `com.cysharp.unitask` | 2.x, optional — only for [UniTask members](#unitask) | ## Usage +### Generated classes + Given a string table collection named `Ui` containing the key `HelloWorld`, the generator produces `Ui.g.cs`: ```csharp +// +// Table collection: Ui +using __LT = global::Severnbli.LocalizationCodegen.LocalizedTables; + namespace Localization { public static class Ui { public const string TableName = "Ui"; - public static string HelloWorld => - LocalizedTables.GetString(TableName, "HelloWorld"); + public static string HelloWorld => __LT.GetString(TableName, "HelloWorld"); } } ``` +The `__LT` alias is declared once per file. All other types (`LocalizedString`, asset types, `Dictionary<,>`) stay fully `global::`-qualified, so your own types can never shadow them. + Use it anywhere from your game code: ```csharp @@ -175,44 +218,152 @@ using Localization; label.text = Ui.HelloWorld; ``` -For **asset table collections**, each property is typed from the entry's asset type (falling back to `UnityEngine.Object`) and returns the localized asset: +For **asset table collections**, each member is typed from the entry's asset type (falling back to `UnityEngine.Object`) and returns the localized asset: ```csharp Sprite icon = Icons.Sword; ``` -For strings with arguments or smart strings, use `LocalizedTables.GetString(Ui.TableName, "Key", args)`. - ### Naming rules -Generated identifiers stay valid C#: +Generated identifiers always stay valid C#: - Invalid characters become `_`. - Names starting with a digit get a `_` prefix. - C# keywords get an `@` prefix. -- Collisions get a numeric suffix. +- Collisions get a numeric suffix, assigned by entry id so older keys keep their names. +- Class names collide case-insensitively (`Ui` and `UI` get separate files on Windows/macOS). +- Reserved names (`System`, `UnityEngine`, `Unity`, the first namespace segment, …) get a `Table` suffix. +- Windows device names (`CON`, `NUL`, `COM1`, …) get a trailing `_`. + +With **Naming Convention = PascalCase** and optional **Key Separators**, `player name` becomes `PlayerName` and `Menu/Start` becomes the nested class `Menu.Start`. These options are off by default, so upgraded projects keep their existing API. + +### Smart strings + +Enable **Smart Strings = Methods** to turn entries that need arguments into methods: + +```csharp +// "{0}, you have {count:plural:one item|{} items}" +public static string Greeting(object arg0, int count) + => __LT.GetStringMixed(TableName, "Greeting", new object[] { arg0 }, + new global::System.Collections.Generic.Dictionary { ["count"] = count }); +``` + +- Positional placeholders (`{0}`) become `arg0`, `arg1`, … (gaps are filled). +- Named placeholders (`{player-name}`, `{player.Name}`) become camelCase parameters. The original name is preserved for the runtime lookup. +- `{}` (the current value inside a formatter) is not a parameter. +- Variables provided by a **Global Variables Group** are not parameters; Unity resolves them. +- **Smart Parameter Types = Inferred** uses `int` for `plural`, `IEnumerable` for `list`, otherwise `object`. +- Placeholder differences between locales are reported as warnings. Enable **Fail CI On Smart String Mismatch** to make `CheckBatch` fail on them. +- **MethodsAndRefs** additionally emits `Ref.Greeting(...)` returning a `LocalizedString` whose arguments and local variables are set. + +> [!NOTE] +> Smart strings are opt-in. Upgraded projects default to `Off`; new projects default to `Methods` when the setup wizard completes. + +### Reference members + +The regular members return a **value**: `Ui.HelloWorld` is the text in the current locale at the moment you read it. When the player switches language, a label you filled that way keeps the old text. + +Enable **Generate Reference Members** to also get a nested `Ref` class that returns a **reference** to the entry instead — Unity's own `LocalizedString` (or `LocalizedAsset` for asset tables), which knows which entry it points at and can follow locale changes: + +```csharp +public static class Ref +{ + public static global::UnityEngine.Localization.LocalizedString HelloWorld + => new global::UnityEngine.Localization.LocalizedString(TableName, "HelloWorld"); +} +``` + +Use it wherever Unity Localization expects a reference — still without magic strings: + +```csharp +// A LocalizeStringEvent component updates its label whenever the locale changes. +localizeStringEvent.StringReference = Ui.Ref.HelloWorld; + +// Or react to locale changes yourself. +var title = Ui.Ref.HelloWorld; +title.StringChanged += text => label.text = text; +``` + +Asset entries use `LocalizedSprite`, `LocalizedAudioClip`, `LocalizedAsset` and the other built-in localized asset types when available. Each access creates a new reference, so keep the one you subscribed to. + +### UniTask + +Install [UniTask](https://github.com/Cysharp/UniTask) (`com.cysharp.unitask` 2.x) and enable **UniTask Members** to emit an awaitable variant next to every member: + +```csharp +public static string HelloWorld => __LT.GetString(TableName, "HelloWorld"); + +public static global::Cysharp.Threading.Tasks.UniTask HelloWorldAsync(global::System.Threading.CancellationToken cancellationToken = default) + => global::Severnbli.LocalizationCodegen.LocalizedTablesUniTask.GetStringAsync(TableName, "HelloWorld", cancellationToken); +``` + +```csharp +label.text = await Ui.HelloWorldAsync(this.GetCancellationTokenOnDestroy()); +Sprite icon = await Icons.SwordAsync(); +``` + +- The async members never block on table loading, so they also work where synchronous loads are not supported (WebGL). +- Smart string methods keep their parameters (`await Ui.GreetingAsync(player, count)`), and asset entries return `UniTask`. +- Cancelling stops the wait; Localization still finishes loading the table in the background. +- Turning the option on never renames existing members. A key that already ends in `Async` keeps its name, and the generated variant gets a suffix (`TitleAsync_2`). +- `LocalizedString.GetLocalizedStringUniTask()` awaits any `LocalizedString`, including `Ref` members. + +> [!IMPORTANT] +> The API lives in the optional `com.severnbli.localization-codegen.UniTask` assembly, which compiles only when UniTask is installed as a package. If UniTask lives under `Assets/`, add the scripting define `LOCALIZATION_CODEGEN_UNITASK`. Without that assembly the option is skipped with a warning, because the generated code would not compile. ## Settings -Open **Window > Localization Codegen**. Settings are stored in `ProjectSettings/LocalizationCodegenSettings.asset`. +Open **Project Settings > Localization Codegen**, or **Window > Localization Codegen** for the standalone window. Settings are stored in `ProjectSettings/LocalizationCodegenSettings.asset`. | Setting | Default | Description | |---|---|---| -| Namespace | `Localization` | Namespace of generated classes (leave empty for the global namespace). | -| Output Folder | `Assets/Generated/Localization` | Must be inside `Assets`. | -| String Tables | on | Generate classes for string table collections. | -| Asset Tables | on | Generate classes for asset table collections. | -| Regenerate On Changes | on | Regenerate automatically when collections change. | +| 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. | +| 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. | +| Use Runtime Alias | on | Emit one `using __LT = ...;` instead of repeating the runtime type on every member. | +| Generate Reference Members | off | Emit the nested [`Ref` class](#reference-members). | +| XML Documentation | off | Add XML docs with the default locale text and smart string parameters. | +| Smart Strings | off (upgraded) / `Methods` (new) | `Off`, `Methods` or `MethodsAndRefs`. | +| Smart Parameter Types | `Object` | `Object` or `Inferred`. | +| 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. | +| 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. + +## CI / batch mode + +```bash +# Regenerate and fail on any error +Unity -batchmode -nographics -projectPath . \ + -executeMethod Severnbli.LocalizationCodegen.Editor.CodeGenerator.GenerateBatch + +# Verify that generated code is up to date (no files are written) +Unity -batchmode -nographics -projectPath . \ + -executeMethod Severnbli.LocalizationCodegen.Editor.CodeGenerator.CheckBatch +``` + +`CheckBatch` compares the generated files on disk with the tables, so it also catches generated files that were edited by hand. The same actions are available under **Tools > Localization Codegen > Regenerate** and **Tools > Localization Codegen > Verify (Dry run)**. The setup wizard is never opened in batch mode. -Buttons: +For clean diffs, add this to `.gitattributes`: -- **Regenerate Now** — regenerate the code immediately. -- **Run Setup Wizard** — reopen the first-run wizard. +```gitattributes +*.g.cs text eol=lf +``` ## Good to know - Only files in the output folder whose first line is `// ` are created, overwritten or deleted. Don't edit generated files by hand. -- If you move generated code into your own assembly definition, reference `Unity.Localization` and `com.severnbli.localization-codegen.Runtime`. +- 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). +- 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. ## License diff --git a/Unity-Package/Assets/root/CHANGELOG.md b/Unity-Package/Assets/root/CHANGELOG.md index 0d92154..b930378 100644 --- a/Unity-Package/Assets/root/CHANGELOG.md +++ b/Unity-Package/Assets/root/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## [1.2.0] - 2026-10-24 + +### Added +- Optional UniTask support. Enable **UniTask Members** to emit a `...Async` method returning `UniTask` next to + every string and asset member, with a `CancellationToken` and the same smart string parameters. +- `LocalizedTablesUniTask` (`GetStringAsync`, `GetAssetAsync`) and the `LocalizedString.GetLocalizedStringUniTask()` + extension in the optional `com.severnbli.localization-codegen.UniTask` assembly, which compiles only when UniTask + (`com.cysharp.unitask`) is installed or `LOCALIZATION_CODEGEN_UNITASK` is defined. +- Editor tests compile the generated code with Unity's compiler, with warnings as errors. + +### Fixed +- `Ref` members of asset table entries did not compile: `LocalizedSprite`, `LocalizedAsset` and the other + localized asset types have no `(table, entry)` constructor. + ## [1.1.1] - 2026-10-24 ### Fixed @@ -66,4 +80,4 @@ ### Added - Initial release of the Unity package. - Added core functionality for A, B, and C. -- Included documentation and example scenes. \ No newline at end of file +- Included documentation and example scenes. diff --git a/Unity-Package/Assets/root/Editor/CodeEmitter.cs b/Unity-Package/Assets/root/Editor/CodeEmitter.cs index 43e9c90..913109c 100644 --- a/Unity-Package/Assets/root/Editor/CodeEmitter.cs +++ b/Unity-Package/Assets/root/Editor/CodeEmitter.cs @@ -14,6 +14,9 @@ internal static class CodeEmitter const string AssetObject = "global::UnityEngine.Object"; const string LocalizedStringType = "global::UnityEngine.Localization.LocalizedString"; const string LocalizedAssetType = "global::UnityEngine.Localization.LocalizedAsset"; + const string UniTaskType = "global::Cysharp.Threading.Tasks.UniTask"; + const string CancellationTokenType = "global::System.Threading.CancellationToken"; + const string CancellationTokenName = "cancellationToken"; /// Assigns deterministic, collision-free class names to every model. public static void AssignClassNames(IList models, EmitOptions options) @@ -116,6 +119,7 @@ sealed class Scope public readonly List Entries = new List(); public readonly Dictionary RawMemberNames = new Dictionary(); public readonly Dictionary MemberNames = new Dictionary(); + public readonly Dictionary AsyncMemberNames = new Dictionary(); public readonly HashSet MemberUsed = new HashSet(StringComparer.Ordinal); } @@ -209,6 +213,20 @@ static void AssignMemberNames(Scope scope, EmitOptions options) scope.MemberNames[entry] = CodegenText.Unique(pair.Key, scope.MemberUsed); } + // Async names are claimed after every key's own name, so adding UniTask members never renames an + // existing member. A key that already ends in "Async" pushes the generated variant to a suffix. + if (options.UniTask) + { + var byId = scope.Entries + .OrderBy(e => e.Id) + .ThenBy(e => e.Key, StringComparer.Ordinal); + foreach (var entry in byId) + { + scope.AsyncMemberNames[entry] = + CodegenText.Unique(scope.MemberNames[entry].TrimStart('@') + "Async", scope.MemberUsed); + } + } + foreach (var child in scope.Children) AssignMemberNames(child, options); } @@ -240,6 +258,13 @@ static void EmitScope(StringBuilder sb, Scope scope, TableModel model, EmitOptio { sb.Append('\n'); EmitEntry(sb, entry, scope.MemberNames[entry], options, level + 1); + + string asyncName; + if (scope.AsyncMemberNames.TryGetValue(entry, out asyncName)) + { + sb.Append('\n'); + EmitAsyncEntry(sb, entry, asyncName, options, level + 1); + } } if (isRoot && options.Refs) @@ -294,6 +319,55 @@ static void EmitEntry(StringBuilder sb, EntryModel entry, string name, EmitOptio static bool IsAssetEntry(EntryModel entry) => entry.AssetTypeName != null; + /// Emits the UniTask variant of an entry, mirroring the parameters of its synchronous member. + static void EmitAsyncEntry(StringBuilder sb, EntryModel entry, string name, EmitOptions options, int level) + { + if (options.XmlDocs && !string.IsNullOrEmpty(entry.Preview)) + EmitSummary(sb, entry.Preview, level); + + var runtime = EmitOptions.UniTaskRuntimeTypeName; + if (IsAssetEntry(entry)) + { + var type = string.IsNullOrEmpty(entry.AssetTypeName) ? AssetObject : entry.AssetTypeName; + sb.Append(Indent(level)).Append("public static ").Append(UniTaskType).Append('<').Append(type).Append("> ") + .Append(name).Append('(').Append(CancellationTokenType).Append(' ').Append(CancellationTokenName) + .Append(" = default)\n"); + sb.Append(Indent(level)).Append(" => ").Append(runtime).Append(".GetAssetAsync<").Append(type) + .Append(">(TableName, ").Append(CodegenText.Literal(entry.Key)).Append(", ") + .Append(CancellationTokenName).Append(");\n"); + return; + } + + var withParams = options.SmartStrings != SmartStringMode.Off && entry.Params.Count > 0; + var positional = withParams + ? entry.Params.Where(p => p.IsPositional).OrderBy(p => p.Index).ToList() + : new List(); + var named = withParams + ? entry.Params.Where(p => !p.IsPositional).OrderBy(p => p.SourceName, StringComparer.Ordinal).ToList() + : new List(); + + // A smart string variable may itself be called cancellationToken. + var parameterNames = new HashSet(entry.Params.Select(p => p.ClrName.TrimStart('@')), StringComparer.Ordinal); + var tokenName = withParams ? CodegenText.Unique(CancellationTokenName, parameterNames) : CancellationTokenName; + + if (withParams) + { + EmitParameterDocs(sb, positional, named, level); + sb.Append(Indent(level)).Append("/// Stops waiting for the table to load.\n"); + } + + var parameters = ParameterList(positional, named); + sb.Append(Indent(level)).Append("public static ").Append(UniTaskType).Append(" ").Append(name).Append('(') + .Append(parameters).Append(parameters.Length > 0 ? ", " : "") + .Append(CancellationTokenType).Append(' ').Append(tokenName).Append(" = default)\n"); + sb.Append(Indent(level)).Append(" => ").Append(runtime).Append(".GetStringAsync(TableName, ") + .Append(CodegenText.Literal(entry.Key)).Append(", "); + if (withParams) + sb.Append(PositionalArray(positional)).Append(", ").Append(NamedDictionary(named)).Append(", "); + sb.Append(tokenName).Append(");\n"); + } + static void EmitRefClass(StringBuilder sb, TableModel model, EmitOptions options, int level) { var strict = !string.IsNullOrEmpty(options.KeySeparators); @@ -347,10 +421,12 @@ static void EmitRefClass(StringBuilder sb, TableModel model, EmitOptions options } else { + // Unlike LocalizedString, LocalizedAsset types only have a parameterless constructor. var type = string.IsNullOrEmpty(entry.AssetTypeName) ? AssetObject : entry.AssetTypeName; sb.Append(Indent(level + 1)).Append("public static ").Append(GetLocalizedAssetType(type)).Append(' ') .Append(name).Append(" => new ").Append(GetLocalizedAssetType(type)) - .Append("(TableName, ").Append(CodegenText.Literal(entry.Key)).Append(");\n"); + .Append(" { TableReference = TableName, TableEntryReference = ") + .Append(CodegenText.Literal(entry.Key)).Append(" };\n"); } } diff --git a/Unity-Package/Assets/root/Editor/CodeGenerator.cs b/Unity-Package/Assets/root/Editor/CodeGenerator.cs index 5fef534..f85577f 100644 --- a/Unity-Package/Assets/root/Editor/CodeGenerator.cs +++ b/Unity-Package/Assets/root/Editor/CodeGenerator.cs @@ -97,6 +97,9 @@ public static GenerateResult Run(GenerateOptions options) try { var emitOptions = BuildEmitOptions(settings); + if (settings.GenerateUniTask && !emitOptions.UniTask) + result.Warnings.Add(UniTaskSupport.MissingMessage); + var reader = new TableReader(emitOptions); var read = reader.Read(settings.GenerateStringTables, settings.GenerateAssetTables); result.Warnings.AddRange(read.Warnings); @@ -284,7 +287,9 @@ static EmitOptions BuildEmitOptions(CodegenSettings settings) Naming = settings.Naming, KeySeparators = settings.KeySeparators, SmartParamTypes = settings.SmartParamTypes, - GenerateAsmdef = settings.GenerateAsmdef + GenerateAsmdef = settings.GenerateAsmdef, + // Generated code must compile, so the option only takes effect when the add-on is compiled. + UniTask = settings.GenerateUniTask && UniTaskSupport.IsAvailable }; } @@ -466,7 +471,7 @@ static string WriteAsmdefIfNeeded( return fullPath; } - static string BuildAsmdefContent(EmitOptions options, List models, out string baseName) + internal static string BuildAsmdefContent(EmitOptions options, List models, out string baseName) { baseName = string.IsNullOrEmpty(options.Namespace) ? "LocalizationCodegen.Generated" @@ -478,6 +483,12 @@ static string BuildAsmdefContent(EmitOptions options, List models, o "Unity.Localization" }; + if (options.UniTask) + { + references.Add(UniTaskSupport.RuntimeAssemblyName); + references.Add(UniTaskSupport.UniTaskAssemblyName); + } + foreach (var model in models) foreach (var assembly in model.AssetAssemblies) references.Add(assembly); diff --git a/Unity-Package/Assets/root/Editor/CodegenModel.cs b/Unity-Package/Assets/root/Editor/CodegenModel.cs index 1d0ce84..2a2d710 100644 --- a/Unity-Package/Assets/root/Editor/CodegenModel.cs +++ b/Unity-Package/Assets/root/Editor/CodegenModel.cs @@ -74,6 +74,7 @@ internal sealed class EmitOptions { public const string DefaultRuntimeAlias = "__LT"; public const string RuntimeTypeName = "global::Severnbli.LocalizationCodegen.LocalizedTables"; + public const string UniTaskRuntimeTypeName = "global::Severnbli.LocalizationCodegen.LocalizedTablesUniTask"; /// Normalized namespace, or for the global namespace. public string Namespace; @@ -90,10 +91,14 @@ internal sealed class EmitOptions /// When true, an asmdef is generated and unreferenced player assemblies may be used. public bool GenerateAsmdef; + /// When true, every member also gets a UniTask-returning ...Async variant. + public bool UniTask; + /// Stable signature of every option that can change output. public string Signature() { - return string.Join("|", new[] + // UniTask is appended only when enabled, so existing hashes (and files) stay valid after upgrading. + return (UniTask ? "unitask|" : "") + string.Join("|", new[] { Namespace ?? "", UseRuntimeAlias ? "alias" : "noalias", diff --git a/Unity-Package/Assets/root/Editor/CodegenSettings.cs b/Unity-Package/Assets/root/Editor/CodegenSettings.cs index 819227e..0a4b6e4 100644 --- a/Unity-Package/Assets/root/Editor/CodegenSettings.cs +++ b/Unity-Package/Assets/root/Editor/CodegenSettings.cs @@ -38,6 +38,9 @@ public sealed class CodegenSettings : ScriptableSingleton [SerializeField] private bool generateAsmdef; [SerializeField] private bool failOnSmartStringMismatch; + // Options introduced in 1.2.0. Off by default, so no migration is needed. + [SerializeField] private bool generateUniTask; + public bool SetupCompleted { get => setupCompleted; set => setupCompleted = value; } public string OutputFolder { get => outputFolder; set => outputFolder = value; } public string Namespace { get => generatedNamespace; set => generatedNamespace = value; } @@ -56,6 +59,7 @@ public sealed class CodegenSettings : ScriptableSingleton public bool GenerateXmlDocs { get => generateXmlDocs; set => generateXmlDocs = value; } public bool GenerateAsmdef { get => generateAsmdef; set => generateAsmdef = value; } public bool FailOnSmartStringMismatch { get => failOnSmartStringMismatch; set => failOnSmartStringMismatch = value; } + public bool GenerateUniTask { get => generateUniTask; set => generateUniTask = value; } public SmartStringMode SmartStrings { diff --git a/Unity-Package/Assets/root/Editor/SettingsGui.cs b/Unity-Package/Assets/root/Editor/SettingsGui.cs index 6279faf..6cbb3fd 100644 --- a/Unity-Package/Assets/root/Editor/SettingsGui.cs +++ b/Unity-Package/Assets/root/Editor/SettingsGui.cs @@ -97,6 +97,12 @@ public static bool Draw() 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); EditorGUILayout.Space(); EditorGUILayout.LabelField("Advanced", EditorStyles.boldLabel); diff --git a/Unity-Package/Assets/root/Editor/UniTaskSupport.cs b/Unity-Package/Assets/root/Editor/UniTaskSupport.cs new file mode 100644 index 0000000..e4a8aba --- /dev/null +++ b/Unity-Package/Assets/root/Editor/UniTaskSupport.cs @@ -0,0 +1,33 @@ +using System; + +namespace Severnbli.LocalizationCodegen.Editor +{ + /// Detects the optional UniTask runtime assembly that generated ...Async members call. + internal static class UniTaskSupport + { + public const string RuntimeAssemblyName = "com.severnbli.localization-codegen.UniTask"; + public const string UniTaskAssemblyName = "UniTask"; + + public const string MissingMessage = + "UniTask members were not generated: the " + RuntimeAssemblyName + " assembly is not compiled. Install " + + "UniTask (com.cysharp.unitask) as a package, or define LOCALIZATION_CODEGEN_UNITASK when UniTask lives " + + "under Assets."; + + /// + /// True when the add-on assembly is compiled. Its asmdef only compiles when UniTask is installed, so this + /// also means UniTask itself is available to generated code. + /// + public static bool IsAvailable + { + get + { + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + { + if (string.Equals(assembly.GetName().Name, RuntimeAssemblyName, StringComparison.Ordinal)) + return true; + } + return false; + } + } + } +} diff --git a/Unity-Package/Assets/root/Editor/UniTaskSupport.cs.meta b/Unity-Package/Assets/root/Editor/UniTaskSupport.cs.meta new file mode 100644 index 0000000..38617bc --- /dev/null +++ b/Unity-Package/Assets/root/Editor/UniTaskSupport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4822f5c2af514e2385285946f69d7eb3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/README.md b/Unity-Package/Assets/root/README.md index ac3cc2e..f4e5741 100644 --- a/Unity-Package/Assets/root/README.md +++ b/Unity-Package/Assets/root/README.md @@ -19,22 +19,34 @@ Unity 2021.3+ + + UniTask optional + MIT License

+

+ Quick start • + Installation • + Usage • + Settings • + CI • + Changelog +

+ --- ## Overview -Localization Codegen reads your [Unity Localization](https://docs.unity3d.com/Packages/com.unity.localization@1.5/manual/index.html) table collections and generates plain C# classes for them — one static class per collection, one property per key. No runtime reflection, no string lookups in your game code, and full autocomplete plus compile-time safety. +Localization Codegen reads your [Unity Localization](https://docs.unity3d.com/Packages/com.unity.localization@1.5/manual/index.html) table collections and generates plain C# classes for them — one static class per collection, one member per key. No runtime reflection, no string lookups in your game code, and full autocomplete plus compile-time safety. ```csharp // Before -label.text = localizationDatabase.GetLocalizedString("Ui", "HelloWorld"); +label.text = LocalizationSettings.StringDatabase.GetLocalizedString("Ui", "HelloWorld"); // After label.text = Ui.HelloWorld; @@ -42,10 +54,32 @@ label.text = Ui.HelloWorld; | Feature | Description | |---|---| -| 🪄 **First-run wizard** | A setup wizard opens automatically after the package is first imported | -| 🧩 **Typed access** | One static class per string or asset table collection, one property per key | -| 🔁 **Automatic regeneration** | Regenerates when table collections, tables or entries change | -| 🛠️ **Editor tooling** | Dedicated window with manual regeneration and settings | +| 🧩 **Typed access** | One static class per string or asset table collection, one member per key | +| 💬 **Smart strings** | Entries with placeholders become methods with typed positional and named parameters | +| 🔗 **Reference members** | Optional `Ref` class with `LocalizedString` / `LocalizedAsset` references that follow locale changes | +| ⚡ **UniTask** | Optional `…Async` members returning `UniTask`, with cancellation | +| 🔁 **Automatic regeneration** | Debounced regeneration after table edits, including changes pulled from version control | +| 🧪 **CI ready** | Batch mode entry points to regenerate, or to fail when generated code is out of date | +| 🪄 **First-run wizard** | A setup wizard opens after the package is first imported | + +## Quick start + +1. Install the package with [OpenUPM](#option-1--openupm-recommended): + + ```bash + openupm add com.severnbli.localization-codegen + ``` + +2. Finish the setup wizard. It picks a namespace and an output folder and runs the first generation. +3. Use the generated classes: + + ```csharp + using Localization; + + label.text = Ui.HelloWorld; + ``` + +Edit your tables as usual — the classes regenerate on their own. ## Installation @@ -78,6 +112,7 @@ The package is published on [OpenUPM](https://openupm.com/packages/com.severnbli 3. Switch back to Unity. The package resolves, compiles, and the setup wizard opens. +> [!TIP] > `openupm add` handles the scoped registry, dependency resolution and `manifest.json` changes for you. You can also add the package from **Window > Package Manager** if the OpenUPM registry is already configured.
@@ -99,7 +134,7 @@ Add the scoped registry and the dependency to `Packages/manifest.json`: } ], "dependencies": { - "com.severnbli.localization-codegen": "1.1.1" + "com.severnbli.localization-codegen": "1.2.0" } } ``` @@ -149,9 +184,12 @@ This variant bypasses Package Manager, so **versioning is manual**: |---|---| | Unity | 2021.3 or newer | | `com.unity.localization` | 1.5.x (automatic with the UPM variants, manual with the standard `.unitypackage`) | +| `com.cysharp.unitask` | 2.x, optional — only for [UniTask members](#unitask) | ## Usage +### Generated classes + Given a string table collection named `Ui` containing the key `HelloWorld`, the generator produces `Ui.g.cs`: ```csharp @@ -170,8 +208,7 @@ namespace Localization } ``` -The `__LT` alias is declared once per file. All other types (`LocalizedString`, asset types, `Dictionary<,>`) -stay fully `global::`-qualified so user types cannot be shadowed. +The `__LT` alias is declared once per file. All other types (`LocalizedString`, asset types, `Dictionary<,>`) stay fully `global::`-qualified, so your own types can never shadow them. Use it anywhere from your game code: @@ -181,7 +218,7 @@ using Localization; label.text = Ui.HelloWorld; ``` -For **asset table collections**, each property is typed from the entry's asset type (falling back to `UnityEngine.Object`) and returns the localized asset: +For **asset table collections**, each member is typed from the entry's asset type (falling back to `UnityEngine.Object`) and returns the localized asset: ```csharp Sprite icon = Icons.Sword; @@ -189,7 +226,7 @@ Sprite icon = Icons.Sword; ### Naming rules -Generated identifiers stay valid C#: +Generated identifiers always stay valid C#: - Invalid characters become `_`. - Names starting with a digit get a `_` prefix. @@ -199,9 +236,7 @@ Generated identifiers stay valid C#: - Reserved names (`System`, `UnityEngine`, `Unity`, the first namespace segment, …) get a `Table` suffix. - Windows device names (`CON`, `NUL`, `COM1`, …) get a trailing `_`. -With **Naming Convention = PascalCase** and optional **Key Separators**, `player name` becomes `PlayerName` -and `Menu/Start` becomes the nested class `Menu.Start`. These options are off by default so upgraded projects -keep their existing API. +With **Naming Convention = PascalCase** and optional **Key Separators**, `player name` becomes `PlayerName` and `Menu/Start` becomes the nested class `Menu.Start`. These options are off by default, so upgraded projects keep their existing API. ### Smart strings @@ -215,22 +250,21 @@ public static string Greeting(object arg0, int count) ``` - Positional placeholders (`{0}`) become `arg0`, `arg1`, … (gaps are filled). -- Named placeholders (`{player-name}`, `{player.Name}`) become camelCase parameters. The original name is - preserved for the runtime lookup. +- Named placeholders (`{player-name}`, `{player.Name}`) become camelCase parameters. The original name is preserved for the runtime lookup. - `{}` (the current value inside a formatter) is not a parameter. - Variables provided by a **Global Variables Group** are not parameters; Unity resolves them. - **Smart Parameter Types = Inferred** uses `int` for `plural`, `IEnumerable` for `list`, otherwise `object`. -- Placeholder differences between locales are reported as warnings. Enable - **Fail CI On Smart String Mismatch** to make `CheckBatch` fail on them. -- **MethodsAndRefs** additionally emits `Ref.Greeting(...)` returning a `LocalizedString` whose arguments - and local variables are set. +- Placeholder differences between locales are reported as warnings. Enable **Fail CI On Smart String Mismatch** to make `CheckBatch` fail on them. +- **MethodsAndRefs** additionally emits `Ref.Greeting(...)` returning a `LocalizedString` whose arguments and local variables are set. -Smart strings are opt-in. Upgraded projects default to `Off`; new projects default to `Methods` when the -setup wizard completes. +> [!NOTE] +> Smart strings are opt-in. Upgraded projects default to `Off`; new projects default to `Methods` when the setup wizard completes. ### Reference members -Enable **Generate Reference Members** to emit a nested `Ref` class: +The regular members return a **value**: `Ui.HelloWorld` is the text in the current locale at the moment you read it. When the player switches language, a label you filled that way keeps the old text. + +Enable **Generate Reference Members** to also get a nested `Ref` class that returns a **reference** to the entry instead — Unity's own `LocalizedString` (or `LocalizedAsset` for asset tables), which knows which entry it points at and can follow locale changes: ```csharp public static class Ref @@ -240,13 +274,47 @@ public static class Ref } ``` -Asset entries use `LocalizedSprite`, `LocalizedAudioClip`, `LocalizedAsset`, and the other built-in -localized asset types when available. +Use it wherever Unity Localization expects a reference — still without magic strings: + +```csharp +// A LocalizeStringEvent component updates its label whenever the locale changes. +localizeStringEvent.StringReference = Ui.Ref.HelloWorld; + +// Or react to locale changes yourself. +var title = Ui.Ref.HelloWorld; +title.StringChanged += text => label.text = text; +``` + +Asset entries use `LocalizedSprite`, `LocalizedAudioClip`, `LocalizedAsset` and the other built-in localized asset types when available. Each access creates a new reference, so keep the one you subscribed to. + +### UniTask + +Install [UniTask](https://github.com/Cysharp/UniTask) (`com.cysharp.unitask` 2.x) and enable **UniTask Members** to emit an awaitable variant next to every member: + +```csharp +public static string HelloWorld => __LT.GetString(TableName, "HelloWorld"); + +public static global::Cysharp.Threading.Tasks.UniTask HelloWorldAsync(global::System.Threading.CancellationToken cancellationToken = default) + => global::Severnbli.LocalizationCodegen.LocalizedTablesUniTask.GetStringAsync(TableName, "HelloWorld", cancellationToken); +``` + +```csharp +label.text = await Ui.HelloWorldAsync(this.GetCancellationTokenOnDestroy()); +Sprite icon = await Icons.SwordAsync(); +``` + +- The async members never block on table loading, so they also work where synchronous loads are not supported (WebGL). +- Smart string methods keep their parameters (`await Ui.GreetingAsync(player, count)`), and asset entries return `UniTask`. +- Cancelling stops the wait; Localization still finishes loading the table in the background. +- Turning the option on never renames existing members. A key that already ends in `Async` keeps its name, and the generated variant gets a suffix (`TitleAsync_2`). +- `LocalizedString.GetLocalizedStringUniTask()` awaits any `LocalizedString`, including `Ref` members. + +> [!IMPORTANT] +> The API lives in the optional `com.severnbli.localization-codegen.UniTask` assembly, which compiles only when UniTask is installed as a package. If UniTask lives under `Assets/`, add the scripting define `LOCALIZATION_CODEGEN_UNITASK`. Without that assembly the option is skipped with a warning, because the generated code would not compile. ## Settings -Open **Project Settings > Localization Codegen**, or **Window > Localization Codegen** for the standalone -window. Settings are stored in `ProjectSettings/LocalizationCodegenSettings.asset`. +Open **Project Settings > Localization Codegen**, or **Window > Localization Codegen** for the standalone window. Settings are stored in `ProjectSettings/LocalizationCodegenSettings.asset`. | Setting | Default | Description | |---|---|---| @@ -256,15 +324,18 @@ window. Settings are stored in `ProjectSettings/LocalizationCodegenSettings.asse | 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. | | Use Runtime Alias | on | Emit one `using __LT = ...;` instead of repeating the runtime type on every member. | -| Generate Reference Members | off | Emit the nested `Ref` class. | +| Generate Reference Members | off | Emit the nested [`Ref` class](#reference-members). | | XML Documentation | off | Add XML docs with the default locale text and smart string parameters. | | Smart Strings | off (upgraded) / `Methods` (new) | `Off`, `Methods` or `MethodsAndRefs`. | | Smart Parameter Types | `Object` | `Object` or `Inferred`. | | 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. | | 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. + ## CI / batch mode ```bash @@ -277,8 +348,7 @@ Unity -batchmode -nographics -projectPath . \ -executeMethod Severnbli.LocalizationCodegen.Editor.CodeGenerator.CheckBatch ``` -The same actions are available under **Tools > Localization Codegen > Regenerate** and -**Tools > Localization Codegen > Verify (Dry run)**. The setup wizard is never opened in batch mode. +`CheckBatch` compares the generated files on disk with the tables, so it also catches generated files that were edited by hand. The same actions are available under **Tools > Localization Codegen > Regenerate** and **Tools > Localization Codegen > Verify (Dry run)**. The setup wizard is never opened in batch mode. For clean diffs, add this to `.gitattributes`: @@ -290,11 +360,9 @@ 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. -- Generated members use the synchronous localization APIs. They block until the table is loaded and are not - supported by Addressables on WebGL. Use `LocalizedTables.GetStringAsync` / `GetAssetAsync` there. -- If `LocalizationSettings` are missing at runtime, generated members return the table key (and log once) - instead of throwing. +- 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). +- 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. ## License diff --git a/Unity-Package/Assets/root/Runtime/AssemblyInfo.cs b/Unity-Package/Assets/root/Runtime/AssemblyInfo.cs new file mode 100644 index 0000000..13e0ff4 --- /dev/null +++ b/Unity-Package/Assets/root/Runtime/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("com.severnbli.localization-codegen.UniTask")] diff --git a/Unity-Package/Assets/root/Runtime/AssemblyInfo.cs.meta b/Unity-Package/Assets/root/Runtime/AssemblyInfo.cs.meta new file mode 100644 index 0000000..73c4817 --- /dev/null +++ b/Unity-Package/Assets/root/Runtime/AssemblyInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a5ece4b0787a4796a66994287dcef5d2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/Runtime/LocalizedTables.cs b/Unity-Package/Assets/root/Runtime/LocalizedTables.cs index 8c64db0..2425750 100644 --- a/Unity-Package/Assets/root/Runtime/LocalizedTables.cs +++ b/Unity-Package/Assets/root/Runtime/LocalizedTables.cs @@ -22,7 +22,8 @@ public static class LocalizedTables { static bool s_WarnedMissingSettings; - static bool HasSettings() + /// True when Localization is configured; logs one warning the first time it is not. + internal static bool HasSettings() { if (LocalizationSettings.HasSettings) return true; @@ -149,7 +150,7 @@ static object[] ToArray(IList values) } /// Wraps any value as a smart string local variable. - sealed class ObjectValueVariable : IVariable + internal sealed class ObjectValueVariable : IVariable { readonly object m_Value; diff --git a/Unity-Package/Assets/root/Runtime/UniTask.meta b/Unity-Package/Assets/root/Runtime/UniTask.meta new file mode 100644 index 0000000..73998b1 --- /dev/null +++ b/Unity-Package/Assets/root/Runtime/UniTask.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 15f761a786fb4dea8cf31fb76fdb498a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/Runtime/UniTask/AssemblyInfo.cs b/Unity-Package/Assets/root/Runtime/UniTask/AssemblyInfo.cs new file mode 100644 index 0000000..6d19d33 --- /dev/null +++ b/Unity-Package/Assets/root/Runtime/UniTask/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("com.severnbli.localization-codegen.UniTask.Tests")] diff --git a/Unity-Package/Assets/root/Runtime/UniTask/AssemblyInfo.cs.meta b/Unity-Package/Assets/root/Runtime/UniTask/AssemblyInfo.cs.meta new file mode 100644 index 0000000..49a4763 --- /dev/null +++ b/Unity-Package/Assets/root/Runtime/UniTask/AssemblyInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4e9167093d4c4a76bda571c5a0efad12 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs b/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs new file mode 100644 index 0000000..33daa9d --- /dev/null +++ b/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using Cysharp.Threading.Tasks; +using UnityEngine.Localization; +using UnityEngine.Localization.Settings; +using UnityEngine.Localization.SmartFormat.PersistentVariables; +using UnityEngine.ResourceManagement.AsyncOperations; + +namespace Severnbli.LocalizationCodegen +{ + /// + /// UniTask entry points used by generated ...Async members. Compiled only when UniTask + /// (com.cysharp.unitask) is installed, or when LOCALIZATION_CODEGEN_UNITASK is defined. + /// + /// + /// The operations come from Unity Localization, which releases them automatically, so nothing here needs to be + /// released by the caller. Cancelling only stops the wait: Localization still finishes loading the table. + /// + public static class LocalizedTablesUniTask + { + /// Loads the translated string for the selected locale without blocking. + public static UniTask GetStringAsync(string table, string key, CancellationToken cancellationToken = default) + => GetStringAsync(table, key, null, null, cancellationToken); + + /// + /// Loads the translated string and applies positional and named smart string arguments, with the same + /// semantics as the synchronous methods. Either argument set may be null. + /// + public static UniTask GetStringAsync( + string table, + string key, + IList positional, + IDictionary named, + CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) + return UniTask.FromCanceled(cancellationToken); + if (!LocalizedTables.HasSettings()) + return UniTask.FromResult(key); + + var hasPositional = positional != null && positional.Count > 0; + var hasNamed = named != null && named.Count > 0; + + IList arguments; + IVariableGroup localVariables = null; + if (hasPositional && hasNamed) + { + // Same as LocalizedTables.GetStringMixed: named values become local variables. + arguments = positional; + localVariables = new NamedVariables(named); + } + else if (hasNamed) + { + // Same as LocalizedTables.GetString(table, key, named): the dictionary is the single argument. + arguments = new object[] { named }; + } + else + { + arguments = hasPositional ? positional : Array.Empty(); + } + + var handle = LocalizationSettings.StringDatabase.GetLocalizedStringAsync( + table, key, arguments, null, FallbackBehavior.UseProjectSettings, localVariables); + return ToUniTask(handle, cancellationToken); + } + + /// Loads the localized asset for the selected locale without blocking. + public static UniTask GetAssetAsync(string table, string key, CancellationToken cancellationToken = default) + where T : UnityEngine.Object + { + if (cancellationToken.IsCancellationRequested) + return UniTask.FromCanceled(cancellationToken); + if (!LocalizedTables.HasSettings()) + return UniTask.FromResult(null); + + var handle = LocalizationSettings.AssetDatabase.GetLocalizedAssetAsync(table, key); + return ToUniTask(handle, cancellationToken); + } + + /// + /// Awaits a Localization operation. The result is read inside the completion callback because Localization + /// releases the operation right after it completes. + /// + internal static UniTask ToUniTask(AsyncOperationHandle handle, CancellationToken cancellationToken) + { + if (!handle.IsValid()) + return UniTask.FromException(new InvalidOperationException("The localization operation is not valid.")); + if (handle.IsDone) + return FromCompleted(handle); + + var source = new UniTaskCompletionSource(); + var registration = cancellationToken.CanBeCanceled + ? cancellationToken.RegisterWithoutCaptureExecutionContext(() => source.TrySetCanceled(cancellationToken)) + : default; + + handle.Completed += completed => + { + registration.Dispose(); + if (completed.Status == AsyncOperationStatus.Succeeded) + source.TrySetResult(completed.Result); + else + source.TrySetException(Failure(completed)); + }; + + return source.Task; + } + + static UniTask FromCompleted(AsyncOperationHandle handle) + { + return handle.Status == AsyncOperationStatus.Succeeded + ? UniTask.FromResult(handle.Result) + : UniTask.FromException(Failure(handle)); + } + + static Exception Failure(AsyncOperationHandle handle) + { + return handle.OperationException ?? + new InvalidOperationException("The localization operation failed with status " + handle.Status + "."); + } + + /// Exposes named arguments as smart string local variables. + sealed class NamedVariables : IVariableGroup + { + readonly IDictionary m_Values; + + public NamedVariables(IDictionary values) + { + m_Values = values; + } + + public bool TryGetValue(string key, out IVariable value) + { + object raw; + if (key != null && m_Values.TryGetValue(key, out raw)) + { + value = new LocalizedTables.ObjectValueVariable(raw); + return true; + } + + value = null; + return false; + } + } + } + + /// UniTask helpers for Unity Localization references, such as the members of a generated Ref class. + public static class LocalizedStringUniTaskExtensions + { + /// Loads the string of a , using its arguments and local variables. + public static UniTask GetLocalizedStringUniTask( + this LocalizedString reference, + CancellationToken cancellationToken = default) + { + if (reference == null) + throw new ArgumentNullException(nameof(reference)); + if (cancellationToken.IsCancellationRequested) + return UniTask.FromCanceled(cancellationToken); + if (!LocalizedTables.HasSettings()) + return UniTask.FromResult(reference.TableEntryReference.Key); + + return LocalizedTablesUniTask.ToUniTask(reference.GetLocalizedStringAsync(), cancellationToken); + } + } +} diff --git a/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs.meta b/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs.meta new file mode 100644 index 0000000..1a9bd01 --- /dev/null +++ b/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 17ee1a67ca5547f7b528929d8344cb91 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/Runtime/UniTask/com.severnbli.localization-codegen.UniTask.asmdef b/Unity-Package/Assets/root/Runtime/UniTask/com.severnbli.localization-codegen.UniTask.asmdef new file mode 100644 index 0000000..5306200 --- /dev/null +++ b/Unity-Package/Assets/root/Runtime/UniTask/com.severnbli.localization-codegen.UniTask.asmdef @@ -0,0 +1,26 @@ +{ + "name": "com.severnbli.localization-codegen.UniTask", + "references": [ + "com.severnbli.localization-codegen.Runtime", + "Unity.Localization", + "Unity.ResourceManager", + "UniTask" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [ + "LOCALIZATION_CODEGEN_UNITASK" + ], + "versionDefines": [ + { + "name": "com.cysharp.unitask", + "expression": "2.0.0", + "define": "LOCALIZATION_CODEGEN_UNITASK" + } + ], + "noEngineReferences": false +} diff --git a/Unity-Package/Assets/root/Runtime/UniTask/com.severnbli.localization-codegen.UniTask.asmdef.meta b/Unity-Package/Assets/root/Runtime/UniTask/com.severnbli.localization-codegen.UniTask.asmdef.meta new file mode 100644 index 0000000..5e9280e --- /dev/null +++ b/Unity-Package/Assets/root/Runtime/UniTask/com.severnbli.localization-codegen.UniTask.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 73d940c77a0a4f98b9f3976e49c17b43 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs b/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs index ca065da..3315221 100644 --- a/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs +++ b/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs @@ -333,7 +333,7 @@ public void Refs_EmitLocalizedStringAndLocalizedAssetMembers() output); StringAssert.Contains( "public static global::UnityEngine.Localization.LocalizedSprite Sprite => " + - "new global::UnityEngine.Localization.LocalizedSprite(TableName, \"Sprite\");", + "new global::UnityEngine.Localization.LocalizedSprite { TableReference = TableName, TableEntryReference = \"Sprite\" };", output); } @@ -350,6 +350,141 @@ public void Refs_AvoidObjectMembers() StringAssert.DoesNotContain("LocalizedString ToString =>", refClass); } + static EmitOptions UniTaskOptions() + { + return new EmitOptions + { + Namespace = "Localization", + UseRuntimeAlias = true, + SmartStrings = SmartStringMode.Methods, + UniTask = true + }; + } + + [Test] + public void UniTask_IsNotEmittedByDefault() + { + var model = Model("Ui", false, (1L, "Title")); + var options = new EmitOptions { Namespace = "Localization", UseRuntimeAlias = true }; + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.DoesNotContain("UniTask", output); + StringAssert.DoesNotContain("TitleAsync", output); + } + + [Test] + public void UniTask_StringEntryGetsAsyncMethod() + { + var model = Model("Ui", false, (1L, "Title")); + var options = UniTaskOptions(); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains("public static string Title => __LT.GetString(TableName, \"Title\");", output); + StringAssert.Contains( + "public static global::Cysharp.Threading.Tasks.UniTask TitleAsync(" + + "global::System.Threading.CancellationToken cancellationToken = default)\n" + + " => global::Severnbli.LocalizationCodegen.LocalizedTablesUniTask.GetStringAsync(" + + "TableName, \"Title\", cancellationToken);", + output); + } + + [Test] + public void UniTask_SmartStringPassesArgumentsAndToken() + { + var entry = new EntryModel { Id = 1, Key = "Greeting" }; + entry.Params.Add(new SmartParam { IsPositional = true, Index = 0, SourceName = "0", ClrName = "arg0", TypeName = "object" }); + entry.Params.Add(new SmartParam { SourceName = "player", ClrName = "player", TypeName = "object" }); + var model = new TableModel { Name = "Ui" }; + model.Entries.Add(entry); + + var options = UniTaskOptions(); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains( + "public static global::Cysharp.Threading.Tasks.UniTask GreetingAsync(object arg0, object player, " + + "global::System.Threading.CancellationToken cancellationToken = default)", + output); + StringAssert.Contains( + ".GetStringAsync(TableName, \"Greeting\", new object[] { arg0 }, " + + "new global::System.Collections.Generic.Dictionary { [\"player\"] = player }, cancellationToken);", + output); + StringAssert.Contains("/// ", output); + } + + [Test] + public void UniTask_TokenParameterAvoidsSmartStringParameterNames() + { + var entry = new EntryModel { Id = 1, Key = "Wait" }; + entry.Params.Add(new SmartParam { SourceName = "cancellationToken", ClrName = "cancellationToken", TypeName = "object" }); + var model = new TableModel { Name = "Ui" }; + model.Entries.Add(entry); + + var options = UniTaskOptions(); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains("WaitAsync(object cancellationToken, global::System.Threading.CancellationToken cancellationToken_2 = default)", output); + StringAssert.Contains("[\"cancellationToken\"] = cancellationToken }, cancellationToken_2);", output); + } + + [Test] + public void UniTask_AssetEntryGetsAsyncMethod() + { + var model = new TableModel { Name = "Icons", IsAsset = true }; + model.Entries.Add(new EntryModel { Id = 1, Key = "Logo", AssetTypeName = "global::UnityEngine.Sprite" }); + + var options = UniTaskOptions(); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains( + "public static global::Cysharp.Threading.Tasks.UniTask LogoAsync(" + + "global::System.Threading.CancellationToken cancellationToken = default)\n" + + " => global::Severnbli.LocalizationCodegen.LocalizedTablesUniTask.GetAssetAsync(" + + "TableName, \"Logo\", cancellationToken);", + output); + } + + [Test] + public void UniTask_AsyncNamesNeverTakeAnExistingKeyName() + { + // The key "TitleAsync" keeps its own name; the variant of "Title" moves to a suffix. + var model = Model("Ui", false, (1L, "Title"), (2L, "TitleAsync"), (3L, "class")); + var options = UniTaskOptions(); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains("public static string TitleAsync => __LT.GetString(TableName, \"TitleAsync\");", output); + StringAssert.Contains("UniTask TitleAsync_2(", output); + StringAssert.Contains("UniTask TitleAsyncAsync(", output); + StringAssert.Contains("UniTask classAsync(", output); + } + + [Test] + public void UniTask_ChangesTheOptionSignatureOnlyWhenEnabled() + { + var off = new EmitOptions(); + var on = new EmitOptions { UniTask = true }; + + StringAssert.DoesNotContain("unitask", off.Signature()); + Assert.AreNotEqual(off.Signature(), on.Signature()); + } + + [Test] + public void UniTask_GeneratedAsmdefReferencesUniTask() + { + string name; + var withUniTask = CodeGenerator.BuildAsmdefContent(UniTaskOptions(), new List(), out name); + var without = CodeGenerator.BuildAsmdefContent(LegacyOptions(), new List(), out name); + + StringAssert.Contains("\"com.severnbli.localization-codegen.UniTask\"", withUniTask); + StringAssert.Contains("\"UniTask\"", withUniTask); + StringAssert.DoesNotContain("UniTask", without); + } + [Test] public void KeySeparators_CreateNestedClasses() { diff --git a/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs b/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs new file mode 100644 index 0000000..c4f9687 --- /dev/null +++ b/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs @@ -0,0 +1,227 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using NUnit.Framework; +using UnityEditor; +using UnityEditor.Compilation; +using UnityEngine.TestTools; + +namespace Severnbli.LocalizationCodegen.Editor.Tests +{ + /// + /// Compiles emitted code with Unity's compiler, with warnings as errors and XML documentation enabled, so a change + /// in the emitter that produces invalid or warning-prone C# fails here instead of in a user's project. + /// + public class GeneratedCodeCompilationTests + { + const string WorkRoot = "Temp/LocalizationCodegenCompileCheck"; + const double TimeoutSeconds = 120; + + // Assemblies generated code may reference, besides the engine modules. + static readonly string[] s_ReferencedAssemblies = + { + "com.severnbli.localization-codegen.Runtime", + "Unity.Localization", + "Unity.ResourceManager", + UniTaskSupport.RuntimeAssemblyName, + UniTaskSupport.UniTaskAssemblyName + }; + + [UnityTest] + public IEnumerator GeneratedCode_Compiles() + { + return Compile(uniTask: false); + } + + [UnityTest] + public IEnumerator GeneratedCodeWithUniTask_Compiles() + { + if (!UniTaskSupport.IsAvailable) + Assert.Ignore("UniTask is not installed in this project."); + return Compile(uniTask: true); + } + + static IEnumerator Compile(bool uniTask) + { + var folder = Path.Combine(WorkRoot, uniTask ? "unitask" : "plain"); + if (Directory.Exists(folder)) + Directory.Delete(folder, true); + Directory.CreateDirectory(folder); + + var sources = new List(); + foreach (var variant in Variants(uniTask)) + { + var models = BuildModels(); + CodeEmitter.AssignClassNames(models, variant.Options); + foreach (var model in models) + { + var path = Path.Combine(folder, variant.Name + "_" + model.ClassName.TrimStart('@') + ".g.cs"); + File.WriteAllText(path, CodeEmitter.Emit(model, variant.Options)); + sources.Add(path); + } + } + + var builder = new AssemblyBuilder(Path.Combine(folder, "CompileCheck.dll"), sources.ToArray()) + { + referencesOptions = ReferencesOptions.UseEngineModules, + additionalReferences = ReferencePaths(uniTask), + compilerOptions = + { + AdditionalCompilerArguments = new[] + { + "-warnaserror+", + "-doc:" + Path.GetFullPath(Path.Combine(folder, "CompileCheck.xml")), + // Missing XML comments are expected for members without a preview. + "-nowarn:1591" + } + } + }; + + CompilerMessage[] messages = null; + builder.buildFinished += (_, result) => messages = result; + + var started = EditorApplication.timeSinceStartup; + while (!builder.Build()) + { + // Build() refuses to start while Unity itself is compiling. + if (EditorApplication.timeSinceStartup - started > TimeoutSeconds) + Assert.Fail("AssemblyBuilder could not start."); + yield return null; + } + + while (messages == null) + { + if (EditorApplication.timeSinceStartup - started > TimeoutSeconds) + Assert.Fail("Compiling the generated code timed out."); + yield return null; + } + + var problems = messages + .Where(m => m.type == CompilerMessageType.Error || m.type == CompilerMessageType.Warning) + .Select(m => m.message) + .ToList(); + Assert.IsEmpty(problems, "Generated code must compile without errors or warnings:\n" + string.Join("\n", problems)); + } + + static string[] ReferencePaths(bool uniTask) + { + var available = CompilationPipeline.GetAssemblies(AssembliesType.Player) + .ToDictionary(a => a.name, a => a.outputPath, StringComparer.Ordinal); + + var paths = new List(); + foreach (var name in s_ReferencedAssemblies) + { + var isUniTask = name == UniTaskSupport.RuntimeAssemblyName || name == UniTaskSupport.UniTaskAssemblyName; + if (isUniTask && !uniTask) + continue; + + string path; + if (available.TryGetValue(name, out path)) + { + paths.Add(Path.GetFullPath(path)); + continue; + } + + // Precompiled package assemblies are not part of the compilation pipeline. + var precompiled = CompilationPipeline.GetPrecompiledAssemblyPaths( + CompilationPipeline.PrecompiledAssemblySources.All) + .FirstOrDefault(p => string.Equals(Path.GetFileNameWithoutExtension(p), name, StringComparison.Ordinal)); + Assert.IsNotNull(precompiled, "Could not find the " + name + " assembly to reference."); + paths.Add(precompiled); + } + return paths.ToArray(); + } + + struct Variant + { + public string Name; + public EmitOptions Options; + } + + static IEnumerable Variants(bool uniTask) + { + // Every option that changes the shape of the output, in a namespace. + yield return new Variant + { + Name = "Full", + Options = new EmitOptions + { + Namespace = "CompileCheck.Full", + UseRuntimeAlias = true, + Refs = true, + XmlDocs = true, + SmartStrings = SmartStringMode.MethodsAndRefs, + SmartParamTypes = SmartParamTypeMode.Inferred, + KeySeparators = "/", + UniTask = uniTask + } + }; + + // PascalCase names in the global namespace without the alias. + yield return new Variant + { + Name = "Global", + Options = new EmitOptions + { + Namespace = null, + UseRuntimeAlias = false, + Refs = true, + XmlDocs = true, + SmartStrings = SmartStringMode.Methods, + Naming = NamingConvention.PascalCase, + UniTask = uniTask + } + }; + + // The 1.0 output. + yield return new Variant + { + Name = "Legacy", + Options = new EmitOptions { Namespace = "CompileCheck.Legacy", UseRuntimeAlias = false, UniTask = uniTask } + }; + } + + static List BuildModels() + { + var strings = new TableModel { Name = "Ui" }; + strings.Entries.Add(new EntryModel { Id = 1, Key = "Title", Preview = "Hello & welcome" }); + strings.Entries.Add(new EntryModel { Id = 2, Key = "TitleAsync" }); + strings.Entries.Add(new EntryModel { Id = 3, Key = "Menu/Start" }); + strings.Entries.Add(new EntryModel { Id = 4, Key = "Menu/Quit" }); + strings.Entries.Add(new EntryModel { Id = 5, Key = "class" }); + strings.Entries.Add(new EntryModel { Id = 6, Key = "ToString" }); + strings.Entries.Add(new EntryModel { Id = 7, Key = "Ref" }); + + var positional = new EntryModel { Id = 8, Key = "Score", Preview = "{0} of {1}" }; + positional.Params.Add(new SmartParam { IsPositional = true, Index = 0, SourceName = "0", ClrName = "arg0", TypeName = "object" }); + positional.Params.Add(new SmartParam { IsPositional = true, Index = 1, SourceName = "1", ClrName = "arg1", TypeName = "object" }); + strings.Entries.Add(positional); + + var named = new EntryModel { Id = 9, Key = "Welcome" }; + named.Params.Add(new SmartParam { SourceName = "player-name", ClrName = "playerName", TypeName = "object" }); + named.Params.Add(new SmartParam { SourceName = "count", ClrName = "count", TypeName = "int", FormatterName = "plural" }); + named.Params.Add(new SmartParam { SourceName = "cancellationToken", ClrName = "cancellationToken", TypeName = "object" }); + strings.Entries.Add(named); + + var mixed = new EntryModel { Id = 10, Key = "Mixed" }; + mixed.Params.Add(new SmartParam { IsPositional = true, Index = 0, SourceName = "0", ClrName = "arg0", TypeName = "object" }); + mixed.Params.Add(new SmartParam + { + SourceName = "items", ClrName = "items", TypeName = "global::System.Collections.IEnumerable", FormatterName = "list" + }); + strings.Entries.Add(mixed); + + var assets = new TableModel { Name = "Ui", IsAsset = true }; + assets.Entries.Add(new EntryModel { Id = 1, Key = "Logo", AssetTypeName = "global::UnityEngine.Sprite" }); + assets.Entries.Add(new EntryModel { Id = 2, Key = "Theme", AssetTypeName = "global::UnityEngine.AudioClip" }); + assets.Entries.Add(new EntryModel { Id = 3, Key = "Anything", AssetTypeName = "global::UnityEngine.Object" }); + assets.Entries.Add(new EntryModel { Id = 4, Key = "Mesh", AssetTypeName = "global::UnityEngine.Mesh" }); + // No dedicated Localized* type: uses the generic LocalizedAsset. + assets.Entries.Add(new EntryModel { Id = 5, Key = "Background", AssetTypeName = "global::UnityEngine.Texture2D" }); + + return new List { strings, assets }; + } + } +} diff --git a/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs.meta b/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs.meta new file mode 100644 index 0000000..443c4f7 --- /dev/null +++ b/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cc993768f369431f9b6c43fd86815fe8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/Tests/Editor/GenerationIntegrationTests.cs b/Unity-Package/Assets/root/Tests/Editor/GenerationIntegrationTests.cs index 02c4a5d..d1de1a7 100644 --- a/Unity-Package/Assets/root/Tests/Editor/GenerationIntegrationTests.cs +++ b/Unity-Package/Assets/root/Tests/Editor/GenerationIntegrationTests.cs @@ -26,6 +26,7 @@ public class GenerationIntegrationTests bool m_GenerateAssetTables; bool m_UseRuntimeAlias; SmartStringMode m_SmartStrings; + bool m_GenerateUniTask; string m_LastOutputFolder; string[] m_GeneratedPaths; string[] m_CollectionHashes; @@ -44,6 +45,7 @@ public void SetUp() m_GenerateAssetTables = m_Settings.GenerateAssetTables; m_UseRuntimeAlias = m_Settings.UseRuntimeAlias; m_SmartStrings = m_Settings.SmartStrings; + m_GenerateUniTask = m_Settings.GenerateUniTask; m_LastOutputFolder = m_Settings.LastOutputFolder; m_GeneratedPaths = m_Settings.GeneratedPaths; m_CollectionHashes = m_Settings.CollectionHashes; @@ -67,6 +69,7 @@ public void SetUp() m_Settings.GenerateAssetTables = false; m_Settings.UseRuntimeAlias = false; m_Settings.SmartStrings = SmartStringMode.Off; + m_Settings.GenerateUniTask = false; m_Settings.Namespace = "CodegenIntegrationTests"; m_Settings.OutputFolder = TestRoot + "/OutA"; m_Settings.CollectionHashes = new string[0]; @@ -84,6 +87,7 @@ public void TearDown() m_Settings.GenerateAssetTables = m_GenerateAssetTables; m_Settings.UseRuntimeAlias = m_UseRuntimeAlias; m_Settings.SmartStrings = m_SmartStrings; + m_Settings.GenerateUniTask = m_GenerateUniTask; m_Settings.LastOutputFolder = m_LastOutputFolder; m_Settings.GeneratedPaths = m_GeneratedPaths; m_Settings.CollectionHashes = m_CollectionHashes; @@ -171,6 +175,27 @@ public void RemovedCollection_DropsItsStoredHash() System.Array.FindAll(m_Settings.CollectionHashes, h => h.StartsWith("S|RemovedCollection|"))); } + [Test] + public void UniTaskOption_EmitsAsyncMembersOnlyWhenTheAddOnIsCompiled() + { + m_Settings.GenerateUniTask = true; + var run = CodeGenerator.Run(new GenerateOptions { PromptOnMassDeletion = false, AllowInBatchMode = true }); + Assert.IsTrue(run.Success, run.Error); + + var output = File.ReadAllText(TestRoot + "/OutA/CodegenIntegration.g.cs"); + if (UniTaskSupport.IsAvailable) + { + StringAssert.Contains("GreetingAsync(", output); + CollectionAssert.DoesNotContain(run.Warnings, UniTaskSupport.MissingMessage); + } + else + { + // Code that references UniTask would not compile, so the option is skipped with a warning. + StringAssert.DoesNotContain("UniTask", output); + CollectionAssert.Contains(run.Warnings, UniTaskSupport.MissingMessage); + } + } + [Test] public void CrLfFileOnDisk_IsNotRewritten() { diff --git a/Unity-Package/Assets/root/Tests/Runtime/UniTask.meta b/Unity-Package/Assets/root/Tests/Runtime/UniTask.meta new file mode 100644 index 0000000..6a88da0 --- /dev/null +++ b/Unity-Package/Assets/root/Tests/Runtime/UniTask.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6b2c9795e2d94ac0a0bcc1653fe0be71 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/Tests/Runtime/UniTask/LocalizedTablesUniTaskTests.cs b/Unity-Package/Assets/root/Tests/Runtime/UniTask/LocalizedTablesUniTaskTests.cs new file mode 100644 index 0000000..dc6903f --- /dev/null +++ b/Unity-Package/Assets/root/Tests/Runtime/UniTask/LocalizedTablesUniTaskTests.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using Cysharp.Threading.Tasks; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Localization; +using UnityEngine.Localization.Settings; +using UnityEngine.ResourceManagement; +using UnityEngine.ResourceManagement.AsyncOperations; + +namespace Severnbli.LocalizationCodegen.Tests +{ + public class LocalizedTablesUniTaskTests + { + /// An operation the test completes by hand. + sealed class ManualOperation : AsyncOperationBase + { + protected override void Execute() + { + } + + public void Succeed(string result) => Complete(result, true, (string)null); + } + + ResourceManager m_ResourceManager; + + [SetUp] + public void SetUp() + { + m_ResourceManager = new ResourceManager(); + } + + [TearDown] + public void TearDown() + { + m_ResourceManager.Dispose(); + } + + static void IgnoreWhenSettingsExist() + { + if (LocalizationSettings.HasSettings) + Assert.Ignore("This test project has LocalizationSettings configured."); + } + + [Test] + public void GetStringAsync_ReturnsKey_WhenSettingsAreMissing() + { + IgnoreWhenSettingsExist(); + + var task = LocalizedTablesUniTask.GetStringAsync("Table", "Key"); + Assert.AreEqual(UniTaskStatus.Succeeded, task.Status); + Assert.AreEqual("Key", task.GetAwaiter().GetResult()); + } + + [Test] + public void GetStringAsyncWithArguments_ReturnsKey_WhenSettingsAreMissing() + { + IgnoreWhenSettingsExist(); + + var named = new Dictionary { ["count"] = 2 }; + var task = LocalizedTablesUniTask.GetStringAsync("Table", "Key", new object[] { 1 }, named); + Assert.AreEqual("Key", task.GetAwaiter().GetResult()); + } + + [Test] + public void GetAssetAsync_ReturnsNull_WhenSettingsAreMissing() + { + IgnoreWhenSettingsExist(); + + var task = LocalizedTablesUniTask.GetAssetAsync("Table", "Key"); + Assert.AreEqual(UniTaskStatus.Succeeded, task.Status); + Assert.IsNull(task.GetAwaiter().GetResult()); + } + + [Test] + public void GetLocalizedStringUniTask_ReturnsKey_WhenSettingsAreMissing() + { + IgnoreWhenSettingsExist(); + + var task = new LocalizedString("Table", "Key").GetLocalizedStringUniTask(); + Assert.AreEqual("Key", task.GetAwaiter().GetResult()); + } + + [Test] + public void AlreadyCancelledToken_ReturnsCancelledTask() + { + var token = new CancellationToken(true); + + Assert.AreEqual(UniTaskStatus.Canceled, LocalizedTablesUniTask.GetStringAsync("Table", "Key", token).Status); + Assert.AreEqual(UniTaskStatus.Canceled, LocalizedTablesUniTask.GetAssetAsync("Table", "Key", token).Status); + } + + [Test] + public void ToUniTask_CompletesWhenTheOperationCompletes() + { + var operation = new ManualOperation(); + var handle = m_ResourceManager.StartOperation(operation, default); + + var task = LocalizedTablesUniTask.ToUniTask(handle, CancellationToken.None); + Assert.AreEqual(UniTaskStatus.Pending, task.Status); + + operation.Succeed("Hello"); + Assert.AreEqual(UniTaskStatus.Succeeded, task.Status); + Assert.AreEqual("Hello", task.GetAwaiter().GetResult()); + + handle.Release(); + } + + [Test] + public void ToUniTask_CancelsWithoutWaitingForTheOperation() + { + var operation = new ManualOperation(); + var handle = m_ResourceManager.StartOperation(operation, default); + + using (var cancellation = new CancellationTokenSource()) + { + var task = LocalizedTablesUniTask.ToUniTask(handle, cancellation.Token); + cancellation.Cancel(); + Assert.AreEqual(UniTaskStatus.Canceled, task.Status); + + // A late completion must not throw or change the result. + Assert.DoesNotThrow(() => operation.Succeed("Late")); + Assert.AreEqual(UniTaskStatus.Canceled, task.Status); + } + + handle.Release(); + } + + [Test] + public void ToUniTask_ReturnsTheResultOfACompletedOperation() + { + var handle = m_ResourceManager.CreateCompletedOperation("Done", null); + + var task = LocalizedTablesUniTask.ToUniTask(handle, CancellationToken.None); + Assert.AreEqual(UniTaskStatus.Succeeded, task.Status); + Assert.AreEqual("Done", task.GetAwaiter().GetResult()); + + handle.Release(); + } + + [Test] + public void ToUniTask_FaultsForAFailedOperation() + { + var handle = m_ResourceManager.CreateCompletedOperationWithException( + null, new InvalidOperationException("Table missing")); + + var task = LocalizedTablesUniTask.ToUniTask(handle, CancellationToken.None); + Assert.AreEqual(UniTaskStatus.Faulted, task.Status); + Assert.Throws(Is.InstanceOf(), () => task.GetAwaiter().GetResult()); + + handle.Release(); + } + + [Test] + public void ToUniTask_FaultsForAnInvalidHandle() + { + var task = LocalizedTablesUniTask.ToUniTask(default(AsyncOperationHandle), CancellationToken.None); + Assert.AreEqual(UniTaskStatus.Faulted, task.Status); + Assert.Throws(() => task.GetAwaiter().GetResult()); + } + } +} diff --git a/Unity-Package/Assets/root/Tests/Runtime/UniTask/LocalizedTablesUniTaskTests.cs.meta b/Unity-Package/Assets/root/Tests/Runtime/UniTask/LocalizedTablesUniTaskTests.cs.meta new file mode 100644 index 0000000..dfdaa8f --- /dev/null +++ b/Unity-Package/Assets/root/Tests/Runtime/UniTask/LocalizedTablesUniTaskTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 86d5e24982d542c48a858b9de3e16cd9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/Tests/Runtime/UniTask/com.severnbli.localization-codegen.UniTask.Tests.asmdef b/Unity-Package/Assets/root/Tests/Runtime/UniTask/com.severnbli.localization-codegen.UniTask.Tests.asmdef new file mode 100644 index 0000000..2a1bb9d --- /dev/null +++ b/Unity-Package/Assets/root/Tests/Runtime/UniTask/com.severnbli.localization-codegen.UniTask.Tests.asmdef @@ -0,0 +1,31 @@ +{ + "name": "com.severnbli.localization-codegen.UniTask.Tests", + "references": [ + "UnityEngine.TestRunner", + "com.severnbli.localization-codegen.Runtime", + "com.severnbli.localization-codegen.UniTask", + "Unity.Localization", + "Unity.ResourceManager", + "UniTask" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": true, + "precompiledReferences": [ + "nunit.framework.dll" + ], + "autoReferenced": false, + "defineConstraints": [ + "UNITY_INCLUDE_TESTS", + "LOCALIZATION_CODEGEN_UNITASK" + ], + "versionDefines": [ + { + "name": "com.cysharp.unitask", + "expression": "2.0.0", + "define": "LOCALIZATION_CODEGEN_UNITASK" + } + ], + "noEngineReferences": false +} diff --git a/Unity-Package/Assets/root/Tests/Runtime/UniTask/com.severnbli.localization-codegen.UniTask.Tests.asmdef.meta b/Unity-Package/Assets/root/Tests/Runtime/UniTask/com.severnbli.localization-codegen.UniTask.Tests.asmdef.meta new file mode 100644 index 0000000..8170306 --- /dev/null +++ b/Unity-Package/Assets/root/Tests/Runtime/UniTask/com.severnbli.localization-codegen.UniTask.Tests.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b63aba92cb0945679013510f1c7c8be3 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/package.json b/Unity-Package/Assets/root/package.json index e292d2b..97f6479 100644 --- a/Unity-Package/Assets/root/package.json +++ b/Unity-Package/Assets/root/package.json @@ -10,7 +10,7 @@ "Generation", "Code Generation" ], - "version": "1.1.1", + "version": "1.2.0", "unity": "2021.3", "description": "C# classes and properties generator from Unity Localization tables", "documentationUrl": "https://github.com/Severnbli/localization-codegen/blob/main/README.md", diff --git a/Unity-Tests/2022.3.62f3/Packages/manifest.json b/Unity-Tests/2022.3.62f3/Packages/manifest.json index 7781219..e9d9f7a 100644 --- a/Unity-Tests/2022.3.62f3/Packages/manifest.json +++ b/Unity-Tests/2022.3.62f3/Packages/manifest.json @@ -1,6 +1,7 @@ { "dependencies": { "com.severnbli.localization-codegen": "file:./../../../Unity-Package/Assets/root", + "com.cysharp.unitask": "2.5.11", "com.unity.feature.development": "1.0.1", "com.unity.test-framework": "1.1.33", "com.unity.toolchain.linux-x86_64": "2.0.11", @@ -37,5 +38,14 @@ }, "testables": [ "com.severnbli.localization-codegen" + ], + "scopedRegistries": [ + { + "name": "package.openupm.com", + "url": "https://package.openupm.com", + "scopes": [ + "com.cysharp.unitask" + ] + } ] } diff --git a/Unity-Tests/2022.3.62f3/Packages/packages-lock.json b/Unity-Tests/2022.3.62f3/Packages/packages-lock.json index 2bf8f35..e80dbfa 100644 --- a/Unity-Tests/2022.3.62f3/Packages/packages-lock.json +++ b/Unity-Tests/2022.3.62f3/Packages/packages-lock.json @@ -1,5 +1,12 @@ { "dependencies": { + "com.cysharp.unitask": { + "version": "2.5.11", + "depth": 0, + "source": "registry", + "dependencies": {}, + "url": "https://package.openupm.com" + }, "com.severnbli.localization-codegen": { "version": "file:./../../../Unity-Package/Assets/root", "depth": 0, diff --git a/commands/check-package.sh b/commands/check-package.sh index ceb511c..ddcd06b 100755 --- a/commands/check-package.sh +++ b/commands/check-package.sh @@ -36,7 +36,13 @@ for changelog in CHANGELOG.md "$package_dir/CHANGELOG.md"; do grep -q "^## \[$version\]" "$changelog" || fail "$changelog has no '## [$version]' entry" done -# 3. Every package asset needs a committed .meta file and every .meta file needs +# 3. The package ships its own copies of the README and changelog (Package +# Manager shows them); they must not drift from the repository root. +for doc in README.md CHANGELOG.md; do + cmp -s "$doc" "$package_dir/$doc" || fail "$package_dir/$doc differs from $doc (copy the root file over it)" +done + +# 4. Every package asset needs a committed .meta file and every .meta file needs # its asset. A missing .meta silently drops the file from the .unitypackage # and gives it a new GUID on every import. Unity ignores hidden entries and # folders ending with '~', so they are skipped. @@ -60,7 +66,7 @@ while IFS= read -r orphan; do [ -n "$orphan" ] && fail "Orphaned .meta without an asset: $package_dir/$orphan.meta" done < <(comm -13 <(echo "$assets") <(echo "$metas")) -# 4. GUIDs must be unique, or Unity reassigns one of them on import. +# 5. GUIDs must be unique, or Unity reassigns one of them on import. duplicates="$(git ls-files -z -- "$package_dir/*.meta" | xargs -0 sed -n 's/^guid: *\([0-9a-f]\{32\}\).*/\1/p' | sort | uniq -d)" [ -z "$duplicates" ] || fail "Duplicate GUIDs in $package_dir: $duplicates"