-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathwrite-translations.js
executable file
·216 lines (195 loc) · 6.09 KB
/
write-translations.js
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
#!/usr/bin/env node
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* generate the i18n/en.json file */
require('@babel/register')({
babelrc: false,
only: [__dirname, `${process.cwd()}/core`],
plugins: [
require('./server/translate-plugin.js'),
require('@babel/plugin-proposal-class-properties').default,
require('@babel/plugin-proposal-object-rest-spread').default,
],
presets: [
require('@babel/preset-react').default,
require('@babel/preset-env').default,
],
});
const traverse = require('@babel/traverse').default;
const babylon = require('babylon');
const fs = require('fs-extra');
const glob = require('glob');
const mkdirp = require('mkdirp');
const nodePath = require('path');
const _ = require('lodash');
const readMetadata = require('./server/readMetadata.js');
const CWD = process.cwd();
const siteConfig = require(`${CWD}/siteConfig.js`);
const sidebars = require(`${CWD}/sidebars.json`);
let customTranslations = {
'localized-strings': {
docs: {},
links: {},
categories: {},
},
'pages-strings': {},
};
if (fs.existsSync(`${CWD}/data/custom-translation-strings.json`)) {
customTranslations = _.merge(
{},
JSON.parse(
fs.readFileSync(`${CWD}/data/custom-translation-strings.json`, 'utf8'),
),
customTranslations,
);
}
function writeFileAndCreateFolder(file, content) {
mkdirp.sync(file.replace(new RegExp('/[^/]*$'), ''));
fs.writeFileSync(file, content);
}
function execute() {
const translations = {
'localized-strings': {
next: 'Next',
previous: 'Previous',
tagline: siteConfig.tagline,
docs: {},
links: {},
categories: {},
},
'pages-strings': {},
};
// look through markdown headers of docs for titles and categories to translate
const docsDir = nodePath.join(CWD, '../', readMetadata.getDocsPath());
const versionedDocsDir = nodePath.join(CWD, 'versioned_docs');
const translateDoc = (file, refDir) => {
const extension = nodePath.extname(file);
if (extension === '.md' || extension === '.markdown') {
let res;
try {
res = readMetadata.processMetadata(file, refDir);
} catch (e) {
console.error(e);
process.exit(1);
}
if (!res) {
return;
}
const metadata = res.metadata;
const id = metadata.localized_id;
translations['localized-strings'].docs[id] = {};
translations['localized-strings'].docs[id].title = metadata.title;
if (metadata.sidebar_label) {
translations['localized-strings'].docs[id].sidebar_label =
metadata.sidebar_label;
}
}
};
glob.sync(`${docsDir}/**`).forEach(file => translateDoc(file, docsDir));
glob
.sync(`${versionedDocsDir}/**`)
.forEach(file => translateDoc(file, versionedDocsDir));
// look through header links for text to translate
siteConfig.headerLinks.forEach(link => {
if (link.label) {
translations['localized-strings'].links[link.label] = link.label;
}
});
// find sidebar category titles to translate
Object.keys(sidebars).forEach(sb => {
const categories = sidebars[sb];
Object.keys(categories).forEach(category => {
translations['localized-strings'].categories[category] = category;
});
});
glob.sync(`${CWD}/versioned_sidebars/*`).forEach(file => {
if (!file.endsWith('-sidebars.json')) {
if (file.endsWith('-sidebar.json')) {
console.warn(
`Skipping ${file}. Make sure your sidebar filenames follow this format: 'version-VERSION-sidebars.json'.`,
);
}
return;
}
let sidebarContent;
try {
sidebarContent = JSON.parse(fs.readFileSync(file, 'utf8'));
} catch (e) {
console.error(`Could not parse ${file} into json. ${e}`);
process.exit(1);
}
Object.keys(sidebarContent).forEach(sb => {
const categories = sidebarContent[sb];
Object.keys(categories).forEach(category => {
translations['localized-strings'].categories[category] = category;
});
});
});
// go through pages to look for text inside translate tags
glob.sync(`${CWD}/pages/en/**`).forEach(file => {
const extension = nodePath.extname(file);
if (extension === '.js') {
const ast = babylon.parse(fs.readFileSync(file, 'utf8'), {
plugins: ['jsx'],
});
traverse(ast, {
enter(path) {
if (
path.node.type === 'JSXElement' &&
path.node.openingElement.name.name === 'translate'
) {
const text = path.node.children[0].value
.trim()
.replace(/\s+/g, ' ');
let description = 'no description given';
const attributes = path.node.openingElement.attributes;
for (let i = 0; i < attributes.length; i++) {
if (attributes[i].name.name === 'desc') {
description = attributes[i].value.value;
}
}
translations['pages-strings'][`${text}|${description}`] = text;
}
},
});
}
});
// Manually add 'Help Translate' to en.json
translations['pages-strings'][
'Help Translate|recruit community translators for your project'
] = 'Help Translate';
translations['pages-strings'][
'Edit this Doc|recruitment message asking to edit the doc source'
] = 'Edit';
translations['pages-strings'][
'Translate this Doc|recruitment message asking to translate the docs'
] = 'Translate';
translations['pages-strings'] = Object.assign(
translations['pages-strings'],
customTranslations['pages-strings'],
);
translations['localized-strings'] = _.merge(
{},
translations['localized-strings'],
customTranslations['localized-strings'],
);
writeFileAndCreateFolder(
`${CWD}/i18n/en.json`,
`${JSON.stringify(
Object.assign(
{
_comment: 'This file is auto-generated by write-translations.js',
},
translations,
),
null,
2,
)}\n`,
);
}
execute();
module.exports = execute;