Skip to content

Instantly share code, notes, and snippets.

@dmarcelino
Forked from narrowtux/xgettext-loader.js
Created March 8, 2018 22:45
Show Gist options
  • Save dmarcelino/4a29bce78fba55c5225d9f39cbdc8ea6 to your computer and use it in GitHub Desktop.
Save dmarcelino/4a29bce78fba55c5225d9f39cbdc8ea6 to your computer and use it in GitHub Desktop.
let child = require("child_process")
let source_map = require("source-map")
let SourceMapConsumer = source_map.SourceMapConsumer
let path = require("path")
var crypto = require('crypto');
module.exports = function(source, sourceMap) {
this.cacheable()
this.async()
var self = this
var xgettext = child.spawn("xgettext", [
"--from-code=UTF-8",
"--language=JavaScript",
"--keyword=gettext:1",
"--keyword=ngettext:1,2",
"--keyword=pgettext:1c,2",
"--keyword=npgettext:1c,2,3",
"--output=-",
"-"
])
xgettext.stdin.write(source)
xgettext.stdin.end()
var po = ""
xgettext.stdout.on("data", (data) => po = po + data)
xgettext.on("close", (code) => {
if (code == 0) {
if (po.trim() != "") {
var lines = source.split("\n")
var filename = path.relative(".", self.resource)
var consumer = null;
if (sourceMap) {
consumer = new SourceMapConsumer(sourceMap)
}
po = po.replace(/^#: st[^:]+:([0-9]+)\n(msgid|msgctxt) ([^\n]+)/igm, (_m, line, msgtype, msgid, _o, _s) => {
line = line * 1
var actualLine = "?"
if (consumer) {
var column = lines[line - 1].indexOf(msgid) + 1
var result = consumer.originalPositionFor({line, column})
actualLine = result.line
}
return `#: ${filename}:${actualLine}\n${msgtype} ${msgid}`
})
po = po.replace("Content-Type: text/plain; charset=CHARSET", "Content-Type: text/plain; charset=utf-8")
let hash = crypto.createHash('md5').update(source).digest("hex");
let query = this.resourceQuery.replace("?", "")
let outPath = path.join("i18n/sources", `${filename}.${hash}.po`)
self.emitFile(outPath, po, {})
}
} else {
throw `xgettext returned with code ${code}`
}
self.callback(null, source)
})
xgettext.stderr.on("data", (error) => {
xgettext.removeAllListeners()
self.callback(error, source)
})
return undefined;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment