Skip to content

Instantly share code, notes, and snippets.

@screeny05
Created November 1, 2017 16:28
Show Gist options
  • Save screeny05/d45c9a94f459ce7e2a4f5b3cf090a5b8 to your computer and use it in GitHub Desktop.
Save screeny05/d45c9a94f459ce7e2a4f5b3cf090a5b8 to your computer and use it in GitHub Desktop.
Extract Shopware Snippets of a given language from the snippets export
const fs = require('fs');
// SCSV = Shopware Crappy Separated Values (SW Export Format)
const parseScsvLine = l => {
l = l.trim();
const tokens = [];
let buf = '';
let isOpenEntity = false;
for (let i = 0; i < l.length; i++) {
const c = l[i];
// ensure we are really closing this token
if (!isOpenEntity && c === ';' && (l[i + 1] === '\'' || (l[i + 1] === '"' && l[i + 2] !== '"') || (l[i + 1] === '"' && l[i + 2] === '"' && l[i + 3] === '"') || l[i + 1] === ';' || !l[i + 1])) {
tokens.push(clearScsvToken(buf));
buf = '';
} else {
if(c === '&'){
isOpenEntity = true;
} else if(isOpenEntity && !c.match(/\w/)){
isOpenEntity = false;
}
buf += c;
}
}
// always push remainder as token
tokens.push(clearScsvToken(buf));
return tokens;
};
const clearScsvToken = t => t.replace(/^'/, '').replace(/^"(.*)"$/, '$1').replace(/""/g, '"').trim();
const escapeCsvCell = v => '"' + v.replace(/"/g, '""') + '"';
const encodeArrayAsCsvLine = a => a.map(v => escapeCsvCell(v)).join(';');
const main = (inPath, lang, outPath = inPath + '.out.csv') => {
const csv = fs.readFileSync(inPath, 'utf8');
const scsvLines = csv.split('\n').map(line => line.trim());
const scsvHeader = scsvLines[0].split(';');
// find i of language-value
let langPos = -1;
scsvHeader.forEach((t, i) => {
if(t === 'value-' + lang){ langPos = i }
});
if(langPos === -1){
return console.error('locale-shopId combination', lang, 'not found in', inPath);
}
const csvHeader = 'namespace;name;value-' + lang + ';dirty-' + lang;
const csvRows = scsvLines
.filter((line, i) => i !== 0)
.map(line => parseScsvLine(line))
.filter(cells => cells.length === scsvHeader.length && cells[langPos])
.map(cells => encodeArrayAsCsvLine([cells[0], cells[1], cells[langPos], '0']))
.join('\r\n');
fs.writeFileSync(outPath, csvHeader + '\r\n' + csvRows, 'utf8');
}
if(process.argv.length >= 4){
main(process.argv[2], process.argv[3], process.argv[4]);
} else {
console.log('usage: node script.js <in csv> <locale>-<shopid> [out]');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment