From 77f12f6441c424c8663af102b2ce03bf17e1f233 Mon Sep 17 00:00:00 2001 From: Virgil Date: Thu, 2 Apr 2026 01:53:57 +0000 Subject: [PATCH] feat(i18n): accept translation contexts in handlers Co-Authored-By: Virgil --- context.go | 9 +++++++++ context_test.go | 1 + handler_test.go | 15 +++++++++++++++ 3 files changed, 25 insertions(+) diff --git a/context.go b/context.go index 53722f4..dbb7dcc 100644 --- a/context.go +++ b/context.go @@ -1,5 +1,7 @@ package i18n +import "fmt" + // TranslationContext provides disambiguation for translations. // // T("direction.right", C("navigation")) // "rechts" (German) @@ -82,6 +84,13 @@ func (c *TranslationContext) ContextString() string { return c.Context } +func (c *TranslationContext) String() string { + if c == nil { + return "" + } + return fmt.Sprint(c.Context) +} + func (c *TranslationContext) GenderString() string { if c == nil { return "" diff --git a/context_test.go b/context_test.go index 870664d..58400a5 100644 --- a/context_test.go +++ b/context_test.go @@ -14,6 +14,7 @@ func TestC_Good(t *testing.T) { require.NotNil(t, ctx) assert.Equal(t, "navigation", ctx.Context) assert.Equal(t, "navigation", ctx.ContextString()) + assert.Equal(t, "navigation", ctx.String()) } func TestC_Good_EmptyContext(t *testing.T) { diff --git a/handler_test.go b/handler_test.go index c9eb4d9..5b2db91 100644 --- a/handler_test.go +++ b/handler_test.go @@ -53,6 +53,11 @@ func TestProgressHandler(t *testing.T) { if got != "Building config.yaml..." { t.Errorf("ProgressHandler.Handle(build, Subject) = %q, want %q", got, "Building config.yaml...") } + + got = h.Handle("i18n.progress.build", []any{C("project")}, nil) + if got != "Building project..." { + t.Errorf("ProgressHandler.Handle(build, TranslationContext) = %q, want %q", got, "Building project...") + } } func TestCountHandler(t *testing.T) { @@ -123,6 +128,11 @@ func TestDoneHandler(t *testing.T) { t.Errorf("DoneHandler.Handle(delete, Subject) = %q, want %q", got, "Config.yaml deleted") } + got = h.Handle("i18n.done.delete", []any{C("config.yaml")}, nil) + if got != "Config.yaml deleted" { + t.Errorf("DoneHandler.Handle(delete, TranslationContext) = %q, want %q", got, "Config.yaml deleted") + } + // Without subject — just past tense got = h.Handle("i18n.done.delete", nil, nil) if got != "Deleted" { @@ -147,6 +157,11 @@ func TestFailHandler(t *testing.T) { t.Errorf("FailHandler.Handle(push, Subject) = %q, want %q", got, "Failed to push commits") } + got = h.Handle("i18n.fail.push", []any{C("commits")}, nil) + if got != "Failed to push commits" { + t.Errorf("FailHandler.Handle(push, TranslationContext) = %q, want %q", got, "Failed to push commits") + } + got = h.Handle("i18n.fail.push", nil, nil) if got != "Failed to push" { t.Errorf("FailHandler.Handle(push) = %q, want %q", got, "Failed to push") -- 2.45.3