Skip to content

Instantly share code, notes, and snippets.

@dipernaa
Last active September 9, 2016 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dipernaa/70c416abd8cf6d607efcb9c85f229794 to your computer and use it in GitHub Desktop.
Save dipernaa/70c416abd8cf6d607efcb9c85f229794 to your computer and use it in GitHub Desktop.
Create C# files from xsd files in a directory
var promise = require('bluebird');
var fs = promise.promisifyAll(require('fs'));
var exec = require('child_process').exec;
var commands = [];
var baseDirectory;
var outputDirectory;
if (process.argv.length < 4) {
console.log('Please enter the two commands required.');
console.log('1 - base directory of XSDs');
console.log('2 - output directory of C# files');
} else {
baseDirectory = process.argv[2];
outputDirectory = process.argv[3];
findXSDs(baseDirectory).then(function() {
var failedCount = 0;
var finalPromise = commands.reduce(function(execPromise, line) {
return execPromise.catch(function() {
failedCount++;
}).finally(function() {
return new promise(function(resolve, reject) {
exec(line, function(err, stdout, stderr) {
var tempDirectory = line.substring(line.indexOf(baseDirectory));
var directory = tempDirectory.substring(0, tempDirectory.indexOf(' &&'));
var tempFile = line.substring(0, line.indexOf('.xsd') + 4);
var file = tempFile.substring(tempFile.lastIndexOf(' ') + 1);
console.log('File path: ' + directory + file);
if (stderr) {
console.log(stderr);
reject();
} else {
console.log(stdout);
resolve();
}
});
});
});
}, promise.resolve());
finalPromise.catch(function() {
failedCount++;
}).finally(function() {
console.log('Done. Number of failures: ' + failedCount);
});
});
}
function buildCommand(directory, fileName) {
return fs.readFileAsync(directory + fileName, 'utf8').then(function(data) {
var imports = data.split('\n').filter(function(line) {
return line.indexOf('xsd:import') > -1;
}).map(function(line) {
var tempLine = line.substring(line.search(/schemaLocation="/));
var start = tempLine.indexOf('"') + 1;
var end = tempLine.indexOf('"', start);
return tempLine.substring(start, end);
});
var joinedImports = '';
if (imports && imports.length > 0) {
joinedImports = imports.join(' ');
}
commands.push('cd ' + directory + ' && xsd ' + fileName + ' ' + joinedImports + ' /c /O:' + outputDirectory);
});
}
function findXSDs(currentPath) {
return fs.readdirAsync(currentPath).then(function(files) {
if (files) {
return promise.all(files.map(function(file) {
if (file.endsWith('.xsd')) {
return buildCommand(currentPath + '/', file);
} else {
return fs.statAsync(currentPath + '/' + file).then(function(stats) {
if (stats.isDirectory()) {
return findXSDs(currentPath + '/' + file);
}
});
}
}));
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment