How to apply translations to Localizable.strings

Issue #492

Suppose we have a base Localizable.strings

1
2
"open" = "Open";
"closed" = "Closed";

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

1
2
"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

1
2
.replace(/\"/g, '')
.replace(/\"/g, '')
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
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()

Comments