Skip to content
This repository has been archived by the owner on Feb 22, 2023. It is now read-only.

Replace {} placeholders with ### and escape quotes in strings in POT file #152

Merged
merged 2 commits into from
Aug 24, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 51 additions & 3 deletions json-to-pot.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,49 @@
// More about the structure of .po files:
// https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html#PO-Files

/*
* white-space
# translator-comments
#. extracted-comments
#: reference…
#, flag…
#| msgid previous-untranslated-string
msgid untranslated-string
msgstr translated-string
*/
Comment on lines +4 to +13
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for adding this, very helpful!


const json = require('./src/locales/en.json')
const fs = require('fs')

const curlyRegex = new RegExp('{[a-z]*}')
const containsCurlyWord = (string) => curlyRegex.test(string)
const checkStringForVars = (string) =>
containsCurlyWord(string) ? '(Do not translate words in curly braces)' : ''
containsCurlyWord(string) ? '(Do not translate words between ###)' : ''

/**
* For GlotPress to display warning when the translators try to
* replace placeholders with something else, we need to wrap the
* placeholders with `###word###`
* @param string
* @return {string}
*/
const replaceVarsPlaceholders = (string) => {
if (!containsCurlyWord(string)) {
return string
}
const variable = /{(?<variable>[a-z]*)}/g
return string.replace(variable, `###$<variable>###`)
}

/**
* Replace placeholder format for variables,
* escape quotes (in a different PR)
* @param string
* @return {string}
*/
const processValue = (string) => {
return escapeQuotes(replaceVarsPlaceholders(string))
}

const findPath = (ob, key) => {
const path = []
Expand Down Expand Up @@ -41,6 +81,8 @@ const findPath = (ob, key) => {
return path.join('.')
}

const escapeQuotes = (str) => str.replace(/"/g, '\\"')

// POT Syntax

// msgctxt context
Expand All @@ -56,7 +98,7 @@ function potTime(json, parent = json) {

# ${findPath(parent, key)}.${key} ${checkStringForVars(value)}
msgctxt "${findPath(parent, key)}.${key}"
msgid "${value}"
msgid "${processValue(value)}"
msgstr ""`
}
if (typeof value === 'object') {
Expand All @@ -67,4 +109,10 @@ msgstr ""`
}

const potFile = potTime(json)

try {
const fileName = 'test.pot'
fs.writeFileSync(fileName, potFile)
console.log(`Successfully wrote pot file to ${fileName}`)
} catch (err) {
console.error(err)
}