-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathi18n.ts
98 lines (92 loc) · 2.73 KB
/
i18n.ts
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
import { Plugin } from '@merryjs/cli/lib/plugin'
import child_process from 'child_process'
import { FlutterOptions } from './action'
import fs from 'fs-extra'
import fg from 'fast-glob'
var OpenCC = require('opencc')
import changeCase from 'change-case'
const translate = require('@vitalets/google-translate-api')
export default async (api: Plugin, options: FlutterOptions) => {
run({
api,
msg: 'extract message from dart file to arb',
command:
'flutter pub pub run intl_translation:extract_to_arb --output-dir=lib/l10n --locale=zh lib/*.dart lib/**/*.dart',
})
const items = await fg('lib/**/*.arb')
const messagesFile = items.filter(item =>
(item as string).includes('messages.arb')
)[0] as string
if (!messagesFile) {
api.log('message file not found')
return
}
const messages = fs.readJSONSync(messagesFile)
const files = items.filter(item => !(item as string).includes('messages.arb'))
for (const file of files) {
const f = file as string
const json = fs.readJSONSync(f)
// merge
const merge = { ...messages, ...json }
// s2tw
if (f.includes('zh_TW') || f.includes('zh_HK')) {
const cc = new OpenCC(f.includes('TW') ? 's2tw.json' : 's2hk.json')
// ignore key start with @ symbol
for (const key in merge) {
if (merge.hasOwnProperty(key)) {
const element = merge[key]
if (key.startsWith('@')) {
continue
}
merge[key] = cc.convertSync(element)
}
}
} else if (!f.includes('zh') && options.auto) {
const matchs = f.match(/intl_(.*)\./)
// defaults to en if match failed
const locale = matchs ? matchs[1] : 'en'
api.log('Translating to %s using Google TranslateToolKit api', locale)
for (const key in merge) {
if (merge.hasOwnProperty(key)) {
const element = merge[key]
if (key.startsWith('@')) {
continue
}
try {
const res = await translate(element, { to: locale })
merge[key] =
locale === 'en' ? changeCase.upperCaseFirst(res.text) : res.text
} catch (error) {
api.log(error)
}
}
}
}
fs.writeFileSync(f, JSON.stringify(merge, null, 2))
}
run({
api,
msg: 'generate dart message from arb',
command:
'flutter pub pub run intl_translation:generate_from_arb --output-dir=lib/l10n --no-use-deferred-loading lib/*.dart lib/**/*.dart lib/l10n/intl_*.arb',
})
}
/**
* run command sync
* @param param0
*/
function run({
api,
command,
msg,
options,
}: {
api: Plugin
command: string
msg: string
options?: FlutterOptions
}) {
api.log(msg)
child_process.execSync(command)
api.log(msg + ' done.')
}