golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123k stars 17.54k forks source link

x/text: messages cannot contain '{' #27849

Open rothskeller opened 5 years ago

rothskeller commented 5 years ago

What version of Go are you using (go version)?

go version go1.11 darwin/amd64 golang.org/x/text 905a57155faa8230500121607930ebb9dd8e139c

What did you do?

Ran gotext update with a message catalog containing the Translation expected '{'.

What did you expect to see?

Correct import of message catalog.

What did you see instead?

gotext: generation failed: error: unmatched '}'

There are really three problems here. First, the substitution mechanism used in translations is too simplistic; it doesn't have any escaping mechanism to allow for the use of a bare '{' in the string. Second, the error message is wrong; it should say unmatched '{', not unmatched '}'. And third, the error message is utterly useless since it doesn't identify which translation has the problem.

mpvl commented 5 years ago

For the first issue, do you have a concrete use case?

The translation strings are indeed quite simplistic, as they are often written by non-engineers unfamiliar with concepts like escaping. One approach is to replace the text to be escaped itself with placeholders, for instance:

printf("Single-number set: { %d }", num)

could rewrite to something like

"Single-number set: {OPEN_BRACE} {Num} {CLOSE_BRACE}" With the placeholder Num as before and OPEN_BRACE="{" and CLOSE_BRACE="}"

Another approach would be to, like go templates, to allow for user-specifiable open and close markers.

What is best depends a bit on what users wants and needs, so input is welcome.

rothskeller commented 5 years ago

The particular use case I hit was in writing an error message to be generated by a JSON parser when it expected to see an object. The message in English was expected '{' or 'null'.

You are correct that this could be resolved by treating the open brace character as something to be interpolated into the message. That seems cumbersome from a developer perspective, but I take your point that it might be more intuitive for a translator.