Skip to content

Commit

Permalink
extract concatenated strings (#143)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicksnyder authored Nov 23, 2018
1 parent 0ebaecb commit 178b9fc
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 8 deletions.
31 changes: 26 additions & 5 deletions v2/goi18n/extract_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,14 +167,10 @@ func (e *extractor) extractMessage(node ast.Node) {
if !ok {
continue
}
value, ok := kve.Value.(*ast.BasicLit)
v, ok := extractStringLiteral(kve.Value)
if !ok {
continue
}
if value.Kind != token.STRING {
continue
}
v := value.Value[1 : len(value.Value)-1]
data[key.Name] = v
}
if len(data) == 0 {
Expand All @@ -187,6 +183,31 @@ func (e *extractor) extractMessage(node ast.Node) {
}
}

func extractStringLiteral(expr ast.Expr) (string, bool) {
switch v := expr.(type) {
case *ast.BasicLit:
if v.Kind != token.STRING {
return "", false
}
return v.Value[1 : len(v.Value)-1], true
case *ast.BinaryExpr:
if v.Op != token.ADD {
return "", false
}
x, ok := extractStringLiteral(v.X)
if !ok {
return "", false
}
y, ok := extractStringLiteral(v.Y)
if !ok {
return "", false
}
return x + y, true
default:
return "", false
}
}

func i18nPackageName(file *ast.File) string {
for _, i := range file.Imports {
if i.Path.Kind == token.STRING && i.Path.Value == `"github.com/nicksnyder/go-i18n/v2/i18n"` {
Expand Down
27 changes: 24 additions & 3 deletions v2/goi18n/extract_command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,30 @@ two = "Two translation"
zero = "Zero translation"
`),
},
{
name: "concat id",
file: `package main
import "github.com/nicksnyder/go-i18n/v2/i18n"
func main() {
_ := &i18n.Message{
ID: "Plural" +
" " +
"ID",
}
}
`,
messages: []*i18n.Message{
{
ID: "Plural ID",
},
},
},
}

for _, test := range tests {
t.Run(test.name+"messages", func(t *testing.T) {
t.Run(test.name+" messages", func(t *testing.T) {
actualMessages, err := extractMessages([]byte(test.file))
if err != nil {
t.Fatal(err)
Expand All @@ -147,7 +168,7 @@ zero = "Zero translation"
t.Fatalf("file:\n%s\nexpected: %s\n got: %s", test.file, marshalTest(test.messages), marshalTest(actualMessages))
}
})
t.Run(test.name+"active file", func(t *testing.T) {
t.Run(test.name+" active file", func(t *testing.T) {
indir := mustTempDir("TestExtractCommandIn")
defer os.RemoveAll(indir)
outdir := mustTempDir("TestExtractCommandOut")
Expand Down Expand Up @@ -218,7 +239,7 @@ other = "{{.Name}} has {{.UnreadEmailCount}} unread emails."
}

func marshalTest(value interface{}) string {
buf, err := json.Marshal(value)
buf, err := json.MarshalIndent(value, "", " ")
if err != nil {
panic(err)
}
Expand Down

0 comments on commit 178b9fc

Please sign in to comment.