<commit_before>(function ($, Backbone, _) {

    var Upload = Backbone.Model.extend({
        url: function () {
            var links = this.get('links'),
                url = links && links.self;
            if (!url) {
                url = Backbone.Model.prototype.url.call(this);
            }
            return url;
        },
        idAttribute: 'name'
    });

    var UploadCollection = Backbone.Collection.extend({
        model: Upload,
        url: '/uploads/',
        parse: function (response) {
            this._count = response.count;
            return response.files || [];
        }
    });

    var uploads = new UploadCollection();

    var UploadView = Backbone.View.extend({
        className: 'file',
        template: _.template('<%- name %> X'),
        events: {
            'click .delete': 'delete'
        },
        initialize: function() {
            this.listenTo(this.model, 'change', this.render);
            this.listenTo(this.model, 'destroy', this.remove);
        },
        render: function () {
            this.$el.html(this.template(this.model.toJSON()));
        },
        delete: function (e) {
            e.preventDefault();
            this.model.destroy();
        }
    });

    var UploadListingView = Backbone.View.extend({
        el: '#files',
        render: function () {
            this.$el.show();
        },
        addFile: function (file) {
            var view = new UploadView({model: file});
            this.$el.append(view.$el);
            view.render();
        }
    });

    var listView = new UploadListingView();
    uploads.on('add', listView.addFile, listView);
    uploads.fetch();
    listView.render();

})(jQuery, Backbone, _);
<commit_msg>New view to handle the drag and drop to upload new files to the API.<commit_after>(function ($, Backbone, _) {

    var Upload = Backbone.Model.extend({
        url: function () {
            var links = this.get('links'),
                url = links && links.self;
            if (!url) {
                url = Backbone.Model.prototype.url.call(this);
            }
            return url;
        },
        idAttribute: 'name'
    });

    var UploadCollection = Backbone.Collection.extend({
        model: Upload,
        url: '/uploads/',
        parse: function (response) {
            this._count = response.count;
            return response.files || [];
        }
    });

    var uploads = new UploadCollection();

    var UploadView = Backbone.View.extend({
        className: 'file',
        template: _.template('<%- name %> X'),
        events: {
            'click .delete': 'delete'
        },
        initialize: function() {
            this.listenTo(this.model, 'change', this.render);
            this.listenTo(this.model, 'destroy', this.remove);
        },
        render: function () {
            this.$el.html(this.template(this.model.toJSON()));
        },
        delete: function (e) {
            e.preventDefault();
            this.model.destroy();
        }
    });

    var UploadListingView = Backbone.View.extend({
        el: '#files',
        render: function () {
            this.$el.show();
        },
        addFile: function (file) {
            var view = new UploadView({model: file});
            this.$el.append(view.$el);
            view.render();
        }
    });

    var NewUploadView = Backbone.View.extend({
        el: '#upload',
        events: {
            'dragenter': 'enter',
            'dragover': 'over',
            'dragend': 'end',
            'dragleave': 'end',
            'drop': 'drop'
        },
        enter: function (e) {
            e.stopPropagation();
            e.preventDefault();
            this.$el.addClass('hover');
            return false;
        },
        over: function (e) {
            e.stopPropagation();
            e.preventDefault();
            this.$el.addClass('hover');
            return false;
        },
        end: function (e) {
            this.$el.removeClass('hover');
        },
        drop: function (e) {
            var formData = new FormData(),
                file;
            e.stopPropagation();
            e.preventDefault();
            if (e.originalEvent.dataTransfer.files.length === 0) {
                return;
            }
            file = e.originalEvent.dataTransfer.files[0];
            formData.append('name', file);
            uploads.create({}, {
                error: $.proxy(this.fail, this),
                wait: true,
                data: formData,
                processData: false,
                contentType: false
            });
            this.end();
        },
        fail: function (_model, response) {
            var errors = response.responseJSON.name,
                errorTemplate = _.template('<p class="error error-<%- code %>"><%- message %>
');
            _.map(errors, function (error) {
                this.$el.before(errorTemplate(error));
            }, this);
            setTimeout($.proxy(function() {
                var errors = $('.error');
                errors.fadeOut('slow', function () {
                    errors.remove();
                });
            }, this), 2500);
        },
        render: function () {
            this.$el.show();
        }
    });

    var listView = new UploadListingView(),
        newView = new NewUploadView();

    uploads.on('add', listView.addFile, listView);
    uploads.fetch();
    listView.render();
    newView.render();

})(jQuery, Backbone, _);
<|endoftext|>


<commit_before>import { pageView } from '../view/page-viewer.js';
import { userModel } from '../models/user-model.js';
import { notificator } from '../helpers/notificator.js';

const STORAGE_USERNAME_IMAGE = 'STORAGE_USERNAME_IMAGE';
const FACEBOOK_USER = 'FACEBOOK_USER';

let userEvents = (function() {

    function showProfile() {
        $('#main-content').addClass('logged-in');
        $('#nav-collapse2').removeClass('in')
        $('#profile-show-hide').removeClass('hidden');
    }

    function hideProfile() {
        $('#main-content').removeClass('logged-in');
        $('#profile-show-hide').addClass('hidden');
    }

    function editProfile() {
        $('#main-content').on('click', '#edit-profile-button', function() {
            $("#user-ready-data").addClass("hidden");
            $("#user-changing-data").removeClass("hidden");
        });
    }

    function updateProfile() {
        $('#main-content').on('click', '#save-profile-changes-btn', function() {
            //update the profile data and display it
            let data = {
                "firstname": $("#textinputFirstname").val(),
                "lastname": $("#textinputLastname").val(),
                "gender": $("#selectbasic option:selected").html(),
                "phone": $("#textinputPhone").val(),
                "address": $("#textinputAddress").val(),
                "image": $("#textinputPhotolink").val(),
                "email": $("#textinputE-mail").val()
            }

            $('#set-image').attr("src", data.image);
            $('#set-firstname').html(data.firstname);
            $('#set-lastname').html(data.lastname);
            $('#set-email').html(data.email);
            $('#set-gender').html(data.gender);
            $('#set-address').html(data.address);
            $('#set-phone').html(data.phone);

            $("#user-ready-data").removeClass("hidden");
            $("#user-changing-data").addClass("hidden");
            notificator.success('Profile Successfully Updated');
            userModel.updateProfile(data);
        });
    }

    function cancelEditProfile() {
        $('#main-content').on('click', '#cancel-profile-changes-btn', function() {
            //cancel any changes
            $("#user-ready-data").removeClass("hidden");
            $("#user-changing-data").addClass("hidden");
            notificator.error('All Changes Canceled');
        });
    }

    function updateDataProfile(res) {
        return {
            username: res.username,
            phone: res.phone,
            address: res.address,
            gender: res.gender,
            email: res.email,
            lastname: res.lastname,
            firstname: res.firstname,
            image: res.image || localStorage.getItem(STORAGE_USERNAME_IMAGE)
        }
    }

    function facebookProfile() {
        return {
            username: localStorage.getItem("first_name", response.first_name) + " " + localStorage.getItem("last_name", response.last_name),
            gender: localStorage.getItem("gender", response.gender),
            lastname: localStorage.getItem("last_name", response.last_name),
            firstname: localStorage.getItem("first_name", response.first_name),
            image: localStorage.getItem("image", response.picture.data.url) || localStorage.getItem(STORAGE_USERNAME_IMAGE)
        }
    }
    return {
        showProfile,
        hideProfile,
        editProfile,
        updateProfile,
        updateDataProfile,
        cancelEditProfile,
        facebookProfile
    }
})();

export { userEvents }<commit_msg>fixed promise of data response<commit_after>import { pageView } from '../view/page-viewer.js';
import { userModel } from '../models/user-model.js';
import { notificator } from '../helpers/notificator.js';

const STORAGE_USERNAME_IMAGE = 'STORAGE_USERNAME_IMAGE';
const FACEBOOK_USER = 'FACEBOOK_USER';

let userEvents = (function() {

    function showProfile() {
        $('#main-content').addClass('logged-in');
        $('#nav-collapse2').removeClass('in')
        $('#profile-show-hide').removeClass('hidden');
    }

    function hideProfile() {
        $('#main-content').removeClass('logged-in');
        $('#profile-show-hide').addClass('hidden');
    }

    function editProfile() {
        $('#main-content').on('click', '#edit-profile-button', function() {
            $("#user-ready-data").addClass("hidden");
            $("#user-changing-data").removeClass("hidden");
        });
    }

    function updateProfile() {
        $('#main-content').on('click', '#save-profile-changes-btn', function() {
            //update the profile data and display it
            let data = {
                "firstname": $("#textinputFirstname").val(),
                "lastname": $("#textinputLastname").val(),
                "gender": $("#selectbasic option:selected").html(),
                "phone": $("#textinputPhone").val(),
                "address": $("#textinputAddress").val(),
                "image": $("#textinputPhotolink").val(),
                "email": $("#textinputE-mail").val()
            }

            $('#set-image').attr("src", data.image);
            $('#set-firstname').html(data.firstname);
            $('#set-lastname').html(data.lastname);
            $('#set-email').html(data.email);
            $('#set-gender').html(data.gender);
            $('#set-address').html(data.address);
            $('#set-phone').html(data.phone);

            $("#user-ready-data").removeClass("hidden");
            $("#user-changing-data").addClass("hidden");
            notificator.success('Profile Successfully Updated');
            userModel.updateProfile(data);
        });
    }

    function cancelEditProfile() {
        $('#main-content').on('click', '#cancel-profile-changes-btn', function() {
            //cancel any changes
            $("#user-ready-data").removeClass("hidden");
            $("#user-changing-data").addClass("hidden");
            notificator.error('All Changes Canceled');
        });
    }

    function updateDataProfile(res) {
        return {
            username: res.username,
            phone: res.phone,
            address: res.address,
            gender: res.gender,
            email: res.email,
            lastname: res.lastname,
            firstname: res.firstname,
            image: res.image || localStorage.getItem(STORAGE_USERNAME_IMAGE)
        }
    }

    function facebookProfile() {
        return {
            username: localStorage.getItem("first_name") + " " + localStorage.getItem("last_name"),
            gender: localStorage.getItem("gender"),
            lastname: localStorage.getItem("last_name"),
            firstname: localStorage.getItem("first_name"),
            image: localStorage.getItem("image") || localStorage.getItem(STORAGE_USERNAME_IMAGE)
        }
    }
    return {
        showProfile,
        hideProfile,
        editProfile,
        updateProfile,
        updateDataProfile,
        cancelEditProfile,
        facebookProfile
    }
})();

export { userEvents }<|endoftext|>


<commit_before>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/

/*
 * Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

var fs = require("fs");
var glob = require("glob");
var path = require('path');
var url = require('url');
var async = require('async');
var Properties = require("../util/properties");
var log4js = require("log4js");
var LibManager = require('../util/libmanager');
var FileUtil = require("../util/fileutil");
var ErrorManager = require("../util/errormanager");
var PhantomJsSetup = require("./phantomJsSetup.js");
var Servermanager = require("../../arrow_server/arrowservermanager.js");

function ArrowSetup(config, argv) {
    var __dirname = global.appRoot;
    this.config = config;
    this.argv = argv;
}

ArrowSetup.prototype.setup = function (callback) {
    var self = this;

    async.series(
        [
            function(cb) {
                self.setuplog4js(function() {
                    return cb(null, 'setuplog4js');
                });
            },

            function(cb) {
                self.setupReportDir(function() {
                    return cb(null, 'setupReportDir');
                });
            },

            function(cb) {
                self.setupDefaultDriverName(function() {
                    return cb(null, 'setupDefaultDriverName');
                });
            },

            function(cb) {
                self.setupTestEngine(function() {
                    return cb(null, 'setupTestEngine');
                });
            },

            function(cb) {
                self.setupDefaultLib(function() {
                    return cb(null, 'setupDefaultLib');
                });
            },

            function(cb) {
                self.setupHeadlessParam(function() {
                    return cb(null, 'setupHeadlessParam');
                });
            },

            function(cb) {
                self.setupCapabilities(function() {
                    return cb(null, 'setupCapabilities');
                });
            },

            function(cb) {
                self.setupMisc(function() {
                    return cb(null, 'setupMisc');
                });
            },

            function(cb) {
                self.setupReplaceParam(function() {
                    return cb(null, 'setupReplaceParam');
                });
            },

            function(cb) {
                self.setupDefaultParam(function() {
                    return cb(null, 'setupDefaultParam');
                });
            },

            function(cb) {
                self.startPhantomJs(function() {
                    return cb(null, 'startPhantomJs');
                });
            },

            function(cb) {
                self.startArrowServer(function() {
                    return cb(null, 'startArrowServer');
                });
            },

            function(cb) {
                self.errorCheck(function() {
                    return cb(null, 'errorCheck');
                });
            },

            function(cb) {
                self.setupUseSSL(function() {
                    return cb(null, 'errorCheck');
                });
            }

        ],
        function(err, results) {
            callback();
        }
    );

};

ArrowSetup.prototype.setupUseSSL = function (cb) {
    var self = this;
    self.logger.trace('setupUseSSL starts');
    if (this.argv.useSSL){
        this.config.useSSL = this.argv.useSSL;
    }
    self.logger.trace('setupUseSSL ends');
    if (cb) {
        cb();
    }
};

ArrowSetup.prototype.setupReplaceParam = function (cb) {

    var self = this;
    self.logger.trace('setupReplaceParam starts');
    if (this.argv.replaceParamJSON) {
        this.config.replaceParamJSON = this.argv.replaceParamJSON;
    }
    self.logger.trace('setupReplaceParam ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupDefaultParam = function (cb) {

    var self = this;
    self.logger.trace('setupDefaultParam starts');
    if (this.argv.defaultParamJSON) {
        this.config.defaultParamJSON = this.argv.defaultParamJSON;
    }
    self.logger.trace('setupDefaultParam ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.errorCheck = function (cb) {

    var self = this, em = ErrorManager.getInstance(),
        environment = function() {
            if (self.argv.argv.cooked) {
                // em.errorLog("self.argv.argv.cooked {0}",  JSON.stringify(self.argv.argv.cooked));
                var cooked = JSON.stringify(self.argv.argv.cooked), proc = self.mock || process;
                cooked.replace(/"--context","([\w\W]*?)"/, function (match, context) {
                    // em.errorLog("match is {0}, context is {1}", match, context);
                    context.replace(/environment:([\w\W]*)/, function (match, env) {
                        // em.errorLog("match is {0}, env is {1}", match, env);
                        if (self.dimensions[0].environment[env] === undefined) {
                            em.errorLog(1000, env, self.dimensionsFile);
                            proc.exit(1);
                        } else {
                            self.environment = env;
                        }
                    });
                });
            }
        },
        dimensions = function() {
            // To Do : should check dimensions file with Json schema
            // em.errorLog("config {0} argv {1}", JSON.stringify(self.config), JSON.stringify(self.argv));
            var dimensions = self.argv.dimensions || self.config.dimensions || "", dimJson, i = 0, proc = self.mock || process,
                errorMessage, argv = self.argv.argv || {}, remain = JSON.stringify(argv.remain) || "",
                dimensionsExist = function () {
                    return remain.match(/"[\w\W]*\.json"/) && dimensions.length > 0;
                };

            if (dimensionsExist()) {
                try {
                    self.dimensionsFile = dimensions;
                    dimJson = JSON.parse(fs.readFileSync(dimensions, "utf-8"));
                } catch (e) {
                    errorMessage = e.message;
                }
                if (dimJson && dimJson.length > 0 && dimJson[i].dimensions) {
                    self.dimensions = dimJson[i].dimensions;
                    // em.errorLog("dimensions {0}", JSON.stringify(self.dimensions));
                } else {
                    em.errorLog(1001, dimensions, errorMessage || JSON.stringify(dimJson));
                    proc.exit(1);
                }
                environment();
            }
        },
        invalidArgument = function() {
            var argv = self.argv, arg, value, isNotValid = false, proc = self.mock || process,
                mandatory = { "seleniumHost" : true };
            for (arg in argv) {
                if (mandatory[arg] === undefined || !mandatory[arg]) {
                    continue;
                }
                value = argv[arg];
                if (value === null || value === "null") {
                    em.errorLog(1006, arg, "null");
                    isNotValid = true;
                } else if (value === '') {
                    em.errorLog(1006, arg, "empty string");
                    isNotValid = true;
                } else if (value === undefined) {
                    em.errorLog(1006, arg, "undefined");
                    isNotValid = true;
                }
            }
            if (isNotValid) {
                proc.exit(1);
            }
            dimensions();
        };

    em.logger = self.mock || em.logger;
    invalidArgument();
    self.logger.trace('errorCheck ends..' + cb);
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupReportDir = function (cb) {

    var self = this,
        artifactsUrl,
        arrowTargetDir = 'arrow-target',
        arrowReportDir = 'arrow-report',
        fileUtil = new FileUtil(),
        targetFolderRelPath, // relative path till target directory
        targetFolderPath, // path till target directory
        reportFolderPath,
        reportFolder = "";

    self.logger.trace('setupReportDir starts');
    global.reportFolder = "";

    if (this.argv.artifactsUrl) {
        artifactsUrl = this.argv.artifactsUrl;
    }
    console.log('****Setup report dir, artifactsUrl:' + artifactsUrl);
    // To generate the reports, if either report is true or reportFolder is passed
    if (this.argv.reportFolder) {
        reportFolder = this.argv.reportFolder;
    }
    targetFolderRelPath = path.join(reportFolder,arrowTargetDir); // Relative path to target directory
    targetFolderPath =  path.resolve(global.workingDirectory, targetFolderRelPath); // Absolute path to target directory
    console.log('****Setup report dir, targetFolderRelPath:' + targetFolderRelPath + ',targetFolderPath:' + targetFolderPath);
    // Cleanup report folder if keepTestReport set to false or undefined
    if (this.argv.keepTestReport === undefined || false === this.argv.keepTestReport) {
        fileUtil.removeDirectory(targetFolderPath);
    }

    if (this.argv.report || this.argv.reportFolder) {
        // Get path till arrow-report directory
//        reportFolderPath = path.resolve(targetFolderPath, arrowReportDir);
        reportFolderPath = path.join(targetFolderPath, arrowReportDir);
        // Create arrow-report directory
        fileUtil.createDirectory(reportFolderPath);

        this.argv.reportFolder = targetFolderPath;
        global.reportFolder = this.argv.reportFolder || "";

    }
    if (artifactsUrl) {
        console.log('****Setup report dir, artifactsUrl:' + artifactsUrl);
        artifactsUrl = url.resolve(artifactsUrl , targetFolderRelPath);
        console.log('****Setup report dir, after resolving:' + artifactsUrl);
        global.artifactsUrl = artifactsUrl;
    }
    self.logger.trace('setupReportDir ends');

    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupMisc = function (cb) {

    var self = this;
    self.logger.trace('setupMisc starts');
    if (this.argv.coverage !== undefined) {
        this.config.coverage = this.argv.coverage;
    }

    if (this.argv.report === undefined && this.config.report) {
        this.argv.report = this.config.report;
    }

    if (this.argv.dimensions) {
        this.argv.dimensions = path.resolve(global.workingDirectory, this.argv.dimensions);
        this.config.dimensions = this.argv.dimensions;
    }
    self.logger.trace('setupMisc ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setuplog4js = function (cb) {

    var logLevel;
    logLevel = this.config["logLevel"];
    log4js.setGlobalLogLevel(logLevel);
    log4js.restoreConsole();
    this.logger = log4js.getLogger("ArrowSetup");
    this.logger.trace('setuplog4js ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupDefaultDriverName = function (cb) {

    var self = this;
    self.logger.trace('setupDefaultDriverName starts');
    // turn on reuseSession, if browser is being reused
    // adding support for "reuse-" too, just in case if a null version is passed with browser.
    if ("reuse" === this.argv.browser || "reuse-" === this.argv.browser) {
        this.argv.reuseSession = true;

        if (!this.argv.driver) {
            this.argv.driver = "selenium";
        }
        delete this.argv.browser;
    }

    // setup the selenium host using the auto hookup if possible
    this.setupSeleniumHost(function() {
        self.logger.trace('setupDefaultDriverName ends');
        if (cb) {
            cb();
        }

    });

};

ArrowSetup.prototype.setupSeleniumHost = function (cb) {

    var self = this;
    self.logger.trace('In setupSeleniumHost starts');
    var wdHubHost,
        wdStatusFile = "/tmp/arrow_sel_server.status";

    // setup the selenium host using the auto hookup if possible
    wdHubHost = this.config["seleniumHost"];
    if (0 === wdHubHost.length) {
        // check if we have a hooked up server
        try {
            fs.statSync(wdStatusFile).isFile();
            wdHubHost = fs.readFileSync(wdStatusFile, "utf-8");
        } catch (ex) {
        }

        // final default
        if (wdHubHost.length === 0) {
            wdHubHost = "http://localhost:4444/wd/hub";
        }
        this.config["seleniumHost"] = wdHubHost;
        self.logger.trace('setupSeleniumHost ends');
        if (cb) {
            cb();
        }

    } else {
        self.logger.trace('setupSeleniumHost ends');
        if (cb) {
            cb();
        }

    }

};

ArrowSetup.prototype.setupDefaultLib = function (cb) {

    var self = this;
    self.logger.trace('setupDefaultLib starts');
    this.argv.lib = new LibManager().getAllCommonLib(this.config, this.config.lib);
    this.logger.debug("Commandline + Common Libs for Test :" + this.config.lib);
    self.logger.trace('setupDefaultLib ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupHeadlessParam = function (cb) {

    var self = this,
        hd,
        results,
        ext;

    self.logger.trace('setupHeadlessParam starts');

    if (!this.argv.argv.remain[0]) {
        self.logger.trace('setupHeadlessParam ends');
        if (cb) {
            cb();
        }

    }

    hd = this.argv.argv.remain[0];

    results = glob.sync(hd);
    this.logger.info("Glob result: " + results);

    if (0 === results.length) {
        this.logger.error("ERROR : No Test or Descriptor Found, while looking for : " + hd);
        process.exit(1);
    }

    ext = path.extname(results[0]);
    // check the first file to determine the type
    if (".json" === ext) {
        this.config.arrDescriptor = results;
    } else if ((".js" === ext) || (".html" === ext)) {
        if (results.length > 1) {
            this.argv.tests = results;
        } else {
            this.argv.test = results[0];
        }
    } else {
        this.logger.fatal("Unknown test file type " + results[0]);
        process.exit(0);
    }
    self.logger.trace('setupHeadlessParam ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupCapabilities = function (cb) {

    var self = this;
    self.logger.trace('setupCapabilities starts');
    if (this.argv.capabilities) {
        this.config.capabilities = this.argv.capabilities;
    }
    self.logger.trace('setupCapabilities ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupTestEngine = function (cb) {

    var self = this;
    self.logger.trace('setupTestEngine starts');
    this.config.engine = "yui";
    if (this.argv.engine) {
        this.config.engine = this.argv.engine;
    }
    if (this.argv.engineConfig) {
        try {
            this.config.engineConfig = this.argv.engineConfig;
            if (fs.statSync(this.argv.engineConfig).isFile()) {
                //get absolute path before chdir
                this.config.engineConfig = path.resolve("", this.argv.engineConfig);
            }
            self.logger.trace('setupTestEngine ends');
            if (cb) {
                cb();
            }

        } catch (e) {
            self.logger.trace('setupTestEngine ends');
            if (cb) {
                cb();
            }

        }
    } else {
        self.logger.trace('setupTestEngine ends');
        if (cb) {
            cb();
        }

    }

};

ArrowSetup.prototype.startArrowServer = function(cb) {

    var self = this;
    self.logger.trace('startArrowServer starts');
    if (this.config.startArrowServer) {
        Servermanager.startArrowServer(function(arrowServerStarted) {
            if (arrowServerStarted === false) {
                self.logger.info('Failed to start Arrow Server. Exiting !!!');
                process.exit(1);
            }
            self.logger.trace('startArrowServer ends');
            if (cb) {
                cb();
            }

        });
    } else {
        self.logger.trace('startArrowServer ends');
        if (cb) {
            cb();
        }

    }

};

ArrowSetup.prototype.startPhantomJs = function(cb) {

    var self = this;
    self.logger.trace('startPhantomJs starts');

    if (this.config.startPhantomJs) {

        PhantomJsSetup.startPhantomJs(self.config.ignoreSslErrorsPhantomJs, function(phantomHost) {
            self.logger.trace('startPhantomJs ends..' + phantomHost);

            if (!phantomHost) {
                self.logger.info('Could not start phantomjs. Exiting.');
                process.exit(1);
            }

            self.config["phantomHost"] = phantomHost;
            if (cb) {
                cb();
            }
        });
    } else if (cb) {
        self.logger.trace('startPhantomJs ends');
        cb();
    }

};

module.exports = ArrowSetup;<commit_msg>Fixing path for artifactsUrl<commit_after>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/

/*
 * Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

var fs = require("fs");
var glob = require("glob");
var path = require('path');
var url = require('url');
var async = require('async');
var Properties = require("../util/properties");
var log4js = require("log4js");
var LibManager = require('../util/libmanager');
var FileUtil = require("../util/fileutil");
var ErrorManager = require("../util/errormanager");
var PhantomJsSetup = require("./phantomJsSetup.js");
var Servermanager = require("../../arrow_server/arrowservermanager.js");

function ArrowSetup(config, argv) {
    var __dirname = global.appRoot;
    this.config = config;
    this.argv = argv;
}

ArrowSetup.prototype.setup = function (callback) {
    var self = this;

    async.series(
        [
            function(cb) {
                self.setuplog4js(function() {
                    return cb(null, 'setuplog4js');
                });
            },

            function(cb) {
                self.setupReportDir(function() {
                    return cb(null, 'setupReportDir');
                });
            },

            function(cb) {
                self.setupDefaultDriverName(function() {
                    return cb(null, 'setupDefaultDriverName');
                });
            },

            function(cb) {
                self.setupTestEngine(function() {
                    return cb(null, 'setupTestEngine');
                });
            },

            function(cb) {
                self.setupDefaultLib(function() {
                    return cb(null, 'setupDefaultLib');
                });
            },

            function(cb) {
                self.setupHeadlessParam(function() {
                    return cb(null, 'setupHeadlessParam');
                });
            },

            function(cb) {
                self.setupCapabilities(function() {
                    return cb(null, 'setupCapabilities');
                });
            },

            function(cb) {
                self.setupMisc(function() {
                    return cb(null, 'setupMisc');
                });
            },

            function(cb) {
                self.setupReplaceParam(function() {
                    return cb(null, 'setupReplaceParam');
                });
            },

            function(cb) {
                self.setupDefaultParam(function() {
                    return cb(null, 'setupDefaultParam');
                });
            },

            function(cb) {
                self.startPhantomJs(function() {
                    return cb(null, 'startPhantomJs');
                });
            },

            function(cb) {
                self.startArrowServer(function() {
                    return cb(null, 'startArrowServer');
                });
            },

            function(cb) {
                self.errorCheck(function() {
                    return cb(null, 'errorCheck');
                });
            },

            function(cb) {
                self.setupUseSSL(function() {
                    return cb(null, 'errorCheck');
                });
            }

        ],
        function(err, results) {
            callback();
        }
    );

};

ArrowSetup.prototype.setupUseSSL = function (cb) {
    var self = this;
    self.logger.trace('setupUseSSL starts');
    if (this.argv.useSSL){
        this.config.useSSL = this.argv.useSSL;
    }
    self.logger.trace('setupUseSSL ends');
    if (cb) {
        cb();
    }
};

ArrowSetup.prototype.setupReplaceParam = function (cb) {

    var self = this;
    self.logger.trace('setupReplaceParam starts');
    if (this.argv.replaceParamJSON) {
        this.config.replaceParamJSON = this.argv.replaceParamJSON;
    }
    self.logger.trace('setupReplaceParam ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupDefaultParam = function (cb) {

    var self = this;
    self.logger.trace('setupDefaultParam starts');
    if (this.argv.defaultParamJSON) {
        this.config.defaultParamJSON = this.argv.defaultParamJSON;
    }
    self.logger.trace('setupDefaultParam ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.errorCheck = function (cb) {

    var self = this, em = ErrorManager.getInstance(),
        environment = function() {
            if (self.argv.argv.cooked) {
                // em.errorLog("self.argv.argv.cooked {0}",  JSON.stringify(self.argv.argv.cooked));
                var cooked = JSON.stringify(self.argv.argv.cooked), proc = self.mock || process;
                cooked.replace(/"--context","([\w\W]*?)"/, function (match, context) {
                    // em.errorLog("match is {0}, context is {1}", match, context);
                    context.replace(/environment:([\w\W]*)/, function (match, env) {
                        // em.errorLog("match is {0}, env is {1}", match, env);
                        if (self.dimensions[0].environment[env] === undefined) {
                            em.errorLog(1000, env, self.dimensionsFile);
                            proc.exit(1);
                        } else {
                            self.environment = env;
                        }
                    });
                });
            }
        },
        dimensions = function() {
            // To Do : should check dimensions file with Json schema
            // em.errorLog("config {0} argv {1}", JSON.stringify(self.config), JSON.stringify(self.argv));
            var dimensions = self.argv.dimensions || self.config.dimensions || "", dimJson, i = 0, proc = self.mock || process,
                errorMessage, argv = self.argv.argv || {}, remain = JSON.stringify(argv.remain) || "",
                dimensionsExist = function () {
                    return remain.match(/"[\w\W]*\.json"/) && dimensions.length > 0;
                };

            if (dimensionsExist()) {
                try {
                    self.dimensionsFile = dimensions;
                    dimJson = JSON.parse(fs.readFileSync(dimensions, "utf-8"));
                } catch (e) {
                    errorMessage = e.message;
                }
                if (dimJson && dimJson.length > 0 && dimJson[i].dimensions) {
                    self.dimensions = dimJson[i].dimensions;
                    // em.errorLog("dimensions {0}", JSON.stringify(self.dimensions));
                } else {
                    em.errorLog(1001, dimensions, errorMessage || JSON.stringify(dimJson));
                    proc.exit(1);
                }
                environment();
            }
        },
        invalidArgument = function() {
            var argv = self.argv, arg, value, isNotValid = false, proc = self.mock || process,
                mandatory = { "seleniumHost" : true };
            for (arg in argv) {
                if (mandatory[arg] === undefined || !mandatory[arg]) {
                    continue;
                }
                value = argv[arg];
                if (value === null || value === "null") {
                    em.errorLog(1006, arg, "null");
                    isNotValid = true;
                } else if (value === '') {
                    em.errorLog(1006, arg, "empty string");
                    isNotValid = true;
                } else if (value === undefined) {
                    em.errorLog(1006, arg, "undefined");
                    isNotValid = true;
                }
            }
            if (isNotValid) {
                proc.exit(1);
            }
            dimensions();
        };

    em.logger = self.mock || em.logger;
    invalidArgument();
    self.logger.trace('errorCheck ends..' + cb);
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupReportDir = function (cb) {

    var self = this,
        artifactsUrl,
        arrowTargetDir = 'arrow-target',
        arrowReportDir = 'arrow-report',
        fileUtil = new FileUtil(),
        targetFolderRelPath, // relative path till target directory
        targetFolderPath, // path till target directory
        reportFolderPath,
        reportFolder = "";

    self.logger.trace('setupReportDir starts');
    global.reportFolder = "";

    if (this.argv.artifactsUrl) {
        artifactsUrl = this.argv.artifactsUrl;
    }
    console.log('****Setup report dir, artifactsUrl:' + artifactsUrl);
    // To generate the reports, if either report is true or reportFolder is passed
    if (this.argv.reportFolder) {
        reportFolder = this.argv.reportFolder;
    }
    targetFolderRelPath = path.join(reportFolder,arrowTargetDir); // Relative path to target directory
    targetFolderPath =  path.resolve(global.workingDirectory, targetFolderRelPath); // Absolute path to target directory
    console.log('****Setup report dir, targetFolderRelPath:' + targetFolderRelPath + ',targetFolderPath:' + targetFolderPath);
    // Cleanup report folder if keepTestReport set to false or undefined
    if (this.argv.keepTestReport === undefined || false === this.argv.keepTestReport) {
        fileUtil.removeDirectory(targetFolderPath);
    }

    if (this.argv.report || this.argv.reportFolder) {
        // Get path till arrow-report directory
        reportFolderPath = path.resolve(targetFolderPath, arrowReportDir);
        // Create arrow-report directory
        fileUtil.createDirectory(reportFolderPath);

        this.argv.reportFolder = targetFolderPath;
        global.reportFolder = this.argv.reportFolder || "";

    }
    if (artifactsUrl) {
        console.log('****Setup report dir, artifactsUrl:' + artifactsUrl);
        artifactsUrl = path.join(artifactsUrl , targetFolderRelPath);
        console.log('****Setup report dir, after resolving:' + artifactsUrl);
        global.artifactsUrl = artifactsUrl;
    }
    self.logger.trace('setupReportDir ends');

    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupMisc = function (cb) {

    var self = this;
    self.logger.trace('setupMisc starts');
    if (this.argv.coverage !== undefined) {
        this.config.coverage = this.argv.coverage;
    }

    if (this.argv.report === undefined && this.config.report) {
        this.argv.report = this.config.report;
    }

    if (this.argv.dimensions) {
        this.argv.dimensions = path.resolve(global.workingDirectory, this.argv.dimensions);
        this.config.dimensions = this.argv.dimensions;
    }
    self.logger.trace('setupMisc ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setuplog4js = function (cb) {

    var logLevel;
    logLevel = this.config["logLevel"];
    log4js.setGlobalLogLevel(logLevel);
    log4js.restoreConsole();
    this.logger = log4js.getLogger("ArrowSetup");
    this.logger.trace('setuplog4js ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupDefaultDriverName = function (cb) {

    var self = this;
    self.logger.trace('setupDefaultDriverName starts');
    // turn on reuseSession, if browser is being reused
    // adding support for "reuse-" too, just in case if a null version is passed with browser.
    if ("reuse" === this.argv.browser || "reuse-" === this.argv.browser) {
        this.argv.reuseSession = true;

        if (!this.argv.driver) {
            this.argv.driver = "selenium";
        }
        delete this.argv.browser;
    }

    // setup the selenium host using the auto hookup if possible
    this.setupSeleniumHost(function() {
        self.logger.trace('setupDefaultDriverName ends');
        if (cb) {
            cb();
        }

    });

};

ArrowSetup.prototype.setupSeleniumHost = function (cb) {

    var self = this;
    self.logger.trace('In setupSeleniumHost starts');
    var wdHubHost,
        wdStatusFile = "/tmp/arrow_sel_server.status";

    // setup the selenium host using the auto hookup if possible
    wdHubHost = this.config["seleniumHost"];
    if (0 === wdHubHost.length) {
        // check if we have a hooked up server
        try {
            fs.statSync(wdStatusFile).isFile();
            wdHubHost = fs.readFileSync(wdStatusFile, "utf-8");
        } catch (ex) {
        }

        // final default
        if (wdHubHost.length === 0) {
            wdHubHost = "http://localhost:4444/wd/hub";
        }
        this.config["seleniumHost"] = wdHubHost;
        self.logger.trace('setupSeleniumHost ends');
        if (cb) {
            cb();
        }

    } else {
        self.logger.trace('setupSeleniumHost ends');
        if (cb) {
            cb();
        }

    }

};

ArrowSetup.prototype.setupDefaultLib = function (cb) {

    var self = this;
    self.logger.trace('setupDefaultLib starts');
    this.argv.lib = new LibManager().getAllCommonLib(this.config, this.config.lib);
    this.logger.debug("Commandline + Common Libs for Test :" + this.config.lib);
    self.logger.trace('setupDefaultLib ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupHeadlessParam = function (cb) {

    var self = this,
        hd,
        results,
        ext;

    self.logger.trace('setupHeadlessParam starts');

    if (!this.argv.argv.remain[0]) {
        self.logger.trace('setupHeadlessParam ends');
        if (cb) {
            cb();
        }

    }

    hd = this.argv.argv.remain[0];

    results = glob.sync(hd);
    this.logger.info("Glob result: " + results);

    if (0 === results.length) {
        this.logger.error("ERROR : No Test or Descriptor Found, while looking for : " + hd);
        process.exit(1);
    }

    ext = path.extname(results[0]);
    // check the first file to determine the type
    if (".json" === ext) {
        this.config.arrDescriptor = results;
    } else if ((".js" === ext) || (".html" === ext)) {
        if (results.length > 1) {
            this.argv.tests = results;
        } else {
            this.argv.test = results[0];
        }
    } else {
        this.logger.fatal("Unknown test file type " + results[0]);
        process.exit(0);
    }
    self.logger.trace('setupHeadlessParam ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupCapabilities = function (cb) {

    var self = this;
    self.logger.trace('setupCapabilities starts');
    if (this.argv.capabilities) {
        this.config.capabilities = this.argv.capabilities;
    }
    self.logger.trace('setupCapabilities ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupTestEngine = function (cb) {

    var self = this;
    self.logger.trace('setupTestEngine starts');
    this.config.engine = "yui";
    if (this.argv.engine) {
        this.config.engine = this.argv.engine;
    }
    if (this.argv.engineConfig) {
        try {
            this.config.engineConfig = this.argv.engineConfig;
            if (fs.statSync(this.argv.engineConfig).isFile()) {
                //get absolute path before chdir
                this.config.engineConfig = path.resolve("", this.argv.engineConfig);
            }
            self.logger.trace('setupTestEngine ends');
            if (cb) {
                cb();
            }

        } catch (e) {
            self.logger.trace('setupTestEngine ends');
            if (cb) {
                cb();
            }

        }
    } else {
        self.logger.trace('setupTestEngine ends');
        if (cb) {
            cb();
        }

    }

};

ArrowSetup.prototype.startArrowServer = function(cb) {

    var self = this;
    self.logger.trace('startArrowServer starts');
    if (this.config.startArrowServer) {
        Servermanager.startArrowServer(function(arrowServerStarted) {
            if (arrowServerStarted === false) {
                self.logger.info('Failed to start Arrow Server. Exiting !!!');
                process.exit(1);
            }
            self.logger.trace('startArrowServer ends');
            if (cb) {
                cb();
            }

        });
    } else {
        self.logger.trace('startArrowServer ends');
        if (cb) {
            cb();
        }

    }

};

ArrowSetup.prototype.startPhantomJs = function(cb) {

    var self = this;
    self.logger.trace('startPhantomJs starts');

    if (this.config.startPhantomJs) {

        PhantomJsSetup.startPhantomJs(self.config.ignoreSslErrorsPhantomJs, function(phantomHost) {
            self.logger.trace('startPhantomJs ends..' + phantomHost);

            if (!phantomHost) {
                self.logger.info('Could not start phantomjs. Exiting.');
                process.exit(1);
            }

            self.config["phantomHost"] = phantomHost;
            if (cb) {
                cb();
            }
        });
    } else if (cb) {
        self.logger.trace('startPhantomJs ends');
        cb();
    }

};

module.exports = ArrowSetup;<|endoftext|>


<commit_before>iD.ui.SourceSwitch = function(context) {
    function click() {
        d3.event.preventDefault();

        var live = d3.select(this).classed('live');

        context.map()
            .flush();

        context.connection()
            .url(live ? 'http://api06.dev.openstreetmap.org' : 'http://www.openstreetmap.org');

        d3.select(this)
            .text(live ? t('source_switch.dev') : t('source_switch.live'))
            .classed('live', !live);
    }

    return function(selection) {
        selection.append('a')
            .attr('href', '#')
            .text(t('source_switch.dev'))
            .classed('live', false)
            .on('click', click);
    };
};
<commit_msg>flush map after changing connection url<commit_after>iD.ui.SourceSwitch = function(context) {
    function click() {
        d3.event.preventDefault();

        var live = d3.select(this).classed('live');

        context.connection()
            .url(live ? 'http://api06.dev.openstreetmap.org' : 'http://www.openstreetmap.org');

        context.map()
            .flush();

        d3.select(this)
            .text(live ? t('source_switch.dev') : t('source_switch.live'))
            .classed('live', !live);
    }

    return function(selection) {
        selection.append('a')
            .attr('href', '#')
            .text(t('source_switch.dev'))
            .classed('live', false)
            .on('click', click);
    };
};
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var events = require('events');
var async = require('async');
var isBinaryFile = require('isbinaryfile');
var util = require('util');

var Conflicter = module.exports = function Conflicter(adapter) {
  events.EventEmitter.call(this);
  this.adapter = adapter;
  this.conflicts = [];
};

util.inherits(Conflicter, events.EventEmitter);

Conflicter.prototype.add = function add(conflict) {
  if (typeof conflict === 'string') {
    conflict = {
      file: conflict,
      content: fs.readFileSync(conflict, 'utf8')
    };
  }

  if (!conflict.file) {
    throw new Error('Missing conflict.file option');
  }

  if (conflict.content === undefined) {
    throw new Error('Missing conflict.content option');
  }

  this.conflicts.push(conflict);
  return this;
};

Conflicter.prototype.reset = function reset() {
  this.conflicts = [];
  return this;
};

Conflicter.prototype.pop = function pop() {
  return this.conflicts.pop();
};

Conflicter.prototype.shift = function shift() {
  return this.conflicts.shift();
};

Conflicter.prototype.resolve = function resolve(cb) {
  var resolveConflicts = function (conflict) {
    return function (next) {
      if (!conflict) {
        return next();
      }

      this.collision(conflict.file, conflict.content, function (status) {
        this.emit('resolved:' + conflict.file, {
          status: status,
          callback: next
        });
      }.bind(this));
    }.bind(this);
  }.bind(this);

  async.series(this.conflicts.map(resolveConflicts), function (err) {
    if (err) {
      cb();
      return this.emit('error', err);
    }

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

Conflicter.prototype._ask = function (filepath, content, cb) {
  // for this particular use case, might use prompt module directly to avoid
  // the additional "Are you sure?" prompt

  var self = this;
  var rfilepath = path.relative(process.cwd(), path.resolve(filepath));

  var config = [{
    type: 'expand',
    message: 'Overwrite ' + rfilepath + '?',
    choices: [{
      key: 'y',
      name: 'overwrite',
      value: function (cb) {
        self.adapter.log.force(rfilepath);
        return cb('force');
      }
    }, {
      key: 'n',
      name: 'do not overwrite',
      value: function (cb) {
        self.adapter.log.skip(rfilepath);
        return cb('skip');
      }
    }, {
      key: 'a',
      name: 'overwrite this and all others',
      value: function (cb) {
        self.adapter.log.force(rfilepath);
        self.force = true;
        return cb('force');
      }
    }, {
      key: 'x',
      name: 'abort',
      value: function () {
        self.adapter.log.writeln('Aborting ...');
        return process.exit(0);
      }
    }, {
      key: 'd',
      name: 'show the differences between the old and the new',
      value: function (cb) {
        self.diff(fs.readFileSync(filepath, 'utf8'), content);
        return self._ask(filepath, content, cb);
      }
    }],
    name: 'overwrite'
  }];

  process.nextTick(function () {
    this.emit('prompt', config);
    this.emit('conflict', filepath);
  }.bind(this));

  this.adapter.prompt(config, function (result) {
    result.overwrite(function (action) {
      cb(action);
    });
  });
};

Conflicter.prototype.collision = function collision(filepath, content, cb) {
  var rfilepath = path.relative(process.cwd(), path.resolve(filepath));
  if (!fs.existsSync(filepath)) {
    this.adapter.log.create(rfilepath);
    return cb('create');
  }

  if (!fs.statSync(path.resolve(filepath)).isDirectory()) {
    var encoding = null;
    if (!isBinaryFile(path.resolve(filepath))) {
      encoding = 'utf8';
    }

    var actual = fs.readFileSync(path.resolve(filepath), encoding);

    // In case of binary content, `actual` and `content` are `Buffer` objects,
    // we just can't compare those 2 objects with standard `===`,
    // so we convert each binary content to an hexadecimal string first, and then compare them with standard `===`
    //
    // For not binary content, we can directly compare the 2 strings this way
    if ((!encoding && (actual.toString('hex') === content.toString('hex'))) ||
      (actual === content)) {
      this.adapter.log.identical(rfilepath);
      return cb('identical');
    }
  }

  if (this.force) {
    this.adapter.log.force(rfilepath);
    return cb('force');
  }

  this.adapter.log.conflict(rfilepath);
  this._ask(filepath, content, cb);
};

// below is borrowed code from visionmedia's excellent mocha (and its reporter)
Conflicter.prototype.diff = function _diff(actual, expected) {
  return this.adapter.diff(actual, expected);
};
<commit_msg>Replace throwing if statement with assertion<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var events = require('events');
var assert = require('assert');
var async = require('async');
var isBinaryFile = require('isbinaryfile');
var util = require('util');

var Conflicter = module.exports = function Conflicter(adapter) {
  events.EventEmitter.call(this);
  this.adapter = adapter;
  this.conflicts = [];
};

util.inherits(Conflicter, events.EventEmitter);

Conflicter.prototype.add = function add(conflict) {
  if (typeof conflict === 'string') {
    conflict = {
      file: conflict,
      content: fs.readFileSync(conflict, 'utf8')
    };
  }

  assert(conflict.file, 'Missing conflict.file option');
  assert(conflict.content !== undefined, 'Missing conflict.content option');

  this.conflicts.push(conflict);
  return this;
};

Conflicter.prototype.reset = function reset() {
  this.conflicts = [];
  return this;
};

Conflicter.prototype.pop = function pop() {
  return this.conflicts.pop();
};

Conflicter.prototype.shift = function shift() {
  return this.conflicts.shift();
};

Conflicter.prototype.resolve = function resolve(cb) {
  var resolveConflicts = function (conflict) {
    return function (next) {
      if (!conflict) {
        return next();
      }

      this.collision(conflict.file, conflict.content, function (status) {
        this.emit('resolved:' + conflict.file, {
          status: status,
          callback: next
        });
      }.bind(this));
    }.bind(this);
  }.bind(this);

  async.series(this.conflicts.map(resolveConflicts), function (err) {
    if (err) {
      cb();
      return this.emit('error', err);
    }

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

Conflicter.prototype._ask = function (filepath, content, cb) {
  // for this particular use case, might use prompt module directly to avoid
  // the additional "Are you sure?" prompt

  var self = this;
  var rfilepath = path.relative(process.cwd(), path.resolve(filepath));

  var config = [{
    type: 'expand',
    message: 'Overwrite ' + rfilepath + '?',
    choices: [{
      key: 'y',
      name: 'overwrite',
      value: function (cb) {
        self.adapter.log.force(rfilepath);
        return cb('force');
      }
    }, {
      key: 'n',
      name: 'do not overwrite',
      value: function (cb) {
        self.adapter.log.skip(rfilepath);
        return cb('skip');
      }
    }, {
      key: 'a',
      name: 'overwrite this and all others',
      value: function (cb) {
        self.adapter.log.force(rfilepath);
        self.force = true;
        return cb('force');
      }
    }, {
      key: 'x',
      name: 'abort',
      value: function () {
        self.adapter.log.writeln('Aborting ...');
        return process.exit(0);
      }
    }, {
      key: 'd',
      name: 'show the differences between the old and the new',
      value: function (cb) {
        self.diff(fs.readFileSync(filepath, 'utf8'), content);
        return self._ask(filepath, content, cb);
      }
    }],
    name: 'overwrite'
  }];

  process.nextTick(function () {
    this.emit('prompt', config);
    this.emit('conflict', filepath);
  }.bind(this));

  this.adapter.prompt(config, function (result) {
    result.overwrite(function (action) {
      cb(action);
    });
  });
};

Conflicter.prototype.collision = function collision(filepath, content, cb) {
  var rfilepath = path.relative(process.cwd(), path.resolve(filepath));
  if (!fs.existsSync(filepath)) {
    this.adapter.log.create(rfilepath);
    return cb('create');
  }

  if (!fs.statSync(path.resolve(filepath)).isDirectory()) {
    var encoding = null;
    if (!isBinaryFile(path.resolve(filepath))) {
      encoding = 'utf8';
    }

    var actual = fs.readFileSync(path.resolve(filepath), encoding);

    // In case of binary content, `actual` and `content` are `Buffer` objects,
    // we just can't compare those 2 objects with standard `===`,
    // so we convert each binary content to an hexadecimal string first, and then compare them with standard `===`
    //
    // For not binary content, we can directly compare the 2 strings this way
    if ((!encoding && (actual.toString('hex') === content.toString('hex'))) ||
      (actual === content)) {
      this.adapter.log.identical(rfilepath);
      return cb('identical');
    }
  }

  if (this.force) {
    this.adapter.log.force(rfilepath);
    return cb('force');
  }

  this.adapter.log.conflict(rfilepath);
  this._ask(filepath, content, cb);
};

// below is borrowed code from visionmedia's excellent mocha (and its reporter)
Conflicter.prototype.diff = function _diff(actual, expected) {
  return this.adapter.diff(actual, expected);
};
<|endoftext|>


<commit_before>/*
 * freepano - WebGL panorama viewer
 *
 * Copyright (c) 2014 FOXEL SA - http://foxel.ch
 * Please read <http://foxel.ch/license> for more information.
 *
 *
 * Author(s):
 *
 *      Luc Deschenaux <l.deschenaux@foxel.ch>
 *
 *
 * This file is part of the FOXEL project <http://foxel.ch>.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * Additional Terms:
 *
 *      You are required to preserve legal notices and author attributions in
 *      that material or in the Appropriate Legal Notices displayed by works
 *      containing it.
 *
 *      You are required to attribute the work as explained in the "Usage and
 *      Attribution" section of <http://foxel.ch/license>.
 */

if (typeof PanoList!=undefined) {
  alert("jquery.freepano.list.js must be loaded after jquery.freepano.poi.js !")
}

function POI(options){
  if (!(this instanceof POI)) {
    return new POI(options)
  }
  $.extend(true,this,POI.prototype.defaults,options);
  this.init();
}

$.extend(true, POI.prototype, {

  defaults: {
    mesh: null,
    radius: Math.PI ,
    coords: {
      lon: 0,
      lat: 90
    },
    size: Math.PI/36,
    callback: function poi_callback(poi_event) {
    }
  },

  // initialize poi and add to panorama scene
  init: function poi_init() {

    var poi=this;
    var panorama=poi.panorama;

    // create object3D if undefined
    if (!poi.object3D) {
      // create mesh if undefined
      if (!poi.mesh) {
        poi.mesh=poi.defaultMesh();
      }
      poi.object3D=new THREE.Object3D();
      poi.object3D.add(poi.mesh);
    }

    // add to scene
    panorama.scene.add(poi.object3D);

    poi.callback({
        type:'ready',
        target: poi
    });

  }, // poi_init

  // create default mesh
  defaultMesh: function poi_defaultMesh() {
     var poi=this;
     var sphere=new THREE.Mesh(new THREE.SphereGeometry(poi.size,100,100), new THREE.MeshBasicMaterial({
           color: 0x000000,
           transparent: true,
           opacity: 0.3
     }));
     return sphere;
  }, // poi_defaultMesh

  // update poi display properties and coordinates

  update: function poi_update() {
    var poi=this;
    var panorama=poi.panorama;

    // set poi model view matrix to identity
    poi.mv=new THREE.Matrix4();

    // rotation around vertical axis
    poi.mv.multiply(new THREE.Matrix4().makeRotationY(-poi.coords.lon*Math.PI/180));

    // rotation around horizontal axis
    poi.mv.multiply(new THREE.Matrix4().makeRotationX(-poi.coords.lat*Math.PI/180));

    // translation towards unity vector
//    poi.mv.multiplyVector4(new THREE.Vector4(0,0,poi.radius,1));

    // compute poi coords
    poi.coords.vec4=new THREE.Vector4(0,0,-poi.radius,1);
    poi.coords.vec4.applyMatrix4(poi.mv);
    poi.coords.vec4.applyMatrix4(poi.panorama.rotation.matrix);

      poi.coords.vec4.applyMatrix4(panorama.viewRotationMatrix);
//    poi.coords.vec4.applyMatrix4(new THREE.Matrix4().makeRotationY(panorama.lon*Math.PI/180));
//    poi.coords.vec4.applyMatrix4(new THREE.Matrix4().makeRotationX(panorama.lat*Math.PI/180));

    poi.object3D.position.x=poi.coords.vec4.x/poi.coords.vec4.w;
    poi.object3D.position.y=poi.coords.vec4.y/poi.coords.vec4.w;
    poi.object3D.position.z=poi.coords.vec4.z/poi.coords.vec4.w;

//    poi.object3D.rotation.setFromRotationMatrix(new THREE.Matrix4().makeRotationY(-panorama.lon*2*Math.PI/180));

    poi.callback({
        type:'update',
        target: poi
    });

  }, // poi_update

  getCoords3D:function(){
    var poi=this;
    var x=poi.mesh.position.x;
    var y=poi.mesh.position.y;
    var z=poi.mesh.position.z;
    // rectangular to polar coordinates
    var r=Math.sqrt(x*x+y*y+z*z);
    var phi=Math.acos(z/r);
    var theta=Math.atan2(y,x);
    // back to rectangular coordinates (to set distance from camera)
    return [
      -poi.radius*Math.sin(phi)*Math.cos(theta),
      -poi.radius*Math.sin(phi)*Math.sin(theta),
      -poi.radius*Math.cos(phi)
    ];
  },
});

function POI_list(options) {
    if (!(this instanceof POI_list)) {
      return new POI_list(options)
    }
    $.extend(true,this,POI_list.prototype.defaults,options);
    this.init();
}

$.extend(true, POI_list.prototype, {

    defaults: {
      callback: function(e) {}
    },

    init: function POI_list_init() {
      var poi_list=this;
      var panorama=poi_list.panorama;
      if (panorama.scene) {
        $.each(panorama.poi.list,function(name) {
          var poi=this;
          poi.instance=null;
          poi.instance=new POI($.extend(true,poi,{
            panorama: panorama
          }));
        });
        poi_list.callback({type: 'init'});
      } else {
        poi_list.on_panorama_ready=function(e) {
          var panorama=this;
          panorama.poi.init();
        }
      }
    },
});

$.extend(POI_list.prototype,{

    // save pointer to Panorama.prototype.init in POI_list.prototype
    panorama_prototype_init: Panorama.prototype.init,

    // save pointer to Panorama.prototype.callback in POI_list.prototype
    panorama_prototype_callback: Panorama.prototype.callback,

    on_panorama_update: function poiList_on_panorama_update(e) {

      var panorama=this;

      if (!panorama.poi) {
        return;
      }

      // update poi list on panorama 'update' event
      $.each(panorama.poi.list,function update_poi() {
        var poiList_elem=this;
        poiList_elem.instance.update();
      });
    }

});

$.extend(Panorama.prototype,{

  init: function poiList_panorama_init() {

      var panorama=this;

      // skip POI_list instantiation if poi list preferences undefined in panorama
      if (panorama.poi!==undefined) {

        // or if poi list is already instantiated
        if (!(panorama.poi instanceof POI_list)) {

          // instantiate poi list
          panorama.poi=new POI_list($.extend(true,{

            // pass panorama instance pointer to poi list instance
            panorama: panorama,

          },panorama.poi));
        }
      }

      // chain with old panorama.prototype.init
      POI_list.prototype.panorama_prototype_init.call(panorama);

  },

  // hook to Panorama.prototype.callback
  callback: function poiList_panorama_prototype_callback(e) {

    var panorama=this;

    if (panorama.poi && panorama.poi['on_panorama_'+e.type]) {
      panorama.poi['on_panorama_'+e.type].apply(panorama,[e]);
    }

    // chain with old panorama.prototype.callback
    POI_list.prototype.panorama_prototype_callback.apply(panorama,[e]);

  } // panorama_prototype_callback_hook

}); // extend Panorama.prototype

<commit_msg>fix unquoted string<commit_after>/*
 * freepano - WebGL panorama viewer
 *
 * Copyright (c) 2014 FOXEL SA - http://foxel.ch
 * Please read <http://foxel.ch/license> for more information.
 *
 *
 * Author(s):
 *
 *      Luc Deschenaux <l.deschenaux@foxel.ch>
 *
 *
 * This file is part of the FOXEL project <http://foxel.ch>.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * Additional Terms:
 *
 *      You are required to preserve legal notices and author attributions in
 *      that material or in the Appropriate Legal Notices displayed by works
 *      containing it.
 *
 *      You are required to attribute the work as explained in the "Usage and
 *      Attribution" section of <http://foxel.ch/license>.
 */

if (typeof(PanoList)!="undefined") {
  alert("jquery.freepano.list.js must be loaded after jquery.freepano.poi.js !")
}

function POI(options){
  if (!(this instanceof POI)) {
    return new POI(options)
  }
  $.extend(true,this,POI.prototype.defaults,options);
  this.init();
}

$.extend(true, POI.prototype, {

  defaults: {
    mesh: null,
    radius: Math.PI ,
    coords: {
      lon: 0,
      lat: 90
    },
    size: Math.PI/36,
    callback: function poi_callback(poi_event) {
    }
  },

  // initialize poi and add to panorama scene
  init: function poi_init() {

    var poi=this;
    var panorama=poi.panorama;

    // create object3D if undefined
    if (!poi.object3D) {
      // create mesh if undefined
      if (!poi.mesh) {
        poi.mesh=poi.defaultMesh();
      }
      poi.object3D=new THREE.Object3D();
      poi.object3D.add(poi.mesh);
    }

    // add to scene
    panorama.scene.add(poi.object3D);

    poi.callback({
        type:'ready',
        target: poi
    });

  }, // poi_init

  // create default mesh
  defaultMesh: function poi_defaultMesh() {
     var poi=this;
     var sphere=new THREE.Mesh(new THREE.SphereGeometry(poi.size,100,100), new THREE.MeshBasicMaterial({
           color: 0x000000,
           transparent: true,
           opacity: 0.3
     }));
     return sphere;
  }, // poi_defaultMesh

  // update poi display properties and coordinates

  update: function poi_update() {
    var poi=this;
    var panorama=poi.panorama;

    // set poi model view matrix to identity
    poi.mv=new THREE.Matrix4();

    // rotation around vertical axis
    poi.mv.multiply(new THREE.Matrix4().makeRotationY(-poi.coords.lon*Math.PI/180));

    // rotation around horizontal axis
    poi.mv.multiply(new THREE.Matrix4().makeRotationX(-poi.coords.lat*Math.PI/180));

    // translation towards unity vector
//    poi.mv.multiplyVector4(new THREE.Vector4(0,0,poi.radius,1));

    // compute poi coords
    poi.coords.vec4=new THREE.Vector4(0,0,-poi.radius,1);
    poi.coords.vec4.applyMatrix4(poi.mv);
    poi.coords.vec4.applyMatrix4(poi.panorama.rotation.matrix);

      poi.coords.vec4.applyMatrix4(panorama.viewRotationMatrix);
//    poi.coords.vec4.applyMatrix4(new THREE.Matrix4().makeRotationY(panorama.lon*Math.PI/180));
//    poi.coords.vec4.applyMatrix4(new THREE.Matrix4().makeRotationX(panorama.lat*Math.PI/180));

    poi.object3D.position.x=poi.coords.vec4.x/poi.coords.vec4.w;
    poi.object3D.position.y=poi.coords.vec4.y/poi.coords.vec4.w;
    poi.object3D.position.z=poi.coords.vec4.z/poi.coords.vec4.w;

//    poi.object3D.rotation.setFromRotationMatrix(new THREE.Matrix4().makeRotationY(-panorama.lon*2*Math.PI/180));

    poi.callback({
        type:'update',
        target: poi
    });

  }, // poi_update

  getCoords3D:function(){
    var poi=this;
    var x=poi.mesh.position.x;
    var y=poi.mesh.position.y;
    var z=poi.mesh.position.z;
    // rectangular to polar coordinates
    var r=Math.sqrt(x*x+y*y+z*z);
    var phi=Math.acos(z/r);
    var theta=Math.atan2(y,x);
    // back to rectangular coordinates (to set distance from camera)
    return [
      -poi.radius*Math.sin(phi)*Math.cos(theta),
      -poi.radius*Math.sin(phi)*Math.sin(theta),
      -poi.radius*Math.cos(phi)
    ];
  },
});

function POI_list(options) {
    if (!(this instanceof POI_list)) {
      return new POI_list(options)
    }
    $.extend(true,this,POI_list.prototype.defaults,options);
    this.init();
}

$.extend(true, POI_list.prototype, {

    defaults: {
      callback: function(e) {}
    },

    init: function POI_list_init() {
      var poi_list=this;
      var panorama=poi_list.panorama;
      if (panorama.scene) {
        $.each(panorama.poi.list,function(name) {
          var poi=this;
          poi.instance=null;
          poi.instance=new POI($.extend(true,poi,{
            panorama: panorama
          }));
        });
        poi_list.callback({type: 'init'});
      } else {
        poi_list.on_panorama_ready=function(e) {
          var panorama=this;
          panorama.poi.init();
        }
      }
    },
});

$.extend(POI_list.prototype,{

    // save pointer to Panorama.prototype.init in POI_list.prototype
    panorama_prototype_init: Panorama.prototype.init,

    // save pointer to Panorama.prototype.callback in POI_list.prototype
    panorama_prototype_callback: Panorama.prototype.callback,

    on_panorama_update: function poiList_on_panorama_update(e) {

      var panorama=this;

      if (!panorama.poi) {
        return;
      }

      // update poi list on panorama 'update' event
      $.each(panorama.poi.list,function update_poi() {
        var poiList_elem=this;
        poiList_elem.instance.update();
      });
    }

});

$.extend(Panorama.prototype,{

  init: function poiList_panorama_init() {

      var panorama=this;

      // skip POI_list instantiation if poi list preferences undefined in panorama
      if (panorama.poi!==undefined) {

        // or if poi list is already instantiated
        if (!(panorama.poi instanceof POI_list)) {

          // instantiate poi list
          panorama.poi=new POI_list($.extend(true,{

            // pass panorama instance pointer to poi list instance
            panorama: panorama,

          },panorama.poi));
        }
      }

      // chain with old panorama.prototype.init
      POI_list.prototype.panorama_prototype_init.call(panorama);

  },

  // hook to Panorama.prototype.callback
  callback: function poiList_panorama_prototype_callback(e) {

    var panorama=this;

    if (panorama.poi && panorama.poi['on_panorama_'+e.type]) {
      panorama.poi['on_panorama_'+e.type].apply(panorama,[e]);
    }

    // chain with old panorama.prototype.callback
    POI_list.prototype.panorama_prototype_callback.apply(panorama,[e]);

  } // panorama_prototype_callback_hook

}); // extend Panorama.prototype

<|endoftext|>


<commit_before>
exports = module.exports = lifecycle
exports.cmd = cmd

var log = require("./log.js")
  , exec = require("./exec.js")
  , npm = require("../../npm.js")
  , path = require("path")
  , readJson = require("./read-json.js")
  , fs = require("graceful-fs")
  , chain = require("slide").chain
  , constants = require("constants")
  , output = require("./output.js")

function lifecycle (pkg, stage, wd, unsafe, cb) {
  if (typeof cb !== "function") cb = unsafe, unsafe = false
  if (typeof cb !== "function") cb = wd, wd = null

  while (pkg && pkg._data) pkg = pkg._data
  if (!pkg) return cb(new Error("Invalid package data"))

  log(pkg._id, stage)
  if (!pkg.scripts) pkg.scripts = {}

  validWd(wd || path.resolve(npm.dir, pkg.name), function (er, wd) {
    if (er) return cb(er)

    unsafe = unsafe || npm.config.get("unsafe-perm")

    if ((wd.indexOf(npm.dir) !== 0 || path.basename(wd) !== pkg.name)
        && !unsafe && pkg.scripts[stage]) {
      log.warn(pkg._id+" "+pkg.scripts[stage], "skipping, cannot run in "+wd)
      return cb()
    }

    // set the env variables, then run scripts as a child process.
    var env = makeEnv(pkg)
    env.npm_lifecycle_event = stage

    // "nobody" typically doesn't have permission to write to /tmp
    // even if it's never used, sh freaks out.
    if (!npm.config.get("unsafe-perm")) env.TMPDIR = wd

    lifecycle_(pkg, stage, wd, env, unsafe, cb)
  })
}

function checkForLink (pkg, cb) {
  var f = path.join(npm.dir, pkg.name)
  fs.lstat(f, function (er, s) {
    cb(null, !(er || !s.isSymbolicLink()))
  })
}

function lifecycle_ (pkg, stage, wd, env, unsafe, cb) {
  var PATH = []
    , p = wd.split("node_modules")
    , acc = path.resolve(p.shift())
  p.forEach(function (pp) {
    PATH.unshift(path.join(acc, "node_modules", ".bin"))
    acc = path.join(acc, "node_modules", pp)
  })
  PATH.unshift(path.join(acc, "node_modules", ".bin"))
  if (env.PATH) PATH.push(env.PATH)
  env.PATH = PATH.join(":")

  var packageLifecycle = pkg.scripts && pkg.scripts.hasOwnProperty(stage)

  if (packageLifecycle) {
    // define this here so it's available to all scripts.
    env.npm_lifecycle_script = pkg.scripts[stage]
  }

  if (npm.config.get("force")) cb = (function (cb_) { return function (er) {
    if (er) log(er, "forced, continuing")
    cb_()
  }})(cb)

  chain
    ( [ packageLifecycle && [runPackageLifecycle, pkg, env, wd, unsafe]
      , [runHookLifecycle, pkg, env, wd, unsafe] ]
    , cb )
}

function validWd (d, cb) {
  fs.stat(d, function (er, st) {
    if (er || !st.isDirectory()) {
      var p = path.dirname(d)
      if (p === d) {
        return cb(new Error("Could not find suitable wd"))
      }
      return validWd(p, cb)
    }
    return cb(null, d)
  })
}

function runPackageLifecycle (pkg, env, wd, unsafe, cb) {
  // run package lifecycle scripts in the package root, or the nearest parent.
  var stage = env.npm_lifecycle_event
    , user = unsafe ? null : npm.config.get("user")
    , group = unsafe ? null : npm.config.get("group")
    , cmd = env.npm_lifecycle_script

  log.verbose(unsafe, "unsafe-perm in lifecycle")

  output.write("\n> "+pkg._id+" " + stage+" "+wd+"\n> "+cmd+"\n", function (er) {
    if (er) return cb(er)
    exec( "sh", ["-c", cmd], env, true, wd
        , user, group
        , function (er, code, stdout, stderr) {
      if (er && !npm.ROLLBACK) {
        log("Failed to exec "+stage+" script", pkg._id)
        er.message = pkg._id + " "
                   + stage + ": `" + env.npm_lifecycle_script+"`\n"
                   + er.message
        if (er.errno !== constants.EPERM) {
          er.errno = npm.ELIFECYCLE
        }
        er.pkgid = pkg._id
        er.stage = stage
        er.script = env.npm_lifecycle_script
        er.pkgname = pkg.name
        return cb(er)
      } else if (er) {
        log.error(er, pkg._id+"."+stage)
        log.error("failed, but continuing anyway", pkg._id+"."+stage)
        return cb()
      }
      cb(er)
    })
  })
}

function runHookLifecycle (pkg, env, wd, unsafe, cb) {
  // check for a hook script, run if present.
  var stage = env.npm_lifecycle_event
    , hook = path.join(npm.dir, ".hooks", stage)
    , user = unsafe ? null : npm.config.get("user")
    , group = unsafe ? null : npm.config.get("group")
    , cmd = hook

  fs.stat(hook, function (er) {
    if (er) return cb()

    exec( "sh", ["-c", cmd], env, true, wd
        , user, group
        , function (er) {
      if (er) {
        er.message += "\nFailed to exec "+stage+" hook script"
        log(er, pkg._id)
      }
      if (npm.ROLLBACK) return cb()
      cb(er)
    })
  })
}

function makeEnv (data, prefix, env) {
  prefix = prefix || "npm_package_"
  if (!env) {
    env = {}
    for (var i in process.env) if (!i.match(/^npm_/)) {
      env[i] = process.env[i]
    }

    // npat asks for tap output
    if (npm.config.get("npat")) env.TAP = 1

    // express and others respect the NODE_ENV value.
    if (npm.config.get("production")) env.NODE_ENV = "production"

  } else if (!data.hasOwnProperty("_lifecycleEnv")) {
    Object.defineProperty(data, "_lifecycleEnv",
      { value : env
      , enumerable : false
      })
  }

  for (var i in data) if (i.charAt(0) !== "_") {
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, '_')
    if (data[i] && typeof(data[i]) === "object") {
      try {
        // quick and dirty detection for cyclical structures
        JSON.stringify(data[i])
        makeEnv(data[i], envKey+"_", env)
      } catch (ex) {
        // usually these are package objects.
        // just get the path and basic details.
        var d = data[i]
        makeEnv( { name: d.name, version: d.version, path:d.path }
               , envKey+"_", env)
      }
    } else {
      env[envKey] = String(data[i])
    }
  }

  if (prefix !== "npm_package_") return env

  prefix = "npm_config_"
  var conf = npm.config.get()
    , pkgConfig = {}
    , pkgVerConfig = {}
    , namePref = data.name + ":"
    , verPref = data.name + "@" + data.version + ":"

  for (var i in conf) if (i.charAt(0) !== "_") {
    var value = String(conf[i])
    if (i.indexOf(namePref) === 0) {
      var k = i.substr(namePref.length).replace(/[^a-zA-Z0-9_]/g, "_")
      pkgConfig[ k ] = value
    } else if (i.indexOf(verPref) === 0) {
      var k = i.substr(verPref.length).replace(/[^a-zA-Z0-9_]/g, "_")
      pkgVerConfig[ k ] = value
    }
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, "_")
    env[envKey] = value
  }

  prefix = "npm_package_config_"
  ;[pkgConfig, pkgVerConfig].forEach(function (conf) {
    for (var i in conf) {
      var envKey = (prefix+i)
      env[envKey] = conf[i]
    }
  })

  return env
}

function cmd (stage) {
  function CMD (args, cb) {
    if (args.length) {
      chain(args.map(function (p) {
        return [npm.commands, "run-script", [p, stage]]
      }), cb)
    } else npm.commands["run-script"]([stage], cb)
 }
  CMD.usage = "npm "+stage+" <name>"
  var installedShallow = require("./completion/installed-shallow.js")
  CMD.completion = function (opts, cb) {
    installedShallow(opts, function (d) {
      return d.scripts && d.scripts[stage]
    }, cb)
  }
  return CMD
}
<commit_msg>Allow private per-package confs<commit_after>
exports = module.exports = lifecycle
exports.cmd = cmd

var log = require("./log.js")
  , exec = require("./exec.js")
  , npm = require("../../npm.js")
  , path = require("path")
  , readJson = require("./read-json.js")
  , fs = require("graceful-fs")
  , chain = require("slide").chain
  , constants = require("constants")
  , output = require("./output.js")

function lifecycle (pkg, stage, wd, unsafe, cb) {
  if (typeof cb !== "function") cb = unsafe, unsafe = false
  if (typeof cb !== "function") cb = wd, wd = null

  while (pkg && pkg._data) pkg = pkg._data
  if (!pkg) return cb(new Error("Invalid package data"))

  log(pkg._id, stage)
  if (!pkg.scripts) pkg.scripts = {}

  validWd(wd || path.resolve(npm.dir, pkg.name), function (er, wd) {
    if (er) return cb(er)

    unsafe = unsafe || npm.config.get("unsafe-perm")

    if ((wd.indexOf(npm.dir) !== 0 || path.basename(wd) !== pkg.name)
        && !unsafe && pkg.scripts[stage]) {
      log.warn(pkg._id+" "+pkg.scripts[stage], "skipping, cannot run in "+wd)
      return cb()
    }

    // set the env variables, then run scripts as a child process.
    var env = makeEnv(pkg)
    env.npm_lifecycle_event = stage

    // "nobody" typically doesn't have permission to write to /tmp
    // even if it's never used, sh freaks out.
    if (!npm.config.get("unsafe-perm")) env.TMPDIR = wd

    lifecycle_(pkg, stage, wd, env, unsafe, cb)
  })
}

function checkForLink (pkg, cb) {
  var f = path.join(npm.dir, pkg.name)
  fs.lstat(f, function (er, s) {
    cb(null, !(er || !s.isSymbolicLink()))
  })
}

function lifecycle_ (pkg, stage, wd, env, unsafe, cb) {
  var PATH = []
    , p = wd.split("node_modules")
    , acc = path.resolve(p.shift())
  p.forEach(function (pp) {
    PATH.unshift(path.join(acc, "node_modules", ".bin"))
    acc = path.join(acc, "node_modules", pp)
  })
  PATH.unshift(path.join(acc, "node_modules", ".bin"))
  if (env.PATH) PATH.push(env.PATH)
  env.PATH = PATH.join(":")

  var packageLifecycle = pkg.scripts && pkg.scripts.hasOwnProperty(stage)

  if (packageLifecycle) {
    // define this here so it's available to all scripts.
    env.npm_lifecycle_script = pkg.scripts[stage]
  }

  if (npm.config.get("force")) cb = (function (cb_) { return function (er) {
    if (er) log(er, "forced, continuing")
    cb_()
  }})(cb)

  chain
    ( [ packageLifecycle && [runPackageLifecycle, pkg, env, wd, unsafe]
      , [runHookLifecycle, pkg, env, wd, unsafe] ]
    , cb )
}

function validWd (d, cb) {
  fs.stat(d, function (er, st) {
    if (er || !st.isDirectory()) {
      var p = path.dirname(d)
      if (p === d) {
        return cb(new Error("Could not find suitable wd"))
      }
      return validWd(p, cb)
    }
    return cb(null, d)
  })
}

function runPackageLifecycle (pkg, env, wd, unsafe, cb) {
  // run package lifecycle scripts in the package root, or the nearest parent.
  var stage = env.npm_lifecycle_event
    , user = unsafe ? null : npm.config.get("user")
    , group = unsafe ? null : npm.config.get("group")
    , cmd = env.npm_lifecycle_script

  log.verbose(unsafe, "unsafe-perm in lifecycle")

  output.write("\n> "+pkg._id+" " + stage+" "+wd+"\n> "+cmd+"\n", function (er) {
    if (er) return cb(er)
    exec( "sh", ["-c", cmd], env, true, wd
        , user, group
        , function (er, code, stdout, stderr) {
      if (er && !npm.ROLLBACK) {
        log("Failed to exec "+stage+" script", pkg._id)
        er.message = pkg._id + " "
                   + stage + ": `" + env.npm_lifecycle_script+"`\n"
                   + er.message
        if (er.errno !== constants.EPERM) {
          er.errno = npm.ELIFECYCLE
        }
        er.pkgid = pkg._id
        er.stage = stage
        er.script = env.npm_lifecycle_script
        er.pkgname = pkg.name
        return cb(er)
      } else if (er) {
        log.error(er, pkg._id+"."+stage)
        log.error("failed, but continuing anyway", pkg._id+"."+stage)
        return cb()
      }
      cb(er)
    })
  })
}

function runHookLifecycle (pkg, env, wd, unsafe, cb) {
  // check for a hook script, run if present.
  var stage = env.npm_lifecycle_event
    , hook = path.join(npm.dir, ".hooks", stage)
    , user = unsafe ? null : npm.config.get("user")
    , group = unsafe ? null : npm.config.get("group")
    , cmd = hook

  fs.stat(hook, function (er) {
    if (er) return cb()

    exec( "sh", ["-c", cmd], env, true, wd
        , user, group
        , function (er) {
      if (er) {
        er.message += "\nFailed to exec "+stage+" hook script"
        log(er, pkg._id)
      }
      if (npm.ROLLBACK) return cb()
      cb(er)
    })
  })
}

function makeEnv (data, prefix, env) {
  prefix = prefix || "npm_package_"
  if (!env) {
    env = {}
    for (var i in process.env) if (!i.match(/^npm_/)) {
      env[i] = process.env[i]
    }

    // npat asks for tap output
    if (npm.config.get("npat")) env.TAP = 1

    // express and others respect the NODE_ENV value.
    if (npm.config.get("production")) env.NODE_ENV = "production"

  } else if (!data.hasOwnProperty("_lifecycleEnv")) {
    Object.defineProperty(data, "_lifecycleEnv",
      { value : env
      , enumerable : false
      })
  }

  for (var i in data) if (i.charAt(0) !== "_") {
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, '_')
    if (data[i] && typeof(data[i]) === "object") {
      try {
        // quick and dirty detection for cyclical structures
        JSON.stringify(data[i])
        makeEnv(data[i], envKey+"_", env)
      } catch (ex) {
        // usually these are package objects.
        // just get the path and basic details.
        var d = data[i]
        makeEnv( { name: d.name, version: d.version, path:d.path }
               , envKey+"_", env)
      }
    } else {
      env[envKey] = String(data[i])
    }
  }

  if (prefix !== "npm_package_") return env

  prefix = "npm_config_"
  var pkgConfig = {}
    , ini = require("./ini.js")
    , keys = ini.keys
    , pkgVerConfig = {}
    , namePref = data.name + ":"
    , verPref = data.name + "@" + data.version + ":"

  keys.forEach(function (i) {
    if (i.charAt(0) === "_" && i.indexOf("_"+namePref) !== 0) {
      return
    }
    var value = String(ini.get(i))
    i = i.replace(/^_+/, "")
    if (i.indexOf(namePref) === 0) {
      var k = i.substr(namePref.length).replace(/[^a-zA-Z0-9_]/g, "_")
      pkgConfig[ k ] = value
    } else if (i.indexOf(verPref) === 0) {
      var k = i.substr(verPref.length).replace(/[^a-zA-Z0-9_]/g, "_")
      pkgVerConfig[ k ] = value
    }
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, "_")
    env[envKey] = value
  })

  prefix = "npm_package_config_"
  ;[pkgConfig, pkgVerConfig].forEach(function (conf) {
    for (var i in conf) {
      var envKey = (prefix+i)
      env[envKey] = conf[i]
    }
  })

  return env
}

