code.gitea.io/gitea@v1.19.3/modules/translation/i18n/format.go (about)

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