forked from phrase/phraseapp-client
/
push.go
473 lines (389 loc) · 10.9 KB
/
push.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
package main
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/daviddengcn/go-colortext"
"github.com/phrase/phraseapp-api-client/Godeps/_workspace/src/gopkg.in/yaml.v2"
"github.com/phrase/phraseapp-go/phraseapp"
)
type PushCommand struct {
Verbose bool `cli:"opt --verbose default=false"`
}
func (cmd *PushCommand) Run() error {
if cmd.Verbose {
Debug = true
}
sources, err := SourcesFromConfig()
if err != nil {
return err
}
for _, source := range sources {
err := source.Push()
if err != nil {
printErr(err, "")
}
}
return nil
}
type Sources []*Source
type Source struct {
File string `yaml:"file,omitempty"`
ProjectId string `yaml:"project_id,omitempty"`
AccessToken string `yaml:"access_token,omitempty"`
FileFormat string `yaml:"file_format,omitempty"`
Params *PushParams `yaml:"params,omitempty"`
RemoteLocales []*phraseapp.Locale
PathComponents *PathComponents
Extension string
}
type PushParams struct {
FileFormat string `yaml:"file_format,omitempty"`
LocaleId string `yaml:"locale_id,omitempty"`
ConvertEmoji *bool `yaml:"convert_emoji,omitempty"`
FormatOptions *map[string]interface{} `yaml:"format_options,omitempty"`
SkipUnverification *bool `yaml:"skip_unverification,omitempty"`
SkipUploadTags *bool `yaml:"skip_upload_tags,omitempty"`
Tags []string `yaml:"tags,omitempty"`
UpdateTranslations *bool `yaml:"update_translations,omitempty"`
}
func (source *Source) Push() error {
Authenticate()
if strings.TrimSpace(source.File) == "" {
return fmt.Errorf("file of source may not be empty")
}
remoteLocales, err := RemoteLocales(source.ProjectId)
if err != nil {
return err
}
source.RemoteLocales = remoteLocales
localeFiles, err := source.LocaleFiles()
if err != nil {
return err
}
for _, localeFile := range localeFiles {
fmt.Println("Uploading", localeFile.RelPath())
if !localeFile.ExistsRemote {
localeDetails, err := source.createLocale(localeFile)
if err == nil {
localeFile.Id = localeDetails.Id
localeFile.RFC = localeDetails.Code
localeFile.Name = localeDetails.Name
}
}
err = source.uploadFile(localeFile)
if err != nil {
printErr(err, "")
} else {
sharedMessage("push", localeFile)
}
}
return nil
}
func (source *Source) createLocale(localeFile *LocaleFile) (*phraseapp.LocaleDetails, error) {
localeParams := new(phraseapp.LocaleParams)
if localeFile.RFC != "" {
localeParams.Code = localeFile.RFC
}
if localeFile.Name != "" {
localeParams.Name = localeFile.Name
} else {
localeParams.Name = localeFile.RFC
}
localeDetails, err := phraseapp.LocaleCreate(source.ProjectId, localeParams)
if err != nil {
return nil, err
}
return localeDetails, nil
}
func (source *Source) uploadFile(localeFile *LocaleFile) error {
uploadParams, err := source.setUploadParams(localeFile)
if err != nil {
return err
}
aUpload, err := phraseapp.UploadCreate(source.ProjectId, uploadParams)
if err != nil {
return err
}
printSummary(&aUpload.Summary)
return nil
}
func (source *Source) LocaleFiles() (LocaleFiles, error) {
source.Extension = filepath.Ext(source.File)
recursiveFiles := []string{}
if strings.Contains(source.File, "**") {
rec, err := source.recurse()
if err != nil {
return nil, err
}
recursiveFiles = rec
}
globFiles, err := source.glob()
if err != nil {
return nil, err
}
filePaths := []string{}
for _, f := range globFiles {
if !Contains(filePaths, f) {
filePaths = append(filePaths, f)
}
}
for _, f := range recursiveFiles {
if !Contains(filePaths, f) {
filePaths = append(filePaths, f)
}
}
var localeFiles LocaleFiles
for _, path := range filePaths {
localeFile, err := source.generateLocaleForFile(path)
if err != nil {
return nil, err
}
localeFiles = append(localeFiles, localeFile)
}
return localeFiles, nil
}
func (source *Source) generateLocaleForFile(path string) (*LocaleFile, error) {
taggedMatches := source.findTaggedMatches(path)
name := taggedMatches["locale_name"]
rfc := taggedMatches["locale_code"]
tag := taggedMatches["tag"]
lc := &LocaleFile{}
if name != "" {
lc.Name = name
}
if rfc != "" {
lc.RFC = rfc
}
if tag != "" {
lc.Tag = tag
}
locale := source.getRemoteLocaleForLocaleFile(lc)
if locale != nil {
lc.ExistsRemote = true
lc.RFC = locale.Code
lc.Name = locale.Name
lc.Id = locale.Id
}
absolutePath, err := filepath.Abs(path)
if err != nil {
return nil, err
}
lc.Path = absolutePath
return lc, nil
}
func (source *Source) findTaggedMatches(path string) map[string]string {
re := regexp.MustCompile("<(locale_name|tag|locale_code)>")
separator := string(os.PathSeparator)
taggedMatches := map[string]string{}
// config/locale/<locale_code>.yml -> ["config", "locale", "<locale_code>.yml"]
parts := strings.Split(source.File, separator)
for _, part := range parts {
if !re.MatchString(part) {
continue
}
// <locale_code>.yml -> (?P<locale_code>.+).yml
match := part
group := re.FindString(part)
if group == "" {
continue
}
replacer := fmt.Sprintf("(?P%s.+)", group)
match = strings.Replace(match, group, replacer, 1)
reMatcher := regexp.MustCompile(match)
namedMatches := reMatcher.SubexpNames()
subMatches := reMatcher.FindStringSubmatch(path)
for i, subMatch := range subMatches {
if subMatch != "" {
split := strings.Split(subMatch, separator)
// the match is either from start or end of path
// res/values-en/Strings.xml -> en/Strings.xml
newMatch := split[0]
if strings.HasPrefix(match, replacer) {
// config/en.lproj -> config/en
newMatch = split[len(split)-1]
}
taggedMatches[namedMatches[i]] = newMatch
}
}
}
return taggedMatches
}
func (source *Source) getRemoteLocaleForLocaleFile(localeFile *LocaleFile) *phraseapp.Locale {
for _, remote := range source.RemoteLocales {
if source.Params != nil {
localeId := source.Params.LocaleId
if remote.Id == localeId || remote.Name == localeId {
return remote
}
}
if remote.Name == localeFile.Name || remote.Code == localeFile.RFC {
return remote
}
}
return nil
}
func (source *Source) fileWithoutPlaceholder() string {
re := regexp.MustCompile("<(locale_name|tag|locale_code)>")
return strings.TrimSuffix(re.ReplaceAllString(source.File, "*"), source.Extension)
}
func (source *Source) extensionWithoutPlaceholder() string {
re := regexp.MustCompile("<(locale_name|tag|locale_code)>")
if re.MatchString(source.Extension) {
return ""
}
return "*" + source.Extension
}
func (source *Source) glob() ([]string, error) {
pattern := source.fileWithoutPlaceholder() + source.extensionWithoutPlaceholder()
files, err := filepath.Glob(pattern)
if Debug {
fmt.Println("Found", len(files), "files matching the source pattern", pattern)
}
if err != nil {
return nil, err
}
return files, nil
}
func (source *Source) recurse() ([]string, error) {
files := []string{}
err := filepath.Walk(source.root(), func(path string, f os.FileInfo, err error) error {
if strings.HasSuffix(f.Name(), source.Extension) {
files = append(files, path)
}
return nil
})
if err != nil {
return nil, err
}
return files, nil
}
func (source *Source) root() string {
separator := string(os.PathSeparator)
parts := strings.Split(source.File, separator)
rootParts := TakeWhile(parts, func(x string) bool { return x != "**" })
root := strings.Join(rootParts, separator)
if root == "" {
root = "."
}
return root
}
func SourcesFromConfig() (Sources, error) {
content, err := ConfigContent()
if err != nil {
return nil, err
}
var config *PushConfig
err = yaml.Unmarshal([]byte(content), &config)
if err != nil {
return nil, err
}
token := config.Phraseapp.AccessToken
projectId := config.Phraseapp.ProjectId
fileFormat := config.Phraseapp.FileFormat
if &config.Phraseapp.Push == nil {
return nil, fmt.Errorf("no sources specified")
}
sources := *config.Phraseapp.Push.Sources
validSources := []*Source{}
for _, source := range sources {
if source == nil {
continue
}
if source.ProjectId == "" {
source.ProjectId = projectId
}
if source.AccessToken == "" {
source.AccessToken = token
}
if source.FileFormat == "" {
source.FileFormat = fileFormat
}
validSources = append(validSources, source)
}
if len(validSources) <= 0 {
return nil, fmt.Errorf("no sources could be identified! Refine the sources list in your config")
}
return validSources, nil
}
func (source *Source) setUploadParams(localeFile *LocaleFile) (*phraseapp.LocaleFileImportParams, error) {
uploadParams := new(phraseapp.LocaleFileImportParams)
uploadParams.File = localeFile.Path
uploadParams.FileFormat = &source.FileFormat
if localeFile.Id != "" {
uploadParams.LocaleId = &(localeFile.Id)
} else if localeFile.RFC != "" {
uploadParams.LocaleId = &(localeFile.RFC)
}
if source.Params == nil {
return uploadParams, nil
}
params := source.Params
localeId := params.LocaleId
if localeId != "" {
uploadParams.LocaleId = &localeId
}
format := params.FileFormat
if format != "" {
uploadParams.FileFormat = &format
}
convertEmoji := params.ConvertEmoji
if convertEmoji != nil {
uploadParams.ConvertEmoji = convertEmoji
}
formatOptions := params.FormatOptions
if formatOptions != nil {
uploadParams.FormatOptions = formatOptions
}
skipUnverification := params.SkipUnverification
if skipUnverification != nil {
uploadParams.SkipUnverification = skipUnverification
}
skipUploadTags := params.SkipUploadTags
if skipUploadTags != nil {
uploadParams.SkipUploadTags = skipUploadTags
}
tags := params.Tags
if tags != nil {
uploadParams.Tags = tags
}
updateTranslations := params.UpdateTranslations
if updateTranslations != nil {
uploadParams.UpdateTranslations = updateTranslations
}
return uploadParams, nil
}
type PushConfig struct {
Phraseapp struct {
AccessToken string `yaml:"access_token"`
ProjectId string `yaml:"project_id"`
FileFormat string `yaml:"file_format,omitempty"`
Push struct {
Sources *Sources
}
}
}
func printSummary(summary *phraseapp.SummaryType) {
newItems := []int64{summary.LocalesCreated, summary.TranslationsUpdated, summary.TranslationKeysCreated, summary.TranslationsCreated}
var changed bool
for _, item := range newItems {
if item > 0 {
changed = true
}
}
if changed || Debug {
printMessage("Locales created: ", fmt.Sprintf("%d", summary.LocalesCreated))
printMessage("- Keys created: ", fmt.Sprintf("%d", summary.TranslationKeysCreated))
printMessage("- Translations created: ", fmt.Sprintf("%d", summary.TranslationsCreated))
printMessage("- Translations updated: ", fmt.Sprintf("%d", summary.TranslationsUpdated))
fmt.Print("\n")
}
}
func printMessage(msg, stat string) {
fmt.Print(msg)
ct.Foreground(ct.Green, true)
fmt.Print(stat)
ct.ResetColor()
}