forked from mgumz/xliffer
/
to_json.go
95 lines (77 loc) · 2.06 KB
/
to_json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// This file is part of *xliffer*
//
// Copyright (C) 2015, Travelping GmbH <copyright@travelping.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package main
import (
"encoding/json"
"flag"
"io"
"log"
"regexp"
)
// toJSON converts the target translation to a simple key:value
// structered JSON file
type toJSON struct {
inFile string
pretty bool
keyMatch string
keyTo string
}
func init() {
registeredConverters["to-json"] = new(toJSON)
}
func (tj *toJSON) Description() string {
return "Converts XLIFF to JSON (key,value)"
}
func (tj *toJSON) ParseArgs(base string, args []string) error {
var fs = flag.NewFlagSet(base+" to-json", flag.ExitOnError)
fs.StringVar(&tj.inFile, "in", "", "infile")
fs.StringVar(&tj.keyMatch, "key-match", "", "translate chars in key (regexp)")
fs.StringVar(&tj.keyTo, "key-to", "", "chars of key gets translated to (string)")
fs.BoolVar(&tj.pretty, "pretty", tj.pretty, "pretty print the resulting json")
return fs.Parse(args)
}
func (tj *toJSON) Prepare() error {
return nil
}
func (tj *toJSON) Convert(w io.Writer) error {
var doc, err = xliffFromFile(tj.inFile)
if err != nil {
return err
}
var keyTrans = func(in string) string { return in }
if tj.keyMatch != "" {
rx, err := regexp.CompilePOSIX(tj.keyMatch)
if err != nil {
return err
}
keyTrans = func(in string) string {
return rx.ReplaceAllString(in, tj.keyTo)
}
}
var mappings = map[string]string{}
for _, file := range doc.File {
// note: no support for "groups" yet.
for _, unit := range file.Body.TransUnit {
unitID := keyTrans(unit.ID)
if _, exist := mappings[unitID]; exist {
log.Printf("warning: double entry for key %q", unitID)
}
mappings[unitID] = unit.Target.Inner
}
}
var out []byte
if tj.pretty {
out, err = json.MarshalIndent(&mappings, "", "\t")
} else {
out, err = json.Marshal(&mappings)
}
if err == nil {
w.Write(out)
}
return err
}