<commit_before>/* https://github.com/DiemenDesign/summernote-cleaner */
(function (factory) {
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory(require('jquery'));
  } else {
    factory(window.jQuery);
  }
}
(function ($) {
  $.extend(true, $.summernote.lang, {
    'en-US': {
      cleaner: {
        tooltip: 'Cleaner',
        not: 'Text has been Cleaned!!!',
        limitText: 'Text',
        limitHTML: 'HTML'
      }
    }
  });
  $.extend($.summernote.options, {
    cleaner: {
      action: 'both', // both|button|paste 'button' only cleans via toolbar button, 'paste' only clean when pasting content, both does both options.
      newline: '
', // Summernote's default is to use '

'
      notStyle: 'position:absolute;top:0;left:0;right:0',
      icon: '<svg xmlns="http://www.w3.org/2000/svg" id="libre-paintbrush" viewBox="0 0 14 14" width="14" height="14"><path d="m 11.821425,1 q 0.46875,0 0.82031,0.311384 0.35157,0.311384 0.35157,0.780134 0,0.421875 -0.30134,1.01116 -2.22322,4.212054 -3.11384,5.035715 -0.64956,0.609375 -1.45982,0.609375 -0.84375,0 -1.44978,-0.61942 -0.60603,-0.61942 -0.60603,-1.469866 0,-0.857143 0.61608,-1.419643 l 4.27232,-3.877232 Q 11.345985,1 11.821425,1 z m -6.08705,6.924107 q 0.26116,0.508928 0.71317,0.870536 0.45201,0.361607 1.00781,0.508928 l 0.007,0.475447 q 0.0268,1.426339 -0.86719,2.32366 Q 5.700895,13 4.261155,13 q -0.82366,0 -1.45982,-0.311384 -0.63616,-0.311384 -1.0212,-0.853795 -0.38505,-0.54241 -0.57924,-1.225446 -0.1942,-0.683036 -0.1942,-1.473214 0.0469,0.03348 0.27455,0.200893 0.22768,0.16741 0.41518,0.29799 0.1875,0.130581 0.39509,0.24442 0.20759,0.113839 0.30804,0.113839 0.27455,0 0.3683,-0.247767 0.16741,-0.441965 0.38505,-0.753349 0.21763,-0.311383 0.4654,-0.508928 0.24776,-0.197545 0.58928,-0.31808 0.34152,-0.120536 0.68974,-0.170759 0.34821,-0.05022 0.83705,-0.07031 z"/></svg>',
      keepHtml: true, //Remove all Html formats
      keepOnlyTags: [], // If keepHtml is true, remove all tags except these
      keepClasses: false, //Remove Classes
      badTags: ['style', 'script', 'applet', 'embed', 'noframes', 'noscript', 'html'], //Remove full tags with contents
      badAttributes: ['style', 'start'], //Remove attributes from remaining tags
      limitChars: 520, // 0|# 0 disables option
      limitDisplay: 'both', // none|text|html|both
      limitStop: false // true/false
    }
  });
  $.extend($.summernote.plugins, {
    'cleaner':function (context) {
      var self = this,
            ui = $.summernote.ui,
         $note = context.layoutInfo.note,
       $editor = context.layoutInfo.editor,
       options = context.options,
          lang = options.langInfo;
      var cleanText = function (txt, nlO) {
        var out = txt;
        if (!options.cleaner.keepClasses) {
          var sS = /(\n|\r| class=(")?Mso[a-zA-Z]+(")?)/g;
             out = txt.replace(sS, ' ');
        }
        var nL = /(\n)+/g;
           out = out.replace(nL, nlO);
        if (options.cleaner.keepHtml) {
          var cS = new RegExp('', 'gi');
             out = out.replace(cS, '');
          var tS = new RegExp('<(/)*(meta|link|\\?xml:|st1:|o:|font)(.*?)>', 'gi');
             out = out.replace(tS, '');
          var bT = options.cleaner.badTags;
          for (var i = 0; i < bT.length; i++) {
            tS = new RegExp('<' + bT[i] + '\\b.*>.*</' + bT[i] + '>', 'gi');
            out = out.replace(tS, '');
          }
          var allowedTags = options.cleaner.keepOnlyTags;
          if (typeof(allowedTags) == "undefined") allowedTags = [];
          if (allowedTags.length > 0) {
            allowedTags = (((allowedTags||'') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
               var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
                    out = out.replace(tags, function($0, $1) {
              return allowedTags.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''
            });
          }
          var bA = options.cleaner.badAttributes;
          for (var ii = 0; ii < bA.length; ii++ ) {
            //var aS=new RegExp(' ('+bA[ii]+'="(.*?)")|('+bA[ii]+'=\'(.*?)\')', 'gi');
            var aS = new RegExp(' ' + bA[ii] + '=[\'|"](.*?)[\'|"]', 'gi');
               out = out.replace(aS, '');

               aS = new RegExp(" " + bA[ii] + "=(.*?) ", "gi");
               out = out.replace(aS, " ");
               aS = new RegExp(" " + bA[ii] + "=(.*?)>", "gi");
               out = out.replace(aS, ">");
          }
        }

        var sS = new RegExp("[ ]{1,}>", "gi");
        out = out.replace(sS, ">");
        return out;
      };
      if (options.cleaner.action == 'both' || options.cleaner.action == 'button') {
        context.memo('button.cleaner', function () {
          var button = ui.button({
            contents: options.cleaner.icon,
            tooltip: lang.cleaner.tooltip,
            container: 'body',
            click:function () {
              if ($note.summernote('createRange').toString())
                $note.summernote('pasteHTML', $note.summernote('createRange').toString());
              else
                $note.summernote('code', cleanText($note.summernote('code')));
              if ($editor.find('.note-status-output').length > 0)
                $editor.find('.note-status-output').html('
' + lang.cleaner.not + '
');
              else
                $editor.find('.note-editing-area').append('
' + lang.cleaner.not + '
');
            }
          });
          return button.render();
        });
      }
      this.events = {
        'summernote.init':function () {
          if ($editor.find('.note-status-output').length < 1) {
            $editor.find('.note-statusbar').prepend('<output class="note-status-output"></output>');
            $("head").append('');
          }
          if (options.cleaner.limitChars != 0 || options.cleaner.limitDisplay != 'none') {
              var textLength = $editor.find(".note-editable").text().replace(/(<([^>]+)>)/ig, "").replace(/( )/, " ");
              var codeLength = $editor.find('.note-editable').html();
            var lengthStatus = '';
            if (textLength.length > options.cleaner.limitChars && options.cleaner.limitChars > 0)
              lengthStatus += 'text-danger">';
            else
              lengthStatus += '">';
            if (options.cleaner.limitDisplay == 'text' || options.cleaner.limitDisplay == 'both') lengthStatus += lang.cleaner.limitText + ': ' + textLength.length;
            if (options.cleaner.limitDisplay == 'both') lengthStatus += ' / ';
            if (options.cleaner.limitDisplay == 'html' || options.cleaner.limitDisplay == 'both') lengthStatus += lang.cleaner.limitHTML + ': ' + codeLength.length;
            $editor.find('.note-status-output').html('<small class="pull-right ' + lengthStatus + ' ');
          }
        },
        'summernote.keydown':function (we, e) {
          if (options.cleaner.limitChars != 0 || options.cleaner.limitDisplay != 'none') {
              var textLength =  $editor.find(".note-editable").text().replace(/(<([^>]+)>)/ig, "").replace(/( )/, " ");
              var codeLength =  $editor.find('.note-editable').html();
            var lengthStatus = '';
            if (options.cleaner.limitStop == true && textLength.length >= options.cleaner.limitChars) {
                   var key = e.keyCode;
              allowed_keys = [8, 37, 38, 39, 40, 46]
              if ($.inArray(key, allowed_keys) != -1) {
                $editor.find('.cleanerLimit').removeClass('text-danger');
                return true;
              } else {
                $editor.find('.cleanerLimit').addClass('text-danger');
                e.preventDefault();
                e.stopPropagation();
              }
            } else {
              if (textLength.length > options.cleaner.limitChars && options.cleaner.limitChars > 0)
                lengthStatus += 'text-danger">';
              else
                lengthStatus += '">';
              if (options.cleaner.limitDisplay == 'text' || options.cleaner.limitDisplay == 'both')
                lengthStatus += lang.cleaner.limitText + ': ' + textLength.length;
              if (options.cleaner.limitDisplay == 'both')
                lengthStatus += ' / ';
              if (options.cleaner.limitDisplay == 'html' || options.cleaner.limitDisplay == 'both')
                lengthStatus += lang.cleaner.limitHTML + ': ' + codeLength.length;
              $editor.find('.note-status-output').html('<small class="cleanerLimit pull-right ' + lengthStatus + ' ');
            }
          }
        },
        'summernote.paste':function (we, e) {
          if (options.cleaner.action == 'both' || options.cleaner.action == 'paste') {
            e.preventDefault();
              var ua = window.navigator.userAgent;
            var msie = ua.indexOf("MSIE ");
                msie = msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./);
            var ffox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
            if (msie)
              var text = window.clipboardData.getData("Text");
            else
              var text = e.originalEvent.clipboardData.getData(options.cleaner.keepHtml ? 'text/html' : 'text/plain');
            if (text) {
              if (msie || ffox)
                setTimeout(function(){$note.summernote('pasteHTML', cleanText(text, options.cleaner.newline));}, 1);
              else
                $note.summernote('pasteHTML', cleanText(text, options.cleaner.newline));
              if ($editor.find('.note-status-output').length > 0)
                $editor.find('.note-status-output').html('
' + lang.cleaner.not + '
');
              else
                $editor.find('.note-resizebar').append('
' + lang.cleaner.not + '
');
            }
          }
        }
      }
    }
  });
}));
<commit_msg>Add fix for new regex without quotes<commit_after>/* https://github.com/DiemenDesign/summernote-cleaner */
(function (factory) {
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory(require('jquery'));
  } else {
    factory(window.jQuery);
  }
}
(function ($) {
  $.extend(true, $.summernote.lang, {
    'en-US': {
      cleaner: {
        tooltip: 'Cleaner',
        not: 'Text has been Cleaned!!!',
        limitText: 'Text',
        limitHTML: 'HTML'
      }
    }
  });
  $.extend($.summernote.options, {
    cleaner: {
      action: 'both', // both|button|paste 'button' only cleans via toolbar button, 'paste' only clean when pasting content, both does both options.
      newline: '
', // Summernote's default is to use '

'
      notStyle: 'position:absolute;top:0;left:0;right:0',
      icon: '<svg xmlns="http://www.w3.org/2000/svg" id="libre-paintbrush" viewBox="0 0 14 14" width="14" height="14"><path d="m 11.821425,1 q 0.46875,0 0.82031,0.311384 0.35157,0.311384 0.35157,0.780134 0,0.421875 -0.30134,1.01116 -2.22322,4.212054 -3.11384,5.035715 -0.64956,0.609375 -1.45982,0.609375 -0.84375,0 -1.44978,-0.61942 -0.60603,-0.61942 -0.60603,-1.469866 0,-0.857143 0.61608,-1.419643 l 4.27232,-3.877232 Q 11.345985,1 11.821425,1 z m -6.08705,6.924107 q 0.26116,0.508928 0.71317,0.870536 0.45201,0.361607 1.00781,0.508928 l 0.007,0.475447 q 0.0268,1.426339 -0.86719,2.32366 Q 5.700895,13 4.261155,13 q -0.82366,0 -1.45982,-0.311384 -0.63616,-0.311384 -1.0212,-0.853795 -0.38505,-0.54241 -0.57924,-1.225446 -0.1942,-0.683036 -0.1942,-1.473214 0.0469,0.03348 0.27455,0.200893 0.22768,0.16741 0.41518,0.29799 0.1875,0.130581 0.39509,0.24442 0.20759,0.113839 0.30804,0.113839 0.27455,0 0.3683,-0.247767 0.16741,-0.441965 0.38505,-0.753349 0.21763,-0.311383 0.4654,-0.508928 0.24776,-0.197545 0.58928,-0.31808 0.34152,-0.120536 0.68974,-0.170759 0.34821,-0.05022 0.83705,-0.07031 z"/></svg>',
      keepHtml: true, //Remove all Html formats
      keepOnlyTags: [], // If keepHtml is true, remove all tags except these
      keepClasses: false, //Remove Classes
      badTags: ['style', 'script', 'applet', 'embed', 'noframes', 'noscript', 'html'], //Remove full tags with contents
      badAttributes: ['style', 'start'], //Remove attributes from remaining tags
      limitChars: 520, // 0|# 0 disables option
      limitDisplay: 'both', // none|text|html|both
      limitStop: false // true/false
    }
  });
  $.extend($.summernote.plugins, {
    'cleaner':function (context) {
      var self = this,
            ui = $.summernote.ui,
         $note = context.layoutInfo.note,
       $editor = context.layoutInfo.editor,
       options = context.options,
          lang = options.langInfo;
      var cleanText = function (txt, nlO) {
        var out = txt;
        if (!options.cleaner.keepClasses) {
          var sS = /(\n|\r| class=(")?Mso[a-zA-Z]+(")?)/g;
             out = txt.replace(sS, ' ');
        }
        var nL = /(\n)+/g;
           out = out.replace(nL, nlO);
        if (options.cleaner.keepHtml) {
          var cS = new RegExp('', 'gi');
             out = out.replace(cS, '');
          var tS = new RegExp('<(/)*(meta|link|\\?xml:|st1:|o:|font)(.*?)>', 'gi');
             out = out.replace(tS, '');
          var bT = options.cleaner.badTags;
          for (var i = 0; i < bT.length; i++) {
            tS = new RegExp('<' + bT[i] + '\\b.*>.*</' + bT[i] + '>', 'gi');
            out = out.replace(tS, '');
          }
          var allowedTags = options.cleaner.keepOnlyTags;
          if (typeof(allowedTags) == "undefined") allowedTags = [];
          if (allowedTags.length > 0) {
            allowedTags = (((allowedTags||'') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
               var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
                    out = out.replace(tags, function($0, $1) {
              return allowedTags.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''
            });
          }
          var bA = options.cleaner.badAttributes;
          for (var ii = 0; ii < bA.length; ii++ ) {
            //var aS=new RegExp(' ('+bA[ii]+'="(.*?)")|('+bA[ii]+'=\'(.*?)\')', 'gi');
            var aS = new RegExp(' ' + bA[ii] + '=[\'|"](.*?)[\'|"]', 'gi');
               out = out.replace(aS, '');

               aS = new RegExp(" " + bA[ii] + "[=0-9a-z]", "gi");
               out = out.replace(aS, "");
          }
        }

        var sS = new RegExp("[ ]{1,}>", "gi");
        out = out.replace(sS, ">");
        return out;
      };
      if (options.cleaner.action == 'both' || options.cleaner.action == 'button') {
        context.memo('button.cleaner', function () {
          var button = ui.button({
            contents: options.cleaner.icon,
            tooltip: lang.cleaner.tooltip,
            container: 'body',
            click:function () {
              if ($note.summernote('createRange').toString())
                $note.summernote('pasteHTML', $note.summernote('createRange').toString());
              else
                $note.summernote('code', cleanText($note.summernote('code')));
              if ($editor.find('.note-status-output').length > 0)
                $editor.find('.note-status-output').html('
' + lang.cleaner.not + '
');
              else
                $editor.find('.note-editing-area').append('
' + lang.cleaner.not + '
');
            }
          });
          return button.render();
        });
      }
      this.events = {
        'summernote.init':function () {
          if ($editor.find('.note-status-output').length < 1) {
            $editor.find('.note-statusbar').prepend('<output class="note-status-output"></output>');
            $("head").append('');
          }
          if (options.cleaner.limitChars != 0 || options.cleaner.limitDisplay != 'none') {
              var textLength = $editor.find(".note-editable").text().replace(/(<([^>]+)>)/ig, "").replace(/( )/, " ");
              var codeLength = $editor.find('.note-editable').html();
            var lengthStatus = '';
            if (textLength.length > options.cleaner.limitChars && options.cleaner.limitChars > 0)
              lengthStatus += 'text-danger">';
            else
              lengthStatus += '">';
            if (options.cleaner.limitDisplay == 'text' || options.cleaner.limitDisplay == 'both') lengthStatus += lang.cleaner.limitText + ': ' + textLength.length;
            if (options.cleaner.limitDisplay == 'both') lengthStatus += ' / ';
            if (options.cleaner.limitDisplay == 'html' || options.cleaner.limitDisplay == 'both') lengthStatus += lang.cleaner.limitHTML + ': ' + codeLength.length;
            $editor.find('.note-status-output').html('<small class="pull-right ' + lengthStatus + ' ');
          }
        },
        'summernote.keydown':function (we, e) {
          if (options.cleaner.limitChars != 0 || options.cleaner.limitDisplay != 'none') {
              var textLength =  $editor.find(".note-editable").text().replace(/(<([^>]+)>)/ig, "").replace(/( )/, " ");
              var codeLength =  $editor.find('.note-editable').html();
            var lengthStatus = '';
            if (options.cleaner.limitStop == true && textLength.length >= options.cleaner.limitChars) {
                   var key = e.keyCode;
              allowed_keys = [8, 37, 38, 39, 40, 46]
              if ($.inArray(key, allowed_keys) != -1) {
                $editor.find('.cleanerLimit').removeClass('text-danger');
                return true;
              } else {
                $editor.find('.cleanerLimit').addClass('text-danger');
                e.preventDefault();
                e.stopPropagation();
              }
            } else {
              if (textLength.length > options.cleaner.limitChars && options.cleaner.limitChars > 0)
                lengthStatus += 'text-danger">';
              else
                lengthStatus += '">';
              if (options.cleaner.limitDisplay == 'text' || options.cleaner.limitDisplay == 'both')
                lengthStatus += lang.cleaner.limitText + ': ' + textLength.length;
              if (options.cleaner.limitDisplay == 'both')
                lengthStatus += ' / ';
              if (options.cleaner.limitDisplay == 'html' || options.cleaner.limitDisplay == 'both')
                lengthStatus += lang.cleaner.limitHTML + ': ' + codeLength.length;
              $editor.find('.note-status-output').html('<small class="cleanerLimit pull-right ' + lengthStatus + ' ');
            }
          }
        },
        'summernote.paste':function (we, e) {
          if (options.cleaner.action == 'both' || options.cleaner.action == 'paste') {
            e.preventDefault();
              var ua = window.navigator.userAgent;
            var msie = ua.indexOf("MSIE ");
                msie = msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./);
            var ffox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
            if (msie)
              var text = window.clipboardData.getData("Text");
            else
              var text = e.originalEvent.clipboardData.getData(options.cleaner.keepHtml ? 'text/html' : 'text/plain');
            if (text) {
              if (msie || ffox)
                setTimeout(function(){$note.summernote('pasteHTML', cleanText(text, options.cleaner.newline));}, 1);
              else
                $note.summernote('pasteHTML', cleanText(text, options.cleaner.newline));
              if ($editor.find('.note-status-output').length > 0)
                $editor.find('.note-status-output').html('
' + lang.cleaner.not + '
');
              else
                $editor.find('.note-resizebar').append('
' + lang.cleaner.not + '
');
            }
          }
        }
      }
    }
  });
}));
<|endoftext|>


<commit_before>exports.init = function (grunt) {
  'use strict';
  var fs = require('fs');
  var tmp = require('tmp');
  var dargs = require('dargs');
  var path = require('path');
  var async = require('async');

  var exports = {};

  function camelCaseToUnderscore(str) {
    return str
      .replace(/([a-z])([A-Z])/g, '$1_$2')
      .toLowerCase();
  }

  // Extracts the options that cannot be used as CLI parameter but only
  // as 'raw' arguments.
  // Returns an object: {raw: str, options: []} with the raw string to be
  // used to generate a config and the list of used options.
  exports.extractRawOptions = function extractRawOptions(options) {
    var raw = options.raw || '';
    var supportedOptions = [
      'http_path',
      'css_path',
      'http_stylesheets_path',
      'sass_path',
      'images_path',
      'http_images_path',
      'generated_images_dir',
      'generated_images_path',
      'http_generated_images_path',
      'javascripts_path',
      'http_javascripts_path',
      'fonts_path',
      'http_fonts_path',
      'http_fonts_dir',
      'extensions_dir',
      'extension_path',
      'cache_dir'
    ];

    var usedOptions = Object.keys(options).filter(function (option) {
      var underscoredOption = camelCaseToUnderscore(option);
      if (supportedOptions.indexOf(underscoredOption) >= 0) {
        // naively escape double-quotes in the value
        var value = options[option].replace(/"/, '\\"');
        raw += underscoredOption + ' = "' + value + '"\n';
        delete options[option];

        return true;
      } else if (underscoredOption === 'asset_cache_buster') {
        // Special handling for asset_cache_buster as it doesn't take
        // a string as argument, but either an inline-ruby block (which we don't
        // support) or a `:none` symbol to disable it.
        if (options[option] === false) {
          raw += underscoredOption + ' :none';
        }
        delete options[option];
        return true;
      }
    });

    return {raw: raw, options: usedOptions};
  };

  // Create a function to add a banner, if requested through the options.
  exports.buildBannerCallback = function (grunt, options) {
    if (!options.specify || !options.banner) {
      if (options.banner && !options.specify) {
        grunt.warn('You can only use the `banner` option in combination with `specify.`');
      }
      // Return a no-op if specify or banner aren't set.
      return function () {};
    }

    var srcFiles = grunt.file.expand({
      filter: function (filePath) {
        return path.basename(filePath)[0] !== '_';
      }
    }, options.specify);

    var banner = options.banner;
    delete options.banner;

    var destFiles = srcFiles.map(function (filename) {
      return filename.replace(options.sassDir, options.cssDir).replace(/\.(css\.)?(scss|sass)$/i, '.css');
    });

    return function () {
      grunt.log.verbose.writeln('Writing CSS banners.');
      async.map(destFiles, function (filename) {
        grunt.log.verbose.writeln('Writing CSS banner for ' + filename);
        var content = grunt.file.read(filename);
        grunt.file.write(filename, banner + grunt.util.linefeed + content);
      });
    };
  };

  // Create a config file on the fly if there are arguments not supported as
  // CLI, returns a function that runs within the temprorary context.
  exports.buildConfigContext = function (options) {
    var rawOptions = exports.extractRawOptions(options);
    if (options.raw && options.config) {
      grunt.warn('The options `raw` and `config` are mutually exclusive');
    }

    if (rawOptions.options.length > 0 && options.config) {
      grunt.warn('The option `config` cannot be combined with ' +
                       'these options: ' + rawOptions.options.join(', ') + '.');
    }

    return function configContext(cb) {
      if (rawOptions.raw) {
        tmp.file(function (err, path, fd) {
          if (err) {
            return cb(err);
          }

          // Dynamically create config.rb as a tmp file for the `raw` content
          fs.writeSync(fd, new Buffer(rawOptions.raw), 0, rawOptions.raw.length);
          cb(null, path);
        });
      } else {
        cb(null, null);
      }
    };
  };

  // build the array of arguments to build the compass command
  exports.buildArgsArray = function (options) {
    var args = ['compile'];
    if (options.clean) {
      args = ['clean'];
    } else if (options.watch) {
      args = ['watch'];
    }

    var basePath = options.basePath;

    if (process.platform === 'win32') {
      args.unshift('compass.bat');
    } else {
      args.unshift('compass');
    }

    if (options.bundleExec) {
      args.unshift('bundle', 'exec');
    }

    if (options.basePath) {
      args.push(options.basePath);
    }

    if (options.specify) {
      var files = grunt.file.expand({
        filter: function (filePath) {
          return path.basename(filePath)[0] !== '_';
        }
      }, options.specify);

      if (files.length > 0) {
        [].push.apply(args, files);
      } else {
        return grunt.log.writeln('`specify` option used, but no files were found.');
      }
    }

    // add converted options
    [].push.apply(args, dargs(options, [
      'raw',
      'clean',
      'bundleExec',
      'basePath',
      'specify',
      'watch'
    ]));

    // Compass doesn't have a long flag for this option:
    // https://github.com/chriseppstein/compass/issues/1055
    if (options.importPath) {
      args = args.map(function (el) {
        return el.replace('--import-path', '-I');
      });
    }

    if (grunt.option('no-color')) {
      args.push('--boring');
    }

    return args;
  };

  return exports;
};
<commit_msg>Update compass.js<commit_after>exports.init = function (grunt) {
  'use strict';
  var fs = require('fs');
  var tmp = require('tmp');
  var dargs = require('dargs');
  var path = require('path');
  var async = require('async');

  var exports = {};

  function camelCaseToUnderscore(str) {
    return str
      .replace(/([a-z])([A-Z])/g, '$1_$2')
      .toLowerCase();
  }

  // Extracts the options that cannot be used as CLI parameter but only
  // as 'raw' arguments.
  // Returns an object: {raw: str, options: []} with the raw string to be
  // used to generate a config and the list of used options.
  exports.extractRawOptions = function extractRawOptions(options) {
    var raw = options.raw || '';
    var supportedOptions = [
      'http_path',
      'css_path',
      'http_stylesheets_path',
      'sass_path',
      'images_path',
      'http_images_path',
      'generated_images_dir',
      'generated_images_path',
      'http_generated_images_path',
      'javascripts_path',
      'http_javascripts_path',
      'fonts_path',
      'http_fonts_path',
      'http_fonts_dir',
      'extensions_dir',
      'extension_path',
      'cache_dir'
    ];

    var usedOptions = Object.keys(options).filter(function (option) {
      var underscoredOption = camelCaseToUnderscore(option);
      if (supportedOptions.indexOf(underscoredOption) >= 0) {
        // naively escape double-quotes in the value
        var value = options[option].replace(/"/, '\\"');
        raw += underscoredOption + ' = "' + value + '"\n';
        delete options[option];

        return true;
      } else if (underscoredOption === 'asset_cache_buster') {
        // Special handling for asset_cache_buster as it doesn't take
        // a string as argument, but either an inline-ruby block (which we don't
        // support) or a `:none` symbol to disable it.
        if (options[option] === false) {
          raw += underscoredOption + ' :none' + '\n';
        }
        delete options[option];
        return true;
      }
    });

    return {raw: raw, options: usedOptions};
  };

  // Create a function to add a banner, if requested through the options.
  exports.buildBannerCallback = function (grunt, options) {
    if (!options.specify || !options.banner) {
      if (options.banner && !options.specify) {
        grunt.warn('You can only use the `banner` option in combination with `specify.`');
      }
      // Return a no-op if specify or banner aren't set.
      return function () {};
    }

    var srcFiles = grunt.file.expand({
      filter: function (filePath) {
        return path.basename(filePath)[0] !== '_';
      }
    }, options.specify);

    var banner = options.banner;
    delete options.banner;

    var destFiles = srcFiles.map(function (filename) {
      return filename.replace(options.sassDir, options.cssDir).replace(/\.(css\.)?(scss|sass)$/i, '.css');
    });

    return function () {
      grunt.log.verbose.writeln('Writing CSS banners.');
      async.map(destFiles, function (filename) {
        grunt.log.verbose.writeln('Writing CSS banner for ' + filename);
        var content = grunt.file.read(filename);
        grunt.file.write(filename, banner + grunt.util.linefeed + content);
      });
    };
  };

  // Create a config file on the fly if there are arguments not supported as
  // CLI, returns a function that runs within the temprorary context.
  exports.buildConfigContext = function (options) {
    var rawOptions = exports.extractRawOptions(options);
    if (options.raw && options.config) {
      grunt.warn('The options `raw` and `config` are mutually exclusive');
    }

    if (rawOptions.options.length > 0 && options.config) {
      grunt.warn('The option `config` cannot be combined with ' +
                       'these options: ' + rawOptions.options.join(', ') + '.');
    }

    return function configContext(cb) {
      if (rawOptions.raw) {
        tmp.file(function (err, path, fd) {
          if (err) {
            return cb(err);
          }

          // Dynamically create config.rb as a tmp file for the `raw` content
          fs.writeSync(fd, new Buffer(rawOptions.raw), 0, rawOptions.raw.length);
          cb(null, path);
        });
      } else {
        cb(null, null);
      }
    };
  };

  // build the array of arguments to build the compass command
  exports.buildArgsArray = function (options) {
    var args = ['compile'];
    if (options.clean) {
      args = ['clean'];
    } else if (options.watch) {
      args = ['watch'];
    }

    var basePath = options.basePath;

    if (process.platform === 'win32') {
      args.unshift('compass.bat');
    } else {
      args.unshift('compass');
    }

    if (options.bundleExec) {
      args.unshift('bundle', 'exec');
    }

    if (options.basePath) {
      args.push(options.basePath);
    }

    if (options.specify) {
      var files = grunt.file.expand({
        filter: function (filePath) {
          return path.basename(filePath)[0] !== '_';
        }
      }, options.specify);

      if (files.length > 0) {
        [].push.apply(args, files);
      } else {
        return grunt.log.writeln('`specify` option used, but no files were found.');
      }
    }

    // add converted options
    [].push.apply(args, dargs(options, [
      'raw',
      'clean',
      'bundleExec',
      'basePath',
      'specify',
      'watch'
    ]));

    // Compass doesn't have a long flag for this option:
    // https://github.com/chriseppstein/compass/issues/1055
    if (options.importPath) {
      args = args.map(function (el) {
        return el.replace('--import-path', '-I');
      });
    }

    if (grunt.option('no-color')) {
      args.push('--boring');
    }

    return args;
  };

  return exports;
};
<|endoftext|>


<commit_before>var jsdom = require("jsdom").jsdom;
    md5 = require('MD5'),
    fs = require("fs"),
    _ = require("underscore");

function mdfiver(htmlfile) {
    this.head = "";
    this.htmlfile = htmlfile;
    if (this.htmlfile) {
        this.html = fs.readFileSync(htmlfile);
    }

}

function createReplaceString(originalFileNameAndMd5) {
    var lastIndexOfPoint = originalFileNameAndMd5.filename.lastIndexOf(".");
    var start = originalFileNameAndMd5.filename.substring(0,lastIndexOfPoint);
    var end = originalFileNameAndMd5.filename.substring(lastIndexOfPoint
    );
    return start+"_"+originalFileNameAndMd5.md5+end;

}

mdfiver.prototype.parseHead = function() {
    this.head = jsdom(
        this.html,
        null
    ).createWindow().document.getElementsByTagName("head")[0];
};

mdfiver.prototype.getScriptTagsPaths = function() {
    var paths = [];
    _.each(this.head.getElementsByTagName("script"), function(element) {
        paths.push(element.getAttribute("src"));
    });
    return paths;
};

mdfiver.prototype.getCSSTagsPaths = function() {
    var paths = [];
    _.each(this.head.getElementsByTagName("link"), function(element) {
        paths.push(element.getAttribute("href"));
    });
    return paths;
};

/***
* Calculates MD5 from chosen file
*
* Returns {filename: "filenamewithpath", md5: "md5"}
*
* @method createMD5FromFile
* @param file file with path
**/
mdfiver.prototype.createMD5FromFile = function(file) {
    var data = fs.readFileSync(file, "utf8");
    return {filename: file, md5:  md5(data)};
};

mdfiver.prototype.fixHtml = function(replaceEntity) {
    var newFileName = createReplaceString(replaceEntity);
    return ""+this.html.replace(replaceEntity.filename, newFileName);
};

mdfiver.prototype.renameFile = function(originalFileNameAndMd5) {
    fs.renameSync(originalFileNameAndMd5.filename, createReplaceString(originalFileNameAndMd5));
};

module.exports = mdfiver;
<commit_msg>replaces html file contents<commit_after>var jsdom = require("jsdom").jsdom;
    md5 = require('MD5'),
    fs = require("fs"),
    _ = require("underscore");

function mdfiver(htmlfile) {
    this.head = "";
    this.htmlfile = htmlfile;
    if (this.htmlfile) {
        this.html = fs.readFileSync(htmlfile, "utf8");
    }

}

function createReplaceString(originalFileNameAndMd5) {
    var lastIndexOfPoint = originalFileNameAndMd5.filename.lastIndexOf(".");
    var start = originalFileNameAndMd5.filename.substring(0,lastIndexOfPoint);
    var end = originalFileNameAndMd5.filename.substring(lastIndexOfPoint
    );
    return start+"_"+originalFileNameAndMd5.md5+end;

}

mdfiver.prototype.parseHead = function() {
    this.head = jsdom(
        this.html,
        null
    ).createWindow().document.getElementsByTagName("head")[0];
};

mdfiver.prototype.getScriptTagsPaths = function() {
    var paths = [];
    _.each(this.head.getElementsByTagName("script"), function(element) {
        paths.push(element.getAttribute("src"));
    });
    return paths;
};

mdfiver.prototype.getCSSTagsPaths = function() {
    var paths = [];
    _.each(this.head.getElementsByTagName("link"), function(element) {
        paths.push(element.getAttribute("href"));
    });
    return paths;
};

/***
* Calculates MD5 from chosen file
*
* Returns {filename: "filenamewithpath", md5: "md5"}
*
* @method createMD5FromFile
* @param file file with path
**/
mdfiver.prototype.createMD5FromFile = function(file) {
    var data = fs.readFileSync(file, "utf8");
    return {filename: file, md5:  md5(data)};
};

mdfiver.prototype.fixHtml = function(replaceEntity) {
    var newFileName = createReplaceString(replaceEntity);
    return this.html.replace(replaceEntity.filename, newFileName);
};

mdfiver.prototype.renameFile = function(originalFileNameAndMd5) {
    fs.renameSync(originalFileNameAndMd5.filename, createReplaceString(originalFileNameAndMd5));
};

module.exports = mdfiver;
<|endoftext|>


<commit_before>/*
 * grunt-maven-tasks
 * https://github.com/smh/grunt-maven-tasks
 *
 * Copyright (c) 2013 Stein Martin Hustad
 * Licensed under the MIT license.
 */

'use strict';

var semver = require('semver');
var fs = require('fs');

function injectDestFolder(targetPath, files) {
  var path = require('path');
  files.forEach(function(file) {
    file.dest = path.join(targetPath, file.dest || '');
  });
  return files;
}

module.exports = function(grunt) {

  grunt.registerMultiTask('maven', 'Packages and deploys artifact to maven repo', function(version, mode) {
    var options = this.options();

    requireOptionProps(options, ['groupId']);

    options.goal = options.goal || this.target;
    options.commitPrefix = options.commitPrefix || '%s';

    if (options.goal === 'deploy') {
      requireOptionProps(options, ['url']);
      deploy(this);
    } else if (options.goal === 'install') {
      install(this);
    } else if (options.goal === 'release') {
      requireOptionProps(options, ['url']);
      release(this, version, mode);
    }
  });

  function install(task) {
    var pkg = grunt.file.readJSON('package.json');
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven:package',
      'maven:install-file');
  }

  function deploy(task) {
    var pkg = grunt.file.readJSON('package.json');
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven:package',
      'maven:deploy-file');
  }

  function release(task, version, mode) {
    var pkg = grunt.file.readJSON('package.json');
    var options = task.options({
      artifactId: pkg.name,
      packaging: 'zip',
      mode: 'minor'
    });

    if (version && !mode && isValidMode(version)) {
      mode = version;
      version = null;
    }

    options.mode = mode || options.mode;
    options.version = version || pkg.version.substr(0, pkg.version.length - '-SNAPSHOT'.length);

    if (options.nextVersion === 'null-SNAPSHOT') {
      grunt.fail.fatal('Failed to determine next development version ' +
        'based on version (' + options.version.cyan +
        ') and mode (' + options.mode.cyan + ')');
    }
    options.nextVersion = semver.inc(options.version, options.mode) + '-SNAPSHOT';
    if (options.nextVersion === 'null-SNAPSHOT') {
      grunt.fail.fatal('Failed to determine next development version ' +
        'based on version (' + options.version.cyan +
        ') and mode (' + options.mode.cyan + ')');
    }

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven:version:' + options.version,
      'maven:package',
      'maven:deploy-file',
      'maven:version:' + options.nextVersion + ':deleteTag');
  }

  function getFileNameBase(options) {
	  return options.artifactId + '-' + options.version
      + (options.classifier ? '-' + options.classifier : '');
  }

  function guaranteeFileName(options) {
    if (!options.file) {
      options.file = getFileNameBase(options) + '.' + options.packaging;
    }
  }

  function configureDestination(options, task) {
    if (typeof options.injectDestFolder === 'undefined' || options.injectDestFolder === true) {
      task.files = injectDestFolder(getFileNameBase(options), task.files);
    }
    grunt.config.set('grunt.maven.commitPrefix', options.commitPrefix);
  }

  function configureMaven(options, task) {
    grunt.config.set('maven.package.options', { archive: options.file, mode: options.packaging });
    grunt.config.set('maven.package.files', task.files);
    grunt.config.set('maven.deploy-file.options', options);
    grunt.config.set('maven.install-file.options', options);
  }

  grunt.registerTask('maven:package', function() {
    var compress = require('grunt-contrib-compress/tasks/lib/compress')(grunt);
    compress.options = grunt.config('maven.package.options');
    compress.tar(grunt.config('maven.package.files'), this.async());
  });

  grunt.registerTask('maven:install-file', function() {
    var options = grunt.config('maven.install-file.options');

    options.packaging = (options.type === 'war') ? 'war' : options.packaging;
    if (options.packaging === 'war'){
        options.file = renameForWarTypeArtifacts(options.file);
    }

    var args = [ 'install:install-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.classifier) {
    	args.push('-Dclassifier=' + options.classifier);
    }
    // The lack of a space after the -s is critical
    // otherwise the path will be processed by maven incorrectly.
    if (options.settingsXml) {
      args.push('-s' + options.settingsXml);
    }

    var done = this.async();
    var msg = 'Installing to maven...';
    grunt.verbose.write(msg);
    grunt.util.spawn({ cmd: 'mvn', args: args, opts: {stdio: 'inherit'} }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to install to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Installed ' + options.file.cyan);
      }
      done(err);
    });
  });

  grunt.registerTask('maven:deploy-file', function() {
    var options = grunt.config('maven.deploy-file.options');

    options.packaging = (options.type === 'war') ? 'war' : options.packaging;
    if (options.packaging === 'war'){
        options.file = renameForWarTypeArtifacts(options.file);
    }

    var args = [ 'deploy:deploy-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.classifier) {
    	args.push('-Dclassifier=' + options.classifier);
    }
    args.push('-Durl='          + options.url);
    if (options.repositoryId) {
      args.push('-DrepositoryId=' + options.repositoryId);
    }
    if (options.settingsXml) {
      // The lack of a space after the -s is critical
      // otherwise the path will be processed by maven incorrectly.
      args.push('-s' + options.settingsXml);
    }

    var done = this.async();
    var msg = 'Deploying to maven...';
    grunt.verbose.write(msg);
    grunt.util.spawn({ cmd: 'mvn', args: args, opts: {stdio: 'inherit'} }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to deploy to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Deployed ' + options.file.cyan + ' to ' + options.url.cyan);
      }
      done(err);
    });
  });

  grunt.registerTask('maven:version', 'Bumps version', function(version, deleteTag) {
    var done = this.async();
    var commitPrefix = grunt.config('grunt.maven.commitPrefix') || '';

    var msg = 'Bumping version to ' + version.cyan + '...';
    grunt.verbose.write(msg);

    grunt.util.spawn({ cmd: 'npm', args: ['version', version, '-m', commitPrefix + '%s'] }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to bump version to ' + version.cyan);
        return done(err);
      }
      grunt.verbose.ok();
      grunt.log.writeln('Version bumped to ' + version.cyan);
      if (deleteTag) {
        isGitRepo(function(isGit) {
          if (!isGit) { return done(); }
          msg = 'Deleting tag v' + version.cyan + '...';
          grunt.verbose.write(msg);
          grunt.util.spawn({ cmd: 'git', args: ['tag', '-d', 'v' + version] }, function(err, result, code) {
            if (err) {
              grunt.verbose.or.write(msg);
              grunt.log.error().error('Failed to delete tag ' + ('v' + version).cyan);
            } else {
              grunt.verbose.ok();
              grunt.log.writeln('Deleted tag ' + ('v' + version).cyan);
            }
            done(err);
          });
        });
      } else {
        done();
      }
    });
  });

  function isGitRepo(fn) {
    grunt.util.spawn({ cmd: 'git', args: ['status', '--porcelain'] }, function(err, result, code) {
      fn(!err);
    });
  }

  function isValidMode(mode) {
    var validModes = ['major', 'minor', 'patch', 'build'].join('|');

    return mode.indexOf('|') < 0 && validModes.indexOf(mode) >=0;
  }

  function requireOptionProps(options, props) {
    var msg = 'Verifying properties ' + grunt.log.wordlist(props) + ' exists in options...';
    grunt.verbose.write(msg);

    var failProps = props.filter(function(p) {
      return !options.hasOwnProperty(p);
    }).map(function(p) {
      return '"' + p + '"';
    });

    if (failProps.length === 0) {
      grunt.verbose.ok();
    } else {
      grunt.verbose.or.write(msg);
      grunt.log.error().error('Unable to process task.');
      throw grunt.util.error('Required options ' + failProps.join(', ') + ' missing.');
    }
  }

  function renameForWarTypeArtifacts(filename) {
    var warFileName = filename.replace('zip', 'war');
    try {
      fs.renameSync(filename, warFileName);
      return warFileName;
    } catch (e) {
      throw e;
    }
  }
};
<commit_msg>Adds support for jar files (in order to support generation of webjars - www.webjars.org); extracts duplicate code.<commit_after>/*
 * grunt-maven-tasks
 * https://github.com/smh/grunt-maven-tasks
 *
 * Copyright (c) 2013 Stein Martin Hustad
 * Licensed under the MIT license.
 */

'use strict';

var semver = require('semver');
var fs = require('fs');

function injectDestFolder(targetPath, files) {
  var path = require('path');
  files.forEach(function(file) {
    file.dest = path.join(targetPath, file.dest || '');
  });
  return files;
}

module.exports = function(grunt) {

  grunt.registerMultiTask('maven', 'Packages and deploys artifact to maven repo', function(version, mode) {
    var options = this.options();

    requireOptionProps(options, ['groupId']);

    options.goal = options.goal || this.target;
    options.commitPrefix = options.commitPrefix || '%s';

    if (options.goal === 'deploy') {
      requireOptionProps(options, ['url']);
      deploy(this);
    } else if (options.goal === 'install') {
      install(this);
    } else if (options.goal === 'release') {
      requireOptionProps(options, ['url']);
      release(this, version, mode);
    }
  });

  function install(task) {
    var pkg = grunt.file.readJSON('package.json');
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven:package',
      'maven:install-file');
  }

  function deploy(task) {
    var pkg = grunt.file.readJSON('package.json');
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven:package',
      'maven:deploy-file');
  }

  function release(task, version, mode) {
    var pkg = grunt.file.readJSON('package.json');
    var options = task.options({
      artifactId: pkg.name,
      packaging: 'zip',
      mode: 'minor'
    });

    if (version && !mode && isValidMode(version)) {
      mode = version;
      version = null;
    }

    options.mode = mode || options.mode;
    options.version = version || pkg.version.substr(0, pkg.version.length - '-SNAPSHOT'.length);

    if (options.nextVersion === 'null-SNAPSHOT') {
      grunt.fail.fatal('Failed to determine next development version ' +
        'based on version (' + options.version.cyan +
        ') and mode (' + options.mode.cyan + ')');
    }
    options.nextVersion = semver.inc(options.version, options.mode) + '-SNAPSHOT';
    if (options.nextVersion === 'null-SNAPSHOT') {
      grunt.fail.fatal('Failed to determine next development version ' +
        'based on version (' + options.version.cyan +
        ') and mode (' + options.mode.cyan + ')');
    }

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven:version:' + options.version,
      'maven:package',
      'maven:deploy-file',
      'maven:version:' + options.nextVersion + ':deleteTag');
  }

  function getFileNameBase(options) {
	  return options.artifactId + '-' + options.version
      + (options.classifier ? '-' + options.classifier : '');
  }

  function guaranteeFileName(options) {
    if (!options.file) {
      options.file = getFileNameBase(options) + '.' + options.packaging;
    }
  }

  function configureDestination(options, task) {
    if (typeof options.injectDestFolder === 'undefined' || options.injectDestFolder === true) {
      task.files = injectDestFolder(getFileNameBase(options), task.files);
    }
    grunt.config.set('grunt.maven.commitPrefix', options.commitPrefix);
  }

  function configureMaven(options, task) {
    grunt.config.set('maven.package.options', { archive: options.file, mode: options.packaging });
    grunt.config.set('maven.package.files', task.files);
    grunt.config.set('maven.deploy-file.options', options);
    grunt.config.set('maven.install-file.options', options);
  }

  grunt.registerTask('maven:package', function() {
    var compress = require('grunt-contrib-compress/tasks/lib/compress')(grunt);
    compress.options = grunt.config('maven.package.options');
    compress.tar(grunt.config('maven.package.files'), this.async());
  });

  grunt.registerTask('maven:install-file', function() {
    var options = grunt.config('maven.install-file.options');

    options.file = renameForKnownPackageTypeArtifacts(options.file, options.packaging);

    var args = [ 'install:install-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.classifier) {
    	args.push('-Dclassifier=' + options.classifier);
    }
    // The lack of a space after the -s is critical
    // otherwise the path will be processed by maven incorrectly.
    if (options.settingsXml) {
      args.push('-s' + options.settingsXml);
    }

    var done = this.async();
    var msg = 'Installing to maven...';
    grunt.verbose.write(msg);
    grunt.util.spawn({ cmd: 'mvn', args: args, opts: {stdio: 'inherit'} }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to install to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Installed ' + options.file.cyan);
      }
      done(err);
    });
  });

  grunt.registerTask('maven:deploy-file', function() {
    var options = grunt.config('maven.deploy-file.options');

    options.file = renameForKnownPackageTypeArtifacts(options.file, options.packaging);

    var args = [ 'deploy:deploy-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.classifier) {
    	args.push('-Dclassifier=' + options.classifier);
    }
    args.push('-Durl='          + options.url);
    if (options.repositoryId) {
      args.push('-DrepositoryId=' + options.repositoryId);
    }
    if (options.settingsXml) {
      // The lack of a space after the -s is critical
      // otherwise the path will be processed by maven incorrectly.
      args.push('-s' + options.settingsXml);
    }

    var done = this.async();
    var msg = 'Deploying to maven...';
    grunt.verbose.write(msg);
    grunt.util.spawn({ cmd: 'mvn', args: args, opts: {stdio: 'inherit'} }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to deploy to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Deployed ' + options.file.cyan + ' to ' + options.url.cyan);
      }
      done(err);
    });
  });

  grunt.registerTask('maven:version', 'Bumps version', function(version, deleteTag) {
    var done = this.async();
    var commitPrefix = grunt.config('grunt.maven.commitPrefix') || '';

    var msg = 'Bumping version to ' + version.cyan + '...';
    grunt.verbose.write(msg);

    grunt.util.spawn({ cmd: 'npm', args: ['version', version, '-m', commitPrefix + '%s'] }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to bump version to ' + version.cyan);
        return done(err);
      }
      grunt.verbose.ok();
      grunt.log.writeln('Version bumped to ' + version.cyan);
      if (deleteTag) {
        isGitRepo(function(isGit) {
          if (!isGit) { return done(); }
          msg = 'Deleting tag v' + version.cyan + '...';
          grunt.verbose.write(msg);
          grunt.util.spawn({ cmd: 'git', args: ['tag', '-d', 'v' + version] }, function(err, result, code) {
            if (err) {
              grunt.verbose.or.write(msg);
              grunt.log.error().error('Failed to delete tag ' + ('v' + version).cyan);
            } else {
              grunt.verbose.ok();
              grunt.log.writeln('Deleted tag ' + ('v' + version).cyan);
            }
            done(err);
          });
        });
      } else {
        done();
      }
    });
  });

  function isGitRepo(fn) {
    grunt.util.spawn({ cmd: 'git', args: ['status', '--porcelain'] }, function(err, result, code) {
      fn(!err);
    });
  }

  function isValidMode(mode) {
    var validModes = ['major', 'minor', 'patch', 'build'].join('|');

    return mode.indexOf('|') < 0 && validModes.indexOf(mode) >=0;
  }

  function requireOptionProps(options, props) {
    var msg = 'Verifying properties ' + grunt.log.wordlist(props) + ' exists in options...';
    grunt.verbose.write(msg);

    var failProps = props.filter(function(p) {
      return !options.hasOwnProperty(p);
    }).map(function(p) {
      return '"' + p + '"';
    });

    if (failProps.length === 0) {
      grunt.verbose.ok();
    } else {
      grunt.verbose.or.write(msg);
      grunt.log.error().error('Unable to process task.');
      throw grunt.util.error('Required options ' + failProps.join(', ') + ' missing.');
    }
  }

  function renameForKnownPackageTypeArtifacts(fileName) {

      if (options.packaging === 'war') {
          fileName = filename.replace('zip', 'war');
      } else if (options.packaging === 'jar') {
          fileName = filename.replace('zip', 'jar');
      }

      try {
          fs.renameSync(filename, fileName);
          return fileName;
      } catch (e) {
          throw e;
      }
  }
};
<|endoftext|>


<commit_before>module.exports = {
  staticFileGlobs: [
    '/index.html',
    '/manifest.json',
    '/bower_components/webcomponentsjs/webcomponents-lite.min.js'
  ],
  navigateFallback: '/index.html'
};
<commit_msg>precache default receipt<commit_after>module.exports = {
  staticFileGlobs: [
    '/index.html',
    '/manifest.json',
    '/bower_components/webcomponentsjs/webcomponents-lite.min.js',
    '/images/default-receipt.png'
  ],
  navigateFallback: '/index.html'
};
<|endoftext|>


<commit_before>/**
 * Infinia Press (TM) (R) (C)
 * ------------------------------
 * Passenger Pigeon
 * ------------------------------
 * Socket Controller
 * v1.2.0
 * Created and modified by Hundotte and xiurobert
 *
 */

var express = require('express'); // Get the module
var app = express(); // Create express by calling the prototype in var express
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
var config = require('./config.json');
// Command line arguments
var cmd = process.argv[2];
var redis = require('redis');
//var redisClient = redis.createClient();
var users = [];

var remove = function(array, item) {
  array.splice(array.indexOf(item), 1);
};

app.get('/', function(req, res) {
  /*
  var messages = redisClient.lrange('messages', 0, 99, function(err, reply) {
    if (!err) {
      var result = [];
      // Loop through the list, parsing each item into an object
      for (var msg in reply) result.push(JSON.parse(reply[msg]));
      // Pass the message list to the view
      res.sendFile(__dirname + '/view/index.html');
      io.emit('history', {
        messages: result
      });
    } else {
    */
  res.sendFile(__dirname + '/view/index.html');
  //}
  //})
});

app.use(express.static(__dirname + '/assets'));
app.use(express.static(__dirname + '/bower_components'));

io.on('connection', function(socket) {
  socket.on('chat message', function(msg) {
    //redisClient.lpush('messages', JSON.stringify(msg));
    //redisClient.ltrim('messages', 0, 99);
    io.to(socket.room).emit('chat message', msg, {
      username: socket.username,
      color: socket.color
    });
  });
  socket.on('typing', function() {
    io.to(socket.room).emit('typing', {
      username: socket.username,
      color: socket.color
    });
  });
  socket.on('file', function(url, ext) {
    if (["jpg", "png", "gif", "psd", "tiff"].indexOf(ext) > -1) {
      io.to(socket.room).emit('image', {
        image: true,
        buffer: url,
        ext: ext,
        sender: socket.username,
        color: socket.color
      });
    } else if (["mov", "mp4", "m4v"].indexOf(ext) > -1) {
      io.to(socket.room).emit('video', {
        video: true,
        buffer: url,
        ext: ext,
        sender: socket.username,
        color: socket.color
      });
    } else {
      io.to(socket.room).emit('document', {
        document: true,
        buffer: url,
        ext: ext,
        sender: socket.username,
        color: socket.color
      })
    }
  });
  socket.on('not typing', function() {
    io.to(socket.room).emit('not typing', {
      username: socket.username,
      color: socket.color
    });
  });
  socket.on('mute', function(user, command) {
    command = command.replace('/mute ', "");
    command = command.split(' ');
    if (command.length > 1){
      var target = command[0];
      var time = command[1];
      if (time.indexOf("s") >= 0) {
        time = time.replace('s', "");
        io.to(socket.room).emit('mute', {
          sender: user,
          target: target,
          duration: time * 1000
        });
      } else if (time.indexOf("h") >= 0) {
        time = time.replace('h', "");
        if (time > config.maxBanTime) {

        } else {
          io.to(socket.room).emit('mute', {
            sender: user,
            target: target,
            duration: time * 1000 * 60
          });
        }
      }
    }
  });
  socket.on('ban', function(user, command) {
    command = command.replace('/ban ', "");
    var target = command;
    io.to(socket.room).emit('ban', {
      sender: user,
      target: target,
      color: socket.color
    });
  });
  socket.on('spy', function(user) {
    io.to(socket.room).emit('spy', {
      user: user
    });
  });
  socket.on('unban', function(user, command) {
    command = command.replace('/unban ', "");
    var target = command;
    io.to(socket.room).emit('unban', {
      sender: user,
      target: target,
      color: socket.color
    });
  });
  socket.on('pm', function(user, command) {
    command = command.replace('/pm ', "");
    command = command.split('/');
    var target = command[0];
    var message = command[1]
    io.to(socket.room).emit('pm', {
      sender: user,
      target: target,
      message: message,
      color: socket.color
    });
  });
  socket.on('changetheme', function(usr, color) {
    socket.username = usr;
    socket.color = color;
    io.to(socket.room).emit('changetheme', {
      username: usr,
      color: socket.color
    });
  });
  socket.on('connection info', function(usr, color, room) {
    socket.username = usr;
    socket.color = color;
    socket.room = room;
    socket.join(socket.room);
    users[socket.room] = Object.prototype.toString.call(users[socket.room]) == "[object Array]" ? users[socket.room] : [];
    if (users[socket.room].indexOf(usr) > -1) {
      socket.emit('repeat username');
    } else {
      users[socket.room].push(usr);
      io.to(socket.room).emit('user add', {
        username: usr,
        color: color,
        online: users[socket.room]
      });
    }
  });
});

io.on('connection', function(socket) {
  //fs.readFile(__dirname + '/assets/pigeon-final.png', function(err, buf){
  // socket.emit('image', { image: true, buffer: buf.toString('base64') });
  // if(!err){
  //  console.log('image test success');
  // }
  //  });
  console.log('Passenger Pigeon >> a user connected');
  socket.on('disconnect', function() {
    socket.broadcast.emit('user left', {
      username: socket.username,
      color: socket.color,
      online: users[socket.room]
    });
    remove(users[socket.room], socket.username);
    console.log('Passenger Pigeon >> user disconnected');
  });
});

http.listen(process.env.PORT || config.port, function() {
  console.log('[PP-Start] Listening on localhost:' + config.port);
});<commit_msg>Testing a new addition. WIP<commit_after>/**
 * Infinia Press (TM) (R) (C)
 * ------------------------------
 * Passenger Pigeon
 * ------------------------------
 * Socket Controller
 * v1.2.0
 * Created and modified by Hundotte and xiurobert
 *
 */

var express = require('express'); // Get the module
var app = express(); // Create express by calling the prototype in var express
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
var config = require('./config.json');
// Command line arguments
var cmd = process.argv[2];
var redis = require('redis');
//var redisClient = redis.createClient();
var users = [];

var remove = function(array, item) {
  array.splice(array.indexOf(item), 1);
};

app.get('/', function(req, res) {
  /*
  var messages = redisClient.lrange('messages', 0, 99, function(err, reply) {
    if (!err) {
      var result = [];
      // Loop through the list, parsing each item into an object
      for (var msg in reply) result.push(JSON.parse(reply[msg]));
      // Pass the message list to the view
      res.sendFile(__dirname + '/view/index.html');
      io.emit('history', {
        messages: result
      });
    } else {
    */
  try{
    username = req.query.username;
  }catch{
  res.sendFile(__dirname + '/view/index.html');
  }
  //}
  //})
});

app.use(express.static(__dirname + '/assets'));
app.use(express.static(__dirname + '/bower_components'));

io.on('connection', function(socket) {
  socket.on('chat message', function(msg) {
    //redisClient.lpush('messages', JSON.stringify(msg));
    //redisClient.ltrim('messages', 0, 99);
    io.to(socket.room).emit('chat message', msg, {
      username: socket.username,
      color: socket.color
    });
  });
  socket.on('typing', function() {
    io.to(socket.room).emit('typing', {
      username: socket.username,
      color: socket.color
    });
  });
  socket.on('file', function(url, ext) {
    if (["jpg", "png", "gif", "psd", "tiff"].indexOf(ext) > -1) {
      io.to(socket.room).emit('image', {
        image: true,
        buffer: url,
        ext: ext,
        sender: socket.username,
        color: socket.color
      });
    } else if (["mov", "mp4", "m4v"].indexOf(ext) > -1) {
      io.to(socket.room).emit('video', {
        video: true,
        buffer: url,
        ext: ext,
        sender: socket.username,
        color: socket.color
      });
    } else {
      io.to(socket.room).emit('document', {
        document: true,
        buffer: url,
        ext: ext,
        sender: socket.username,
        color: socket.color
      })
    }
  });
  socket.on('not typing', function() {
    io.to(socket.room).emit('not typing', {
      username: socket.username,
      color: socket.color
    });
  });
  socket.on('mute', function(user, command) {
    command = command.replace('/mute ', "");
    command = command.split(' ');
    if (command.length > 1){
      var target = command[0];
      var time = command[1];
      if (time.indexOf("s") >= 0) {
        time = time.replace('s', "");
        io.to(socket.room).emit('mute', {
          sender: user,
          target: target,
          duration: time * 1000
        });
      } else if (time.indexOf("h") >= 0) {
        time = time.replace('h', "");
        if (time > config.maxBanTime) {

        } else {
          io.to(socket.room).emit('mute', {
            sender: user,
            target: target,
            duration: time * 1000 * 60
          });
        }
      }
    }
  });
  socket.on('ban', function(user, command) {
    command = command.replace('/ban ', "");
    var target = command;
    io.to(socket.room).emit('ban', {
      sender: user,
      target: target,
      color: socket.color
    });
  });
  socket.on('spy', function(user) {
    io.to(socket.room).emit('spy', {
      user: user
    });
  });
  socket.on('unban', function(user, command) {
    command = command.replace('/unban ', "");
    var target = command;
    io.to(socket.room).emit('unban', {
      sender: user,
      target: target,
      color: socket.color
    });
  });
  socket.on('pm', function(user, command) {
    command = command.replace('/pm ', "");
    command = command.split('/');
    var target = command[0];
    var message = command[1]
    io.to(socket.room).emit('pm', {
      sender: user,
      target: target,
      message: message,
      color: socket.color
    });
  });
  socket.on('changetheme', function(usr, color) {
    socket.username = usr;
    socket.color = color;
    io.to(socket.room).emit('changetheme', {
      username: usr,
      color: socket.color
    });
  });
  socket.on('connection info', function(usr, color, room) {
    socket.username = usr;
    socket.color = color;
    socket.room = room;
    socket.join(socket.room);
    users[socket.room] = Object.prototype.toString.call(users[socket.room]) == "[object Array]" ? users[socket.room] : [];
    if (users[socket.room].indexOf(usr) > -1) {
      socket.emit('repeat username');
    } else {
      users[socket.room].push(usr);
      io.to(socket.room).emit('user add', {
        username: usr,
        color: color,
        online: users[socket.room]
      });
    }
  });
});

io.on('connection', function(socket) {
  //fs.readFile(__dirname + '/assets/pigeon-final.png', function(err, buf){
  // socket.emit('image', { image: true, buffer: buf.toString('base64') });
  // if(!err){
  //  console.log('image test success');
  // }
  //  });
  console.log('Passenger Pigeon >> a user connected');
  socket.on('disconnect', function() {
    socket.broadcast.emit('user left', {
      username: socket.username,
      color: socket.color,
      online: users[socket.room]
    });
    remove(users[socket.room], socket.username);
    console.log('Passenger Pigeon >> user disconnected');
  });
});

http.listen(process.env.PORT || config.port, function() {
  console.log('[PP-Start] Listening on localhost:' + config.port);
});<|endoftext|>