Issue #492

Suppose we have a base Localizable.strings

"open" = "Open";
"closed" = "Closed";

After sending that file for translations, we get translated versions.

"open" = "Åpen";
"closed" = "Stengt";

Searching and copy pasting these to our Localizable.strings is tedious and time consuming. We can write a script to apply that.

Remember that we need to be aware of smart and dump quotes

.replace(/\"/g, '')
.replace(/\"/g, '')
const fs = require('fs')

const originalFile = 'MyApp/Resources/nb.lproj/Localizable.strings'
const translationString = `
"open" = "Åpen";
"closed" = "Stengt";
`

class Translation {
    constructor(key, value) {
        this.key = key
        this.value = value
    }
}

Translation.make = function make(line) {
    if (!line.endsWith(';')) {
        return new Translation('', '')
    }

    const parts = line
        .replace(';')
        .split(" = ")

    const key = parts[0]
        .replace(/\"/g, '')
        .replace(/\”/g, '')
    const value = parts[1]
        .replace(/\"/g, '')
        .replace(/\”/g, '')
        .replace('undefined', '')
    return new Translation(key, value)
}

function main() {
    const translations = translationString
        .split(/\r?\n/)
        .map((line) => { return Translation.make(line) })

    apply(translations, originalFile)
}

function apply(translations, originalFile) {
    try {
        const originalData = fs.readFileSync(originalFile, 'utf8')
        const originalLines = originalData.split(/\r?\n/)
        const parsedLine = originalLines.map((originalLine) => {
            const originalTranslation = Translation.make(originalLine)
            const find = translations.find((translation) => { return translation.key === originalTranslation.key })
            if (originalLine !== "" && find !== undefined &&  find.key !== "") {
                return `"${find.key}" = "${find.value}";`
            } else {
                return originalLine
            }
        })

        const parsedData = parsedLine.join('\n')
        fs.writeFileSync(originalFile, parsedData, { overwrite: true })
    } catch (err) {
        console.error(err)
    }
}

main()