1
0

command_runner.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. var exec = Npm.require('child_process').exec,
  2. execSync = function(cmd, options, stdoutHandler, stderrHandler, callback) {
  3. stdoutHandler('$ ' + cmd);
  4. exec(cmd,
  5. options,
  6. Meteor.bindEnvironment(
  7. function(error, stdout, stderr) {
  8. if( stdout !== '' ) {
  9. stdoutHandler(stdout);
  10. }
  11. if( stderr != '' ) {
  12. stderrHandler(stderr);
  13. }
  14. callback();
  15. }
  16. )
  17. );
  18. },
  19. replace = function(string, customs = {}) {
  20. var globals = {'%ROOT_CWD%': DEPLOYMENT_FOLDER};
  21. for(var key in globals) {
  22. string = string.replace(key, globals[key]);
  23. }
  24. for(var key in customs) {
  25. string = string.replace(key, customs[key]);
  26. }
  27. return string;
  28. };
  29. CommandRunner = {
  30. run: function( data, callback = undefined) {
  31. var bundle = _.extend({deployment: {}, project:{}, stdout: console.log, stderr: console.error, counter: 0, deploy_script: true}, data),
  32. customs = {'%CWD%': bundle.project._id, '%GIT%': bundle.project.git_url};
  33. var line = bundle.script[bundle.counter],
  34. command = replace(line.cmd, customs ),
  35. options = line.options;
  36. options.cwd = replace(options.cwd, customs);
  37. execSync(command, options, bundle.stdout, bundle.stderr, function() {
  38. bundle.counter++;
  39. if( bundle.counter >= bundle.script.length ) {
  40. if( bundle.deploy_script && bundle.project.commands ) {
  41. bundle.deploy_script = false;
  42. bundle.script = bundle.project.commands.split('\n');
  43. bundle.counter = 0;
  44. CommandRunner.commands(bundle, callback);
  45. } else if( callback ) {
  46. if( bundle.deployment ) {
  47. DeploymentService.update_status(bundle.deployment._id, 'closed', callback);
  48. } else {
  49. callback();
  50. }
  51. }
  52. } else {
  53. CommandRunner.run(bundle, callback);
  54. }
  55. });
  56. },
  57. commands: function(bundle, callback = undefined) {
  58. var command = bundle.script[bundle.counter],
  59. customs = {'%CWD%': bundle.project._id},
  60. options = {
  61. cwd: replace('%ROOT_CWD%/%CWD%', customs)
  62. };
  63. execSync(command, options, bundle.stdout, bundle.stderr, function() {
  64. bundle.counter++;
  65. if( bundle.counter >= bundle.script.length ) {
  66. if( bundle.deployment ) {
  67. DeploymentService.update_status(bundle.deployment._id, 'closed', callback);
  68. } else {
  69. callback();
  70. }
  71. } else {
  72. CommandRunner.commands(bundle, callback);
  73. }
  74. });
  75. }
  76. }