Format quotation marks, newlines for PO export

This commit is contained in:
Felix von Drigalski 2022-03-29 11:45:05 +09:00 committed by Felix von Drigalski
parent 01cdb5049e
commit 24bcff57f7
2 changed files with 32 additions and 5 deletions

View file

@ -3,6 +3,7 @@ package gotext
import (
"bytes"
"encoding/gob"
"regexp"
"sort"
"strconv"
"strings"
@ -589,17 +590,17 @@ func (do *Domain) MarshalText() ([]byte, error) {
}
if ref.context == "" {
buf.WriteString("\nmsgid \"" + trans.ID + "\"")
buf.WriteString("\nmsgid \"" + EscapeSpecialCharacters(trans.ID) + "\"")
} else {
buf.WriteString("\nmsgctxt \"" + ref.context + "\"\nmsgid \"" + trans.ID + "\"")
buf.WriteString("\nmsgctxt \"" + EscapeSpecialCharacters(ref.context) + "\"\nmsgid \"" + EscapeSpecialCharacters(trans.ID) + "\"")
}
if trans.PluralID == "" {
buf.WriteString("\nmsgstr \"" + trans.Trs[0] + "\"")
buf.WriteString("\nmsgstr \"" + EscapeSpecialCharacters(trans.Trs[0]) + "\"")
} else {
buf.WriteString("\nmsgid_plural \"" + trans.PluralID + "\"")
for i, tr := range trans.Trs {
buf.WriteString("\nmsgstr[" + strconv.Itoa(i) + "] \"" + tr + "\"")
buf.WriteString("\nmsgstr[" + EscapeSpecialCharacters(strconv.Itoa(i)) + "] \"" + tr + "\"")
}
}
}
@ -607,6 +608,12 @@ func (do *Domain) MarshalText() ([]byte, error) {
return buf.Bytes(), nil
}
func EscapeSpecialCharacters(s string) string {
s = regexp.MustCompile(`([^\\])(")`).ReplaceAllString(s, "$1\\\"") // Escape non-escaped double quotation marks
s = strings.ReplaceAll(s, "\n", "\"\n\"") // Convert newlines into multi-line strings
return s
}
// MarshalBinary implements encoding.BinaryMarshaler interface
func (do *Domain) MarshalBinary() ([]byte, error) {
obj := new(TranslatorEncoding)

View file

@ -1,6 +1,9 @@
package gotext
import "testing"
import (
"fmt"
"testing"
)
const (
enUSFixture = "fixtures/en_US/default.po"
@ -69,3 +72,20 @@ func TestDomain_GetTranslations(t *testing.T) {
}
}
}
func TestDomain_CheckExportFormatting(t *testing.T) {
po := NewPo()
po.Set("myid", "test string\nwith \"newline\"")
poBytes, _ := po.MarshalText()
expectedOutput := `msgid ""
msgstr ""
msgid "myid"
msgstr "test string"
"with \"newline\""`
if string(poBytes) != expectedOutput {
t.Errorf("Exported PO format does not match. Received:\n\n%v\n\n\nExpected:\n\n%v", string(poBytes), expectedOutput)
}
}