-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
521 lines (429 loc) · 12.4 KB
/
main.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
package main
import (
"errors"
"github.com/fsnotify/fsnotify"
"log"
"os/signal"
"os/user"
"path/filepath"
"sort"
"syscall"
"encoding/xml"
"fmt"
"os"
"strings"
"flag"
"io/ioutil"
"github.com/sirupsen/logrus"
"github.com/tealeg/xlsx"
)
func main() {
outputPath := flag.String("output", "", "Path to output the resource files or Excel file when using -invert=true")
inputFile := flag.String("input", "", "Excel file or directory to watch. All .xlsx files will be parsed. With -invert=true this will read the .resx file(s)")
watch := flag.Bool("watch", false, "Watch for file changes. If false, just execute once")
invert := flag.Bool("invert", false, "Indicate that input file is .RESX and generate an Excel file as output")
verbose := flag.Bool("v", false, "Verbose")
trace := flag.Bool("vv", false, "Very verbose")
flag.Parse()
if *outputPath == "" {
logrus.Error("Specify the output path for resource files: --output=PATH")
os.Exit(1)
}
if *inputFile == "" {
logrus.Error("Specify the Excel file or path: --input=PATH")
os.Exit(2)
}
if *trace {
logrus.StandardLogger().SetLevel(logrus.TraceLevel)
logrus.Println("VERY VERBOSE MODE")
} else if *verbose {
logrus.StandardLogger().SetLevel(logrus.DebugLevel)
logrus.Println("VERBOSE MODE")
} else {
logrus.StandardLogger().SetLevel(logrus.InfoLevel)
}
*outputPath = expandUserDirectory(*outputPath)
*inputFile = expandUserDirectory(*inputFile)
if _, err := os.Stat(*inputFile); errors.Is(err, os.ErrNotExist) {
logrus.Error("Given Excel file/path does not exist")
os.Exit(3)
}
if _, err := os.Stat(*outputPath); errors.Is(err, os.ErrNotExist) {
logrus.Error("Given output path does not exist")
os.Exit(3)
}
if *invert {
success, err := importResx(*inputFile, *outputPath)
if err != nil {
panic(err)
}
if success {
logrus.Info("Successfully converted the RESX to Excel")
} else {
logrus.Info("Could not convert RESX to Excel for some unknown reason")
}
} else {
if !*watch {
processXlsx(*inputFile, *outputPath)
}
if *watch {
watchForFileChanges(*inputFile, *outputPath)
}
}
}
func watchForFileChanges(excelFile, outputPath string) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
go func() {
for {
select {
case event := <-watcher.Events:
logrus.Debug("event:", event)
if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create || event.Op&fsnotify.Rename == fsnotify.Rename {
if strings.HasSuffix(event.Name, ".xlsx") {
logrus.Info("modified or created file:", event.Name)
processXlsx(event.Name, outputPath)
}
}
case err := <-watcher.Errors:
log.Println("error:", err)
}
}
}()
// TODO: watch a specific file from config or command line
err = watcher.Add(excelFile)
if err != nil {
log.Fatal(err)
}
// Handle OS Signals
ch := make(chan os.Signal, 5)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT)
loop:
for {
select {
case sig := <-ch:
switch sig {
case os.Interrupt:
fallthrough
case syscall.SIGQUIT:
logrus.Debug("")
logrus.Debug("Got interrupt....")
break loop
case syscall.SIGHUP:
logrus.Debug("SIGHUP, need to re-read some configuration...")
default:
logrus.Debug("Unknown signal: ", sig)
}
}
}
logrus.Info("Shutting down...")
}
func expandUserDirectory(path string) string {
usr, _ := user.Current()
dir := usr.HomeDir
if path == "~" {
// In case of "~", which won't be caught by the "else if"
path = strings.Replace(path, "~", dir, 1)
} else if strings.HasPrefix(path, "~/") {
// Use strings.HasPrefix so we don't match paths like
// "/something/~/something/"
path = filepath.Join(dir, path[2:])
}
return path
}
func readFile(file string) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
byteValue, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return byteValue, nil
}
func importResx(resxFileName, outputPath string) (bool, error) {
byteValue, err := readFile(resxFileName)
if err != nil {
return false, err
}
root := &ResRoot{}
err = xml.Unmarshal(byteValue, root)
if err != nil {
return false, err
}
// find all locale files for this resource file
// split file name and extension, search matches, parse matches.
ext := filepath.Ext(resxFileName)
name := strings.TrimSuffix(resxFileName, ext)
pattern := name + ".*" + ext
baseDir, baseName, err := getPathInfo(resxFileName, os.PathSeparator)
if err != nil {
panic(err)
}
logrus.Trace("Base Dir", baseDir, "Base Name", baseName)
//slashedPath := filepath.ToSlash(resxFileName)
//baseDir := slashedPath[:strings.LastIndexByte(slashedPath, '/')] + "/"
//fileName := strings.TrimPrefix(name, baseDir)
matches, err := filepath.Glob(pattern)
if err != nil {
return false, err
}
orderedKeys := make([]string, 0)
newData := data{
sheetName: baseName,
cultureCodes: make([]string, 0),
identifiers: map[string]translation{},
}
for _, v := range root.Data {
orderedKeys = append(orderedKeys, v.Name)
newData.identifiers[v.Name] = translation{
key: v.Name,
neutral: v.Value,
comment: v.Comment,
translations: map[string]string{},
}
}
for _, localeFile := range matches {
// ./Resx/Resources.se.resx
code := strings.TrimPrefix(localeFile, filepath.Clean(baseDir)+string(os.PathSeparator))
// Resources.se.resx
code = strings.TrimPrefix(code, baseName+".")
// se.resx
code = strings.TrimSuffix(code, ext)
// se
newData.cultureCodes = append(newData.cultureCodes, code)
logrus.Debug("Found locale file: ", localeFile, " Culture code: ", code)
byteValue, err := readFile(localeFile)
if err != nil {
return false, err
}
translationRoot := &ResRoot{}
err = xml.Unmarshal(byteValue, translationRoot)
if err != nil {
return false, err
}
for _, v := range translationRoot.Data {
logrus.Trace("\\ Found translation for: ", v.Name, " Value: ", strings.Replace(v.Value, "\n", " ", 0))
orderedKeys = append(orderedKeys, v.Name)
if newData.identifiers[v.Name].translations == nil {
logrus.Warn(v.Name, " does not exist in neutral language")
newData.identifiers[v.Name] = translation{
name: baseName,
key: v.Name,
neutral: "MISSING",
comment: "WARNING",
translations: map[string]string{},
}
}
logrus.Trace("Adding to key ", v.Name, " translation code ", code, " value ", v.Value)
newData.identifiers[v.Name].translations[code] = v.Value
}
}
orderedKeys = unique(orderedKeys)
sort.Strings(orderedKeys)
newData.orderedKeys = orderedKeys
err = writeExcelFile(filepath.Join(outputPath, baseName+".xlsx"), newData)
if err != nil {
return false, err
}
return true, nil
}
func unique(intSlice []string) []string {
keys := make(map[string]bool)
list := []string{}
for _, entry := range intSlice {
if _, value := keys[entry]; !value {
keys[entry] = true
list = append(list, entry)
}
}
return list
}
func getPathInfo(path string, pathSeparator rune) (baseDir string, baseName string, err error) {
ext := filepath.Ext(path)
name := strings.TrimSuffix(path, ext)
baseDir = path[:strings.LastIndex(path, string(pathSeparator))] + string(pathSeparator)
baseName = strings.TrimPrefix(name, baseDir)
return
}
func writeExcelFile(outputFile string, data data) error {
var wb *xlsx.File
if _, err := os.Stat(outputFile); errors.Is(err, os.ErrNotExist) {
wb = xlsx.NewFile()
} else {
// open an existing file
wb, err = xlsx.OpenFile(outputFile)
if err != nil {
return err
}
}
var sht *xlsx.Sheet
var err error
// new file
if len(wb.Sheets) == 0 {
sht, err = wb.AddSheet(data.sheetName)
} else {
if _, exists := wb.Sheet[data.sheetName]; exists {
sht = wb.Sheet[data.sheetName]
for i := 0; i < sht.MaxRow; i++ {
_ = sht.RemoveRowAtIndex(0)
}
} else {
sht, err = wb.AddSheet(data.sheetName)
if err != nil {
panic(err)
}
}
}
row := sht.AddRow()
row.AddCell().Value = "identifier"
row.AddCell().Value = "description"
row.AddCell().Value = "neutral"
for _, v := range data.cultureCodes {
row.AddCell().Value = v
}
for _, key := range data.orderedKeys {
row := sht.AddRow()
obj := data.identifiers[key]
row.AddCell().Value = obj.key
row.AddCell().Value = obj.comment
row.AddCell().Value = obj.neutral
for _, v := range data.cultureCodes {
row.AddCell().Value = obj.translations[v]
}
}
return wb.Save(outputFile)
}
func processXlsx(excelFileName, outputPath string) {
xlFile, err := xlsx.OpenFile(excelFileName)
if err != nil {
fmt.Fprint(os.Stderr, err)
return
}
descriptions := map[string]string{} // identifier : description
languages := make(map[string]map[string]string) // language => identifier : value
languageIndex := make(map[int]string) // index => language
for _, sheet := range xlFile.Sheets {
rowIndex := 0
for _, row := range sheet.Rows {
rowIndex++
cellIndex := 0
// first row, extract langauges
if rowIndex == 1 {
for _, cell := range row.Cells {
// skip first and second cell in first row (identifier / description)
if cellIndex < 2 {
cellIndex++
continue
}
cellIndex++
text := cell.String()
if _, ok := languages[text]; !ok {
languages[text] = make(map[string]string)
languageIndex[len(languageIndex)] = text
}
}
continue
}
cellIndex = 0
identifier := ""
for _, cell := range row.Cells {
text := cell.String()
if cellIndex == 0 {
if len(text) == 0 || text == "-" {
goto NEXT_ROW
}
identifier = text
cellIndex++
continue
}
if cellIndex == 1 {
// identifier
if _, ok := descriptions[text]; !ok {
//if cell.GetStyle().Font.Color == "FFFF0000" {}
descriptions[identifier] = text
}
}
if lang, ok := languages[languageIndex[cellIndex-2]]; ok {
lang[identifier] = text
}
cellIndex++
}
NEXT_ROW:
//fmt.Println("")
}
headers := []ResHeader{
{Key: "resmimetype", Value: ResHeaderValue{Value: "text/microsoft-resx"}},
{Key: "version", Value: ResHeaderValue{Value: "2.0"}},
{Key: "reader", Value: ResHeaderValue{Value: "System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"}},
{Key: "writer", Value: ResHeaderValue{Value: "System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"}},
}
for lang, data := range languages {
p := ResRoot{Headers: headers}
for identifier, word := range data {
if len(word) == 0 {
continue
}
p.Data = append(p.Data, ResData{Name: strings.Replace(identifier, " ", "_", -1), Space: "preserve", Value: word, Comment: descriptions[identifier]})
}
if xmlstring, err := xml.MarshalIndent(p, "", " "); err == nil {
xmlstring = []byte(xml.Header + string(xmlstring))
filename := fmt.Sprintf("%s/%s.%s.resx", strings.TrimRight(outputPath, "/"), strings.Trim(sheet.Name, " "), strings.Trim(lang, ""))
if lang == "neutral" {
filename = fmt.Sprintf("%s/%s.resx", strings.TrimRight(outputPath, "/"), strings.Trim(sheet.Name, " "))
}
d1 := []byte(xmlstring)
err := ioutil.WriteFile(filename, d1, 0644)
if err != nil {
log.Printf("error writing Filename: %s\n%s\n", filename, xmlstring)
} else {
log.Printf("written filename: %s\n", filename)
}
} else {
log.Printf("error %v", err)
}
}
}
}
type data struct {
sheetName string
cultureCodes []string
identifiers map[string]translation
orderedKeys []string
}
type translation struct {
name string
key string
neutral string
comment string
translations map[string]string
}
// ResHeader ...
type ResHeader struct {
Key string `xml:"name,attr"`
Value ResHeaderValue `xml:",innerxml"`
}
// ResHeaderValue ...
type ResHeaderValue struct {
XMLName xml.Name `xml:"value"`
Value string `xml:",chardata"`
}
// ResData ...
type ResData struct {
XMLName xml.Name `xml:"data"`
Name string `xml:"name,attr"`
Space string `xml:"xml:space,attr"`
Value string `xml:"value"`
Comment string `xml:"comment,omitempty"`
}
// ResRoot ...
type ResRoot struct {
XMLName xml.Name `xml:"root"`
Headers []ResHeader `xml:"resheader,omitempty"`
Data []ResData `xml:"data,omitempty"`
}