<commit_before>/*
 * grunt-enspire
 * https://github.com/jasonfutch/grunt-enspire
 *
 * Copyright (c) 2015 jasonfutch
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('enspire', 'A plugin for specific use with in Enspire Commerce.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      punctuation: '.',
      separator: ', '
    });

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      // Concat specified files.
      var src = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        return grunt.file.read(filepath);
      }).join(grunt.util.normalizelf(options.separator));

      // Handle options.
      src += options.punctuation;

      // Write the destination file.
      grunt.file.write(f.dest, src);

      // Print a success message.
      grunt.log.writeln('File "' + f.dest + '" created.');
    });
  });

};
<commit_msg>initial scaffolding<commit_after>/*
 * grunt-enspire
 * https://github.com/jasonfutch/grunt-enspire
 *
 * Copyright (c) 2015 jasonfutch
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

    // Please see the Grunt documentation for more information regarding task
    // creation: http://gruntjs.com/creating-tasks

    grunt.registerTask('enspire','A plugin for specific use within Enspire Commerce.', function(arg1, arg2) {

        // Holds platform.json config
        var objPlatform;

        // Holds required dependencies
        var required = {
            modules:[],
            views:[],
            bower:[]
        };

        if(grunt.option('commands')){
            grunt.log.writeln('\nOptions:');
            grunt.log.writeln('\t--init \t\t\t Creates an empty platform.json file');
            grunt.log.writeln('\t--init-force \t\t Overwrites platform.json with an empty file');
            grunt.log.writeln('\t--init-bower \t\t Creates a default .browerrc file');
            grunt.log.writeln('\t--init-bower-force \t Overwrites a .browerrc with a default file');
            grunt.log.writeln('\t--theme \t\t Defines the theme to use, instead of the one defined in platform.json');
            return true;
        }

        //Create platform.json
        if(grunt.option('init') || grunt.option('init-force')){
            if(grunt.file.exists('platform.json') && !grunt.option('init-force')){
                grunt.log.error('"platform.json" already exists, to overwrite run "grunt enspire --init-force" command');
                return false;
            }
            grunt.file.write('platform.json','{\n\t"theme":"",\n\t"modules":[],\n\t"views":[],\n\t"includes":{\n\t\t"js":[],\n\t\t"css":[],\n\t\t"scss":[]\n\t}\n}');
            return true;
        }

        //Create .bowerrc
        if(grunt.option('init') || grunt.option('init-bower')){
            if(grunt.file.exists('.bowerrc') && !grunt.option('init-bower-force')){
                grunt.log.error('".bowerrc" already exists, to overwrite run "grunt enspire --init-bower-force" command');
                return false;
            }
            grunt.file.write('.bowerrc','{\n\t"directory":"bower_components",\n\t"json":"bower.json"\n}');
            return true;
        }

        if(!grunt.file.exists('platform.json')){
            grunt.log.error('"platform.json" is a required file and must be in the root directory. To create an empty one run "grunt enspire --init" command');
            return false;
        }

        objPlatform = grunt.file.readJSON('platform.json');

        if(objPlatform.bower_directory===undefined){
            if(!grunt.file.exists('.bowerrc')){
                grunt.log.error('".bowerrc" file is a required if bower_directory is not defined in "platform.json". To create a default one run "grunt enspire --init-bower" command');
                return false;
            }

            var bowerrc = grunt.file.readJSON('.bowerrc');
            objPlatform.bower_directory = bowerrc.directory;
        }

        if(!grunt.file.exists(objPlatform.bower_directory)){
            grunt.log.error('"'+objPlatform.bower_directory+'" directory was not found, try running "bower install" command.');
            return false;
        }

        if(!grunt.file.exists(objPlatform.bower_directory+'/enspire.platform/')){
            grunt.log.error('"enspire.platform" folder was not found in your '+objPlatform.bower_directory+' directory.');
            return false;
        }

        if(!grunt.file.exists(objPlatform.bower_directory+'/enspire.ui/')){
            grunt.log.error('"enspire.ui" folder was not found in your '+objPlatform.bower_directory+' directory.');
            return false;
        }

        if(grunt.option('theme')!==undefined){
            if(grunt.option('theme')===0){
                grunt.log.error('"--themes" option can not be blank, it must have a value. ex: "--theme=myThemeName"');
                return false;
            }
            if(grunt.option('theme')===0 || grunt.option('theme')===true){
                grunt.log.error('"--themes" must have a value defined. ex: "--theme=myThemeName"');
                return false;
            }
            objPlatform.theme = grunt.option('theme');
        }

        if(objPlatform.theme===undefined || objPlatform.theme===''){
            if(objPlatform.theme===undefined) grunt.log.warn('"theme" is undefined in the "platform.json" file');
            if(objPlatform.theme==='') grunt.log.warn('"theme" is blank in the "platform.json" file');
        }else{
            if(!grunt.file.exists(objPlatform.bower_directory+'/enspire.platform/themes/')){
                grunt.log.error('"themes" folder is missing from "'+objPlatform.bower_directory+'/enspire.platform" directory.');
                return false;
            }

            if(!grunt.file.exists(objPlatform.bower_directory+'/enspire.platform/themes/'+objPlatform.theme+'/')){
                grunt.log.error('"'+objPlatform.theme+'" theme does not exist in "'+objPlatform.bower_directory+'/enspire.platform/themes/" directory.');
                return false;
            }
        }

        if(objPlatform.modules!==undefined){
            if(!Array.isArray(objPlatform.modules)){
                grunt.log.error('"modules" must be an array in the "platform.json" file');
                return false;
            }

            var folderModules = objPlatform.bower_directory+'/enspire.platform/modules/';
            if(!grunt.file.exists(folderModules)){
                grunt.log.error('"modules" folder is missing from "'+folderModules+'" directory.');
                return false;
            }

            var lngModules = objPlatform.modules.length;
            for(var i=0;i<lngModules;i++){
                var moduleName = objPlatform.modules[i];
                var moduleFolder = folderModules+moduleName+'/';

                if(moduleName===''){
                    grunt.log.error('"'+moduleName+'" module does not exist in "'+folderModules+'" directory. Please remove the empty string from your array in "modules" property of your "plaform.json" file.');
                    return false;
                }

                if(!grunt.file.exists(moduleFolder)){
                    grunt.log.error('"'+moduleName+'" module does not exist in "'+folderModules+'" directory.');
                    return false;
                }else{
                    var moduleConfig = moduleFolder+'.enspirerc';
                    if(grunt.file.exists(moduleConfig)){
                        var objModuleConfig = grunt.file.readJSON(moduleConfig);

                        if(objModuleConfig.dependencies!==undefined){
                            if(objModuleConfig.dependencies.modules!==undefined){
                                if(!Array.isArray(objModuleConfig.dependencies.modules)){
                                    grunt.log.error('"'+moduleConfig+'" dependencies.module property must be in an array format.');
                                    return false;
                                }

                                var lngModulesDependencyModules = objModuleConfig.dependencies.modules.length;
                                for(var x=0; x<lngModulesDependencyModules; x++){
                                    var ModulesDependencyModule = objModuleConfig.dependencies.modules[x];
                                    if(required.modules.indexOf(ModulesDependencyModule) == -1 && objPlatform.modules.indexOf(ModulesDependencyModule) == -1){
                                        required.modules.push(ModulesDependencyModule);
                                    }
                                }
                            }
                            console.log(required.modules);
                        }
                    }
                }
            }
        }

        if(objPlatform.views!==undefined){
            if(!Array.isArray(objPlatform.views)){
                grunt.log.error('"views" must be an array in the "platform.json" file');
                return false;
            }

            if(!grunt.file.exists(objPlatform.bower_directory+'/enspire.platform/views/')){
                grunt.log.error('"views" folder is missing from "'+objPlatform.bower_directory+'/enspire.platform" directory.');
                return false;
            }

            var lngViews = objPlatform.views.length;
            for(var i=0;i<lngViews;i++){
                var aryFiles = grunt.file.expand({cwd:objPlatform.bower_directory+'/enspire.platform/views/'},objPlatform.views[i]);
                if(aryFiles.length===0){
                    grunt.log.warn('"'+objPlatform.views[i]+'" does not return any files from the "'+objPlatform.bower_directory+'/enspire.platform/views/" directory.');
                }
            }
        }

        if(objPlatform.includes!==undefined){
            if(objPlatform.includes.js!==undefined){
                var lngJS = objPlatform.includes.js.length;
                for(var i=0;i<lngJS;i++){
                    var aryFiles = grunt.file.expand(objPlatform.includes.js[i]);
                    if(aryFiles.length===0){
                        grunt.log.warn('"'+objPlatform.includes.js[i]+'" does not return any files.');
                    }else{
                        var hasJS = false;
                        for(var x=0;x<aryFiles.length;x++){
                            if(aryFiles[x].indexOf('.js', aryFiles[x].length - 3) !== -1) hasJS = true;
                        }
                        if(hasJS===false){
                            grunt.log.warn('"'+objPlatform.includes.js[i]+'" does not return any *.js files.');
                        }
                    }
                }
            }

            if(objPlatform.includes.css!==undefined){
                var lngCSS = objPlatform.includes.css.length;
                for(var i=0;i<lngCSS;i++){
                    var aryFiles = grunt.file.expand(objPlatform.includes.css[i]);
                    if(aryFiles.length===0){
                        grunt.log.warn('"'+objPlatform.includes.css[i]+'" does not return any files.');
                    }else{
                        var hasCSS = false;
                        for(var x=0;x<aryFiles.length;x++){
                            if(aryFiles[x].indexOf('.css', aryFiles[x].length - 4) !== -1) hasCSS = true;
                        }
                        if(hasCSS===false){
                            grunt.log.warn('"'+objPlatform.includes.css[i]+'" does not return any *.css files.');
                        }
                    }
                }
            }

            if(objPlatform.includes.scss!==undefined){
                var lngSCSS = objPlatform.includes.scss.length;
                for(var i=0;i<lngSCSS;i++){
                    var aryFiles = grunt.file.expand(objPlatform.includes.scss[i]);
                    if(aryFiles.length===0){
                        grunt.log.warn('"'+objPlatform.includes.scss[i]+'" does not return any files.');
                    }else{
                        var hasSCSS = false;
                        for(var x=0;x<aryFiles.length;x++){
                            if(aryFiles[x].indexOf('.scss', aryFiles[x].length - 5) !== -1) hasSCSS = true;
                            if(aryFiles[x].indexOf('.sass', aryFiles[x].length - 5) !== -1) hasSCSS = true;
                        }
                        if(hasSCSS===false){
                            grunt.log.warn('"'+objPlatform.includes.scss[i]+'" does not return any *.scss or *.sass files.');
                        }
                    }
                }
            }
        }

        if(!grunt.file.exists('src')){
            grunt.log.error('"src" folder is missing from root directory, try running "yo enspire" to setup scaffolding.');
            return false;
        }

        if(!grunt.file.exists('src/js')){
            grunt.log.error('"js" folder was not found in your "src" directory.');
        }
        if(!grunt.file.exists('src/styles')){
            grunt.log.error('"styles" folder was not found in your "src" directory.');
        }
        if(!grunt.file.exists('src/views')){
            grunt.log.error('"views" folder was not found in your "src" directory.');
        }

        if(!grunt.file.exists('src/index.html')){
            grunt.log.error('"index.html" missing from your "src" directory.');
            return false;
        }

        var js = [];
        var css = [];
        var scss = [];

    });

    //grunt.registerMultiTask('enspire', 'A plugin for specific use with in Enspire Commerce.', function() {
    //  // Merge task-specific and/or target-specific options with these defaults.
    //  var options = this.options({
    //    punctuation: '.',
    //    separator: ', '
    //  });
    //
    //  // Iterate over all specified file groups.
    //  this.files.forEach(function(f) {
    //    // Concat specified files.
    //    var src = f.src.filter(function(filepath) {
    //      // Warn on and remove invalid source files (if nonull was set).
    //      if (!grunt.file.exists(filepath)) {
    //        grunt.log.warn('Source file "' + filepath + '" not found.');
    //        return false;
    //      } else {
    //        return true;
    //      }
    //    }).map(function(filepath) {
    //      // Read file source.
    //      return grunt.file.read(filepath);
    //    }).join(grunt.util.normalizelf(options.separator));
    //
    //    // Handle options.
    //    src += options.punctuation;
    //
    //    // Write the destination file.
    //    grunt.file.write(f.dest, src);
    //
    //    // Print a success message.
    //    grunt.log.writeln('File "' + f.dest + '" created.');
    //  });
    //});

};
<|endoftext|>


<commit_before>/*
 * grunt-hashmap
 * https://github.com/ktmud/grunt-hashmap
 *
 * Copyright (c) 2013 ktmud
 * Licensed under the MIT license.
 */
'use strict';

var crypto = require('crypto');
var path = require('path');
var fs = require('fs');
var defaultOutput = '#{= dest}/hash.json';
var defaultEtag = '#{= blksize}-#{= +mtime}';
var defaultRename = '#{= dirname}/#{= basename}_#{= hash}#{= extname}';

//var defaultEtag = '#{size}-#{+mtime}';
//var defaultRename = '#{dirname}/#{basename}_#{hash}#{extname}';

module.exports.defaultEtag = defaultEtag;

module.exports = function(grunt) {

  grunt.registerMultiTask('hashmap', 'Your task description goes here.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      output: defaultOutput,
      merge: false,
      encoding: null, // encoding of file contents
      etag: null,
      algorithm: 'md5', // the algorithm to create the hash
      rename: defaultRename, // save the original file as what
      keep: true, // should we keep the original file or not
      hashlen: 10, // length for hashsum digest
    });

    grunt.template.addDelimiters('#{ }', '#{', '}');

    var tmpl_option = {
      delimiters: '#{ }',
    };

    var encoding = options.encoding;
    var rename_format = (typeof options.rename === 'string') ? options.rename : defaultRename;

    var done = this.async();

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      var cwd = f.cwd;
      var dest = f.dest;

      // Concat specified files.
      var src = f.src.filter(function(filepath) {
        filepath = realpath(filepath);
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else if (grunt.file.isFile(filepath)) {
          return true;
        }
      });
      var mapping = {};

      if (grunt.file.isFile(dest)) {
        grunt.log.warn('Destination must be a directory.');
      }

      src.forEach(function(filepath) {
        var r = realpath(filepath), d;

        if (options.etag) {
          fs.stat(r, function(err, stats) {
            if (err) {
              grunt.log.error('Stats for "' + filepath + '" failed.');
            }
            var etag = (typeof options.etag === 'string') ? options.etag : defaultEtag;
            tmpl_option['data'] = stats;
            d = grunt.template.process(etag, tmpl_option);
            stash(filepath, d);
          });
        } else {
          var s = fs.ReadStream(r);
          //var contents = grunt.file.read(r, { encoding: null });
          var shasum = crypto.createHash(options.algorithm);
          s.on('data', function(data) {
            if (encoding) {
              data = data.toString(encoding);
            }
            shasum.update(data);
          });
          s.on('end', function() {
            d = shasum.digest('hex').slice(0, options.hashlen);
            stash(filepath, d);
          });
        }
      });

      function stash(filepath, d) {
        mapping[filepath] = d;

        grunt.verbose.writeln(
          (options.etag ? 'Etag' : 'Hash') + ' for ' + filepath + ': ' + d);

        dest && save(filepath);

        if (Object.keys(mapping).length === src.length) {
          output();
        }
      }

      function realpath(filepath) {
        return cwd ? path.join(cwd, filepath) : filepath;
      }
      function renamed(filepath) {
        if (rename_format) {
          var hash = mapping[filepath];
          var extname = path.extname(filepath);
          tmpl_option['data'] = {
            dest: dest,
            cwd: cwd,
            hash: hash,
            extname: extname,
            dirname: path.dirname(filepath),
            basename: path.basename(filepath, extname),
          };
          filepath = grunt.template.process(rename_format, tmpl_option);
        }
        return filepath;
      }

      function save(filepath) {
        var srcfile = realpath(filepath);
        var destfile = path.join(dest, renamed(filepath));
        if (srcfile !== destfile) {
          if (destfile.indexOf(dest) === -1) {
            grunt.log.warn('Renamed target "' + destfile + '" is not in dest directory.');
          }
          grunt.file.copy(srcfile, destfile);
          grunt.log.oklns('"' + srcfile + '" => "' + destfile + '"');
          if (!options.keep) {
            grunt.verbose.writeln('Deleting source "' + srcfile + '"..');
            grunt.file.delete(srcfile);
          }
        }
      }

      function output() {
        grunt.log.oklns('All hashed.');
        if (options.output) {
          tmpl_option['data'] = { cwd: cwd || '', dest: dest };

          var jsonfile = typeof options.output === 'string' ? options.output : defaultOutput;
          jsonfile = grunt.template.process(jsonfile, tmpl_option);
          if (options.merge && grunt.file.exists(jsonfile)) {
            var old = grunt.file.readJSON(jsonfile);
            if (typeof old === 'object') {
              for (var k in old) {
                if (!(k in mapping)) {
                  mapping[k] = old[k];
                }
              }
            }
          }
          grunt.file.write(jsonfile, JSON.stringify(mapping));
          grunt.log.oklns('Hashmap "' + jsonfile + '" saved.');
        }
        done();
      }
    });
  });

};
<commit_msg>fix async<commit_after>/*
 * grunt-hashmap
 * https://github.com/ktmud/grunt-hashmap
 *
 * Copyright (c) 2013 ktmud
 * Licensed under the MIT license.
 */
'use strict';

var crypto = require('crypto');
var path = require('path');
var fs = require('fs');
var defaultOutput = '#{= dest}/hash.json';
var defaultEtag = '#{= blksize}-#{= +mtime}';
var defaultRename = '#{= dirname}/#{= basename}_#{= hash}#{= extname}';

//var defaultEtag = '#{size}-#{+mtime}';
//var defaultRename = '#{dirname}/#{basename}_#{hash}#{extname}';

module.exports.defaultEtag = defaultEtag;

module.exports = function(grunt) {

  grunt.registerMultiTask('hashmap', 'Your task description goes here.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      output: defaultOutput,
      merge: false,
      encoding: null, // encoding of file contents
      etag: null,
      algorithm: 'md5', // the algorithm to create the hash
      rename: defaultRename, // save the original file as what
      keep: true, // should we keep the original file or not
      hashlen: 10, // length for hashsum digest
    });

    grunt.template.addDelimiters('#{ }', '#{', '}');

    var tmpl_option = {
      delimiters: '#{ }',
    };

    var encoding = options.encoding;
    var rename_format = (typeof options.rename === 'string') ? options.rename : defaultRename;

    var done = this.async();

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      var cwd = f.cwd;
      var dest = f.dest;

      // Concat specified files.
      var src = f.src.filter(function(filepath) {
        filepath = realpath(filepath);
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else if (grunt.file.isFile(filepath)) {
          return true;
        }
      });
      var mapping = {};

      if (!src.length) {
        grunt.log.writeln('No source file..');
        done();
        return;
      }

      if (grunt.file.isFile(dest)) {
        grunt.log.warn('Destination must be a directory.');
      }

      src.forEach(function(filepath) {
        var r = realpath(filepath), d;

        if (options.etag) {
          fs.stat(r, function(err, stats) {
            if (err) {
              grunt.log.error('Stats for "' + filepath + '" failed.');
            }
            var etag = (typeof options.etag === 'string') ? options.etag : defaultEtag;
            tmpl_option['data'] = stats;
            d = grunt.template.process(etag, tmpl_option);
            stash(filepath, d);
          });
        } else {
          var s = fs.ReadStream(r);
          //var contents = grunt.file.read(r, { encoding: null });
          var shasum = crypto.createHash(options.algorithm);
          s.on('data', function(data) {
            if (encoding) {
              data = data.toString(encoding);
            }
            shasum.update(data);
          });
          s.on('end', function() {
            d = shasum.digest('hex').slice(0, options.hashlen);
            stash(filepath, d);
          });
        }
      });

      function stash(filepath, d) {
        mapping[filepath] = d;

        grunt.verbose.writeln(
          (options.etag ? 'Etag' : 'Hash') + ' for ' + filepath + ': ' + d);

        dest && save(filepath);

        if (Object.keys(mapping).length === src.length) {
          output();
        }
      }

      function realpath(filepath) {
        return cwd ? path.join(cwd, filepath) : filepath;
      }
      function renamed(filepath) {
        if (rename_format) {
          var hash = mapping[filepath];
          var extname = path.extname(filepath);
          tmpl_option['data'] = {
            dest: dest,
            cwd: cwd,
            hash: hash,
            extname: extname,
            dirname: path.dirname(filepath),
            basename: path.basename(filepath, extname),
          };
          filepath = grunt.template.process(rename_format, tmpl_option);
        }
        return filepath;
      }

      function save(filepath) {
        var srcfile = realpath(filepath);
        var destfile = path.join(dest, renamed(filepath));
        if (srcfile !== destfile) {
          if (destfile.indexOf(dest) === -1) {
            grunt.log.warn('Renamed target "' + destfile + '" is not in dest directory.');
          }
          grunt.file.copy(srcfile, destfile);
          grunt.log.oklns('"' + srcfile + '" => "' + destfile + '"');
          if (!options.keep) {
            grunt.verbose.writeln('Deleting source "' + srcfile + '"..');
            grunt.file.delete(srcfile);
          }
        }
      }

      function output() {
        grunt.log.oklns('All hashed.');
        if (options.output) {
          tmpl_option['data'] = { cwd: cwd || '', dest: dest };

          var jsonfile = typeof options.output === 'string' ? options.output : defaultOutput;
          jsonfile = grunt.template.process(jsonfile, tmpl_option);
          if (options.merge && grunt.file.exists(jsonfile)) {
            var old = grunt.file.readJSON(jsonfile);
            if (typeof old === 'object') {
              for (var k in old) {
                if (!(k in mapping)) {
                  mapping[k] = old[k];
                }
              }
            }
          }
          grunt.file.write(jsonfile, JSON.stringify(mapping));
          grunt.log.oklns('Hashmap "' + jsonfile + '" saved.');
        }
        done();
      }
    });
  });

};
<|endoftext|>


<commit_before>var request = require('request'),
    fs = require('fs'),
    _ = require('underscore'),
    q = require('q');
/*
 * grunt-jenkins
 * https://github.com/sghill/grunt-jenkins
 *
 * Copyright (c) 2012 sghill
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {

  grunt.config.requires('jenkins.serverAddress');

  var SERVER = grunt.config('jenkins.serverAddress');
  var PIPELINE_DIRECTORY = grunt.config('jenkins.pipelineDirectory') || 'pipeline';

  function logError(e) {
    grunt.log.error(e);
  }

  function isLast(item, collection) {
    return _.isEqual(item, _.last(collection));
  }

  function withDot(filename) {
    return (/\./).test(filename);
  }

  function loadJobsFromDisk() {
    var deferred = q.defer();
    fs.readdir(PIPELINE_DIRECTORY, function(e, contents) {
      if(e) { return deferred.reject(e); }
      // assumption: we don't have periods in our job names
      var directories = _.reject(contents, withDot);
      deferred.resolve(directories);
    });
    return deferred.promise;
  }

  function fetchJobConfigurationStrategy(job) {
    var deferred = q.defer();
    var url = [SERVER, 'job', job, 'config.xml'].join('/');
    request(url, function(e, r, b) {
      var strategy = r.statusCode === 200 ? 'update' : 'create';
      grunt.log.writeln(strategy + ': ' + job);
      deferred.resolve({strategy: strategy, jobName: job});
    });
    return deferred.promise;
  }

  function fetchFileContents(fileAndJob) {
    var deferred = q.defer();
    fs.readFile(fileAndJob.fileName, function(e, contents) {
      if(e) { return deferred.reject(e); }
      deferred.resolve({fileContents: contents, jobName: fileAndJob.jobName });
    });
    return deferred.promise;
  }

  function createJob (config) {
    var deferred = q.defer();
    var options = {
      url: [SERVER, 'createItem'].join('/'),
      method: 'POST',
      qs: {
        name: config.jobName
      },
      headers: {
        'Content-Type': 'text/xml'
      },
      body: config.fileContents
    };

    request(options, function(e, r, b) {
      if(e) { return deferred.reject(e); }
      deferred.resolve(r.statusCode === 200);
    });

    return deferred.promise;
  }

  function updateJob (config) {
    var deferred = q.defer(),
        options = {
      url: [SERVER, 'job', config.jobName, 'config.xml'].join('/'),
      method: 'POST',
      body: config.fileContents
    };

    request(options, function(e, r, b) {
      if(e) { return deferred.reject(e); }
      deferred.resolve(r.statusCode === 200);
    });

    return deferred.promise;
  }

  function applyStrategy (strategyObj) {
    var deferred = q.defer(),
        filename = [PIPELINE_DIRECTORY, strategyObj.jobName, 'config.xml'].join('/'),
        fileStrategy = {fileName: filename, jobName: strategyObj.jobName};

    function resolve (val) {
      deferred.resolve(val);
    }

    if(strategyObj.strategy === 'create') {
      fetchFileContents(fileStrategy).
        then(createJob).
        then(resolve);
    } else if (strategyObj.strategy === 'update') {
      fetchFileContents(fileStrategy).
        then(updateJob).
        then(resolve);
    }

    return deferred.promise;
  }

  function createOrUpdateJobs(directories) {
    var deferred = q.defer();

    function resolve (val) {
      deferred.resolve(val);
    }

    _.each(directories, function(folder) {
      fetchJobConfigurationStrategy(folder).
        then(applyStrategy).
        then(resolve);
    });

    return deferred.promise;
  }

  function loadPluginsFromDisk() {
    var deferred = q.defer();
    var filename = [PIPELINE_DIRECTORY, 'plugins.json'].join('/');
    fs.readFile(filename, function(e, contents) {
      if(e || _.isUndefined(contents)) { return deferred.reject(e); }
      deferred.resolve(JSON.parse(contents));
    });
    return deferred.promise;
  }

  function transformToJenkinsXml(plugins) {
    var attributes = _.map(plugins, function(p) {
      return ['<install plugin="', p.id, '@', p.version, '" />'].join('');
    }).join('\n');
    return ['<jenkins>', attributes, '</jenkins>'].join('\n');
  }

  function installPlugins(xml) {
    var deferred = q.defer(),
        options = {
          url: [SERVER, 'pluginManager', 'installNecessaryPlugins'].join('/'),
          method: 'POST',
          body: xml
        };

    request(options, function(e, r, b) {
      if(e) { return deferred.reject(e); }
      deferred.resolve(r.statusCode === 200);
    });

    return deferred.promise;
  }

  function fetchEnabledPluginsFromServer() {
    var url = [SERVER, 'pluginManager', 'api', 'json?depth=1'].join('/');
    var deferred = q.defer();

    request(url, function(e, r, body) {
      var result = _.filter(JSON.parse(body).plugins, function(p) { return p.enabled; });
      var plugins = _.map(result, function(p) { return { id: p.shortName, version: p.version }; });

      deferred.resolve(plugins);
    });

    return deferred.promise;
  }

  function ensureDirectoriesExist(directories) {
    _.each(directories, function(d, index) {
      var path = _.take(directories, (index + 1)).join('/');
      if(!fs.existsSync(path)) {
        fs.mkdirSync(path);
      }
    });
  }

  function writeFileToPipelineDirectory(plugins) {
    var deferred = q.defer();
    ensureDirectoriesExist([PIPELINE_DIRECTORY]);
    var filename = [PIPELINE_DIRECTORY, 'plugins.json'].join('/');
    var body = JSON.stringify(plugins, null, 2);
    fs.writeFile(filename, body, 'utf8', function(e) {
      if(e) { return deferred.reject(e); }

      grunt.log.ok('created file: ' + filename);
      deferred.resolve();
    });

    return deferred.promise;
  }

  function fetchJobsFromServer() {
    var deferred = q.defer();
    var url = [SERVER, 'api', 'json'].join('/');

    request(url, function(e, r, body) {
      if(e) { return deferred.reject(e); }
      var jobs = JSON.parse(body).jobs;
      deferred.resolve(_.map(jobs, function(j) { return { name: j.name, url: j.url }; }));
    });

    return deferred.promise;
  }

  function fetchJobConfigurations(jobs) {
    var deferred = q.defer();
    var jobConfigurations = [];
    var errors = [];
    var responseCodes = [];
    _.each(jobs, function(j) {
      request([j.url, 'config.xml'].join(''), function(e, r, body) {
        errors.push(e);
        responseCodes.push(r.statusCode);
        j.config = body;
        jobConfigurations.push(j);
        if(isLast(j, jobs)) {
          if(_.any(errors, function(e) { return e; }) ||
             _.any(responseCodes, function(c) { return c !== 200; })) {
            return deferred.reject();
          }
          deferred.resolve(jobConfigurations);
        }
      });
    });
    return deferred.promise;
  }

  function writeToJobDirectories(jobs) {
    var deferred = q.defer();
    _.each(jobs, function(j) {
      ensureDirectoriesExist([PIPELINE_DIRECTORY, j.name]);
      var filename = [PIPELINE_DIRECTORY, j.name, 'config.xml'].join('/');

      fs.writeFile(filename, j.config, 'utf8', function(e) {
        if(e) { return deferred.reject(e); }

        grunt.log.ok('created file: ' + filename);
        if(isLast(j, jobs)) {
          deferred.resolve(jobs);
        }
      });
    });
    return deferred.promise;
  }

  function compareToJobsOnDisk(serverJobsAndConfigurations) {
    var deferred = q.defer();
    loadJobsFromDisk().
      then(function(jobNames) {
        var serverJobNames = _.pluck(serverJobsAndConfigurations, 'name');
        if(!_.isEmpty(_.difference(serverJobNames, jobNames))) {
          grunt.log.error('Jobs mismatch.');
          return deferred.resolve(false);
        }
        var results = [];
        var errors = [];
        _.each(jobNames, function(name) {
          var filename = [PIPELINE_DIRECTORY, name, 'config.xml'].join('/');
          fs.readFile(filename, function(e, contents) {
            if(e) { errors.push(e); }
            var serverJob = _.find(serverJobsAndConfigurations, function(j) { return j.name === name; });
            if(serverJob) { //sometimes this comes back with nothing, figure out what the deal is
              results.push(serverJob.config === contents.toString());
              if(isLast(name, jobNames)) {
                var result = _.all(results, function(r) { return r; }) &&
                            !_.any(errors, function(e) { return e; });
                if(result) {
                  grunt.log.ok('All ' + jobNames.length + ' jobs verified!');
                } else {
                  grunt.log.error('Jobs configuration mismatch.');
                }
                deferred.resolve(result);
              }
            }
          })
        });
      });
    return deferred.promise;
  }

  function compareToPluginsOnDisk(serverPlugins) {
    var deferred = q.defer();
    loadPluginsFromDisk().
    then(function(onDiskPlugins) {
      var result = _.isEqual(serverPlugins, onDiskPlugins);
      if(result) {
        grunt.log.ok('All ' + serverPlugins.length + ' plugins verified!');
      } else {
        grunt.log.error('Plugins mismatched.');
      }
      deferred.resolve(result);
    }, logError);
    return deferred.promise;
  }

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerTask('jenkins-install', 'jenkins-install-jobs jenkins-install-plugins');
  grunt.registerTask('jenkins-backup', 'jenkins-backup-jobs jenkins-backup-plugins');
  grunt.registerTask('jenkins-list', 'jenkins-list-jobs jenkins-list-plugins');
  grunt.registerTask('jenkins-verify', 'jenkins-verify-jobs jenkins-verify-plugins');

  grunt.registerTask('jenkins-install-jobs', 'install all Jenkins jobs', function() {
    var done = this.async();
    loadJobsFromDisk().
      then(createOrUpdateJobs).
      then(function() { done(true); }, logError);
  });

  grunt.registerTask('jenkins-install-plugins', 'install all Jenkins plugins', function() {
    var done = this.async();
    loadPluginsFromDisk().
      then(transformToJenkinsXml).
      then(installPlugins).
      then(function() { done(true); }, logError);
  });

  grunt.registerTask('jenkins-backup-jobs', 'backup all Jenkins jobs', function() {
    var done = this.async();
    fetchJobsFromServer().
      then(fetchJobConfigurations).
      then(writeToJobDirectories).
      then(function() { done(true); }, logError);
  });

  grunt.registerTask('jenkins-backup-plugins', 'backup all enabled Jenkins plugins', function() {
    var done = this.async();
    fetchEnabledPluginsFromServer().
      then(writeFileToPipelineDirectory).
      then(function() { done(true); }, logError);
  });

  grunt.registerTask('jenkins-list-jobs', 'list all found Jenkins jobs', function() {
    var done = this.async();
    fetchJobsFromServer().
      then(function(jobs) {
        _.each(jobs, function(j) {
          grunt.log.writeln('job: ' + j.name + ' @ ' + j.url);
        });
      }).
      then(function() { done(true); }, logError);
  });

  grunt.registerTask('jenkins-list-plugins', 'list all enabled Jenkins plugins', function() {
    var done = this.async();
    fetchEnabledPluginsFromServer().
      then(function(plugins) {
        _.each(plugins, function(p) {
          grunt.log.writeln('plugin id: ' + p.id + ', version: ' + p.version);
        });
      }).
      then(function() { done(true); }, logError);
  });

  grunt.registerTask('jenkins-verify-jobs', 'verify job configurations in Jenkins match the on-disk versions', function() {
    var done = this.async();
    fetchJobsFromServer().
      then(fetchJobConfigurations).
      then(compareToJobsOnDisk).
      then(function(result) { done(result); }, logError);
  });

  grunt.registerTask('jenkins-verify-plugins', 'verify plugins in Jenkins match the on-disk versions', function() {
    var done = this.async();
    fetchEnabledPluginsFromServer().
      then(compareToPluginsOnDisk).
      then(function(result) { done(result); }, logError);
  });
};
<commit_msg>fail installing and verifying when files aren't present<commit_after>var request = require('request'),
    fs = require('fs'),
    _ = require('underscore'),
    q = require('q');
/*
 * grunt-jenkins
 * https://github.com/sghill/grunt-jenkins
 *
 * Copyright (c) 2012 sghill
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {

  grunt.config.requires('jenkins.serverAddress');

  var SERVER = grunt.config('jenkins.serverAddress');
  var PIPELINE_DIRECTORY = grunt.config('jenkins.pipelineDirectory') || 'pipeline';

  function logError(e) {
    grunt.log.error(e);
  }

  function isLast(item, collection) {
    return _.isEqual(item, _.last(collection));
  }

  function withDot(filename) {
    return (/\./).test(filename);
  }

  function loadJobsFromDisk() {
    var deferred = q.defer();
    fs.readdir(PIPELINE_DIRECTORY, function(e, contents) {
      if(e) { return deferred.reject(e); }
      // assumption: we don't have periods in our job names
      var directories = _.reject(contents, withDot);
      deferred.resolve(directories);
    });
    return deferred.promise;
  }

  function fetchJobConfigurationStrategy(job) {
    var deferred = q.defer();
    var url = [SERVER, 'job', job, 'config.xml'].join('/');
    request(url, function(e, r, b) {
      var strategy = r.statusCode === 200 ? 'update' : 'create';
      grunt.log.writeln(strategy + ': ' + job);
      deferred.resolve({strategy: strategy, jobName: job});
    });
    return deferred.promise;
  }

  function fetchFileContents(fileAndJob) {
    var deferred = q.defer();
    fs.readFile(fileAndJob.fileName, function(e, contents) {
      if(e) { return deferred.reject(e); }
      deferred.resolve({fileContents: contents, jobName: fileAndJob.jobName });
    });
    return deferred.promise;
  }

  function createJob (config) {
    var deferred = q.defer();
    var options = {
      url: [SERVER, 'createItem'].join('/'),
      method: 'POST',
      qs: {
        name: config.jobName
      },
      headers: {
        'Content-Type': 'text/xml'
      },
      body: config.fileContents
    };

    request(options, function(e, r, b) {
      if(e) { return deferred.reject(e); }
      deferred.resolve(r.statusCode === 200);
    });

    return deferred.promise;
  }

  function updateJob (config) {
    var deferred = q.defer(),
        options = {
      url: [SERVER, 'job', config.jobName, 'config.xml'].join('/'),
      method: 'POST',
      body: config.fileContents
    };

    request(options, function(e, r, b) {
      if(e) { return deferred.reject(e); }
      deferred.resolve(r.statusCode === 200);
    });

    return deferred.promise;
  }

  function applyStrategy (strategyObj) {
    var deferred = q.defer(),
        filename = [PIPELINE_DIRECTORY, strategyObj.jobName, 'config.xml'].join('/'),
        fileStrategy = {fileName: filename, jobName: strategyObj.jobName};

    function resolve (val) {
      deferred.resolve(val);
    }

    if(strategyObj.strategy === 'create') {
      fetchFileContents(fileStrategy).
        then(createJob).
        then(resolve);
    } else if (strategyObj.strategy === 'update') {
      fetchFileContents(fileStrategy).
        then(updateJob).
        then(resolve);
    }

    return deferred.promise;
  }

  function createOrUpdateJobs(directories) {
    var deferred = q.defer();

    function resolve (val) {
      deferred.resolve(val);
    }

    _.each(directories, function(folder) {
      fetchJobConfigurationStrategy(folder).
        then(applyStrategy).
        then(resolve);
    });

    return deferred.promise;
  }

  function loadPluginsFromDisk() {
    var deferred = q.defer();
    var filename = [PIPELINE_DIRECTORY, 'plugins.json'].join('/');
    fs.readFile(filename, function(e, contents) {
      if(e || _.isUndefined(contents)) { return deferred.reject(e); }
      deferred.resolve(JSON.parse(contents));
    });
    return deferred.promise;
  }

  function transformToJenkinsXml(plugins) {
    var attributes = _.map(plugins, function(p) {
      return ['<install plugin="', p.id, '@', p.version, '" />'].join('');
    }).join('\n');
    return ['<jenkins>', attributes, '</jenkins>'].join('\n');
  }

  function installPlugins(xml) {
    var deferred = q.defer(),
        options = {
          url: [SERVER, 'pluginManager', 'installNecessaryPlugins'].join('/'),
          method: 'POST',
          body: xml
        };

    request(options, function(e, r, b) {
      if(e) { return deferred.reject(e); }
      deferred.resolve(r.statusCode === 200);
    });

    return deferred.promise;
  }

  function fetchEnabledPluginsFromServer() {
    var url = [SERVER, 'pluginManager', 'api', 'json?depth=1'].join('/');
    var deferred = q.defer();

    request(url, function(e, r, body) {
      var result = _.filter(JSON.parse(body).plugins, function(p) { return p.enabled; });
      var plugins = _.map(result, function(p) { return { id: p.shortName, version: p.version }; });

      deferred.resolve(plugins);
    });

    return deferred.promise;
  }

  function ensureDirectoriesExist(directories) {
    _.each(directories, function(d, index) {
      var path = _.take(directories, (index + 1)).join('/');
      if(!fs.existsSync(path)) {
        fs.mkdirSync(path);
      }
    });
  }

  function writeFileToPipelineDirectory(plugins) {
    var deferred = q.defer();
    ensureDirectoriesExist([PIPELINE_DIRECTORY]);
    var filename = [PIPELINE_DIRECTORY, 'plugins.json'].join('/');
    var body = JSON.stringify(plugins, null, 2);
    fs.writeFile(filename, body, 'utf8', function(e) {
      if(e) { return deferred.reject(e); }

      grunt.log.ok('created file: ' + filename);
      deferred.resolve();
    });

    return deferred.promise;
  }

  function fetchJobsFromServer() {
    var deferred = q.defer();
    var url = [SERVER, 'api', 'json'].join('/');

    request(url, function(e, r, body) {
      if(e) { return deferred.reject(e); }
      var jobs = JSON.parse(body).jobs;
      deferred.resolve(_.map(jobs, function(j) { return { name: j.name, url: j.url }; }));
    });

    return deferred.promise;
  }

  function fetchJobConfigurations(jobs) {
    var deferred = q.defer();
    var jobConfigurations = [];
    var errors = [];
    var responseCodes = [];
    _.each(jobs, function(j) {
      request([j.url, 'config.xml'].join(''), function(e, r, body) {
        errors.push(e);
        responseCodes.push(r.statusCode);
        j.config = body;
        jobConfigurations.push(j);
        if(isLast(j, jobs)) {
          if(_.any(errors, function(e) { return e; }) ||
             _.any(responseCodes, function(c) { return c !== 200; })) {
            return deferred.reject();
          }
          deferred.resolve(jobConfigurations);
        }
      });
    });
    return deferred.promise;
  }

  function writeToJobDirectories(jobs) {
    var deferred = q.defer();
    _.each(jobs, function(j) {
      ensureDirectoriesExist([PIPELINE_DIRECTORY, j.name]);
      var filename = [PIPELINE_DIRECTORY, j.name, 'config.xml'].join('/');

      fs.writeFile(filename, j.config, 'utf8', function(e) {
        if(e) { return deferred.reject(e); }

        grunt.log.ok('created file: ' + filename);
        if(isLast(j, jobs)) {
          deferred.resolve(jobs);
        }
      });
    });
    return deferred.promise;
  }

  function compareToJobsOnDisk(serverJobsAndConfigurations) {
    var deferred = q.defer();
    loadJobsFromDisk().
      then(function(jobNames) {
        var serverJobNames = _.pluck(serverJobsAndConfigurations, 'name');
        if(!_.isEmpty(_.difference(serverJobNames, jobNames))) {
          grunt.log.error('Jobs mismatch.');
          return deferred.resolve(false);
        }
        var results = [];
        var errors = [];
        _.each(jobNames, function(name) {
          var filename = [PIPELINE_DIRECTORY, name, 'config.xml'].join('/');
          fs.readFile(filename, function(e, contents) {
            if(e) { errors.push(e); }
            var serverJob = _.find(serverJobsAndConfigurations, function(j) { return j.name === name; });
            if(serverJob) { //sometimes this comes back with nothing, figure out what the deal is
              results.push(serverJob.config === contents.toString());
              if(isLast(name, jobNames)) {
                var result = _.all(results, function(r) { return r; }) &&
                            !_.any(errors, function(e) { return e; });
                if(result) {
                  grunt.log.ok('All ' + jobNames.length + ' jobs verified!');
                } else {
                  grunt.log.error('Jobs configuration mismatch.');
                }
                deferred.resolve(result);
              }
            }
          })
        });
      }, logError);
    return deferred.promise;
  }

  function compareToPluginsOnDisk(serverPlugins) {
    var deferred = q.defer();
    loadPluginsFromDisk().
    then(function(onDiskPlugins) {
      var result = _.isEqual(serverPlugins, onDiskPlugins);
      if(result) {
        grunt.log.ok('All ' + serverPlugins.length + ' plugins verified!');
      } else {
        grunt.log.error('Plugins mismatched.');
      }
      deferred.resolve(result);
    }, logError);
    return deferred.promise;
  }

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerTask('jenkins-install', 'jenkins-install-jobs jenkins-install-plugins');
  grunt.registerTask('jenkins-backup', 'jenkins-backup-jobs jenkins-backup-plugins');
  grunt.registerTask('jenkins-list', 'jenkins-list-jobs jenkins-list-plugins');
  grunt.registerTask('jenkins-verify', 'jenkins-verify-jobs jenkins-verify-plugins');

  grunt.registerTask('jenkins-install-jobs', 'install all Jenkins jobs', function() {
    var done = this.async();
    loadJobsFromDisk().
      then(createOrUpdateJobs).
      then(function() { done(true); }, logError);
  });

  grunt.registerTask('jenkins-install-plugins', 'install all Jenkins plugins', function() {
    var done = this.async();
    loadPluginsFromDisk().
      then(transformToJenkinsXml).
      then(installPlugins).
      then(function() { done(true); }, logError);
  });

  grunt.registerTask('jenkins-backup-jobs', 'backup all Jenkins jobs', function() {
    var done = this.async();
    fetchJobsFromServer().
      then(fetchJobConfigurations).
      then(writeToJobDirectories).
      then(function() { done(true); }, logError);
  });

  grunt.registerTask('jenkins-backup-plugins', 'backup all enabled Jenkins plugins', function() {
    var done = this.async();
    fetchEnabledPluginsFromServer().
      then(writeFileToPipelineDirectory).
      then(function() { done(true); }, logError);
  });

  grunt.registerTask('jenkins-list-jobs', 'list all found Jenkins jobs', function() {
    var done = this.async();
    fetchJobsFromServer().
      then(function(jobs) {
        _.each(jobs, function(j) {
          grunt.log.writeln('job: ' + j.name + ' @ ' + j.url);
        });
      }).
      then(function() { done(true); }, logError);
  });

  grunt.registerTask('jenkins-list-plugins', 'list all enabled Jenkins plugins', function() {
    var done = this.async();
    fetchEnabledPluginsFromServer().
      then(function(plugins) {
        _.each(plugins, function(p) {
          grunt.log.writeln('plugin id: ' + p.id + ', version: ' + p.version);
        });
      }).
      then(function() { done(true); }, logError);
  });

  grunt.registerTask('jenkins-verify-jobs', 'verify job configurations in Jenkins match the on-disk versions', function() {
    var done = this.async();
    fetchJobsFromServer().
      then(fetchJobConfigurations).
      then(compareToJobsOnDisk).
      then(function(result) { done(result); }, logError);
  });

  grunt.registerTask('jenkins-verify-plugins', 'verify plugins in Jenkins match the on-disk versions', function() {
    var done = this.async();
    fetchEnabledPluginsFromServer().
      then(compareToPluginsOnDisk).
      then(function(result) { done(result); }, logError);
  });
};
<|endoftext|>


<commit_before>module.exports = function(grunt) {

    'use strict';

    var spawn = require('child_process').spawn,
        path = require('path'),
        async = require('async'),
        fs = require('fs');

    var _ = grunt.util._;

    var versions = {
        1.0: '1.0.3705',
        1.1: '1.1.4322',
        2.0: '2.0.50727',
        3.5: '3.5',
        4.0: '4.0.30319'
    };

    grunt.registerMultiTask('msbuild', 'Run MSBuild tasks', function() {

        var asyncCallback = this.async();

        var options = this.options({
            targets: ['Build'],
            buildParameters: {},
            failOnError: true,
            verbosity: 'normal',
            processor: '',
            nologo: true
        });

        if (!options.projectConfiguration) {
            options.projectConfiguration = 'Release';
        }

        grunt.verbose.writeln('Using Options: ' + JSON.stringify(options, null, 4).cyan);

        var projectFunctions = [];

        this.files.forEach(function(filePair) {
            filePair.src.forEach(function(src) {
                projectFunctions.push(function(cb) {
                    build(src, options, cb);
                });

                projectFunctions.push(function(cb) {
                    cb();
                });
            });
        });

        async.series(projectFunctions, function() {
            asyncCallback();
        });

    });

    function build(src, options, cb) {

        grunt.log.writeln('Building ' + src.cyan);

        var cmd = createCommand(options.version || null, options.processor);
        var args = createCommandArgs(src, options);

        grunt.verbose.writeln('Using cmd:', cmd);
        grunt.verbose.writeln('Using args:', args);

        if (!cmd) {
            return;
        }

        var cp = spawn(cmd, args, {
            stdio: 'inherit'
        });

        cp.on('close', function(code) {
            var success = code === 0;
            grunt.verbose.writeln('close received - code: ', success);

            if (code === 0) {
                grunt.log.writeln('Build complete ' + src.cyan);
                cb();
            } else {
                grunt.log.writeln(('MSBuild failed with code: ' + code).cyan + src);
                if (options.failOnError) {
                    grunt.warn('MSBuild exited with a failure code: ' + code);
                }
            }

        });

    }

    function createCommandArgs(src, options) {

        var args = [];

        var projectPath = path.normalize(path.resolve() + '/' + src);

        args.push(projectPath);

        args.push('/target:' + options.targets);
        args.push('/verbosity:' + options.verbosity);

        if (options.nologo) {
            args.push('/nologo');
        }

        if (options.maxCpuCount) {
            grunt.verbose.writeln('Using maxcpucount:', +options.maxCpuCount);
            args.push('/maxcpucount:' + options.maxCpuCount);
        }

        args.push('/property:Configuration=' + options.projectConfiguration);

        for (var buildArg in options.buildParameters) {
            args.push('/property:' + buildArg + '=' + options.buildParameters[buildArg]);
        }

        return args;
    }

    function createCommand(version, processor) {

        // temp mono xbuild usage for linux / osx - assumes xbuild is in the path, works on my machine...
        if (process.platform === 'linux' || process.platform === 'darwin') {
            return 'xbuild';
        }

        if (!version) {
            var msBuild12Path = 'C:\\Program Files (x86)\\MSBuild\\12.0\\Bin\\MSBuild.exe';
            if (fs.existsSync(msBuild12Path)) {
                grunt.log.writeln('MSBuild 12 available, using this');
                grunt.verbose.writeln('Using MSBuild at:', msBuild12Path.cyan);
                return msBuild12Path;
            }
        }

        processor = 'Framework' + (processor === 64 ? processor : '');

        var specificVersion = versions[version];

        if (!specificVersion) {
            grunt.fatal('Unrecognised .NET framework version "' + version + '"');
        }

        var buildExecutablePath = path.join(process.env.WINDIR, 'Microsoft.Net', processor, 'v' + specificVersion, 'MSBuild.exe');

        grunt.verbose.writeln('Using MSBuild at:' + buildExecutablePath.cyan);

        if (!fs.existsSync(buildExecutablePath)) {
            grunt.fatal('Unable to find MSBuild executable');
        }

        return path.normalize(buildExecutablePath);

    }

};
<commit_msg>Added fallback to version 4.0 if no version is specified and MSBuild 12 is not found<commit_after>module.exports = function(grunt) {

    'use strict';

    var spawn = require('child_process').spawn,
        path = require('path'),
        async = require('async'),
        fs = require('fs');

    var _ = grunt.util._;

    var versions = {
        1.0: '1.0.3705',
        1.1: '1.1.4322',
        2.0: '2.0.50727',
        3.5: '3.5',
        4.0: '4.0.30319'
    };

    grunt.registerMultiTask('msbuild', 'Run MSBuild tasks', function() {

        var asyncCallback = this.async();

        var options = this.options({
            targets: ['Build'],
            buildParameters: {},
            failOnError: true,
            verbosity: 'normal',
            processor: '',
            nologo: true
        });

        if (!options.projectConfiguration) {
            options.projectConfiguration = 'Release';
        }

        grunt.verbose.writeln('Using Options: ' + JSON.stringify(options, null, 4).cyan);

        var projectFunctions = [];

        this.files.forEach(function(filePair) {
            filePair.src.forEach(function(src) {
                projectFunctions.push(function(cb) {
                    build(src, options, cb);
                });

                projectFunctions.push(function(cb) {
                    cb();
                });
            });
        });

        async.series(projectFunctions, function() {
            asyncCallback();
        });

    });

    function build(src, options, cb) {

        grunt.log.writeln('Building ' + src.cyan);

        var cmd = createCommand(options.version || null, options.processor);
        var args = createCommandArgs(src, options);

        grunt.verbose.writeln('Using cmd:', cmd);
        grunt.verbose.writeln('Using args:', args);

        if (!cmd) {
            return;
        }

        var cp = spawn(cmd, args, {
            stdio: 'inherit'
        });

        cp.on('close', function(code) {
            var success = code === 0;
            grunt.verbose.writeln('close received - code: ', success);

            if (code === 0) {
                grunt.log.writeln('Build complete ' + src.cyan);
                cb();
            } else {
                grunt.log.writeln(('MSBuild failed with code: ' + code).cyan + src);
                if (options.failOnError) {
                    grunt.warn('MSBuild exited with a failure code: ' + code);
                }
            }

        });

    }

    function createCommandArgs(src, options) {

        var args = [];

        var projectPath = path.normalize(path.resolve() + '/' + src);

        args.push(projectPath);

        args.push('/target:' + options.targets);
        args.push('/verbosity:' + options.verbosity);

        if (options.nologo) {
            args.push('/nologo');
        }

        if (options.maxCpuCount) {
            grunt.verbose.writeln('Using maxcpucount:', +options.maxCpuCount);
            args.push('/maxcpucount:' + options.maxCpuCount);
        }

        args.push('/property:Configuration=' + options.projectConfiguration);

        for (var buildArg in options.buildParameters) {
            args.push('/property:' + buildArg + '=' + options.buildParameters[buildArg]);
        }

        return args;
    }

    function createCommand(version, processor) {

        // temp mono xbuild usage for linux / osx - assumes xbuild is in the path, works on my machine...
        if (process.platform === 'linux' || process.platform === 'darwin') {
            return 'xbuild';
        }

        console.log('version', version);

        if (!version) {
            var msBuild12Path = 'C:\\Program Files (x86)\\MSBuild\\12.0\\Bin\\MSBuild.exe';
            if (fs.existsSync(msBuild12Path)) {
                grunt.log.writeln('MSBuild 12 available, using this');
                grunt.verbose.writeln('Using MSBuild at:', msBuild12Path.cyan);
                return msBuild12Path;
            } else {
                // Fallback to version 4.0
                version = 4.0;
            }
        }

        processor = 'Framework' + (processor === 64 ? processor : '');

        var specificVersion = versions[version];

        if (!specificVersion) {
            grunt.fatal('Unrecognised .NET framework version "' + version + '"');
        }

        var buildExecutablePath = path.join(process.env.WINDIR, 'Microsoft.Net', processor, 'v' + specificVersion, 'MSBuild.exe');

        grunt.verbose.writeln('Using MSBuild at:' + buildExecutablePath.cyan);

        if (!fs.existsSync(buildExecutablePath)) {
            grunt.fatal('Unable to find MSBuild executable');
        }

        return path.normalize(buildExecutablePath);

    }

};
<|endoftext|>


<commit_before>/**
 * Created by anonymoussc on 11/03/15 15:03.
 */

'use strict';

// Load plugins
var gulp       = require('gulp'),
    rename     = require('gulp-rename'),
    del        = require('del'),
    template   = require('gulp-template'),
    moment     = require('moment'),
    S          = require('string'),
    argv       = require('yargs').argv,
    precompile = require('./precompile.js');

var config   = precompile.config,
    league   = precompile.league,
    composer = precompile.composer,
    laravel  = precompile.laravel,
    ngApps   = precompile.ngApps,
    ngApp    = precompile.ngApp;

var key = '', keyProtected = 'name', obj = '', countObj = '', count = 0;

var process = {
    generate: processGenerate
};

function processGenerate() {

    argv.generator = argv.g ? argv.g : argv.generator;

    if ((argv.generator === league.name) || (config.generator === league.name)) {
        if (((argv.generator === league.name) && (!config.generator)) || ((config.generator === league.name) && (!argv.generator))) {

            obj      = league;
            countObj = objSize(obj) - 1;

            preProcessFile(obj, countObj);
        }
    } else if ((argv.generator === composer.name) || (config.generator === composer.name)) {
        if (((argv.generator === composer.name) && (!config.generator)) || ((config.generator === composer.name) && (!argv.generator))) {

            obj      = composer;
            countObj = objSize(obj) - 1;

            preProcessFile(obj, countObj);

        }
    } else if ((argv.generator === laravel.name) || (config.generator === laravel.name)) {
        if (((argv.generator === laravel.name) && (!config.generator)) || ((config.generator === laravel.name) && (!argv.generator))) {

            if (argv.ngApps) {

                obj      = ngApps;
                countObj = objSize(obj) - 1;

                // preProcessFile(obj, countObj);

                for (key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        if ((typeof obj[key].src !== 'undefined') && (typeof obj[key].fileName !== 'undefined') && (typeof obj[key].dest !== 'undefined')) {

                            processFile(obj[key].src, obj[key].fileName, obj[key].dest);

                        }
                    }
                }
            } else if (argv.ngApp) {

                obj      = ngApp;
                countObj = objSize(obj) - 1;

                // preProcessFile(obj, countObj);

                for (key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        if ((typeof obj[key].src !== 'undefined') && (typeof obj[key].fileName !== 'undefined') && (typeof obj[key].dest !== 'undefined')) {

                            processFile(obj[key].src, obj[key].fileName, obj[key].dest);

                        }
                    }
                }
            }

            obj      = laravel;
            countObj = objSize(obj) - 1;

            preProcessFile(obj, countObj);

        }
    } else if ((argv.generator === ngApps.name) || (config.generator === ngApps.name)) {
        if (((argv.generator === ngApps.name) && (!config.generator)) || ((config.generator === ngApps.name) && (!argv.generator))) {

            obj      = ngApps;
            countObj = objSize(obj) - 1;

            preProcessFile(obj, countObj);

        }
    } else if ((argv.generator === ngApp.name) || (config.generator === ngApp.name)) {
        if (((argv.generator === ngApp.name) && (!config.generator)) || ((config.generator === ngApp.name) && (!argv.generator))) {

            obj      = ngApp;
            countObj = objSize(obj) - 1;

            preProcessFile(obj, countObj);

        }
    }
}

function processFile(src, fileName, dest) {

    var gulpDoing;

    //console.log('File src : ' + src);
    //console.log('File name : ' + fileName);
    //console.log('File dest : ' + dest);

    if (!fileName) {
        gulpDoing = gulp.src(src)
            .pipe(template(precompile.dataSrc))
            .pipe(gulp.dest(dest));

    } else {
        gulpDoing = gulp.src(src)
            .pipe(template(precompile.dataSrc))
            .pipe(rename(fileName))
            .pipe(gulp.dest(dest));
    }

    return gulpDoing;

}

function objSize(obj) {
    var count = 0;

    if (typeof obj === "object") {

        if (Object.keys) {
            count = Object.keys(obj).length;
        } else if (window._) {
            count = _.keys(obj).length;
        } else if (window.$) {
            count = $.map(obj, function() {
                return 1;
            }).length;
        } else {
            for (var key in obj) if (obj.hasOwnProperty(key)) count++;
        }

    }

    return count;
}

function preProcessFile(o, co) {
    for (key in o) {
        if (o.hasOwnProperty(key)) {
            if ((typeof o[key].src !== 'undefined') && (typeof o[key].fileName !== 'undefined') && (typeof o[key].dest !== 'undefined')) {
                if (co !== count) {
                    processFile(o[key].src, o[key].fileName, o[key].dest);
                } else {
                    return processFile(o[key].src, o[key].fileName, o[key].dest);
                }
            }

            count++;
        }
    }
}

module.exports = process;
<commit_msg>Update process.js<commit_after>/**
 * Created by anonymoussc on 11/03/15 15:03.
 */

'use strict';

// Load plugins
var gulp       = require('gulp'),
    rename     = require('gulp-rename'),
    del        = require('del'),
    template   = require('gulp-template'),
    moment     = require('moment'),
    S          = require('string'),
    argv       = require('yargs').argv,
    precompile = require('./precompile.js');

var config   = precompile.config,
    league   = precompile.league,
    composer = precompile.composer,
    laravel  = precompile.laravel,
    ngApps   = precompile.ngApps,
    ngApp    = precompile.ngApp;

var key = '', keyProtected = 'name', obj = '', countObj = '', count = 0;

var process = {
    generate: processGenerate
};

function processGenerate() {

    argv.generator = argv.g ? argv.g : argv.generator;

    if ((argv.generator === league.name) || (config.generator === league.name)) {
        if (((argv.generator === league.name) && (!config.generator)) || ((config.generator === league.name) && (!argv.generator))) {

            obj      = league;
            countObj = objSize(obj) - 1;

            preProcessFile(obj, countObj);
        }
    } else if ((argv.generator === composer.name) || (config.generator === composer.name)) {
        if (((argv.generator === composer.name) && (!config.generator)) || ((config.generator === composer.name) && (!argv.generator))) {

            obj      = composer;
            countObj = objSize(obj) - 1;

            preProcessFile(obj, countObj);

        }
    } else if ((argv.generator === laravel.name) || (config.generator === laravel.name)) {
        if (((argv.generator === laravel.name) && (!config.generator)) || ((config.generator === laravel.name) && (!argv.generator))) {

            if (argv.ngApps) {

                obj      = ngApps;
                countObj = objSize(obj) - 1;

                // preProcessFile(obj, countObj);

                for (key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        if ((typeof obj[key].src !== 'undefined') && (typeof obj[key].fileName !== 'undefined') && (typeof obj[key].dest !== 'undefined')) {

                            processFile(obj[key].src, obj[key].fileName, obj[key].dest);

                        }
                    }
                }
            } else if (argv.ngApp) {

                obj      = ngApp;
                countObj = objSize(obj) - 1;

                // preProcessFile(obj, countObj);

                for (key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        if ((typeof obj[key].src !== 'undefined') && (typeof obj[key].fileName !== 'undefined') && (typeof obj[key].dest !== 'undefined')) {

                            processFile(obj[key].src, obj[key].fileName, obj[key].dest);

                        }
                    }
                }
            }

            obj      = laravel;
            countObj = objSize(obj) - 1;

            preProcessFile(obj, countObj);

        }
    } else if ((argv.generator === ngApps.name) || (config.generator === ngApps.name)) {
        if (((argv.generator === ngApps.name) && (!config.generator)) || ((config.generator === ngApps.name) && (!argv.generator))) {

            obj      = ngApps;
            countObj = objSize(obj) - 1;

            preProcessFile(obj, countObj);

        }
    } else if ((argv.generator === ngApp.name) || (config.generator === ngApp.name)) {
        if (((argv.generator === ngApp.name) && (!config.generator)) || ((config.generator === ngApp.name) && (!argv.generator))) {

            obj      = ngApp;
            countObj = objSize(obj) - 1;

            preProcessFile(obj, countObj);

        }
    }
}

function processFile(src, fileName, dest) {

    var gulpDoing;

    //console.log('File src : ' + src);
    //console.log('File name : ' + fileName);
    //console.log('File dest : ' + dest);

    if (!fileName) {
        gulpDoing = gulp.src(src)
            .pipe(template(precompile.dataSrc))
            .pipe(gulp.dest(dest));

    } else {
        gulpDoing = gulp.src(src)
            .pipe(template(precompile.dataSrc))
            .pipe(rename(fileName))
            .pipe(gulp.dest(dest));
    }

    return gulpDoing;

}

function preProcessFile(o, co) {
    for (key in o) {
        if (o.hasOwnProperty(key)) {
            if ((typeof o[key].src !== 'undefined') && (typeof o[key].fileName !== 'undefined') && (typeof o[key].dest !== 'undefined')) {
                if (co !== count) {
                    processFile(o[key].src, o[key].fileName, o[key].dest);
                } else {
                    return processFile(o[key].src, o[key].fileName, o[key].dest);
                }
            }

            count++;
        }
    }
}

function objSize(obj) {

    var count = 0;

    if (typeof obj === "object") {

        if (Object.keys) {
            count = Object.keys(obj).length;
        } else if (window._) {
            count = _.keys(obj).length;
        } else if (window.$) {
            count = $.map(obj, function() {
                return 1;
            }).length;
        } else {
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    count++;
                }
            }
        }

    }

    return count;
}

module.exports = process;
<|endoftext|>


<commit_before>/*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://yuilibrary.com/license/
*/

var path = require('path'),
    fs = require('fs'),
    timethat = require('timethat'),
    cpr = require('cpr').cpr,
    crypto = require('crypto'),
    cssproc = require('cssproc'),
    rimraf = require('rimraf');

module.exports = function(grunt) {

    var VERSION = grunt.option('release-version') || '',
        BUILD = grunt.option('release-build'),
        start, startTime, head, sha;

    if (VERSION && (!BUILD || BUILD === 'git' || BUILD === 'sha')) {
        head = grunt.file.read('.git/HEAD').replace('ref: ', '').trim();
        if (head) {
            sha = grunt.file.read(path.join('.git/', head)).trim();
            if (sha) {
                sha = sha.substr(0, 7);
                grunt.log.warn('No --release-build passed, using sha: ' + sha);
                BUILD = sha;
                grunt.config.set('build', BUILD);
            }
        }
    }

    if (VERSION && VERSION !== '') {
        start = path.join(process.cwd(), 'release', VERSION);
        grunt.config.set('version', VERSION);
    }

    grunt.registerTask('release', 'Create a YUI Release', [
        'release-boot',
        'release-prebuild',
        'release-prep',
        'release-clean',
        'build',
        'dist',
        'cdn',
        'cdn-ssl',
        'release-validate',
        'release-zip',
        'release-finish'
    ]);
    grunt.registerTask('release-prebuild', 'Build and test before prep', [
        'build',
        'test'
    ]);

    grunt.registerTask('release-validate', 'Validate the release before zipping', function() {
        grunt.log.ok('Validating the Release files.');
        /*
            Only looks for common, predictable files to make sure the other
            tasks did their job.
        */
        var dirs = [
            'cdn',
            'cdn/build',
            'cdn/build/yui',
            'cdn/build/yui/yui-min.js',
            'cdn-ssl',
            'cdn-ssl/build',
            'cdn-ssl/build/yui',
            'cdn-ssl/build/yui/yui-min.js',
            'npm',
            'npm/package.json',
            'npm/index.js',
            'npm/debug.js',
            'dist',
            'dist/api',
            'dist/api/index.html',
            'dist/api/data.json',
            'dist/docs',
            'dist/docs/index.html',
            'dist/releasenotes',
            'dist/releasenotes/HISTORY.yui.md',
            'dist/tests',
            'dist/tests/yui/tests/unit/index.html',
            'dist/README.md',
            'dist/LICENSE.md'
        ],
        fail = function(file) {
            grunt.fail.fatal('Failed to find: ' + file);
        },
        base = path.join('release', VERSION);

        if (!grunt.file.exists(base)) {
            fail(base);
        } else {
            grunt.log.writeln('Found!: '.green + base.cyan);
        }

        dirs.forEach(function(d) {
            var file = path.join(base, d);
            if (!grunt.file.exists(file)) {
                fail(file);
            } else {
                grunt.log.writeln('Found!: '.green + file.cyan);
            }
        });

    });

    grunt.registerTask('release-zip', 'Zipping up', [
        'compress:dist',
        'compress:cdn',
        'compress:cdn-ssl',
        'release-md5'
    ]);

    grunt.registerTask('release-md5', 'Create MD5 for release file', function() {
        var done = this.async(),
            file = path.join(start, 'archives', 'yui_' + VERSION + '.zip'),
            md5File = file + '.MD5',
            shasum = crypto.createHash('md5'),
            s = fs.ReadStream(file),
            finish = function() {
                grunt.log.ok('Checking for release zips');
                var files = [
                    'akamai_' + VERSION + '.zip',
                    'akamaissl_' + VERSION + '.zip',
                    'yui_' + VERSION + '.zip',
                    'yui_' + VERSION + '.zip.MD5'
                ];
                files.forEach(function(f) {
                    var file = path.join('release', VERSION, 'archives', f);
                    if (grunt.file.exists(file)) {
                        grunt.log.writeln('Found!: '.green + ' ' + file.cyan);
                    } else {
                        grunt.fail.fatal('Failed to find: ' + file.red);
                    }
                });
                done();
            };

        s.on('data', function(d) { shasum.update(d); });
        s.on('end', function() {
            var md5 = shasum.digest('hex');
            grunt.log.ok('Setting MD5 for release to: ' + md5);
            grunt.log.writeln('');
            grunt.file.write(md5File, md5 + '\n');
            finish();
        });
    });

    grunt.registerTask('release-boot', 'Booting the YUI Release', function() {
        startTime = new Date();

        if (!VERSION) {
            grunt.fail.fatal('No version found, use --release-version=x.y.z');
        }

        if (!BUILD) {
            grunt.fail.fatal('No build number found, use --release-build=x.y.z');
        }

        grunt.log.ok('Preparing YUI release for ' + VERSION + ', building and testing raw');
    });

    grunt.registerTask('release-prep', 'Booting the YUI Release', function() {
        grunt.cli.options.release = true;
        grunt.log.ok('All tests passed, starting offical build now');
    });

    grunt.registerTask('release-finish', 'Complete the YUI Release', function() {
        var endTime = new Date();
        grunt.log.ok('YUI Release for ' + VERSION + ' completed in ' + timethat.calc(startTime, endTime));
    });

    grunt.registerTask('release-clean', 'Cleaning release', function() {
        grunt.log.write('Deleting release directory');
        var done = this.async();
        rimraf(start, function() {
            grunt.log.writeln('...OK');
            done();
        });
    });

    grunt.registerTask('cdn', 'Preparing CDN Release', function() {
        grunt.log.writeln('Preparing CDN Release');
        var done = this.async(),
            source = path.join(start, 'dist', 'build'),
            dest = path.join(start, 'cdn', 'build');

        grunt.log.write('Copying build');

        cpr(source, dest, function() {
            grunt.log.writeln('...OK');
            grunt.log.writeln('Processing CSS files');
            var count = 0,
                complete = 0;

            grunt.file.recurse(dest, function(file) {
                if (path.extname(file) === '.css') {
                    count++;
                    var str = grunt.file.read(file);
                    cssproc.parse({
                        root: path.join(dest, '../'),
                        path: file,
                        base: 'http:/'+'/yui.yahooapis.com/' + VERSION + '/'
                    }, str, function(err, data) {
                        if (str !== data) {
                            complete++;
                            grunt.file.write(file, data);
                        }
                    });
                }
            });

            grunt.log.writeln('Processed ' + complete + ' of ' + count + ' css files.');
            done();
        });

    });

    grunt.registerTask('cdn-ssl', 'Preparing CDN SSL Release', function() {
        grunt.log.writeln('Preparing CDN SSL Release');
        var done = this.async(),
            source = path.join(start, 'dist', 'build'),
            dest = path.join(start, 'cdn-ssl', 'build');

        grunt.log.write('Copying build');

        cpr(source, dest, function() {
            grunt.log.writeln('...OK');
            grunt.log.writeln('Processing CSS files');
            var count = 0,
                complete = 0;

            grunt.file.recurse(dest, function(file) {
                if (path.extname(file) === '.css') {
                    count++;
                    var str = grunt.file.read(file);
                    cssproc.parse({
                        root: path.join(dest, '../'),
                        path: file,
                        base: 'https:/'+'/yui-s.yahooapis.com/' + VERSION + '/'
                    }, str, function(err, data) {
                        if (str !== data) {
                            complete++;
                            grunt.file.write(file, data);
                        }
                    });
                }
            });

            grunt.log.writeln('Processed ' + complete + ' of ' + count + ' css files.');
            done();
        });
    });

};
<commit_msg>If you are on a detached HEAD, use the sha found<commit_after>/*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://yuilibrary.com/license/
*/

var path = require('path'),
    fs = require('fs'),
    timethat = require('timethat'),
    cpr = require('cpr').cpr,
    crypto = require('crypto'),
    cssproc = require('cssproc'),
    rimraf = require('rimraf');

module.exports = function(grunt) {

    var VERSION = grunt.option('release-version') || '',
        BUILD = grunt.option('release-build'),
        start, startTime, head, sha;

    if (VERSION && (!BUILD || BUILD === 'git' || BUILD === 'sha')) {
        head = grunt.file.read('.git/HEAD').replace('ref: ', '').trim();
        if (head) {
            try {
                sha = grunt.file.read(path.join('.git/', head)).trim();
            } catch (e) {
                sha = head.trim();
            }
            if (sha) {
                sha = sha.substr(0, 7);
                grunt.log.warn('No --release-build passed, using sha: ' + sha);
                BUILD = sha;
                grunt.config.set('build', BUILD);
            }
        }
    }

    if (VERSION && VERSION !== '') {
        start = path.join(process.cwd(), 'release', VERSION);
        grunt.config.set('version', VERSION);
    }

    grunt.registerTask('release', 'Create a YUI Release', [
        'release-boot',
        'release-prebuild',
        'release-prep',
        'release-clean',
        'build',
        'dist',
        'cdn',
        'cdn-ssl',
        'release-validate',
        'release-zip',
        'release-finish'
    ]);
    grunt.registerTask('release-prebuild', 'Build and test before prep', [
        'build',
        'test'
    ]);

    grunt.registerTask('release-validate', 'Validate the release before zipping', function() {
        grunt.log.ok('Validating the Release files.');
        /*
            Only looks for common, predictable files to make sure the other
            tasks did their job.
        */
        var dirs = [
            'cdn',
            'cdn/build',
            'cdn/build/yui',
            'cdn/build/yui/yui-min.js',
            'cdn-ssl',
            'cdn-ssl/build',
            'cdn-ssl/build/yui',
            'cdn-ssl/build/yui/yui-min.js',
            'npm',
            'npm/package.json',
            'npm/index.js',
            'npm/debug.js',
            'dist',
            'dist/api',
            'dist/api/index.html',
            'dist/api/data.json',
            'dist/docs',
            'dist/docs/index.html',
            'dist/releasenotes',
            'dist/releasenotes/HISTORY.yui.md',
            'dist/tests',
            'dist/tests/yui/tests/unit/index.html',
            'dist/README.md',
            'dist/LICENSE.md'
        ],
        fail = function(file) {
            grunt.fail.fatal('Failed to find: ' + file);
        },
        base = path.join('release', VERSION);

        if (!grunt.file.exists(base)) {
            fail(base);
        } else {
            grunt.log.writeln('Found!: '.green + base.cyan);
        }

        dirs.forEach(function(d) {
            var file = path.join(base, d);
            if (!grunt.file.exists(file)) {
                fail(file);
            } else {
                grunt.log.writeln('Found!: '.green + file.cyan);
            }
        });

    });

    grunt.registerTask('release-zip', 'Zipping up', [
        'compress:dist',
        'compress:cdn',
        'compress:cdn-ssl',
        'release-md5'
    ]);

    grunt.registerTask('release-md5', 'Create MD5 for release file', function() {
        var done = this.async(),
            file = path.join(start, 'archives', 'yui_' + VERSION + '.zip'),
            md5File = file + '.MD5',
            shasum = crypto.createHash('md5'),
            s = fs.ReadStream(file),
            finish = function() {
                grunt.log.ok('Checking for release zips');
                var files = [
                    'akamai_' + VERSION + '.zip',
                    'akamaissl_' + VERSION + '.zip',
                    'yui_' + VERSION + '.zip',
                    'yui_' + VERSION + '.zip.MD5'
                ];
                files.forEach(function(f) {
                    var file = path.join('release', VERSION, 'archives', f);
                    if (grunt.file.exists(file)) {
                        grunt.log.writeln('Found!: '.green + ' ' + file.cyan);
                    } else {
                        grunt.fail.fatal('Failed to find: ' + file.red);
                    }
                });
                done();
            };

        s.on('data', function(d) { shasum.update(d); });
        s.on('end', function() {
            var md5 = shasum.digest('hex');
            grunt.log.ok('Setting MD5 for release to: ' + md5);
            grunt.log.writeln('');
            grunt.file.write(md5File, md5 + '\n');
            finish();
        });
    });

    grunt.registerTask('release-boot', 'Booting the YUI Release', function() {
        startTime = new Date();

        if (!VERSION) {
            grunt.fail.fatal('No version found, use --release-version=x.y.z');
        }

        if (!BUILD) {
            grunt.fail.fatal('No build number found, use --release-build=x.y.z');
        }

        grunt.log.ok('Preparing YUI release for ' + VERSION + ', building and testing raw');
    });

    grunt.registerTask('release-prep', 'Booting the YUI Release', function() {
        grunt.cli.options.release = true;
        grunt.log.ok('All tests passed, starting offical build now');
    });

    grunt.registerTask('release-finish', 'Complete the YUI Release', function() {
        var endTime = new Date();
        grunt.log.ok('YUI Release for ' + VERSION + ' completed in ' + timethat.calc(startTime, endTime));
    });

    grunt.registerTask('release-clean', 'Cleaning release', function() {
        grunt.log.write('Deleting release directory');
        var done = this.async();
        rimraf(start, function() {
            grunt.log.writeln('...OK');
            done();
        });
    });

    grunt.registerTask('cdn', 'Preparing CDN Release', function() {
        grunt.log.writeln('Preparing CDN Release');
        var done = this.async(),
            source = path.join(start, 'dist', 'build'),
            dest = path.join(start, 'cdn', 'build');

        grunt.log.write('Copying build');

        cpr(source, dest, function() {
            grunt.log.writeln('...OK');
            grunt.log.writeln('Processing CSS files');
            var count = 0,
                complete = 0;

            grunt.file.recurse(dest, function(file) {
                if (path.extname(file) === '.css') {
                    count++;
                    var str = grunt.file.read(file);
                    cssproc.parse({
                        root: path.join(dest, '../'),
                        path: file,
                        base: 'http:/'+'/yui.yahooapis.com/' + VERSION + '/'
                    }, str, function(err, data) {
                        if (str !== data) {
                            complete++;
                            grunt.file.write(file, data);
                        }
                    });
                }
            });

            grunt.log.writeln('Processed ' + complete + ' of ' + count + ' css files.');
            done();
        });

    });

    grunt.registerTask('cdn-ssl', 'Preparing CDN SSL Release', function() {
        grunt.log.writeln('Preparing CDN SSL Release');
        var done = this.async(),
            source = path.join(start, 'dist', 'build'),
            dest = path.join(start, 'cdn-ssl', 'build');

        grunt.log.write('Copying build');

        cpr(source, dest, function() {
            grunt.log.writeln('...OK');
            grunt.log.writeln('Processing CSS files');
            var count = 0,
                complete = 0;

            grunt.file.recurse(dest, function(file) {
                if (path.extname(file) === '.css') {
                    count++;
                    var str = grunt.file.read(file);
                    cssproc.parse({
                        root: path.join(dest, '../'),
                        path: file,
                        base: 'https:/'+'/yui-s.yahooapis.com/' + VERSION + '/'
                    }, str, function(err, data) {
                        if (str !== data) {
                            complete++;
                            grunt.file.write(file, data);
                        }
                    });
                }
            });

            grunt.log.writeln('Processed ' + complete + ' of ' + count + ' css files.');
            done();
        });
    });

};
<|endoftext|>


<commit_before>var Promise = require('es6-promise').Promise;
var log = require('./utils/log');
var fs = require('./utils/fs');
var git = require('./utils/git');
var helper = require('./utils/config-helper');
var component, paths, pkg;

function ghPagesRelease(message){
    component = helper.getConfig();
    if (!component.release){
        log.info('Skipping GH-Pages Release : `release` set to false within component.config.js');
        return Promise.resolve();
    }
    var ghPages = require('gh-pages');
    message = message || 'Update';
    log.info("\nReleasing to gh-pages : `" + message + "`\n");
    return new Promise(function(resolve, reject){
        ghPages.publish(component.paths.site.root, {message: message }, function(err) {
            ghPages.clean();
            err && reject(err);
            !err && resolve();
        });
    });
}

function s3(version){
    component = helper.getConfig();
    if (!component.release){
        log.info('Skipping Release : `release` set to false within component.config.js');
        return Promise.resolve();
    }
    log.info("\nReleasing : \n");
    var Release = require('./wrappers/' + (component.release || 's3'));
    var options = (component[component.release]) || {};
    var target = options.target || options.directoryPrefix || '';//deprecate directoryPrefix
    if (version){
        target = target.replace(/("|\/)[0-9]+\.[0-9]+\.[0-9]\-?(?:(?:[0-9A-Za-z-]+\.?)+)?("|\/)/g, '$1' + version + '$2');
    }
    return new Release(component.paths.site.root + '/**/*.*', target, options).write();
}

function releaseGit(version){
    if (!git.checkRemote()){
        log.onError('No valid Remote Git URL.\nPlease update your `.git/config` file or run:\n $ component init git');
    }
    component = helper.getConfig();
    version = version || component.pkg.version;
    log.info('Start release to Git : ' + version);
    return git.release(version);
}

function run(type){
    var bump = require('./bump').run;
    var bumpedVersion;
    return bump(type).then(function(version) {
        bumpedVersion = version;
        return releaseGit(version);
    }).then(function(){
        return ghPagesRelease('v' + bumpedVersion);
    }).then(function(){
        return s3(bumpedVersion);
    }).catch(log.onError);
}

module.exports = {
    git: releaseGit,
    'gh-pages': ghPagesRelease,
    s3: s3,
    run: run,
    adhoc: run
};
<commit_msg>undo gh-pages limitation<commit_after>var Promise = require('es6-promise').Promise;
var log = require('./utils/log');
var fs = require('./utils/fs');
var git = require('./utils/git');
var helper = require('./utils/config-helper');
var component, paths, pkg;

function ghPagesRelease(message){
    component = helper.getConfig();
    var ghPages = require('gh-pages');
    message = message || 'Update';
    log.info("\nReleasing to gh-pages : `" + message + "`\n");
    return new Promise(function(resolve, reject){
        ghPages.publish(component.paths.site.root, {message: message }, function(err) {
            ghPages.clean();
            err && reject(err);
            !err && resolve();
        });
    });
}

function s3(version){
    component = helper.getConfig();
    if (!component.release){
        log.info('Skipping Release : `release` set to false within component.config.js');
        return Promise.resolve();
    }
    if (component.release.indexOf('s3') < 0) return;
    log.info("\nReleasing : \n");
    var Release = require('./wrappers/' + (component.release || 's3'));
    var options = (component[component.release]) || {};
    var target = options.target || options.directoryPrefix || '';//deprecate directoryPrefix
    if (version){
        target = target.replace(/("|\/)[0-9]+\.[0-9]+\.[0-9]\-?(?:(?:[0-9A-Za-z-]+\.?)+)?("|\/)/g, '$1' + version + '$2');
    }
    return new Release(component.paths.site.root + '/**/*.*', target, options).write();
}

function releaseGit(version){
    if (!git.checkRemote()){
        log.onError('No valid Remote Git URL.\nPlease update your `.git/config` file or run:\n $ component init git');
    }
    component = helper.getConfig();
    version = version || component.pkg.version;
    log.info('Start release to Git : ' + version);
    return git.release(version);
}

function run(type){
    var bump = require('./bump').run;
    var bumpedVersion;
    return bump(type).then(function(version) {
        bumpedVersion = version;
        return releaseGit(version);
    }).then(function(){
        return ghPagesRelease('v' + bumpedVersion);
    }).then(function(){
        return s3(bumpedVersion);
    }).catch(log.onError);
}

module.exports = {
    git: releaseGit,
    'gh-pages': ghPagesRelease,
    s3: s3,
    run: run,
    adhoc: run
};
<|endoftext|>