<commit_before>// docready for modern browsers
document.addEventListener("DOMContentLoaded", function(event) {

    var datasrc = dataReposAllOfThem;
    //var datasrc = dataReposAll;
    //var datasrc = dataReposSome;
    //console.log(datasrc);

    // Sort datasource array by date
    // ------------------------------------------------------------
    datasrc.sort(function(a, b) {
        return a.author_date_unix_timestamp - b.author_date_unix_timestamp;
    });
    //console.log(datasrc);

    // Round up the date so that we can sort commits from different repos by date
    // ------------------------------------------------------------
    var roundDate = function(timeStamp) {
        var d = new Date(timeStamp);
        return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0);
    };

    // Calculate number of days between two dates
    // ------------------------------------------------------------
    var daysBetween = function(timeStampA, timeStampB) {
        var oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
        var firstDate = new Date(timeStampA * 1000);
        var secondDate = new Date(timeStampB * 1000);
        var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
        return diffDays;
    };

    // Calculate number of days since one date
    // ------------------------------------------------------------
    var daysSince = function(timeStamp) {
        var oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
        var sinceDate = new Date(timeStamp * 1000);
        var now = Date.now();
        var diffDays = Math.round(Math.abs((sinceDate.getTime() - now)/(oneDay)));
        return diffDays;
    };

    // Get the key in array that occurs most often
    // ------------------------------------------------------------
    var mostOften = function(array) {
        if(array.length === 0) {
            return null;
        }
        var modeMap = {};
        var maxEl = array[0], maxCount = 1;
        for(var i = 0; i < array.length; i++) {
            var el = array[i];
            if (modeMap[el] === null) {
                modeMap[el] = 1;
            } else {
                modeMap[el]++;
            }
            if(modeMap[el] > maxCount) {
                maxEl = el;
                maxCount = modeMap[el];
            }
        }
        return maxEl;
    };

    // Count duplicate keys within an array
    // ------------------------------------------------------------
    var groupByDuplicatesInArray = function(array) {
        if(array.length === 0) {
            return null;
        }
        var counts = {};
        array.forEach(function(x) {
            counts[x] = (counts[x] || 0) + 1;
        });
        return counts;
    };

    // Create object array based on key and its value
    // ------------------------------------------------------------
    var groupByKeyAndValue = function(data, key, val) {
        var arr = [];
        for (var i in data) {
            if (data[i][key] == val) {
                arr.push(data[i]);
            }
        }
        return arr;
    };
    var weekMonday = groupByKeyAndValue(datasrc, 'date_day_week', 'Mon');
    //console.log(weekMonday);

    // Create array based on key value
    // ------------------------------------------------------------
    var arrayByKey = function(data, key) {
        var arr = [];
        for (var i in data) {
            if (data[i][key] === undefined) {
                data[i][key] = '0';
            }
            arr.push(data[i][key]);
        }
        return arr;
    };
    var arrayCommitNr = arrayByKey(datasrc, 'commit_nr');
    //console.log(arrayCommitNr);
    var arrayImpact = arrayByKey(datasrc, 'impact');
    //console.log(arrayImpact);
    var arrayTimestamp = arrayByKey(datasrc, 'author_date_unix_timestamp');
    //console.log(arrayTimestamp);

    // most commited day overall
    //console.log(mostOften(arrayByKey(datasrc, 'date_day_week')));

    // Create array based on key value, sorted
    // ------------------------------------------------------------
    var arrayByKeySorted = function(data, key) {
        var arr = [];
        for (var i in data) {
            arr.push(data[i][key]);
        }
        arr.sort(function(a, b) {
            return a - b;
        });
        return arr;
    };
    var arrayByKeySortedVar = arrayByKeySorted(datasrc, 'author_date_unix_timestamp');
    //console.log(arrayByKeySortedVar);

    // Return number that results from adding a key to itself
    // ------------------------------------------------------------
    var totalSum = function(data) {
        var sum = 0;
        for (var i = 0; i < data.length; i++) {
            sum += parseInt(data[i]);
          //console.log(sum);
        }
        return sum;
    };
    var arrayImpactTotal = totalSum(arrayImpact);
    //console.log(arrayImpactTotal);

    // Return number of items in an object
    // ------------------------------------------------------------
    var itemsSum = function(data) {
        var sum = 0;
        for (var i = 0; i < data.length; i++) {
            sum += 1;
        }
        return sum;
    };
    var arrayTotal = itemsSum(datasrc);
    //console.log(arrayTotal);

    // Return average value based on number of items in an object
    // ------------------------------------------------------------
    var itemsAverage = function(data) {
        var sum = 0;
        for (var i = 0; i < data.length; i++) {
            sum += parseInt(data[i]);
        }
        var avg = sum/data.length;
        return avg;
    };
    var arrayAverage = itemsAverage(datasrc);
    //console.log(arrayAverage);

    // Create array based on key values added to themselves
    // ------------------------------------------------------------
    var sumArray = function(data) {
        var sum = 0;
        var arr = [];
        for (var i in data) {
            sum += parseInt(data[i]);
            arr.push(sum);
          //console.log(sum);
        }
        return arr;
    };
    var arrayImpactSum = sumArray(arrayImpact);
    //console.log(arrayImpactSum);

    // Create object array based on key
    // ------------------------------------------------------------
    var groupByAuto = function(data, key) {
        var groups = {};
        for (var i in data) {
            if (!groups.hasOwnProperty(data[i][key])) {
                groups[data[i][key]] = [];
            }
            groups[data[i][key]].push(data[i]);
        }
        return groups;
    };
    var objDateDayWeek = groupByAuto(datasrc, 'date_day_week');
    //console.log(objDateDayWeek);
    var objRepository = groupByAuto(datasrc, 'repository');
    //console.log(objRepository);

    // Create object array based on key
    // ------------------------------------------------------------
    var groupByAuthors = function(data, author) {
        var groups = {};
        for (var i in data) {
            var a = data[i][author].match(/[^@]*/);
            if (!groups.hasOwnProperty(data[i][author])) {
                groups[data[i][author]] = [];
            }
            groups[data[i][author]].push(data[i]);
        }
        return groups;
    };
    var groupByAuthorsVar = groupByAuthors(datasrc, 'author_email');
    //console.log(groupByAuthorsVar);

    // Create array based on key value
    // ------------------------------------------------------------
    var arrayAllRepos = function(data) {
        var arr = [];
        for (var i in data) {
            arr.push(data[i]);
        }
        return arr;
    };
    var arrayAllReposLength = function(data) {
        var arr = [];
        for (var i in data) {
            arr.push(data[i].length);
        }
        return arr;
    };
    var arrayAllReposVar = arrayAllRepos(Object.keys(objRepository));
    //console.log(arrayAllReposVar);
    var arrayAllReposValueArrayLength = arrayAllReposLength(Object.keys(objRepository));
    //console.log(arrayAllReposValueArrayLength);

    // Merge two arrays of identical length
    // ------------------------------------------------------------
    var arraysMerge = function(keys, values) {
        var obj = {};
        for (var i = 0; i < keys.length; i++) {
            obj[keys[i]] = values[i];
        }
        return obj;
    };

    // Create array with year changes
    // ------------------------------------------------------------
    var arrayYearChanges = function(data, year) {
        var arr = [];
        for (var i in data) {
            var currentYear = data[i][year];
            var previousYear;
            if (previousYear != currentYear) {
                arr.push(data[i][year]);
            } else {
                arr.push('');
            }
            previousYear = data[i][year];
        }
        return arr;
    };
    var arrayYearChangesVar = arrayYearChanges(datasrc, 'date_year');
    //console.log(arrayYearChangesVar);

    // Get author stats and output it on a dedicated object
    // ------------------------------------------------------------
    var groupByAuthorsStats = function(data, author) {
        var obja = {};
        for (var i in data) {
            if (!obja.hasOwnProperty(data[i][author])) {
                obja[data[i][author]] = [];
            }
            obja[data[i][author]].push(data[i]);
        }
        // create an object to receive customised author stats
        var stats = {};
        // iterate through 'obja' object
        for (var b in obja) {
           if (obja.hasOwnProperty(b)) {
                var objb = obja[b];
                // calculate total impact
                var authorImpact = arrayByKey(objb, 'impact');
                var authorImpactSum = totalSum(authorImpact);
                // calculate total number of commits
                var authorNrCommits = itemsSum(objb);
                // push new data to array
                if (!stats.hasOwnProperty(b)) {
                    stats[b] = [];
                }
                stats[b].push({
                    commits: authorNrCommits,
                    impact: authorImpactSum
                });
            }
        }
        return stats;
    };
    var groupByAuthorsStatsVar = groupByAuthorsStats(datasrc, 'author_email');
    //console.log(groupByAuthorsStatsVar);

    // Get author stats and output it on a dedicated array
    // ------------------------------------------------------------
    var arrayAuthorsStats = function(data, type) {
        var obja = {};
        for (var i in data) {
            if (!obja.hasOwnProperty(data[i].author_email)) {
                obja[data[i].author_email] = [];
            }
            obja[data[i].author_email].push(data[i]);
        }
        // create an object to receive customised author stats
        var stats = [];
        // iterate through 'obja' object

        for (var b in obja) {
           if (obja.hasOwnProperty(b)) {
                var objb = obja[b];
                // calculate total impact
                var authorImpact = arrayByKey(objb, 'impact');
                var authorImpactSum = totalSum(authorImpact);
                // calculate total number of commits
                var authorNrCommits = itemsSum(objb);
                // calculate author's most commited day
                var authorDays = arrayByKey(objb, 'date_day_week');
                var authorDay = mostOften(authorDays);
                // calculate days between first and last commits
                var commitDateFirst = objb[0].author_date_unix_timestamp;
                var commitDateLast = objb[objb.length - 1].author_date_unix_timestamp;
                var daysActive = daysBetween(commitDateFirst, commitDateLast);
                // calculate days since first and last commits
                var daysSinceFirstCommit = daysSince(commitDateFirst);
                var daysSinceLastCommit = daysSince(commitDateLast);
                // push new data to array
                if (type == 'author') {
                    stats.push(b);
                } else if (type == 'commits') {
                    stats.push(authorNrCommits);
                } else if (type == 'impact') {
                    stats.push(authorImpactSum);
                } else if (type == 'day') {
                    stats.push(authorDay);
                } else if (type == 'daysActive') {
                    stats.push(daysActive);
                } else if (type == 'daysSinceFirstCommit') {
                    stats.push(daysSinceFirstCommit);
                } else if (type == 'daysSinceLastCommit') {
                    stats.push(daysSinceLastCommit);
                } else if (type == 'weekdays') {
                    stats.push({
                        author : b,
                        weekdays: groupByDuplicatesInArray(authorDays)
                    });
                } else {
                    stats.push({
                        author: b,
                        commits: authorNrCommits,
                        impact: authorImpactSum,
                        day : authorDay,
                        weekdays : groupByDuplicatesInArray(authorDays),
                        daysActive : daysActive,
                        commitDateFirst : commitDateFirst,
                        commitDateLast : commitDateLast,
                        daysSinceFirstCommit : daysSinceFirstCommit,
                        daysSinceLastCommit : daysSinceLastCommit
                    });
                }
            }
        }
        return stats;
    };
    var arrayAuthorsStatsVarAll = arrayAuthorsStats(datasrc);
    //console.log(arrayAuthorsStatsVarAll);
    var arrayAuthorsStatsVarAuthor = arrayAuthorsStats(datasrc, 'author');
    //console.log(arrayAuthorsStatsVarAuthor);
    var arrayAuthorsStatsVarCommits = arrayAuthorsStats(datasrc, 'commits');
    //console.log(arrayAuthorsStatsVarCommits);
    var arrayAuthorsStatsVarImpact = arrayAuthorsStats(datasrc, 'impact');
    //console.log(arrayAuthorsStatsVarImpact);
    var arrayAuthorsStatsVarDay = arrayAuthorsStats(datasrc, 'day');
    //console.log(arrayAuthorsStatsVarDay);
    var arrayAuthorsStatsVarWeekdays = arrayAuthorsStats(datasrc, 'weekdays');
    // console.log(arrayAuthorsStatsVarWeekdays);
    var arrayAuthorsStatsVarDaysActive = arrayAuthorsStats(datasrc, 'daysActive');
    // console.log(arrayAuthorsStatsVarDaysActive);
    var arrayAuthorsStatsVarDaysSinceFirstCommit = arrayAuthorsStats(datasrc, 'daysSinceFirstCommit');
    // console.log(arrayAuthorsStatsVarDaysSinceFirstCommit);
    var arrayAuthorsStatsVarDaysSinceLastCommit = arrayAuthorsStats(datasrc, 'daysSinceLastCommit');
    // console.log(arrayAuthorsStatsVarDaysSinceLastCommit);

    // Some global stats
    // ------------------------------------------------------------
    var arrayAuthorsStatsVarDaysActiveAverage = itemsAverage(arrayAuthorsStatsVarDaysActive);
    console.log('The average number of active days of a single committer is ' + arrayAuthorsStatsVarDaysActiveAverage + ', which is the equivalent to ' + arrayAuthorsStatsVarDaysActiveAverage / 365 + ' years');
    var arrayAuthorsStatsVarCommitsAverage = itemsAverage(arrayAuthorsStatsVarCommits);
    console.log('The average number of commits by a single committer is ' + arrayAuthorsStatsVarCommitsAverage + ', which is the equivalent to ' + arrayAuthorsStatsVarCommitsAverage / arrayAuthorsStatsVarDaysActiveAverage + ' a day');
    var arrayAuthorsStatsVarImpactAverage = itemsAverage(arrayAuthorsStatsVarImpact);
    console.log('The average impact by a single committer is ' + arrayAuthorsStatsVarImpactAverage + ' lines of code');

    // var arrayAuthorsStatsAuthorAndCommits = arraysMerge(arrayAuthorsStatsVarAuthor, arrayAuthorsStatsVarCommits);
    // console.log(arrayAuthorsStatsAuthorAndCommits);
    // var arrayAuthorsStatsAuthorAndImpact = arraysMerge(arrayAuthorsStatsVarAuthor, arrayAuthorsStatsVarImpact);
    // console.log(arrayAuthorsStatsAuthorAndImpact);

    // Create array of objects with authors and their impact
    // ------------------------------------------------------------
    var arrayAuthorImpact = function(data, author, impact) {
        var arr = [];
        for (var i in data) {
            var a = data[i][author].match(/[^@]*/);
            arr.push('{ "author":"' + a + '", "impact":"' + data[i][impact] + '"},');
        }
        return arr;
    };
    var arrayAuthorImpactVar = arrayAuthorImpact(datasrc, 'author_email', 'impact');
    //console.log(arrayAuthorImpactVar);

/*
    new Chartist.Line('.ct-chart-impact', {
        labels: arrayYearChangesVar,
        series: [
          arrayImpact
        ]
    }, {
        height: '300px',
        high: 900000,
        low: -300000,
        showArea: true,
        showLine: true,
        showPoint: false,
        fullWidth: true,
        chartPadding: {
            top: 0,
            right: 0,
            bottom: 0,
            left: 40
        },
        axisX: {
            showLabel: true,
            showGrid: true
        }
    });

    new Chartist.Line('.ct-chart-impact-cumulative', {
        labels: arrayYearChangesVar,
        series: [
          arrayImpactSum
        ]
    }, {
        height: '300px',
      //high: 1400000, // with 'dataReposSome'
      //high: 3700000, // with 'dataReposAll'
        high: 26000000, // with 'dataReposAll' based on 'dataReposAllOfThemClean'
      //high: 8000000000, // with 'dataReposAll' based on 'dataReposAllOfThemClean'
        low: 1000,
        showArea: true,
        showLine: true,
        showPoint: false,
        fullWidth: true,
        chartPadding: {
            top: 0,
            right: 0,
            bottom: 0,
            left: 40
        },
        axisX: {
            showLabel: true,
            showGrid: true
        }
    });
*/
});
<commit_msg>Remove charts, worry about them later<commit_after>// docready for modern browsers
document.addEventListener("DOMContentLoaded", function(event) {

    var datasrc = dataReposAllOfThem;
    //var datasrc = dataReposAll;
    //var datasrc = dataReposSome;
    //console.log(datasrc);

    // Sort datasource array by date
    // ------------------------------------------------------------
    datasrc.sort(function(a, b) {
        return a.author_date_unix_timestamp - b.author_date_unix_timestamp;
    });
    //console.log(datasrc);

    // Round up the date so that we can sort commits from different repos by date
    // ------------------------------------------------------------
    var roundDate = function(timeStamp) {
        var d = new Date(timeStamp);
        return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0);
    };

    // Calculate number of days between two dates
    // ------------------------------------------------------------
    var daysBetween = function(timeStampA, timeStampB) {
        var oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
        var firstDate = new Date(timeStampA * 1000);
        var secondDate = new Date(timeStampB * 1000);
        var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
        return diffDays;
    };

    // Calculate number of days since one date
    // ------------------------------------------------------------
    var daysSince = function(timeStamp) {
        var oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
        var sinceDate = new Date(timeStamp * 1000);
        var now = Date.now();
        var diffDays = Math.round(Math.abs((sinceDate.getTime() - now)/(oneDay)));
        return diffDays;
    };

    // Get the key in array that occurs most often
    // ------------------------------------------------------------
    var mostOften = function(array) {
        if(array.length === 0) {
            return null;
        }
        var modeMap = {};
        var maxEl = array[0], maxCount = 1;
        for(var i = 0; i < array.length; i++) {
            var el = array[i];
            if (modeMap[el] === null) {
                modeMap[el] = 1;
            } else {
                modeMap[el]++;
            }
            if(modeMap[el] > maxCount) {
                maxEl = el;
                maxCount = modeMap[el];
            }
        }
        return maxEl;
    };

    // Count duplicate keys within an array
    // ------------------------------------------------------------
    var groupByDuplicatesInArray = function(array) {
        if(array.length === 0) {
            return null;
        }
        var counts = {};
        array.forEach(function(x) {
            counts[x] = (counts[x] || 0) + 1;
        });
        return counts;
    };

    // Create object array based on key and its value
    // ------------------------------------------------------------
    var groupByKeyAndValue = function(data, key, val) {
        var arr = [];
        for (var i in data) {
            if (data[i][key] == val) {
                arr.push(data[i]);
            }
        }
        return arr;
    };
    var weekMonday = groupByKeyAndValue(datasrc, 'date_day_week', 'Mon');
    //console.log(weekMonday);

    // Create array based on key value
    // ------------------------------------------------------------
    var arrayByKey = function(data, key) {
        var arr = [];
        for (var i in data) {
            if (data[i][key] === undefined) {
                data[i][key] = '0';
            }
            arr.push(data[i][key]);
        }
        return arr;
    };
    var arrayCommitNr = arrayByKey(datasrc, 'commit_nr');
    //console.log(arrayCommitNr);
    var arrayImpact = arrayByKey(datasrc, 'impact');
    //console.log(arrayImpact);
    var arrayTimestamp = arrayByKey(datasrc, 'author_date_unix_timestamp');
    //console.log(arrayTimestamp);

    // most commited day overall
    //console.log(mostOften(arrayByKey(datasrc, 'date_day_week')));

    // Create array based on key value, sorted
    // ------------------------------------------------------------
    var arrayByKeySorted = function(data, key) {
        var arr = [];
        for (var i in data) {
            arr.push(data[i][key]);
        }
        arr.sort(function(a, b) {
            return a - b;
        });
        return arr;
    };
    var arrayByKeySortedVar = arrayByKeySorted(datasrc, 'author_date_unix_timestamp');
    //console.log(arrayByKeySortedVar);

    // Return number that results from adding a key to itself
    // ------------------------------------------------------------
    var totalSum = function(data) {
        var sum = 0;
        for (var i = 0; i < data.length; i++) {
            sum += parseInt(data[i]);
          //console.log(sum);
        }
        return sum;
    };
    var arrayImpactTotal = totalSum(arrayImpact);
    //console.log(arrayImpactTotal);

    // Return number of items in an object
    // ------------------------------------------------------------
    var itemsSum = function(data) {
        var sum = 0;
        for (var i = 0; i < data.length; i++) {
            sum += 1;
        }
        return sum;
    };
    var arrayTotal = itemsSum(datasrc);
    //console.log(arrayTotal);

    // Return average value based on number of items in an object
    // ------------------------------------------------------------
    var itemsAverage = function(data) {
        var sum = 0;
        for (var i = 0; i < data.length; i++) {
            sum += parseInt(data[i]);
        }
        var avg = sum/data.length;
        return avg;
    };
    var arrayAverage = itemsAverage(datasrc);
    //console.log(arrayAverage);

    // Create array based on key values added to themselves
    // ------------------------------------------------------------
    var sumArray = function(data) {
        var sum = 0;
        var arr = [];
        for (var i in data) {
            sum += parseInt(data[i]);
            arr.push(sum);
          //console.log(sum);
        }
        return arr;
    };
    var arrayImpactSum = sumArray(arrayImpact);
    //console.log(arrayImpactSum);

    // Create object array based on key
    // ------------------------------------------------------------
    var groupByAuto = function(data, key) {
        var groups = {};
        for (var i in data) {
            if (!groups.hasOwnProperty(data[i][key])) {
                groups[data[i][key]] = [];
            }
            groups[data[i][key]].push(data[i]);
        }
        return groups;
    };
    var objDateDayWeek = groupByAuto(datasrc, 'date_day_week');
    //console.log(objDateDayWeek);
    var objRepository = groupByAuto(datasrc, 'repository');
    //console.log(objRepository);

    // Create object array based on key
    // ------------------------------------------------------------
    var groupByAuthors = function(data, author) {
        var groups = {};
        for (var i in data) {
            var a = data[i][author].match(/[^@]*/);
            if (!groups.hasOwnProperty(data[i][author])) {
                groups[data[i][author]] = [];
            }
            groups[data[i][author]].push(data[i]);
        }
        return groups;
    };
    var groupByAuthorsVar = groupByAuthors(datasrc, 'author_email');
    //console.log(groupByAuthorsVar);

    // Create array based on key value
    // ------------------------------------------------------------
    var arrayAllRepos = function(data) {
        var arr = [];
        for (var i in data) {
            arr.push(data[i]);
        }
        return arr;
    };
    var arrayAllReposLength = function(data) {
        var arr = [];
        for (var i in data) {
            arr.push(data[i].length);
        }
        return arr;
    };
    var arrayAllReposVar = arrayAllRepos(Object.keys(objRepository));
    //console.log(arrayAllReposVar);
    var arrayAllReposValueArrayLength = arrayAllReposLength(Object.keys(objRepository));
    //console.log(arrayAllReposValueArrayLength);

    // Merge two arrays of identical length
    // ------------------------------------------------------------
    var arraysMerge = function(keys, values) {
        var obj = {};
        for (var i = 0; i < keys.length; i++) {
            obj[keys[i]] = values[i];
        }
        return obj;
    };

    // Create array with year changes
    // ------------------------------------------------------------
    var arrayYearChanges = function(data, year) {
        var arr = [];
        for (var i in data) {
            var currentYear = data[i][year];
            var previousYear;
            if (previousYear != currentYear) {
                arr.push(data[i][year]);
            } else {
                arr.push('');
            }
            previousYear = data[i][year];
        }
        return arr;
    };
    var arrayYearChangesVar = arrayYearChanges(datasrc, 'date_year');
    //console.log(arrayYearChangesVar);

    // Get author stats and output it on a dedicated object
    // ------------------------------------------------------------
    var groupByAuthorsStats = function(data, author) {
        var obja = {};
        for (var i in data) {
            if (!obja.hasOwnProperty(data[i][author])) {
                obja[data[i][author]] = [];
            }
            obja[data[i][author]].push(data[i]);
        }
        // create an object to receive customised author stats
        var stats = {};
        // iterate through 'obja' object
        for (var b in obja) {
           if (obja.hasOwnProperty(b)) {
                var objb = obja[b];
                // calculate total impact
                var authorImpact = arrayByKey(objb, 'impact');
                var authorImpactSum = totalSum(authorImpact);
                // calculate total number of commits
                var authorNrCommits = itemsSum(objb);
                // push new data to array
                if (!stats.hasOwnProperty(b)) {
                    stats[b] = [];
                }
                stats[b].push({
                    commits: authorNrCommits,
                    impact: authorImpactSum
                });
            }
        }
        return stats;
    };
    var groupByAuthorsStatsVar = groupByAuthorsStats(datasrc, 'author_email');
    //console.log(groupByAuthorsStatsVar);

    // Get author stats and output it on a dedicated array
    // ------------------------------------------------------------
    var arrayAuthorsStats = function(data, type) {
        var obja = {};
        for (var i in data) {
            if (!obja.hasOwnProperty(data[i].author_email)) {
                obja[data[i].author_email] = [];
            }
            obja[data[i].author_email].push(data[i]);
        }
        // create an object to receive customised author stats
        var stats = [];
        // iterate through 'obja' object

        for (var b in obja) {
           if (obja.hasOwnProperty(b)) {
                var objb = obja[b];
                // calculate total impact
                var authorImpact = arrayByKey(objb, 'impact');
                var authorImpactSum = totalSum(authorImpact);
                // calculate total number of commits
                var authorNrCommits = itemsSum(objb);
                // calculate author's most commited day
                var authorDays = arrayByKey(objb, 'date_day_week');
                var authorDay = mostOften(authorDays);
                // calculate days between first and last commits
                var commitDateFirst = objb[0].author_date_unix_timestamp;
                var commitDateLast = objb[objb.length - 1].author_date_unix_timestamp;
                var daysActive = daysBetween(commitDateFirst, commitDateLast);
                // calculate days since first and last commits
                var daysSinceFirstCommit = daysSince(commitDateFirst);
                var daysSinceLastCommit = daysSince(commitDateLast);
                // push new data to array
                if (type == 'author') {
                    stats.push(b);
                } else if (type == 'commits') {
                    stats.push(authorNrCommits);
                } else if (type == 'impact') {
                    stats.push(authorImpactSum);
                } else if (type == 'day') {
                    stats.push(authorDay);
                } else if (type == 'daysActive') {
                    stats.push(daysActive);
                } else if (type == 'daysSinceFirstCommit') {
                    stats.push(daysSinceFirstCommit);
                } else if (type == 'daysSinceLastCommit') {
                    stats.push(daysSinceLastCommit);
                } else if (type == 'weekdays') {
                    stats.push({
                        author : b,
                        weekdays: groupByDuplicatesInArray(authorDays)
                    });
                } else {
                    stats.push({
                        author: b,
                        commits: authorNrCommits,
                        impact: authorImpactSum,
                        day : authorDay,
                        weekdays : groupByDuplicatesInArray(authorDays),
                        daysActive : daysActive,
                        commitDateFirst : commitDateFirst,
                        commitDateLast : commitDateLast,
                        daysSinceFirstCommit : daysSinceFirstCommit,
                        daysSinceLastCommit : daysSinceLastCommit
                    });
                }
            }
        }
        return stats;
    };
    var arrayAuthorsStatsVarAll = arrayAuthorsStats(datasrc);
    //console.log(arrayAuthorsStatsVarAll);
    var arrayAuthorsStatsVarAuthor = arrayAuthorsStats(datasrc, 'author');
    //console.log(arrayAuthorsStatsVarAuthor);
    var arrayAuthorsStatsVarCommits = arrayAuthorsStats(datasrc, 'commits');
    //console.log(arrayAuthorsStatsVarCommits);
    var arrayAuthorsStatsVarImpact = arrayAuthorsStats(datasrc, 'impact');
    //console.log(arrayAuthorsStatsVarImpact);
    var arrayAuthorsStatsVarDay = arrayAuthorsStats(datasrc, 'day');
    //console.log(arrayAuthorsStatsVarDay);
    var arrayAuthorsStatsVarWeekdays = arrayAuthorsStats(datasrc, 'weekdays');
    // console.log(arrayAuthorsStatsVarWeekdays);
    var arrayAuthorsStatsVarDaysActive = arrayAuthorsStats(datasrc, 'daysActive');
    // console.log(arrayAuthorsStatsVarDaysActive);
    var arrayAuthorsStatsVarDaysSinceFirstCommit = arrayAuthorsStats(datasrc, 'daysSinceFirstCommit');
    // console.log(arrayAuthorsStatsVarDaysSinceFirstCommit);
    var arrayAuthorsStatsVarDaysSinceLastCommit = arrayAuthorsStats(datasrc, 'daysSinceLastCommit');
    // console.log(arrayAuthorsStatsVarDaysSinceLastCommit);

    // Some global stats
    // ------------------------------------------------------------
    var arrayAuthorsStatsVarDaysActiveAverage = itemsAverage(arrayAuthorsStatsVarDaysActive);
    console.log('The average number of active days of a single committer is ' + arrayAuthorsStatsVarDaysActiveAverage + ', which is the equivalent to ' + arrayAuthorsStatsVarDaysActiveAverage / 365 + ' years');
    var arrayAuthorsStatsVarCommitsAverage = itemsAverage(arrayAuthorsStatsVarCommits);
    console.log('The average number of commits by a single committer is ' + arrayAuthorsStatsVarCommitsAverage + ', which is the equivalent to ' + arrayAuthorsStatsVarCommitsAverage / arrayAuthorsStatsVarDaysActiveAverage + ' a day');
    var arrayAuthorsStatsVarImpactAverage = itemsAverage(arrayAuthorsStatsVarImpact);
    console.log('The average impact by a single committer is ' + arrayAuthorsStatsVarImpactAverage + ' lines of code');

    // var arrayAuthorsStatsAuthorAndCommits = arraysMerge(arrayAuthorsStatsVarAuthor, arrayAuthorsStatsVarCommits);
    // console.log(arrayAuthorsStatsAuthorAndCommits);
    // var arrayAuthorsStatsAuthorAndImpact = arraysMerge(arrayAuthorsStatsVarAuthor, arrayAuthorsStatsVarImpact);
    // console.log(arrayAuthorsStatsAuthorAndImpact);

    // Create array of objects with authors and their impact
    // ------------------------------------------------------------
    var arrayAuthorImpact = function(data, author, impact) {
        var arr = [];
        for (var i in data) {
            var a = data[i][author].match(/[^@]*/);
            arr.push('{ "author":"' + a + '", "impact":"' + data[i][impact] + '"},');
        }
        return arr;
    };
    var arrayAuthorImpactVar = arrayAuthorImpact(datasrc, 'author_email', 'impact');
    //console.log(arrayAuthorImpactVar);

});
<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash')
const path = require('path')
const yosay = require('yosay')
const superb = require('superb')
const mkdirp = require('mkdirp')
const ghUser = require('gh-user')
const finepack = require('finepack')
const humanizeUrl = require('humanize-url')
const askName = require('inquirer-npm-name')
const Generator = require('yeoman-generator')

const { capitalizeName, setupDependenciesVersions } = require('./helpers')

const CONST = {
  LINTERS: {
    choose: ['jscs', 'jshint', 'standard']
  },

  TESTING: {
    choose: ['ava', 'jest', 'mocha', 'should', 'tap', 'tape']
  },

  TRANSPILERS: {
    choose: ['coffee-script']
  }
}

module.exports = class extends Generator {
  initializing () {
    this.licenseYear = new Date().getFullYear()
  }

  projectName () {
    this.log(yosay(`Initializing ${superb()} Project`))
    const cb = this.async()

    const promise = askName({
      name: 'name',
      message: 'Your project name',
      default: _.kebabCase(path.basename(process.cwd())),
      filter: _.kebabCase,
      validate: str => str.length > 0
    }, this)

    promise
      .then(answer => {
        const name = answer.name
        this.appName = name
        this.camelAppName = _.camelCase(name)
        this.capitalizeName = capitalizeName(this.appName)
        cb()
      })
  }

  setupPath () {
    if (path.basename(this.destinationPath()) !== this.appName) {
      this.log(
        `Your generator must be inside a folder named ${this.appName}\n
        I'll automatically create this folder.`
      )
      mkdirp(this.appName)
      this.destinationRoot(this.destinationPath(this.appName))
    }

    this.readme = this.fs.read(this.templatePath('README/header.md'))
    this.package = this.fs.read(this.templatePath('package/base.json'))
  }

  questions () {
    const cb = this.async()

    const promise = this.prompt([{
      name: 'appDescription',
      message: 'A short description of your project',
      default: "I'm a lazy"
    }, {
      name: 'userLogin',
      message: 'Would you mind telling me your username on GitHub?',
      default: 'someone'
    }, {
      name: 'cli',
      message: 'Do you need a CLI ?',
      type: 'confirm',
      default: false
    }])

    promise.then(props => {
      this.appDescription = props.appDescription
      this.userLogin = props.userLogin
      this.cli = props.cli
      cb()
    })
  }

  userInfo () {
    const cb = this.async()
    const promise = ghUser(this.userLogin)

    promise.then(user => {
      this.userName = user.name
      this.userEmail = user.email || this.user.git.email()
      this.userUrl = user.blog
      this.githubUrl = user.html_url
      this.humanizeUserUrl = humanizeUrl(this.userUrl)
      cb()
    })
  }

  transpilers () {
    const cb = this.async()

    const promise = this.prompt([{
      type: 'checkbox',
      name: 'transpilers',
      message: 'Select transpilers:',
      choices: CONST.TRANSPILERS.choose
    }])

    promise.then(props => {
      CONST.TRANSPILERS.choose
        .forEach(choice => (this[choice] = _.includes(props.transpilers, choice)))
      cb()
    })
  }

  linters () {
    const cb = this.async()

    const promise = this.prompt([{
      type: 'checkbox',
      name: 'linter',
      message: 'Select the linter:',
      choices: CONST.LINTERS.choose
    }])

    promise.then(props => {
      CONST.LINTERS.choose
        .forEach(choice => (this[choice] = _.includes(props.linter, choice)))
      cb()
    })
  }

  testing () {
    const cb = this.async()

    const promise = this.prompt([{
      type: 'checkbox',
      name: 'testing',
      message: 'Select testing tools:',
      choices: CONST.TESTING.choose
    }])

    promise.then(props => {
      CONST.TESTING.choose
        .forEach(choice => (this[choice] = _.includes(props.testing, choice)))
      cb()
    })
  }

  setup () {
    this.fs.copy(
      this.templatePath('_editorconfig'),
      this.destinationPath('.editorconfig')
    )
    this.fs.copy(
      this.templatePath('_gitignore'),
      this.destinationPath('.gitignore')
    )
    this.fs.copy(
      this.templatePath('_gitattributes'),
      this.destinationPath('.gitattributes')
    )
    this.fs.copy(
      this.templatePath('_npmignore'),
      this.destinationPath('.npmignore')
    )
    this.fs.copy(
      this.templatePath('_npmrc'),
      this.destinationPath('.npmrc')
    )
    this.fs.copy(
      this.templatePath('_travis.yml'),
      this.destinationPath('.travis.yml')
    )
    this.fs.copyTpl(
      this.templatePath('_LICENSE'),
      this.destinationPath('LICENSE'),
      this
    )

    this.package = _.template(this.package)(this)
    this.package = JSON.parse(this.package)

    if (this.cli) {
      let cliPackage = this.fs.read(this.templatePath('package/cli.json'))
      cliPackage = _.template(cliPackage)(this)
      cliPackage = JSON.parse(cliPackage)

      this.package = Object.assign({}, this.package, cliPackage)
      this.readme += this.fs.read(this.templatePath('README/install/cli.md'))

      this.fs.copyTpl(
        this.templatePath('bin/_help.txt'),
        this.destinationPath('bin/help.txt'),
        this
      )
      this.fs.copy(
        this.templatePath('bin/_index.js'),
        this.destinationPath('bin/index.js')
      )
    } else {
      this.readme += this.fs.read(this.templatePath('README/install/normal.md'))
    }

    this.fs.copy(
      this.templatePath('_bumpedrc'),
      this.destinationPath('.bumpedrc')
    )

    /* TRANSPILERS */

    CONST.TRANSPILERS.choose.forEach(transpiler =>
      (this[transpiler]) && (this.package.dependencies[transpiler] = 'latest'))

    /* TESTING */

    CONST.TESTING.choose.forEach(testing =>
      (this[testing]) && (this.package.devDependencies[testing] = 'latest'))

    let testScript = 'mocha'
    if (this.mocha) {
      this.fs.copy(
        this.templatePath('test/_mocha.opts'),
        this.destinationPath('test/mocha.opts')
      )
    }
    if (this.ava) testScript = 'ava'
    if (this.tape && !this.mocha) testScript = 'tape'
    this.package.scripts.test += testScript

    if (this.jest) {
      delete this.package.devDependencies.nyc // nyc is not needed anymore!
      this.package.scripts.coveralls = 'cat ./coverage/lcov.info | coveralls'
      this.package.scripts.test = 'jest --coverage'
      this.package.scripts['test:watch'] = 'jest --watch'
      const jestConfig = this.fs.readJSON(this.templatePath('package/jest.json'))
      this.package = Object.assign({}, this.package, jestConfig)
    }

    /* LINTERS */

    let lintScript = ''

    CONST.LINTERS.choose.forEach(linter => {
      if (this[linter]) {
        this.package.devDependencies[linter] = 'latest'
        lintScript += lintScript === '' ? linter : ' && ' + linter
      }
    })

    if (this.jshint) {
      this.fs.copy(
        this.templatePath('_jshintrc'),
        this.destinationPath('.jshintrc')
      )
    }
    if (this.jscs) {
      this.fs.copy(
        this.templatePath('_jscsrc'),
        this.destinationPath('.jscsrc')
      )
    }

    this.package.scripts.lint = lintScript

    if (this.standard) {
      this.package.devDependencies['prettier-standard'] = 'latest'
      this.package.devDependencies['standard-markdown'] = 'latest'
      this.package.scripts.prelint = 'npm run pretty'
      this.package.scripts.pretty = 'prettier-standard {core,test,bin}/**/*.js'

      this.package.devDependencies['husky'] = 'latest'
      this.package.devDependencies['lint-staged'] = 'latest'

      this.package.scripts['precommit'] = 'lint-staged'
      this.package.scripts['precommit-lint'] = 'prettier-standard'

      this.package['lint-staged'] = {
        '*.js': [
          'precommit-lint',
          'git add'
        ]
      }

      lintScript = `standard-markdown && ${lintScript}`

      if (this.mocha || this.jest) {
        this.package.standard = { env: [this.mocha ? 'mocha' : 'jest'] }
      }
    }

    this.package.scripts.lint = lintScript

    /* INDEX.JS */

    const indexExtension = this['coffee-script'] ? 'coffee' : 'js'
    this.fs.copy(
      this.templatePath(`_index.${indexExtension}`),
      this.destinationPath('index.js')
    )

    /* README */

    this.readme += this.fs.read(this.templatePath('README/body.md'))
    this.readme = _.template(this.readme)(this)
    this.fs.write(this.destinationPath('README.md'), this.readme)
  }

  dependenciesVersion () {
    const cb = this.async()

    setupDependenciesVersions(this.package)
      .then(newPkg => {
        this.package = newPkg
        cb()
      })
  }

  writePackage () {
    const cb = this.async()

    finepack(this.package, {
      validate: false,
      color: false
    }, (err, packageFormated) => {
      if (err) cb(err)
      this.fs.writeJSON(this.destinationPath('package.json'), packageFormated)
      cb()
    })
  }

  install () {
    this.spawnCommandSync('git', ['init'])
    const repoSSH = `git@github.com:${this.userLogin}/${this.appName}.git`
    this.spawnCommandSync('git', ['remote', 'add', 'origin', repoSSH])

    this.installDependencies({ bower: false })
  }
}
<commit_msg>Add --single-quote flag to prettier<commit_after>'use strict'

const _ = require('lodash')
const path = require('path')
const yosay = require('yosay')
const superb = require('superb')
const mkdirp = require('mkdirp')
const ghUser = require('gh-user')
const finepack = require('finepack')
const humanizeUrl = require('humanize-url')
const askName = require('inquirer-npm-name')
const Generator = require('yeoman-generator')

const { capitalizeName, setupDependenciesVersions } = require('./helpers')

const CONST = {
  LINTERS: {
    choose: ['jscs', 'jshint', 'standard']
  },

  TESTING: {
    choose: ['ava', 'jest', 'mocha', 'should', 'tap', 'tape']
  },

  TRANSPILERS: {
    choose: ['coffee-script']
  }
}

module.exports = class extends Generator {
  initializing () {
    this.licenseYear = new Date().getFullYear()
  }

  projectName () {
    this.log(yosay(`Initializing ${superb()} Project`))
    const cb = this.async()

    const promise = askName({
      name: 'name',
      message: 'Your project name',
      default: _.kebabCase(path.basename(process.cwd())),
      filter: _.kebabCase,
      validate: str => str.length > 0
    }, this)

    promise
      .then(answer => {
        const name = answer.name
        this.appName = name
        this.camelAppName = _.camelCase(name)
        this.capitalizeName = capitalizeName(this.appName)
        cb()
      })
  }

  setupPath () {
    if (path.basename(this.destinationPath()) !== this.appName) {
      this.log(
        `Your generator must be inside a folder named ${this.appName}\n
        I'll automatically create this folder.`
      )
      mkdirp(this.appName)
      this.destinationRoot(this.destinationPath(this.appName))
    }

    this.readme = this.fs.read(this.templatePath('README/header.md'))
    this.package = this.fs.read(this.templatePath('package/base.json'))
  }

  questions () {
    const cb = this.async()

    const promise = this.prompt([{
      name: 'appDescription',
      message: 'A short description of your project',
      default: "I'm a lazy"
    }, {
      name: 'userLogin',
      message: 'Would you mind telling me your username on GitHub?',
      default: 'someone'
    }, {
      name: 'cli',
      message: 'Do you need a CLI ?',
      type: 'confirm',
      default: false
    }])

    promise.then(props => {
      this.appDescription = props.appDescription
      this.userLogin = props.userLogin
      this.cli = props.cli
      cb()
    })
  }

  userInfo () {
    const cb = this.async()
    const promise = ghUser(this.userLogin)

    promise.then(user => {
      this.userName = user.name
      this.userEmail = user.email || this.user.git.email()
      this.userUrl = user.blog
      this.githubUrl = user.html_url
      this.humanizeUserUrl = humanizeUrl(this.userUrl)
      cb()
    })
  }

  transpilers () {
    const cb = this.async()

    const promise = this.prompt([{
      type: 'checkbox',
      name: 'transpilers',
      message: 'Select transpilers:',
      choices: CONST.TRANSPILERS.choose
    }])

    promise.then(props => {
      CONST.TRANSPILERS.choose
        .forEach(choice => (this[choice] = _.includes(props.transpilers, choice)))
      cb()
    })
  }

  linters () {
    const cb = this.async()

    const promise = this.prompt([{
      type: 'checkbox',
      name: 'linter',
      message: 'Select the linter:',
      choices: CONST.LINTERS.choose
    }])

    promise.then(props => {
      CONST.LINTERS.choose
        .forEach(choice => (this[choice] = _.includes(props.linter, choice)))
      cb()
    })
  }

  testing () {
    const cb = this.async()

    const promise = this.prompt([{
      type: 'checkbox',
      name: 'testing',
      message: 'Select testing tools:',
      choices: CONST.TESTING.choose
    }])

    promise.then(props => {
      CONST.TESTING.choose
        .forEach(choice => (this[choice] = _.includes(props.testing, choice)))
      cb()
    })
  }

  setup () {
    this.fs.copy(
      this.templatePath('_editorconfig'),
      this.destinationPath('.editorconfig')
    )
    this.fs.copy(
      this.templatePath('_gitignore'),
      this.destinationPath('.gitignore')
    )
    this.fs.copy(
      this.templatePath('_gitattributes'),
      this.destinationPath('.gitattributes')
    )
    this.fs.copy(
      this.templatePath('_npmignore'),
      this.destinationPath('.npmignore')
    )
    this.fs.copy(
      this.templatePath('_npmrc'),
      this.destinationPath('.npmrc')
    )
    this.fs.copy(
      this.templatePath('_travis.yml'),
      this.destinationPath('.travis.yml')
    )
    this.fs.copyTpl(
      this.templatePath('_LICENSE'),
      this.destinationPath('LICENSE'),
      this
    )

    this.package = _.template(this.package)(this)
    this.package = JSON.parse(this.package)

    if (this.cli) {
      let cliPackage = this.fs.read(this.templatePath('package/cli.json'))
      cliPackage = _.template(cliPackage)(this)
      cliPackage = JSON.parse(cliPackage)

      this.package = Object.assign({}, this.package, cliPackage)
      this.readme += this.fs.read(this.templatePath('README/install/cli.md'))

      this.fs.copyTpl(
        this.templatePath('bin/_help.txt'),
        this.destinationPath('bin/help.txt'),
        this
      )
      this.fs.copy(
        this.templatePath('bin/_index.js'),
        this.destinationPath('bin/index.js')
      )
    } else {
      this.readme += this.fs.read(this.templatePath('README/install/normal.md'))
    }

    this.fs.copy(
      this.templatePath('_bumpedrc'),
      this.destinationPath('.bumpedrc')
    )

    /* TRANSPILERS */

    CONST.TRANSPILERS.choose.forEach(transpiler =>
      (this[transpiler]) && (this.package.dependencies[transpiler] = 'latest'))

    /* TESTING */

    CONST.TESTING.choose.forEach(testing =>
      (this[testing]) && (this.package.devDependencies[testing] = 'latest'))

    let testScript = 'mocha'
    if (this.mocha) {
      this.fs.copy(
        this.templatePath('test/_mocha.opts'),
        this.destinationPath('test/mocha.opts')
      )
    }
    if (this.ava) testScript = 'ava'
    if (this.tape && !this.mocha) testScript = 'tape'
    this.package.scripts.test += testScript

    if (this.jest) {
      delete this.package.devDependencies.nyc // nyc is not needed anymore!
      this.package.scripts.coveralls = 'cat ./coverage/lcov.info | coveralls'
      this.package.scripts.test = 'jest --coverage'
      this.package.scripts['test:watch'] = 'jest --watch'
      const jestConfig = this.fs.readJSON(this.templatePath('package/jest.json'))
      this.package = Object.assign({}, this.package, jestConfig)
    }

    /* LINTERS */

    let lintScript = ''

    CONST.LINTERS.choose.forEach(linter => {
      if (this[linter]) {
        this.package.devDependencies[linter] = 'latest'
        lintScript += lintScript === '' ? linter : ' && ' + linter
      }
    })

    if (this.jshint) {
      this.fs.copy(
        this.templatePath('_jshintrc'),
        this.destinationPath('.jshintrc')
      )
    }
    if (this.jscs) {
      this.fs.copy(
        this.templatePath('_jscsrc'),
        this.destinationPath('.jscsrc')
      )
    }

    this.package.scripts.lint = lintScript

    if (this.standard) {
      this.package.devDependencies['prettier-standard'] = 'latest'
      this.package.devDependencies['standard-markdown'] = 'latest'
      this.package.scripts.prelint = 'npm run pretty'
      this.package.scripts.pretty = 'prettier-standard --single-quote {core,test,bin}/**/*.js'

      this.package.devDependencies['husky'] = 'latest'
      this.package.devDependencies['lint-staged'] = 'latest'

      this.package.scripts['precommit'] = 'lint-staged'
      this.package.scripts['precommit-lint'] = 'prettier-standard --single-quote'

      this.package['lint-staged'] = {
        '*.js': [
          'precommit-lint',
          'git add'
        ]
      }

      lintScript = `standard-markdown && ${lintScript}`

      if (this.mocha || this.jest) {
        this.package.standard = { env: [this.mocha ? 'mocha' : 'jest'] }
      }
    }

    this.package.scripts.lint = lintScript

    /* INDEX.JS */

    const indexExtension = this['coffee-script'] ? 'coffee' : 'js'
    this.fs.copy(
      this.templatePath(`_index.${indexExtension}`),
      this.destinationPath('index.js')
    )

    /* README */

    this.readme += this.fs.read(this.templatePath('README/body.md'))
    this.readme = _.template(this.readme)(this)
    this.fs.write(this.destinationPath('README.md'), this.readme)
  }

  dependenciesVersion () {
    const cb = this.async()

    setupDependenciesVersions(this.package)
      .then(newPkg => {
        this.package = newPkg
        cb()
      })
  }

  writePackage () {
    const cb = this.async()

    finepack(this.package, {
      validate: false,
      color: false
    }, (err, packageFormated) => {
      if (err) cb(err)
      this.fs.writeJSON(this.destinationPath('package.json'), packageFormated)
      cb()
    })
  }

  install () {
    this.spawnCommandSync('git', ['init'])
    const repoSSH = `git@github.com:${this.userLogin}/${this.appName}.git`
    this.spawnCommandSync('git', ['remote', 'add', 'origin', repoSSH])

    this.installDependencies({ bower: false })
  }
}
<|endoftext|>


<commit_before>"use strict";

const debug = require('debug')('dpe:core'),
    async   = require('async'),
    path    = require('path'),
    util    = require('util'),
    uuid    = require('node-uuid'),
    fs      = require('fs'),
    _       = require('lodash');

var Signal = require('./signal');
var Client = require('./client');
var API = require('./api');
var Process = require('./process');

var EventEmitter2 = require('eventemitter2').EventEmitter2;

class Core {
    constructor(_service) {
        this.service = _service;
        //noinspection JSUnresolvedVariable
        this.queue = async.priorityQueue(this.handle.bind(this), 1);
        this.queue.drain = this.onDrain.bind(this);

        this.context = {};
        this.instance = new Map();
        this.client = new Map();
        this.process = new Map();

        this._keep = _.values(this.service.get('net.servers'));

        this.baseAPI = require('./module')(this, API);
        //this.tags = require('./module/tags')(this);
        this.tags = this.service.get('tags');
    }

    init(_packages) {
        debug('core init with: ', _packages);

        _packages.map((packageName) => {
            if (!this.service.get('deps.' + packageName)) {
                debug('skip: ' + packageName);
            } else {
                var pack = require(this.service.get('deps.' + packageName).require);
                debug('package: ' + packageName);

                Object.keys(pack).map((moduleName) => {
                    var module = require(path.resolve(path.dirname(this.service.get('deps.' + packageName).require), pack[moduleName].require));
                    debug('\tmodule: ' + moduleName);

                    Object.keys(module).map((methodName) => {
                        this.instance.set(`${moduleName}.${methodName}`, new API(
                            `${moduleName}.${methodName}`,
                            {
                                access: "module"
                            },
                            module[methodName]
                        ));
                        debug('\t\tmethod: ' + methodName);
                    });
                });
            }
        });
        debug("core loaded");

        this.keepConnection();

        setInterval(this.keepConnection.bind(this), 60000);
    }

    keepConnection() {
        if (this._keep.length) {
            debug('keep check');
            this._keep.map((server) => {
                var _cid = server.href;
                if (!this.client.has(_cid)) {
                    this.baseAPI.connect(this, {
                        url: server.href
                    }, (err, res) => {
                        debug("baseAPI.connect callback", err, res)
                    });
                }
            });
        }
    }

    onDrain() {
        debug('queue is empty');
    }

    onClientConnected(_sid, _api, _meta, _data) {
        _meta = Object.assign(_meta, _data);
        if (_data.uid == "local") {
            _meta.type = "cli";
            if (_data.key == this.service.get('local.key')) {
                _meta.type = "local-cli";
            }
        }
        if (_meta.tags && !_.isArray(_meta.tags)) {
            _meta.tags = _meta.tags.split(',');
        }
        _meta._sid = _sid;

        var _cid = Client.getID(_meta);

        if (this.client.get(_cid)) {
            debug('upgrade client: ' + _cid);
            this.client.get(_cid).upgrade(_api, _meta);
            return;
        }

        debug('add client: ' + _cid);
        var newClient = new Client(_cid, _api, _meta);
        this.client.set(_cid, newClient);
        this.client.get(_cid).onRequest((_signal) => {
            debug('catch request');
            this.send(new Signal(Object.assign(_signal, {
                _cid: _cid
            })));
        });

        this.client.get(_cid).onClose(() => {
            debug('client disconnected', _cid);
            this.onClientDisconnected(_cid);
        });

        this.client.get(_cid).onError((err) => {
            debug('client error: ', _cid, err);
            this.onClientDisconnected(_cid);
        });

        if (["cli", "local-cli"].indexOf(_meta.type) == -1) {
            this.client.get(_cid).request(new Signal({
                _cid: "self",
                "instance.list": {
                    export: true
                }
            }), (_signal) => {
                var exportList = _signal.get('instance.list');
                if (exportList && exportList['$result']) exportList = exportList['$result'];
                debug("HANDLE REMOTE INSTANCES");
                exportList.map((item) => {
                    if (!this.instance.has(item.name)) {
                        debug('export: ' + item.name);
                        this.instance.set(item.name, new API(item.name, {
                                access: "module",
                                from: _cid
                            }, this.getRemoteCallAPI(item.name)
                        ));
                    } else {
                        this.instance.get(item.name).from.push(_cid);
                    }
                });
            });
        }
    }

    getRemoteCallAPI(_name) {
        return (function (env, args, callback) {
            var _cid = this.instance.get(_name).select(this.client, args['@tags']);
            if (!_cid) {
                return callback(new Error('E_NO_INSTANCE'));
            }
            if (this.client.has(_cid)) {
                var rawSignal = {};
                rawSignal[_name] = args;
                this.client.get(_cid).request(new Signal(rawSignal), (_response) => {
                    debug("REMOTE RESPONSE", _response);
                    if (_response.get('$error')) {
                        return callback(new Error(_response.get('$error')));
                    }
                    if (_response.get(_name)) {
                        return callback(null, _response.get(_name));
                    }
                    return callback(new Error('E_FAILED'));
                });
            }
        }).bind(this);
    }

    onClientDisconnected(_cid) {
        debug('remove client: ' + _cid);
        this.client.get(_cid).close();
        this.client.delete(_cid);
        this.instance.forEach((api, key) => {
            api.from = _.without(api.from, _cid);
            if (api.from.length == 0 && !api.export && api.access != "core") {
                debug('remove: ' + key);
                this.instance.delete(key);
            }
        });
    }

    handle(_signal, _callback) {
        debug("handle - start: ", _signal._sid);
        if (!_signal._pid && _signal.length() > 1) {
            //new process
            debug('process - start');
            var p = new Process(this.api.bind(this));
            this.process.set(p._pid, p);
            _signal._pid = p._pid;
            this.client.get(_signal._cid).response(_signal.getResult());
            return p.handle(_signal, () => {
                this.onHandled(_signal, _callback);
            });
        }
        if (_signal._pid) {
            //update process
            debug('process - update');
            return this.process.get(_signal._pid).handle(_signal, () => {
                this.onHandled(_signal, _callback);
            });
        }

        debug('no process');
        _signal.each(this.api.bind(this), () => {
            this.onHandled(_signal, _callback);
        });
    }

    onHandled(_signal, _callback) {
        if (_signal._pid && this.process.get(_signal._pid).isComplete()) {
            if (this.client.has(_signal._cid)) {
                debug('process - complete');
                this.client.get(_signal._cid).response(this.process.get(_signal._pid).getResult(_signal));
                this.process.delete(_signal._pid);
            } else {
                debug('process - await');
            }
        } else {
            debug('signal - complete', _signal.getResult());
            if (this.client.has(_signal._cid)) {
                this.client.get(_signal._cid).response(_signal.getResult());
            } else {
                debug(`client ${_signal._cid} is not found`)
            }
        }
        _callback();
    }

    send(_signal) {
        if (this.client.has(_signal._target)) {
            debug("resend: ", _signal);
            this.client.get(_signal._target).request(_signal, (_response) => {
                if (this.client.has(_signal._cid)) {
                    this.client.get(_signal._cid).response(_response);
                }
            });
        } else {
            if (_signal.length() == 1) {
                debug("execute: ", _signal);
                _signal.each(this.api.bind(this), () => {
                    this.onHandled(_signal, () => {});
                });
            } else {
                debug("enqueue: ", _signal);
                this.queue.push(_signal, 0);
            }
        }
    }
    api(name, _args, done) {
        if (arguments.length == 1) {
            debug('api get: ' + name);
            return this.instance.get(name);
        }
        debug('api call: ' + name);
        if (!this.instance.has(name)) {
            return done(new Error('E_API_NOT_FOUND'));
        }

        done = _.once(done);

        var api = this.instance.get(name);
        var args = (_args instanceof Signal) ? _args.get(name) : _args;

        var context = (_args instanceof Signal) ? this.process.get(_args._pid).context : this.context;
        var timer = null;

        if (args['@map_from']) {
            //@todo: map from for arguments change
        }

        switch (api.constructor.name) {
            case 'API':
                if (_args._ttl != 0) {
                    timer = setTimeout(() => {
                        done(new Error('E_TIMEOUT'));
                    }, _args._ttl ? _args._ttl : 60 * 1000);
                }
                return api.invoke(context, this, args, (err, result) => {
                    clearTimeout(timer);
                    debug('API CALL RESULT:', err, result);
                    //mapping
                    if (args['@map_to'] && _.isPlainObject(args['@map_to']) && result) {
                        debug('api call - map_to object-object found');
                        var newResult = {};
                        Object.keys(args['@map_to']).map((mapPath) => {
                            var curValue = _.get(result, mapPath);
                            if (curValue) {
                                debug('map path found in result', result, args['@map_to']);
                                _.set(newResult, mapPath, curValue);
                                return;
                            }
                            if (args['@map_to'][mapPath] == "$result") {
                                _.set(newResult, mapPath, result);
                            } else {
                                _.set(newResult, mapPath, _.get(result, args['@map_to'][mapPath]));
                            }
                        });
                        result = newResult;
                    }
                    if (args['@map_to'] && _.isString(args['@map_to']) && result) {
                        if (_.isPlainObject(result)) {
                            debug('api call - map_to string-object found');
                            result = _.get(result, args['@map_to']);
                        }
                    }

                    done(err, result);
                });
            case 'Component':
                timer = setTimeout(() => {
                    done(new Error('E_TIMEOUT'));
                }, _args._ttl ? _args._ttl : 60*1000);
                return api.invoke(context, {
                    log: this.service.constructor.log,
                    error: this.service.constructor.error,
                    send: this.send.bind(this),
                    api: this.api.bind(this)
                }, args, (err, result) => {
                    clearTimeout(timer);
                    done(err, result);
                });
            default:
                return done(new Error('E_UNKNOWN'));
        }
    }
}

module.exports = Core;
<commit_msg>add remote response check<commit_after>"use strict";

const debug = require('debug')('dpe:core'),
    async   = require('async'),
    path    = require('path'),
    util    = require('util'),
    uuid    = require('node-uuid'),
    fs      = require('fs'),
    _       = require('lodash');

var Signal = require('./signal');
var Client = require('./client');
var API = require('./api');
var Process = require('./process');

var EventEmitter2 = require('eventemitter2').EventEmitter2;

class Core {
    constructor(_service) {
        this.service = _service;
        //noinspection JSUnresolvedVariable
        this.queue = async.priorityQueue(this.handle.bind(this), 1);
        this.queue.drain = this.onDrain.bind(this);

        this.context = {};
        this.instance = new Map();
        this.client = new Map();
        this.process = new Map();

        this._keep = _.values(this.service.get('net.servers'));

        this.baseAPI = require('./module')(this, API);
        //this.tags = require('./module/tags')(this);
        this.tags = this.service.get('tags');
    }

    init(_packages) {
        debug('core init with: ', _packages);

        _packages.map((packageName) => {
            if (!this.service.get('deps.' + packageName)) {
                debug('skip: ' + packageName);
            } else {
                var pack = require(this.service.get('deps.' + packageName).require);
                debug('package: ' + packageName);

                Object.keys(pack).map((moduleName) => {
                    var module = require(path.resolve(path.dirname(this.service.get('deps.' + packageName).require), pack[moduleName].require));
                    debug('\tmodule: ' + moduleName);

                    Object.keys(module).map((methodName) => {
                        this.instance.set(`${moduleName}.${methodName}`, new API(
                            `${moduleName}.${methodName}`,
                            {
                                access: "module"
                            },
                            module[methodName]
                        ));
                        debug('\t\tmethod: ' + methodName);
                    });
                });
            }
        });
        debug("core loaded");

        this.keepConnection();

        setInterval(this.keepConnection.bind(this), 60000);
    }

    keepConnection() {
        if (this._keep.length) {
            debug('keep check');
            this._keep.map((server) => {
                var _cid = server.href;
                if (!this.client.has(_cid)) {
                    this.baseAPI.connect(this, {
                        url: server.href
                    }, (err, res) => {
                        debug("baseAPI.connect callback", err, res)
                    });
                }
            });
        }
    }

    onDrain() {
        debug('queue is empty');
    }

    onClientConnected(_sid, _api, _meta, _data) {
        _meta = Object.assign(_meta, _data);
        if (_data.uid == "local") {
            _meta.type = "cli";
            if (_data.key == this.service.get('local.key')) {
                _meta.type = "local-cli";
            }
        }
        if (_meta.tags && !_.isArray(_meta.tags)) {
            _meta.tags = _meta.tags.split(',');
        }
        _meta._sid = _sid;

        var _cid = Client.getID(_meta);

        if (this.client.get(_cid)) {
            debug('upgrade client: ' + _cid);
            this.client.get(_cid).upgrade(_api, _meta);
            return;
        }

        debug('add client: ' + _cid);
        var newClient = new Client(_cid, _api, _meta);
        this.client.set(_cid, newClient);
        this.client.get(_cid).onRequest((_signal) => {
            debug('catch request');
            this.send(new Signal(Object.assign(_signal, {
                _cid: _cid
            })));
        });

        this.client.get(_cid).onClose(() => {
            debug('client disconnected', _cid);
            this.onClientDisconnected(_cid);
        });

        this.client.get(_cid).onError((err) => {
            debug('client error: ', _cid, err);
            this.onClientDisconnected(_cid);
        });

        if (["cli", "local-cli"].indexOf(_meta.type) == -1) {
            this.client.get(_cid).request(new Signal({
                _cid: "self",
                "instance.list": {
                    export: true
                }
            }), (_signal) => {
                var exportList = _signal.get('instance.list');
                if (exportList && exportList['$result']) exportList = exportList['$result'];
                debug("HANDLE REMOTE INSTANCES");
                exportList.map((item) => {
                    if (!this.instance.has(item.name)) {
                        debug('export: ' + item.name);
                        this.instance.set(item.name, new API(item.name, {
                                access: "module",
                                from: _cid
                            }, this.getRemoteCallAPI(item.name)
                        ));
                    } else {
                        this.instance.get(item.name).from.push(_cid);
                    }
                });
            });
        }
    }

    getRemoteCallAPI(_name) {
        return (function (env, args, callback) {
            var _cid = this.instance.get(_name).select(this.client, args['@tags']);
            if (!_cid) {
                return callback(new Error('E_NO_INSTANCE'));
            }
            if (this.client.has(_cid)) {
                var rawSignal = {};
                rawSignal[_name] = args;
                this.client.get(_cid).request(new Signal(rawSignal), (_response) => {
                    debug("REMOTE RESPONSE", _response);
                    if (_response instanceof Signal) {
                        if (_response.get('$error')) {
                            return callback(new Error(_response.get('$error')));
                        }
                        if (_response.get(_name)) {
                            return callback(null, _response.get(_name));
                        }
                    }
                    if (_response instanceof Error) {
                        return callback(_response);
                    }
                    return callback(new Error('E_FAILED'));
                });
            }
        }).bind(this);
    }

    onClientDisconnected(_cid) {
        debug('remove client: ' + _cid);
        this.client.get(_cid).close();
        this.client.delete(_cid);
        this.instance.forEach((api, key) => {
            api.from = _.without(api.from, _cid);
            if (api.from.length == 0 && !api.export && api.access != "core") {
                debug('remove: ' + key);
                this.instance.delete(key);
            }
        });
    }

    handle(_signal, _callback) {
        debug("handle - start: ", _signal._sid);
        if (!_signal._pid && _signal.length() > 1) {
            //new process
            debug('process - start');
            var p = new Process(this.api.bind(this));
            this.process.set(p._pid, p);
            _signal._pid = p._pid;
            this.client.get(_signal._cid).response(_signal.getResult());
            return p.handle(_signal, () => {
                this.onHandled(_signal, _callback);
            });
        }
        if (_signal._pid) {
            //update process
            debug('process - update');
            return this.process.get(_signal._pid).handle(_signal, () => {
                this.onHandled(_signal, _callback);
            });
        }

        debug('no process');
        _signal.each(this.api.bind(this), () => {
            this.onHandled(_signal, _callback);
        });
    }

    onHandled(_signal, _callback) {
        if (_signal._pid && this.process.get(_signal._pid).isComplete()) {
            if (this.client.has(_signal._cid)) {
                debug('process - complete');
                this.client.get(_signal._cid).response(this.process.get(_signal._pid).getResult(_signal));
                this.process.delete(_signal._pid);
            } else {
                debug('process - await');
            }
        } else {
            debug('signal - complete', _signal.getResult());
            if (this.client.has(_signal._cid)) {
                this.client.get(_signal._cid).response(_signal.getResult());
            } else {
                debug(`client ${_signal._cid} is not found`)
            }
        }
        _callback();
    }

    send(_signal) {
        if (this.client.has(_signal._target)) {
            debug("resend: ", _signal);
            this.client.get(_signal._target).request(_signal, (_response) => {
                if (this.client.has(_signal._cid)) {
                    this.client.get(_signal._cid).response(_response);
                }
            });
        } else {
            if (_signal.length() == 1) {
                debug("execute: ", _signal);
                _signal.each(this.api.bind(this), () => {
                    this.onHandled(_signal, () => {});
                });
            } else {
                debug("enqueue: ", _signal);
                this.queue.push(_signal, 0);
            }
        }
    }
    api(name, _args, done) {
        if (arguments.length == 1) {
            debug('api get: ' + name);
            return this.instance.get(name);
        }
        debug('api call: ' + name);
        if (!this.instance.has(name)) {
            return done(new Error('E_API_NOT_FOUND'));
        }

        done = _.once(done);

        var api = this.instance.get(name);
        var args = (_args instanceof Signal) ? _args.get(name) : _args;

        var context = (_args instanceof Signal) ? this.process.get(_args._pid).context : this.context;
        var timer = null;

        if (args['@map_from']) {
            //@todo: map from for arguments change
        }

        switch (api.constructor.name) {
            case 'API':
                if (_args._ttl != 0) {
                    timer = setTimeout(() => {
                        done(new Error('E_TIMEOUT'));
                    }, _args._ttl ? _args._ttl : 60 * 1000);
                }
                return api.invoke(context, this, args, (err, result) => {
                    clearTimeout(timer);
                    debug('API CALL RESULT:', err, result);
                    //mapping
                    if (args['@map_to'] && _.isPlainObject(args['@map_to']) && result) {
                        debug('api call - map_to object-object found');
                        var newResult = {};
                        Object.keys(args['@map_to']).map((mapPath) => {
                            var curValue = _.get(result, mapPath);
                            if (curValue) {
                                debug('map path found in result', result, args['@map_to']);
                                _.set(newResult, mapPath, curValue);
                                return;
                            }
                            if (args['@map_to'][mapPath] == "$result") {
                                _.set(newResult, mapPath, result);
                            } else {
                                _.set(newResult, mapPath, _.get(result, args['@map_to'][mapPath]));
                            }
                        });
                        result = newResult;
                    }
                    if (args['@map_to'] && _.isString(args['@map_to']) && result) {
                        if (_.isPlainObject(result)) {
                            debug('api call - map_to string-object found');
                            result = _.get(result, args['@map_to']);
                        }
                    }

                    done(err, result);
                });
            case 'Component':
                timer = setTimeout(() => {
                    done(new Error('E_TIMEOUT'));
                }, _args._ttl ? _args._ttl : 60*1000);
                return api.invoke(context, {
                    log: this.service.constructor.log,
                    error: this.service.constructor.error,
                    send: this.send.bind(this),
                    api: this.api.bind(this)
                }, args, (err, result) => {
                    clearTimeout(timer);
                    done(err, result);
                });
            default:
                return done(new Error('E_UNKNOWN'));
        }
    }
}

module.exports = Core;
<|endoftext|>


<commit_before>'use strict';

var init = require('./transforms/init');
var env = require('./transforms/env');

/**
 * Load initialization transforms
 *
 *  | runner
 *  | loaders
 *  | create
 *  | options
 *  | middleware
 *  | plugins
 *  | load
 *  | engines
 *  | helpers - load helpers last
 */

module.exports = function init_(verb) {
  verb.transform('cwd', init.cwd);
  verb.transform('verb', init.verb);
  verb.transform('args', init.args);

  verb.transform('env', env.env);
  verb.transform('pkg', env.pkg);
  verb.transform('keys', env.keys);
  verb.transform('author', env.author);
  verb.transform('user', env.user);
  verb.transform('username', env.username);
  verb.transform('github', env.github);
  verb.transform('travis', env.travis);
  verb.transform('missing', env.missing);

  verb.transform('ignore', init.ignore);
  verb.transform('files', init.files);
  verb.transform('helpers', init.helpers);

  verb.on('init', function () {
    verb.transform('store', init.store);
    verb.transform('options', init.options);
    verb.transform('loaders', init.loaders);
    verb.transform('create', init.create);
    verb.transform('middleware', init.middleware);
    verb.transform('plugins', init.plugins);
    verb.transform('load', init.load);
    verb.transform('engines', init.engines);
    verb.transform('runner', init.runner);
  });
};
<commit_msg>re-organized, expose `files`<commit_after>'use strict';

var mod = require('./transforms/modifiers');
var init = require('./transforms/init');
var env = require('./transforms/env');

/**
 * Load initialization transforms
 *
 *  | runner
 *  | loaders
 *  | create
 *  | options
 *  | middleware
 *  | plugins
 *  | load
 *  | engines
 *  | helpers - load helpers last
 */

module.exports = function init_(verb) {
  verb.transform('cwd', init.cwd);
  verb.transform('verb', init.verb);
  verb.transform('args', init.args);
  verb.transform('ignore', init.ignore);
  verb.transform('files', env.files);

  verb.transform('env', env.env);
  verb.transform('pkg', env.pkg);
  verb.transform('keys', env.keys);
  verb.transform('author', env.author);
  verb.transform('user', env.user);
  verb.transform('username', env.username);
  verb.transform('github', env.github);
  verb.transform('travis', env.travis);
  verb.transform('missing', env.missing);
  verb.transform('github-url', mod.github_url);
  verb.transform('twitter-url', mod.twitter_url);

  verb.on('init', function () {
    verb.transform('store', init.store);
    verb.transform('runner', init.runner);
    verb.transform('options', init.options);
    verb.transform('loaders', init.loaders);
    verb.transform('create', init.create);
    verb.transform('engines', init.engines);
    verb.transform('middleware', init.middleware);
    verb.transform('helpers', init.helpers);
    verb.transform('load', init.load);
    verb.transform('plugins', init.plugins);
    verb.emit('loaded');
  });

  verb.on('loaded', function () {
    verb.transform('helpers', init.helpers);
  });
};
<|endoftext|>


<commit_before>var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var AdGenerator = module.exports = function AdGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(AdGenerator, yeoman.generators.Base);

AdGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [
    {
      name: 'name',
      message: 'Please enter a name for this ad unit.',
      default: 'Ad Unit'
    }, {
      name: 'width',
      message: 'What is the width of this ad unit?',
      default: '336'
    }, {
      name: 'height',
      message: 'What is the height of this ad unit?',
      default: '850'
    }, {
      name: 'namespace',
      message: 'What wpAd namespace would you like to wrap your JS in?',
      default: 'myUniqueNamespace'
    }, {
      name: 'abs_path',
      message: 'Please enter a path for where this will live on the live server?',
      default: '/wp-adv/advertisers/myUnit/'
    }, {
      name: 'advertiser',
      message: 'Who is the advertiser (optional)?'
    }, {
      name: 'bug_id',
      message: 'What is the bug id (optional)?'
    }, {
      name: 'test_kw',
      message: 'what is the test_kw (optional)?'
    }
  ];

  this.prompt(prompts, function (props) {

    //store all prompts
    for(var key in props){
      if(props.hasOwnProperty(key) && !this[key]){
        this[key] = props[key];
      }
    }

    cb();
  }.bind(this));
};

AdGenerator.prototype.app = function app() {
  this.mkdir('src');
  this.mkdir('src/js');
  this.mkdir('src/js/lib');
  this.mkdir('src/sass');
  this.mkdir('src/img');
  this.mkdir('src/test');
};

AdGenerator.prototype.templatefiles = function projectfiles() {
  this.template('_package.json', 'package.json');
  this.template('_bower.json', 'bower.json');
  this.template('_Gruntfile.js', 'Gruntfile.js');
  this.template('src/_index.html', 'src/index.html');
  this.template('src/js/_main.js', 'src/js/main.js');
  this.template('src/sass/_style.sass', 'src/sass/style.sass');
}

AdGenerator.prototype.projectfiles = function projectfiles() {
  //this.copy('Gruntfile.js', 'Gruntfile.js');
  this.copy('config.rb', 'config.rb');
  this.copy('bowerrc', '.bowerrc');
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
};
<commit_msg>added .gitignore<commit_after>var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var AdGenerator = module.exports = function AdGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(AdGenerator, yeoman.generators.Base);

AdGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [
    {
      name: 'name',
      message: 'Please enter a name for this ad unit.',
      default: 'Ad Unit'
    }, {
      name: 'width',
      message: 'What is the width of this ad unit?',
      default: '336'
    }, {
      name: 'height',
      message: 'What is the height of this ad unit?',
      default: '850'
    }, {
      name: 'namespace',
      message: 'What wpAd namespace would you like to wrap your JS in?',
      default: 'myUniqueNamespace'
    }, {
      name: 'abs_path',
      message: 'Please enter a path for where this will live on the live server?',
      default: '/wp-adv/advertisers/myUnit/'
    }, {
      name: 'advertiser',
      message: 'Who is the advertiser (optional)?'
    }, {
      name: 'bug_id',
      message: 'What is the bug id (optional)?'
    }, {
      name: 'test_kw',
      message: 'what is the test_kw (optional)?'
    }
  ];

  this.prompt(prompts, function (props) {

    //store all prompts
    for(var key in props){
      if(props.hasOwnProperty(key) && !this[key]){
        this[key] = props[key];
      }
    }

    cb();
  }.bind(this));
};

AdGenerator.prototype.app = function app() {
  this.mkdir('src');
  this.mkdir('src/js');
  this.mkdir('src/js/lib');
  this.mkdir('src/sass');
  this.mkdir('src/img');
  this.mkdir('src/test');
};

AdGenerator.prototype.templatefiles = function projectfiles() {
  this.template('_package.json', 'package.json');
  this.template('_bower.json', 'bower.json');
  this.template('_Gruntfile.js', 'Gruntfile.js');
  this.template('src/_index.html', 'src/index.html');
  this.template('src/js/_main.js', 'src/js/main.js');
  this.template('src/sass/_style.sass', 'src/sass/style.sass');
}

AdGenerator.prototype.projectfiles = function projectfiles() {
  //this.copy('Gruntfile.js', 'Gruntfile.js');
  this.copy('gitignore', '.gitignore');
  this.copy('config.rb', 'config.rb');
  this.copy('bowerrc', '.bowerrc');
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
};
<|endoftext|>


<commit_before>'use babel';

// eslint-disable-next-line import/no-extraneous-dependencies, import/extensions
import { CompositeDisposable } from 'atom';
import path from 'path';
import tmp from 'tmp';

export default {
  config: {
    executablePath: {
      type: 'string',
      default: '',
    },
    includeDirs: {
      type: 'array',
      default: [],
      items: {
        type: 'string',
      },
    },
    pa: {
      type: 'array',
      default: [],
      items: {
        type: 'string',
      },
    },
  },

  activate() {
    require('atom-package-deps').install();
    this.subscriptions = new CompositeDisposable();

    this.subscriptions.add(
      atom.config.observe('linter-erlc.executablePath', (executablePath) => {
        this.executablePath = executablePath;
      }),
    );

    this.subscriptions.add(
      atom.config.observe('linter-erlc.pa', (pa) => {
        this.erlcPa = pa;
      }),
    );

    this.subscriptions.add(
      atom.config.observe('linter-erlc.includeDirs', (includeDirs) => {
        this.erlcIncludeDirs = includeDirs;
      }),
    );
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  provideLinter() {
    const helpers = require('atom-linter');
    return {
      name: 'erlc',
      grammarScopes: ['source.erlang'],
      scope: 'file',
      lintOnFly: false,
      lint: (textEditor) => {
        const tmpPathObj = tmp.dirSync({ unsafeCleanup: true });
        const filePath = textEditor.getPath();
        const args = ['-Wall', '-v', '-o', tmpPathObj.name];
        let projectPath = null;

        if (!filePath.match(/\.erl$/)) {
          return [];
        }

        this.erlcPa.forEach((paPath) => {
          args.push('-pa');
          args.push(paPath);
        });

        const dirName = path.basename(path.dirname(filePath));
        if (dirName === 'src' | dirName === 'test') {
          projectPath = path.dirname(path.dirname(filePath));
        }

        this.erlcIncludeDirs.forEach((includePath) => {
          args.push('-I');
          if (projectPath && !includePath.match(/^\//)) {
            args.push(path.join(projectPath, includePath));
          } else {
            args.push(includePath);
          }
        });

        args.push(filePath);

        return helpers.exec(this.executablePath, args, { ignoreExitCode: true }).then((result) => {
          const toReturn = [];
          const patterns = [
            {
              regex: /(.+):(\d+):\s(.+)/,
              cb: m => ({ lineNo: m[2], text: m[3] }),
            },
            {
              regex: /(.+): (.+)/,
              cb: m => ({ lineNo: 1, text: m[2] }),
            },
          ];
          const lines = result.split('\n');
          const sourceLines = textEditor.getBuffer().getLines();
          for (const line of lines) {
            if (!line) {
              continue;
            }

            const matches = patterns.map((x) => {
              const match = line.match(x.regex);
              return match ? x.cb(match) : null;
            });
            const match = matches[0];
            const lineNo = Number.parseInt(match.lineNo, 10) - 1;
            let message = match.text;
            let type;
            if (message.match(/Warning:/)) {
              message = message.replace(/Warning: (.+)/, '$1');
              type = 'Warning';
            } else {
              type = 'Error';
            }

            const beforeMatch = message.match(/before: '?(.+?)'?/);
            const unUsedMatch = message.match(/variable '(.+)' is unused/);
            const sourceLine = sourceLines[lineNo];
            let column1 = 0;
            let column2 = sourceLine.length;
            if (beforeMatch) {
              column2 = sourceLine.lastIndexOf(beforeMatch[1]);
            } else if (unUsedMatch) {
              column1 = sourceLine.indexOf(unUsedMatch[1]);
              column2 = column1 + unUsedMatch[1].length;
            }

            toReturn.push({
              type,
              text: message,
              range: [[lineNo, column1], [lineNo, column2]],
              filePath,
            });
          }
          tmpPathObj.removeCallback();
          return toReturn;
        });
      },
    };
  },
};
<commit_msg>Logical not bitwise OR<commit_after>'use babel';

// eslint-disable-next-line import/no-extraneous-dependencies, import/extensions
import { CompositeDisposable } from 'atom';
import path from 'path';
import tmp from 'tmp';

export default {
  config: {
    executablePath: {
      type: 'string',
      default: '',
    },
    includeDirs: {
      type: 'array',
      default: [],
      items: {
        type: 'string',
      },
    },
    pa: {
      type: 'array',
      default: [],
      items: {
        type: 'string',
      },
    },
  },

  activate() {
    require('atom-package-deps').install();
    this.subscriptions = new CompositeDisposable();

    this.subscriptions.add(
      atom.config.observe('linter-erlc.executablePath', (executablePath) => {
        this.executablePath = executablePath;
      }),
    );

    this.subscriptions.add(
      atom.config.observe('linter-erlc.pa', (pa) => {
        this.erlcPa = pa;
      }),
    );

    this.subscriptions.add(
      atom.config.observe('linter-erlc.includeDirs', (includeDirs) => {
        this.erlcIncludeDirs = includeDirs;
      }),
    );
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  provideLinter() {
    const helpers = require('atom-linter');
    return {
      name: 'erlc',
      grammarScopes: ['source.erlang'],
      scope: 'file',
      lintOnFly: false,
      lint: (textEditor) => {
        const tmpPathObj = tmp.dirSync({ unsafeCleanup: true });
        const filePath = textEditor.getPath();
        const args = ['-Wall', '-v', '-o', tmpPathObj.name];
        let projectPath = null;

        if (!filePath.match(/\.erl$/)) {
          return [];
        }

        this.erlcPa.forEach((paPath) => {
          args.push('-pa');
          args.push(paPath);
        });

        const dirName = path.basename(path.dirname(filePath));
        if (dirName === 'src' || dirName === 'test') {
          projectPath = path.dirname(path.dirname(filePath));
        }

        this.erlcIncludeDirs.forEach((includePath) => {
          args.push('-I');
          if (projectPath && !includePath.match(/^\//)) {
            args.push(path.join(projectPath, includePath));
          } else {
            args.push(includePath);
          }
        });

        args.push(filePath);

        return helpers.exec(this.executablePath, args, { ignoreExitCode: true }).then((result) => {
          const toReturn = [];
          const patterns = [
            {
              regex: /(.+):(\d+):\s(.+)/,
              cb: m => ({ lineNo: m[2], text: m[3] }),
            },
            {
              regex: /(.+): (.+)/,
              cb: m => ({ lineNo: 1, text: m[2] }),
            },
          ];
          const lines = result.split('\n');
          const sourceLines = textEditor.getBuffer().getLines();
          for (const line of lines) {
            if (!line) {
              continue;
            }

            const matches = patterns.map((x) => {
              const match = line.match(x.regex);
              return match ? x.cb(match) : null;
            });
            const match = matches[0];
            const lineNo = Number.parseInt(match.lineNo, 10) - 1;
            let message = match.text;
            let type;
            if (message.match(/Warning:/)) {
              message = message.replace(/Warning: (.+)/, '$1');
              type = 'Warning';
            } else {
              type = 'Error';
            }

            const beforeMatch = message.match(/before: '?(.+?)'?/);
            const unUsedMatch = message.match(/variable '(.+)' is unused/);
            const sourceLine = sourceLines[lineNo];
            let column1 = 0;
            let column2 = sourceLine.length;
            if (beforeMatch) {
              column2 = sourceLine.lastIndexOf(beforeMatch[1]);
            } else if (unUsedMatch) {
              column1 = sourceLine.indexOf(unUsedMatch[1]);
              column2 = column1 + unUsedMatch[1].length;
            }

            toReturn.push({
              type,
              text: message,
              range: [[lineNo, column1], [lineNo, column2]],
              filePath,
            });
          }
          tmpPathObj.removeCallback();
          return toReturn;
        });
      },
    };
  },
};
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var chalk = require('chalk');

var MyappGenerator = yeoman.generators.Base.extend({
  init: function () {
    this.pkg = require('../package.json');

    this.on('end', function () {
      if (!this.options['skip-install']) {
        this.installDependencies();
      }
    });
  },

  askFor: function () {
    var done = this.async();
    this.log(this.yeoman);
    this.log(chalk.magenta('You\'re using the fantastic mobileApp generator.'));

    var prompts = [{
      name: 'appTitle',
      message: 'Give your fantastic, sweet and awesome app a name: '
    },
      {
        type: 'checkbox',
        name: 'bowerPackages',
        message: 'Choose the libraries you need: ',
        choices: [
          {
            name: 'Bootstrap',
            value: 'includeBootstrap',
            checked: false
          }, {
            name: 'jQuery',
            value: 'includeJQuery',
            checked: true
          }, {
            name: 'Angular JS',
            value: 'includeAngular',
            checked: false
          }
        ]
      }];

    this.prompt(prompts, function (features) {
      function includedBowerFeature(f) {
        return bower.indexOf(f) !== -1;
      }

      var bower = features.bowerPackages;
      this.appTitle = features.appTitle;

      this.bootstrap = includedBowerFeature("includeBootstrap");
      this.jQuery = includedBowerFeature("includeJQuery");
      this.angular = includedBowerFeature("includeAngular");

      done();
    }.bind(this));
  },

  app: function () {
    this.mkdir('img');
    this.mkdir('css');
    this.mkdir('js');
    this.mkdir('vendor');

    this.template('Gruntfile.js', 'Gruntfile.js');
    this.template('index.html', 'index.html');
    this.template('_bower.json', 'bower.json');
    this.template('_config.json', 'config.json');
    this.template('_package.json', 'package.json');
    this.template('sass/style.sass', 'css/style.sass');
    this.template('sass/reset.sass', 'css/reset.sass');

    this.copy('_package.json', 'package.json');
    this.copy('_bower.json', 'bower.json');
  },

  projectfiles: function () {
    this.copy('editorconfig', '.editorconfig');
    this.copy('jshintrc', '.jshintrc');
    this.copy('bowerrc', '.bowerrc');
    this.copy('gitignore', '.gitignore');
  }
});

module.exports = MyappGenerator;<commit_msg>added main.js to templates<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var chalk = require('chalk');

var MyappGenerator = yeoman.generators.Base.extend({
  init: function () {
    this.pkg = require('../package.json');

    this.on('end', function () {
      if (!this.options['skip-install']) {
        this.installDependencies();
      }
    });
  },

  askFor: function () {
    var done = this.async();
    this.log(this.yeoman);
    this.log(chalk.magenta('You\'re using the fantastic mobileApp generator.'));

    var prompts = [{
      name: 'appTitle',
      message: 'Give your fantastic, sweet and awesome app a name: '
    },
      {
        type: 'checkbox',
        name: 'bowerPackages',
        message: 'Choose the libraries you need: ',
        choices: [
          {
            name: 'Bootstrap',
            value: 'includeBootstrap',
            checked: false
          }, {
            name: 'jQuery',
            value: 'includeJQuery',
            checked: true
          }, {
            name: 'Angular JS',
            value: 'includeAngular',
            checked: false
          }
        ]
      }];

    this.prompt(prompts, function (features) {
      function includedBowerFeature(f) {
        return bower.indexOf(f) !== -1;
      }

      var bower = features.bowerPackages;
      this.appTitle = features.appTitle;

      this.bootstrap = includedBowerFeature("includeBootstrap");
      this.jQuery = includedBowerFeature("includeJQuery");
      this.angular = includedBowerFeature("includeAngular");

      done();
    }.bind(this));
  },

  app: function () {
    this.mkdir('img');
    this.mkdir('css');
    this.mkdir('js');
    this.mkdir('vendor');

    this.template('Gruntfile.js', 'Gruntfile.js');
    this.template('index.html', 'index.html');
    this.template('_bower.json', 'bower.json');
    this.template('_config.json', 'config.json');
    this.template('_package.json', 'package.json');
    this.template('sass/style.sass', 'css/style.sass');
    this.template('sass/reset.sass', 'css/reset.sass');
    this.template('js/main.js', 'js/main.js');

    this.copy('_package.json', 'package.json');
    this.copy('_bower.json', 'bower.json');
  },

  projectfiles: function () {
    this.copy('editorconfig', '.editorconfig');
    this.copy('jshintrc', '.jshintrc');
    this.copy('bowerrc', '.bowerrc');
    this.copy('gitignore', '.gitignore');
  }
});

module.exports = MyappGenerator;<|endoftext|>