forked from facebook/create-react-app
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcoalesceLocales.js
188 lines (173 loc) · 6.93 KB
/
coalesceLocales.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
'use strict';
const debug = require('debug')('coalesceLocales');
const dependencyTree = require('dependency-tree');
const jsonfile = require('jsonfile');
const path = require('path');
const fs = require('fs');
const rimraf = require('rimraf');
const chokidar = require('chokidar');
const _ = require('lodash');
const glob = require('fast-glob')
exports.coalesceLocales = paths => {
console.time('per-locale coalesce');
const builtLocalesDir = `${paths.appSrc}/locales/dist`;
if (fs.existsSync(builtLocalesDir)) {
rimraf.sync(builtLocalesDir);
}
fs.mkdirSync(builtLocalesDir);
const index = fs.existsSync(`${paths.appSrc}/index.tsx`)
? `${paths.appSrc}/index.tsx`
: `${paths.appSrc}/index.js`;
const nonExistents = []
const list = dependencyTree.toList({
filename: index,
directory: paths.appPath,
tsConfig: fs.existsSync(paths.appTsConfig) && paths.appTsConfig,
noTypeDefinitions: true, // optional
detective: { es6: { mixedImports: true }},
nodeModulesConfig: { entry: 'module' },
nonExistent: nonExistents,
filter: filePath => filePath.includes(paths.appSrc) || filePath.includes('@fs'),
}).sort();
/*
REMINDER: when comparing paths, make sure to take into account Windows/WSL2 paths that will look like: 'C:\\Users\\MyUser\\my-project\\node_modules\\@fs\\flags-js\\src\\index.js'
Constructing paths with forward slashes works, but not comparing the file path string, which needs to use `path.join()` or `path.sep`
*/
// the nonExistents array is populated with any file that dependencyTree was unable to locate on the filesystem.
// Currently we have an issue if npm didn't flatten a dependency to node_modules/@fs/ then dependencyTree says that
// dependency is nonExistent. Specifically chinese-discovery-surname got into an issue once where zion-header wasn't
// flattened, and so they didn't get zion-header translations coalesced. We are adding this globbing logic to go
// find the least nested path to the "nonExistent" module.
const hiddenNestedZionDeps = nonExistents.filter(filePath => filePath.startsWith(path.join('@fs','zion-')))
const hiddenNestedLocaleFiles = hiddenNestedZionDeps.map(filePath => {
const hiddenLocaleFiles = glob.sync([`node_modules/@fs/**/${filePath}/**/locales/index.js`], { absolute: true })
.filter(filePath => !filePath.includes(`${path.sep}cjs${path.sep}`))
return _.sortBy(hiddenLocaleFiles, filePath => filePath.split(path.sep).length)[0]
})
// adding this filter logic up in dependencyTree doesn't work as expected
const realList = [...list.filter(filePath => filePath.includes(path.join('locales','index.js'))), ...hiddenNestedLocaleFiles]
const allLocales = {};
const collisionReport = {
collisions: [],
potentialCollisions: [],
};
const statsReport = {
namespaces: new Set(),
locales: new Set(),
keys: new Set(),
};
realList.forEach(p => {
if (!p) {return}
const dir = path.dirname(p);
// console.log('dir', dir)
const locales = fs
.readdirSync(dir)
.filter(d => !d.includes('.') && d !== 'dist');
locales.forEach(locale => {
statsReport.locales.add(locale);
const namespaces = fs
.readdirSync(path.join(dir, locale))
.map(d => d.split('.')[0]);
allLocales[locale] = allLocales[locale] || {};
namespaces.forEach(ns => {
statsReport.namespaces.add(ns);
const strings = jsonfile.readFileSync(
`${path.join(dir, locale, ns)}.json`
);
allLocales[locale][ns] = allLocales[locale][ns] || {};
// console.log('strings', Object.keys(strings))
// console.log('allLocales', Object.keys(allLocales[locale][ns]||{}))
Object.keys(strings).map(key => statsReport.keys.add(key));
const collisions = _.intersection(
Object.keys(allLocales[locale][ns]),
Object.keys(strings)
);
if (collisions && collisions.length > 0) {
collisions.forEach(collisionKey => {
if (
allLocales[locale][ns][collisionKey] !== strings[collisionKey]
) {
collisionReport.collisions.push({
key: collisionKey,
locale,
ns,
oldValue: allLocales[locale][ns][collisionKey],
newValue: strings[collisionKey],
});
// console.error(`COLLISION: key=${collisionKey} locale=${locale} namespace=${ns} "${strings[collisionKey]}" overrides "${allLocales[locale][ns][collisionKey]}"`)
} else {
collisionReport.potentialCollisions.push({
key: collisionKey,
locale,
ns,
oldValue: allLocales[locale][ns][collisionKey],
newValue: strings[collisionKey],
});
}
});
}
allLocales[locale][ns] = { ...allLocales[locale][ns], ...strings };
});
});
});
if (collisionReport.potentialCollisions.length > 0) {
console.warn(`WARNING: There were ${collisionReport.potentialCollisions.length} potential collisions detected when coalescing locales, the values were the same, but could diverge in the future:
To see a list of all potential collisions, turn on debugging with "DEBUG=coalesceLocales" before the command you just ran `);
collisionReport.potentialCollisions.forEach(
({ key, locale, ns, newValue }) =>
debug(
`\tkey=${key} namespace=${ns} locale=${locale} value="${newValue}"`
)
);
}
if (collisionReport.collisions.length > 0) {
console.error(
`ERROR: There were ${collisionReport.collisions.length} collisions were detected when coalescing locales.`
);
collisionReport.collisions.forEach(
({ key, locale, ns, newValue, oldValue }) =>
console.error(
`\tkey=${key} namespace=${ns} locale=${locale} newValue="${newValue}" oldValue="${oldValue}"`
)
);
}
Object.keys(allLocales).forEach(locale => {
fs.mkdirSync(path.join(builtLocalesDir, locale));
Object.keys(allLocales[locale]).forEach(namespace => {
jsonfile.writeFileSync(
`${path.join(builtLocalesDir, locale, namespace)}.json`,
allLocales[locale][namespace]
);
});
});
console.timeEnd('per-locale coalesce');
console.log(`Locales Stats`, {
namespaces: statsReport.namespaces,
locales: statsReport.locales,
keys: statsReport.keys.size,
});
// console.dir(allLocales)
// throw new Error('boom')
};
exports.watchCoalesce = paths => {
const watcher = chokidar.watch(
`${path.join(paths.appSrc, 'locales')}/!(dist)/*`,
{
ignored: 'dist',
}
);
watcher.on(
'all',
_.debounce(() => {
console.log('Detected change to locales, recoalescing...');
exports.coalesceLocales(paths);
}, 250)
);
['SIGINT', 'SIGTERM'].forEach(function (sig) {
process.on(sig, function () {
watcher.close();
process.exit();
});
});
exports.coalesceLocales(paths);
};