Merge pull request #61 from felixvd/fix-po-export

Format quotation marks and newlines for PO export
This commit is contained in:
Leonel Quinteros 2022-03-31 12:11:18 -03:00 committed by GitHub
commit 4f17e07cb4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 31 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,8 @@
package gotext
import "testing"
import (
"testing"
)
const (
enUSFixture = "fixtures/en_US/default.po"
@ -69,3 +71,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)
}
}