From 5d3f99c7c6d0f2c304dc13c6fa6aa675daf310cc Mon Sep 17 00:00:00 2001 From: Gusted Date: Sun, 26 Jun 2022 16:19:22 +0200 Subject: [PATCH] Make better use of i18n (#20096) * Prototyping * Start work on creating offsets * Modify tests * Start prototyping with actual MPH * Twiddle around * Twiddle around comments * Convert templates * Fix external languages * Fix latest translation * Fix some test * Tidy up code * Use simple map * go mod tidy * Move back to data structure - Uses less memory by creating for each language a map. * Apply suggestions from code review Co-authored-by: delvh * Add some comments * Fix tests * Try to fix tests * Use en-US as defacto fallback * Use correct slices * refactor (#4) * Remove TryTr, add log for missing translation key * Refactor i18n - Separate dev and production locale stores. - Allow for live-reloading in dev mode. Co-authored-by: zeripath * Fix live-reloading & check for errors * Make linter happy * live-reload with periodic check (#5) * Fix tests Co-authored-by: delvh Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: wxiaoguang Co-authored-by: zeripath --- integrations/auth_ldap_test.go | 5 +- integrations/branches_test.go | 6 +- integrations/pull_merge_test.go | 4 +- integrations/release_test.go | 12 +- integrations/repo_branch_test.go | 20 +-- integrations/signin_test.go | 10 +- integrations/signup_test.go | 8 +- integrations/user_test.go | 6 +- modules/markup/markdown/toc.go | 4 +- modules/templates/helper.go | 2 - modules/timeutil/since.go | 117 +++++++-------- modules/timeutil/since_test.go | 23 ++- modules/translation/i18n/i18n.go | 142 +++++++++++++----- modules/translation/i18n/i18n_test.go | 44 +++--- modules/translation/translation.go | 52 +++---- routers/web/admin/admin.go | 3 +- routers/web/auth/auth.go | 4 +- routers/web/auth/password.go | 4 +- routers/web/dev/template.go | 4 +- routers/web/repo/blame.go | 2 +- routers/web/repo/issue_content_history.go | 13 +- routers/web/user/setting/account.go | 4 +- routers/web/user/setting/profile.go | 6 +- services/cron/cron.go | 3 +- services/cron/setting.go | 12 +- services/cron/tasks.go | 8 +- services/mailer/mail.go | 6 +- templates/admin/cron.tmpl | 2 +- templates/admin/process-row.tmpl | 2 +- templates/admin/stacktrace-row.tmpl | 2 +- templates/explore/repo_list.tmpl | 2 +- templates/package/shared/list.tmpl | 2 +- templates/package/shared/versionlist.tmpl | 2 +- templates/package/view.tmpl | 2 +- templates/repo/activity.tmpl | 12 +- templates/repo/branch/list.tmpl | 6 +- templates/repo/commit_page.tmpl | 4 +- templates/repo/commits_list.tmpl | 4 +- templates/repo/diff/comments.tmpl | 2 +- templates/repo/issue/milestone_issues.tmpl | 2 +- templates/repo/issue/milestones.tmpl | 2 +- templates/repo/issue/view_content.tmpl | 2 +- .../repo/issue/view_content/comments.tmpl | 6 +- templates/repo/issue/view_content/pull.tmpl | 6 +- templates/repo/issue/view_title.tmpl | 4 +- templates/repo/projects/list.tmpl | 2 +- templates/repo/projects/view.tmpl | 2 +- templates/repo/release/list.tmpl | 4 +- templates/repo/settings/lfs.tmpl | 2 +- templates/repo/settings/lfs_file_find.tmpl | 2 +- templates/repo/settings/lfs_locks.tmpl | 2 +- templates/repo/view_list.tmpl | 4 +- templates/repo/wiki/pages.tmpl | 2 +- templates/repo/wiki/revision.tmpl | 2 +- templates/repo/wiki/view.tmpl | 2 +- templates/shared/issuelist.tmpl | 2 +- templates/shared/searchbottom.tmpl | 2 +- templates/user/dashboard/feeds.tmpl | 2 +- templates/user/dashboard/milestones.tmpl | 2 +- .../user/settings/security/webauthn.tmpl | 2 +- 60 files changed, 340 insertions(+), 282 deletions(-) diff --git a/integrations/auth_ldap_test.go b/integrations/auth_ldap_test.go index 296b647e6..492a4fdad 100644 --- a/integrations/auth_ldap_test.go +++ b/integrations/auth_ldap_test.go @@ -16,7 +16,7 @@ import ( "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" - "code.gitea.io/gitea/modules/translation/i18n" + "code.gitea.io/gitea/modules/translation" "code.gitea.io/gitea/services/auth" "github.com/stretchr/testify/assert" @@ -275,8 +275,7 @@ func TestLDAPUserSigninFailed(t *testing.T) { addAuthSourceLDAP(t, "") u := otherLDAPUsers[0] - - testLoginFailed(t, u.UserName, u.Password, i18n.Tr("en", "form.username_password_incorrect")) + testLoginFailed(t, u.UserName, u.Password, translation.NewLocale("en-US").Tr("form.username_password_incorrect")) } func TestLDAPUserSSHKeySync(t *testing.T) { diff --git a/integrations/branches_test.go b/integrations/branches_test.go index 551c5f8af..8b05e24a0 100644 --- a/integrations/branches_test.go +++ b/integrations/branches_test.go @@ -9,7 +9,7 @@ import ( "net/url" "testing" - "code.gitea.io/gitea/modules/translation/i18n" + "code.gitea.io/gitea/modules/translation" "github.com/stretchr/testify/assert" ) @@ -37,7 +37,7 @@ func TestUndoDeleteBranch(t *testing.T) { htmlDoc, name := branchAction(t, ".undo-button") assert.Contains(t, htmlDoc.doc.Find(".ui.positive.message").Text(), - i18n.Tr("en", "repo.branch.restore_success", name), + translation.NewLocale("en-US").Tr("repo.branch.restore_success", name), ) }) } @@ -46,7 +46,7 @@ func deleteBranch(t *testing.T) { htmlDoc, name := branchAction(t, ".delete-branch-button") assert.Contains(t, htmlDoc.doc.Find(".ui.positive.message").Text(), - i18n.Tr("en", "repo.branch.deletion_success", name), + translation.NewLocale("en-US").Tr("repo.branch.deletion_success", name), ) } diff --git a/integrations/pull_merge_test.go b/integrations/pull_merge_test.go index de519094d..2a3a461ef 100644 --- a/integrations/pull_merge_test.go +++ b/integrations/pull_merge_test.go @@ -27,7 +27,7 @@ import ( "code.gitea.io/gitea/modules/git" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/test" - "code.gitea.io/gitea/modules/translation/i18n" + "code.gitea.io/gitea/modules/translation" "code.gitea.io/gitea/services/pull" repo_service "code.gitea.io/gitea/services/repository" files_service "code.gitea.io/gitea/services/repository/files" @@ -204,7 +204,7 @@ func TestCantMergeWorkInProgress(t *testing.T) { text := strings.TrimSpace(htmlDoc.doc.Find(".merge-section > .item").Last().Text()) assert.NotEmpty(t, text, "Can't find WIP text") - assert.Contains(t, text, i18n.Tr("en", "repo.pulls.cannot_merge_work_in_progress"), "Unable to find WIP text") + assert.Contains(t, text, translation.NewLocale("en-US").Tr("repo.pulls.cannot_merge_work_in_progress"), "Unable to find WIP text") assert.Contains(t, text, "[wip]", "Unable to find WIP text") }) } diff --git a/integrations/release_test.go b/integrations/release_test.go index d75d74956..dd32a64ed 100644 --- a/integrations/release_test.go +++ b/integrations/release_test.go @@ -14,7 +14,7 @@ import ( "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/test" - "code.gitea.io/gitea/modules/translation/i18n" + "code.gitea.io/gitea/modules/translation" "github.com/PuerkitoBio/goquery" "github.com/stretchr/testify/assert" @@ -86,7 +86,7 @@ func TestCreateRelease(t *testing.T) { session := loginUser(t, "user2") createNewRelease(t, session, "/user2/repo1", "v0.0.1", "v0.0.1", false, false) - checkLatestReleaseAndCount(t, session, "/user2/repo1", "v0.0.1", i18n.Tr("en", "repo.release.stable"), 4) + checkLatestReleaseAndCount(t, session, "/user2/repo1", "v0.0.1", translation.NewLocale("en-US").Tr("repo.release.stable"), 4) } func TestCreateReleasePreRelease(t *testing.T) { @@ -95,7 +95,7 @@ func TestCreateReleasePreRelease(t *testing.T) { session := loginUser(t, "user2") createNewRelease(t, session, "/user2/repo1", "v0.0.1", "v0.0.1", true, false) - checkLatestReleaseAndCount(t, session, "/user2/repo1", "v0.0.1", i18n.Tr("en", "repo.release.prerelease"), 4) + checkLatestReleaseAndCount(t, session, "/user2/repo1", "v0.0.1", translation.NewLocale("en-US").Tr("repo.release.prerelease"), 4) } func TestCreateReleaseDraft(t *testing.T) { @@ -104,7 +104,7 @@ func TestCreateReleaseDraft(t *testing.T) { session := loginUser(t, "user2") createNewRelease(t, session, "/user2/repo1", "v0.0.1", "v0.0.1", false, true) - checkLatestReleaseAndCount(t, session, "/user2/repo1", "v0.0.1", i18n.Tr("en", "repo.release.draft"), 4) + checkLatestReleaseAndCount(t, session, "/user2/repo1", "v0.0.1", translation.NewLocale("en-US").Tr("repo.release.draft"), 4) } func TestCreateReleasePaging(t *testing.T) { @@ -124,11 +124,11 @@ func TestCreateReleasePaging(t *testing.T) { } createNewRelease(t, session, "/user2/repo1", "v0.0.12", "v0.0.12", false, true) - checkLatestReleaseAndCount(t, session, "/user2/repo1", "v0.0.12", i18n.Tr("en", "repo.release.draft"), 10) + checkLatestReleaseAndCount(t, session, "/user2/repo1", "v0.0.12", translation.NewLocale("en-US").Tr("repo.release.draft"), 10) // Check that user4 does not see draft and still see 10 latest releases session2 := loginUser(t, "user4") - checkLatestReleaseAndCount(t, session2, "/user2/repo1", "v0.0.11", i18n.Tr("en", "repo.release.stable"), 10) + checkLatestReleaseAndCount(t, session2, "/user2/repo1", "v0.0.11", translation.NewLocale("en-US").Tr("repo.release.stable"), 10) } func TestViewReleaseListNoLogin(t *testing.T) { diff --git a/integrations/repo_branch_test.go b/integrations/repo_branch_test.go index 30a446cce..74d85c5b1 100644 --- a/integrations/repo_branch_test.go +++ b/integrations/repo_branch_test.go @@ -13,7 +13,7 @@ import ( "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/test" - "code.gitea.io/gitea/modules/translation/i18n" + "code.gitea.io/gitea/modules/translation" "github.com/stretchr/testify/assert" ) @@ -52,37 +52,37 @@ func testCreateBranches(t *testing.T, giteaURL *url.URL) { OldRefSubURL: "branch/master", NewBranch: "feature/test1", ExpectedStatus: http.StatusSeeOther, - FlashMessage: i18n.Tr("en", "repo.branch.create_success", "feature/test1"), + FlashMessage: translation.NewLocale("en-US").Tr("repo.branch.create_success", "feature/test1"), }, { OldRefSubURL: "branch/master", NewBranch: "", ExpectedStatus: http.StatusSeeOther, - FlashMessage: i18n.Tr("en", "form.NewBranchName") + i18n.Tr("en", "form.require_error"), + FlashMessage: translation.NewLocale("en-US").Tr("form.NewBranchName") + translation.NewLocale("en-US").Tr("form.require_error"), }, { OldRefSubURL: "branch/master", NewBranch: "feature=test1", ExpectedStatus: http.StatusSeeOther, - FlashMessage: i18n.Tr("en", "repo.branch.create_success", "feature=test1"), + FlashMessage: translation.NewLocale("en-US").Tr("repo.branch.create_success", "feature=test1"), }, { OldRefSubURL: "branch/master", NewBranch: strings.Repeat("b", 101), ExpectedStatus: http.StatusSeeOther, - FlashMessage: i18n.Tr("en", "form.NewBranchName") + i18n.Tr("en", "form.max_size_error", "100"), + FlashMessage: translation.NewLocale("en-US").Tr("form.NewBranchName") + translation.NewLocale("en-US").Tr("form.max_size_error", "100"), }, { OldRefSubURL: "branch/master", NewBranch: "master", ExpectedStatus: http.StatusSeeOther, - FlashMessage: i18n.Tr("en", "repo.branch.branch_already_exists", "master"), + FlashMessage: translation.NewLocale("en-US").Tr("repo.branch.branch_already_exists", "master"), }, { OldRefSubURL: "branch/master", NewBranch: "master/test", ExpectedStatus: http.StatusSeeOther, - FlashMessage: i18n.Tr("en", "repo.branch.branch_name_conflict", "master/test", "master"), + FlashMessage: translation.NewLocale("en-US").Tr("repo.branch.branch_name_conflict", "master/test", "master"), }, { OldRefSubURL: "commit/acd1d892867872cb47f3993468605b8aa59aa2e0", @@ -93,21 +93,21 @@ func testCreateBranches(t *testing.T, giteaURL *url.URL) { OldRefSubURL: "commit/65f1bf27bc3bf70f64657658635e66094edbcb4d", NewBranch: "feature/test3", ExpectedStatus: http.StatusSeeOther, - FlashMessage: i18n.Tr("en", "repo.branch.create_success", "feature/test3"), + FlashMessage: translation.NewLocale("en-US").Tr("repo.branch.create_success", "feature/test3"), }, { OldRefSubURL: "branch/master", NewBranch: "v1.0.0", CreateRelease: "v1.0.0", ExpectedStatus: http.StatusSeeOther, - FlashMessage: i18n.Tr("en", "repo.branch.tag_collision", "v1.0.0"), + FlashMessage: translation.NewLocale("en-US").Tr("repo.branch.tag_collision", "v1.0.0"), }, { OldRefSubURL: "tag/v1.0.0", NewBranch: "feature/test4", CreateRelease: "v1.0.1", ExpectedStatus: http.StatusSeeOther, - FlashMessage: i18n.Tr("en", "repo.branch.create_success", "feature/test4"), + FlashMessage: translation.NewLocale("en-US").Tr("repo.branch.create_success", "feature/test4"), }, } for _, test := range tests { diff --git a/integrations/signin_test.go b/integrations/signin_test.go index 811f9326e..952efcfdd 100644 --- a/integrations/signin_test.go +++ b/integrations/signin_test.go @@ -11,7 +11,7 @@ import ( "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" - "code.gitea.io/gitea/modules/translation/i18n" + "code.gitea.io/gitea/modules/translation" "github.com/stretchr/testify/assert" ) @@ -47,10 +47,10 @@ func TestSignin(t *testing.T) { password string message string }{ - {username: "wrongUsername", password: "wrongPassword", message: i18n.Tr("en", "form.username_password_incorrect")}, - {username: "wrongUsername", password: "password", message: i18n.Tr("en", "form.username_password_incorrect")}, - {username: "user15", password: "wrongPassword", message: i18n.Tr("en", "form.username_password_incorrect")}, - {username: "user1@example.com", password: "wrongPassword", message: i18n.Tr("en", "form.username_password_incorrect")}, + {username: "wrongUsername", password: "wrongPassword", message: translation.NewLocale("en-US").Tr("form.username_password_incorrect")}, + {username: "wrongUsername", password: "password", message: translation.NewLocale("en-US").Tr("form.username_password_incorrect")}, + {username: "user15", password: "wrongPassword", message: translation.NewLocale("en-US").Tr("form.username_password_incorrect")}, + {username: "user1@example.com", password: "wrongPassword", message: translation.NewLocale("en-US").Tr("form.username_password_incorrect")}, } for _, s := range samples { diff --git a/integrations/signup_test.go b/integrations/signup_test.go index 7b4567437..b34e40f28 100644 --- a/integrations/signup_test.go +++ b/integrations/signup_test.go @@ -13,7 +13,7 @@ import ( "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/translation/i18n" + "code.gitea.io/gitea/modules/translation" "github.com/stretchr/testify/assert" ) @@ -68,9 +68,9 @@ func TestSignupEmail(t *testing.T) { wantStatus int wantMsg string }{ - {"exampleUser@example.com\r\n", http.StatusOK, i18n.Tr("en", "form.email_invalid")}, - {"exampleUser@example.com\r", http.StatusOK, i18n.Tr("en", "form.email_invalid")}, - {"exampleUser@example.com\n", http.StatusOK, i18n.Tr("en", "form.email_invalid")}, + {"exampleUser@example.com\r\n", http.StatusOK, translation.NewLocale("en-US").Tr("form.email_invalid")}, + {"exampleUser@example.com\r", http.StatusOK, translation.NewLocale("en-US").Tr("form.email_invalid")}, + {"exampleUser@example.com\n", http.StatusOK, translation.NewLocale("en-US").Tr("form.email_invalid")}, {"exampleUser@example.com", http.StatusSeeOther, ""}, } diff --git a/integrations/user_test.go b/integrations/user_test.go index 41127a4e4..33113369a 100644 --- a/integrations/user_test.go +++ b/integrations/user_test.go @@ -14,7 +14,7 @@ import ( user_model "code.gitea.io/gitea/models/user" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/test" - "code.gitea.io/gitea/modules/translation/i18n" + "code.gitea.io/gitea/modules/translation" "github.com/stretchr/testify/assert" ) @@ -67,7 +67,7 @@ func TestRenameInvalidUsername(t *testing.T) { htmlDoc := NewHTMLParser(t, resp.Body) assert.Contains(t, htmlDoc.doc.Find(".ui.negative.message").Text(), - i18n.Tr("en", "form.alpha_dash_dot_error"), + translation.NewLocale("en-US").Tr("form.alpha_dash_dot_error"), ) unittest.AssertNotExistsBean(t, &user_model.User{Name: invalidUsername}) @@ -131,7 +131,7 @@ func TestRenameReservedUsername(t *testing.T) { htmlDoc := NewHTMLParser(t, resp.Body) assert.Contains(t, htmlDoc.doc.Find(".ui.negative.message").Text(), - i18n.Tr("en", "user.form.name_reserved", reservedUsername), + translation.NewLocale("en-US").Tr("user.form.name_reserved", reservedUsername), ) unittest.AssertNotExistsBean(t, &user_model.User{Name: reservedUsername}) diff --git a/modules/markup/markdown/toc.go b/modules/markup/markdown/toc.go index fec45103e..103894d1a 100644 --- a/modules/markup/markdown/toc.go +++ b/modules/markup/markdown/toc.go @@ -9,7 +9,7 @@ import ( "net/url" "code.gitea.io/gitea/modules/markup" - "code.gitea.io/gitea/modules/translation/i18n" + "code.gitea.io/gitea/modules/translation" "github.com/yuin/goldmark/ast" ) @@ -18,7 +18,7 @@ func createTOCNode(toc []markup.Header, lang string) ast.Node { details := NewDetails() summary := NewSummary() - summary.AppendChild(summary, ast.NewString([]byte(i18n.Tr(lang, "toc")))) + summary.AppendChild(summary, ast.NewString([]byte(translation.NewLocale(lang).Tr("toc")))) details.AppendChild(details, summary) ul := ast.NewList('-') details.AppendChild(details, ul) diff --git a/modules/templates/helper.go b/modules/templates/helper.go index 93463ce0c..4679cf9eb 100644 --- a/modules/templates/helper.go +++ b/modules/templates/helper.go @@ -105,7 +105,6 @@ func NewFuncMap() []template.FuncMap { "Str2html": Str2html, "TimeSince": timeutil.TimeSince, "TimeSinceUnix": timeutil.TimeSinceUnix, - "RawTimeSince": timeutil.RawTimeSince, "FileSize": base.FileSize, "PrettyNumber": base.PrettyNumber, "JsPrettyNumber": JsPrettyNumber, @@ -484,7 +483,6 @@ func NewTextFuncMap() []texttmpl.FuncMap { }, "TimeSince": timeutil.TimeSince, "TimeSinceUnix": timeutil.TimeSinceUnix, - "RawTimeSince": timeutil.RawTimeSince, "DateFmtLong": func(t time.Time) string { return t.Format(time.RFC1123Z) }, diff --git a/modules/timeutil/since.go b/modules/timeutil/since.go index b22fe59ba..5e89b0faa 100644 --- a/modules/timeutil/since.go +++ b/modules/timeutil/since.go @@ -12,7 +12,7 @@ import ( "time" "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/translation/i18n" + "code.gitea.io/gitea/modules/translation" ) // Seconds-based time units @@ -29,146 +29,146 @@ func round(s float64) int64 { return int64(math.Round(s)) } -func computeTimeDiffFloor(diff int64, lang string) (int64, string) { - var diffStr string +func computeTimeDiffFloor(diff int64, lang translation.Locale) (int64, string) { + diffStr := "" switch { case diff <= 0: diff = 0 - diffStr = i18n.Tr(lang, "tool.now") + diffStr = lang.Tr("tool.now") case diff < 2: diff = 0 - diffStr = i18n.Tr(lang, "tool.1s") + diffStr = lang.Tr("tool.1s") case diff < 1*Minute: - diffStr = i18n.Tr(lang, "tool.seconds", diff) + diffStr = lang.Tr("tool.seconds", diff) diff = 0 case diff < 2*Minute: diff -= 1 * Minute - diffStr = i18n.Tr(lang, "tool.1m") + diffStr = lang.Tr("tool.1m") case diff < 1*Hour: - diffStr = i18n.Tr(lang, "tool.minutes", diff/Minute) + diffStr = lang.Tr("tool.minutes", diff/Minute) diff -= diff / Minute * Minute case diff < 2*Hour: diff -= 1 * Hour - diffStr = i18n.Tr(lang, "tool.1h") + diffStr = lang.Tr("tool.1h") case diff < 1*Day: - diffStr = i18n.Tr(lang, "tool.hours", diff/Hour) + diffStr = lang.Tr("tool.hours", diff/Hour) diff -= diff / Hour * Hour case diff < 2*Day: diff -= 1 * Day - diffStr = i18n.Tr(lang, "tool.1d") + diffStr = lang.Tr("tool.1d") case diff < 1*Week: - diffStr = i18n.Tr(lang, "tool.days", diff/Day) + diffStr = lang.Tr("tool.days", diff/Day) diff -= diff / Day * Day case diff < 2*Week: diff -= 1 * Week - diffStr = i18n.Tr(lang, "tool.1w") + diffStr = lang.Tr("tool.1w") case diff < 1*Month: - diffStr = i18n.Tr(lang, "tool.weeks", diff/Week) + diffStr = lang.Tr("tool.weeks", diff/Week) diff -= diff / Week * Week case diff < 2*Month: diff -= 1 * Month - diffStr = i18n.Tr(lang, "tool.1mon") + diffStr = lang.Tr("tool.1mon") case diff < 1*Year: - diffStr = i18n.Tr(lang, "tool.months", diff/Month) + diffStr = lang.Tr("tool.months", diff/Month) diff -= diff / Month * Month case diff < 2*Year: diff -= 1 * Year - diffStr = i18n.Tr(lang, "tool.1y") + diffStr = lang.Tr("tool.1y") default: - diffStr = i18n.Tr(lang, "tool.years", diff/Year) + diffStr = lang.Tr("tool.years", diff/Year) diff -= (diff / Year) * Year } return diff, diffStr } -func computeTimeDiff(diff int64, lang string) (int64, string) { - var diffStr string +func computeTimeDiff(diff int64, lang translation.Locale) (int64, string) { + diffStr := "" switch { case diff <= 0: diff = 0 - diffStr = i18n.Tr(lang, "tool.now") + diffStr = lang.Tr("tool.now") case diff < 2: diff = 0 - diffStr = i18n.Tr(lang, "tool.1s") + diffStr = lang.Tr("tool.1s") case diff < 1*Minute: - diffStr = i18n.Tr(lang, "tool.seconds", diff) + diffStr = lang.Tr("tool.seconds", diff) diff = 0 case diff < Minute+Minute/2: diff -= 1 * Minute - diffStr = i18n.Tr(lang, "tool.1m") + diffStr = lang.Tr("tool.1m") case diff < 1*Hour: minutes := round(float64(diff) / Minute) if minutes > 1 { - diffStr = i18n.Tr(lang, "tool.minutes", minutes) + diffStr = lang.Tr("tool.minutes", minutes) } else { - diffStr = i18n.Tr(lang, "tool.1m") + diffStr = lang.Tr("tool.1m") } diff -= diff / Minute * Minute case diff < Hour+Hour/2: diff -= 1 * Hour - diffStr = i18n.Tr(lang, "tool.1h") + diffStr = lang.Tr("tool.1h") case diff < 1*Day: hours := round(float64(diff) / Hour) if hours > 1 { - diffStr = i18n.Tr(lang, "tool.hours", hours) + diffStr = lang.Tr("tool.hours", hours) } else { - diffStr = i18n.Tr(lang, "tool.1h") + diffStr = lang.Tr("tool.1h") } diff -= diff / Hour * Hour case diff < Day+Day/2: diff -= 1 * Day - diffStr = i18n.Tr(lang, "tool.1d") + diffStr = lang.Tr("tool.1d") case diff < 1*Week: days := round(float64(diff) / Day) if days > 1 { - diffStr = i18n.Tr(lang, "tool.days", days) + diffStr = lang.Tr("tool.days", days) } else { - diffStr = i18n.Tr(lang, "tool.1d") + diffStr = lang.Tr("tool.1d") } diff -= diff / Day * Day case diff < Week+Week/2: diff -= 1 * Week - diffStr = i18n.Tr(lang, "tool.1w") + diffStr = lang.Tr("tool.1w") case diff < 1*Month: weeks := round(float64(diff) / Week) if weeks > 1 { - diffStr = i18n.Tr(lang, "tool.weeks", weeks) + diffStr = lang.Tr("tool.weeks", weeks) } else { - diffStr = i18n.Tr(lang, "tool.1w") + diffStr = lang.Tr("tool.1w") } diff -= diff / Week * Week case diff < 1*Month+Month/2: diff -= 1 * Month - diffStr = i18n.Tr(lang, "tool.1mon") + diffStr = lang.Tr("tool.1mon") case diff < 1*Year: months := round(float64(diff) / Month) if months > 1 { - diffStr = i18n.Tr(lang, "tool.months", months) + diffStr = lang.Tr("tool.months", months) } else { - diffStr = i18n.Tr(lang, "tool.1mon") + diffStr = lang.Tr("tool.1mon") } diff -= diff / Month * Month case diff < Year+Year/2: diff -= 1 * Year - diffStr = i18n.Tr(lang, "tool.1y") + diffStr = lang.Tr("tool.1y") default: years := round(float64(diff) / Year) if years > 1 { - diffStr = i18n.Tr(lang, "tool.years", years) + diffStr = lang.Tr("tool.years", years) } else { - diffStr = i18n.Tr(lang, "tool.1y") + diffStr = lang.Tr("tool.1y") } diff -= (diff / Year) * Year } @@ -177,24 +177,24 @@ func computeTimeDiff(diff int64, lang string) (int64, string) { // MinutesToFriendly returns a user friendly string with number of minutes // converted to hours and minutes. -func MinutesToFriendly(minutes int, lang string) string { +func MinutesToFriendly(minutes int, lang translation.Locale) string { duration := time.Duration(minutes) * time.Minute return TimeSincePro(time.Now().Add(-duration), lang) } // TimeSincePro calculates the time interval and generate full user-friendly string. -func TimeSincePro(then time.Time, lang string) string { +func TimeSincePro(then time.Time, lang translation.Locale) string { return timeSincePro(then, time.Now(), lang) } -func timeSincePro(then, now time.Time, lang string) string { +func timeSincePro(then, now time.Time, lang translation.Locale) string { diff := now.Unix() - then.Unix() if then.After(now) { - return i18n.Tr(lang, "tool.future") + return lang.Tr("tool.future") } if diff == 0 { - return i18n.Tr(lang, "tool.now") + return lang.Tr("tool.now") } var timeStr, diffStr string @@ -209,11 +209,11 @@ func timeSincePro(then, now time.Time, lang string) string { return strings.TrimPrefix(timeStr, ", ") } -func timeSince(then, now time.Time, lang string) string { +func timeSince(then, now time.Time, lang translation.Locale) string { return timeSinceUnix(then.Unix(), now.Unix(), lang) } -func timeSinceUnix(then, now int64, lang string) string { +func timeSinceUnix(then, now int64, lang translation.Locale) string { lbl := "tool.ago" diff := now - then if then > now { @@ -221,36 +221,31 @@ func timeSinceUnix(then, now int64, lang string) string { diff = then - now } if diff <= 0 { - return i18n.Tr(lang, "tool.now") + return lang.Tr("tool.now") } _, diffStr := computeTimeDiff(diff, lang) - return i18n.Tr(lang, lbl, diffStr) -} - -// RawTimeSince retrieves i18n key of time since t -func RawTimeSince(t time.Time, lang string) string { - return timeSince(t, time.Now(), lang) + return lang.Tr(lbl, diffStr) } // TimeSince calculates the time interval and generate user-friendly string. -func TimeSince(then time.Time, lang string) template.HTML { +func TimeSince(then time.Time, lang translation.Locale) template.HTML { return htmlTimeSince(then, time.Now(), lang) } -func htmlTimeSince(then, now time.Time, lang string) template.HTML { +func htmlTimeSince(then, now time.Time, lang translation.Locale) template.HTML { return template.HTML(fmt.Sprintf(`%s`, - then.In(setting.DefaultUILocation).Format(GetTimeFormat(lang)), + then.In(setting.DefaultUILocation).Format(GetTimeFormat(lang.Language())), timeSince(then, now, lang))) } // TimeSinceUnix calculates the time interval and generate user-friendly string. -func TimeSinceUnix(then TimeStamp, lang string) template.HTML { +func TimeSinceUnix(then TimeStamp, lang translation.Locale) template.HTML { return htmlTimeSinceUnix(then, TimeStamp(time.Now().Unix()), lang) } -func htmlTimeSinceUnix(then, now TimeStamp, lang string) template.HTML { +func htmlTimeSinceUnix(then, now TimeStamp, lang translation.Locale) template.HTML { return template.HTML(fmt.Sprintf(`%s`, - then.FormatInLocation(GetTimeFormat(lang), setting.DefaultUILocation), + then.FormatInLocation(GetTimeFormat(lang.Language()), setting.DefaultUILocation), timeSinceUnix(int64(then), int64(now), lang))) } diff --git a/modules/timeutil/since_test.go b/modules/timeutil/since_test.go index 49951b6e4..8bdb9d754 100644 --- a/modules/timeutil/since_test.go +++ b/modules/timeutil/since_test.go @@ -12,7 +12,6 @@ import ( "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/translation" - "code.gitea.io/gitea/modules/translation/i18n" "github.com/stretchr/testify/assert" ) @@ -42,16 +41,16 @@ func TestMain(m *testing.M) { } func TestTimeSince(t *testing.T) { - assert.Equal(t, "now", timeSince(BaseDate, BaseDate, "en")) + assert.Equal(t, "now", timeSince(BaseDate, BaseDate, translation.NewLocale("en-US"))) // test that each diff in `diffs` yields the expected string test := func(expected string, diffs ...time.Duration) { t.Run(expected, func(t *testing.T) { for _, diff := range diffs { - actual := timeSince(BaseDate, BaseDate.Add(diff), "en") - assert.Equal(t, i18n.Tr("en", "tool.ago", expected), actual) - actual = timeSince(BaseDate.Add(diff), BaseDate, "en") - assert.Equal(t, i18n.Tr("en", "tool.from_now", expected), actual) + actual := timeSince(BaseDate, BaseDate.Add(diff), translation.NewLocale("en-US")) + assert.Equal(t, translation.NewLocale("en-US").Tr("tool.ago", expected), actual) + actual = timeSince(BaseDate.Add(diff), BaseDate, translation.NewLocale("en-US")) + assert.Equal(t, translation.NewLocale("en-US").Tr("tool.from_now", expected), actual) } }) } @@ -82,13 +81,13 @@ func TestTimeSince(t *testing.T) { } func TestTimeSincePro(t *testing.T) { - assert.Equal(t, "now", timeSincePro(BaseDate, BaseDate, "en")) + assert.Equal(t, "now", timeSincePro(BaseDate, BaseDate, translation.NewLocale("en-US"))) // test that a difference of `diff` yields the expected string test := func(expected string, diff time.Duration) { - actual := timeSincePro(BaseDate, BaseDate.Add(diff), "en") + actual := timeSincePro(BaseDate, BaseDate.Add(diff), translation.NewLocale("en-US")) assert.Equal(t, expected, actual) - assert.Equal(t, "future", timeSincePro(BaseDate.Add(diff), BaseDate, "en")) + assert.Equal(t, "future", timeSincePro(BaseDate.Add(diff), BaseDate, translation.NewLocale("en-US"))) } test("1 second", time.Second) test("2 seconds", 2*time.Second) @@ -119,7 +118,7 @@ func TestHtmlTimeSince(t *testing.T) { setting.DefaultUILocation = time.UTC // test that `diff` yields a result containing `expected` test := func(expected string, diff time.Duration) { - actual := htmlTimeSince(BaseDate, BaseDate.Add(diff), "en") + actual := htmlTimeSince(BaseDate, BaseDate.Add(diff), translation.NewLocale("en-US")) assert.Contains(t, actual, `title="Sat Jan 1 00:00:00 UTC 2000"`) assert.Contains(t, actual, expected) } @@ -138,7 +137,7 @@ func TestComputeTimeDiff(t *testing.T) { test := func(base int64, str string, offsets ...int64) { for _, offset := range offsets { t.Run(fmt.Sprintf("%s:%d", str, offset), func(t *testing.T) { - diff, diffStr := computeTimeDiff(base+offset, "en") + diff, diffStr := computeTimeDiff(base+offset, translation.NewLocale("en-US")) assert.Equal(t, offset, diff) assert.Equal(t, str, diffStr) }) @@ -171,7 +170,7 @@ func TestComputeTimeDiff(t *testing.T) { func TestMinutesToFriendly(t *testing.T) { // test that a number of minutes yields the expected string test := func(expected string, minutes int) { - actual := MinutesToFriendly(minutes, "en") + actual := MinutesToFriendly(minutes, translation.NewLocale("en-US")) assert.Equal(t, expected, actual) } test("1 minute", 1) diff --git a/modules/translation/i18n/i18n.go b/modules/translation/i18n/i18n.go index 664e457ec..acce5f19f 100644 --- a/modules/translation/i18n/i18n.go +++ b/modules/translation/i18n/i18n.go @@ -7,10 +7,13 @@ package i18n import ( "errors" "fmt" + "os" "reflect" - "strings" + "sync" + "time" "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/setting" "gopkg.in/ini.v1" ) @@ -18,45 +21,90 @@ import ( var ( ErrLocaleAlreadyExist = errors.New("lang already exists") - DefaultLocales = NewLocaleStore() + DefaultLocales = NewLocaleStore(true) ) type locale struct { store *LocaleStore langName string - langDesc string - messages *ini.File + textMap map[int]string // the map key (idx) is generated by store's textIdxMap + + sourceFileName string + sourceFileInfo os.FileInfo + lastReloadCheckTime time.Time } type LocaleStore struct { - // at the moment, all these fields are readonly after initialization - langNames []string - langDescs []string - localeMap map[string]*locale + reloadMu *sync.Mutex // for non-prod(dev), use a mutex for live-reload. for prod, no mutex, no live-reload. + + langNames []string + langDescs []string + + localeMap map[string]*locale + textIdxMap map[string]int + defaultLang string } -func NewLocaleStore() *LocaleStore { - return &LocaleStore{localeMap: make(map[string]*locale)} +func NewLocaleStore(isProd bool) *LocaleStore { + ls := &LocaleStore{localeMap: make(map[string]*locale), textIdxMap: make(map[string]int)} + if !isProd { + ls.reloadMu = &sync.Mutex{} + } + return ls } // AddLocaleByIni adds locale by ini into the store -func (ls *LocaleStore) AddLocaleByIni(langName, langDesc string, localeFile interface{}, otherLocaleFiles ...interface{}) error { +// if source is a string, then the file is loaded. in dev mode, the file can be live-reloaded +// if source is a []byte, then the content is used +func (ls *LocaleStore) AddLocaleByIni(langName, langDesc string, source interface{}) error { if _, ok := ls.localeMap[langName]; ok { return ErrLocaleAlreadyExist } + + lc := &locale{store: ls, langName: langName} + if fileName, ok := source.(string); ok { + lc.sourceFileName = fileName + lc.sourceFileInfo, _ = os.Stat(fileName) // live-reload only works for regular files. the error can be ignored + } + + ls.langNames = append(ls.langNames, langName) + ls.langDescs = append(ls.langDescs, langDesc) + ls.localeMap[lc.langName] = lc + + return ls.reloadLocaleByIni(langName, source) +} + +func (ls *LocaleStore) reloadLocaleByIni(langName string, source interface{}) error { iniFile, err := ini.LoadSources(ini.LoadOptions{ IgnoreInlineComment: true, UnescapeValueCommentSymbols: true, - }, localeFile, otherLocaleFiles...) - if err == nil { - iniFile.BlockMode = false - lc := &locale{store: ls, langName: langName, langDesc: langDesc, messages: iniFile} - ls.langNames = append(ls.langNames, lc.langName) - ls.langDescs = append(ls.langDescs, lc.langDesc) - ls.localeMap[lc.langName] = lc + }, source) + if err != nil { + return fmt.Errorf("unable to load ini: %w", err) } - return err + iniFile.BlockMode = false + + lc := ls.localeMap[langName] + lc.textMap = make(map[int]string) + for _, section := range iniFile.Sections() { + for _, key := range section.Keys() { + var trKey string + if section.Name() == "" || section.Name() == "DEFAULT" { + trKey = key.Name() + } else { + trKey = section.Name() + "." + key.Name() + } + textIdx, ok := ls.textIdxMap[trKey] + if !ok { + textIdx = len(ls.textIdxMap) + ls.textIdxMap[trKey] = textIdx + } + lc.textMap[textIdx] = key.Value() + } + } + iniFile = nil + return nil } func (ls *LocaleStore) HasLang(langName string) bool { @@ -87,25 +135,39 @@ func (ls *LocaleStore) Tr(lang, trKey string, trArgs ...interface{}) string { // Tr translates content to locale language. fall back to default language. func (l *locale) Tr(trKey string, trArgs ...interface{}) string { - var section string - - idx := strings.IndexByte(trKey, '.') - if idx > 0 { - section = trKey[:idx] - trKey = trKey[idx+1:] - } - - trMsg := trKey - if trIni, err := l.messages.Section(section).GetKey(trKey); err == nil { - trMsg = trIni.Value() - } else if l.store.defaultLang != "" && l.langName != l.store.defaultLang { - // try to fall back to default - if defaultLocale, ok := l.store.localeMap[l.store.defaultLang]; ok { - if trIni, err = defaultLocale.messages.Section(section).GetKey(trKey); err == nil { - trMsg = trIni.Value() + if l.store.reloadMu != nil { + l.store.reloadMu.Lock() + defer l.store.reloadMu.Unlock() + now := time.Now() + if now.Sub(l.lastReloadCheckTime) >= time.Second && l.sourceFileInfo != nil && l.sourceFileName != "" { + l.lastReloadCheckTime = now + if sourceFileInfo, err := os.Stat(l.sourceFileName); err == nil && !sourceFileInfo.ModTime().Equal(l.sourceFileInfo.ModTime()) { + if err = l.store.reloadLocaleByIni(l.langName, l.sourceFileName); err == nil { + l.sourceFileInfo = sourceFileInfo + } else { + log.Error("unable to live-reload the locale file %q, err: %v", l.sourceFileName, err) + } } } } + msg, _ := l.tryTr(trKey, trArgs...) + return msg +} + +func (l *locale) tryTr(trKey string, trArgs ...interface{}) (msg string, found bool) { + trMsg := trKey + textIdx, ok := l.store.textIdxMap[trKey] + if ok { + if msg, found = l.textMap[textIdx]; found { + trMsg = msg // use current translation + } else if l.langName != l.store.defaultLang { + if def, ok := l.store.localeMap[l.store.defaultLang]; ok { + return def.tryTr(trKey, trArgs...) + } + } else if !setting.IsProd { + log.Error("missing i18n translation key: %q", trKey) + } + } if len(trArgs) > 0 { fmtArgs := make([]interface{}, 0, len(trArgs)) @@ -128,13 +190,15 @@ func (l *locale) Tr(trKey string, trArgs ...interface{}) string { fmtArgs = append(fmtArgs, arg) } } - return fmt.Sprintf(trMsg, fmtArgs...) + return fmt.Sprintf(trMsg, fmtArgs...), found } - return trMsg + return trMsg, found } -func ResetDefaultLocales() { - DefaultLocales = NewLocaleStore() +// ResetDefaultLocales resets the current default locales +// NOTE: this is not synchronized +func ResetDefaultLocales(isProd bool) { + DefaultLocales = NewLocaleStore(isProd) } // Tr use default locales to translate content to target language. diff --git a/modules/translation/i18n/i18n_test.go b/modules/translation/i18n/i18n_test.go index 70066016c..32f7585b3 100644 --- a/modules/translation/i18n/i18n_test.go +++ b/modules/translation/i18n/i18n_test.go @@ -27,30 +27,36 @@ fmt = %[2]s %[1]s sub = Changed Sub String `) - ls := NewLocaleStore() - assert.NoError(t, ls.AddLocaleByIni("lang1", "Lang1", testData1)) - assert.NoError(t, ls.AddLocaleByIni("lang2", "Lang2", testData2)) - ls.SetDefaultLang("lang1") + for _, isProd := range []bool{true, false} { + ls := NewLocaleStore(isProd) + assert.NoError(t, ls.AddLocaleByIni("lang1", "Lang1", testData1)) + assert.NoError(t, ls.AddLocaleByIni("lang2", "Lang2", testData2)) + ls.SetDefaultLang("lang1") - result := ls.Tr("lang1", "fmt", "a", "b") - assert.Equal(t, "a b", result) + result := ls.Tr("lang1", "fmt", "a", "b") + assert.Equal(t, "a b", result) - result = ls.Tr("lang2", "fmt", "a", "b") - assert.Equal(t, "b a", result) + result = ls.Tr("lang2", "fmt", "a", "b") + assert.Equal(t, "b a", result) - result = ls.Tr("lang1", "section.sub") - assert.Equal(t, "Sub String", result) + result = ls.Tr("lang1", "section.sub") + assert.Equal(t, "Sub String", result) - result = ls.Tr("lang2", "section.sub") - assert.Equal(t, "Changed Sub String", result) + result = ls.Tr("lang2", "section.sub") + assert.Equal(t, "Changed Sub String", result) - result = ls.Tr("", ".dot.name") - assert.Equal(t, "Dot Name", result) + result = ls.Tr("", ".dot.name") + assert.Equal(t, "Dot Name", result) - result = ls.Tr("lang2", "section.mixed") - assert.Equal(t, `test value; more text`, result) + result = ls.Tr("lang2", "section.mixed") + assert.Equal(t, `test value; more text`, result) - langs, descs := ls.ListLangNameDesc() - assert.Equal(t, []string{"lang1", "lang2"}, langs) - assert.Equal(t, []string{"Lang1", "Lang2"}, descs) + langs, descs := ls.ListLangNameDesc() + assert.Equal(t, []string{"lang1", "lang2"}, langs) + assert.Equal(t, []string{"Lang1", "Lang2"}, descs) + + result, found := ls.localeMap["lang1"].tryTr("no-such") + assert.Equal(t, "no-such", result) + assert.False(t, found) + } } diff --git a/modules/translation/translation.go b/modules/translation/translation.go index da9d9b9b6..fcc101d96 100644 --- a/modules/translation/translation.go +++ b/modules/translation/translation.go @@ -5,6 +5,7 @@ package translation import ( + "path" "sort" "strings" @@ -12,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/options" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/translation/i18n" + "code.gitea.io/gitea/modules/util" "golang.org/x/text/language" ) @@ -40,31 +42,35 @@ func AllLangs() []*LangType { return allLangs } -// TryTr tries to do the translation, if no translation, it returns (format, false) -func TryTr(lang, format string, args ...interface{}) (string, bool) { - s := i18n.Tr(lang, format, args...) - // now the i18n library is not good enough and we can only use this hacky method to detect whether the transaction exists - idx := strings.IndexByte(format, '.') - defaultText := format - if idx > 0 { - defaultText = format[idx+1:] - } - return s, s != defaultText -} - // InitLocales loads the locales func InitLocales() { - i18n.ResetDefaultLocales() + i18n.ResetDefaultLocales(setting.IsProd) localeNames, err := options.Dir("locale") if err != nil { log.Fatal("Failed to list locale files: %v", err) } - localFiles := make(map[string][]byte, len(localeNames)) + localFiles := make(map[string]interface{}, len(localeNames)) for _, name := range localeNames { - localFiles[name], err = options.Locale(name) - if err != nil { - log.Fatal("Failed to load %s locale file. %v", name, err) + if options.IsDynamic() { + // Try to check if CustomPath has the file, otherwise fallback to StaticRootPath + value := path.Join(setting.CustomPath, "options/locale", name) + + isFile, err := util.IsFile(value) + if err != nil { + log.Fatal("Failed to load %s locale file. %v", name, err) + } + + if isFile { + localFiles[name] = value + } else { + localFiles[name] = path.Join(setting.StaticRootPath, "options/locale", name) + } + } else { + localFiles[name], err = options.Locale(name) + if err != nil { + log.Fatal("Failed to load %s locale file. %v", name, err) + } } } @@ -76,6 +82,7 @@ func InitLocales() { matcher = language.NewMatcher(supportedTags) for i := range setting.Names { key := "locale_" + setting.Langs[i] + ".ini" + if err = i18n.DefaultLocales.AddLocaleByIni(setting.Langs[i], setting.Names[i], localFiles[key]); err != nil { log.Error("Failed to set messages to %s: %v", setting.Langs[i], err) } @@ -132,16 +139,7 @@ func (l *locale) Language() string { // Tr translates content to target language. func (l *locale) Tr(format string, args ...interface{}) string { - if setting.IsProd { - return i18n.Tr(l.Lang, format, args...) - } - - // in development, we should show an error if a translation key is missing - s, ok := TryTr(l.Lang, format, args...) - if !ok { - log.Error("missing i18n translation key: %q", format) - } - return s + return i18n.Tr(l.Lang, format, args...) } // Language specific rules for translating plural texts diff --git a/routers/web/admin/admin.go b/routers/web/admin/admin.go index 24c07b5c1..ebe5066d2 100644 --- a/routers/web/admin/admin.go +++ b/routers/web/admin/admin.go @@ -25,6 +25,7 @@ import ( "code.gitea.io/gitea/modules/queue" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/timeutil" + "code.gitea.io/gitea/modules/translation" "code.gitea.io/gitea/modules/updatechecker" "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/web" @@ -85,7 +86,7 @@ var sysStatus struct { } func updateSystemStatus() { - sysStatus.Uptime = timeutil.TimeSincePro(setting.AppStartTime, "en") + sysStatus.Uptime = timeutil.TimeSincePro(setting.AppStartTime, translation.NewLocale("en-US")) m := new(runtime.MemStats) runtime.ReadMemStats(m) diff --git a/routers/web/auth/auth.go b/routers/web/auth/auth.go index ea5c7232a..213b88903 100644 --- a/routers/web/auth/auth.go +++ b/routers/web/auth/auth.go @@ -629,7 +629,7 @@ func handleUserCreated(ctx *context.Context, u *user_model.User, gothUser *goth. ctx.Data["IsSendRegisterMail"] = true ctx.Data["Email"] = u.Email - ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language()) + ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale) ctx.HTML(http.StatusOK, TplActivate) if setting.CacheService.Enabled { @@ -658,7 +658,7 @@ func Activate(ctx *context.Context) { if setting.CacheService.Enabled && ctx.Cache.IsExist("MailResendLimit_"+ctx.Doer.LowerName) { ctx.Data["ResendLimited"] = true } else { - ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language()) + ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale) mailer.SendActivateAccountMail(ctx.Locale, ctx.Doer) if setting.CacheService.Enabled { diff --git a/routers/web/auth/password.go b/routers/web/auth/password.go index c41c8bd1e..c21ca9cf6 100644 --- a/routers/web/auth/password.go +++ b/routers/web/auth/password.go @@ -63,7 +63,7 @@ func ForgotPasswdPost(ctx *context.Context) { u, err := user_model.GetUserByEmail(email) if err != nil { if user_model.IsErrUserNotExist(err) { - ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language()) + ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale) ctx.Data["IsResetSent"] = true ctx.HTML(http.StatusOK, tplForgotPassword) return @@ -93,7 +93,7 @@ func ForgotPasswdPost(ctx *context.Context) { } } - ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language()) + ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale) ctx.Data["IsResetSent"] = true ctx.HTML(http.StatusOK, tplForgotPassword) } diff --git a/routers/web/dev/template.go b/routers/web/dev/template.go index 29d6033a7..afef0d8d1 100644 --- a/routers/web/dev/template.go +++ b/routers/web/dev/template.go @@ -21,8 +21,8 @@ func TemplatePreview(ctx *context.Context) { ctx.Data["AppVer"] = setting.AppVer ctx.Data["AppUrl"] = setting.AppURL ctx.Data["Code"] = "2014031910370000009fff6782aadb2162b4a997acb69d4400888e0b9274657374" - ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language()) - ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language()) + ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale) + ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale) ctx.Data["CurDbValue"] = "" ctx.HTML(http.StatusOK, base.TplName(ctx.Params("*"))) diff --git a/routers/web/repo/blame.go b/routers/web/repo/blame.go index e96e2142d..06c43aec1 100644 --- a/routers/web/repo/blame.go +++ b/routers/web/repo/blame.go @@ -255,7 +255,7 @@ func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames m commitCnt++ // User avatar image - commitSince := timeutil.TimeSinceUnix(timeutil.TimeStamp(commit.Author.When.Unix()), ctx.Locale.Language()) + commitSince := timeutil.TimeSinceUnix(timeutil.TimeStamp(commit.Author.When.Unix()), ctx.Locale) var avatar string if commit.User != nil { diff --git a/routers/web/repo/issue_content_history.go b/routers/web/repo/issue_content_history.go index d8a21c7fd..a9386d274 100644 --- a/routers/web/repo/issue_content_history.go +++ b/routers/web/repo/issue_content_history.go @@ -17,7 +17,6 @@ import ( "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/timeutil" - "code.gitea.io/gitea/modules/translation/i18n" "github.com/sergi/go-diff/diffmatchpatch" ) @@ -29,14 +28,13 @@ func GetContentHistoryOverview(ctx *context.Context) { return } - lang := ctx.Locale.Language() editedHistoryCountMap, _ := issues_model.QueryIssueContentHistoryEditedCountMap(ctx, issue.ID) ctx.JSON(http.StatusOK, map[string]interface{}{ "i18n": map[string]interface{}{ - "textEdited": i18n.Tr(lang, "repo.issues.content_history.edited"), - "textDeleteFromHistory": i18n.Tr(lang, "repo.issues.content_history.delete_from_history"), - "textDeleteFromHistoryConfirm": i18n.Tr(lang, "repo.issues.content_history.delete_from_history_confirm"), - "textOptions": i18n.Tr(lang, "repo.issues.content_history.options"), + "textEdited": ctx.Tr("repo.issues.content_history.edited"), + "textDeleteFromHistory": ctx.Tr("repo.issues.content_history.delete_from_history"), + "textDeleteFromHistoryConfirm": ctx.Tr("repo.issues.content_history.delete_from_history_confirm"), + "textOptions": ctx.Tr("repo.issues.content_history.options"), }, "editedHistoryCountMap": editedHistoryCountMap, }) @@ -55,7 +53,6 @@ func GetContentHistoryList(ctx *context.Context) { // render history list to HTML for frontend dropdown items: (name, value) // name is HTML of "avatar + userName + userAction + timeSince" // value is historyId - lang := ctx.Locale.Language() var results []map[string]interface{} for _, item := range items { var actionText string @@ -67,7 +64,7 @@ func GetContentHistoryList(ctx *context.Context) { } else { actionText = ctx.Locale.Tr("repo.issues.content_history.edited") } - timeSinceText := timeutil.TimeSinceUnix(item.EditedUnix, lang) + timeSinceText := timeutil.TimeSinceUnix(item.EditedUnix, ctx.Locale) username := item.UserName if setting.UI.DefaultShowFullName && strings.TrimSpace(item.UserFullName) != "" { diff --git a/routers/web/user/setting/account.go b/routers/web/user/setting/account.go index 3e96cc7c8..cc59524fd 100644 --- a/routers/web/user/setting/account.go +++ b/routers/web/user/setting/account.go @@ -146,7 +146,7 @@ func EmailPost(ctx *context.Context) { log.Error("Set cache(MailResendLimit) fail: %v", err) } } - ctx.Flash.Info(ctx.Tr("settings.add_email_confirmation_sent", address, timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language()))) + ctx.Flash.Info(ctx.Tr("settings.add_email_confirmation_sent", address, timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale))) ctx.Redirect(setting.AppSubURL + "/user/settings/account") return } @@ -208,7 +208,7 @@ func EmailPost(ctx *context.Context) { log.Error("Set cache(MailResendLimit) fail: %v", err) } } - ctx.Flash.Info(ctx.Tr("settings.add_email_confirmation_sent", email.Email, timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language()))) + ctx.Flash.Info(ctx.Tr("settings.add_email_confirmation_sent", email.Email, timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale))) } else { ctx.Flash.Success(ctx.Tr("settings.add_email_success")) } diff --git a/routers/web/user/setting/profile.go b/routers/web/user/setting/profile.go index 46399338f..b07813e72 100644 --- a/routers/web/user/setting/profile.go +++ b/routers/web/user/setting/profile.go @@ -23,7 +23,7 @@ import ( "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/translation/i18n" + "code.gitea.io/gitea/modules/translation" "code.gitea.io/gitea/modules/typesniffer" "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/web" @@ -136,7 +136,7 @@ func ProfilePost(ctx *context.Context) { middleware.SetLocaleCookie(ctx.Resp, ctx.Doer.Language, 0) log.Trace("User settings updated: %s", ctx.Doer.Name) - ctx.Flash.Success(i18n.Tr(ctx.Doer.Language, "settings.update_profile_success")) + ctx.Flash.Success(translation.NewLocale(ctx.Doer.Language).Tr("settings.update_profile_success")) ctx.Redirect(setting.AppSubURL + "/user/settings") } @@ -425,7 +425,7 @@ func UpdateUserLang(ctx *context.Context) { middleware.SetLocaleCookie(ctx.Resp, ctx.Doer.Language, 0) log.Trace("User settings updated: %s", ctx.Doer.Name) - ctx.Flash.Success(i18n.Tr(ctx.Doer.Language, "settings.update_language_success")) + ctx.Flash.Success(translation.NewLocale(ctx.Doer.Language).Tr("settings.update_language_success")) ctx.Redirect(setting.AppSubURL + "/user/settings/appearance") } diff --git a/services/cron/cron.go b/services/cron/cron.go index ebbcd75b6..8e19e0441 100644 --- a/services/cron/cron.go +++ b/services/cron/cron.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/process" "code.gitea.io/gitea/modules/sync" + "code.gitea.io/gitea/modules/translation" "github.com/gogs/cron" ) @@ -63,7 +64,7 @@ type TaskTableRow struct { task *Task } -func (t *TaskTableRow) FormatLastMessage(locale string) string { +func (t *TaskTableRow) FormatLastMessage(locale translation.Locale) string { if t.Status == "finished" { return t.task.GetConfig().FormatMessage(locale, t.Name, t.Status, t.LastDoer) } diff --git a/services/cron/setting.go b/services/cron/setting.go index 9b59a562f..eb13242e9 100644 --- a/services/cron/setting.go +++ b/services/cron/setting.go @@ -7,7 +7,7 @@ package cron import ( "time" - "code.gitea.io/gitea/modules/translation/i18n" + "code.gitea.io/gitea/modules/translation" ) // Config represents a basic configuration interface that cron task @@ -15,7 +15,7 @@ type Config interface { IsEnabled() bool DoRunAtStart() bool GetSchedule() string - FormatMessage(locale, name, status, doer string, args ...interface{}) string + FormatMessage(locale translation.Locale, name, status, doer string, args ...interface{}) string DoNoticeOnSuccess() bool } @@ -69,9 +69,9 @@ func (b *BaseConfig) DoNoticeOnSuccess() bool { // FormatMessage returns a message for the task // Please note the `status` string will be concatenated with `admin.dashboard.cron.` and `admin.dashboard.task.` to provide locale messages. Similarly `name` will be composed with `admin.dashboard.` to provide the locale name for the task. -func (b *BaseConfig) FormatMessage(locale, name, status, doer string, args ...interface{}) string { +func (b *BaseConfig) FormatMessage(locale translation.Locale, name, status, doer string, args ...interface{}) string { realArgs := make([]interface{}, 0, len(args)+2) - realArgs = append(realArgs, i18n.Tr(locale, "admin.dashboard."+name)) + realArgs = append(realArgs, locale.Tr("admin.dashboard."+name)) if doer == "" { realArgs = append(realArgs, "(Cron)") } else { @@ -81,7 +81,7 @@ func (b *BaseConfig) FormatMessage(locale, name, status, doer string, args ...in realArgs = append(realArgs, args...) } if doer == "" { - return i18n.Tr(locale, "admin.dashboard.cron."+status, realArgs...) + return locale.Tr("admin.dashboard.cron."+status, realArgs...) } - return i18n.Tr(locale, "admin.dashboard.task."+status, realArgs...) + return locale.Tr("admin.dashboard.task."+status, realArgs...) } diff --git a/services/cron/tasks.go b/services/cron/tasks.go index 2252ad21e..c26e47e0c 100644 --- a/services/cron/tasks.go +++ b/services/cron/tasks.go @@ -94,7 +94,7 @@ func (t *Task) RunWithUser(doer *user_model.User, config Config) { doerName = doer.Name } - ctx, _, finished := pm.AddContext(baseCtx, config.FormatMessage("en-US", t.Name, "process", doerName)) + ctx, _, finished := pm.AddContext(baseCtx, config.FormatMessage(translation.NewLocale("en-US"), t.Name, "process", doerName)) defer finished() if err := t.fun(ctx, doer, config); err != nil { @@ -114,7 +114,7 @@ func (t *Task) RunWithUser(doer *user_model.User, config Config) { t.LastDoer = doerName t.lock.Unlock() - if err := admin_model.CreateNotice(ctx, admin_model.NoticeTask, config.FormatMessage("en-US", t.Name, "cancelled", doerName, message)); err != nil { + if err := admin_model.CreateNotice(ctx, admin_model.NoticeTask, config.FormatMessage(translation.NewLocale("en-US"), t.Name, "cancelled", doerName, message)); err != nil { log.Error("CreateNotice: %v", err) } return @@ -127,7 +127,7 @@ func (t *Task) RunWithUser(doer *user_model.User, config Config) { t.lock.Unlock() if config.DoNoticeOnSuccess() { - if err := admin_model.CreateNotice(ctx, admin_model.NoticeTask, config.FormatMessage("en-US", t.Name, "finished", doerName)); err != nil { + if err := admin_model.CreateNotice(ctx, admin_model.NoticeTask, config.FormatMessage(translation.NewLocale("en-US"), t.Name, "finished", doerName)); err != nil { log.Error("CreateNotice: %v", err) } } @@ -148,7 +148,7 @@ func RegisterTask(name string, config Config, fun func(context.Context, *user_mo log.Debug("Registering task: %s", name) i18nKey := "admin.dashboard." + name - if _, ok := translation.TryTr("en-US", i18nKey); !ok { + if value := translation.NewLocale("en-US").Tr(i18nKey); value == i18nKey { return fmt.Errorf("translation is missing for task %q, please add translation for %q", name, i18nKey) } diff --git a/services/mailer/mail.go b/services/mailer/mail.go index f93622955..52011ce35 100644 --- a/services/mailer/mail.go +++ b/services/mailer/mail.go @@ -75,8 +75,8 @@ func sendUserMail(language string, u *user_model.User, tpl base.TplName, code, s locale := translation.NewLocale(language) data := map[string]interface{}{ "DisplayName": u.DisplayName(), - "ActiveCodeLives": timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, language), - "ResetPwdCodeLives": timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, language), + "ActiveCodeLives": timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, locale), + "ResetPwdCodeLives": timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, locale), "Code": code, "Language": locale.Language(), // helper @@ -126,7 +126,7 @@ func SendActivateEmailMail(u *user_model.User, email *user_model.EmailAddress) { locale := translation.NewLocale(u.Language) data := map[string]interface{}{ "DisplayName": u.DisplayName(), - "ActiveCodeLives": timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, locale.Language()), + "ActiveCodeLives": timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, locale), "Code": u.GenerateEmailActivateCode(email.Email), "Email": email.Email, "Language": locale.Language(), diff --git a/templates/admin/cron.tmpl b/templates/admin/cron.tmpl index a73813ef8..cf3532c77 100644 --- a/templates/admin/cron.tmpl +++ b/templates/admin/cron.tmpl @@ -24,7 +24,7 @@ {{DateFmtLong .Next}} {{if gt .Prev.Year 1 }}{{DateFmtLong .Prev}}{{else}}N/A{{end}} {{.ExecTimes}} - {{if eq .Status "" }}—{{else if eq .Status "finished"}}{{svg "octicon-check" 16}}{{else}}{{svg "octicon-x" 16}}{{end}} + {{if eq .Status "" }}—{{else if eq .Status "finished"}}{{svg "octicon-check" 16}}{{else}}{{svg "octicon-x" 16}}{{end}} {{end}} diff --git a/templates/admin/process-row.tmpl b/templates/admin/process-row.tmpl index 2191677a5..d072a649f 100644 --- a/templates/admin/process-row.tmpl +++ b/templates/admin/process-row.tmpl @@ -3,7 +3,7 @@
{{if eq .Process.Type "request"}}{{svg "octicon-globe" 16 }}{{else if eq .Process.Type "system"}}{{svg "octicon-cpu" 16 }}{{else}}{{svg "octicon-terminal" 16 }}{{end}}
{{.Process.Description}}
-
{{TimeSince .Process.Start .root.i18n.Lang}}
+
{{TimeSince .Process.Start .root.i18n}}
{{if ne .Process.Type "system"}} diff --git a/templates/admin/stacktrace-row.tmpl b/templates/admin/stacktrace-row.tmpl index a21ef72d6..af7ea3623 100644 --- a/templates/admin/stacktrace-row.tmpl +++ b/templates/admin/stacktrace-row.tmpl @@ -13,7 +13,7 @@
{{.Process.Description}}
-
{{if ne .Process.Type "none"}}{{TimeSince .Process.Start .root.i18n.Lang}}{{end}}
+
{{if ne .Process.Type "none"}}{{TimeSince .Process.Start .root.i18n}}{{end}}
{{if or (eq .Process.Type "request") (eq .Process.Type "normal") }} diff --git a/templates/explore/repo_list.tmpl b/templates/explore/repo_list.tmpl index 1bc831d9d..c0e371b8a 100644 --- a/templates/explore/repo_list.tmpl +++ b/templates/explore/repo_list.tmpl @@ -60,7 +60,7 @@ {{end}}
{{end}} -

{{$.i18n.Tr "org.repo_updated"}} {{TimeSinceUnix .UpdatedUnix $.i18n.Lang}}

+

{{$.i18n.Tr "org.repo_updated"}} {{TimeSinceUnix .UpdatedUnix $.i18n}}

{{else}} diff --git a/templates/package/shared/list.tmpl b/templates/package/shared/list.tmpl index ce2b57e4a..eb2beac9e 100644 --- a/templates/package/shared/list.tmpl +++ b/templates/package/shared/list.tmpl @@ -29,7 +29,7 @@ {{svg .Package.Type.SVGName 16}} {{.Package.Type.Name}}
- {{$timeStr := TimeSinceUnix .Version.CreatedUnix $.i18n.Lang}} + {{$timeStr := TimeSinceUnix .Version.CreatedUnix $.i18n}} {{$hasRepositoryAccess := false}} {{if .Repository}} {{$hasRepositoryAccess = index $.RepositoryAccessMap .Repository.ID}} diff --git a/templates/package/shared/versionlist.tmpl b/templates/package/shared/versionlist.tmpl index 59f7cd164..3d9ae5ef4 100644 --- a/templates/package/shared/versionlist.tmpl +++ b/templates/package/shared/versionlist.tmpl @@ -21,7 +21,7 @@ {{.Version.LowerVersion}}
- {{$.i18n.Tr "packages.published_by" (TimeSinceUnix .Version.CreatedUnix $.i18n.Lang) .Creator.HomeLink (.Creator.GetDisplayName | Escape) | Safe}} + {{$.i18n.Tr "packages.published_by" (TimeSinceUnix .Version.CreatedUnix $.i18n) .Creator.HomeLink (.Creator.GetDisplayName | Escape) | Safe}}
diff --git a/templates/package/view.tmpl b/templates/package/view.tmpl index efad9f9b8..9a3157c28 100644 --- a/templates/package/view.tmpl +++ b/templates/package/view.tmpl @@ -9,7 +9,7 @@

{{.PackageDescriptor.Package.Name}} ({{.PackageDescriptor.Version.Version}})

- {{$timeStr := TimeSinceUnix .PackageDescriptor.Version.CreatedUnix $.i18n.Lang}} + {{$timeStr := TimeSinceUnix .PackageDescriptor.Version.CreatedUnix $.i18n}} {{if .HasRepositoryAccess}} {{.i18n.Tr "packages.published_by_in" $timeStr .PackageDescriptor.Creator.HomeLink (.PackageDescriptor.Creator.GetDisplayName | Escape) .PackageDescriptor.Repository.HTMLURL (.PackageDescriptor.Repository.FullName | Escape) | Safe}} {{else}} diff --git a/templates/repo/activity.tmpl b/templates/repo/activity.tmpl index 36108dddc..c6fca8677 100644 --- a/templates/repo/activity.tmpl +++ b/templates/repo/activity.tmpl @@ -131,7 +131,7 @@ {{if not .IsTag}} {{.Title | RenderEmoji}} {{end}} - {{TimeSinceUnix .CreatedUnix $.i18n.Lang}} + {{TimeSinceUnix .CreatedUnix $.i18n}}

{{end}}
@@ -150,7 +150,7 @@

{{$.i18n.Tr "repo.activity.merged_prs_label"}} #{{.Index}} {{.Issue.Title | RenderEmoji}} - {{TimeSinceUnix .MergedUnix $.i18n.Lang}} + {{TimeSinceUnix .MergedUnix $.i18n}}

{{end}} @@ -169,7 +169,7 @@

{{$.i18n.Tr "repo.activity.opened_prs_label"}} #{{.Index}} {{.Issue.Title | RenderEmoji}} - {{TimeSinceUnix .Issue.CreatedUnix $.i18n.Lang}} + {{TimeSinceUnix .Issue.CreatedUnix $.i18n}}

{{end}} @@ -188,7 +188,7 @@

{{$.i18n.Tr "repo.activity.closed_issue_label"}} #{{.Index}} {{.Title | RenderEmoji}} - {{TimeSinceUnix .ClosedUnix $.i18n.Lang}} + {{TimeSinceUnix .ClosedUnix $.i18n}}

{{end}} @@ -207,7 +207,7 @@

{{$.i18n.Tr "repo.activity.new_issue_label"}} #{{.Index}} {{.Title | RenderEmoji}} - {{TimeSinceUnix .CreatedUnix $.i18n.Lang}} + {{TimeSinceUnix .CreatedUnix $.i18n}}

{{end}} @@ -231,7 +231,7 @@ {{else}} {{.Title | RenderEmoji}} {{end}} - {{TimeSinceUnix .UpdatedUnix $.i18n.Lang}} + {{TimeSinceUnix .UpdatedUnix $.i18n}}

{{end}} diff --git a/templates/repo/branch/list.tmpl b/templates/repo/branch/list.tmpl index 6c34ba4c1..d36a69e5b 100644 --- a/templates/repo/branch/list.tmpl +++ b/templates/repo/branch/list.tmpl @@ -18,7 +18,7 @@ {{svg "octicon-shield-lock"}} {{end}} {{.DefaultBranch}} -

{{svg "octicon-git-commit" 16 "mr-2"}}{{ShortSha .DefaultBranchBranch.Commit.ID.String}} · {{RenderCommitMessage $.Context .DefaultBranchBranch.Commit.CommitMessage .RepoLink .Repository.ComposeMetas}} · {{.i18n.Tr "org.repo_updated"}} {{TimeSince .DefaultBranchBranch.Commit.Committer.When .i18n.Lang}}

+

{{svg "octicon-git-commit" 16 "mr-2"}}{{ShortSha .DefaultBranchBranch.Commit.ID.String}} · {{RenderCommitMessage $.Context .DefaultBranchBranch.Commit.CommitMessage .RepoLink .Repository.ComposeMetas}} · {{.i18n.Tr "org.repo_updated"}} {{TimeSince .DefaultBranchBranch.Commit.Committer.When .i18n}}

{{if and $.IsWriter (not $.Repository.IsArchived) (not .IsDeleted)}} @@ -53,13 +53,13 @@ {{if .IsDeleted}} {{.Name}} -

{{$.i18n.Tr "repo.branch.deleted_by" .DeletedBranch.DeletedBy.Name}} {{TimeSinceUnix .DeletedBranch.DeletedUnix $.i18n.Lang}}

+

{{$.i18n.Tr "repo.branch.deleted_by" .DeletedBranch.DeletedBy.Name}} {{TimeSinceUnix .DeletedBranch.DeletedUnix $.i18n}}

{{else}} {{if .IsProtected}} {{svg "octicon-shield-lock"}} {{end}} {{.Name}} -

{{svg "octicon-git-commit" 16 "mr-2"}}{{ShortSha .Commit.ID.String}} · {{RenderCommitMessage $.Context .Commit.CommitMessage $.RepoLink $.Repository.ComposeMetas}} · {{$.i18n.Tr "org.repo_updated"}} {{TimeSince .Commit.Committer.When $.i18n.Lang}}

+

{{svg "octicon-git-commit" 16 "mr-2"}}{{ShortSha .Commit.ID.String}} · {{RenderCommitMessage $.Context .Commit.CommitMessage $.RepoLink $.Repository.ComposeMetas}} · {{$.i18n.Tr "org.repo_updated"}} {{TimeSince .Commit.Committer.When $.i18n}}

{{end}} diff --git a/templates/repo/commit_page.tmpl b/templates/repo/commit_page.tmpl index 1e6296836..96190e3ab 100644 --- a/templates/repo/commit_page.tmpl +++ b/templates/repo/commit_page.tmpl @@ -156,7 +156,7 @@ {{avatarByEmail .Commit.Author.Email .Commit.Author.Email 28 "mr-3"}} {{.Commit.Author.Name}} {{end}} - {{TimeSince .Commit.Author.When $.i18n.Lang}} + {{TimeSince .Commit.Author.When $.i18n}} {{if or (ne .Commit.Committer.Name .Commit.Author.Name) (ne .Commit.Committer.Email .Commit.Author.Email)}} {{.i18n.Tr "repo.diff.committed_by"}} {{if ne .Verification.CommittingUser.ID 0}} @@ -277,7 +277,7 @@ {{else}} {{.NoteCommit.Author.Name}} {{end}} - {{TimeSince .NoteCommit.Author.When $.i18n.Lang}} + {{TimeSince .NoteCommit.Author.When $.i18n}}
{{RenderNote $.Context .Note $.RepoLink $.Repository.ComposeMetas}}
diff --git a/templates/repo/commits_list.tmpl b/templates/repo/commits_list.tmpl index 65baee6b6..d94d31307 100644 --- a/templates/repo/commits_list.tmpl +++ b/templates/repo/commits_list.tmpl @@ -76,9 +76,9 @@ {{end}} {{if .Committer}} - {{TimeSince .Committer.When $.i18n.Lang}} + {{TimeSince .Committer.When $.i18n}} {{else}} - {{TimeSince .Author.When $.i18n.Lang}} + {{TimeSince .Author.When $.i18n}} {{end}} {{end}} diff --git a/templates/repo/diff/comments.tmpl b/templates/repo/diff/comments.tmpl index 6a581ba04..912c9d72f 100644 --- a/templates/repo/diff/comments.tmpl +++ b/templates/repo/diff/comments.tmpl @@ -1,6 +1,6 @@ {{range .comments}} -{{ $createdStr:= TimeSinceUnix .CreatedUnix $.root.i18n.Lang }} +{{ $createdStr:= TimeSinceUnix .CreatedUnix $.root.i18n }}
{{if .OriginalAuthor }} diff --git a/templates/repo/issue/milestone_issues.tmpl b/templates/repo/issue/milestone_issues.tmpl index cb2779db3..ca08b44fc 100644 --- a/templates/repo/issue/milestone_issues.tmpl +++ b/templates/repo/issue/milestone_issues.tmpl @@ -22,7 +22,7 @@
- {{ $closedDate:= TimeSinceUnix .Milestone.ClosedDateUnix $.i18n.Lang }} + {{ $closedDate:= TimeSinceUnix .Milestone.ClosedDateUnix $.i18n }} {{if .IsClosed}} {{svg "octicon-clock"}} {{$.i18n.Tr "repo.milestones.closed" $closedDate|Str2html}} {{else}} diff --git a/templates/repo/issue/milestones.tmpl b/templates/repo/issue/milestones.tmpl index 235044cb1..6185ff370 100644 --- a/templates/repo/issue/milestones.tmpl +++ b/templates/repo/issue/milestones.tmpl @@ -71,7 +71,7 @@
- {{ $closedDate:= TimeSinceUnix .ClosedDateUnix $.i18n.Lang }} + {{ $closedDate:= TimeSinceUnix .ClosedDateUnix $.i18n }} {{if .IsClosed}} {{svg "octicon-clock"}} {{$.i18n.Tr "repo.milestones.closed" $closedDate|Str2html}} {{else}} diff --git a/templates/repo/issue/view_content.tmpl b/templates/repo/issue/view_content.tmpl index 52353d46d..a1a53c80f 100644 --- a/templates/repo/issue/view_content.tmpl +++ b/templates/repo/issue/view_content.tmpl @@ -15,7 +15,7 @@ - {{ $createdStr:= TimeSinceUnix .Issue.CreatedUnix $.i18n.Lang }} + {{ $createdStr:= TimeSinceUnix .Issue.CreatedUnix $.i18n }}
diff --git a/templates/repo/issue/view_content/comments.tmpl b/templates/repo/issue/view_content/comments.tmpl index 0258a9f96..2dbc34e02 100644 --- a/templates/repo/issue/view_content/comments.tmpl +++ b/templates/repo/issue/view_content/comments.tmpl @@ -1,7 +1,7 @@ {{ template "base/alert" }} {{range .Issue.Comments}} {{if call $.ShouldShowCommentType .Type}} - {{ $createdStr:= TimeSinceUnix .CreatedUnix $.i18n.Lang }} + {{ $createdStr:= TimeSinceUnix .CreatedUnix $.i18n }}