function cmd (stage) {
  function CMD (args, cb) {
    if (args.length) {
      chain(args.map(function (p) {
        return [npm.commands, "run-script", [p, stage]]
      }), cb)
    } else npm.commands["run-script"]([stage], cb)
 }
  CMD.usage = "npm "+stage+" <name>"
  var installedShallow = require("./completion/installed-shallow.js")
  CMD.completion = function (opts, cb) {
    installedShallow(opts, function (d) {
      return d.scripts && d.scripts[stage]
    }, cb)
  }
  return CMD
}
<|endoftext|>


<commit_before>import R from 'ramda'

export const notEmpty = R.compose(R.not, R.isEmpty)
export const isEmptyValue = R.compose(R.isEmpty, R.trim)
export const nilOrEmpty = R.either(R.isNil, isEmptyValue)

export const hasValue = R.compose(R.not, nilOrEmpty)

export const isObject = value => {
  const type = typeof value
  return value != null && (type === 'object' || type === 'function')
}

const notNil = R.compose(R.not, R.isNil)

const validObjects = R.compose(R.pickBy(notNil), R.pickBy(isObject))

const emptyArray = obj => Array.isArray(obj) && obj.length === 0

const validValues = R.compose(
  R.map(R.trim),
  R.pickBy(notNil),
  R.reject(isObject)
)

