Skip to content

Instantly share code, notes, and snippets.

@RomkeVdMeulen
Last active October 12, 2016 10:43
Show Gist options
  • Save RomkeVdMeulen/fee35daf1bad6ac8589188da636b4a03 to your computer and use it in GitHub Desktop.
Save RomkeVdMeulen/fee35daf1bad6ac8589188da636b4a03 to your computer and use it in GitHub Desktop.
Collect text usage during build step
var es = require('event-stream');
var fs = require('fs');
var mkdirp = Promise.denodeify(require('mkdirp'));
var path = require('path');
var plumber = require('gulp-plumber');
var Promise = require('promise');
var ts = require('typescript');
var typescript = require('gulp-typescript');
var paths = {
source: "../src",
output: "../dist",
textkeys: "../build/META-INF/frontend-textkeys.conf"
};
var typescriptCompiler = typescriptCompiler || null;
gulp.task('build-typescript', function() {
if (!typescriptCompiler) {
typescriptCompiler = typescript.createProject('tsconfig.json', {
typescript: ts
});
}
return gulp.src(paths.source)
.pipe(plumber())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(collectTextUsage())
.pipe(typescript(typescriptCompiler))
.pipe(sourcemaps.write({includeContent: true}))
.pipe(gulp.dest(paths.output));
});
function collectTextUsage() {
var textkeys = new Set();
return es.through(function(file) {
this.emit('data', file);
var fileSource = file.contents.toString();
var fileNode = ts.createSourceFile(file.path, fileSource, ts.ScriptTarget.ES5, false);
function extractTextKeys(node) {
if (node.kind === ts.SyntaxKind.StringLiteral) {
textkeys.add(node.text);
}
ts.forEachChild(node, extractTextKeys);
}
function checkNode(node) {
if (node.kind === ts.SyntaxKind.Decorator) {
var code = fileSource.substring(node.pos, node.end).trim();
if (code.match(/^@text(Promise)?\(/)) {
extractTextKeys(node);
}
} else {
ts.forEachChild(node, checkNode);
}
}
checkNode(fileNode);
}, function() {
var textArray = Array.from(textkeys.values());
textArray.sort();
mkdirp(path.dirname(paths.textkeys), function() {
var fileHandle = fs.openSync(paths.textkeys, "w");
fs.writeSync(fileHandle, textArray.join("\n"));
fs.closeSync(fileHandle);
this.emit('end');
}.bind(this));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment