-
-
Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathorderLocale.mjs
73 lines (61 loc) · 1.99 KB
/
orderLocale.mjs
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
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import prettier from 'prettier'
// Check if value is an object. Do not count arrays as objects.
const isObject = o => (Array.isArray(o) ? false : typeof o === 'object')
// Get files from given directory.
const getDirectoryFiles = (source, omit) =>
fs
.readdirSync(source, { withFileTypes: true })
.filter(v => !omit.includes(v.name))
.map(dirent => dirent.name)
// Order keys of a json object.
const orderKeysAlphabetically = o =>
Object.keys(o)
.sort()
.reduce((obj, key) => {
obj[key] = o[key]
return obj
}, {})
// Order json object by its keys.
const orderJsonByKeys = (json) => {
// order top level keys.
json = orderKeysAlphabetically(json)
// order child objects if they are values.
const jsonOrdered = {}
Object.entries(json).forEach(
([k, v]) => isObject(v)
? jsonOrdered[k] = orderJsonByKeys(v)
: jsonOrdered[k] = v,
)
return jsonOrdered
}
// Project locale directory.
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const localeDir = path.join(__dirname, '..', 'i18n/locales')
// Get all language paths to re-order.
const languages = getDirectoryFiles(localeDir, []).filter(file => file.endsWith('.json'))
// For each language path.
for (const lng of languages) {
const pathToLanguageFile = path.join(localeDir, `/${lng}`)
fs.readFile(pathToLanguageFile, async (error) => {
if (error) return
const json = JSON.parse(fs.readFileSync(pathToLanguageFile).toString())
// order json object alphabetically.
const orderedJson = orderJsonByKeys(json)
// format json object.
const formatted = await prettier.format(JSON.stringify(orderedJson), {
parser: 'json',
})
fs.writeFile(pathToLanguageFile, formatted, (err) => {
if (err) {
console.err(err)
}
else {
console.log(`✅ Keys in ${pathToLanguageFile} are sorted alphabetically`)
}
})
})
}