export const cast = (fields, source) => {
  const casted = R.pick(fields, source)

  return R.merge(validValues(casted), validObjects(casted))
}

const keyOf = R.compose(R.head, R.keys)
const valueOf = R.compose(R.head, R.values)

export const changeset = source => ({
  exsit: (obj, cb, opt = {}) => {
    if (source.__dirty__) return changeset(source)

    const field = keyOf(obj)
    const trans = valueOf(obj)
    let isInValid = false
    if (emptyArray(source[field])) {
      isInValid = true
    } else if (!Array.isArray(source[field]) && nilOrEmpty(source[field])) {
      isInValid = true
    }
    if (isInValid) {
      const title = trans
      const msg = opt.msg || '不能为空'

      cb({ title, msg })
      return changeset(R.merge(source, { __dirty__: true, __rat__: field }))
    }
    return changeset(source)
  },
  min: (obj, num, cb) => {
    if (source.__dirty__) return changeset(source)

    const field = keyOf(obj)
    const trans = valueOf(obj)

    if (R.trim(source[field]).length < num) {
      const title = trans
      const msg = `不能小于 ${num} 个字符`

      cb({ title, msg })
      return changeset(R.merge(source, { __dirty__: true, __rat__: field }))
    }
    return changeset(source)
  },
  alreadyExsits: (obj, target, pools, cb) => {
    if (source.__dirty__) return changeset(source)
    const field = keyOf(obj)
    const trans = valueOf(obj)

    if (R.length(R.filter(R.equals(target), pools)) > 0) {
      const title = trans
      const msg = `已经存在了, 请核对。`

      cb({ title, msg })
      return changeset(R.merge(source, { __dirty__: true, __rat__: field }))
    }

    return changeset(source)
    // R.length(R.filter(R.equals(target), source)) > 0
  },
  startsWith: (obj, prefix, cb, condition = true) => {
    if (source.__dirty__ || !condition) return changeset(source)

    const field = keyOf(obj)
    const trans = valueOf(obj)

    if (!R.startsWith(prefix, R.trim(source[field]))) {
      const title = trans
      const msg = `请填写 ${prefix} 开头的链接地址`

      cb({ title, msg })
      return changeset(R.merge(source, { __dirty__: true, __rat__: field }))
    }
    return changeset(source)
  },
  durationFmt: (obj, cb) => {
    if (source.__dirty__) return changeset(source)
    const field = keyOf(obj)
    const trans = valueOf(obj)

    const shortFmt = /^([01]?[0-9]|[0-5][0-9]):[0-5][0-9]$/
    const longFmt = /^(?:0[0-2]|0[0-9]):[0-5][0-9]:[0-5][0-9]$/
    // https://stackoverflow.com/questions/2732799/regex-time-validation-hhmm
    // https://stackoverflow.com/questions/14892740/regular-expression-for-hhmmss

    if (shortFmt.test(source[field]) || longFmt.test(source[field])) {
      return changeset(source)
    }
    const title = trans
    const msg = '格式：mm:ss 或者 hh:mm:ss'

    cb({ title, msg })
    return changeset(R.merge(source, { __dirty__: true, __rat__: field }))
  },
  dateFmt: (obj, cb) => {
    if (source.__dirty__) return changeset(source)

    const field = keyOf(obj)
    const trans = valueOf(obj)

    /* const regex = /[0-9]{4}[/][0-9]{2}[/][0-9]{2}$/ */
    const regex = /[0-9]{4}[/][0-9][0-9][/][0-3][0-9]$/
    const isValidDate = !Number.isNaN(Date.parse(source[field]))

    if (regex.test(source[field]) && isValidDate) {
      return changeset(source)
    }
    const title = trans
    const msg = '请输入格式为：YYYY/MM/DD 的合法日期'

    cb({ title, msg })
    return changeset(R.merge(source, { __dirty__: true, __rat__: field }))
  },
  done: () => {
    if (source.__dirty__) {
      return { passed: false, rat: source.__rat__ }
    }
    return { passed: true }
  },
})
<commit_msg>style: fmt<commit_after>import R from 'ramda'

