-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.js
More file actions
102 lines (85 loc) · 3.03 KB
/
index.js
File metadata and controls
102 lines (85 loc) · 3.03 KB
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
var fs = require('fs')
var path = require('path')
var gettextParser = require('gettext-parser')
var babelParser = require('@babel/parser')
var walk = require('babylon-walk')
var functionNames = require('./lib/constant').DEFAULT_FUNCTION_NAMES
var DEFAULT_HEADERS = require('./lib/constant').DEFAULT_HEADERS
/**
* The parser function
* @param {String} input The path to soure JavaScript file
* @param {String} output The path of the output PO file
* @param {Function} cb The callback function
*/
function parser (inputs, output, plugins, cb) {
var data = {
charset: 'UTF-8',
headers: DEFAULT_HEADERS,
translations: {
context: {}
}
}
var defaultContext = data.translations.context
var headers = data.headers
headers['plural-forms'] = headers['plural-forms'] || DEFAULT_HEADERS['plural-forms']
headers['content-type'] = headers['content-type'] || DEFAULT_HEADERS['content-type']
var nplurals = /nplurals ?= ?(\d)/.exec(headers['plural-forms'])[1]
inputs
.forEach(function (file) {
var resolvedFilePath = path.join(process.cwd(), file)
var src = fs.readFileSync(resolvedFilePath, 'utf8')
try {
var ast = babelParser.parse(src, {
sourceType: 'module',
plugins: ['jsx'].concat(plugins)
})
} catch (e) {
console.error(`SyntaxError in ${file} (line: ${e.loc.line}, column: ${e.loc.column})`)
process.exit(1)
}
walk.simple(ast.program, {
CallExpression: function (node) {
if (functionNames.hasOwnProperty(node.callee.name) ||
node.callee.property && functionNames.hasOwnProperty(node.callee.property.name)) {
var functionName = functionNames[node.callee.name] || functionNames[node.callee.property.name]
var translate = {}
var args = node.arguments
for (var i = 0, l = args.length; i < l; i++) {
var name = functionName[i]
if (name && name !== 'count' && name !== 'domain') {
var arg = args[i]
var value = arg.value
if (value) {
var line = node.loc.start.line
translate[name] = value
translate['comments'] = {
reference: file + ':' + line
}
}
if (name === 'msgid_plural') {
translate.msgstr = []
for (var p = 0; p < nplurals; p++) {
translate.msgstr[p] = ''
}
}
}
}
var context = defaultContext
var msgctxt = translate.msgctxt
if (msgctxt) {
data.translations[msgctxt] = data.translations[msgctxt] || {}
context = data.translations[msgctxt]
}
context[translate.msgid] = translate
}
}
})
})
fs.writeFile(output, gettextParser.po.compile(data), function (err) {
if (err) {
cb(err)
}
cb(null)
})
}
module.exports = parser