gitea源码

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package i18n
  4. import (
  5. "errors"
  6. "fmt"
  7. "reflect"
  8. )
  9. // Format formats provided arguments for a given translated message
  10. func Format(format string, args ...any) (msg string, err error) {
  11. if len(args) == 0 {
  12. return format, nil
  13. }
  14. fmtArgs := make([]any, 0, len(args))
  15. for _, arg := range args {
  16. val := reflect.ValueOf(arg)
  17. if val.Kind() == reflect.Slice {
  18. // Previously, we would accept Tr(lang, key, a, [b, c], d, [e, f]) as Sprintf(msg, a, b, c, d, e, f)
  19. // but this is an unstable behavior.
  20. //
  21. // So we restrict the accepted arguments to either:
  22. //
  23. // 1. Tr(lang, key, [slice-items]) as Sprintf(msg, items...)
  24. // 2. Tr(lang, key, args...) as Sprintf(msg, args...)
  25. if len(args) == 1 {
  26. for i := 0; i < val.Len(); i++ {
  27. fmtArgs = append(fmtArgs, val.Index(i).Interface())
  28. }
  29. } else {
  30. err = errors.New("arguments to i18n should not contain uncertain slices")
  31. break
  32. }
  33. } else {
  34. fmtArgs = append(fmtArgs, arg)
  35. }
  36. }
  37. return fmt.Sprintf(format, fmtArgs...), err
  38. }