Created
June 23, 2023 07:26
-
-
Save andrii-bodnar/a4ae6c45b6d332c8201ab9e1fd25716e to your computer and use it in GitHub Desktop.
Lingui JSON catalog format migration script v3 -> v4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
/* eslint-disable no-restricted-syntax, no-await-in-loop */ | |
import crypto from 'node:crypto' | |
import fs from 'node:fs/promises' | |
// from https://github.com/lingui/js-lingui/blob/59f0eb3565611d5860c883aa42a20365392ca1d8/packages/message-utils/src/generateMessageId.ts | |
const UNIT_SEPARATOR = '\u001F' | |
function generateMessageId(msg, context = '') { | |
return crypto | |
.createHash('sha256') | |
.update(msg + UNIT_SEPARATOR + (context || '')) | |
.digest('base64') | |
.slice(0, 6) | |
} | |
function printHelp() { | |
process.stdout.write( | |
[ | |
'Migrate Lingui’s JSON catalogues into new hash–based keys.', | |
'', | |
`Usage: ${process.argv.slice(0, 2).join(' ')} JSON_FILE...`, | |
'', | |
].join('\n') | |
) | |
} | |
const filePaths = process.argv.slice(2) | |
if (!filePaths.length) { | |
printHelp() | |
process.exit(64) | |
} else if (['-h', '--help'].includes(filePaths[0])) { | |
printHelp() | |
process.exit(0) | |
} | |
for (const filePath of filePaths) { | |
const json = await fs.readFile(filePath, { encoding: 'utf-8' }) | |
const msgs = JSON.parse(json) | |
const newMsgs = Object.fromEntries( | |
Object.entries(msgs).map(([key, value]) => { | |
if (value.message) { | |
// Already in new format | |
return [key, value] | |
} | |
const message = key | |
const { translation, extractedComments: comments } = value | |
return [ | |
generateMessageId(message), | |
{ | |
translation, | |
message, | |
comments, | |
}, | |
] | |
}) | |
) | |
await fs.writeFile(filePath, JSON.stringify(newMsgs, null, 2)) | |
} | |
process.stdout.write('Done. You probably want to run this now:\n') | |
process.stdout.write('npx lingui extract && npx lingui compile\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment