<commit_before>var JVCAPI = {};

JVCAPI.version = "0.5";

JVCAPI.page = {};

JVCAPI.page.is = {
    liste_des_sujets: function () {
        return document.querySelector(".conteneur-topic-pagi li[data-id]") !== null;
    },
    topic: function () {
        return document.querySelector(".bloc-message-forum[data-id]") !== null && document.querySelector(".page-active") !== null;
    },
    message: function () {
        return document.querySelector(".text-muted") !== null && document.querySelector(".bloc-message-forum[data-id]") !== null;
    }
};

JVCAPI.topic = {};

JVCAPI.topic.getUrlInfos = function (url) {
    if(url === undefined)
    {
        url = document.location.href;
    }
    let l1, l2, l3, l4;
    if (/http:\/\/www.jeuxvideo.com\/forums\/([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)-/.test(url)) {
        l1 = RegExp.$1, l2 = RegExp.$2, l3 = RegExp.$3, l4 = RegExp.$4;
    }
    return {
        topicID: l3,
        forumID: l2,
        code: l1,
        currentPage: l4
    };
};

JVCAPI.topic.getMessages = function (link, callback) {
    let local = false;
    if ((typeof link === "object") && (link !== null)) {
        if (link.local === undefined || !link.local) {
            if (link.code === undefined) {
                link.code = 42;
            }
            if (link.forumID === undefined) {
                link.forumID = 51;
            }
            if (link.page === undefined) {
                link.page = 1;
            }
            if (link.topicID === undefined) {
                callback({
                    error: "topicID manquant"
                });
                return;
            }
            link = "http://www.jeuxvideo.com/forums/" + link.code + "-" + link.forumID + "-" + link.topicID + "-" + link.page + "-0-1-0-0.htm";
        } else {
            local = true;
        }
    }

    function f(html) {
        let divs = JVCAPI.stringToHtml(html).querySelectorAll(".conteneur-message"),
            posts = [];
        divs.forEach(function (el) {
            let pseudo = "";
            if (/current-topic-author/.test(el.querySelector(".bloc-pseudo-msg").innerHTML.trim())) {
                pseudo = el.querySelector(".user-avatar-msg").getAttribute("alt");
            } else {
                pseudo = el.querySelector(".bloc-pseudo-msg").innerHTML.trim();
            }
            let avatar = "";
            try {
                avatar = el.querySelector(".bloc-avatar-msg").querySelector("img").getAttribute("data-srcset");
            } catch (e) {
                try {
                    avatar = el.querySelector(".bloc-avatar-msg").querySelector("img").getAttribute("src");
                }
                catch(e) {
                    avatar = "http://image.jeuxvideo.com/avatar/default.jpg";
                }
            }
            let date = "";
            try {
                date = el.querySelector(".bloc-date-msg").innerHTML.trim();
            } catch (e) {
                date = el.querySelector(".bloc-date-msg").querySelector("a").innerHTML.trim();
            }
            let message = "";
            try {
                message = el.querySelector(".txt-msg").innerHTML;
            } catch (e) {
                message = '
Ce pseudo figure dans votre blacklist

' + el.querySelector(".msg-pseudo-blacklist-view").outerHTML + '
';
            }
            let signature = "";
            try {
                signature = el.querySelector(".signature-msg").innerHTML.trim();
            } catch (e) {
                signature = "";
            }
            let ddbLink = null;
            try {
                if(el.querySelector(".picto-msg-exclam") !== null)
                    ddbLink = el.querySelector(".picto-msg-exclam").dataset.selector;
            }
            catch (e) {}
            posts.push({
                id: el.parentElement.getAttribute("data-id"),
                pseudo: pseudo,
                avatar: avatar,
                date: date,
                message: message,
                signature: signature,
                grade: el.querySelector(".text-modo") !== null ? "modo" : el.querySelector(".text-admin") !== null ? "admin" : "",
                page: JVCAPI.stringToHtml(html).querySelector(".page-active").innerHTML.trim(),
                ddbLink: ddbLink
            });
        });
        return posts;
    }
    if (!local) {
        try {
        let req = new XMLHttpRequest();
        req.onreadystatechange = function (event) {
            if (this.readyState === XMLHttpRequest.DONE) {
                if (this.status === 200) {
                    let html = this.responseText;
                    callback({
                        html: html,
                        posts: f(html)
                    });
                } else {
                    let status = this.status;
                    callback({
                        error: status
                    });
                }
            }
        };
        req.open('GET', link, true);
        req.send(null);
    }
    catch(e) {
        callback({
            error: "XMLHttpRequest error"
        });
    }
    } else {
        callback({
            html: document.documentElement.innerHTML,
            posts: f(document.documentElement.innerHTML)
        });
    }
};
JVCAPI.stringToHtml = function (s) {
    return (new DOMParser()).parseFromString(s, "text/html");
};

JVCAPI.query = function (q) {
    return document.querySelector(q);
}

var stringToHtml = JVCAPI.stringToHtml;
var query = JVCAPI.query;
<commit_msg>Correction bug suite au passage en https de JVC<commit_after>var JVCAPI = {};

JVCAPI.version = "0.5";

JVCAPI.page = {};

JVCAPI.page.is = {
    liste_des_sujets: function () {
        return document.querySelector(".conteneur-topic-pagi li[data-id]") !== null;
    },
    topic: function () {
        return document.querySelector(".bloc-message-forum[data-id]") !== null && document.querySelector(".page-active") !== null;
    },
    message: function () {
        return document.querySelector(".text-muted") !== null && document.querySelector(".bloc-message-forum[data-id]") !== null;
    }
};

JVCAPI.topic = {};

JVCAPI.topic.getUrlInfos = function (url) {
    if(url === undefined)
    {
        url = document.location.href;
    }
    let l1, l2, l3, l4;
    if (/https?:\/\/www.jeuxvideo.com\/forums\/([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)-/.test(url)) {
        l1 = RegExp.$1, l2 = RegExp.$2, l3 = RegExp.$3, l4 = RegExp.$4;
    }
    return {
        topicID: l3,
        forumID: l2,
        code: l1,
        currentPage: l4
    };
};

JVCAPI.topic.getMessages = function (link, callback) {
    let local = false;
    if ((typeof link === "object") && (link !== null)) {
        if (link.local === undefined || !link.local) {
            if (link.code === undefined) {
                link.code = 42;
            }
            if (link.forumID === undefined) {
                link.forumID = 51;
            }
            if (link.page === undefined) {
                link.page = 1;
            }
            if (link.topicID === undefined) {
                callback({
                    error: "topicID manquant"
                });
                return;
            }
            link = "https?://www.jeuxvideo.com/forums/" + link.code + "-" + link.forumID + "-" + link.topicID + "-" + link.page + "-0-1-0-0.htm";
        } else {
            local = true;
        }
    }

    function f(html) {
        let divs = JVCAPI.stringToHtml(html).querySelectorAll(".conteneur-message"),
            posts = [];
        divs.forEach(function (el) {
            let pseudo = "";
            if (/current-topic-author/.test(el.querySelector(".bloc-pseudo-msg").innerHTML.trim())) {
                pseudo = el.querySelector(".user-avatar-msg").getAttribute("alt");
            } else {
                pseudo = el.querySelector(".bloc-pseudo-msg").innerHTML.trim();
            }
            let avatar = "";
            try {
                avatar = el.querySelector(".bloc-avatar-msg").querySelector("img").getAttribute("data-srcset");
            } catch (e) {
                try {
                    avatar = el.querySelector(".bloc-avatar-msg").querySelector("img").getAttribute("src");
                }
                catch(e) {
                    avatar = "https://image.jeuxvideo.com/avatar/default.jpg";
                }
            }
            let date = "";
            try {
                date = el.querySelector(".bloc-date-msg").innerHTML.trim();
            } catch (e) {
                date = el.querySelector(".bloc-date-msg").querySelector("a").innerHTML.trim();
            }
            let message = "";
            try {
                message = el.querySelector(".txt-msg").innerHTML;
            } catch (e) {
                message = '
Ce pseudo figure dans votre blacklist

' + el.querySelector(".msg-pseudo-blacklist-view").outerHTML + '
';
            }
            let signature = "";
            try {
                signature = el.querySelector(".signature-msg").innerHTML.trim();
            } catch (e) {
                signature = "";
            }
            let ddbLink = null;
            try {
                if(el.querySelector(".picto-msg-exclam") !== null)
                    ddbLink = el.querySelector(".picto-msg-exclam").dataset.selector;
            }
            catch (e) {}
            posts.push({
                id: el.parentElement.getAttribute("data-id"),
                pseudo: pseudo,
                avatar: avatar,
                date: date,
                message: message,
                signature: signature,
                grade: el.querySelector(".text-modo") !== null ? "modo" : el.querySelector(".text-admin") !== null ? "admin" : "",
                page: JVCAPI.stringToHtml(html).querySelector(".page-active").innerHTML.trim(),
                ddbLink: ddbLink
            });
        });
        return posts;
    }
    if (!local) {
        try {
        let req = new XMLHttpRequest();
        req.onreadystatechange = function (event) {
            if (this.readyState === XMLHttpRequest.DONE) {
                if (this.status === 200) {
                    let html = this.responseText;
                    callback({
                        html: html,
                        posts: f(html)
                    });
                } else {
                    let status = this.status;
                    callback({
                        error: status
                    });
                }
            }
        };
        req.open('GET', link, true);
        req.send(null);
    }
    catch(e) {
        callback({
            error: "XMLHttpRequest error"
        });
    }
    } else {
        callback({
            html: document.documentElement.innerHTML,
            posts: f(document.documentElement.innerHTML)
        });
    }
};
JVCAPI.stringToHtml = function (s) {
    return (new DOMParser()).parseFromString(s, "text/html");
};

JVCAPI.query = function (q) {
    return document.querySelector(q);
}

var stringToHtml = JVCAPI.stringToHtml;
var query = JVCAPI.query;
<|endoftext|>


<commit_before>/**
 * anyBaseConverter (https://github.com/zensh/nodeAnyBaseConverter)
 * This extend Number.toString() and parseInt(), you can define base number and convert string table yourself.
 * Copyright (c) 2012-2013, ZENSH. (MIT Licensed)
 */

;(function() {
    function anyBaseConverter(original, base, string_table) {

        //  anyBaseConverter(original, [base], [string_table]);
        //
        //  This function extend Number.toString() and parseInt(), you can define base number and convert string table yourself.
        //
        //      original : String or Number, when String, character must be in string_table, converter to a decimal number;
        //                 when Number converter to a string that used string_table;
        //          base : Number, optional, default value is 10, must be an integer, 2 <= base <= string_table.length; if base <=36
        //                 and string_table use default value, anyBaseConverter() call native base conversion.
        //  string_table : String, optional, default value is "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
        //                 character must be unique.
        //
        var STRING = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            result;

        function decToGeneric(o, b, c) {
            if (b <= 36 && c === STRING) {
                return o.toString(b); // Fallback to native base conversion
            }
            var re = '',
                q = 0;
            while (o != 0) {
                q = o % b;
                re = c[q] + re;
                o = (o - q) / b;
            }
            return re;
        }
        function genericToDec(o, b, c) {
            if (b <= 36 && c === STRING) {
                return parseInt(o, b); // Fallback to native base conversion
            }
            var cache = {},
            s = '',
                re = 0,
                pow = 1;
            for (var i = o.length - 1; i >= 0; i--) {
                s = o[i];
                if (typeof cache[s] == 'undefined') {
                    cache[s] = c.indexOf(s);
                }
                re += pow * cache[s];
                pow *= b;
            }
            return re;
        }
        try {
            //Check out string_table
            string_table = string_table || STRING; //if undefined, set default value STRING
            if (string_table !== STRING && string_table === STRING.slice(0, string_table.length)) {
                string_table = STRING;
            } //if subset of STRING, set default value STRING
            if (typeof string_table === 'string' && string_table.length >= 2) {
                if (string_table !== STRING) { //if STRING, need not check out
                    // var reg = /\s+/;  //check if any Unicode whitespace character
                    // if(reg.test(string_table)) {
                    //     throw new Error('"string_table" err! It must be not a unicode whitespace character!');
                    // }
                    var unique = {};
                    for (var i = string_table.length - 1; i >= 0; i--) { //check out for uniquely
                        if (unique['__' + string_table[i]] !== 1) unique['__' + string_table[i]] = 1;
                        else throw new Error('"string_table" err! It must be unique! : "' + string_table[i] + '"');
                    };
                }
            } else {
                throw new Error('"string_table" must be string, and string_table.length >=2.');
            }
            //check out base
            base = base || 10; //if undefined, set default value 10
            if (typeof base !== 'number' || !isFinite(base) || base !== Math.floor(base) || base < 2 || base > string_table.length) {
                throw new Error('Invalid "base" number! It must be an integer, and 2 <= base <= string_table.length.');
            }
            //check out original and execute
            switch (typeof original) {
                case 'number':
                    if (isFinite(original) && original >= 0 && original <= Number.MAX_VALUE && original === Math.floor(original)) {
                        result = decToGeneric(original, base, string_table);
                    } else {
                        throw new Error('Invalid "original" number! It must be an integer, and 0 <= number <= Number.MAX_VALUE.');
                    }
                    break;
                case 'string':
                    for (var i = original.length - 1; i >= 0; i--) {
                        var checkout = string_table.indexOf(original[i]);
                        if (checkout === -1 || checkout >= base) {
                            throw new Error('"' + original[i] + '" is invalid "original" string! Available character is "' + string_table + '".');
                        }
                    };
                    result = genericToDec(original, base, string_table);
                    break;
                default:
                    throw new Error('"original" must be number or string!');
            }
            return result;
        } catch (err) {
            console.log(err);
            return null;
        }
    };
    if (typeof module !== 'undefined') {
        module.exports = anyBaseConverter;
    } else {
        this.anyBaseConverter = anyBaseConverter;
    }
}).call(function() {
    return this || (typeof window !== 'undefined' ? window : global);
}());

<commit_msg>直接抛出错误输入，不再catch<commit_after>/**
 * anyBaseConverter (https://github.com/zensh/nodeAnyBaseConverter)
 * This extend Number.toString() and parseInt(), you can define base number and convert string table yourself.
 * Copyright (c) 2012-2013, ZENSH. (MIT Licensed)
 */

;(function() {
    function anyBaseConverter(original, base, string_table) {

        //  anyBaseConverter(original, [base], [string_table]);
        //
        //  This function extend Number.toString() and parseInt(), you can define base number and convert string table yourself.
        //
        //      original : String or Number, when String, character must be in string_table, converter to a decimal number;
        //                 when Number converter to a string that used string_table;
        //          base : Number, optional, default value is 10, must be an integer, 2 <= base <= string_table.length; if base <=36
        //                 and string_table use default value, anyBaseConverter() call native base conversion.
        //  string_table : String, optional, default value is "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
        //                 character must be unique.
        //
        var STRING = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            result;

        function decToGeneric(o, b, c) {
            if (b <= 36 && c === STRING) {
                return o.toString(b); // Fallback to native base conversion
            }
            var re = '',
                q = 0;
            while (o != 0) {
                q = o % b;
                re = c[q] + re;
                o = (o - q) / b;
            }
            return re;
        }
        function genericToDec(o, b, c) {
            if (b <= 36 && c === STRING) {
                return parseInt(o, b); // Fallback to native base conversion
            }
            var cache = {},
            s = '',
                re = 0,
                pow = 1;
            for (var i = o.length - 1; i >= 0; i--) {
                s = o[i];
                if (typeof cache[s] == 'undefined') {
                    cache[s] = c.indexOf(s);
                }
                re += pow * cache[s];
                pow *= b;
            }
            return re;
        }

        //Check out string_table
        string_table = string_table || STRING; //if undefined, set default value STRING
        if (string_table !== STRING && string_table === STRING.slice(0, string_table.length)) {
            string_table = STRING;
        } //if subset of STRING, set default value STRING
        if (typeof string_table === 'string' && string_table.length >= 2) {
            if (string_table !== STRING) { //if STRING, need not check out
                // var reg = /\s+/;  //check if any Unicode whitespace character
                // if(reg.test(string_table)) {
                //     throw new Error('"string_table" err! It must be not a unicode whitespace character!');
                // }
                var unique = {};
                for (var i = string_table.length - 1; i >= 0; i--) { //check out for uniquely
                    if (unique['__' + string_table[i]] !== 1) unique['__' + string_table[i]] = 1;
                    else throw new Error('"string_table" err! It must be unique! : "' + string_table[i] + '"');
                };
            }
        } else {
            throw new Error('"string_table" must be string, and string_table.length >=2.');
        }
        //check out base
        base = base || 10; //if undefined, set default value 10
        if (typeof base !== 'number' || !isFinite(base) || base !== Math.floor(base) || base < 2 || base > string_table.length) {
            throw new Error('Invalid "base" number! It must be an integer, and 2 <= base <= string_table.length.');
        }
        //check out original and execute
        switch (typeof original) {
            case 'number':
                if (isFinite(original) && original >= 0 && original <= Number.MAX_VALUE && original === Math.floor(original)) {
                    result = decToGeneric(original, base, string_table);
                } else {
                    throw new Error('Invalid "original" number! It must be an integer, and 0 <= number <= Number.MAX_VALUE.');
                }
                break;
            case 'string':
                for (var i = original.length - 1; i >= 0; i--) {
                    var checkout = string_table.indexOf(original[i]);
                    if (checkout === -1 || checkout >= base) {
                        throw new Error('"' + original[i] + '" is invalid "original" string! Available character is "' + string_table + '".');
                    }
                };
                result = genericToDec(original, base, string_table);
                break;
            default:
                throw new Error('"original" must be number or string!');
        }
        return result;
    };
    if (typeof module !== 'undefined') {
        module.exports = anyBaseConverter;
    } else {
        this.anyBaseConverter = anyBaseConverter;
    }
}).call(function() {
    return this || (typeof window !== 'undefined' ? window : global);
}());
<|endoftext|>


<commit_before>var request = require('request');
var moment = require('moment');

function getDrinks(callback) {
  request('http://104.131.47.86:8000/api/drinks', function (error, response, body) {
    var json = JSON.parse(body);
    callback = (typeof callback === 'function') ? callback : function() {};
    callback(json.objects);
  });
}

function getRecentDrinks(drinks, callback) {
  var currentTime = moment();
  var recentDrinks = [];
  for(var i = 0; i < drinks.length; i++) {
    var timeDiff = currentTime.diff(drinks[i].time, 'minutes')
    if(timeDiff < 30) {
      recentDrinks.push(drinks[i]);
    }
  }
  callback = (typeof callback === 'function') ? callback : function() {};
  callback(recentDrinks);
}

function addDrinkVolumes(drinks, callback) {
  var volume = 0;
  for(var i = 0; i < drinks.length; i++) {
    volume = volume + drinks[i].volume_ml;
  }
  console.log(volume);
  callback = (typeof callback === 'function') ? callback : function() {};
  callback(volume);
}

<commit_msg>added error checking to getDrinks<commit_after>var request = require('request');
var moment = require('moment');

function getDrinks(callback) {
  request('http://104.131.47.86:8000/api/drinks', function (error, response, body) {
    if(!error) {
      var json = JSON.parse(body);
      callback = (typeof callback === 'function') ? callback : function() {};
      callback(json.objects);
    }
  });
}

function getRecentDrinks(drinks, callback) {
  var currentTime = moment();
  var recentDrinks = [];
  for(var i = 0; i < drinks.length; i++) {
    var timeDiff = currentTime.diff(drinks[i].time, 'minutes')
    if(timeDiff < 30) {
      recentDrinks.push(drinks[i]);
    }
  }
  callback = (typeof callback === 'function') ? callback : function() {};
  callback(recentDrinks);
}

function addDrinkVolumes(drinks, callback) {
  var volume = 0;
  for(var i = 0; i < drinks.length; i++) {
    volume = volume + drinks[i].volume_ml;
  }
  console.log(volume);
  callback = (typeof callback === 'function') ? callback : function() {};
  callback(volume);
}

<|endoftext|>


<commit_before>/**
 * @overview Book-Generator Lib
 * @module bookGenerator
 * @author Dominik Sigmund
 * @version 0.1
 * @description Creates pdfs from Images
 * @memberof resilienz
 * @requires module:fs
 * @requires module:sync
 * @requires module:child_process
 * @requires bin:imagemagick
 */
 var fs = require('fs')
 var async = require('async')
 const execSync = require('child_process').execSync
 function BookGenerator (layouter, pagespath, bookpath, bookpages) {
   var self = {}
   self.pagespath = pagespath
   self.bookpath = bookpath
   self.pages = bookpages
   self.layouter = layouter
   self.createBook = createBook
   self.getBook = getBook
   return self
 }

 function createBook (actionid, language, callback) {
   var self = this
   fs.readdir(self.pagespath + '/' + actionid, function (error, files) {
     if (error) {
       fs.mkdir(self.pagespath + '/' + actionid, function (error) {
         if (error) {
           callback(error)
         } else {
           fs.readdir(self.pagespath + '/' + actionid, function (error, files) {
             if (error) {
               callback(error)
             } else {
               composeFiles(self.layouter, self.pagespath, actionid, language, self.pages, function (error, parm) {
                 if (error) {
                   callback(error)
                 } else {
                   makePDF(self.bookpath, parm, actionid, function (error) {
                     if (error) {
                       callback(error)
                     } else {
                       callback(null, self.bookpath + '/' + actionid + '.pdf')
                     }
                   })
                 }
               })
             }
           })
         }
       })
     } else {
       composeFiles(self.layouter, self.pagespath, actionid, language, self.pages, function (error, parm) {
         if (error) {
           callback(error)
         } else {
           makePDF(self.bookpath, parm, actionid, function (error) {
             if (error) {
               callback(error)
             } else {
               callback(null, self.bookpath + '/' + actionid + '.pdf')
             }
           })
         }
       })
     }
   })
 }

 function createPage (layouter, actionid, language, pagespath, page, callback) {
   var split = false
   var target = ''
   if (page === 1 || page === 44) {
     target = pagespath + '/' + actionid + '/' + page + '.png'
   } else {
     target = pagespath + '/' + actionid + '/' + page + '_two.png'
     split = true
   }
   var parameter = ''
   layouter.createPage(actionid, language, page, function () {
     if (split) {
       // convert -crop 720x1040 image.png cropped_%d.png
       execSync('convert -crop 720x1040 ' + target + ' /tmp/splitted_$d.png') // to tmp
       execSync('mv /tmp/splitted_1.png ' + pagespath + '/' + actionid + '/' + page + '.png')
       execSync('mv /tmp/splitted_2.png ' + pagespath + '/' + actionid + '/' + (page + 1) + '.png')
       parameter = pagespath + '/' + actionid + '/' + page + '.png'
       parameter += pagespath + '/' + actionid + '/' + (page + 1) + '.png'
     } else {
       parameter += target
     }
     callback(null, parameter)
   })
 }

 function composeFiles (layouter, pagespath, actionid, language, maxPages, callback) {
   var listOfTasks = []
   for (var i = 1; i <= maxPages; i++) {
     if (i !== 1 && i % 2 !== 0) continue
     var page = i
     listOfTasks.push(function (callback) {
       (function (variable) {
         createPage(layouter, actionid, language, pagespath, variable, callback)
       })(page)
     }
    )
   }
   async.series(listOfTasks, function (error, parameters) {
     if (error) {
       callback(error)
     } else {
       callback(null, parameters.join(' '))
     }
   })
 }

 function makePDF (bookpath, parameter, actionid, callback) {
   var cmd = 'convert ' + parameter + ' -compress Zip ' + bookpath + '/' + actionid + '.pdf'
   console.log(cmd)
   var output = execSync(cmd, true)
   if (output.stderr || output.stdout) {
     console.log(output.stdout)
     console.error(output.stderr)
     callback(output)
   } else {
     callback(null)
   }
 }

 function getBook (actionid, callback) {
   var self = this
   fs.access(self.bookpath + '/' + actionid + '.pdf', fs.constants.R_OK | fs.constants.W_OK, function (error) {
     if (error) {
       self.createBook(actionid, function (error) {
         if (error) {
           callback(error)
         } else {
           callback(null, self.bookpath + '/' + actionid + '.pdf')
         }
       })
     } else {
       callback(null, self.bookpath + '/' + actionid + '.pdf')
     }
   })
 }

 module.exports = BookGenerator
<commit_msg>counting<commit_after>/**
 * @overview Book-Generator Lib
 * @module bookGenerator
 * @author Dominik Sigmund
 * @version 0.1
 * @description Creates pdfs from Images
 * @memberof resilienz
 * @requires module:fs
 * @requires module:sync
 * @requires module:child_process
 * @requires bin:imagemagick
 */
 var fs = require('fs')
 var async = require('async')
 const execSync = require('child_process').execSync
 function BookGenerator (layouter, pagespath, bookpath, bookpages) {
   var self = {}
   self.pagespath = pagespath
   self.bookpath = bookpath
   self.pages = bookpages
   self.layouter = layouter
   self.createBook = createBook
   self.getBook = getBook
   return self
 }

 function createBook (actionid, language, callback) {
   var self = this
   fs.readdir(self.pagespath + '/' + actionid, function (error, files) {
     if (error) {
       fs.mkdir(self.pagespath + '/' + actionid, function (error) {
         if (error) {
           callback(error)
         } else {
           fs.readdir(self.pagespath + '/' + actionid, function (error, files) {
             if (error) {
               callback(error)
             } else {
               composeFiles(self.layouter, self.pagespath, actionid, language, self.pages, function (error, parm) {
                 if (error) {
                   callback(error)
                 } else {
                   makePDF(self.bookpath, parm, actionid, function (error) {
                     if (error) {
                       callback(error)
                     } else {
                       callback(null, self.bookpath + '/' + actionid + '.pdf')
                     }
                   })
                 }
               })
             }
           })
         }
       })
     } else {
       composeFiles(self.layouter, self.pagespath, actionid, language, self.pages, function (error, parm) {
         if (error) {
           callback(error)
         } else {
           makePDF(self.bookpath, parm, actionid, function (error) {
             if (error) {
               callback(error)
             } else {
               callback(null, self.bookpath + '/' + actionid + '.pdf')
             }
           })
         }
       })
     }
   })
 }

 function createPage (layouter, actionid, language, pagespath, page, callback) {
   var split = false
   var target = ''
   if (page === 1 || page === 44) {
     target = pagespath + '/' + actionid + '/' + page + '.png'
   } else {
     target = pagespath + '/' + actionid + '/' + page + '_two.png'
     split = true
   }
   var parameter = ''
   layouter.createPage(actionid, language, page, function () {
     if (split) {
       // convert -crop 720x1040 image.png cropped_%d.png
       execSync('convert -crop 720x1040 ' + target + ' /tmp/splitted_$d.png') // to tmp
       execSync('mv /tmp/splitted_1.png ' + pagespath + '/' + actionid + '/' + page + '.png')
       execSync('mv /tmp/splitted_2.png ' + pagespath + '/' + actionid + '/' + (page + 1) + '.png')
       parameter = pagespath + '/' + actionid + '/' + page + '.png'
       parameter += pagespath + '/' + actionid + '/' + (page + 1) + '.png'
     } else {
       parameter += target
     }
     callback(null, parameter)
   })
 }

 function composeFiles (layouter, pagespath, actionid, language, maxPages, callback) {
   var listOfTasks = []
   var pages = []
   for (var i = 1; i <= maxPages; i++) {
     if (i !== 1 && i % 2 !== 0) continue
     pages.push(i)
   }
   pages.forEach(function (listItem, index) {
     listOfTasks.push(function (callback) { createPage(layouter, actionid, language, pagespath, listItem, callback) })
   })
   async.series(listOfTasks, function (error, parameters) {
     if (error) {
       callback(error)
     } else {
       callback(null, parameters.join(' '))
     }
   })
 }

 function makePDF (bookpath, parameter, actionid, callback) {
   var cmd = 'convert ' + parameter + ' -compress Zip ' + bookpath + '/' + actionid + '.pdf'
   console.log(cmd)
   var output = execSync(cmd, true)
   if (output.stderr || output.stdout) {
     console.log(output.stdout)
     console.error(output.stderr)
     callback(output)
   } else {
     callback(null)
   }
 }

 function getBook (actionid, callback) {
   var self = this
   fs.access(self.bookpath + '/' + actionid + '.pdf', fs.constants.R_OK | fs.constants.W_OK, function (error) {
     if (error) {
       self.createBook(actionid, function (error) {
         if (error) {
           callback(error)
         } else {
           callback(null, self.bookpath + '/' + actionid + '.pdf')
         }
       })
     } else {
       callback(null, self.bookpath + '/' + actionid + '.pdf')
     }
   })
 }

 module.exports = BookGenerator
<|endoftext|>


<commit_before>(function(){var r,n;r=function(){function r(r){"function"==typeof r&&this.draw(r)}var n,t,e,a,o,u,i;return t=/:([\w\d]+)/g,i=/\*/g,a=function(r){var n,t;return n="([^/]+)",t=".*",o(r,n,t)},u=function(r){var n,t;return n="[^/]+",t="(.*)",o(r,n,t)},o=function(r,n,e){return r=r.replace(t,n).replace(i,e),RegExp("^"+r+"$","i")},n=function(r){var n,t,e,a;for(t=/[:|\*]([\w\d]+)/g,a=[];n=t.exec(r);)a.push(e=n[1]);return a},e=function(r){var n,t,e;if(t={},null!=r)for(e=/[\?&]([^=&]+)=?([^&$]+)?/g;n=e.exec(r);)t[n[1]]=n[2];return t},r.prototype.draw=function(r){return r.call(this)},r.prototype.map=function(r,n){var t;if(null==(t=this.mappings)&&(this.mappings=[]),"string"!=typeof r)throw Error("route must be a string");if("function"!=typeof n)throw Error("callback must be a function");return this.mappings.push({route:r,callback:n})},r.prototype.match=function(r,n){var t,e,a,o,u,i,p,l,c;for(l=this.mappings,c=[],i=0,p=l.length;p>i;i++){if(e=l[i],a=this.scan(r,e.route)){if(null!=n){o=n.params,delete n.params;for(t in n)u=n[t],a[t]=u;if(null!=o&&null==a.params)a.params=o;else for(t in o)u=o[t],a.params[t]=u}e.callback(a);break}c.push(void 0)}return c},r.prototype.matchLocation=function(r){var n,t,a;null==r&&(r=window.location),t={},null!=r.search&&(t.params=e(r.search));for(n in r)a=r[n],t[n]=a;return this.match(r.pathname,t)},r.prototype.scan=function(r,t,e){var o,i,p,l,c,s,f,m,h,g,d;if(null==e&&(e={}),s=e.param_regexp||a(t),e.param_regexp=s,!s.test(r))return!1;for(h=e.splat_regexp||u(t),e.splat_regexp=h,l=s.exec(r),m=h.exec(r),c=e.param_names||n(t),e.param_names=c,f={},o=g=0,d=c.length;d>g;o=++g)p=c[o],f[p]=l[o+1];return f.splats=m.slice(1),i={params:f}},r.prototype.namespace=function(r,n){var t,e;return e=this,t={map:function(n,t){return e.map(r+n,t)}},n.call(t)},r}(),n!==void 0&&null!==n?("undefined"!=typeof module&&null!==module&&null!=module.exports&&(n=module.exports=r),n.Cartograph=r):"function"==typeof define&&define.amd?define(function(){return r}):this.Cartograph=r}).call(this);<commit_msg>update minified version<commit_after>(function(){var r,n;r=function(){function r(r){"function"==typeof r&&this.draw(r)}var n,t,e,a,o,p,u;return t=/:([\w\d]+)/g,u=/\*/g,a=function(r){var n,t;return n="([^/]+)",t=".*",o(r,n,t)},p=function(r){var n,t;return n="[^/]+",t="(.*)",o(r,n,t)},o=function(r,n,e){var a;return a=/[\-{}\[\]+?.,\\\^$|#\s]/g,r=r.replace(a,"\\$&").replace(t,n).replace(u,e),RegExp("^"+r+"$","i")},n=function(r){var n,t,e,a;for(t=/[:|\*]([\w\d]+)/g,a=[];n=t.exec(r);)a.push(e=n[1]);return a},e=function(r){var n,t,e;if(t={},null!=r)for(e=/[\?&]([^=&]+)=?([^&$]+)?/g;n=e.exec(r);)t[n[1]]=n[2];return t},r.prototype.draw=function(r){return r.call(this)},r.prototype.map=function(r,n){var t;if(null==(t=this.mappings)&&(this.mappings=[]),"string"!=typeof r)throw Error("route must be a string");if("function"!=typeof n)throw Error("callback must be a function");return this.mappings.push({route:r,callback:n})},r.prototype.match=function(r,n){var t,e,a,o,p,u,i,l,c;for(l=this.mappings,c=[],u=0,i=l.length;i>u;u++){if(e=l[u],a=this.scan(r,e.route)){if(null!=n){o=n.params,delete n.params;for(t in n)p=n[t],a[t]=p;if(null!=o&&null==a.params)a.params=o;else for(t in o)p=o[t],a.params[t]=p}e.callback(a);break}c.push(void 0)}return c},r.prototype.matchLocation=function(r){var n,t,a;null==r&&(r=window.location),t={},null!=r.search&&(t.params=e(r.search));for(n in r)a=r[n],t[n]=a;return this.match(r.pathname,t)},r.prototype.scan=function(r,t,e){var o,u,i,l,c,s,f,m,h,g,d;if(null==e&&(e={}),s=e.param_regexp||a(t),e.param_regexp=s,!s.test(r))return!1;for(h=e.splat_regexp||p(t),e.splat_regexp=h,l=s.exec(r),m=h.exec(r),c=e.param_names||n(t),e.param_names=c,f={},o=g=0,d=c.length;d>g;o=++g)i=c[o],f[i]=l[o+1];return f.splats=m.slice(1),u={params:f}},r.prototype.namespace=function(r,n){var t,e;return e=this,t={map:function(n,t){return e.map(r+n,t)}},n.call(t)},r}(),n!==void 0&&null!==n?("undefined"!=typeof module&&null!==module&&null!=module.exports&&(n=module.exports=r),n.Cartograph=r):"function"==typeof define&&define.amd?define(function(){return r}):this.Cartograph=r}).call(this);<|endoftext|>


<commit_before>import stylesheet from './stylesheet';
import StyleSheet from 'stilr';
import React, { PropTypes as Type } from 'react';
import { findMatch, settings, vertical, variables, assign } from './utils';

const ERGONOMICS = Object.keys( settings );

const cellStyles = StyleSheet.create({
  base: {
    padding: `0 ${ variables.gutter }`
  },
  baseFlex: {
    flex: 1
  },
  flex: {
    display: 'flex'
  },
  top: {
    alignSelf: vertical.top
  },
  bottom: {
    alignSelf: vertical.bottom
  },
  center: {
    alignSelf: vertical.center
  }
}, stylesheet);

class Cell extends React.Component {
  constructor(props, context) {
    super(props, context);
  }

  static propTypes = {
    grow: Type.oneOf([false, true, Type.number]),
    gutter: Type.string,
    flex: Type.bool,
    align: Type.oneOf(['top', 'center', 'bottom']),
    size: (props, propName) => {
      if (props[propName] && props[propName].split('/').length !== 2) {
        return new Error('Size should be a fraction, e.g. 1/6');
      }
    }
  }

  calcWidth(size) {
    const [ numerator, denominator ] = size ? size.split('/') : [];
    const calcSize = `${ ( 100 / denominator ) * numerator }%`;
    return {
      width: calcSize
    };
  }

  handleFlexSize = (breakpoint ) => {
    const { grow, size } = this.props;
    const growStyle = typeof grow === 'number'
      ? grow
      : grow === false
        ? 0
        : undefined;

    return breakpoint && breakpoint !== 'hidden'
      ? this.calcWidth( breakpoint )
      : size
        ? this.calcWidth(size)
        : growStyle !== undefined
          ? { flex: `${ growStyle } 1 auto`,
              WebkitFlex: `${ growStyle } 1 auto`,
              msFlex: `${ growStyle } 1 auto` }
          : null;
  }

  getDefinedBreakpoints = () => {
    let breakpoints = [];

    for (let i = 0, len = ERGONOMICS.length; i < len; i++) {
      if ( this.props[ERGONOMICS[i]] ) breakpoints.push(ERGONOMICS[i]);
    }

    return breakpoints;
  }

  getMatchingBreakpoint = () => {
    return this.props[
      findMatch.apply(
        null,
        this.getDefinedBreakpoints()
      )
    ];
  }

  render() {
    const {
      gutter,
      flex,
      className,
      align,
      style,
      children,
      ...rest
    } = this.props;

    const breakpoint = this.getMatchingBreakpoint();
    const flexSize = this.handleFlexSize(breakpoint);

    this.styles = assign( {},
      gutter
        ? { padding: `0 ${ gutter }` }
        : null,
      flexSize,
      style );

    const classes = [
      cellStyles.base,
      flexSize
        ? null
        : cellStyles.baseFlex,
      className,
      flex
        ? cellStyles.flex : null,
      align
        ? cellStyles[align]
        : null
    ].filter(Boolean).join(' ');

    return breakpoint === 'hidden'
      ? null
      : <div
          { ...rest }
          style={ this.styles }
          className={ classes }>
          { children }
        </div>;
  }
}

export default Cell;
<commit_msg>src: early return if cell is hidden, to avoid calculating css and classes<commit_after>import stylesheet from './stylesheet';
import StyleSheet from 'stilr';
import React, { PropTypes as Type } from 'react';
import { findMatch, settings, vertical, variables, assign } from './utils';

const ERGONOMICS = Object.keys( settings );

const cellStyles = StyleSheet.create({
  base: {
    padding: `0 ${ variables.gutter }`
  },
  baseFlex: {
    flex: 1
  },
  flex: {
    display: 'flex'
  },
  top: {
    alignSelf: vertical.top
  },
  bottom: {
    alignSelf: vertical.bottom
  },
  center: {
    alignSelf: vertical.center
  }
}, stylesheet);

class Cell extends React.Component {
  constructor(props, context) {
    super(props, context);
  }

  static propTypes = {
    grow: Type.oneOf([false, true, Type.number]),
    gutter: Type.string,
    flex: Type.bool,
    align: Type.oneOf(['top', 'center', 'bottom']),
    size: (props, propName) => {
      if (props[propName] && props[propName].split('/').length !== 2) {
        return new Error('Size should be a fraction, e.g. 1/6');
      }
    }
  }

  calcWidth(size) {
    const [ numerator, denominator ] = size ? size.split('/') : [];
    const calcSize = `${ ( 100 / denominator ) * numerator }%`;
    return {
      width: calcSize
    };
  }

  handleFlexSize = (breakpoint ) => {
    const { grow, size } = this.props;
    const growStyle = typeof grow === 'number'
      ? grow
      : grow === false
        ? 0
        : undefined;

    return breakpoint && breakpoint !== 'hidden'
      ? this.calcWidth( breakpoint )
      : size
        ? this.calcWidth(size)
        : growStyle !== undefined
          ? { flex: `${ growStyle } 1 auto`,
              WebkitFlex: `${ growStyle } 1 auto`,
              msFlex: `${ growStyle } 1 auto` }
          : null;
  }

  getDefinedBreakpoints = () => {
    let breakpoints = [];

    for (let i = 0, len = ERGONOMICS.length; i < len; i++) {
      if ( this.props[ERGONOMICS[i]] ) breakpoints.push(ERGONOMICS[i]);
    }

    return breakpoints;
  }

  getMatchingBreakpoint = () => {
    return this.props[
      findMatch.apply(
        null,
        this.getDefinedBreakpoints()
      )
    ];
  }

  render() {
    const {
      gutter,
      flex,
      className,
      align,
      style,
      children,
      ...rest
    } = this.props;

    const breakpoint = this.getMatchingBreakpoint();

    // Return early for performance
    if (breakpoint === 'hidden') {
      return null;
    }

    const flexSize = this.handleFlexSize(breakpoint);

    this.styles = assign( {},
      gutter
        ? { padding: `0 ${ gutter }` }
        : null,
      flexSize,
      style );

    const classes = [
      cellStyles.base,
      flexSize
        ? null
        : cellStyles.baseFlex,
      className,
      flex
        ? cellStyles.flex : null,
      align
        ? cellStyles[align]
        : null
    ].filter(Boolean).join(' ');

    return (
      <div
        { ...rest }
        style={ this.styles }
        className={ classes }>
        { children }
      </div>
    );
  }
}

export default Cell;
<|endoftext|>


<commit_before>var exports = module.exports = {};

var pieces = {
  white: {
    P: '♙',
    K: '♔',
    Q: '♕',
    R: '♖',
    B: '♗',
    N: '♘',
  },
  black: {
    P: '♟',
    K: '♚',
    Q: '♛',
    R: '♜',
    B: '♝',
    N: '♞',
  }
};

exports.renderBoard = function(board) {
  var disp = '';
  for (var x = 0; x < 8; x++) {
    for (var y = 0; y < 8; y++) {
      var square = board.board.squares[x*8+y]
      if (square.piece) {
        var piece = square.piece.notation || 'P';
        disp += pieces[square.piece.side.name][piece];
      } else {
        if ((x+y) % 2 === 1) {
          disp += " ";
        } else {
          disp += "█"
        }
      }
    }
    disp += '\n';
  }
  return disp;
}
<commit_msg>added numbering<commit_after>var exports = module.exports = {};

var pieces = {
  white: {
    P: '♙',
    K: '♔',
    Q: '♕',
    R: '♖',
    B: '♗',
    N: '♘',
  },
  black: {
    P: '♟',
    K: '♚',
    Q: '♛',
    R: '♜',
    B: '♝',
    N: '♞',
  }
};

exports.renderBoard = function(board) {
  var disp = '';
  for (var x = 0; x < 8; x++) {
    disp+= x+'';
    for (var y = 0; y < 8; y++) {
      var square = board.board.squares[x*8+y]
      if (square.piece) {
        var piece = square.piece.notation || 'P';
        disp += pieces[square.piece.side.name][piece];
      } else {
        if ((x+y) % 2 === 1) {
          disp += " ";
        } else {
          disp += "█"
        }
      }
    }
    disp += '\n';
  }
  disp += ' ABCDEFGH';
  return disp;
}
<|endoftext|>


<commit_before>var CloudCmd, Util, DOM, $;
(function(CloudCmd, Util, DOM){
    'use strict';

    CloudCmd.Console = new ConsoleProto(CloudCmd, Util, DOM);

    function ConsoleProto(CloudCmd, Util, DOM){
        var Name    = 'Console',
            Key     = CloudCmd.Key,
            Images  = DOM.Images,
            Console = this;

        this.init                = function(pCallBack){
            Util.loadOnLoad([
                Console.show,
                load,
                CloudCmd.View,
                DOM.jqueryLoad,
            ]);

            DOM.Events.addKey(listener);
            DOM.setButtonKey('f10', Console.show);

            delete Console.init;
        };

        this.show                       = function(){
            var lElement, lViewElement;

            Images.showLoad({top:true});

            lViewElement     = DOM.anyload({
                name        : 'div',
                id          : 'view',
                attribute   : {
                    tabindex : 0
                },
                not_append  : true
            }),

            lElement    = DOM.anyload({
                name        : 'div',
                className   : 'console',
                parent      : lViewElement
            }),

            $(lElement).console({
                promptLabel: '# ',
                commandValidate : function(line){
                    var lRet = line !== "";

                    return lRet;
                },
                commandHandle   : function(line){
                    return line;
                },
                autofocus       : true,
                animateScroll   : true,
                promptHistory   : true,
            });

            CloudCmd.View.show(lViewElement);
        };

        this.hide                       =  function(){
            CloudCmd.View.hide();
        };

        function load(pCallBack){
            Util.time(Name + ' load');

            var lDir    =  CloudCmd.LIBDIRCLIENT + 'terminal/jquery-console/',
                lFiles  = [
                    lDir + 'jquery.console.js',
                    lDir + 'jquery.console.css'
                ];

            DOM.anyLoadInParallel(lFiles, function(){
                console.timeEnd(Name + ' load');

                Util.exec(pCallBack);
            });
        }

        function listener(pEvent){
            var lF10        = Key.F10,
                lESC        = Key.ESC,
                lIsBind     = Key.isBind(),
                lKey        = pEvent.keyCode;

            /* если клавиши можно обрабатывать */
            if (lIsBind)
                switch(lKey){
                    case lF10:
                        Console.show();
                        break;
                    case lESC:
                        Console.hide();
                        break;
                }

        }
    }

})(CloudCmd, Util, DOM);<commit_msg>removed DOM.setButtonKey(f10, Console.show); from Console init<commit_after>var CloudCmd, Util, DOM, $;
(function(CloudCmd, Util, DOM){
    'use strict';

    CloudCmd.Console = new ConsoleProto(CloudCmd, Util, DOM);

    function ConsoleProto(CloudCmd, Util, DOM){
        var Name    = 'Console',
            Key     = CloudCmd.Key,
            Images  = DOM.Images,
            Console = this;

        this.init                = function(pCallBack){
            Util.loadOnLoad([
                Console.show,
                load,
                CloudCmd.View,
                DOM.jqueryLoad,
            ]);

            DOM.Events.addKey(listener);

            delete Console.init;
        };

        this.show                       = function(){
            var lElement, lViewElement;

            Images.showLoad({top:true});

            lViewElement     = DOM.anyload({
                name        : 'div',
                id          : 'view',
                attribute   : {
                    tabindex : 0
                },
                not_append  : true
            }),

            lElement    = DOM.anyload({
                name        : 'div',
                className   : 'console',
                parent      : lViewElement
            }),

            $(lElement).console({
                promptLabel: '# ',
                commandValidate : function(line){
                    var lRet = line !== "";

                    return lRet;
                },
                commandHandle   : function(line){
                    return line;
                },
                autofocus       : true,
                animateScroll   : true,
                promptHistory   : true,
            });

            CloudCmd.View.show(lViewElement);
        };

        this.hide                       =  function(){
            CloudCmd.View.hide();
        };

        function load(pCallBack){
            Util.time(Name + ' load');

            var lDir    =  CloudCmd.LIBDIRCLIENT + 'terminal/jquery-console/',
                lFiles  = [
                    lDir + 'jquery.console.js',
                    lDir + 'jquery.console.css'
                ];

            DOM.anyLoadInParallel(lFiles, function(){
                console.timeEnd(Name + ' load');

                Util.exec(pCallBack);
            });
        }

        function listener(pEvent){
            var lF10        = Key.F10,
                lESC        = Key.ESC,
                lIsBind     = Key.isBind(),
                lKey        = pEvent.keyCode;

            /* если клавиши можно обрабатывать */
            if (lIsBind)
                switch(lKey){
                    case lF10:
                        Console.show();
                        break;
                    case lESC:
                        Console.hide();
                        break;
                }

        }
    }

})(CloudCmd, Util, DOM);<|endoftext|>


<commit_before>var _ = require('lodash')
    , Artifact = require('../artifact')
    , AWS = require('aws-sdk')
    , novalib = require('../nova-lib')
    , fs = require('fs')
    , moment = require('moment')
    , NovaError = require('../nova-error')
    , program = require('../program')
    , Project = require('../project')
    , ProjectRef = require('../project-ref')
    , path = require('path')
    , util = require('util')
    , utils = require('../utils');

function Command(opts) {
    if (!(this instanceof Command)) {
        return new Command(opts);
    }

    this.commandOptions = opts.options;

    if (_(opts.argv).isEmpty()) {
        throw new Error('Missing project reference');
    } else if (opts.argv.length !== 1) {
        throw new Error('Too many project references specified');
    }

    var ref = ProjectRef.parse(opts.argv[0]);
    this.project = new Project(ref.name);
    this.artifactName = ref.subname;

    if (!this.artifactName) {
        throw new Error('Build command needs an artifact name.');
    }
}

Command.options = [];
Command.usageText = '[options] project_name/artifact_name';
Command.descriptionText = 'Builds artifacts for the project';

function ensureBucketsExist(regions) {
    var regionsWithoutBuckets = _.filter(regions, region => {
        return program.getNovaBucket().region !== region
            && program.getDataBucket(region) === null;
    });

    if (regionsWithoutBuckets.length === 0) {
        return Promise.resolve();
    }

    var question = util.format(
'Artifacts cannot be placed in regions without nova data buckets.\n\
You can ether run nova init --data-bucket and create the buckets\n\
or nova can create default buckets for you.\n\
Should nova create buckets in regions %s and carry on?\
', regionsWithoutBuckets.join(','));

    return utils.yesorno(question).then(shouldCreateBuckets => {
        if (!shouldCreateBuckets) {
            return Promise.reject(new NovaError('Please init buckets in region(s) ' + regionsWithoutBuckets.join(',') + '. See nova init.'));
        }
        var awsAccountId = program.getAwsAccountId();
        // Params for aws.createBucket
        var bucketsToCreate = _.map(regionsWithoutBuckets, region => {
            return {
                Bucket: util.format('nova-%s-%s', region, awsAccountId),
                ACL: 'private',
                CreateBucketConfiguration: {
                    LocationConstraint: region,
                },
            };
        });
        if (program.options.verbose) {
            console.log('Creating buckets: ' + _.map(bucketsToCreate, 'Bucket').join(','));
        }
        var createBucketPromises = _.map(bucketsToCreate, bucketParams => {
            var region = bucketParams.CreateBucketConfiguration.LocationConstraint;
            var s3 = new AWS.S3({ region: region, signatureVersion: 'v4' });
            var createBucket = utils.pbind(s3.createBucket, s3, bucketParams);
            return createBucket();
        });
        return Promise.all(createBucketPromises).then(values => {
            // Transform into objects accepted by Program.setDataBucket
            return _.map(values, (bucketData, index) => {
                return {
                    region: regionsWithoutBuckets[index],
                    name: bucketsToCreate[index].Bucket,
                    location: bucketData.Location,
                };
            });
        })  ;
    }).then(buckets => {
        return _.map(buckets, bucket => {
            return program.setDataBucket(bucket);
        });
    });
}

function uploadArtifactToS3(keyPath, artifact, regions) {
    var uploadInfo = _.map(regions, region => {
        var bucket = program.getBucket(region);
        return {
            bucketName: bucket.name,
            bucketRegion: region,
            bucketKeyPath: keyPath,
            artifactReadStream: fs.createReadStream(artifact.path),
        };
    });

    var uploadPromises = _.map(uploadInfo, info => {
        var params = {
            Bucket: info.bucketName,
            Key: info.bucketKeyPath,
            Body: info.artifactReadStream,
        };
        var s3 = new AWS.S3({ region : info.bucketRegion, signatureVersion: 'v4' });

        var s3ManagedUploader = s3.upload(params);
        var lastProgress = 0;
        if (program.options.verbose) {
            s3ManagedUploader.on('httpUploadProgress', function(event) {
                var thisProgress = event.loaded / event.total * 100;
                if (thisProgress === 100 || thisProgress > lastProgress + 7) {
                    console.log('Progress (', info.bucketRegion, ')', thisProgress.toFixed(1), '% -', event.loaded, 'of', event.total);
                    lastProgress = thisProgress;
                }
            });
        }

        var s3ManagedUploaderSend = utils.pbind(s3ManagedUploader.send, s3ManagedUploader);
        return s3ManagedUploaderSend().then(function(data) {
            return {
                bucket: info.bucketName,
                key: info.bucketKeyPath,
                region: info.bucketRegion,
                url: data.Location,
            };
        });
    });

    return Promise.all(uploadPromises);
}

Command.prototype.execute = function() {
    var metaInfo = {
        timestamp: moment().utc().format('YYYYMMDDTHHmmss'),
    };

    if (program.options.verbose) {
        console.log('Loading project ' + this.project.name);
    }

    this.project.load(novalib.init({
        projectName: this.project.name,
    }));

    var artifactDef = this.project.findArtifact(this.artifactName);
    if (!artifactDef) {
        throw new Error(`Failed to find artifact '${this.artifactName}' in project '${this.project.name}'`);
    }

    metaInfo.regions = typeof artifactDef.region === 'string'
        ? [artifactDef.region]
        : artifactDef.region;

    if (program.options.verbose) {
        console.log('Ensuring nova buckets in regions ' + metaInfo.regions.join(','));
    }

    return ensureBucketsExist(metaInfo.regions).then(() => {
        if (program.options.verbose) {
            console.log('Building artifact ' + this.artifactName);
        }

        var options = {}; // Currently unused but reserved for future use.
        return utils.pdone(artifactDef.build, artifactDef, options);
    }).then(artifact => {
        if (artifact.type !== Artifact.Type.EBApp
            && artifact.type !== Artifact.Type.Lambda) {
            throw new Error('Only EBApp,Lambda artifact type supported currently');
        }

        if (program.options.verbose) {
            console.log('Uploading artifact to regions ' + metaInfo.regions.join(','));
        }

        var baseName = path.basename(artifact.path);
        var keyPath = path.join(
            'data',
            this.project.name,
            'artifacts',
            this.artifactName,
            metaInfo.timestamp,
            baseName);

        return uploadArtifactToS3(keyPath, artifact, metaInfo.regions);
    }).then(values => {
        if (program.options.verbose) {
            console.log('Updating meta info...');
        }

        delete metaInfo.regions;
        metaInfo.artifacts = _.keyBy(values, 'region');

        return Artifact.setMeta(this.project.name, this.artifactName, metaInfo);
    });
};

module.exports = Command;
<commit_msg>can add that back in when we actually need it<commit_after>var _ = require('lodash')
    , Artifact = require('../artifact')
    , AWS = require('aws-sdk')
    , novalib = require('../nova-lib')
    , fs = require('fs')
    , moment = require('moment')
    , NovaError = require('../nova-error')
    , program = require('../program')
    , Project = require('../project')
    , ProjectRef = require('../project-ref')
    , path = require('path')
    , util = require('util')
    , utils = require('../utils');

function Command(opts) {
    if (!(this instanceof Command)) {
        return new Command(opts);
    }

    this.commandOptions = opts.options;

    if (_(opts.argv).isEmpty()) {
        throw new Error('Missing project reference');
    } else if (opts.argv.length !== 1) {
        throw new Error('Too many project references specified');
    }

    var ref = ProjectRef.parse(opts.argv[0]);
    this.project = new Project(ref.name);
    this.artifactName = ref.subname;

    if (!this.artifactName) {
        throw new Error('Build command needs an artifact name.');
    }
}

Command.options = [];
Command.usageText = '[options] project_name/artifact_name';
Command.descriptionText = 'Builds artifacts for the project';

function ensureBucketsExist(regions) {
    var regionsWithoutBuckets = _.filter(regions, region => {
        return program.getNovaBucket().region !== region
            && program.getDataBucket(region) === null;
    });

    if (regionsWithoutBuckets.length === 0) {
        return Promise.resolve();
    }

    var question = util.format(
'Artifacts cannot be placed in regions without nova data buckets.\n\
You can ether run nova init --data-bucket and create the buckets\n\
or nova can create default buckets for you.\n\
Should nova create buckets in regions %s and carry on?\
', regionsWithoutBuckets.join(','));

    return utils.yesorno(question).then(shouldCreateBuckets => {
        if (!shouldCreateBuckets) {
            return Promise.reject(new NovaError('Please init buckets in region(s) ' + regionsWithoutBuckets.join(',') + '. See nova init.'));
        }
        var awsAccountId = program.getAwsAccountId();
        // Params for aws.createBucket
        var bucketsToCreate = _.map(regionsWithoutBuckets, region => {
            return {
                Bucket: util.format('nova-%s-%s', region, awsAccountId),
                ACL: 'private',
                CreateBucketConfiguration: {
                    LocationConstraint: region,
                },
            };
        });
        if (program.options.verbose) {
            console.log('Creating buckets: ' + _.map(bucketsToCreate, 'Bucket').join(','));
        }
        var createBucketPromises = _.map(bucketsToCreate, bucketParams => {
            var region = bucketParams.CreateBucketConfiguration.LocationConstraint;
            var s3 = new AWS.S3({ region: region, signatureVersion: 'v4' });
            var createBucket = utils.pbind(s3.createBucket, s3, bucketParams);
            return createBucket();
        });
        return Promise.all(createBucketPromises).then(values => {
            // Transform into objects accepted by Program.setDataBucket
            return _.map(values, (bucketData, index) => {
                return {
                    region: regionsWithoutBuckets[index],
                    name: bucketsToCreate[index].Bucket,
                    location: bucketData.Location,
                };
            });
        })  ;
    }).then(buckets => {
        return _.map(buckets, bucket => {
            return program.setDataBucket(bucket);
        });
    });
}

function uploadArtifactToS3(keyPath, artifact, regions) {
    var uploadInfo = _.map(regions, region => {
        var bucket = program.getBucket(region);
        return {
            bucketName: bucket.name,
            bucketRegion: region,
            bucketKeyPath: keyPath,
            artifactReadStream: fs.createReadStream(artifact.path),
        };
    });

    var uploadPromises = _.map(uploadInfo, info => {
        var params = {
            Bucket: info.bucketName,
            Key: info.bucketKeyPath,
            Body: info.artifactReadStream,
        };
        var s3 = new AWS.S3({ region : info.bucketRegion, signatureVersion: 'v4' });

        var s3ManagedUploader = s3.upload(params);
        var lastProgress = 0;
        if (program.options.verbose) {
            s3ManagedUploader.on('httpUploadProgress', function(event) {
                var thisProgress = event.loaded / event.total * 100;
                if (thisProgress === 100 || thisProgress > lastProgress + 7) {
                    console.log('Progress (', info.bucketRegion, ')', thisProgress.toFixed(1), '% -', event.loaded, 'of', event.total);
                    lastProgress = thisProgress;
                }
            });
        }

        var s3ManagedUploaderSend = utils.pbind(s3ManagedUploader.send, s3ManagedUploader);
        return s3ManagedUploaderSend().then(function(data) {
            return {
                bucket: info.bucketName,
                key: info.bucketKeyPath,
                region: info.bucketRegion,
                url: data.Location,
            };
        });
    });

    return Promise.all(uploadPromises);
}

Command.prototype.execute = function() {
    var metaInfo = {
        timestamp: moment().utc().format('YYYYMMDDTHHmmss'),
    };

    if (program.options.verbose) {
        console.log('Loading project ' + this.project.name);
    }

    this.project.load(novalib.init({
        projectName: this.project.name,
    }));

    var artifactDef = this.project.findArtifact(this.artifactName);
    if (!artifactDef) {
        throw new Error(`Failed to find artifact '${this.artifactName}' in project '${this.project.name}'`);
    }

    metaInfo.regions = typeof artifactDef.region === 'string'
        ? [artifactDef.region]
        : artifactDef.region;

    if (program.options.verbose) {
        console.log('Ensuring nova buckets in regions ' + metaInfo.regions.join(','));
    }

    return ensureBucketsExist(metaInfo.regions).then(() => {
        if (program.options.verbose) {
            console.log('Building artifact ' + this.artifactName);
        }

        return utils.pdone(artifactDef.build, artifactDef);
    }).then(artifact => {
        if (artifact.type !== Artifact.Type.EBApp
            && artifact.type !== Artifact.Type.Lambda) {
            throw new Error('Only EBApp,Lambda artifact type supported currently');
        }

        if (program.options.verbose) {
            console.log('Uploading artifact to regions ' + metaInfo.regions.join(','));
        }

        var baseName = path.basename(artifact.path);
        var keyPath = path.join(
            'data',
            this.project.name,
            'artifacts',
            this.artifactName,
            metaInfo.timestamp,
            baseName);

        return uploadArtifactToS3(keyPath, artifact, metaInfo.regions);
    }).then(values => {
        if (program.options.verbose) {
            console.log('Updating meta info...');
        }

        delete metaInfo.regions;
        metaInfo.artifacts = _.keyBy(values, 'region');

        return Artifact.setMeta(this.project.name, this.artifactName, metaInfo);
    });
};

module.exports = Command;
<|endoftext|>


<commit_before>'use strict'

var Expression = require('../expression')
var Definition = require('../definition')

var True = require('./true')
var False = require('./false')

var InjectiveQ = require('./injective-q')

var Zero = require('./zero')
var Plus = require('./plus')
var And = require('./and')

function stop (a, b) {
  return new Expression(module.exports.symbol(), [a, b])
}

function isEqual (a, b) {
  if (a === b) return true
  var ad = a.def()
  if (ad) {
    var bd = b.def()
    if (bd) return ad === bd
    return stop(a, b)
  }

  if (a.atomic() || b.atomic()) {
    return stop(a, b)
  }

  var head = a.head()

  var aArgs = a.args()
  var bArgs = b.args()

  if (head.def() === Plus) {
    var termsA = aArgs.slice(0)
    var termsB = bArgs.slice(0)

    aArgs.forEach(function (ta) {
      for (var i = 0; i < termsB.length; i++) {
        var tb = termsB[i]
        if (isEqual(ta, tb) === true) {
          // remove from both:
          var iA = termsA.indexOf(ta)
          termsA.splice(iA, 1)
          termsB.splice(i, 1)
        }
      }
    })

    if (termsA.length > termsB.length) {
      var tmp = termsA
      termsA = termsB
      termsB = tmp
    }

    if (!termsA.length && !termsB.length) return true
    if (!termsA.length) {
      return new Expression(
        module.exports.symbol(),
        [
          Zero.symbol(),
          new Expression(
            Plus.symbol(),
            termsB
          ).eval()
        ]
      )
    }

    return new Expression(
      module.exports.symbol(),
      [
        new Expression(
          Plus.symbol(),
          termsA
        ).eval(),
        new Expression(
          Plus.symbol(),
          termsB
        ).eval()
      ]
    )
  }

  var argLength = a.args().length
  if (argLength !== b.args().length) return stop(a, b)

  // TODO: isStrictEqual
  if (isEqual(head, b.head()) === true) {
    if (argLength === 0) return true
    var inj = new InjectiveQ(head)
    if (inj.def() === True) {
      var questionbles = []
      for (var i2 = 0; i2 < argLength; i2++) {
        var res = isEqual(aArgs[i2], bArgs[i2])
        if (res === false) {
          return false
        } else if (res !== true) {
          questionbles.push(res)
        }
      }

      if (questionbles.length) {
        return new Expression(And.symbol(), questionbles)
      }
      return true
    }
  }

  return stop(a, b)
}

// Defines the strictest equivalence class apart from definitional equality
// That is, this takes into account objects which have no definition but are identical
module.exports = new Definition(function (a, b) {
  if (a && b) {
    var res = isEqual(a, b)
    if (res === true) return True.symbol('True')
    if (res === false) return False.symbol('False')
    return res
  }
})
<commit_msg>real number equality check<commit_after>'use strict'

var Expression = require('../expression')
var Definition = require('../definition')

var True = require('./true')
var False = require('./false')

var InjectiveQ = require('./injective-q')

var Zero = require('./zero')
var Plus = require('./plus')
var And = require('./and')
var Real = require('./real')

function stop (a, b) {
  return new Expression(module.exports.symbol(), [a, b])
}

function getRealParts (n) {
  var parts = n._value.split('.')
  parts[0] = parts[0].replace(/^0+/, '')
  parts[1] = (parts[1] || '').replace(/0+$/, '')
  return parts
}

function realIsEqual (a, b) {
  var nas = getRealParts(a)
  var nbs = getRealParts(b)

  return nas[0] === nbs[0] && nas[1] === nbs[1]
}

function isEqual (a, b) {
  if (a === b) return true
  var ad = a.def()
  if (ad) {
    var bd = b.def()
    if (bd) return ad === bd
    return stop(a, b)
  }

  if (a.atomic() || b.atomic()) {
    if (a.atomic() && b.atomic()) {
      var ahd = a.head().def()
      var bhd = a.head().def()
      if (bhd && bhd === ahd) {
        if (bhd === Real) {
          return realIsEqual(a, b)
        }
      }
    }
    return stop(a, b)
  }

  var head = a.head()

  var aArgs = a.args()
  var bArgs = b.args()

  if (head.def() === Plus) {
    var termsA = aArgs.slice(0)
    var termsB = bArgs.slice(0)

    aArgs.forEach(function (ta) {
      for (var i = 0; i < termsB.length; i++) {
        var tb = termsB[i]
        if (isEqual(ta, tb) === true) {
          // remove from both:
          var iA = termsA.indexOf(ta)
          termsA.splice(iA, 1)
          termsB.splice(i, 1)
        }
      }
    })

    if (termsA.length > termsB.length) {
      var tmp = termsA
      termsA = termsB
      termsB = tmp
    }

    if (!termsA.length && !termsB.length) return true
    if (!termsA.length) {
      return new Expression(
        module.exports.symbol(),
        [
          Zero.symbol(),
          new Expression(
            Plus.symbol(),
            termsB
          ).eval()
        ]
      )
    }

    return new Expression(
      module.exports.symbol(),
      [
        new Expression(
          Plus.symbol(),
          termsA
        ).eval(),
        new Expression(
          Plus.symbol(),
          termsB
        ).eval()
      ]
    )
  }

  var argLength = a.args().length
  if (argLength !== b.args().length) return stop(a, b)

  // TODO: isStrictEqual
  if (isEqual(head, b.head()) === true) {
    if (argLength === 0) return true
    var inj = new InjectiveQ(head)
    if (inj.def() === True) {
      var questionbles = []
      for (var i2 = 0; i2 < argLength; i2++) {
        var res = isEqual(aArgs[i2], bArgs[i2])
        if (res === false) {
          return false
        } else if (res !== true) {
          questionbles.push(res)
        }
      }

      if (questionbles.length) {
        return new Expression(And.symbol(), questionbles)
      }
      return true
    }
  }

  return stop(a, b)
}

// Defines the strictest equivalence class apart from definitional equality
// That is, this takes into account objects which have no definition but are identical
module.exports = new Definition(function (a, b) {
  if (a && b) {
    var res = isEqual(a, b)
    if (res === true) return True.symbol('True')
    if (res === false) return False.symbol('False')
    return res
  }
})
<|endoftext|>


<commit_before>const is = require('@sindresorhus/is');
const crypto = require('crypto');
const { maskToken } = require('../datasource/npm');

module.exports = {
  decryptConfig,
};

function decryptConfig(config, privateKey) {
  logger.trace({ config }, 'decryptConfig()');
  const decryptedConfig = { ...config };
  for (const [key, val] of Object.entries(config)) {
    if (key === 'encrypted' && is.object(val)) {
      logger.debug({ config: val }, 'Found encrypted config');
      if (privateKey) {
        for (const [eKey, eVal] of Object.entries(val)) {
          try {
            const decryptedStr = crypto
              .privateDecrypt(privateKey, Buffer.from(eVal, 'base64'))
              .toString();
            logger.info(`Decrypted ${eKey}`);
            if (eKey === 'npmToken') {
              const token = decryptedStr.replace(/\n$/, '');
              logger.info({ token: maskToken(token) }, 'Migrating npmToken to npmrc');
              decryptedConfig.npmrc = `//registry.npmjs.org/:_authToken=${token}\n`;
            } else {
              decryptedConfig[eKey] = decryptedStr;
            }
          } catch (err) {
            logger.warn({ err }, `Error decrypting ${eKey}`);
          }
        }
      } else {
        logger.error('Found encrypted data but no privateKey');
      }
      delete decryptedConfig.encrypted;
    } else if (is.array(val)) {
      decryptedConfig[key] = [];
      val.forEach(item => {
        if (is.object(item) && !is.array(item)) {
          decryptedConfig[key].push(decryptConfig(item, privateKey));
        } else {
          decryptedConfig[key].push(item);
        }
      });
    } else if (is.object(val) && key !== 'content') {
      decryptedConfig[key] = decryptConfig(val, privateKey);
    }
  }
  delete decryptedConfig.encrypted;
  logger.trace({ config: decryptedConfig }, 'decryptedConfig');
  return decryptedConfig;
}
<commit_msg>chore: fix prettier formatting<commit_after>const is = require('@sindresorhus/is');
const crypto = require('crypto');
const { maskToken } = require('../datasource/npm');

module.exports = {
  decryptConfig,
};

function decryptConfig(config, privateKey) {
  logger.trace({ config }, 'decryptConfig()');
  const decryptedConfig = { ...config };
  for (const [key, val] of Object.entries(config)) {
    if (key === 'encrypted' && is.object(val)) {
      logger.debug({ config: val }, 'Found encrypted config');
      if (privateKey) {
        for (const [eKey, eVal] of Object.entries(val)) {
          try {
            const decryptedStr = crypto
              .privateDecrypt(privateKey, Buffer.from(eVal, 'base64'))
              .toString();
            logger.info(`Decrypted ${eKey}`);
            if (eKey === 'npmToken') {
              const token = decryptedStr.replace(/\n$/, '');
              logger.info(
                { token: maskToken(token) },
                'Migrating npmToken to npmrc'
              );
              decryptedConfig.npmrc = `//registry.npmjs.org/:_authToken=${token}\n`;
            } else {
              decryptedConfig[eKey] = decryptedStr;
            }
          } catch (err) {
            logger.warn({ err }, `Error decrypting ${eKey}`);
          }
        }
      } else {
        logger.error('Found encrypted data but no privateKey');
      }
      delete decryptedConfig.encrypted;
    } else if (is.array(val)) {
      decryptedConfig[key] = [];
      val.forEach(item => {
        if (is.object(item) && !is.array(item)) {
          decryptedConfig[key].push(decryptConfig(item, privateKey));
        } else {
          decryptedConfig[key].push(item);
        }
      });
    } else if (is.object(val) && key !== 'content') {
      decryptedConfig[key] = decryptConfig(val, privateKey);
    }
  }
  delete decryptedConfig.encrypted;
  logger.trace({ config: decryptedConfig }, 'decryptedConfig');
  return decryptedConfig;
}
<|endoftext|>


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

var config = require('../config');
var PackageName = require('./package-name');
var path = require('path');
var extend = require('../common').extend;
var hasProperties = require('../common').hasProperties;
var registryCache = require('../package').registryCache;
var Promise = require('rsvp').Promise;
var ui = require('../ui');
var fs = require('graceful-fs');
var asp = require('rsvp').denodeify;
var readJSON = require('../common').readJSON;
var alphabetize = require('../common').alphabetize;
var globalConfig = require('../global-config');
var processDeps = require('../package').processDeps;

var isWindows = process.platform.match(/^win/);
var winRegEx = /\\/g;
function winPath(path) {
  if (!isWindows)
    return path;
  return path.replace(winRegEx, '/');
}

/*
 * Package.json Configuration Class
 *
 * name
 * main
 * registry
 * dependencies
 * configFile
 * baseURL
 * lib
 * dist
 * packages
 * format
 * map
 * buildConfig
 *
 */
function PackageJSON(fileName) {
  this.fileName = fileName;
}

PackageJSON.prototype.read = function(prompts) {
  if (this.read_)
    throw "Package.json file already read";

  this.read_ = true;
  var self = this;
  var pjson;

  return readJSON(this.fileName)
  .then(function(_pjson) {
    self.originalPjson = _pjson;

    self.jspmPrefix = true;
    if (_pjson.registry && !_pjson.jspm)
      self.jspmPrefix = false;

    // derive the jspm config from the 'jspm' property in the package.json
    // also sets the registry property if dependencies are jspm-prefixed
    pjson = config.derivePackageConfig(_pjson);

    prompts = prompts || (!_pjson.jspm && !_pjson.registry);

    if (prompts)
      return doInitPrompts(pjson, self.fileName, self.jspmPrefix)
      .then(function(prefixed) {
        self.jspmPrefix = prefixed;
      });
  })
  .then(function() {
    self.dir = path.dirname(self.fileName);

    // populate defaults as we go
    var defaults = self.defaults = {};

    // create structured configuration with defaults
    defaults.name = 'app';
    self.name = pjson.name || defaults.name;

    self.registry = pjson.registry || globalConfig.config.registry;
    self.dependencies = {};
    // only read dependencies when combined with a registry property
    self.dependencies = processDeps(pjson.dependencies, self.registry);

    defaults.baseURL = self.dir;
    self.baseURL = pjson.directories && pjson.directories.baseURL && path.resolve(self.dir, pjson.directories.baseURL) || defaults.baseURL;

    defaults.lib = path.resolve(self.baseURL, 'lib');
    defaults.dist = path.resolve(self.baseURL, 'dist');
    defaults.packages = path.resolve(self.baseURL, 'jspm_packages');

    defaults.main = defaults.lib + '/index';
    self.main = pjson.main || defaults.main;

    self.lib = pjson.directories && pjson.directories.lib && path.resolve(self.dir, pjson.directories.lib) || defaults.lib;
    self.dist = pjson.directories && pjson.directories.dist && path.resolve(self.dir, pjson.directories.dist) || defaults.dist;
    // NB can remove jspmPackages suport in time
    self.packages = pjson.directories && pjson.directories.packages && path.resolve(self.dir, pjson.directories.packages)
      || pjson.directories && pjson.directories.jspmPackages && path.resolve(self.dir, pjson.directories.jspmPackages) || defaults.packages;

    defaults.configFile = path.resolve(self.baseURL, 'config.js');
    self.configFile = pjson.configFile && path.resolve(self.dir, pjson.configFile) || defaults.configFile;

    self.format = pjson.format;
    self.map = extend({}, pjson.map || {});

    // NB remove when nodelibs no longer built this way
    self.useJSExtensions = pjson.useJSExtensions;

    self.buildConfig = extend({}, pjson.buildConfig || {});

    return prompts;
  });
}

PackageJSON.prototype.write = function() {
  var pjson = this.jspmPrefix ? {} : this.originalPjson;

  if (!this.jspmPrefix) {
    delete pjson.jspm;
    pjson.registry = this.registry || globalConfig.config.registry;
  }
  else if (this.registry != 'jspm') {
    pjson.registry = this.registry;
  }

  var defaults = this.defaults;

  // only set properties that differ from the defaults
  if (this.name != defaults.name)
    pjson.name = this.name;
  if (this.main != defaults.main)
    pjson.main = this.main;

  if (this.format)
    pjson.format = this.format;

  var directories = {};
  if (this.baseURL != defaults.baseURL)
    directories.baseURL = this.baseURL;
  directories.lib = this.lib;
  if (this.dist != defaults.dist)
    directories.dist = this.dist;
  if (this.packages != defaults.packages)
    directories.packages = this.packages;

  if (hasProperties(directories)) {
    for (var d in directories) {
      directories[d] = winPath(path.relative(this.dir, directories[d]));
      if (!directories[d])
        directories[d] = '.';
    }
    pjson.directories = extend(pjson.directories || {}, directories);
    pjson.directories = alphabetize(pjson.directories);
  }

  if (this.configFile != defaults.configFile)
    pjson.configFile = winPath(path.relative(this.dir, this.configFile));

  pjson.map = alphabetize(this.map);
  if (!hasProperties(pjson.map))
    delete pjson.map;

  pjson.dependencies = {};
  var depValue;
  for (var d in this.dependencies) {
    var dep = this.dependencies[d];
    if (!dep)
      continue;
    if (dep.endpoint == 'jspm') {
      if (d == dep.package)
        depValue = dep.version;
      else
        depValue = dep.exactPackage;
    }
    // name is exactly as in registry
    else if (registryCache[d] == dep.name)
        depValue = dep.version;
    else
      depValue = dep.exactName;

    pjson.dependencies[d] = depValue;
  }
  pjson.dependencies = alphabetize(pjson.dependencies);
  if (!hasProperties(pjson.dependencies))
    delete pjson.dependencies;

  pjson.buildConfig = this.buildConfig;
  if (!hasProperties(pjson.buildConfig))
    delete pjson.buildConfig;

  // dedupe jspm properties against base properties
  if (this.jspmPrefix) {
    for (var p in pjson) {
      if (this.originalPjson[p] === pjson[p])
        delete pjson[p];
    }
    this.originalPjson.jspm = pjson;
  }

  // NB check that the file hasn't changed since we opened it and if so, prompt
  return asp(fs.writeFile)(this.fileName, JSON.stringify(this.originalPjson, null, 2) + '\n');
}

// can take an existing non-jspm package.json
function doInitPrompts(pjson, pjsonPath, prefixed) {
  var baseDir = path.dirname(pjsonPath);
  var base;

  pjson.directories = pjson.directories || {};

  return Promise.resolve()
  .then(function() {
    return ui.confirm('Would you like jspm to prefix the jspm package.json properties under %jspm%?', prefixed);
  })
  .then(function(prefix) {
    prefixed = prefix;
    return ui.input('Enter the package name for the project', pjson.name);
  })
  .then(function(name) {
    pjson.name = name;
    return ui.input('Enter server baseURL (public folder path)', pjson.directories.baseURL || '.');
  })
  .then(function(baseURL) {
    base = path.relative(process.cwd(), path.resolve(baseURL));
    baseURL = path.relative(baseDir, path.resolve(baseURL));
    if (!base)
      base = '.';
    base += path.sep;
    if (baseURL)
      pjson.directories.baseURL = baseURL;
    return ui.input('Enter project code folder', pjson.directories.lib || base + 'lib');
  })
  .then(function(lib) {
    pjson.directories.lib = path.relative(baseDir, path.resolve(lib));
    if (!pjson.directories.lib)
      pjson.directories.lib = '.';
    return ui.input('Enter jspm packages folder', pjson.directories.packages || base + 'jspm_packages');
  })
  .then(function(packages) {
    pjson.directories.packages = path.relative(baseDir, path.resolve(packages));
    return ui.input('Enter config file path', pjson.configFile || base + 'config.js');
  })
  .then(function(configFile) {
    pjson.configFile = path.relative(baseDir, path.resolve(configFile))
    return prefixed;
  });
}

module.exports = PackageJSON;
<commit_msg>default directories.lib to current folderg<commit_after>/*
 *   Copyright 2014-2015 Guy Bedford (http://guybedford.com)
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

var config = require('../config');
var PackageName = require('./package-name');
var path = require('path');
var extend = require('../common').extend;
var hasProperties = require('../common').hasProperties;
var registryCache = require('../package').registryCache;
var Promise = require('rsvp').Promise;
var ui = require('../ui');
var fs = require('graceful-fs');
var asp = require('rsvp').denodeify;
var readJSON = require('../common').readJSON;
var alphabetize = require('../common').alphabetize;
var globalConfig = require('../global-config');
var processDeps = require('../package').processDeps;

var isWindows = process.platform.match(/^win/);
var winRegEx = /\\/g;
function winPath(path) {
  if (!isWindows)
    return path;
  return path.replace(winRegEx, '/');
}

/*
 * Package.json Configuration Class
 *
 * name
 * main
 * registry
 * dependencies
 * configFile
 * baseURL
 * lib
 * dist
 * packages
 * format
 * map
 * buildConfig
 *
 */
function PackageJSON(fileName) {
  this.fileName = fileName;
}

PackageJSON.prototype.read = function(prompts) {
  if (this.read_)
    throw "Package.json file already read";

  this.read_ = true;
  var self = this;
  var pjson;

  return readJSON(this.fileName)
  .then(function(_pjson) {
    self.originalPjson = _pjson;

    self.jspmPrefix = true;
    if (_pjson.registry && !_pjson.jspm)
      self.jspmPrefix = false;

    // derive the jspm config from the 'jspm' property in the package.json
    // also sets the registry property if dependencies are jspm-prefixed
    pjson = config.derivePackageConfig(_pjson);

    prompts = prompts || (!_pjson.jspm && !_pjson.registry);

    if (prompts)
      return doInitPrompts(pjson, self.fileName, self.jspmPrefix)
      .then(function(prefixed) {
        self.jspmPrefix = prefixed;
      });
  })
  .then(function() {
    self.dir = path.dirname(self.fileName);

    // populate defaults as we go
    var defaults = self.defaults = {};

    // create structured configuration with defaults
    defaults.name = 'app';
    self.name = pjson.name || defaults.name;

    self.registry = pjson.registry || globalConfig.config.registry;
    self.dependencies = {};
    // only read dependencies when combined with a registry property
    self.dependencies = processDeps(pjson.dependencies, self.registry);

    defaults.baseURL = self.dir;
    self.baseURL = pjson.directories && pjson.directories.baseURL && path.resolve(self.dir, pjson.directories.baseURL) || defaults.baseURL;

    defaults.lib = path.resolve(self.baseURL, '.');
    defaults.dist = path.resolve(self.baseURL, 'dist');
    defaults.packages = path.resolve(self.baseURL, 'jspm_packages');

    defaults.main = defaults.lib + '/index';
    self.main = pjson.main || defaults.main;

    self.lib = pjson.directories && pjson.directories.lib && path.resolve(self.dir, pjson.directories.lib) || defaults.lib;
    self.dist = pjson.directories && pjson.directories.dist && path.resolve(self.dir, pjson.directories.dist) || defaults.dist;
    // NB can remove jspmPackages suport in time
    self.packages = pjson.directories && pjson.directories.packages && path.resolve(self.dir, pjson.directories.packages)
      || pjson.directories && pjson.directories.jspmPackages && path.resolve(self.dir, pjson.directories.jspmPackages) || defaults.packages;

    defaults.configFile = path.resolve(self.baseURL, 'config.js');
    self.configFile = pjson.configFile && path.resolve(self.dir, pjson.configFile) || defaults.configFile;

    self.format = pjson.format;
    self.map = extend({}, pjson.map || {});

    // NB remove when nodelibs no longer built this way
    self.useJSExtensions = pjson.useJSExtensions;

    self.buildConfig = extend({}, pjson.buildConfig || {});

    return prompts;
  });
}

PackageJSON.prototype.write = function() {
  var pjson = this.jspmPrefix ? {} : this.originalPjson;

  if (!this.jspmPrefix) {
    delete pjson.jspm;
    pjson.registry = this.registry || globalConfig.config.registry;
  }
  else if (this.registry != 'jspm') {
    pjson.registry = this.registry;
  }

  var defaults = this.defaults;

  // only set properties that differ from the defaults
  if (this.name != defaults.name)
    pjson.name = this.name;
  if (this.main != defaults.main)
    pjson.main = this.main;

  if (this.format)
    pjson.format = this.format;

  var directories = {};
  if (this.baseURL != defaults.baseURL)
    directories.baseURL = this.baseURL;
  if (this.lib != defaults.lib)
    directories.lib = this.lib;
  if (this.dist != defaults.dist)
    directories.dist = this.dist;
  if (this.packages != defaults.packages)
    directories.packages = this.packages;

  if (hasProperties(directories)) {
    for (var d in directories) {
      directories[d] = winPath(path.relative(this.dir, directories[d]));
      if (!directories[d])
        directories[d] = '.';
    }
    pjson.directories = extend(pjson.directories || {}, directories);
    pjson.directories = alphabetize(pjson.directories);
  }

  if (this.configFile != defaults.configFile)
    pjson.configFile = winPath(path.relative(this.dir, this.configFile));

  pjson.map = alphabetize(this.map);
  if (!hasProperties(pjson.map))
    delete pjson.map;

  pjson.dependencies = {};
  var depValue;
  for (var d in this.dependencies) {
    var dep = this.dependencies[d];
    if (!dep)
      continue;
    if (dep.endpoint == 'jspm') {
      if (d == dep.package)
        depValue = dep.version;
      else
        depValue = dep.exactPackage;
    }
    // name is exactly as in registry
    else if (registryCache[d] == dep.name)
        depValue = dep.version;
    else
      depValue = dep.exactName;

    pjson.dependencies[d] = depValue;
  }
  pjson.dependencies = alphabetize(pjson.dependencies);
  if (!hasProperties(pjson.dependencies))
    delete pjson.dependencies;

  pjson.buildConfig = this.buildConfig;
  if (!hasProperties(pjson.buildConfig))
    delete pjson.buildConfig;

  // dedupe jspm properties against base properties
  if (this.jspmPrefix) {
    for (var p in pjson) {
      if (this.originalPjson[p] === pjson[p])
        delete pjson[p];
    }
    this.originalPjson.jspm = pjson;
  }

  // NB check that the file hasn't changed since we opened it and if so, prompt
  return asp(fs.writeFile)(this.fileName, JSON.stringify(this.originalPjson, null, 2) + '\n');
}

// can take an existing non-jspm package.json
function doInitPrompts(pjson, pjsonPath, prefixed) {
  var baseDir = path.dirname(pjsonPath);
  var base;

  pjson.directories = pjson.directories || {};

  return Promise.resolve()
  .then(function() {
    return ui.confirm('Would you like jspm to prefix the jspm package.json properties under %jspm%?', prefixed);
  })
  .then(function(prefix) {
    prefixed = prefix;
    return ui.input('Enter the package name for the project', pjson.name);
  })
  .then(function(name) {
    pjson.name = name;
    return ui.input('Enter server baseURL (public folder path)', pjson.directories.baseURL || './');
  })
  .then(function(baseURL) {
    base = path.relative(process.cwd(), path.resolve(baseURL));
    baseURL = path.relative(baseDir, path.resolve(baseURL));
    if (!base)
      base = '.';
    base += path.sep;
    if (baseURL)
      pjson.directories.baseURL = baseURL;
    return ui.input('Enter project code folder', pjson.directories.lib || base);
  })
  .then(function(lib) {
    pjson.directories.lib = path.relative(baseDir, path.resolve(lib));
    if (!pjson.directories.lib)
      pjson.directories.lib = '.';
    return ui.input('Enter jspm packages folder', pjson.directories.packages || base + 'jspm_packages');
  })
  .then(function(packages) {
    pjson.directories.packages = path.relative(baseDir, path.resolve(packages));
    return ui.input('Enter config file path', pjson.configFile || base + 'config.js');
  })
  .then(function(configFile) {
    pjson.configFile = path.relative(baseDir, path.resolve(configFile))
    return prefixed;
  });
}

module.exports = PackageJSON;
<|endoftext|>