You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

format.go 1.0KB

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