Skip to content

Instantly share code, notes, and snippets.

@felixhaeberle
Created October 10, 2023 12:36
Show Gist options
  • Save felixhaeberle/40e0fe6ea73154f7210ef4280f33b07a to your computer and use it in GitHub Desktop.
Save felixhaeberle/40e0fe6ea73154f7210ef4280f33b07a to your computer and use it in GitHub Desktop.
Merge languages files (JSON) to inlang message format
// Execute with `node merge.js`
// WARNING: This script does currently not support VariableReferences / variables in your text
import fs from "node:fs"
import path from "node:path"
const inputDirectory = "./" // Replace with your actual directory path
const outputFile = "messages.json"
const messages = {
$schema: "https://inlang.com/schema/inlang-message-format",
data: [],
}
// Read all files in the input directory
for (const file of fs.readdirSync(inputDirectory)) {
const filePath = path.join(inputDirectory, file)
if (fs.statSync(filePath).isFile() && file.endsWith(".json") && file !== outputFile) {
const languageTag = file.replace(".json", "")
// Read the JSON file
const content = JSON.parse(fs.readFileSync(filePath, "utf-8"))
// Iterate through each message in the file
const flattenMessages = (obj, parentKey = "") => {
let result = {}
for (let key in obj) {
const currentKey = parentKey ? `${parentKey}_${key}` : key
if (typeof obj[key] === "object") {
result = { ...result, ...flattenMessages(obj[key], currentKey) }
} else {
result[currentKey] = obj[key]
}
}
return result
}
const flattenedContent = flattenMessages(content)
for (const id in flattenedContent) {
const existingMessage = messages.data.find((m) => m.id === id)
if (existingMessage) {
// Message with the same ID already exists, add a new variant
existingMessage.variants.push({
match: [],
languageTag,
pattern: [
{
type: "Text",
value: flattenedContent[id],
},
],
})
} else {
// Message does not exist, create a new message
messages.data.push({
id,
selectors: [],
variants: [
{
match: [],
languageTag,
pattern: [
{
type: "Text",
value: flattenedContent[id],
},
],
},
],
})
}
}
}
}
// Write the merged messages to the output file
fs.writeFileSync(outputFile, JSON.stringify(messages, undefined, 2))
console.log(`Messages merged and saved to ${outputFile}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment