<commit_before>// ext. libs
var fs = require('fs');
var https = require('https');
var esprima = require('esprima');
var markdown = require('markdown').markdown;
var Handlebars = require('handlebars');
var cheerio = require('cheerio');

module.exports = function(grunt) {

  // grunt task def.
  grunt.registerTask('documantix', 'Documents stuff.', function() {
    var done = this.async();
    var header = '';
    var footer = '';

    var config = grunt.config.get('documantix');
    var files = grunt.file.expand(config.src);

    var vars = config.options.vars;

    var numberOfFiles = files.length;
    var numberOfParsedFiles = 0;

    // load header
    https.get('https://raw.github.com/' + config.options.header, function(headRes) {
      headRes.on('data', function(d) {
        header += d;
      });

      headRes.on('end', function () {

    https.get('https://raw.github.com/' + config.options.footer, function(footRes) {
      footRes.on('data', function(d) {
        footer += d;
      });

      footRes.on('end', function () {

        files.forEach(function (file) {
          var comments = [];
          var parsedComments = [];
          var content = '';
          var contents = fs.readFileSync(file);
          // parse comments
          comments = esprima.parse(contents, {comment: true}).comments;

          comments.forEach(function (comment, idx) {
            if (comment.type !== 'Block') {
              return false;
            }

            var cv = comment.value.split('\n *');
            var pc = {annotations: {}, md: '', html: ''};

            cv.forEach(function (line) {
              if (line.trim() === '*') {
                return false;
              }

              if (line.trim().substr(0,1) === '@') {
                var p1 = line.trim().split('@');
                var p2 = [];
                p1.forEach(function (part) {
                  if (part !== '') {
                    p2.push(part);
                  }
                });

                var name = p2[0].substr(0, p2[0].indexOf(' '));
                var content = p2[0].substring(p2[0].indexOf(' ')).trim();

                if (!name) {
                  name = content;
                  content = true;
                }

                pc.annotations[name] =  content;
              } else {
                pc.md += line + '\n';
              }
            });

            pc.html = markdown.toHTML(pc.md);
            pc.html = (pc.annotations.method ? '
 .' + pc.annotations.method + '
' : '
' + pc.annotations.part + '
') + pc.html;

            if (pc.annotations.api) {
              parsedComments.push(pc);
            }
          });

          parsedComments.forEach(function (comment) {
            if (comment.annotations.api) {

              // do that  replacing thingie
              var $ = cheerio.load(comment.html);
              var $cde = $('code');

              $cde.each(function (idx, el) {
                if ($(el).html().substr(0, 10) === 'javascript') {
                  var contents = $(el).html().substring(10);
                  var plum = $('
' + contents + '
');
                  $('code').eq(idx).replaceWith(plum);
                }

                if ($(el).html().substr(0, 4) === 'html') {
                  var contents = $(el).html().substring(4);
                  var plum = $('
' + contents + '
');
                  $('code').eq(idx).replaceWith(plum);
                }

                if ($(el).html().substr(0, 3) === 'css') {
                  var contents = $(el).html().substring(3);
                  var plum = $('
' + contents + '
');
                  $('code').eq(idx).replaceWith(plum);
                }

                if ($(el).html().substr(0, 3) === 'bash') {
                  var contents = $(el).html().substring(3);
                  var plum = $('
' + contents + '
');
                  $('code').eq(idx).replaceWith(plum);
                }
              });

              comment.html = $.html();
              content += comment.html;
            }
          });

          // add sidebar nav
          var sidenav = '';
          var hasNavElements = false;
          parsedComments.forEach(function (comment) {
            if (comment.annotations.api && comment.annotations.method) {
              hasNavElements = true;
              sidenav += '
' + comment.annotations.method + '
'
            }
          });

          var oldContent = content;
          content = '
';

          if (hasNavElements) {
            content += '

' + Handlebars.compile(sidenav)(vars) + '

';
            content += '

' + oldContent + '

';
          } else {
            content += '
' + oldContent + '
';
          }

          content += '
';

              if (parsedComments && parsedComments[0]) {
                if (parsedComments[0].annotations.part && parsedComments[0].annotations.part.trim() !== '') {

                  grunt.file.write(config.options.target + '/' + parsedComments[0].annotations.part.toLowerCase() + '.html', Handlebars.compile(header)(vars) + Handlebars.compile(content)(vars) + Handlebars.compile(footer)(vars));
                  grunt.log.ok('File generated: ' + config.options.target + '/' + parsedComments[0].annotations.part.toLowerCase() + '.html');
                  numberOfParsedFiles++;
                } else {
                  numberOfParsedFiles++;
                }
              } else {
                numberOfParsedFiles++;
              }

              if (numberOfParsedFiles === numberOfFiles) {
                grunt.log.ok('All files generated');
                done();
              }

            });

          });
        });

      });
    });

  });
};
<commit_msg>Added conditional sidebar<commit_after>// ext. libs
var fs = require('fs');
var https = require('https');
var esprima = require('esprima');
var markdown = require('markdown').markdown;
var Handlebars = require('handlebars');
var cheerio = require('cheerio');

module.exports = function(grunt) {

  // grunt task def.
  grunt.registerTask('documantix', 'Documents stuff.', function() {
    var done = this.async();
    var header = '';
    var footer = '';

    var config = grunt.config.get('documantix');
    var files = grunt.file.expand(config.src);

    var vars = config.options.vars;

    var numberOfFiles = files.length;
    var numberOfParsedFiles = 0;

    // load header
    https.get('https://raw.github.com/' + config.options.header, function(headRes) {
      headRes.on('data', function(d) {
        header += d;
      });

      headRes.on('end', function () {

    https.get('https://raw.github.com/' + config.options.footer, function(footRes) {
      footRes.on('data', function(d) {
        footer += d;
      });

      footRes.on('end', function () {

        files.forEach(function (file) {
          var comments = [];
          var parsedComments = [];
          var content = '';
          var contents = fs.readFileSync(file);
          // parse comments
          comments = esprima.parse(contents, {comment: true}).comments;

          comments.forEach(function (comment, idx) {
            if (comment.type !== 'Block') {
              return false;
            }

            var cv = comment.value.split('\n *');
            var pc = {annotations: {}, md: '', html: ''};

            cv.forEach(function (line) {
              if (line.trim() === '*') {
                return false;
              }

              if (line.trim().substr(0,1) === '@') {
                var p1 = line.trim().split('@');
                var p2 = [];
                p1.forEach(function (part) {
                  if (part !== '') {
                    p2.push(part);
                  }
                });

                var name = p2[0].substr(0, p2[0].indexOf(' '));
                var content = p2[0].substring(p2[0].indexOf(' ')).trim();

                if (!name) {
                  name = content;
                  content = true;
                }

                pc.annotations[name] =  content;
              } else {
                pc.md += line + '\n';
              }
            });

            pc.html = markdown.toHTML(pc.md);
            pc.html = (pc.annotations.method ? '
 .' + pc.annotations.method + '
' : '
' + pc.annotations.part + '
') + pc.html;

            if (pc.annotations.api) {
              parsedComments.push(pc);
            }
          });

          parsedComments.forEach(function (comment) {
            if (comment.annotations.api) {

              // do that  replacing thingie
              var $ = cheerio.load(comment.html);
              var $cde = $('code');

              $cde.each(function (idx, el) {
                if ($(el).html().substr(0, 10) === 'javascript') {
                  var contents = $(el).html().substring(10);
                  var plum = $('
' + contents + '
');
                  $('code').eq(idx).replaceWith(plum);
                }

                if ($(el).html().substr(0, 4) === 'html') {
                  var contents = $(el).html().substring(4);
                  var plum = $('
' + contents + '
');
                  $('code').eq(idx).replaceWith(plum);
                }

                if ($(el).html().substr(0, 3) === 'css') {
                  var contents = $(el).html().substring(3);
                  var plum = $('
' + contents + '
');
                  $('code').eq(idx).replaceWith(plum);
                }

                if ($(el).html().substr(0, 3) === 'bash') {
                  var contents = $(el).html().substring(3);
                  var plum = $('
' + contents + '
');
                  $('code').eq(idx).replaceWith(plum);
                }
              });

              comment.html = $.html();
              content += comment.html;
            }
          });

          // add sidebar nav
          var sidenav = '';
          var hasNavElements = false;
          parsedComments.forEach(function (comment) {
            if (comment.annotations.api && comment.annotations.method) {
              hasNavElements = true;
              sidenav += '
' + comment.annotations.method + '
'
            }
          });

          var oldContent = content;
          content = '
';

          if (hasNavElements) {
            content += '

' + Handlebars.compile(sidenav)(vars) + '

';
            content += '

' + oldContent + '

';
          } else {
            content += '
' + oldContent + '
';
          }
          content += '
';
          vars.isSidebar = hasNavElements;

              if (parsedComments && parsedComments[0]) {
                if (parsedComments[0].annotations.part && parsedComments[0].annotations.part.trim() !== '') {

                  grunt.file.write(config.options.target + '/' + parsedComments[0].annotations.part.toLowerCase() + '.html', Handlebars.compile(header)(vars) + Handlebars.compile(content)(vars) + Handlebars.compile(footer)(vars));
                  grunt.log.ok('File generated: ' + config.options.target + '/' + parsedComments[0].annotations.part.toLowerCase() + '.html');
                  numberOfParsedFiles++;
                } else {
                  numberOfParsedFiles++;
                }
              } else {
                numberOfParsedFiles++;
              }

              if (numberOfParsedFiles === numberOfFiles) {
                grunt.log.ok('All files generated');
                done();
              }

            });

          });
        });

      });
    });

  });
};
<|endoftext|>


<commit_before>'use strict';

/*
 * grunt-file-blocks
 * https://github.com/rrharvey/grunt-file-blocks
 *
 * Copyright (c) 2013 Ryan Harvey
 * Licensed under the MIT license.
 */

var File = require('../lib/file');
var FileProcessor = require('../lib/fileprocessor');
var BlockConfig = require('../lib/blockconfig');
var grunt = require('grunt');
var _ = require('lodash');

module.exports = function (grunt) {
    var TASKNAME = 'fileblocks';

    var overwriteProps = _.partialRight(_.assign, function (a, b) {
        return typeof b === 'undefined' ? a : b;
    });

    /**
     * Normalize and return block configurations from the Gruntfile.
     * @param {Object[]|Object.<string, object>} blocks - The block configurations from the Gruntfile.
     * @returns {BlockConfig[]}
     */
    var getConfigs = function (data, options) {
        var configs = [];

        if (_.isArray(data)) {
            _(data).forEach(function (block) {
                configs.push(new BlockConfig(block.name, block, options));
            });
        } else if (_.isPlainObject(data)) {
            _.forOwn(data, function (value, name) {
                configs.push(new BlockConfig(name, value, options));
            });
        } else {
            grunt.warn('Block configuration must be an array or object.');
        }

        return configs;
    };

    /**
     * Validate the source-destination file mapping.
     * @param {Object} A source-destination file mapping.
     */
    var validateFile = function (file) {
        if (file.src.length > 1) {
            var ignored = file.src.splice(1);
            grunt.log.errorlns('Expected a single source file. Ignoring ' + ignored.join(', ') + '.');
        }

        if (!file.src[0]) {
            grunt.warn('Source files not found for pattern "' + file.orig.src[0] + '".');
        }

        if (!grunt.file.exists(file.src[0])) {
            grunt.warn('Source file ' + file.src[0] + ' not found.');
        }
    };

    grunt.registerMultiTask(TASKNAME, 'Prepares a block in a file by inserting or removing a line (script tag, link, or reference) for each file matching a specified pattern.', function () {
        // Merge task-specific and/or target-specific options with these defaults.
        var options = this.options({
            removeBlock: false,
            removeAnchors: false,
            removeFiles: false
        });

        this.files.forEach(function (file) {
            validateFile(file);
            var srcPath = file.src[0];
            var destPath = file.dest;

            if (!!file.blocks) {
                // There are blocks are defined
                overwriteProps(options, file.options);
                var configs = getConfigs(file.blocks, options);
                var srcFile = new File(srcPath).load();
                var processor = new FileProcessor(srcFile);
                var blocks = processor.getBlocks(configs);

                grunt.log.debug('Source file before processing.');
                grunt.log.debug(srcFile.content);

                blocks.forEach(function (block) {
                    block.updateFiles();
                    processor.processBlock(block);
                });

                grunt.log.debug('Source file after processing.');
                grunt.log.debug(srcFile.content);

                var updatedBlocks = blocks.filter(function (block) {
                    return block.changed;
                });

                if (updatedBlocks.length > 0) {
                    srcFile.save(destPath);
                }
            }
        });
    });
};
<commit_msg>Copy target level config for each source file. Fixes #1.<commit_after>'use strict';

/*
 * grunt-file-blocks
 * https://github.com/rrharvey/grunt-file-blocks
 *
 * Copyright (c) 2013 Ryan Harvey
 * Licensed under the MIT license.
 */

var File = require('../lib/file');
var FileProcessor = require('../lib/fileprocessor');
var BlockConfig = require('../lib/blockconfig');
var grunt = require('grunt');
var _ = require('lodash');

module.exports = function (grunt) {
    var TASKNAME = 'fileblocks';

    var overwriteProps = _.partialRight(_.assign, function (a, b) {
        return typeof b === 'undefined' ? a : b;
    });

    /**
     * Normalize and return block configurations from the Gruntfile.
     * @param {Object[]|Object.<string, object>} blocks - The block configurations from the Gruntfile.
     * @returns {BlockConfig[]}
     */
    var getConfigs = function (data, options) {
        var configs = [];

        if (_.isArray(data)) {
            _(data).forEach(function (block) {
                configs.push(new BlockConfig(block.name, block, options));
            });
        } else if (_.isPlainObject(data)) {
            _.forOwn(data, function (value, name) {
                configs.push(new BlockConfig(name, value, options));
            });
        } else {
            grunt.warn('Block configuration must be an array or object.');
        }

        return configs;
    };

    /**
     * Validate the source-destination file mapping.
     * @param {Object} A source-destination file mapping.
     */
    var validateFile = function (file) {
        if (file.src.length > 1) {
            var ignored = file.src.splice(1);
            grunt.log.errorlns('Expected a single source file. Ignoring ' + ignored.join(', ') + '.');
        }

        if (!file.src[0]) {
            grunt.warn('Source files not found for pattern "' + file.orig.src[0] + '".');
        }

        if (!grunt.file.exists(file.src[0])) {
            grunt.warn('Source file ' + file.src[0] + ' not found.');
        }
    };

    grunt.registerMultiTask(TASKNAME, 'Prepares a block in a file by inserting or removing a line (script tag, link, or reference) for each file matching a specified pattern.', function () {
        // Merge task-specific and/or target-specific options with these defaults.
        var options = this.options({
            removeBlock: false,
            removeAnchors: false,
            removeFiles: false
        });

        this.files.forEach(function (file) {
            validateFile(file);
            var srcPath = file.src[0];
            var destPath = file.dest;

            if (!!file.blocks) {
                // There are blocks are defined
                var targetOpts = _.clone(options);
                overwriteProps(targetOpts, file.options);
                var configs = getConfigs(file.blocks, targetOpts);
                var srcFile = new File(srcPath).load();
                var processor = new FileProcessor(srcFile);
                var blocks = processor.getBlocks(configs);

                grunt.log.debug('Source file before processing.');
                grunt.log.debug(srcFile.content);

                blocks.forEach(function (block) {
                    block.updateFiles();
                    processor.processBlock(block);
                });

                grunt.log.debug('Source file after processing.');
                grunt.log.debug(srcFile.content);

                var updatedBlocks = blocks.filter(function (block) {
                    return block.changed;
                });

                if (updatedBlocks.length > 0) {
                    srcFile.save(destPath);
                }
            }
        });
    });
};
<|endoftext|>


<commit_before>'use strict';
var
  xpath = require('xpath'),
  xmldom = require('xmldom'),
  js2xmlparser = require("js2xmlparser"),
  xml2js = require("xml2js"),
  fs = require('fs'),
  merge = require("deepmerge");

var namespaces = {
  "default": "http://www.w3.org/ns/widgets",
  "cdv": "http://cordova.apache.org/ns/1.0",
  "gap": "http://phonegap.com/ns/1.0"
};

// builds a js2xmlparser-compatible object from cordova config options
var js2domjs = function(options) {
  var data = {"@": {}}, i, attr;
  // widget
  var attrs = ['id', 'version', 'android-versionCode', 'ios-CFBundleVersion'];
  attrs.forEach(function(attr) {
    if (typeof options[attr] !== "undefined") {
      data["@"][attr] = options[attr];
    }
  });
  //  name
  if (typeof options.name === "string") {
    data.name = options.name;
  }
  //  name
  if (typeof options.description === "string") {
    data.description = options.description;
  }
  // author
  if (typeof options.author === "object") {
    data.author = {"@": {}};
    Object.keys(options.author).forEach(function(prop) {
      if (prop === "name") {
        data.author["#"] = options.author[prop];
      } else {
        data.author["@"][prop] = options.author[prop];
      }
    });
  }
  // access
  if (typeof options.access === "object") {
    data.access = {
      "@": options.access
    };
  }
  // content
  if (typeof options.content === "object") {
    data.content = {
      "@": options.content
    };
  }
  // preferences
  if (typeof options.preferences == "object") {
    var preferences = [], key;
    for (key in options.preferences) {
      preferences.push({
        "@": {
          name: key,
          value: options.preferences[key]
        }
      });
    }
    data.preference = preferences;
  }
  // icons
  if (options.icons instanceof Array) {
    data.icon = options.icons.map(function(icon) {
      return {
        "@": icon
      };
    });
  }
  // screens
  if (options.screens instanceof Array) {
    data.screen = options.screens.map(function(screen) {
      return {
        "@": screen
      };
    });
  }
  // platforms
  if (typeof options.platforms == "object") {
    var platform, platforms = [];
    for (platform in options.platforms) {
      platforms.push(merge({
        "@": {
          name: platform
        }
      }, js2domjs(options.platforms[platform])));
    }
    data.platform = platforms;
  }
  // plugins
  if (typeof options.plugins == "object") {
    var plugin, plugins = [], params;
    for (plugin in options.plugins) {
      var pluginData = options.plugins[plugin];
      if (typeof pluginData == "string") {
        pluginData = {
          version: pluginData
        };
      }
      pluginData.name = plugin;
      params = [];
      if (pluginData.params) {
        for (var param in pluginData.params) {
          params.push({
            "@": {
              name: param,
              value: pluginData.params[param]
            }
          });
        }
        delete pluginData.params;
      }
      var pluginXmlJs = {
        "@": pluginData
      };
      if (params.length) {
        pluginXmlJs.param = params;
      }
      plugins.push(pluginXmlJs);
    }
    data["gap:plugin"] = plugins;
  }
  return data;
};

var dom2js = function(node) {
  var select = xpath.useNamespaces(namespaces);
  var result = {};
  var rootNode = select(".", node)[0];
  if (rootNode) {
    // top-level attributes
    var attrs = ['id', 'version', 'android-versionCode', 'ios-CFBundleVersion'];
    attrs.forEach(function(attr) {
      var value = rootNode.getAttribute(attr);
      if (value) {
        result[attr] = value;
      }
    });
    // name
    var nameNodes = select("./default:name", node);
    if (nameNodes.length && nameNodes[0].firstChild) {
      result.name = nameNodes[0].firstChild.nodeValue;
    }
    // description
    var descriptionNodes = select("./default:description", node);
    if (descriptionNodes.length && descriptionNodes[0].firstChild) {
      result.description = descriptionNodes[0].firstChild.nodeValue;
    }
    // author
    var authorNodes = select("./default:author", node);
    if (authorNodes.length) {
      var author = {
        email: authorNodes[0].getAttribute('email'),
        href: authorNodes[0].getAttribute('href')
      };
      if (authorNodes[0].firstChild) {
        author.name = authorNodes[0].firstChild.nodeValue;
      }
      result.author = author;
    }
    // preferences
    var preferenceNodes = select("./default:preference", node);
    if (preferenceNodes.length) {
      result.preferences = {};
      preferenceNodes.forEach(function(preferenceNode) {
        var name = preferenceNode.getAttribute('name');
        if (name) {
          var value = preferenceNode.getAttribute('value');
          result.preferences[name] = value;
        }
      });
    }
    // platforms
    var platformNodes = select("./default:platform", node);
    if (platformNodes.length) {
      result.platforms = {};
      platformNodes.forEach(function(platformNode) {
        var name = platformNode.getAttribute('name');
        if (name) {
          result.platforms[name] = dom2js(platformNode);
        }
      });
    }
    // plugins
    var pluginNodes = select("./gap:plugin", node);
    if (pluginNodes.length) {
      result.plugins = {};
      pluginNodes.forEach(function(pluginNode) {
        var name = pluginNode.getAttribute('name');
        if (name) {
          var version = pluginNode.getAttribute('version');
          var plugin = {
            version: version ? version : "",
            params: {}
          };
          var pluginParamNodes = select("./default:param", pluginNode);
          if (pluginParamNodes.length) {
            pluginParamNodes.forEach(function(pluginParamNode) {
              var name = pluginParamNode.getAttribute('name');
              if (name) {
                plugin.params[name] = pluginParamNode.getAttribute('value');
              }
            });
          }
          result.plugins[name] = plugin;
        }
      });
    }
    // icons
    var iconNodes = select("./default:icon", node);
    if (iconNodes.length) {
      result.icons = iconNodes.map(function(iconNode) {
        return {
          src: iconNode.getAttribute('src'),
          width: iconNode.getAttribute('width'),
          height: iconNode.getAttribute('height')
        };
      });
    }
    // screens
    var screenNodes = select("./default:screen", node);
    if (screenNodes.length) {
      result.screens = iconNodes.map(function(screenNode) {
        return {
          src: screenNode.getAttribute('src'),
          width: screenNode.getAttribute('width'),
          height: screenNode.getAttribute('height')
        };
      });
    }
    return result;
  }
};

function normalize(json) {
  // normalize config platforms
  if (json.platforms instanceof Array) {
    var platforms = {};
    for (var platform in options.config.platforms) {
      platforms[platform] = {};
    }
    json.platforms = platforms;
  }
  return json;
}

function Config() {
  // keep domjs-representation
  this.json = null;
  this.domjs = null;
}

Config.prototype.toJSON = function() {
  return this.json;
};

Config.prototype.toXML = function() {
  var xml;
  if (this.domjs) {
    var domjs = this.domjs;
    Object.keys(namespaces).forEach(function(ns) {
      domjs["@"][ns !== "default" ? "xmlns:" + ns : "xmlns"] = namespaces[ns];
    });
    xml = js2xmlparser( "widget", domjs );
  }
  return xml;
};

Config.prototype.load = function(file) {
  // load json
  var json, doc;
  // read object
  if (typeof file == "object") {
    if (file.documentElement || file.ownerDocument) {
      doc = file;
    } else {
      json = file;
    }
  }
  // read file
  if (!json && !doc) {
    var contents = fs.readFileSync(file, 'utf8');
    if (contents) {
      try {
        json = JSON.parse(contents);
      } catch(e) {
      }
      if (!json) {
        try {
          doc = new xmldom.DOMParser().parseFromString(contents);
        } catch(e) {
        }
      }
    }
  }

  if (json) {
    this.json = normalize(json);
    this.domjs = js2domjs(json);

  } else if (doc && contents) {

    // get json
    json = dom2js(doc.documentElement);
    this.json = normalize(json);

    // convert to domjs
    var domjs;
    var parser = new xml2js.Parser({attrkey: "@", charkey: "#"});
    parser.parseString(contents, function (err, result) {
      if (!err) {
        domjs = result["widget"];
      }
    });
    if (domjs) {
      this.domjs = domjs;
    }
  }

};

Config.prototype.save = function(dest) {
  fs.writeFileSync(dest, this.toXML());
};

module.exports = Config;<commit_msg>Exports instance<commit_after>'use strict';
var
  xpath = require('xpath'),
  xmldom = require('xmldom'),
  js2xmlparser = require("js2xmlparser"),
  xml2js = require("xml2js"),
  fs = require('fs'),
  merge = require("deepmerge");

var namespaces = {
  "default": "http://www.w3.org/ns/widgets",
  "cdv": "http://cordova.apache.org/ns/1.0",
  "gap": "http://phonegap.com/ns/1.0"
};

// builds a js2xmlparser-compatible object from cordova config options
var js2domjs = function(options) {
  var data = {"@": {}}, i, attr;
  // widget
  var attrs = ['id', 'version', 'android-versionCode', 'ios-CFBundleVersion'];
  attrs.forEach(function(attr) {
    if (typeof options[attr] !== "undefined") {
      data["@"][attr] = options[attr];
    }
  });
  //  name
  if (typeof options.name === "string") {
    data.name = options.name;
  }
  //  name
  if (typeof options.description === "string") {
    data.description = options.description;
  }
  // author
  if (typeof options.author === "object") {
    data.author = {"@": {}};
    Object.keys(options.author).forEach(function(prop) {
      if (prop === "name") {
        data.author["#"] = options.author[prop];
      } else {
        data.author["@"][prop] = options.author[prop];
      }
    });
  }
  // access
  if (typeof options.access === "object") {
    data.access = {
      "@": options.access
    };
  }
  // content
  if (typeof options.content === "object") {
    data.content = {
      "@": options.content
    };
  }
  // preferences
  if (typeof options.preferences == "object") {
    var preferences = [], key;
    for (key in options.preferences) {
      preferences.push({
        "@": {
          name: key,
          value: options.preferences[key]
        }
      });
    }
    data.preference = preferences;
  }
  // icons
  if (options.icons instanceof Array) {
    data.icon = options.icons.map(function(icon) {
      return {
        "@": icon
      };
    });
  }
  // screens
  if (options.screens instanceof Array) {
    data.screen = options.screens.map(function(screen) {
      return {
        "@": screen
      };
    });
  }
  // platforms
  if (typeof options.platforms == "object") {
    var platform, platforms = [];
    for (platform in options.platforms) {
      platforms.push(merge({
        "@": {
          name: platform
        }
      }, js2domjs(options.platforms[platform])));
    }
    data.platform = platforms;
  }
  // plugins
  if (typeof options.plugins == "object") {
    var plugin, plugins = [], params;
    for (plugin in options.plugins) {
      var pluginData = options.plugins[plugin];
      if (typeof pluginData == "string") {
        pluginData = {
          version: pluginData
        };
      }
      pluginData.name = plugin;
      params = [];
      if (pluginData.params) {
        for (var param in pluginData.params) {
          params.push({
            "@": {
              name: param,
              value: pluginData.params[param]
            }
          });
        }
        delete pluginData.params;
      }
      var pluginXmlJs = {
        "@": pluginData
      };
      if (params.length) {
        pluginXmlJs.param = params;
      }
      plugins.push(pluginXmlJs);
    }
    data["gap:plugin"] = plugins;
  }
  return data;
};

var dom2js = function(node) {
  var select = xpath.useNamespaces(namespaces);
  var result = {};
  var rootNode = select(".", node)[0];
  if (rootNode) {
    // top-level attributes
    var attrs = ['id', 'version', 'android-versionCode', 'ios-CFBundleVersion'];
    attrs.forEach(function(attr) {
      var value = rootNode.getAttribute(attr);
      if (value) {
        result[attr] = value;
      }
    });
    // name
    var nameNodes = select("./default:name", node);
    if (nameNodes.length && nameNodes[0].firstChild) {
      result.name = nameNodes[0].firstChild.nodeValue;
    }
    // description
    var descriptionNodes = select("./default:description", node);
    if (descriptionNodes.length && descriptionNodes[0].firstChild) {
      result.description = descriptionNodes[0].firstChild.nodeValue;
    }
    // author
    var authorNodes = select("./default:author", node);
    if (authorNodes.length) {
      var author = {
        email: authorNodes[0].getAttribute('email'),
        href: authorNodes[0].getAttribute('href')
      };
      if (authorNodes[0].firstChild) {
        author.name = authorNodes[0].firstChild.nodeValue;
      }
      result.author = author;
    }
    // preferences
    var preferenceNodes = select("./default:preference", node);
    if (preferenceNodes.length) {
      result.preferences = {};
      preferenceNodes.forEach(function(preferenceNode) {
        var name = preferenceNode.getAttribute('name');
        if (name) {
          var value = preferenceNode.getAttribute('value');
          result.preferences[name] = value;
        }
      });
    }
    // platforms
    var platformNodes = select("./default:platform", node);
    if (platformNodes.length) {
      result.platforms = {};
      platformNodes.forEach(function(platformNode) {
        var name = platformNode.getAttribute('name');
        if (name) {
          result.platforms[name] = dom2js(platformNode);
        }
      });
    }
    // plugins
    var pluginNodes = select("./gap:plugin", node);
    if (pluginNodes.length) {
      result.plugins = {};
      pluginNodes.forEach(function(pluginNode) {
        var name = pluginNode.getAttribute('name');
        if (name) {
          var version = pluginNode.getAttribute('version');
          var plugin = {
            version: version ? version : "",
            params: {}
          };
          var pluginParamNodes = select("./default:param", pluginNode);
          if (pluginParamNodes.length) {
            pluginParamNodes.forEach(function(pluginParamNode) {
              var name = pluginParamNode.getAttribute('name');
              if (name) {
                plugin.params[name] = pluginParamNode.getAttribute('value');
              }
            });
          }
          result.plugins[name] = plugin;
        }
      });
    }
    // icons
    var iconNodes = select("./default:icon", node);
    if (iconNodes.length) {
      result.icons = iconNodes.map(function(iconNode) {
        return {
          src: iconNode.getAttribute('src'),
          width: iconNode.getAttribute('width'),
          height: iconNode.getAttribute('height')
        };
      });
    }
    // screens
    var screenNodes = select("./default:screen", node);
    if (screenNodes.length) {
      result.screens = iconNodes.map(function(screenNode) {
        return {
          src: screenNode.getAttribute('src'),
          width: screenNode.getAttribute('width'),
          height: screenNode.getAttribute('height')
        };
      });
    }
    return result;
  }
};

function normalize(json) {
  // normalize config platforms
  if (json.platforms instanceof Array) {
    var platforms = {};
    for (var platform in options.config.platforms) {
      platforms[platform] = {};
    }
    json.platforms = platforms;
  }
  return json;
}

function Config(pkg) {
  // keep domjs-representation
  this.pkg = pkg;
  this.json = null;
  this.domjs = null;
}

Config.prototype.toJSON = function() {
  return this.json;
};

Config.prototype.toXML = function() {
  var xml;
  if (this.domjs) {
    var domjs = this.domjs;
    Object.keys(namespaces).forEach(function(ns) {
      domjs["@"][ns !== "default" ? "xmlns:" + ns : "xmlns"] = namespaces[ns];
    });
    xml = js2xmlparser( "widget", domjs );
  }
  return xml;
};

Config.prototype.load = function(file) {
  // load json
  var json, doc;
  // read object
  if (typeof file == "object") {
    if (file.documentElement || file.ownerDocument) {
      doc = file;
    } else {
      json = file;
    }
  }
  // read file
  if (!json && !doc) {
    var contents = fs.readFileSync(file, 'utf8');
    if (contents) {
      try {
        json = JSON.parse(contents);
      } catch(e) {
      }
      if (!json) {
        try {
          doc = new xmldom.DOMParser().parseFromString(contents);
        } catch(e) {
        }
      }
    }
  }

  if (json) {
    this.json = normalize(json);
    this.domjs = js2domjs(json);

  } else if (doc && contents) {

    // get json
    json = dom2js(doc.documentElement);
    this.json = normalize(json);

    // convert to domjs
    var domjs;
    var parser = new xml2js.Parser({attrkey: "@", charkey: "#"});
    parser.parseString(contents, function (err, result) {
      if (!err) {
        domjs = result["widget"];
      }
    });
    if (domjs) {
      this.domjs = domjs;
    }
  }

  return this.json;

};

Config.prototype.save = function(dest) {
  fs.writeFileSync(dest, this.toXML());
};

module.exports = new Config();<|endoftext|>


<commit_before>/*
 * grunt-php-config
 * https://github.com/mothepro/grunt-php-config
 *
 * Copyright (c) 2015 Maurice Prosper
 * Licensed under the MIT license.
 */

'use strict';
Array.prototype.clone = function() {
    return this.slice(0);
};

module.exports = function(grunt) {
    var sprintf = require('sprintf-js').sprintf;
    var _ = require('lodash');

    var constants = [];

    function makeConst(consts, parent, raw, allCaps) {
        var k, val, _raw, _allCaps, _parent;

        for(k in consts) {
            if(!consts.hasOwnProperty(k)) continue;

            // props
            val         = consts[k].value || consts[k]; // for shorthand
            _raw        = consts[k].raw || raw; // override
            _allCaps    = consts[k].allCaps || allCaps; // override

            // add the constant
            if(grunt.util.kindOf(val) === 'string')
                constants.push({
                    name: k,
                    value: val,
                    parent: parent,
                    raw: _raw,
                    allCaps: _allCaps
                });

            // loop through children
            if(grunt.util.kindOf(consts[k]) === 'object')
                if(_.without(Object.keys(consts[k]), 'value', 'raw', 'allCaps').length) {
                    _parent = parent.clone();
                    _parent.push(k);
                    makeConst(consts[k], _parent, _raw, _allCaps);
                }
        }
    }

    function write(type) {
        var data, name, value;

        switch(type) {
            case 'php':
                data = sprintf('<?php // Generated on %s\n', grunt.template.today('mmmm dS yyyy @ h:MM:ss TT'));

                constants.forEach(function(v) {
                    name = v.name;
                    value = v.value;

                    // add to prefix first namespace
                    name = sprintf('%s%s\\%s', (v.parent.length ? '\\' : ''), v.parent.join('\\'), name);

                    if(!v.raw)
                        value = sprintf("'%s'", grunt.config.escape(value));

                    if(v.allCaps)
                        name = name.toUpperCase();

                    data += sprintf('define(\'%s\', %s);\n', name, value);
                });

                break;

            default:
                grunt.fail.fatal(sprintf('Unknown type "%s".', type));
        }

        return data;
    }

    grunt.registerMultiTask('php_config', 'Builds a PHP config and constants file', function() {
        // Merge task-specific and/or target-specific options with these defaults.
        var options = this.options({
            type: 'php',
            allCaps: true,
            raw: false,

            constants: null
        }), out = '';

        if (typeof options.constants === 'object') {
            constants = [];
            makeConst(options.constants, [], options.raw, options.allCaps);
            out = write(options.type);

            // all good?
            if (!this.errorCount)
                this.files.forEach(function (f) {
                    grunt.file.write(f.dest, out);
                    grunt.log.ok(sprintf('%d constants saved in %s file "%s"', constants.length, options.type, f.dest));
                });

        }

        return !this.errorCount;
    });
};<commit_msg>Escape quotes properly<commit_after>/*
 * grunt-php-config
 * https://github.com/mothepro/grunt-php-config
 *
 * Copyright (c) 2015 Maurice Prosper
 * Licensed under the MIT license.
 */

'use strict';
Array.prototype.clone = function() {
    return this.slice(0);
};

module.exports = function(grunt) {
    var sprintf = require('sprintf-js').sprintf;
    var _ = require('lodash');

    var constants = [];

    function makeConst(consts, parent, raw, allCaps) {
        var k, val, _raw, _allCaps, _parent;

        for(k in consts) {
            if(!consts.hasOwnProperty(k)) continue;

            // props
            val         = consts[k].value || consts[k]; // for shorthand
            _raw        = consts[k].raw || raw; // override
            _allCaps    = consts[k].allCaps || allCaps; // override

            // add the constant
            if(grunt.util.kindOf(val) === 'string')
                constants.push({
                    name: k,
                    value: val,
                    parent: parent,
                    raw: _raw,
                    allCaps: _allCaps
                });

            // loop through children
            if(grunt.util.kindOf(consts[k]) === 'object')
                if(_.without(Object.keys(consts[k]), 'value', 'raw', 'allCaps').length) {
                    _parent = parent.clone();
                    _parent.push(k);
                    makeConst(consts[k], _parent, _raw, _allCaps);
                }
        }
    }

    function write(type) {
        var data, name, value;

        switch(type) {
            case 'php':
                data = sprintf('<?php // Generated on %s\n', grunt.template.today('mmmm dS yyyy @ h:MM:ss TT'));

                constants.forEach(function(v) {
                    name = v.name;
                    value = v.value;

                    // add to prefix first namespace
                    name = sprintf('%s%s\\%s', (v.parent.length ? '\\' : ''), v.parent.join('\\'), name);

                    if(!v.raw)
                        value = sprintf("'%s'", value.replace(/'/g, "\\'"));

                    if(v.allCaps)
                        name = name.toUpperCase();

                    data += sprintf('define(\'%s\', %s);\n', name, value);
                });

                break;

            default:
                grunt.fail.fatal(sprintf('Unknown type "%s".', type));
        }

        return data;
    }

    grunt.registerMultiTask('php_config', 'Builds a PHP config and constants file', function() {
        // Merge task-specific and/or target-specific options with these defaults.
        var options = this.options({
            type: 'php',
            allCaps: true,
            raw: false,

            constants: null
        }), out = '';

        if (typeof options.constants === 'object') {
            constants = [];
            makeConst(options.constants, [], options.raw, options.allCaps);
            out = write(options.type);

            // all good?
            if (!this.errorCount)
                this.files.forEach(function (f) {
                    grunt.file.write(f.dest, out);
                    grunt.log.ok(sprintf('%d constants saved in %s file "%s"', constants.length, options.type, f.dest));
                });

        }

        return !this.errorCount;
    });
};<|endoftext|>


<commit_before>// Include Gulp and Plugins
var _       = require('underscore');
var argv    = require('yargs').argv;
var fs      = require('fs');
var gulp    = require('gulp');
var mkdirp  = require('mkdirp');

// Task which takes care of the actual site build itself
gulp.task('site-build', function() {

    // Calling build method from statgen
    statgen.build();

    // siteData will hold the meta information for the site
    var siteData = {
        posts: [],
        pages: [],
        archive: [],
        tags: [],
        navigation: []
    };

    // Local functions
    readMD();
    createAuxData();
    createAllPages();

    function readMD() {

        // Validating if the directory does exist
        if(dirExists(paths.posts)) {

            // FileSystem will read the dir for posts and loop through each file
            fs.readdirSync(paths.posts).forEach(function(file) {

                // Return, if after the . split is not equal to the MD file extension
                if (file.split('.')[1] != 'md') {
                    return;
                }

                // Add meta-data to content via fm for the the posts method and it's corresponding
                // file using the UTF-8 format
                var data = fm(fs.readFileSync(paths.posts + file, 'utf8'));
                var post = data.attr;

                // Date formatting
                post.year      = moment(post.date).format('YYYY');
                post.niceDate  = moment(post.date).format('MMMM YYYY');
                post.shortDate = moment(post.date).format('MMM DD');

                // post.content is marked to the DOM Body Object
                post.content = marked(data.body);

                // Pushing tags to the siteData.tags array
                _.each(post.tags, function(tag){
                    siteData.tags.push(
                        {
                            tag: tag,
                            post: post
                        }
                    );
                });

                // Pushing posts to the siteData.posts array
                siteData.posts.push(post);
            });
        }

        // Validating if the directory does exist
        else if (dirExists(paths.pages)) {

            // FileSystem will read the dir for pages and loop through each file
            fs.readdirSync(paths.pages).forEach(function(file) {

                // Return, if after the . split is not equal to the MD file extension
                if (file.split('.')[1] != 'md') {
                    return
                };

                // Add meta-data to content via fm for the the pages method and it's corresponding
                // file using the UTF-8 format
                var data = fm(fs.readFileSync(paths.pages + file, 'utf8'));
                var page = data.attr;

                // page.content is marked to the DOM Body Object
                page.content = marked(data.body);

                // We'll then add all this to the siteData.pages empty array
                siteData.pages.push(page);
            });
        }
    }

    function createAuxData() {

        // Sort articles in decending order
        siteData.posts = _.sortBy(siteData.posts, 'date').reverse();

        // Get the very latest articles whilst abiding by the posts limit
        siteData.recentPosts = siteData.posts.slice(0, config.recentPostsLimit);

        // Create tags
        var postsByTag = _.groupBy(siteData.tags, 'tag');
        siteData.tags = [];

        // Produces a new array of values by mapping each value in list through a transformation function
        _.mapObject(postsByTag, function(val, key) {
            siteData.tags.push(
                {
                    name: key,
                    posts: val
                }
            );
        });

        //  Create archive by year
        var postsByYear = _.groupBy(siteData.posts, 'year');

        // Produces a new array of values by mapping each value in list through a transformation function
        _.mapObject(postsByYear, function(val, key) {
            siteData.archive.push(
                {
                    year: key,
                    posts: val
                }
            );
        });

        // We'll now reverse the siteData.archive array
        siteData.archive.reverse();

        //  Create navigation
        _.each(siteData.pages, function(page){

            // If there is navigation on page
            if(page.navigation) {

                // Push the following Object into siteData navigation Object array
                siteData.navigation.push(
                    {
                        slug: page.slug,
                        title: page.navigationTitle,
                        url: (page.slug === 'home') ? '/' : '/' + page.slug + '/',
                        active: false,
                        order: page.order
                    }
                );
            }
        });

        // Sort the Navigation by order
        siteData.navigation = _.sortBy(siteData.navigation, 'order');
    }

    function createAllPages() {

        // Looping through siteData.pages with callback
        _.each(siteData.pages, function(page) {

            var pageData = {
                page: page,
                navigation: siteData.navigation,
                recentPosts: siteData.recentPosts,
                archive: siteData.archive,
                config: config
            };

            _.each(siteData.navigation, function(item) {
                item.active = (item.slug == page.slug) ? true : false;
            });

            if (page.slug === 'home') {
                var path = paths.dist;
                pageData.pageTitle = setPageTitle(config.siteTitle);
                pageData.showRecent = true;
                pageData.isHome = true;
            } else {
                var path = paths.dist + page.slug + '/';
                pageData.pageTitle = setPageTitle(page.navigationTitle);
            }

            createPage(
                {
                    layout: page.layout,
                    pageData: pageData,
                    path: path
                }
            );
        });

        _.each(siteData.posts, function(post) {
            var pageData = {
                config: config,
                navigation: siteData.navigation,
                pageTitle: setPageTitle(post.title),
                post: post,
                recentPosts: siteData.recentPosts
            };

            // Resetting navigation active state
            _.forEach(siteData.navigation, function(item) {
                item.active = false;
            });

            createPage({
                layout: post.layout,
                path: paths.dist + post.year + '/' + post.slug + '/',
                pageData: pageData
            });
        });

        _.each(siteData.tags, function(tag) {
            var pageData = {
                config: config,
                navigation: siteData.navigation,
                pageTitle: setPageTitle('Tag: ' + tag.name),
                recentPosts: siteData.recentPosts,
                tag: tag
            };

            createPage(
                {
                    layout: 'tag',
                    path: paths.dist + '/tag/' + tag.name + '/',
                    pageData: pageData
                }
            );
        });

    }

    function createPage(data) {
        var html     = template(data.pageData);
        var layout   = fs.readFileSync(paths.layouts + data.layout + '.html', 'utf8');
        var template = handlebars.compile(layout)

        // Create a directory relative to data.path
        mkdirp(data.path, function(err) {

            // Error handler
            if(err) return console.log(err);

            // FileSystem will write to the path of index.html in html format
            fs.writeFile(data.path + 'index.html', html, function(err) {

                // Error handler
                if(err) return console.log(err);
            });
        });
    }

    function setPageTitle(title) {
        return title + ' - ' + config.author;
    }

    function capitalize(str) {
        return str[0].toUpperCase() + str.slice(1);
    }

    // Function to test code block for any errors
    function dirExists(path) {
        try {
            fs.statSync(path);
            return true;
        } catch(err) {
            return false;
        }
    }
});
<commit_msg>require statgen.js<commit_after>// Include Gulp and Plugins
var _       = require('underscore');
var argv    = require('yargs').argv;
var fs      = require('fs');
var gulp    = require('gulp');
var mkdirp  = require('mkdirp');

var statgen = require('./statgen');

// Task which takes care of the actual site build itself
gulp.task('site-build', function() {

    // Calling build method from statgen
    statgen.build();

    // siteData will hold the meta information for the site
    var siteData = {
        posts: [],
        pages: [],
        archive: [],
        tags: [],
        navigation: []
    };

    // Local functions
    readMD();
    createAuxData();
    createAllPages();

    function readMD() {

        // Validating if the directory does exist
        if(dirExists(paths.posts)) {

            // FileSystem will read the dir for posts and loop through each file
            fs.readdirSync(paths.posts).forEach(function(file) {

                // Return, if after the . split is not equal to the MD file extension
                if (file.split('.')[1] != 'md') {
                    return;
                }

                // Add meta-data to content via fm for the the posts method and it's corresponding
                // file using the UTF-8 format
                var data = fm(fs.readFileSync(paths.posts + file, 'utf8'));
                var post = data.attr;

                // Date formatting
                post.year      = moment(post.date).format('YYYY');
                post.niceDate  = moment(post.date).format('MMMM YYYY');
                post.shortDate = moment(post.date).format('MMM DD');

                // post.content is marked to the DOM Body Object
                post.content = marked(data.body);

                // Pushing tags to the siteData.tags array
                _.each(post.tags, function(tag){
                    siteData.tags.push(
                        {
                            tag: tag,
                            post: post
                        }
                    );
                });

                // Pushing posts to the siteData.posts array
                siteData.posts.push(post);
            });
        }

        // Validating if the directory does exist
        else if (dirExists(paths.pages)) {

            // FileSystem will read the dir for pages and loop through each file
            fs.readdirSync(paths.pages).forEach(function(file) {

                // Return, if after the . split is not equal to the MD file extension
                if (file.split('.')[1] != 'md') {
                    return
                };

                // Add meta-data to content via fm for the the pages method and it's corresponding
                // file using the UTF-8 format
                var data = fm(fs.readFileSync(paths.pages + file, 'utf8'));
                var page = data.attr;

                // page.content is marked to the DOM Body Object
                page.content = marked(data.body);

                // We'll then add all this to the siteData.pages empty array
                siteData.pages.push(page);
            });
        }
    }

    function createAuxData() {

        // Sort articles in decending order
        siteData.posts = _.sortBy(siteData.posts, 'date').reverse();

        // Get the very latest articles whilst abiding by the posts limit
        siteData.recentPosts = siteData.posts.slice(0, config.recentPostsLimit);

        // Create tags
        var postsByTag = _.groupBy(siteData.tags, 'tag');
        siteData.tags = [];

        // Produces a new array of values by mapping each value in list through a transformation function
        _.mapObject(postsByTag, function(val, key) {
            siteData.tags.push(
                {
                    name: key,
                    posts: val
                }
            );
        });

        //  Create archive by year
        var postsByYear = _.groupBy(siteData.posts, 'year');

        // Produces a new array of values by mapping each value in list through a transformation function
        _.mapObject(postsByYear, function(val, key) {
            siteData.archive.push(
                {
                    year: key,
                    posts: val
                }
            );
        });

        // We'll now reverse the siteData.archive array
        siteData.archive.reverse();

        //  Create navigation
        _.each(siteData.pages, function(page){

            // If there is navigation on page
            if(page.navigation) {

                // Push the following Object into siteData navigation Object array
                siteData.navigation.push(
                    {
                        slug: page.slug,
                        title: page.navigationTitle,
                        url: (page.slug === 'home') ? '/' : '/' + page.slug + '/',
                        active: false,
                        order: page.order
                    }
                );
            }
        });

        // Sort the Navigation by order
        siteData.navigation = _.sortBy(siteData.navigation, 'order');
    }

    function createAllPages() {

        // Looping through siteData.pages with callback
        _.each(siteData.pages, function(page) {

            var pageData = {
                page: page,
                navigation: siteData.navigation,
                recentPosts: siteData.recentPosts,
                archive: siteData.archive,
                config: config
            };

            _.each(siteData.navigation, function(item) {
                item.active = (item.slug == page.slug) ? true : false;
            });

            if (page.slug === 'home') {
                var path = paths.dist;
                pageData.pageTitle = setPageTitle(config.siteTitle);
                pageData.showRecent = true;
                pageData.isHome = true;
            } else {
                var path = paths.dist + page.slug + '/';
                pageData.pageTitle = setPageTitle(page.navigationTitle);
            }

            createPage(
                {
                    layout: page.layout,
                    pageData: pageData,
                    path: path
                }
            );
        });

        _.each(siteData.posts, function(post) {
            var pageData = {
                config: config,
                navigation: siteData.navigation,
                pageTitle: setPageTitle(post.title),
                post: post,
                recentPosts: siteData.recentPosts
            };

            // Resetting navigation active state
            _.forEach(siteData.navigation, function(item) {
                item.active = false;
            });

            createPage({
                layout: post.layout,
                path: paths.dist + post.year + '/' + post.slug + '/',
                pageData: pageData
            });
        });

        _.each(siteData.tags, function(tag) {
            var pageData = {
                config: config,
                navigation: siteData.navigation,
                pageTitle: setPageTitle('Tag: ' + tag.name),
                recentPosts: siteData.recentPosts,
                tag: tag
            };

            createPage(
                {
                    layout: 'tag',
                    path: paths.dist + '/tag/' + tag.name + '/',
                    pageData: pageData
                }
            );
        });

    }

    function createPage(data) {
        var html     = template(data.pageData);
        var layout   = fs.readFileSync(paths.layouts + data.layout + '.html', 'utf8');
        var template = handlebars.compile(layout)

        // Create a directory relative to data.path
        mkdirp(data.path, function(err) {

            // Error handler
            if(err) return console.log(err);

            // FileSystem will write to the path of index.html in html format
            fs.writeFile(data.path + 'index.html', html, function(err) {

                // Error handler
                if(err) return console.log(err);
            });
        });
    }

    function setPageTitle(title) {
        return title + ' - ' + config.author;
    }

    function capitalize(str) {
        return str[0].toUpperCase() + str.slice(1);
    }

    // Function to test code block for any errors
    function dirExists(path) {
        try {
            fs.statSync(path);
            return true;
        } catch(err) {
            return false;
        }
    }
});
<|endoftext|>


<commit_before>/*
* grunt-tfs-unlock
* https://github.com/danactive/grunt-tfs-unlock
*
* Copyright (c) 2013 Dan BROOKS
* 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('tfs-unlock', 'Checkout TFS files', function() {
		var tfs = require('./../node_modules/tfs-unlock/tfs-unlock.js'),
			options = this.options();

		tfs.init({
			"callback": grunt.task.current.async(),
			"visualStudioPath": tfs[options.tfsPath[0]][options.tfsPath[1]]
		});

		// Iterate over all specified file groups.
		this.files.forEach(function (file) {
			file.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;
				}
				console.log(tfs[options.action]([filepath]));
				return true;
			});
		});
	});
};
<commit_msg>Use VS auto-discovery if options.tfsPath is not specified<commit_after>/*
* grunt-tfs-unlock
* https://github.com/danactive/grunt-tfs-unlock
*
* Copyright (c) 2013 Dan BROOKS
* 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('tfs-unlock', 'Checkout TFS files', function() {
		var tfs = require('./../node_modules/tfs-unlock/tfs-unlock.js'),
			options = this.options();

		if (options.tfsPath && options.tfsPath.length >= 2) {
			tfs.init({
				"callback": grunt.task.current.async(),
				"visualStudioPath": tfs[options.tfsPath[0]][options.tfsPath[1]]
			});
		} else {
			tfs.init({
				"callback": grunt.task.current.async()
			});
		}

		// Iterate over all specified file groups.
		this.files.forEach(function (file) {
			file.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;
				}
				console.log(tfs[options.action]([filepath]));
				return true;
			});
		});
	});
};
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  appveyor: '[![Windows Build Status](https://img.shields.io/appveyor/ci/{%= repository %}.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/{%= repository %})',

  bower: '[![Bower version](https://img.shields.io/bower/v/{%= name %}.svg?style=flat)]',

  travis: '[![Build Status](https://img.shields.io/travis/{%= repository %}.svg?style=flat)](https://travis-ci.org/{%= repository %})',

  travisLinus: '[![Linux Build Status](https://img.shields.io/travis/{%= repository %}.svg?style=flat&label=Travis)](https://travis-ci.org/{%= repository %})',

  fury: '[![NPM version](https://img.shields.io/npm/v/{%= name %}.svg?style=flat)](https://www.npmjs.com/package/{%= name %})',

  gitter: '[![Gitter](https://badges.gitter.im/join_chat.svg)](https://gitter.im/{%= repository %})',

  npm: '[![NPM version](https://img.shields.io/npm/v/{%= name %}.svg?style=flat)](https://www.npmjs.com/package/{%= name %})',

  downloads: '[![NPM downloads](https://img.shields.io/npm/dm/{%= name %}.svg?style=flat)](https://npmjs.org/package/{%= name %})',

  coveralls: '[![Coverage Status](https://img.shields.io/coveralls/{%= repository %}.svg?style=flat)](https://coveralls.io/r/{%= repository %})'
};
<commit_msg>organize badges<commit_after>'use strict';

module.exports = {
  appveyor: '[![Windows Build Status](https://img.shields.io/appveyor/ci/{%= repository %}.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/{%= repository %})',

  bower: '[![Bower version](https://img.shields.io/bower/v/{%= name %}.svg?style=flat)]',

  coveralls: '[![Coverage Status](https://img.shields.io/coveralls/{%= repository %}.svg?style=flat)](https://coveralls.io/r/{%= repository %})',

  downloads: '[![NPM monthly downloads](https://img.shields.io/npm/dm/{%= name %}.svg?style=flat)](https://npmjs.org/package/{%= name %})',

  'npm-downloads-monthly': '[![NPM monthly downloads](https://img.shields.io/npm/dm/{%= name %}.svg?style=flat)](https://npmjs.org/package/{%= name %})',

  'npm-downloads-total': '[![NPM total downloads](https://img.shields.io/npm/dt/{%= name %}.svg?style=flat)](https://npmjs.org/package/{%= name %})',

  gitter: '[![Gitter](https://badges.gitter.im/join_chat.svg)](https://gitter.im/{%= repository %})',

  npm: '[![NPM version](https://img.shields.io/npm/v/{%= name %}.svg?style=flat)](https://www.npmjs.com/package/{%= name %})',

  travis: '[![Build Status](https://img.shields.io/travis/{%= repository %}.svg?style=flat)](https://travis-ci.org/{%= repository %})',

  travisLinus: '[![Linux Build Status](https://img.shields.io/travis/{%= repository %}.svg?style=flat&label=Travis)](https://travis-ci.org/{%= repository %})',
};
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', '{views}');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());{css}
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
<commit_msg>gen: fix indentation in app.js<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', '{views}');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());{css}
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<|endoftext|>


<commit_before>var hash = location.hash.split('/'),
    API_HOST = 'http://' + window.location.hostname + ':5000/',
    API_BASE = API_HOST,
    REPO;

if (hash.length > 1) {
    REPO = hash[1] + '/' + hash[2];
    API_BASE += hash[1] + '/' + hash[2];
    initDashboard();
} else {
    getDefaultRepo();
}

/*
 * Bundle together different functions
 * used to load the widgets in the application
 */
function initDashboard () {
    populateOpenIssues();
    populateOpenPulls();
    populateTimeline();
    $('#user-repo').text(REPO);
    changeTabs();
}

/*
 * According to URL path
 * navigate to different tabs in the application
 */
function changeTabs() {

    var href = location.href.split('/');
    if (href.length > 6) {
        var tab = href.pop();
        var tabs = $('ul.menu li');
        tabs.each(function (idx, el) {
            var text = $(el).text().toLowerCase();
            if (text == tab) {
                $(el).trigger('click');
            }
        });
    }

}

function loadKibana() {
    $('#kibana-iframe').attr('src', 'kibana-latest/index.html');
}

function fitTabContainer () {
    var $container = $('#tab-container');
    $container.height($(window).height() - $container.offset().top - 20);
}

window.onresize = fitTabContainer;
fitTabContainer();

$('#repo-select-trigger').on('click', function () {

    var $container = $('.repo-select');
    var $repoList = $('ul', $container);

    $container.toggleClass('hidden');

    if (!$container.hasClass('hidden')) {
        getAvailableRepos(addRepos);
    } else {
        $('.show--fade-in').removeClass('show--fade-in');
        setTimeout(function () {
            $repoList.empty();
        }, 200);
    }
});

function getAvailableRepos (cb) {
    $.get(API_HOST + 'available_repos')
        .success(cb)
    .fail(function (data) {
        console.log('An error has occured');
    });
}

function addRepos (data) {
    var $container = $('.repo-select');

    var $repoList = $('ul', $container);
    data.data.forEach(function (repo) {
        var repoLink = document.createElement('a');
        var repoLI = document.createElement('li');
        repoLink.href = location.origin + '/#/' + repo;
        repoLink.textContent = repo;
        repoLink.target = '_blank';
        repoLI.appendChild(repoLink);
        repoLI = $(repoLI);
        repoLI.on('click', function (e) {
            e.preventDefault();
            loadDashboard(repoLink.href);
        });
        $repoList.append(repoLI);
    });

    $repoList.toggleClass('show--fade-in');
}

function getDefaultRepo() {
    getAvailableRepos(function (data) {
        setLocation(location.origin + '/#/' + data.data[0]); // load first repo
        hash = data.data[0].split('/');
        REPO = hash[0] + '/' + hash[1];
        API_BASE += hash[0] + '/' + hash[1];
        initDashboard();
    });
}

function setLocation (newlocation) {
    location.href = newlocation;
}

function loadDashboard (newlocation) {
    setLocation(newlocation);
    location.reload();
}

function populateOpenIssues() {
    $.get(API_BASE + "/issues_count").success(function (data) {
        var count = data.data.open;
        $('#open-issues-count').text(count);

        if (!count) {
            return;
        }

        var $p = $('#open-issues');
        $p.click(function () {
            var url = 'http://github.com/' + REPO + '/issues?state=open';
            window.location.href = url;
        });
        $p.addClass('clickable');
    });
}

function populateOpenPulls() {
    $.get(API_BASE + "/pulls_count").success(function (data) {
        var count = data.data.open;
        $('#open-pulls-count').text(count);

        if (!count) {
            return;
        }

        var $p = $('#open-pulls');
        $p.click(function () {
            var url = 'http://github.com/' + REPO + '/pulls?state=open';
            window.location.href = url;
        });
        $p.addClass('clickable');
    });
}

function logFailure(fail) {
    console.log("Trouble getting data. API server down?");
    console.log(fail);
}
<commit_msg>allow clicking anywhere to kill repo select popup; #61<commit_after>var hash = location.hash.split('/'),
    API_HOST = 'http://' + window.location.hostname + ':5000/',
    API_BASE = API_HOST,
    REPO;

if (hash.length > 1) {
    REPO = hash[1] + '/' + hash[2];
    API_BASE += hash[1] + '/' + hash[2];
    initDashboard();
} else {
    getDefaultRepo();
}

/*
 * Bundle together different functions
 * used to load the widgets in the application
 */
function initDashboard () {
    populateOpenIssues();
    populateOpenPulls();
    populateTimeline();
    $('#user-repo').text(REPO);
    changeTabs();
}

/*
 * According to URL path
 * navigate to different tabs in the application
 */
function changeTabs() {

    var href = location.href.split('/');
    if (href.length > 6) {
        var tab = href.pop();
        var tabs = $('ul.menu li');
        tabs.each(function (idx, el) {
            var text = $(el).text().toLowerCase();
            if (text == tab) {
                $(el).trigger('click');
            }
        });
    }

}

function loadKibana() {
    $('#kibana-iframe').attr('src', 'kibana-latest/index.html');
}

function fitTabContainer () {
    var $container = $('#tab-container');
    $container.height($(window).height() - $container.offset().top - 20);
}

window.onresize = fitTabContainer;
fitTabContainer();

$('#repo-select-trigger').on('click', function (e) {
    e.stopPropagation();

    var $container = $('.repo-select');
    var $repoList = $('ul', $container);

    $container.toggleClass('hidden');

    if (!$container.hasClass('hidden')) {
        getAvailableRepos(addRepos);
        $(window).on('click', function () {
            $('.show--fade-in').removeClass('show--fade-in');
            setTimeout(function () {
                $repoList.empty();
            }, 200);
            $(window).off('click');
            $container.toggleClass('hidden');
        })
    } else {
        $('.show--fade-in').removeClass('show--fade-in');
        setTimeout(function () {
            $repoList.empty();
        }, 200);
    }
});

function getAvailableRepos (cb) {
    $.get(API_HOST + 'available_repos')
        .success(cb)
    .fail(function (data) {
        console.log('An error has occured');
    });
}

function addRepos (data) {
    var $container = $('.repo-select');

    var $repoList = $('ul', $container);
    data.data.forEach(function (repo) {
        var repoLink = document.createElement('a');
        var repoLI = document.createElement('li');
        repoLink.href = location.origin + '/#/' + repo;
        repoLink.textContent = repo;
        repoLink.target = '_blank';
        repoLI.appendChild(repoLink);
        repoLI = $(repoLI);
        repoLI.on('click', function (e) {
            e.preventDefault();
            loadDashboard(repoLink.href);
        });
        $repoList.append(repoLI);
    });

    $repoList.toggleClass('show--fade-in');
}

function getDefaultRepo() {
    getAvailableRepos(function (data) {
        setLocation(location.origin + '/#/' + data.data[0]); // load first repo
        hash = data.data[0].split('/');
        REPO = hash[0] + '/' + hash[1];
        API_BASE += hash[0] + '/' + hash[1];
        initDashboard();
    });
}

function setLocation (newlocation) {
    location.href = newlocation;
}

function loadDashboard (newlocation) {
    setLocation(newlocation);
    location.reload();
}

function populateOpenIssues() {
    $.get(API_BASE + "/issues_count").success(function (data) {
        var count = data.data.open;
        $('#open-issues-count').text(count);

        if (!count) {
            return;
        }

        var $p = $('#open-issues');
        $p.click(function () {
            var url = 'http://github.com/' + REPO + '/issues?state=open';
            window.location.href = url;
        });
        $p.addClass('clickable');
    });
}

function populateOpenPulls() {
    $.get(API_BASE + "/pulls_count").success(function (data) {
        var count = data.data.open;
        $('#open-pulls-count').text(count);

        if (!count) {
            return;
        }

        var $p = $('#open-pulls');
        $p.click(function () {
            var url = 'http://github.com/' + REPO + '/pulls?state=open';
            window.location.href = url;
        });
        $p.addClass('clickable');
    });
}

function logFailure(fail) {
    console.log("Trouble getting data. API server down?");
    console.log(fail);
}
<|endoftext|>


<commit_before>'use strict';
/**
 * Builds the primary key name depending on model configurations
 */
module.exports = class PrimaryKeyBuilder {
    constructor(Model) { this.Model = Model; }
    build() {
        let pk = 'id';
        if (!this.Model.settings.idInjection)
        for (let key in this.Model.rawProperties)
        if (this.Model.rawProperties[key].id) pk = key;
        return pk;
    }
}<commit_msg>Clean pk builder Instead of using manual logic, used method getIdName()<commit_after>'use strict';
/**
 * Builds the primary key name depending on model configurations
 */
module.exports = class PrimaryKeyBuilder {
    constructor(Model) { this.Model = Model; }
    build() {
        return  this.Model.getIdName();
    }
}
<|endoftext|>


<commit_before>var gui = require ( '../../' );

// Initialize the framework and the default page
gui.init ();

const LED_GREEN  = 1
    , LED_OFF    = 0
    , SWITCH_ON  = "on"
    , SWITCH_OFF = "off";

// create a IO view on page
var ioView = gui.addIoView ();

// change update speed to 1 sec (= 1000 ms)
ioView.setUpdateMilliSec ( 10000 );

// add a "LED" at x/y 100px/100px and stich it to "on" (=1)
var led = LED_GREEN;
ioView.addLED ( "myFirstLED", 200, 100, led );

ioView.addSwitch (
  "mySwitch",               // the ID
  100, 100,                 // x,y pos of switch
  [ SWITCH_ON, SWITCH_OFF ],  // possible values
  function(switchValue) {
    console.log ( "Switch now: " + switchValue );
    if ( switchValue == SWITCH_ON ) {
      ioView.setLED ( "myFirstLED", LED_GREEN );
    } else {
      ioView.setLED ( "myFirstLED", LED_OFF );
    }
  }
);<commit_msg>improved code formatting of I/O example<commit_after>const LED_GREEN = 1, LED_OFF = 0, SWITCH_ON = 'on', SWITCH_OFF = 'off'

var gui = require( '../../' )
var log = require( 'npmlog' )

// Initialize the framework and the default page
gui.init()

// create a IO view on page
var ioView = gui.addIoView()

// change update speed to 1 sec (= 1000 ms)
ioView.setUpdateMilliSec( 10000 )

// add a 'LED' at x/y 100px/100px and stich it to 'on' (=1)
var led = LED_GREEN
ioView.addLED( 'myFirstLED', 200, 100, led )

ioView.addSwitch(
    'mySwitch',                   // the ID
    100, 100,                     // x,y pos of switch
    [ SWITCH_ON, SWITCH_OFF ],    // possible values
    function ( switchValue ) {
      log.info( 'Switch "mySwitch"', 'now %j', switchValue );
      if ( switchValue == SWITCH_ON ) {
        ioView.setLED( 'myFirstLED', LED_GREEN );
      } else {
        ioView.setLED( 'myFirstLED', LED_OFF );
      }
    }
)<|endoftext|>


<commit_before>"use strict";

module.exports.mockLoggingService = function () {
    return jasmine.createSpyObj('loggingService', ['error', 'debug', 'info', 'warn']);
};

module.exports.mockMessagingUtilities = function () {
    return jasmine.createSpyObj('messagingUtilities', ['waitForChannelMessage']);
};

module.exports.mockSignallingService = function () {
    return jasmine.createSpyObj('signallingService', ['initialize', 'getSignallingInfo', 'sendOffer', 'sendAnswer', 'on', 'removeListener']);
};

module.exports.mockCyclonNode = function () {
    return jasmine.createSpyObj('cyclonNode', ['getId', 'start', 'executeShuffle', 'createNewPointer', 'handleShuffleRequest', 'handleShuffleResponse', 'emit']);
};

module.exports.mockRtc = function () {
    return jasmine.createSpyObj('rtc', ['join', 'onChannel', 'openChannel']);
};

module.exports.mockChannel = function() {
    return jasmine.createSpyObj('channel', ['getRemotePeer', 'createOffer', 'createAnswer', 'sendAnswer', 'waitForChannelEstablishment', 'waitForIceCandidates', 'sendOffer', 'handleAnswer', 'waitForChannelToOpen', 'send', 'receive', 'close', 'cancel']);
}

module.exports.mockAsyncExecService = function () {
    return jasmine.createSpyObj('asyncExecService', ['setTimeout', 'setInterval', 'clearTimeout', 'clearInterval']);
};

module.exports.mockPeerConnection = function (name) {
    return jasmine.createSpyObj(name || 'peerConnection', ['createOffer', 'createAnswer', 'waitForChannelEstablishment', 'waitForChannelToOpen', 'handleAnswer', 'close', 'waitForIceCandidates', 'cancel']);
};

module.exports.mockTimingService = function () {
    return jasmine.createSpyObj('timingService', ['getCurrentTimeInMilliseconds']);
};

module.exports.mockRtcObjectFactory = function () {
    return jasmine.createSpyObj('rtcObjectFactory', ['createRTCSessionDescription', 'createRTCIceCandidate']);
};

module.exports.mockSignallingSocket = function () {
    return jasmine.createSpyObj('signallingSocket', ['getCurrentServerSpecs', 'initialize', 'on']);
};

module.exports.mockHttpRequestService = function () {
    return jasmine.createSpyObj('httpRequestService', ['get', 'post']);
};

module.exports.mockPeerConnectionFactory = function () {
    return jasmine.createSpyObj('peerConnectionFactory', ['createPeerConnection']);
};

module.exports.mockShuffleStateFactory = function () {
    return jasmine.createSpyObj('shuffleStateFactory', ['createOutgoingShuffleState', 'createIncomingShuffleState']);
};

module.exports.mockOutgoingShuffleState = function (name) {
    return jasmine.createSpyObj(name || 'outgoingShuffleState', ['sendShuffleRequest', 'processShuffleResponse', 'sendResponseAcknowledgement', 'close', 'cancel']);
};

module.exports.mockIncomingShuffleState = function () {
    return jasmine.createSpyObj('incomingShuffleState', ['processShuffleRequest', 'waitForResponseAcknowledgement', 'close', 'cancel']);
};

module.exports.mockNeighbourSet = function () {
    return jasmine.createSpyObj('neighbourSet', ['contains', 'insert', 'remove', 'get', 'size', 'selectShuffleSet', 'findOldestId', 'randomSelection', 'incrementAges', 'resetAge', 'mergeNodePointerIfNewer']);
};

module.exports.mockComms = function () {
    return jasmine.createSpyObj('comms', ['sendShuffleRequest', 'sendShuffleResponse', 'getPointerData']);
};

module.exports.mockStorage = function() {
    return jasmine.createSpyObj('storage', ['getItem', 'setItem']);
};

//
// WebRTC API mocks
//
module.exports.mockRtcDataChannel = function (name) {
    return jasmine.createSpyObj(name || 'rtcDataChannel', ['send', 'close']);
};

module.exports.mockRtcPeerConnection = function () {
    return jasmine.createSpyObj('rtcPeerConnection', ['createDataChannel', 'createOffer', 'setLocalDescription', 'setRemoteDescription', 'createAnswer', 'addIceCandidate', 'close']);
};

//
// Success/failure callbacks for testing
//
module.exports.createSuccessCallback = function () {
    return jasmine.createSpy('successCallback');
};

module.exports.createFailureCallback = function () {
    return jasmine.createSpy('failureCallback').andCallFake(function (error) {
        //console.error("Error occurred!", error);
    });
};

module.exports.mockPromise = function() {
    var mockPromise = jasmine.createSpyObj('mockPromise', ['isPending', 'close', 'cancel', 'then', 'catch', 'cancellable']);
    mockPromise.then.andReturn(mockPromise);
    mockPromise.cancellable.andReturn(mockPromise);
    mockPromise.catch.andReturn(mockPromise);
    return mockPromise;
};
<commit_msg>Fix test<commit_after>"use strict";

module.exports.mockLoggingService = function () {
    return jasmine.createSpyObj('loggingService', ['error', 'debug', 'info', 'warn']);
};

module.exports.mockMessagingUtilities = function () {
    return jasmine.createSpyObj('messagingUtilities', ['waitForChannelMessage']);
};

module.exports.mockSignallingService = function () {
    return jasmine.createSpyObj('signallingService', ['initialize', 'getSignallingInfo', 'sendOffer', 'sendAnswer', 'on', 'removeListener']);
};

module.exports.mockCyclonNode = function () {
    return jasmine.createSpyObj('cyclonNode', ['getId', 'start', 'executeShuffle', 'createNewPointer', 'handleShuffleRequest', 'handleShuffleResponse', 'emit']);
};

module.exports.mockRtc = function () {
    return jasmine.createSpyObj('rtc', ['join', 'onChannel', 'openChannel', 'on']);
};

module.exports.mockChannel = function() {
    return jasmine.createSpyObj('channel', ['getRemotePeer', 'createOffer', 'createAnswer', 'sendAnswer', 'waitForChannelEstablishment', 'waitForIceCandidates', 'sendOffer', 'handleAnswer', 'waitForChannelToOpen', 'send', 'receive', 'close', 'cancel']);
}

module.exports.mockAsyncExecService = function () {
    return jasmine.createSpyObj('asyncExecService', ['setTimeout', 'setInterval', 'clearTimeout', 'clearInterval']);
};

module.exports.mockPeerConnection = function (name) {
    return jasmine.createSpyObj(name || 'peerConnection', ['createOffer', 'createAnswer', 'waitForChannelEstablishment', 'waitForChannelToOpen', 'handleAnswer', 'close', 'waitForIceCandidates', 'cancel']);
};

module.exports.mockTimingService = function () {
    return jasmine.createSpyObj('timingService', ['getCurrentTimeInMilliseconds']);
};

module.exports.mockRtcObjectFactory = function () {
    return jasmine.createSpyObj('rtcObjectFactory', ['createRTCSessionDescription', 'createRTCIceCandidate']);
};

module.exports.mockSignallingSocket = function () {
    return jasmine.createSpyObj('signallingSocket', ['getCurrentServerSpecs', 'initialize', 'on']);
};

module.exports.mockHttpRequestService = function () {
    return jasmine.createSpyObj('httpRequestService', ['get', 'post']);
};

module.exports.mockPeerConnectionFactory = function () {
    return jasmine.createSpyObj('peerConnectionFactory', ['createPeerConnection']);
};

module.exports.mockShuffleStateFactory = function () {
    return jasmine.createSpyObj('shuffleStateFactory', ['createOutgoingShuffleState', 'createIncomingShuffleState']);
};

module.exports.mockOutgoingShuffleState = function (name) {
    return jasmine.createSpyObj(name || 'outgoingShuffleState', ['sendShuffleRequest', 'processShuffleResponse', 'sendResponseAcknowledgement', 'close', 'cancel']);
};

module.exports.mockIncomingShuffleState = function () {
    return jasmine.createSpyObj('incomingShuffleState', ['processShuffleRequest', 'waitForResponseAcknowledgement', 'close', 'cancel']);
};

module.exports.mockNeighbourSet = function () {
    return jasmine.createSpyObj('neighbourSet', ['contains', 'insert', 'remove', 'get', 'size', 'selectShuffleSet', 'findOldestId', 'randomSelection', 'incrementAges', 'resetAge', 'mergeNodePointerIfNewer']);
};

module.exports.mockComms = function () {
    return jasmine.createSpyObj('comms', ['sendShuffleRequest', 'sendShuffleResponse', 'getPointerData']);
};

module.exports.mockStorage = function() {
    return jasmine.createSpyObj('storage', ['getItem', 'setItem']);
};

//
// WebRTC API mocks
//
module.exports.mockRtcDataChannel = function (name) {
    return jasmine.createSpyObj(name || 'rtcDataChannel', ['send', 'close']);
};

module.exports.mockRtcPeerConnection = function () {
    return jasmine.createSpyObj('rtcPeerConnection', ['createDataChannel', 'createOffer', 'setLocalDescription', 'setRemoteDescription', 'createAnswer', 'addIceCandidate', 'close']);
};

//
// Success/failure callbacks for testing
//
module.exports.createSuccessCallback = function () {
    return jasmine.createSpy('successCallback');
};

module.exports.createFailureCallback = function () {
    return jasmine.createSpy('failureCallback').andCallFake(function (error) {
        //console.error("Error occurred!", error);
    });
};

module.exports.mockPromise = function() {
    var mockPromise = jasmine.createSpyObj('mockPromise', ['isPending', 'close', 'cancel', 'then', 'catch', 'cancellable']);
    mockPromise.then.andReturn(mockPromise);
    mockPromise.cancellable.andReturn(mockPromise);
    mockPromise.catch.andReturn(mockPromise);
    return mockPromise;
};
<|endoftext|>