-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathproject.go
340 lines (283 loc) · 7.32 KB
/
project.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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"path"
"path/filepath"
"strings"
"sync"
"text/template"
"github.com/99designs/api-sdk-go"
"github.com/urfave/cli"
)
var ProjectCommand = cli.Command{
Name: "project",
Usage: "manage local project files",
Before: func(c *cli.Context) error {
err := cmdBefore(c)
if err != nil {
return nil
}
return loadProjectErr
},
Subcommands: []cli.Command{
projectFilesCommand,
projectStatusCommand,
projectPullCommand,
projectPushCommand,
},
}
var prefixFlag = cli.StringFlag{
Name: "prefix",
Usage: "Prefix to use for uploaded file names",
EnvVar: "SMARTLING_PREFIX",
}
func fetchRemoteFileList() stringSlice {
files := stringSlice{}
listFiles, err := client.List(smartling.FilesListRequest{})
logAndQuitIfError(err)
for _, fs := range listFiles.Items {
files = append(files, fs.FileURI)
}
return files
}
var remoteFileList = stringSlice{}
var remoteFileListFetched = false
func getRemoteFileList() stringSlice {
if !remoteFileListFetched {
remoteFileList = fetchRemoteFileList()
}
return remoteFileList
}
func fetchLocales() []string {
ll := []string{}
locales, err := client.Locales()
logAndQuitIfError(err)
for _, l := range locales {
ll = append(ll, l.LocaleID)
}
return ll
}
var projectFilesCommand = cli.Command{
Name: "files",
Usage: "lists the local files",
Action: func(c *cli.Context) {
if len(c.Args()) != 0 {
log.Println("Wrong number of arguments")
log.Fatalln("Usage: files")
}
for _, projectFilepath := range ProjectConfig.Files() {
fmt.Println(projectFilepath)
}
},
}
var projectStatusCommand = cli.Command{
Name: "status",
Usage: "show the status of the project's remote files",
Flags: []cli.Flag{
prefixFlag,
cli.BoolFlag{
Name: "awaiting-auth",
Usage: "Output the number of strings Awaiting Authorization",
},
},
Action: func(c *cli.Context) {
if len(c.Args()) > 0 {
log.Println("Wrong number of arguments")
log.Fatalln("Usage: status")
}
prefix := prefixOrGitPrefix(c.String("prefix"))
locales := fetchLocales()
statuses := GetProjectStatus(prefix, locales)
if c.Bool("awaiting-auth") {
fmt.Println(statuses.AwaitingAuthorizationCount())
} else {
fmt.Print("\n")
PrintProjectStatusTable(statuses, locales)
fmt.Print("\n")
fmt.Printf("Awaiting Authorization: %4d\n", statuses.AwaitingAuthorizationCount())
fmt.Printf("Total: %4d\n", statuses.TotalStringsCount())
}
},
}
var projectPullCommand = cli.Command{
Name: "pull",
Usage: "translate local project files using Smartling as a translation memory",
Flags: []cli.Flag{
prefixFlag,
},
Action: func(c *cli.Context) {
if len(c.Args()) > 0 {
log.Println("Wrong number of arguments")
log.Fatalln("Usage: pull")
}
prefix := prefixOrGitPrefix(c.String("prefix"))
pullAllProjectFiles(prefix)
},
}
func pullAllProjectFiles(prefix string) {
locales, err := client.Locales()
logAndQuitIfError(err)
// do this first to cache result and prevent races in the goroutines
_ = getRemoteFileList()
var wg sync.WaitGroup
for _, projectFilepath := range ProjectConfig.Files() {
for _, l := range locales {
wg.Add(1)
go func(locale, projectFilepath string) {
defer wg.Done()
pullProjectFile(projectFilepath, locale, prefix)
}(l.LocaleID, projectFilepath)
}
}
wg.Wait()
}
func pullProjectFile(projectFilepath, locale, prefix string) {
hit, b, err := translateProjectFile(projectFilepath, locale, prefix)
logAndQuitIfError(err)
fp := localPullFilePath(projectFilepath, locale)
cached := ""
if hit {
cached = "(using cache)"
}
err = ioutil.WriteFile(fp, b, 0644)
logAndQuitIfError(err)
fmt.Println("Wrote", fp, cached)
}
func cleanPrefix(s string) string {
s = path.Clean("/" + s)
if s == "/" {
return ""
}
return s
}
func prefixOrGitPrefix(prefix string) string {
if prefix == "" {
prefix = pushPrefix()
}
prefix = cleanPrefix(prefix)
if prefix != "" {
log.Println("Using prefix", prefix)
}
return prefix
}
var projectPushCommand = cli.Command{
Name: "push",
Usage: "upload local project files that contain untranslated strings",
Flags: []cli.Flag{
prefixFlag,
},
Action: func(c *cli.Context) {
if len(c.Args()) > 0 {
log.Println("Wrong number of arguments")
log.Fatalln("Usage: push")
}
prefix := prefixOrGitPrefix(c.String("prefix"))
pushAllProjectFiles(prefix)
},
}
// if prefix is empty, don't append the hash also
func projectFileRemoteName(projectFilepath, prefix string) string {
remoteFile := projectFilepath
if prefix != "" {
remoteFile = fmt.Sprintf("%s/%s/%s", prefix, projectFileHash(projectFilepath), projectFilepath)
}
return path.Clean("/" + remoteFile)
}
func readFile(projectFilepath string) []byte {
f, err := ioutil.ReadFile(projectFilepath)
logAndQuitIfError(err)
return f
}
func pushProjectFile(projectFilepath, prefix string) string {
remoteFile := projectFileRemoteName(projectFilepath, prefix)
req := &smartling.FileUploadRequest{
FileURIRequest: smartling.FileURIRequest{FileURI: remoteFile},
FileType: filetypeForProjectFile(projectFilepath),
File: readFile(projectFilepath),
}
req.Smartling.Directives = ProjectConfig.ParserConfig
_, err := client.Upload(req)
logAndQuitIfError(err)
log.Println("Uploaded", remoteFile)
return remoteFile
}
func pushProjectFileIfNotExists(projectFilepath, prefix string) (string, bool) {
remoteFiles := getRemoteFileList()
remoteFileName := projectFileRemoteName(projectFilepath, prefix)
if prefix != "" && remoteFiles.contains(remoteFileName) {
return remoteFileName, false
}
return pushProjectFile(projectFilepath, prefix), true
}
func pushAllProjectFiles(prefix string) {
pushedFilesCount := 0
// do this first to cache result and prevent races in the goroutines
_ = getRemoteFileList()
var wg sync.WaitGroup
for _, projectFilepath := range ProjectConfig.Files() {
wg.Add(1)
go func(projectFilepath string) {
defer wg.Done()
_, pushed := pushProjectFileIfNotExists(projectFilepath, prefix)
if pushed {
pushedFilesCount++
}
}(projectFilepath)
}
wg.Wait()
if pushedFilesCount == 0 {
fmt.Println("Nothing to do")
}
}
func filetypeForProjectFile(projectFilepath string) smartling.FileType {
ft := smartling.GetFileTypeByExtension(path.Ext(projectFilepath))
if ft == "" {
ft = ProjectConfig.FileType
}
if ft == "" {
log.Panicln("Can't determine file type for " + projectFilepath)
}
return ft
}
type FilenameParts struct {
Path string
Base string
Dir string
Ext string
PathWithoutExt string
Locale string
}
func localRelativeFilePath(remotepath string) string {
fp, err := filepath.Rel(".", path.Join(ProjectConfig.path, remotepath))
logAndQuitIfError(err)
return fp
}
func localPullFilePath(p, locale string) string {
parts := FilenameParts{
Path: p,
Dir: path.Dir(p),
Base: path.Base(p),
Ext: path.Ext(p),
Locale: locale,
}
dt := defaultPullDestination
if dt != "" {
dt = ProjectConfig.PullFilePath
}
out := bytes.NewBufferString("")
tmpl := template.New("name")
tmpl.Funcs(template.FuncMap{
"TrimSuffix": strings.TrimSuffix,
"Truncate": func(s string, n int) string {
return s[:n]
},
})
_, err := tmpl.Parse(dt)
logAndQuitIfError(err)
err = tmpl.Execute(out, parts)
logAndQuitIfError(err)
return localRelativeFilePath(out.String())
}