<commit_before>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function () {
    /**
     * Gadget prefix.
     * @const
     */
    var GADGET_PREFIX = (osapi.container.GadgetHolder.IFRAME_ID_PREFIX_ = 'sandbox-');

    /**
     * Gadget container prefix.
     * @const
     */
    var CONTAINER_PREFIX = 'gadget-';

    var gadgets = {};
    var server = ues.global.server;
    var host = ues.global.host;
    var resolveURI = ues.dashboards.resolveURI;
    var context = ues.global.context;

    var resolveGadgetURL = function (uri) {
        uri = resolveURI(uri);
        if (uri.match(/^https?:\/\//i)) {
            return uri;
        }
        uri = uri.replace(/^(..\/)*/i, '');

        var hostname = host.hostname ? host.hostname : window.location.hostname,
            port = host.port ? host.port : window.location.port,
            protocol = host.protocol ? (host.protocol + ":") : window.location.protocol;

        port = port ? (":" + port) : "";
        return protocol + '//' + hostname + port + context + '/' + uri;
    };

    var subscribeForClient = ues.hub.subscribeForClient;

    var containerId = function (id) {
        return CONTAINER_PREFIX + id;
    };

    var gadgetId = function (id) {
        return GADGET_PREFIX + CONTAINER_PREFIX + id;
    };

    ues.hub.subscribeForClient = function (container, topic, conSubId) {
        var clientId = container.getClientID();
        var data = gadgets[clientId];
        if (!data) {
            return subscribeForClient.apply(ues.hub, [container, topic, conSubId]);
        }
        var component = data.component;
        var channel = component.id + '.' + topic;
        console.log('subscribing container:%s topic:%s, channel:%s by %s', clientId, topic, channel);
        return subscribeForClient.apply(ues.hub, [container, channel, conSubId]);
    };

    var component = (ues.plugins.components['gadget'] = {});

    var hasCustomUserPrefView = function (metadata, comp) {
        if (metadata.views.hasOwnProperty('settings')) {
            comp.hasCustomUserPrefView = true;
        }
    };

    var hasCustomFullView = function (metadata, comp) {
        if (metadata.views.hasOwnProperty('full')) {
            comp.hasCustomFullView = true;
        }
    };

    var loadLocalizedTitle = function (styles, comp) {
        var userLang = navigator.languages ?
            navigator.languages[0] : (navigator.language || navigator.userLanguage || navigator.browserLanguage);
        var locale_titles = comp.content.locale_titles || {};
        styles.title = locale_titles[userLang] || comp.content.title;
        comp.content.locale_titles = locale_titles || {};
    };

    component.create = function (sandbox, comp, hub, done) {
        var content = comp.content;
        var url = resolveGadgetURL(content.data.url);
        var settings = content.settings || {};
        var styles = content.styles || {};
        var options = content.options || (content.options = {});
        ues.gadgets.preload(url, function (err, metadata) {
            var pref;
            var name;
            var option;
            var params = {};
            var prefs = metadata.userPrefs;
            for (pref in prefs) {
                if (prefs.hasOwnProperty(pref)) {
                    pref = prefs[pref];
                    name = pref.name;
                    option = options[name] || {};
                    options[name] = {
                        type: option.type || pref.dataType,
                        title: option.title || pref.displayName,
                        value: option.value || pref.defaultValue,
                        options: option.options || pref.orderedEnumValues,
                        required: option.required || pref.required
                    };
                    params[name] = option.value;
                }
            }

            loadLocalizedTitle(styles, comp);
            var cid = containerId(comp.id);
            var gid = gadgetId(comp.id);
            sandbox.find('.ues-component-title').text(styles.title);
            if (styles.no_heading) {
                if(isDesigner(sandbox)){
                    sandbox.addClass('ues-no-heading');
                }
                sandbox.find('.ues-component-heading').hide();
            } else {
                sandbox.removeClass('ues-no-heading');
                sandbox.find('.ues-component-heading').show();
            }

            var titlePositon = 'ues-component-title-' + (styles.titlePosition || 'left');
            sandbox.find('.ues-component-heading')
                .removeClass('ues-component-title-left ues-component-title-center ues-component-title-right')
                .addClass(titlePositon);

            if (ues.global.dbType === 'default') {
                hasCustomUserPrefView(metadata, comp);
                hasCustomFullView(metadata, comp);
            }

            var container = $('<div />').attr('id', cid);
            sandbox.find('.ues-component-body').html(container);
            var hasHeading = !sandbox.closest('.ues-component').hasClass('ues-no-heading');
            var renderParams = {};
            renderParams[osapi.container.RenderParam.HEIGHT] =
                parseInt(sandbox.closest('.ues-component-box').height()) -
                (hasHeading ? sandbox.closest('.ues-component-box').find('.ues-component-heading').height() : 0) - 2;
            renderParams[osapi.container.RenderParam.VIEW] = comp.viewOption || 'home';
            var site = ues.gadgets.render(container, url, params, renderParams);
            gadgets[gid] = {
                component: comp,
                site: site
            };
            done(false, comp);
        });
    };

    component.update = function (sandbox, comp, hub, done) {
        component.destroy(sandbox, comp, hub, function (err) {
            if (err) {
                throw err;
            }
            component.create(sandbox, comp, hub, done);
        });
    };

    component.destroy = function (sandbox, comp, hub, done) {
        var gid = gadgetId(comp.id);
        var data = gadgets[gid];
        var site = data.site;
        ues.gadgets.remove(site.getId());
        $('.ues-component-box-gadget', sandbox).remove();
        done(false);
    };

    //check whether current mode is view or design
    isDesigner = function(sandbox){
        if ((sandbox.context.baseURI).indexOf("?editor=true")==-1){
            return false;
        } else {
            return true;
        }
    };
}());<commit_msg>Fixed an issue in the dashboard view mode when the gadget titlebar is hidden<commit_after>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function () {
    /**
     * Gadget prefix.
     * @const
     */
    var GADGET_PREFIX = (osapi.container.GadgetHolder.IFRAME_ID_PREFIX_ = 'sandbox-');

    /**
     * Gadget container prefix.
     * @const
     */
    var CONTAINER_PREFIX = 'gadget-';

    var gadgets = {};
    var server = ues.global.server;
    var host = ues.global.host;
    var resolveURI = ues.dashboards.resolveURI;
    var context = ues.global.context;

    var resolveGadgetURL = function (uri) {
        uri = resolveURI(uri);
        if (uri.match(/^https?:\/\//i)) {
            return uri;
        }
        uri = uri.replace(/^(..\/)*/i, '');

        var hostname = host.hostname ? host.hostname : window.location.hostname,
            port = host.port ? host.port : window.location.port,
            protocol = host.protocol ? (host.protocol + ":") : window.location.protocol;

        port = port ? (":" + port) : "";
        return protocol + '//' + hostname + port + context + '/' + uri;
    };

    var subscribeForClient = ues.hub.subscribeForClient;

    var containerId = function (id) {
        return CONTAINER_PREFIX + id;
    };

    var gadgetId = function (id) {
        return GADGET_PREFIX + CONTAINER_PREFIX + id;
    };

    ues.hub.subscribeForClient = function (container, topic, conSubId) {
        var clientId = container.getClientID();
        var data = gadgets[clientId];
        if (!data) {
            return subscribeForClient.apply(ues.hub, [container, topic, conSubId]);
        }
        var component = data.component;
        var channel = component.id + '.' + topic;
        console.log('subscribing container:%s topic:%s, channel:%s by %s', clientId, topic, channel);
        return subscribeForClient.apply(ues.hub, [container, channel, conSubId]);
    };

    var component = (ues.plugins.components['gadget'] = {});

    var hasCustomUserPrefView = function (metadata, comp) {
        if (metadata.views.hasOwnProperty('settings')) {
            comp.hasCustomUserPrefView = true;
        }
    };

    var hasCustomFullView = function (metadata, comp) {
        if (metadata.views.hasOwnProperty('full')) {
            comp.hasCustomFullView = true;
        }
    };

    var loadLocalizedTitle = function (styles, comp) {
        var userLang = navigator.languages ?
            navigator.languages[0] : (navigator.language || navigator.userLanguage || navigator.browserLanguage);
        var locale_titles = comp.content.locale_titles || {};
        styles.title = locale_titles[userLang] || comp.content.title;
        comp.content.locale_titles = locale_titles || {};
    };

    component.create = function (sandbox, comp, hub, done) {
        var content = comp.content;
        var url = resolveGadgetURL(content.data.url);
        var settings = content.settings || {};
        var styles = content.styles || {};
        var options = content.options || (content.options = {});
        ues.gadgets.preload(url, function (err, metadata) {
            var pref;
            var name;
            var option;
            var params = {};
            var prefs = metadata.userPrefs;
            for (pref in prefs) {
                if (prefs.hasOwnProperty(pref)) {
                    pref = prefs[pref];
                    name = pref.name;
                    option = options[name] || {};
                    options[name] = {
                        type: option.type || pref.dataType,
                        title: option.title || pref.displayName,
                        value: option.value || pref.defaultValue,
                        options: option.options || pref.orderedEnumValues,
                        required: option.required || pref.required
                    };
                    params[name] = option.value;
                }
            }

            loadLocalizedTitle(styles, comp);
            var cid = containerId(comp.id);
            var gid = gadgetId(comp.id);
            sandbox.find('.ues-component-title').text(styles.title);
            if (styles.no_heading) {
                sandbox.addClass('ues-no-heading');
                sandbox.find('.ues-component-heading').hide();
            } else {
                sandbox.removeClass('ues-no-heading');
                sandbox.find('.ues-component-heading').show();
            }

            var titlePositon = 'ues-component-title-' + (styles.titlePosition || 'left');
            sandbox.find('.ues-component-heading')
                .removeClass('ues-component-title-left ues-component-title-center ues-component-title-right')
                .addClass(titlePositon);

            if (ues.global.dbType === 'default') {
                hasCustomUserPrefView(metadata, comp);
                hasCustomFullView(metadata, comp);
            }

            var container = $('<div />').attr('id', cid);
            sandbox.find('.ues-component-body').html(container);
            var hasHeading = !sandbox.closest('.ues-component').hasClass('ues-no-heading');
            var renderParams = {};
            renderParams[osapi.container.RenderParam.HEIGHT] =
                parseInt(sandbox.closest('.ues-component-box').height()) -
                (hasHeading ? sandbox.closest('.ues-component-box').find('.ues-component-heading').height() : 0) - 2;
            renderParams[osapi.container.RenderParam.VIEW] = comp.viewOption || 'home';
            var site = ues.gadgets.render(container, url, params, renderParams);
            gadgets[gid] = {
                component: comp,
                site: site
            };
            done(false, comp);
        });
    };

    component.update = function (sandbox, comp, hub, done) {
        component.destroy(sandbox, comp, hub, function (err) {
            if (err) {
                throw err;
            }
            component.create(sandbox, comp, hub, done);
        });
    };

    component.destroy = function (sandbox, comp, hub, done) {
        var gid = gadgetId(comp.id);
        var data = gadgets[gid];
        var site = data.site;
        ues.gadgets.remove(site.getId());
        $('.ues-component-box-gadget', sandbox).remove();
        done(false);
    };
}());<|endoftext|>


<commit_before>const bot = require('./bot');
const functions = require('./functions');
const music = require('./music');
const bf2 = require('revive-stats.js').bf2;
const bf2142 = require('revive-stats.js').bf2142;
const Discord = require('discord.js')
const rank = require('./rank');
const request = require('request-promise');
const stats = require('./stats');
const math = require('mathjs');
const crypto = require('crypto');
const web = require('./web');
const help = require('./help');
const index = require('./hotline');

bot.on('message', message => {
    if (!message.content.startsWith('~')) {
        return;
    } //base case
    var cmd = message.content.split(' ')[0].substring(1).toLowerCase();
    if (commands.hasOwnProperty(cmd))
        commands[cmd].exec(message);
});
var commands = {
    'ping': {
        description: 'reply with a pong',
        syntax: '~ping',
        exec: function(message) {
            message.reply('pong');
        }
    },
    'yo': {
        description: 'reply with a yo bro',
        syntax: '~yo',
        exec: function(message) {
            message.reply('yo bro');
        }
    },
    'link': {
        description: 'link revive account to this discord account',
        syntax: '~link',
        exec: function(message) {
            functions.integrate(message.author);
        }
    },
    'refresh': {
        description: 'refresh a user discord link status',
        syntax: '~refresh',
        exec: function(message) {
            if (message.content.toString().includes('all')) {
                functions.refreshAll(bot.guilds.get('184536578654339072').members.array())
            } else if(message.mentions.users.size !=0 ) {
		message.mentions.users.map(functions.refreshUser);
		}else{

                functions.refreshUser(message.author);
            }
        }
    },
    'bf2': {
        description: 'finds a bf2 player',
        syntax: '~bf2 <PlayerName>',
        exec: function(message) {
            var nick = message.content.substring(5).trim();
            bf2.getPlayers(nick).then(plist => {
                console.log("BF2 in index.js gets executed");
                if (plist == null) {
                    message.channel.sendMessage("API Down or invalid search");
                    return;
                }
                if (plist.length >= 1) {
                    //checking for exact matches
                    var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                    console.log(exact);
                    var res = "**S.no.\tName \t link**";
                }
                if (plist.length == 0) {
                    message.channel.sendMessage("Player not found");
                    return;
                }
                var start = 0;
                var past = 0;
                if (exact != null) {
                    res = res + "\n" + (1) + "\t" + "\t" + str(exact,'bf2');
                    start++;
                }
                for (var i = start; i < plist.length; i++) {
                    if (exact != null && i == plist.indexOf(exact)) {
                        past++;
                        continue;
                    }
                    if (i == 26) {
                        res = res + "\n" + (plist.length - 25) +
                            " more players found to Get a full list of players \n" +
                            "<https://battlelog.co/player_search.php?q=" + nick + ">";
                        break;
                    } else {
                        res = res + " \n" + (i + 1 - past) +
                            "\t" + "\t" + str(plist[i],'bf2');
                    }
                }
                message.channel.sendMessage(res);
                console.log(res);
            });
        }
    },
    'bf2142': {
        description: 'finds a bf2142 player',
        syntax: '~bf2142 <PlayerName>',
        exec: function(message) {

            let nick = message.content.substring(7).trim();
            bf2142.getPlayers(nick).then(plist => {
                console.log("BF2142 in index.js gets executed");
                if (plist == null) {
                    message.channel.sendMessage("API Down or invalid search");
                    return;
                }
                if (plist.length >= 1) {
                    //checking for exact matches
                    var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                    console.log(exact);
                    var res = "**S.no.\tName \t link**";
                }
                if (plist.length == 0) {
                    message.channel.sendMessage("Player not found");
                    return;
                }
                var start = 0;
                var past = 0;
                if (exact != null) {
                    res = res + "\n" + (1) + "\t" + "\t" + str(exact);
                    start++;
                }
                for (var i = start; i < plist.length; i++) {
                    if (exact != null && i == plist.indexOf(exact)) {
                        past++;
                        continue;
                    }
                    if (i == 26) {
                        res = res + "\n" + (plist.length - 25) +
                            " more players found to Get a full list of players \n" +
                            "<https://battlelog.co/player_search.php?q=" + nick + ">";
                        break;
                    } else {
                        res = res + " \n" + (i + 1 - past) +
                            "\t" + "\t" + str(plist[i]);
                    }
                }
                message.channel.sendMessage(res);
                console.log(res);
            });
        }
    },
    'cookie': {
        description: 'eats a cookie',
        syntax: '~cookie',
        exec: function(message) {
            message.reply('crunch crunch');
        }
    },
    'add': {
        description: 'adds a person to a role',
        syntax: '~add <UserMention> to <roleName>',
        exec: function(message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.addRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'remove': {
        description: 'removes a person to a role',
        syntax: '~remove <UserMention> from <roleName>',
        exec: function(message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.removeRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'help': {
        description: 'displays help',
        syntax: '~help',
        exec: function(message) {
            var embed = new Discord.RichEmbed().setTitle('HELP').setColor("#FF7F50");
            for (cmd in commands) {
                embed.addField(cmd, "Description: " + commands[cmd].description + "\n" + "Syntax: " + commands[cmd].syntax);
            }
            //embed.addField('Music',"Description: Access the music bot using - as the prefix" + "\n"+ "Syntax: -help");
            message.channel.sendEmbed(embed);
        }
    },
    'play': {
        description: 'plays the youtube url specified',
        syntax: '~play <youtube_url>',
        exec: function(message) {
            url = message.content.substring(6).trim();
            music.play(url, message);
        }
    },
    'pause': {
        description: 'pauses the voice stream',
        syntax: '~pause',
        exec: function(message) {
            music.pause(message);
        }
    },
    'resume': {
        description: 'resumes the voice stream',
        syntax: '~resume',
        exec: function(message) {
            music.resume(message);
        }
    },
    'clear': {
        description: 'clears the playlist',
        syntax: '~clear',
        exec: function(message) {
            music.clear(message);
        }
    },
    'playnext': {
        description: 'plays the next song',
        syntax: '~playnext',
        exec: function(message) {
            music.playNext(message);
        }
    },
    'setvol': {
        description: 'sets the play volume',
        syntax: '~setVol',
        exec: function(message) {
            music.setVol(message.content.substring(7).trim());
        }
    },
    'queue': {
        description: 'views the queue',
        syntax: '~queue',
        exec: function(message) {
            music.queue(message);
        }
    },
    'info': {
        description: 'Gives the Battlelog Profile of a Verified User',
        syntax: '~info @usermention',
        exec: function(message) {
            rank.rank(message);
        }
    },
    'request': {
        description: 'execute a request',
        syntax: '~request <request>',
        exec: function(message) {
            if (message.guild != bot.guilds.get('256299642180861953')) {
                return;
            }
            var msg = message.content.substring(9).trim();
            var call = function(error, response, body) {
                if (error) {
                    message.reply(error);
                } else {
                    console.log(body)
                    if (body.length > 2000)
			body = body.toString().substring(0,1980)+"...";
                        message.channel.sendMessage("```Javascript\n" + body + '```');
                }
            };
            if (msg.startsWith('{')) msg = JSON.parse(msg)
				else msg = getOptions(msg);
            request(msg, call);
        }
    },
    'stats': {
        description: 'displays the guild stats',
        syntax: '~stats',
        exec: function(message) {
            stats.stats(message);
        }
    },
    'calc': {
        description: 'evalutes a mathematical expression',
        syntax: '~calc <expression>',
        exec: function(message) {
            let res = message.content.substring(6)//.match(/[ 0-9\%\(\)\^\/\+\-\*]+/);
           // res = res.join(' ');
	    res = math.eval(res);
	    console.log(res);
            message.channel.sendMessage(res);
        }
    },                                                   'hash': {                                              description: 'hashes a text.',
	  syntax: '~hash <algorithm> <text>',
	  exec: function(message) {
		  let res = message.content.trim().substring(6);
		  let algo = res.split(' ')[0];
		  res = res.substring(algo.length+1).trim();
		  if(crypto.getHashes().indexOf(algo)===-1){
			  message.channel.sendMessage('Invalid algorithm \n Valid hashing Algorithms are:\n'+crypto.getHashes().join(' , '));
			  return;}
		  res = checksum(res,algo);
		  console.log(res);                                  message.channel.sendMessage('hash of message:'+res);
		  if(message.attachments.size>0)
		  {
			  res = message.attachments.first().url;
			  request(res).then(body=> message.channel.sendMessage('Hash of file:\n'+checksum(body,algo)));
		  }
	  }
    },
     'convert': {                                           description: 'hashes a dec number to a different base.',
	 syntax: '~convert <base> <decnumber>',             exec: function(message)
	     {
		 let res = message.content.trim().substring(9);
		 let base = res.split(' ')[0];
		 res = res.substring(base.length+1).trim();
		 base = parseInt(base);
		 res = parseInt(res).toString(base);
		 console.log(res);                                  message.channel.sendMessage(res);          }
     }
}
const str = function(soldier,game)
{
	if(game=='bf2')
	{game='http://battlelog.co/bfhq?pid='}
	else
	{game='http://bl2142.co/bfhq?pid='}
	return soldier.nick+'\t'+"<"+game+soldier.pid+">";
};
const getOptions = function(URL) {
    return {
        url: URL,
        headers: {
            'User-Agent': 'GameSpyHTTP/1.0'
        }
    };
};
function checksum (str, algorithm) {
	console.log(str);
	console.log(algorithm);
	    return crypto
	        .createHash(algorithm || 'md5')
	        .update(str)
	        .digest('hex')
	}
<commit_msg>fixed links<commit_after>const bot = require('./bot');
const functions = require('./functions');
const music = require('./music');
const bf2 = require('revive-stats.js').bf2;
const bf2142 = require('revive-stats.js').bf2142;
const Discord = require('discord.js')
const rank = require('./rank');
const request = require('request-promise');
const stats = require('./stats');
const math = require('mathjs');
const crypto = require('crypto');
const web = require('./web');
const help = require('./help');
const index = require('./hotline');

bot.on('message', message => {
    if (!message.content.startsWith('~')) {
        return;
    } //base case
    var cmd = message.content.split(' ')[0].substring(1).toLowerCase();
    if (commands.hasOwnProperty(cmd))
        commands[cmd].exec(message);
});
var commands = {
    'ping': {
        description: 'reply with a pong',
        syntax: '~ping',
        exec: function(message) {
            message.reply('pong');
        }
    },
    'yo': {
        description: 'reply with a yo bro',
        syntax: '~yo',
        exec: function(message) {
            message.reply('yo bro');
        }
    },
    'link': {
        description: 'link revive account to this discord account',
        syntax: '~link',
        exec: function(message) {
            functions.integrate(message.author);
        }
    },
    'refresh': {
        description: 'refresh a user discord link status',
        syntax: '~refresh',
        exec: function(message) {
            if (message.content.toString().includes('all')) {
                functions.refreshAll(bot.guilds.get('184536578654339072').members.array())
            } else if(message.mentions.users.size !=0 ) {
		message.mentions.users.map(functions.refreshUser);
		}else{

                functions.refreshUser(message.author);
            }
        }
    },
    'bf2': {
        description: 'finds a bf2 player',
        syntax: '~bf2 <PlayerName>',
        exec: function(message) {
            var nick = message.content.substring(5).trim();
            bf2.getPlayers(nick).then(plist => {
                console.log("BF2 in index.js gets executed");
                if (plist == null) {
                    message.channel.sendMessage("API Down or invalid search");
                    return;
                }
                if (plist.length >= 1) {
                    //checking for exact matches
                    var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                    console.log(exact);
                    var res = "**S.no.\tName \t link**";
                }
                if (plist.length == 0) {
                    message.channel.sendMessage("Player not found");
                    return;
                }
                var start = 0;
                var past = 0;
                if (exact != null) {
                    res = res + "\n" + (1) + "\t" + "\t" + str(exact,'bf2');
                    start++;
                }
                for (var i = start; i < plist.length; i++) {
                    if (exact != null && i == plist.indexOf(exact)) {
                        past++;
                        continue;
                    }
                    if (i == 26) {
                        res = res + "\n" + (plist.length - 25) +
                            " more players found to Get a full list of players \n" +
                            "<https://battlelog.co/player_search.php?q=" + nick + ">";
                        break;
                    } else {
                        res = res + " \n" + (i + 1 - past) +
                            "\t" + "\t" + str(plist[i],'bf2');
                    }
                }
                message.channel.sendMessage(res);
                console.log(res);
            });
        }
    },
    'bf2142': {
        description: 'finds a bf2142 player',
        syntax: '~bf2142 <PlayerName>',
        exec: function(message) {

            let nick = message.content.substring(7).trim();
            bf2142.getPlayers(nick).then(plist => {
                console.log("BF2142 in index.js gets executed");
                if (plist == null) {
                    message.channel.sendMessage("API Down or invalid search");
                    return;
                }
                if (plist.length >= 1) {
                    //checking for exact matches
                    var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                    console.log(exact);
                    var res = "**S.no.\tName \t link**";
                }
                if (plist.length == 0) {
                    message.channel.sendMessage("Player not found");
                    return;
                }
                var start = 0;
                var past = 0;
                if (exact != null) {
                    res = res + "\n" + (1) + "\t" + "\t" + str(exact);
                    start++;
                }
                for (var i = start; i < plist.length; i++) {
                    if (exact != null && i == plist.indexOf(exact)) {
                        past++;
                        continue;
                    }
                    if (i == 26) {
                        res = res + "\n" + (plist.length - 25) +
                            " more players found to Get a full list of players \n" +
                            "<https://battlelog.co/player_search.php?q=" + nick + ">";
                        break;
                    } else {
                        res = res + " \n" + (i + 1 - past) +
                            "\t" + "\t" + str(plist[i]);
                    }
                }
                message.channel.sendMessage(res);
                console.log(res);
            });
        }
    },
    'cookie': {
        description: 'eats a cookie',
        syntax: '~cookie',
        exec: function(message) {
            message.reply('crunch crunch');
        }
    },
    'add': {
        description: 'adds a person to a role',
        syntax: '~add <UserMention> to <roleName>',
        exec: function(message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.addRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'remove': {
        description: 'removes a person to a role',
        syntax: '~remove <UserMention> from <roleName>',
        exec: function(message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.removeRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'help': {
        description: 'displays help',
        syntax: '~help',
        exec: function(message) {
            var embed = new Discord.RichEmbed().setTitle('HELP').setColor("#FF7F50");
            for (cmd in commands) {
                embed.addField(cmd, "Description: " + commands[cmd].description + "\n" + "Syntax: " + commands[cmd].syntax);
            }
            //embed.addField('Music',"Description: Access the music bot using - as the prefix" + "\n"+ "Syntax: -help");
            message.channel.sendEmbed(embed);
        }
    },
    'play': {
        description: 'plays the youtube url specified',
        syntax: '~play <youtube_url>',
        exec: function(message) {
            url = message.content.substring(6).trim();
            music.play(url, message);
        }
    },
    'pause': {
        description: 'pauses the voice stream',
        syntax: '~pause',
        exec: function(message) {
            music.pause(message);
        }
    },
    'resume': {
        description: 'resumes the voice stream',
        syntax: '~resume',
        exec: function(message) {
            music.resume(message);
        }
    },
    'clear': {
        description: 'clears the playlist',
        syntax: '~clear',
        exec: function(message) {
            music.clear(message);
        }
    },
    'playnext': {
        description: 'plays the next song',
        syntax: '~playnext',
        exec: function(message) {
            music.playNext(message);
        }
    },
    'setvol': {
        description: 'sets the play volume',
        syntax: '~setVol',
        exec: function(message) {
            music.setVol(message.content.substring(7).trim());
        }
    },
    'queue': {
        description: 'views the queue',
        syntax: '~queue',
        exec: function(message) {
            music.queue(message);
        }
    },
    'info': {
        description: 'Gives the Battlelog Profile of a Verified User',
        syntax: '~info @usermention',
        exec: function(message) {
            rank.rank(message);
        }
    },
    'request': {
        description: 'execute a request',
        syntax: '~request <request>',
        exec: function(message) {
            if (message.guild != bot.guilds.get('256299642180861953')) {
                return;
            }
            var msg = message.content.substring(9).trim();
            var call = function(error, response, body) {
                if (error) {
                    message.reply(error);
                } else {
                    console.log(body)
                    if (body.length > 2000)
			body = body.toString().substring(0,1980)+"...";
                        message.channel.sendMessage("```Javascript\n" + body + '```');
                }
            };
            if (msg.startsWith('{')) msg = JSON.parse(msg)
				else msg = getOptions(msg);
            request(msg, call);
        }
    },
    'stats': {
        description: 'displays the guild stats',
        syntax: '~stats',
        exec: function(message) {
            stats.stats(message);
        }
    },
    'calc': {
        description: 'evalutes a mathematical expression',
        syntax: '~calc <expression>',
        exec: function(message) {
            let res = message.content.substring(6)//.match(/[ 0-9\%\(\)\^\/\+\-\*]+/);
           // res = res.join(' ');
	    res = math.eval(res);
	    console.log(res);
            message.channel.sendMessage(res);
        }
    },                                                   'hash': {                                              description: 'hashes a text.',
	  syntax: '~hash <algorithm> <text>',
	  exec: function(message) {
		  let res = message.content.trim().substring(6);
		  let algo = res.split(' ')[0];
		  res = res.substring(algo.length+1).trim();
		  if(crypto.getHashes().indexOf(algo)===-1){
			  message.channel.sendMessage('Invalid algorithm \n Valid hashing Algorithms are:\n'+crypto.getHashes().join(' , '));
			  return;}
		  res = checksum(res,algo);
		  console.log(res);                                  message.channel.sendMessage('hash of message:'+res);
		  if(message.attachments.size>0)
		  {
			  res = message.attachments.first().url;
			  request(res).then(body=> message.channel.sendMessage('Hash of file:\n'+checksum(body,algo)));
		  }
	  }
    },
     'convert': {                                           description: 'hashes a dec number to a different base.',
	 syntax: '~convert <base> <decnumber>',             exec: function(message)
	     {
		 let res = message.content.trim().substring(9);
		 let base = res.split(' ')[0];
		 res = res.substring(base.length+1).trim();
		 base = parseInt(base);
		 res = parseInt(res).toString(base);
		 console.log(res);                                  message.channel.sendMessage(res);          }
     }
}
const str = function(soldier,game)
{
	if(game=='bf2')
	{game='httpa://battlelog.co/bfhq.php?pid='}
	else
	{game='https://bl2142.co/bfhq.php?pid='}
	return soldier.nick+'\t'+"<"+game+soldier.pid+">";
};
const getOptions = function(URL) {
    return {
        url: URL,
        headers: {
            'User-Agent': 'GameSpyHTTP/1.0'
        }
    };
};
function checksum (str, algorithm) {
	console.log(str);
	console.log(algorithm);
	    return crypto
	        .createHash(algorithm || 'md5')
	        .update(str)
	        .digest('hex')
	}
<|endoftext|>


<commit_before>module.exports = {
	title: 'Mrm',
	tagline: 'Codemods for your project config files',
	url: 'https://github.com/sapegin/mrm',
	baseUrl: '/',
	favicon: 'img/favicon.png',
	organizationName: 'sapegin',
	projectName: 'mrm',
	themeConfig: {
		disableDarkMode: true,
		prism: {
			theme: require('prism-react-renderer/themes/nightOwlLight'),
		},
		navbar: {
			hideOnScroll: false,
			title: 'Mrm',
			links: [
				{
					to: 'docs/getting-started',
					activeBasePath: 'docs',
					label: 'Docs',
					position: 'left',
				},
				{
					to: 'docs/mrm-preset-default',
					activeBasePath: 'docs',
					label: 'Presets',
					position: 'left',
				},
				{
					to: 'docs/mrm-task-codecov',
					activeBasePath: 'docs',
					label: 'Tasks',
					position: 'left',
				},
				{
					href: 'https://github.com/sapegin/mrm',
					label: 'GitHub',
					position: 'right',
				},
			],
		},
		footer: {
			style: 'dark',
			links: [
				{
					title: 'Docs',
					items: [
						{
							label: 'Changelog',
							href: 'https://github.com/sapegin/mrm/releases',
						},
						{
							label: 'Contributing',
							href:
								'https://github.com/sapegin/mrm/blob/master/Contributing.md',
						},
					],
				},
				{
					title: 'Social',
					items: [
						{
							label: 'Twitter',
							href: 'https://twitter.com/iamsapegin',
						},
						{
							label: 'GitHub',
							href: 'https://github.com/sapegin/mrm',
						},
					],
				},
				{
					title: 'Sponsor',
					items: [
						{
							label: 'Buy me a coffee',
							href: 'https://www.buymeacoffee.com/sapegin',
						},
					],
				},
			],
			copyright: `Made with coffee in Berlin by Artem Sapegin and contributors`,
		},
	},
	presets: [
		[
			'@docusaurus/preset-classic',
			{
				docs: {
					sidebarPath: require.resolve('./sidebars.js'),
					remarkPlugins: require('./remark'),
				},
				theme: {
					customCss: require.resolve('./src/css/custom.css'),
				},
			},
		],
	],
};
<commit_msg>chore: Fix site URL maybe 🦆<commit_after>module.exports = {
	title: 'Mrm',
	tagline: 'Codemods for your project config files',
	url: 'https://mrmjs.netlify.app',
	baseUrl: '/',
	favicon: 'img/favicon.png',
	organizationName: 'sapegin',
	projectName: 'mrm',
	themeConfig: {
		disableDarkMode: true,
		prism: {
			theme: require('prism-react-renderer/themes/nightOwlLight'),
		},
		navbar: {
			hideOnScroll: false,
			title: 'Mrm',
			links: [
				{
					to: 'docs/getting-started',
					activeBasePath: 'docs',
					label: 'Docs',
					position: 'left',
				},
				{
					to: 'docs/mrm-preset-default',
					activeBasePath: 'docs',
					label: 'Presets',
					position: 'left',
				},
				{
					to: 'docs/mrm-task-codecov',
					activeBasePath: 'docs',
					label: 'Tasks',
					position: 'left',
				},
				{
					href: 'https://github.com/sapegin/mrm',
					label: 'GitHub',
					position: 'right',
				},
			],
		},
		footer: {
			style: 'dark',
			links: [
				{
					title: 'Docs',
					items: [
						{
							label: 'Changelog',
							href: 'https://github.com/sapegin/mrm/releases',
						},
						{
							label: 'Contributing',
							href:
								'https://github.com/sapegin/mrm/blob/master/Contributing.md',
						},
					],
				},
				{
					title: 'Social',
					items: [
						{
							label: 'Twitter',
							href: 'https://twitter.com/iamsapegin',
						},
						{
							label: 'GitHub',
							href: 'https://github.com/sapegin/mrm',
						},
					],
				},
				{
					title: 'Sponsor',
					items: [
						{
							label: 'Buy me a coffee',
							href: 'https://www.buymeacoffee.com/sapegin',
						},
					],
				},
			],
			copyright: `Made with coffee in Berlin by Artem Sapegin and contributors`,
		},
	},
	presets: [
		[
			'@docusaurus/preset-classic',
			{
				docs: {
					sidebarPath: require.resolve('./sidebars.js'),
					remarkPlugins: require('./remark'),
				},
				theme: {
					customCss: require.resolve('./src/css/custom.css'),
				},
			},
		],
	],
};
<|endoftext|>


<commit_before>const bot = require('./bot');
const functions = require('./functions');
const bf2 = require('./bf2');
const bf2142 = require('./bf2142');
const Discord = require('discord.js')

bot.on('message', message => {
    if (!message.content.startsWith('~')) {
        return;
    } //base case
    var cmd = message.content.split(' ')[0].substring(1).toLowerCase();
    commands[cmd].exec(message);
});
var commands = {
    'pong': {
        description: 'reply with a pong',
        syntax: '~ping',
        exec: function(message) {
            message.reply('pong');
        }
    },
    'yo': {
        description: 'reply with a yo bro',
        syntax: '~yo',
        exec: function(message) {
            message.reply('yo bro');
        }
    },
    'link': {
        description: 'link revive account to this discord account',
        syntax: '~link',
        exec: function(message) {
            functions.integrate(message.author);
        }
    },
    'refresh': {
        description: 'refresh a user discord link status',
        syntax: '~refresh',
        exec: function(message) {
            if (message.content.substring(9).trim() == 'all' &&
                message.guild.name == 'Revive Netowrk Dev') {
                functions.refreshAll(bot.guilds.get('184536578654339072').members.array())
            } else {
                functions.refreshUser(message.author);
            }
        }
    },
    'bf2': {
        description: 'finds a bf2 player',
        syntax: '~bf2 <PlayerName>',
        exec: function(message) {
            var nick = message.content.substring(5).trim();
            var plist = bf2.getPlayers(nick);
            console.log("BF2 in index.js gets executed");
            if (plist == null) {
                message.channel.sendMessage("API Down or invalid search");
                return;
            }
            if (plist.length >= 1) {
                //checking for exact matches
                var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                console.log(exact);
                var res = "**S.no.\tName \t PID \t Score**";
            }
			    if (plist.length == 0) {
                message.channel.sendMessage("Player not found"); return;
            }
            var start = 0;
            var past = 0;
            if (exact != null) {
                res = res + "\n" + (1) + "\t" + "\t" + exact.str();
                start++;
            }
            for (var i = start; i < plist.length; i++) {
                if (exact != null && i == plist.indexOf(exact)) {
                    past++;
                    continue;
                }
                if (i == 26) {
                    res = res + "\n" + (plist.length - 25) +
                        " more players found to Get a full list of players \n" +
                        "<https://battlelog.co/player_search.php?q=" + nick + ">";
                    break;
                } else {
                    res = res + " \n" + (i + 1 - past) +
                        "\t" + "\t" + plist[i].str();
                }
            }
			message.channel.sendMessage(res);
			console.log(res);
        }
    },
    'bf2142': {
        description: 'finds a bf2142 player',
        syntax: '~bf2142 <PlayerName>',
        exec: function(message) {

            var nick = message.content.substring(7).trim();
            var plist = bf2142.getPlayers(nick);
            console.log("BF2142 in index.js gets executed");
            if (plist == null) {
                message.channel.sendMessage("API Down or invalid search");
                return;
            }
            if (plist.length >= 1) {
                //checking for exact matches
                var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                console.log(exact);
                var res = "**S.no.\tName \t PID**";
            }
			if (plist.length == 0) {
                message.channel.sendMessage("Player not found");return;
            }
            var start = 0;
            var past = 0;
            if (exact != null) {
                res = res + "\n" + (1) + "\t" + "\t" + exact.str();
                start++;
            }
            for (var i = start; i < plist.length; i++) {
                if (exact != null && i == plist.indexOf(exact)) {
                    past++;
                    continue;
                }
                if (i == 26) {
                    res = res + "\n" + (plist.length - 25) +
                        " more players found to Get a full list of players \n" +
                        "<https://battlelog.co/player_search.php?q=" + nick + ">";
                    break;
                } else {
                    res = res + " \n" + (i + 1 - past) +
                        "\t" + "\t" + plist[i].str();
                }
            }
			message.channel.sendMessage(res);
			console.log(res);
        }
    },
    'cookie': {
        description: 'eats a cookie',
        syntax: '~cookie',
        exec: function(message) {
            message.reply('crunch crunch');
        }
    },
    'add': {
        description: 'adds a person to a role',
        syntax: '~add <UserMention> to <roleName>',
        exec: function(message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.addRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'remove': {
        description: 'removes a person to a role',
        syntax: '~remove <UserMention> from <roleName>',
        exec: function(message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.removeRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'help': {
        description: 'displays help',
        syntax: '~help',
        exec: function(message) {
			var embed = new Discord.RichEmbed().setTitle('HELP').setColor("#FF7F50");
            for (cmd in commands) {
                embed.addField(cmd,"Decription: " + commands[cmd].description + "\n"+ "Syntax: " + commands[cmd].syntax);
			}
            message.channel.sendEmbed(embed);
        }
    }
}<commit_msg>Fixed Typo<commit_after>const bot = require('./bot');
const functions = require('./functions');
const bf2 = require('./bf2');
const bf2142 = require('./bf2142');
const Discord = require('discord.js')

bot.on('message', message => {
    if (!message.content.startsWith('~')) {
        return;
    } //base case
    var cmd = message.content.split(' ')[0].substring(1).toLowerCase();
    commands[cmd].exec(message);
});
var commands = {
    'pong': {
        description: 'reply with a pong',
        syntax: '~ping',
        exec: function(message) {
            message.reply('pong');
        }
    },
    'yo': {
        description: 'reply with a yo bro',
        syntax: '~yo',
        exec: function(message) {
            message.reply('yo bro');
        }
    },
    'link': {
        description: 'link revive account to this discord account',
        syntax: '~link',
        exec: function(message) {
            functions.integrate(message.author);
        }
    },
    'refresh': {
        description: 'refresh a user discord link status',
        syntax: '~refresh',
        exec: function(message) {
            if (message.content.substring(9).trim() == 'all' &&
                message.guild.name == 'Revive Netowrk Dev') {
                functions.refreshAll(bot.guilds.get('184536578654339072').members.array())
            } else {
                functions.refreshUser(message.author);
            }
        }
    },
    'bf2': {
        description: 'finds a bf2 player',
        syntax: '~bf2 <PlayerName>',
        exec: function(message) {
            var nick = message.content.substring(5).trim();
            var plist = bf2.getPlayers(nick);
            console.log("BF2 in index.js gets executed");
            if (plist == null) {
                message.channel.sendMessage("API Down or invalid search");
                return;
            }
            if (plist.length >= 1) {
                //checking for exact matches
                var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                console.log(exact);
                var res = "**S.no.\tName \t PID \t Score**";
            }
			    if (plist.length == 0) {
                message.channel.sendMessage("Player not found"); return;
            }
            var start = 0;
            var past = 0;
            if (exact != null) {
                res = res + "\n" + (1) + "\t" + "\t" + exact.str();
                start++;
            }
            for (var i = start; i < plist.length; i++) {
                if (exact != null && i == plist.indexOf(exact)) {
                    past++;
                    continue;
                }
                if (i == 26) {
                    res = res + "\n" + (plist.length - 25) +
                        " more players found to Get a full list of players \n" +
                        "<https://battlelog.co/player_search.php?q=" + nick + ">";
                    break;
                } else {
                    res = res + " \n" + (i + 1 - past) +
                        "\t" + "\t" + plist[i].str();
                }
            }
			message.channel.sendMessage(res);
			console.log(res);
        }
    },
    'bf2142': {
        description: 'finds a bf2142 player',
        syntax: '~bf2142 <PlayerName>',
        exec: function(message) {

            var nick = message.content.substring(7).trim();
            var plist = bf2142.getPlayers(nick);
            console.log("BF2142 in index.js gets executed");
            if (plist == null) {
                message.channel.sendMessage("API Down or invalid search");
                return;
            }
            if (plist.length >= 1) {
                //checking for exact matches
                var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                console.log(exact);
                var res = "**S.no.\tName \t PID**";
            }
			if (plist.length == 0) {
                message.channel.sendMessage("Player not found");return;
            }
            var start = 0;
            var past = 0;
            if (exact != null) {
                res = res + "\n" + (1) + "\t" + "\t" + exact.str();
                start++;
            }
            for (var i = start; i < plist.length; i++) {
                if (exact != null && i == plist.indexOf(exact)) {
                    past++;
                    continue;
                }
                if (i == 26) {
                    res = res + "\n" + (plist.length - 25) +
                        " more players found to Get a full list of players \n" +
                        "<https://battlelog.co/player_search.php?q=" + nick + ">";
                    break;
                } else {
                    res = res + " \n" + (i + 1 - past) +
                        "\t" + "\t" + plist[i].str();
                }
            }
			message.channel.sendMessage(res);
			console.log(res);
        }
    },
    'cookie': {
        description: 'eats a cookie',
        syntax: '~cookie',
        exec: function(message) {
            message.reply('crunch crunch');
        }
    },
    'add': {
        description: 'adds a person to a role',
        syntax: '~add <UserMention> to <roleName>',
        exec: function(message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.addRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'remove': {
        description: 'removes a person to a role',
        syntax: '~remove <UserMention> from <roleName>',
        exec: function(message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.removeRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'help': {
        description: 'displays help',
        syntax: '~help',
        exec: function(message) {
			var embed = new Discord.RichEmbed().setTitle('HELP').setColor("#FF7F50");
            for (cmd in commands) {
                embed.addField(cmd,"Description: " + commands[cmd].description + "\n"+ "Syntax: " + commands[cmd].syntax);
			}
            message.channel.sendEmbed(embed);
        }
    }
}<|endoftext|>


<commit_before>/*! [replace-name] v[replace-version] */
/***************************************************************************************************************************************************************
 *
 * skip-link function
 *
 * Provide skip links to navigation and content.
 *
 **************************************************************************************************************************************************************/

import React from 'react';
import PropTypes from 'prop-types';

/**
 * One skip-link item
 *
 * @param  {array}    link         - The link object
 * @param  {string}   link.link    - The href for the link
 * @param  {string}   link.text    - The link text
 * @param  {function} link.onClick - A function called when the link is clicked
 */
export const SkipLinkItem = ({ link }) => {
	const attributeOptions = {};

	if( typeof link.onClick === 'function' ) {
		attributeOptions.onClick = link.onClick;
	}

	return (
		{ link.text }
	);
};

SkipLinkItem.propTypes = {
	link: PropTypes.shape({
		link: PropTypes.string.isRequired,
		text: PropTypes.string.isRequired,
		onClick: PropTypes.func,
	}).isRequired,
};

/**
 * DEFAULT
 * The skip-link component
 *
 * @param  {array} links - The links, format: { url: '', text: '', onClick: () }
 */
const SkipLink = ({ links }) => (

		{ links.map( ( link, i ) => <SkipLinkItem key={ i } link={ link } /> ) }

);

SkipLink.propTypes = {
	links: PropTypes.arrayOf(
		PropTypes.shape({
			link: PropTypes.string.isRequired,
			text: PropTypes.string.isRequired,
			onClick: PropTypes.func,
		})
		).isRequired,
};

export default SkipLink;
<commit_msg>skip link attribute options<commit_after>/*! [replace-name] v[replace-version] */
/***************************************************************************************************************************************************************
 *
 * skip-link function
 *
 * Provide skip links to navigation and content.
 *
 **************************************************************************************************************************************************************/

import React from 'react';
import PropTypes from 'prop-types';

/**
 * One skip-link item
 *
 * @param  {array}    link             - The link object
 * @param  {string}   link.link        - The href for the link
 * @param  {string}   link.text        - The link text
 * @param  {function} link.onClick     - A function called when the link is clicked
 * @param  {object}   attributeOptions - Any other attribute options
 */
export const SkipLinkItem = ({ link, ...attributeOptions }) => {

	if( typeof link.onClick === 'function' ) {
		attributeOptions.onClick = link.onClick;
	}

	return (
		{ link.text }
	);
};

SkipLinkItem.propTypes = {
	link: PropTypes.shape({
		link: PropTypes.string.isRequired,
		text: PropTypes.string.isRequired,
		onClick: PropTypes.func,
	}).isRequired,
};

/**
 * DEFAULT
 * The skip-link component
 *
 * @param  {array} links - The links, format: { url: '', text: '', onClick: () }
 * @param  {object} attributeOptions - Any other attribute options
 */
const SkipLink = ({ links, ...attributeOptions }) => (

		{ links.map( ( link, i ) => <SkipLinkItem key={ i } link={ link } /> ) }

);

SkipLink.propTypes = {
	links: PropTypes.arrayOf(
		PropTypes.shape({
			link: PropTypes.string.isRequired,
			text: PropTypes.string.isRequired,
			onClick: PropTypes.func,
		})
		).isRequired,
};

export default SkipLink;
<|endoftext|>


<commit_before>
var minimatch = require('minimatch');
var path =  require('path');

var joinPath = (function () {
    var _join = path.join;
    return function (base, request) {
        if (request) {
            return _join(base, request).replace(/\\/g, '/');
        }
        return base.replace(/\\/g, '/');
    }
})();

function Codegs(config) {

    this.config = {
        rootdir:      null,
        mainfile:     null,
        source:       null,
        output:       null,
        core:         null,
        node_core:    null,
        node_modules: null,
        kernel:       null
    };

    this.files = {
        core:         {},
        node_core:    {},
        node_modules: {},
        source:       {},
        main:         null,
        kernel:       null
    };
    this.ignoreFilepath = [];
    this.ignorePattern = [];
    this.content = '';

    if (config) {
        Codegs.prototype.addConfig.call(this, config);
    }
}

Codegs.create = function (config) {
    return new Codegs(config);
};

Codegs.prototype.addConfig = function (config) {

    if (config.rootdir) {
        this.config.rootdir = config.rootdir;
    }

    if (config.mainfile) {
        this.config.mainfile = config.mainfile;
    }

    if (config.source) {
        if (this.config.source === null) {
            this.config.source = [];
        }
        this.config.source = this.config.source.concat(config.source);
    }

    if (config.output) {
        this.config.output = config.output;
    }

    if (config.core) {
        this.config.core = config.core;
    }

    if (config.node_core) {
        this.config.node_core = config.node_core;
    }

    if (config.node_modules) {
        if (this.config.node_modules === null) {
            this.config.node_modules = [];
        }
        this.config.node_modules = this.config.node_modules.concat(config.node_modules);
    }

    if (config.kernel) {
        this.config.kernel = config.kernel;
    }

    return null;
};

Codegs.prototype.loadPackageJson = function (filepath, mockfs) {
    var fs = mockfs || require('fs');
    var error = null;

    if ( ! fs.existsSync(filepath)) {
        return 'Error: package.json is not found.';
    }

    var packageInfo = this._require(filepath);

    var config = {
        rootdir:      path.dirname(filepath),
        mainfile:     packageInfo.main || null,
        node_modules: []
    };

    if (packageInfo.files) {
        config.source = [];
        for (var i = 0; i < packageInfo.files.length; i++) {
            config.source.push(joinPath(config.rootdir, packageInfo.files[i]));
        }
    }
    if (packageInfo.dependencies) {
        for (var p in packageInfo.dependencies) {
            if (packageInfo.dependencies.hasOwnProperty(p)) {
                config.node_modules.push(p);
            }
        }
    }

    error = this.addConfig(config);
    if (error) {
        return error;
    }

    this.packageInfo = packageInfo;

    // load .npmignore file.
    var ignoreFilepath = joinPath(config.rootdir, '.npmignore');
    if ( ! fs.existsSync(ignoreFilepath)) {
        return error;
    }

    var patterns = fs.readFileSync(ignoreFilepath, 'utf8').split('\n');
    for (var j = 0; j < patterns.length; j++) {
        if (patterns[j] !== '') {
            this._addIgnorePattern('**/' + patterns[j]);
        }
    }

    return error;
};

// this sub function is hook point for jasmine-spy.
Codegs.prototype._require = function (filepath) {
    return require(filepath);
};

Codegs.prototype.run = function () {
    var steps = [
            this.setup,
            this.addCoreFiles,
            this.addNodeCoreFiles,
            this.addNodeModules,
            this.addSourceFiles,
            this.compile,
            this.out
        ],
        error = null;

    for (var i = 0; (i < steps.length) && (error === null); i++) {
        error = steps[i].apply(this);
    }
    return error;
}

Codegs.prototype.setup = function (mockfs) {
    var fs = mockfs || require('fs');
    var error;

    // config.rootdir
    if ( ! this.config.rootdir) {
        this.config.rootdir = process.cwd();
    }

    // config.mainfile
    if ( ! this.config.mainfile) {
        this.config.mainfile = process.cwd();
    }

    // config.core
    if (this.config.core) {
        this.config.core = path.resolve(this.config.rootdir, this.config.core);
        if ( ! fs.existsSync(this.config.core)) {
            return 'Error: core module directory is not existent.';
        }
        if ( ! fs.statSync(this.config.core).isDirectory()) {
            return 'Error: core module directory is not directory.';
        }
    } else {
        // default value. not check if it exists.
        this.config.core = path.resolve(this.config.rootdir, './core');
    }

    // config.node_core
    if (this.config.node_core) {
        this.config.node_core = path.resolve(this.config.rootdir, this.config.node_core);
        if ( ! fs.existsSync(this.config.node_core)) {
            return 'Error: node_core module directory is not existent.';
        }
        if ( ! fs.statSync(this.config.node_core).isDirectory()) {
            return 'Error: node_core module directory is not directory.';
        }
    } else {
        // default value. not check if it exists.
        this.config.node_core = path.resolve(this.config.rootdir, './node_core');
    }

    // files.main
    this.files.main = path.resolve(this.config.rootdir, this.config.mainfile);
    if ( ! fs.existsSync(this.files.main)) {
        this.files.main = null;
        return 'Error: main file is not existent.';
    }
    if ( ! fs.statSync(this.files.main).isFile()) {
        this.files.main = null;
        return 'Error: main file is not valid filetype.';
    }
    this._addIgnoreFilepath(this.files.main);

    // files.kernel
    if (this.config.kernel) {

        this.files.kernel = path.resolve(this.config.rootdir, this.config.kernel);
        if ( ! fs.existsSync(this.files.kernel)) {
            this.files.kernel = null;
            return 'Error: kernel file is not existent.';
        }
        if ( ! fs.statSync(this.files.kernel).isFile()) {
            this.files.kernel = null;
            return 'Error: kernel file is not valid filetype.';
        }
        this._addIgnoreFilepath(this.files.kernel);
    }

    return null;
};

Codegs.prototype.addCoreFiles = function (mockfs) {
    var fs = mockfs || require('fs');

    if (typeof this.config.core !== 'string') {
        return 'Error: core file directory is not specified.';
    }

    var coredir = joinPath(this.config.core);
    var error = this._addFilesToList(this.files.core, coredir, 'core/', false, mockfs);
    if (error === null) {
        coredir = coredir.slice(-1) === '/' ? coredir.slice(0, -1) : coredir;
        this._addIgnoreFilepath(coredir);
    }
    return error;
};

Codegs.prototype.addNodeCoreFiles = function (mockfs) {
    var fs = mockfs || require('fs');

    if (typeof this.config.node_core !== 'string') {
        return 'Error: node_core file directory is not specified.';
    }

    var nodecoredir = joinPath(this.config.node_core);
    var error = this._addFilesToList(this.files.node_core, nodecoredir, 'node_core/', false, mockfs);
    if (error === null) {
        nodecoredir = nodecoredir.slice(-1) === '/' ? nodecoredir.slice(0, -1) : nodecoredir;
        this._addIgnoreFilepath(nodecoredir);
    }
    return error;
};

Codegs.prototype.addNodeModules = function (mockfs) {
    var fs = mockfs || require('fs');

    var rootdir = joinPath(this.config.rootdir);
    var moduledir = joinPath(rootdir, './node_modules');

    if (this.config.node_modules === null) {
        var error = this._addFilesToList(this.files.node_modules, moduledir, '/node_modules/', false, mockfs);
        if (error === null) {
            this._addIgnoreFilepath(moduledir);
        }
        return error;
    }

    var i, source, storepath, error = null;
    for (i = 0; i < this.config.node_modules.length; i++) {

        storepath = source = joinPath(moduledir, this.config.node_modules[i]);
        storepath = storepath === rootdir ? '/' : storepath.slice(rootdir.length);

        error = this._addFilesToList(this.files.node_modules, source, storepath, false, mockfs);
        if (error === null) {
            source = source.slice(-1) === '/' ? source.slice(0, -1) : source;
            this._addIgnoreFilepath(source);
        } else {
            break;
        }
    }
    return error;
};

Codegs.prototype.addSourceFiles = function (mockfs) {
    var fs = mockfs || require('fs');

    if (this.config.source === null) {
        this.config.source = [];
        this.config.source.push(this.config.rootdir);
    }

    var i, source, storepath, error = null;
    var rootdir = joinPath(this.config.rootdir);

    for (i = 0; i < this.config.source.length; i++) {

        storepath = source = joinPath(this.config.source[i]);

        if (storepath.slice(0, rootdir.length) !== rootdir) {
            return 'Error: Source directory is outside project root.';
        }
        storepath = storepath === rootdir ? '/' : storepath.slice(rootdir.length);

        error = this._addFilesToList(this.files.source, source, storepath, true, mockfs);
        if (error === null) {
            source = source.slice(-1) === '/' ? source.slice(0, -1) : source;
            this._addIgnoreFilepath(source);
        } else {
            break;
        }
    }
    return error;
};

Codegs.prototype.compile = function (mockfs) {
    var fs = mockfs || require('fs');

    this.content = '';
    var content = '';

    content = Codegs._compileFilesList(this.files.core, mockfs);
    this.content += content;

    content = Codegs._compileFilesList(this.files.node_core, mockfs);
    this.content += content;

    content = Codegs._compileFilesList(this.files.node_modules, mockfs);
    this.content += content;

    content = Codegs._compileFilesList(this.files.source, mockfs);
    this.content += content;

    var mainfileList = Codegs._createFilesList(this.config, this.files.main, 'main');
    content = Codegs._compileFilesList(mainfileList, mockfs);
    this.content += content;

    if (this.files.kernel) {
        var corefileList = {};
        corefileList[this.files.kernel] = { type: 'core', path: '' };
        content = Codegs._compileFilesList(corefileList, mockfs);
    } else {
        // kernel === null, then should not wrap. just read and append.
        content = fs.readFileSync(require.resolve('./module.js'));
    }
    this.content += content;

    return null;
};

Codegs.prototype.out = function (mockfs) {
    var fs = mockfs || require('fs');

    if (this.config.output) {
        try {
            fs.writeFileSync(this.config.output, this.content);
        } catch(e) {
            return 'Error: ' + e;
        }
        return null;
    }

    return this.content;
};

Codegs._createFilesList = function (config, file, type) {
    var rootdir = joinPath(config.rootdir);
    var rootlength = rootdir.length　- (rootdir.slice(-1) === '/' ? 1 : 0);

    var mainpath = file.slice(rootlength);
    var fileList = {};

    fileList[file] = { type: type, path: mainpath};

    return fileList;
};

Codegs._compileFilesList = function (filesList, mockfs) {
    var fs = mockfs || require('fs');
    var codegsModule = require('./module');

    var file, content, err, mergedContent = '';

    for (file in filesList) {
        content = fs.readFileSync(file, {encoding: 'utf8'});
        content = codegsModule.wrap(content, filesList[file].path, filesList[file].type);
        if (content === null) {
            throw new Error("Error: Invalid filepath '" + filesList[file].path +
                            "'or type '" + filesList[file].type + "'");
        }
        mergedContent += content;
    }
    return mergedContent;
};

Codegs.prototype._addIgnoreFilepath = function (filepath) {
    this.ignoreFilepath.push(filepath);
};

Codegs.prototype._addIgnorePattern = function (pattern) {
    this.ignorePattern.push(pattern);
};

Codegs.prototype._isIgnoreFile = function (file, checkPattern) {
    for (var i = 0; i < this.ignoreFilepath.length; i++) {
        if (file === this.ignoreFilepath[i]) {
            return true;
        }
    }
    if (checkPattern) {
        for (var i = 0; i < this.ignorePattern.length; i++) {
            if (minimatch(file, this.ignorePattern[i])) {
                return true;
            }
        }
    }
    return false;
};

Codegs.prototype._addFilesToList = function (list, source, storepath, checkPattern, mockfs) {
    var fs = mockfs || require('fs');

    if (this._isIgnoreFile(source, checkPattern)) {
        return null;
    }

    if ( ! fs.existsSync(source)) {
        //return ("Error: File or Directory not Exists. '" + source + "'");
        return null;
    }

    var stat = fs.statSync(source);

    if (stat.isFile()) {
        // If specific file passed, no file type checking to add.
        if (list[source] === undefined) {
            list[source] = {
                type : source.slice(-5) === '.json' ? 'json' : 'js',
                path : storepath
            }
        }
        return null;
    }
    if (stat.isDirectory()) {
        var files = fs.readdirSync(source);

        var error;
        for (var i = 0; i < files.length; i++) {
            if (this._isIgnoreFile(files[i], checkPattern)) {
                continue;
            }
            stat = fs.statSync(joinPath(source, files[i]));
            if (stat.isFile()) {
                // File types to add are only '.js' and '.json', by default.
                if (! ( ((files[i].length > 3) && (files[i].slice(-3) === '.js')) ||
                        ((files[i].length > 5) && (files[i].slice(-5) === '.json'))) ) {
                    continue;
                }
            }
            error = this._addFilesToList(list,
                                    joinPath(source, files[i]),
                                    joinPath(storepath, files[i]),
                                    checkPattern,
                                    mockfs);
            if (error !== null) {
                return error;
            }
        }
        return null;
    }
    return null
}

module.exports = Codegs;
<commit_msg>codegs: cleanup linter error.<commit_after>
var minimatch = require('minimatch');
var path =  require('path');

var joinPath = (function () {
    var _join = path.join;
    return function (base, request) {
        if (request) {
            return _join(base, request).replace(/\\/g, '/');
        }
        return base.replace(/\\/g, '/');
    };
})();

function Codegs(config) {

    this.config = {
        rootdir:      null,
        mainfile:     null,
        source:       null,
        output:       null,
        core:         null,
        node_core:    null,
        node_modules: null,
        kernel:       null
    };

    this.files = {
        core:         {},
        node_core:    {},
        node_modules: {},
        source:       {},
        main:         null,
        kernel:       null
    };
    this.ignoreFilepath = [];
    this.ignorePattern = [];
    this.content = '';

    if (config) {
        Codegs.prototype.addConfig.call(this, config);
    }
}

Codegs.create = function (config) {
    return new Codegs(config);
};

Codegs.prototype.addConfig = function (config) {

    if (config.rootdir) {
        this.config.rootdir = config.rootdir;
    }

    if (config.mainfile) {
        this.config.mainfile = config.mainfile;
    }

    if (config.source) {
        if (this.config.source === null) {
            this.config.source = [];
        }
        this.config.source = this.config.source.concat(config.source);
    }

    if (config.output) {
        this.config.output = config.output;
    }

    if (config.core) {
        this.config.core = config.core;
    }

    if (config.node_core) {
        this.config.node_core = config.node_core;
    }

    if (config.node_modules) {
        if (this.config.node_modules === null) {
            this.config.node_modules = [];
        }
        this.config.node_modules = this.config.node_modules.concat(config.node_modules);
    }

    if (config.kernel) {
        this.config.kernel = config.kernel;
    }

    return null;
};

Codegs.prototype.loadPackageJson = function (filepath, mockfs) {
    var fs = mockfs || require('fs');
    var error = null;

    if ( ! fs.existsSync(filepath)) {
        return 'Error: package.json is not found.';
    }

    var packageInfo = this._require(filepath);

    var config = {
        rootdir:      path.dirname(filepath),
        mainfile:     packageInfo.main || null,
        node_modules: []
    };

    if (packageInfo.files) {
        config.source = [];
        for (var i = 0; i < packageInfo.files.length; i++) {
            config.source.push(joinPath(config.rootdir, packageInfo.files[i]));
        }
    }
    if (packageInfo.dependencies) {
        for (var p in packageInfo.dependencies) {
            if (packageInfo.dependencies.hasOwnProperty(p)) {
                config.node_modules.push(p);
            }
        }
    }

    error = this.addConfig(config);
    if (error) {
        return error;
    }

    this.packageInfo = packageInfo;

    // load .npmignore file.
    var ignoreFilepath = joinPath(config.rootdir, '.npmignore');
    if ( ! fs.existsSync(ignoreFilepath)) {
        return error;
    }

    var patterns = fs.readFileSync(ignoreFilepath, 'utf8').split('\n');
    for (var j = 0; j < patterns.length; j++) {
        if (patterns[j] !== '') {
            this._addIgnorePattern('**/' + patterns[j]);
        }
    }

    return error;
};

// this sub function is hook point for jasmine-spy.
Codegs.prototype._require = function (filepath) {
    return require(filepath);
};

Codegs.prototype.run = function () {
    var steps = [
            this.setup,
            this.addCoreFiles,
            this.addNodeCoreFiles,
            this.addNodeModules,
            this.addSourceFiles,
            this.compile,
            this.out
        ],
        error = null;

    for (var i = 0; (i < steps.length) && (error === null); i++) {
        error = steps[i].apply(this);
    }
    return error;
};

Codegs.prototype.setup = function (mockfs) {
    var fs = mockfs || require('fs');

    // config.rootdir
    if ( ! this.config.rootdir) {
        this.config.rootdir = process.cwd();
    }

    // config.mainfile
    if ( ! this.config.mainfile) {
        this.config.mainfile = process.cwd();
    }

    // config.core
    if (this.config.core) {
        this.config.core = path.resolve(this.config.rootdir, this.config.core);
        if ( ! fs.existsSync(this.config.core)) {
            return 'Error: core module directory is not existent.';
        }
        if ( ! fs.statSync(this.config.core).isDirectory()) {
            return 'Error: core module directory is not directory.';
        }
    } else {
        // default value. not check if it exists.
        this.config.core = path.resolve(this.config.rootdir, './core');
    }

    // config.node_core
    if (this.config.node_core) {
        this.config.node_core = path.resolve(this.config.rootdir, this.config.node_core);
        if ( ! fs.existsSync(this.config.node_core)) {
            return 'Error: node_core module directory is not existent.';
        }
        if ( ! fs.statSync(this.config.node_core).isDirectory()) {
            return 'Error: node_core module directory is not directory.';
        }
    } else {
        // default value. not check if it exists.
        this.config.node_core = path.resolve(this.config.rootdir, './node_core');
    }

    // files.main
    this.files.main = path.resolve(this.config.rootdir, this.config.mainfile);
    if ( ! fs.existsSync(this.files.main)) {
        this.files.main = null;
        return 'Error: main file is not existent.';
    }
    if ( ! fs.statSync(this.files.main).isFile()) {
        this.files.main = null;
        return 'Error: main file is not valid filetype.';
    }
    this._addIgnoreFilepath(this.files.main);

    // files.kernel
    if (this.config.kernel) {

        this.files.kernel = path.resolve(this.config.rootdir, this.config.kernel);
        if ( ! fs.existsSync(this.files.kernel)) {
            this.files.kernel = null;
            return 'Error: kernel file is not existent.';
        }
        if ( ! fs.statSync(this.files.kernel).isFile()) {
            this.files.kernel = null;
            return 'Error: kernel file is not valid filetype.';
        }
        this._addIgnoreFilepath(this.files.kernel);
    }

    return null;
};

Codegs.prototype.addCoreFiles = function (mockfs) {

    if (typeof this.config.core !== 'string') {
        return 'Error: core file directory is not specified.';
    }

    var coredir = joinPath(this.config.core);
    var error = this._addFilesToList(this.files.core, coredir, 'core/', false, mockfs);
    if (error === null) {
        coredir = coredir.slice(-1) === '/' ? coredir.slice(0, -1) : coredir;
        this._addIgnoreFilepath(coredir);
    }
    return error;
};

Codegs.prototype.addNodeCoreFiles = function (mockfs) {

    if (typeof this.config.node_core !== 'string') {
        return 'Error: node_core file directory is not specified.';
    }

    var nodecoredir = joinPath(this.config.node_core);
    var error = this._addFilesToList(this.files.node_core, nodecoredir, 'node_core/', false, mockfs);
    if (error === null) {
        nodecoredir = nodecoredir.slice(-1) === '/' ? nodecoredir.slice(0, -1) : nodecoredir;
        this._addIgnoreFilepath(nodecoredir);
    }
    return error;
};

Codegs.prototype.addNodeModules = function (mockfs) {

    var error = null;
    var rootdir = joinPath(this.config.rootdir);
    var moduledir = joinPath(rootdir, './node_modules');

    if (this.config.node_modules === null) {
        error = this._addFilesToList(this.files.node_modules, moduledir, '/node_modules/', false, mockfs);
        if (error === null) {
            this._addIgnoreFilepath(moduledir);
        }
        return error;
    }

    var i, source, storepath;
    for (i = 0; i < this.config.node_modules.length; i++) {

        storepath = source = joinPath(moduledir, this.config.node_modules[i]);
        storepath = storepath === rootdir ? '/' : storepath.slice(rootdir.length);

        error = this._addFilesToList(this.files.node_modules, source, storepath, false, mockfs);
        if (error === null) {
            source = source.slice(-1) === '/' ? source.slice(0, -1) : source;
            this._addIgnoreFilepath(source);
        } else {
            break;
        }
    }
    return error;
};

Codegs.prototype.addSourceFiles = function (mockfs) {

    if (this.config.source === null) {
        this.config.source = [];
        this.config.source.push(this.config.rootdir);
    }

    var i, source, storepath, error = null;
    var rootdir = joinPath(this.config.rootdir);

    for (i = 0; i < this.config.source.length; i++) {

        storepath = source = joinPath(this.config.source[i]);

        if (storepath.slice(0, rootdir.length) !== rootdir) {
            return 'Error: Source directory is outside project root.';
        }
        storepath = storepath === rootdir ? '/' : storepath.slice(rootdir.length);

        error = this._addFilesToList(this.files.source, source, storepath, true, mockfs);
        if (error === null) {
            source = source.slice(-1) === '/' ? source.slice(0, -1) : source;
            this._addIgnoreFilepath(source);
        } else {
            break;
        }
    }
    return error;
};

Codegs.prototype.compile = function (mockfs) {
    var fs = mockfs || require('fs');

    this.content = '';
    var content = '';

    content = Codegs._compileFilesList(this.files.core, mockfs);
    this.content += content;

    content = Codegs._compileFilesList(this.files.node_core, mockfs);
    this.content += content;

    content = Codegs._compileFilesList(this.files.node_modules, mockfs);
    this.content += content;

    content = Codegs._compileFilesList(this.files.source, mockfs);
    this.content += content;

    var mainfileList = Codegs._createFilesList(this.config, this.files.main, 'main');
    content = Codegs._compileFilesList(mainfileList, mockfs);
    this.content += content;

    if (this.files.kernel) {
        var corefileList = {};
        corefileList[this.files.kernel] = { type: 'core', path: '' };
        content = Codegs._compileFilesList(corefileList, mockfs);
    } else {
        // kernel === null, then should not wrap. just read and append.
        content = fs.readFileSync(require.resolve('./module.js'));
    }
    this.content += content;

    return null;
};

Codegs.prototype.out = function (mockfs) {
    var fs = mockfs || require('fs');

    if (this.config.output) {
        try {
            fs.writeFileSync(this.config.output, this.content);
        } catch(e) {
            return 'Error: ' + e;
        }
        return null;
    }

    return this.content;
};

Codegs._createFilesList = function (config, file, type) {
    var rootdir = joinPath(config.rootdir);
    var rootlength = rootdir.length　- (rootdir.slice(-1) === '/' ? 1 : 0);

    var mainpath = file.slice(rootlength);
    var fileList = {};

    fileList[file] = { type: type, path: mainpath};

    return fileList;
};

Codegs._compileFilesList = function (filesList, mockfs) {
    var fs = mockfs || require('fs');
    var codegsModule = require('./module');

    var file, content, mergedContent = '';

    for (file in filesList) {
        if (filesList.hasOwnProperty(file)) {
            content = fs.readFileSync(file, {encoding: 'utf8'});
            content = codegsModule.wrap(content, filesList[file].path, filesList[file].type);
            if (content === null) {
                throw new Error("Error: Invalid filepath '" + filesList[file].path +
                                "'or type '" + filesList[file].type + "'");
            }
            mergedContent += content;
        }
    }
    return mergedContent;
};

Codegs.prototype._addIgnoreFilepath = function (filepath) {
    this.ignoreFilepath.push(filepath);
};

Codegs.prototype._addIgnorePattern = function (pattern) {
    this.ignorePattern.push(pattern);
};

Codegs.prototype._isIgnoreFile = function (file, checkPattern) {
    for (var i = 0; i < this.ignoreFilepath.length; i++) {
        if (file === this.ignoreFilepath[i]) {
            return true;
        }
    }
    if (checkPattern) {
        for (var j = 0; j < this.ignorePattern.length; j++) {
            if (minimatch(file, this.ignorePattern[j])) {
                return true;
            }
        }
    }
    return false;
};

Codegs.prototype._addFilesToList = function (list, source, storepath, checkPattern, mockfs) {
    var fs = mockfs || require('fs');

    if (this._isIgnoreFile(source, checkPattern)) {
        return null;
    }

    if ( ! fs.existsSync(source)) {
        //return ("Error: File or Directory not Exists. '" + source + "'");
        return null;
    }

    var stat = fs.statSync(source);

    if (stat.isFile()) {
        // If specific file passed, no file type checking to add.
        if (list[source] === undefined) {
            list[source] = {
                type : source.slice(-5) === '.json' ? 'json' : 'js',
                path : storepath
            };
        }
        return null;
    }
    if (stat.isDirectory()) {
        var files = fs.readdirSync(source);

        var error;
        for (var i = 0; i < files.length; i++) {
            if (this._isIgnoreFile(files[i], checkPattern)) {
                continue;
            }
            stat = fs.statSync(joinPath(source, files[i]));
            if (stat.isFile()) {
                // File types to add are only '.js' and '.json', by default.
                if (! ( ((files[i].length > 3) && (files[i].slice(-3) === '.js')) ||
                        ((files[i].length > 5) && (files[i].slice(-5) === '.json'))) ) {
                    continue;
                }
            }
            error = this._addFilesToList(list,
                                    joinPath(source, files[i]),
                                    joinPath(storepath, files[i]),
                                    checkPattern,
                                    mockfs);
            if (error !== null) {
                return error;
            }
        }
        return null;
    }
    return null;
};

module.exports = Codegs;
<|endoftext|>