export const notEmpty = R.compose(
  R.not,
  R.isEmpty
)
export const isEmptyValue = R.compose(
  R.isEmpty,
  R.trim
)
export const nilOrEmpty = R.either(R.isNil, isEmptyValue)

export const hasValue = R.compose(
  R.not,
  nilOrEmpty
)

export const isObject = value => {
  const type = typeof value
  return value != null && (type === 'object' || type === 'function')
}

const notNil = R.compose(
  R.not,
  R.isNil
)

const validObjects = R.compose(
  R.pickBy(notNil),
  R.pickBy(isObject)
)

const emptyArray = obj => Array.isArray(obj) && obj.length === 0

const validValues = R.compose(
  R.map(R.trim),
  R.pickBy(notNil),
  R.reject(isObject)
)

export const cast = (fields, source) => {
  const casted = R.pick(fields, source)

  return R.merge(validValues(casted), validObjects(casted))
}

const keyOf = R.compose(
  R.head,
  R.keys
)
const valueOf = R.compose(
  R.head,
  R.values
)

export const changeset = source => ({
  exsit: (obj, cb, opt = {}) => {
    if (source.__dirty__) return changeset(source)

    const field = keyOf(obj)
    const trans = valueOf(obj)
    let isInValid = false
    if (emptyArray(source[field])) {
      isInValid = true
    } else if (!Array.isArray(source[field]) && nilOrEmpty(source[field])) {
      isInValid = true
    }
    if (isInValid) {
      const title = trans
      const msg = opt.msg || '不能为空'

      cb({ title, msg })
      return changeset(R.merge(source, { __dirty__: true, __rat__: field }))
    }
    return changeset(source)
  },
  min: (obj, num, cb) => {
    if (source.__dirty__) return changeset(source)

    const field = keyOf(obj)
    const trans = valueOf(obj)

    if (R.trim(source[field]).length < num) {
      const title = trans
      const msg = `不能小于 ${num} 个字符`

      cb({ title, msg })
      return changeset(R.merge(source, { __dirty__: true, __rat__: field }))
    }
    return changeset(source)
  },
  alreadyExsits: (obj, target, pools, cb) => {
    if (source.__dirty__) return changeset(source)
    const field = keyOf(obj)
    const trans = valueOf(obj)

    if (R.length(R.filter(R.equals(target), pools)) > 0) {
      const title = trans
      const msg = `已经存在了, 请核对。`

      cb({ title, msg })
      return changeset(R.merge(source, { __dirty__: true, __rat__: field }))
    }

    return changeset(source)
    // R.length(R.filter(R.equals(target), source)) > 0
  },
  startsWith: (obj, prefix, cb, condition = true) => {
    if (source.__dirty__ || !condition) return changeset(source)

    const field = keyOf(obj)
    const trans = valueOf(obj)

    if (!R.startsWith(prefix, R.trim(source[field]))) {
      const title = trans
      const msg = `请填写 ${prefix} 开头的链接地址`

      cb({ title, msg })
      return changeset(R.merge(source, { __dirty__: true, __rat__: field }))
    }
    return changeset(source)
  },
  durationFmt: (obj, cb) => {
    if (source.__dirty__) return changeset(source)
    const field = keyOf(obj)
    const trans = valueOf(obj)

    const shortFmt = /^([01]?[0-9]|[0-5][0-9]):[0-5][0-9]$/
    const longFmt = /^(?:0[0-2]|0[0-9]):[0-5][0-9]:[0-5][0-9]$/
    // https://stackoverflow.com/questions/2732799/regex-time-validation-hhmm
    // https://stackoverflow.com/questions/14892740/regular-expression-for-hhmmss

    if (shortFmt.test(source[field]) || longFmt.test(source[field])) {
      return changeset(source)
    }
    const title = trans
    const msg = '格式：mm:ss 或者 hh:mm:ss'

    cb({ title, msg })
    return changeset(R.merge(source, { __dirty__: true, __rat__: field }))
  },
  dateFmt: (obj, cb) => {
    if (source.__dirty__) return changeset(source)

    const field = keyOf(obj)
    const trans = valueOf(obj)

    /* const regex = /[0-9]{4}[/][0-9]{2}[/][0-9]{2}$/ */
    const regex = /[0-9]{4}[/][0-9][0-9][/][0-3][0-9]$/
    const isValidDate = !Number.isNaN(Date.parse(source[field]))

    if (regex.test(source[field]) && isValidDate) {
      return changeset(source)
    }
    const title = trans
    const msg = '请输入格式为：YYYY/MM/DD 的合法日期'

    cb({ title, msg })
    return changeset(R.merge(source, { __dirty__: true, __rat__: field }))
  },
  done: () => {
    if (source.__dirty__) {
      return { passed: false, rat: source.__rat__ }
    }
    return { passed: true }
  },
})
<|endoftext|>


<commit_before>var async = require('async');
var logger = require('../../lib/logger.lib');

var status = [
    "尚未注册",
    "正在竞拍",
    "已被注册",
    "禁止注册",
    "公示阶段",
    "尚未放出"
];

var resolveStatus = [
    "未设置解析",
    "官方解析器",
    "私有解析器"
];

module.exports = function (req, res) {
    var ethereum = req.app.get("ethereum");
    var ens = req.app.get("ens");
    var publicResolver = ens.publicResolver;
    var domain = req.query.domain;
    console.log("try to parse " + domain + " length " + domain.length);

    function getDomainInfo(d) {
        var dHash = ethereum.sha3(d);
        var namehash = ens.namehash(d + ".eth");
        var entry = ens.ethRegistrar.entries(dHash);
        var status_int = parseInt(entry[0]);
        var address = entry[1];
        var date = new Date(parseInt(entry[2]) * 1000);
        var highestBid = ethereum.fromWei(entry[4], "ether");
        var secondBid = ethereum.fromWei(entry[3], "ether");
        var status_ch = status[status_int];
        var ret = {
            sti : status_int,
            date: date,
            stch : status_ch,
            high : highestBid,
            sec : secondBid
        };

        if(status_int == 2){
            ret.owner = ens.ens.owner(namehash);
            if(ret.owner == '0x0000000000000000000000000000000000000000'){
                ret = {
                    sti : status_int,
                    date: date,
                    stch : "等待领取",
                    high : highestBid,
                    sec : secondBid
                };
            }
        }

        //load deed
        ret.deed = address;
        /*
        if(address != '0x0000000000000000000000000000000000000000'){
            //var deed = ens.deedContract.at(address);

        }*/

        ret.resolve = {
            status: 0,
            resolveTo: "0x0000000000000000000000000000000000000000",
            resolver: "0x0000000000000000000000000000000000000000"
        };
        //resolver
        ret.resolver = ens.ens.resolver(namehash);

        if(ret.resolver != '0x0000000000000000000000000000000000000000') {
            //
            if(ret.resolver == publicResolver.address){
                ret.status = 1;
                ret.resolveTo = publicResolver.addr(dHash);
            } else {
                ret.status = 2;
                ret.resolveTo = ens.resolveContract.at(ret.resolver).addr(namehash);
            }
        }
        return ret;
    }

    res.json(getDomainInfo(domain));
};

<commit_msg>auto<commit_after>var async = require('async');
var logger = require('../../lib/logger.lib');

var status = [
    "尚未注册",
    "正在竞拍",
    "已被注册",
    "禁止注册",
    "公示阶段",
    "尚未放出"
];

var resolveStatus = [
    "未设置解析",
    "官方解析器",
    "私有解析器"
];

module.exports = function (req, res) {
    var ethereum = req.app.get("ethereum");
    var ens = req.app.get("ens");
    var publicResolver = ens.publicResolver;
    var domain = req.query.domain;
    console.log("try to parse " + domain + " length " + domain.length);

    function getDomainInfo(d) {
        var dHash = ethereum.sha3(d);
        var namehash = ens.namehash(d + ".eth");
        var entry = ens.ethRegistrar.entries(dHash);
        var status_int = parseInt(entry[0]);
        var address = entry[1];
        var date = new Date(parseInt(entry[2]) * 1000);
        var highestBid = ethereum.fromWei(entry[4], "ether");
        var secondBid = ethereum.fromWei(entry[3], "ether");
        var status_ch = status[status_int];
        var ret = {
            sti : status_int,
            date: date,
            stch : status_ch,
            high : highestBid,
            sec : secondBid
        };

        if(status_int == 2){
            ret.owner = ens.ens.owner(namehash);
            if(ret.owner == '0x0000000000000000000000000000000000000000'){
                ret = {
                    sti : status_int,
                    date: date,
                    stch : "等待领取",
                    high : highestBid,
                    sec : secondBid
                };
            }
        }

        //load deed
        ret.deed = address;
        /*
        if(address != '0x0000000000000000000000000000000000000000'){
            var deed = ens.deedContract.at(address);
            ret.deed =
        }*/

        ret.resolve = {
            status: 0,
            resolveTo: "0x0000000000000000000000000000000000000000",
            resolver: "0x0000000000000000000000000000000000000000"
        };
        //resolver
        ret.resolve.resolver = ens.ens.resolver(namehash);

        if(ret.resolve.resolver != '0x0000000000000000000000000000000000000000') {
            //
            if(ret.resolve.resolver == publicResolver.address){
                ret.resolve.status = 1;
                ret.resolve.resolveTo = publicResolver.addr(dHash);
            } else {
                ret.resolve.status = 2;
                ret.resolve.resolveTo = ens.resolveContract.at(ret.resolver).addr(namehash);
            }
        }
        return ret;
    }

    res.json(getDomainInfo(domain));
};

<|endoftext|>