<commit_before>"use strict";

/*eslint-disable max-nested-callbacks*/

const
    tools = require("../../res/tools.js"),
    fs = require("fs"),

    mergeCounts = (dest, src) => Object.keys(src).forEach(key => {
        if (dest[key]) {
            dest[key] += src[key];
        } else {
            dest[key] = src[key];
        }
    }),

    mergeBranches = (dest, src) => Object.keys(src).forEach(key => {
        if (dest[key]) {
            dest[key][0] += src[key][0];
            dest[key][1] += src[key][1];
        } else {
            dest[key] = src[key];
        }
    }),

    mergeCoverageData = (dst, src, fileName) => {
        let dstCoverageData = dst[fileName],
            srcCoverageData = src[fileName];
        if (dstCoverageData) {
            // Assuming the maps are properly generated
            mergeCounts(dstCoverageData.s, srcCoverageData.s);
            mergeCounts(dstCoverageData.f, srcCoverageData.f);
            mergeBranches(dstCoverageData.b, srcCoverageData.b);
        } else {
            dst[fileName] = srcCoverageData;
        }
    },

    mergeCoverage = (dst, src) => {
        Object.keys(src).forEach(fileName => {
            mergeCoverageData(dst, src, fileName);
        });
    },

    ConfigFile = require("../../make/configFile.js"),

    getHosts = () => {
        const
            configFile = new ConfigFile(),
            hosts = ["phantomjs"];
        if (Object.keys(configFile.content.browsers).length !== 0) {
            hosts.push("browser");
        }
        if (configFile.content.host.java) {
            hosts.push("rhino");
        }
        if (configFile.content.host.nashorn) {
            hosts.push("nashorn");
        }
        if (configFile.content.host.wscript) {
            hosts.push("wscript");
        } else {
            hosts.push("nodewscript");
        }
        return hosts;
    };

module.exports = function (grunt) {

    grunt.registerTask("mergeCoverage", () => {
        let coverage = grunt.file.readJSON("tmp/coverage/reports/coverage.json");
        getHosts()
            .map(host => host === "nodewscript" ? "wscript" : host)
            .forEach(host => {
                try {
                    let hostCoverage = grunt.file.readJSON(`tmp/coverage/reports/coverage.${host}.json`);
                    mergeCoverage(coverage, hostCoverage);
                } catch (e) {
                    grunt.fail.warn(`Missing coverage information for ${host}: ${e.toString()}`);
                }
            });
        fs.writeFileSync("tmp/coverage/reports/coverage.json", JSON.stringify(coverage));
    });

    const varPrefix = "var ";

    grunt.registerTask("fixInstrument", () => {
        // Because code generation uses templates that are instrumented, the __cov_XXX variables must be global
        configuration.files.src.forEach(fileName => {
            let srcPath = `tmp/coverage/instrument/${fileName}`,
                instrumentedLines = fs.readFileSync(srcPath).toString().split("\n"),
                // Assuming the __cov_ variable is on the second line
                secondLine = instrumentedLines[1];
            if (secondLine.indexOf(varPrefix) === 0) {
                instrumentedLines[1] = `global.${secondLine.substr(varPrefix.length)}`;
                fs.writeFileSync(srcPath, instrumentedLines.join("\n"));
                console.log(`${fileName} updated`);
            }
        });
    });

    let coverageTasks = [
        "instrument",
        "fixInstrument",
        "copy:instrumentSourcesJson",
        "connectIf",
        "mochaTest:coverage",
        "storeCoverage"

    ].concat(getHosts()
        .filter(host => host !== "browser")
        .map(host => host === "phantomjs" ? "phantom" : host)
        .map(host => `exec:test${tools.capitalize(host)}Coverage`)
    );

    // Prefer chrome if possible
    if (configuration.browsers.chrome) {
        coverageTasks.push("exec:testChromeCoverage");
    } else {
        let browser = Object.keys(configuration.browsers)[0];
        if (browser) {
            coverageTasks.push(`exec:test${tools.capitalize(browser)}Coverage`);
        }
    }

    coverageTasks.push("mergeCoverage", "makeReport", "coverage");

    grunt.registerTask("istanbul", coverageTasks);
};
<commit_msg>no-magic-numbers (#280)<commit_after>"use strict";

/*eslint-disable max-nested-callbacks*/

const
    tools = require("../../res/tools.js"),
    fs = require("fs"),

    mergeCounts = (dest, src) => Object.keys(src).forEach(key => {
        if (dest[key]) {
            dest[key] += src[key];
        } else {
            dest[key] = src[key];
        }
    }),

    BRANCH_IF = 0,
    BRANCH_ELSE = 1,

    mergeBranches = (dest, src) => Object.keys(src).forEach(key => {
        if (dest[key]) {
            dest[key][BRANCH_IF] += src[key][BRANCH_IF];
            dest[key][BRANCH_ELSE] += src[key][BRANCH_ELSE];
        } else {
            dest[key] = src[key];
        }
    }),

    mergeCoverageData = (dst, src, fileName) => {
        let dstCoverageData = dst[fileName],
            srcCoverageData = src[fileName];
        if (dstCoverageData) {
            // Assuming the maps are properly generated
            mergeCounts(dstCoverageData.s, srcCoverageData.s);
            mergeCounts(dstCoverageData.f, srcCoverageData.f);
            mergeBranches(dstCoverageData.b, srcCoverageData.b);
        } else {
            dst[fileName] = srcCoverageData;
        }
    },

    mergeCoverage = (dst, src) => {
        Object.keys(src).forEach(fileName => {
            mergeCoverageData(dst, src, fileName);
        });
    },

    ConfigFile = require("../../make/configFile.js"),

    getHosts = () => {
        const
            configFile = new ConfigFile(),
            hosts = ["phantomjs"];
        if (Object.keys(configFile.content.browsers).length) {
            hosts.push("browser");
        }
        if (configFile.content.host.java) {
            hosts.push("rhino");
        }
        if (configFile.content.host.nashorn) {
            hosts.push("nashorn");
        }
        if (configFile.content.host.wscript) {
            hosts.push("wscript");
        } else {
            hosts.push("nodewscript");
        }
        return hosts;
    };

module.exports = function (grunt) {

    grunt.registerTask("mergeCoverage", () => {
        let coverage = grunt.file.readJSON("tmp/coverage/reports/coverage.json");
        getHosts()
            .map(host => host === "nodewscript" ? "wscript" : host)
            .forEach(host => {
                try {
                    let hostCoverage = grunt.file.readJSON(`tmp/coverage/reports/coverage.${host}.json`);
                    mergeCoverage(coverage, hostCoverage);
                } catch (e) {
                    grunt.fail.warn(`Missing coverage information for ${host}: ${e.toString()}`);
                }
            });
        fs.writeFileSync("tmp/coverage/reports/coverage.json", JSON.stringify(coverage));
    });

    const
        varPrefix = "var ",
        coverageVariablePos = 1; // Assuming the __cov_ variable is on the second line

    grunt.registerTask("fixInstrument", () => {
        // Because code generation uses templates that are instrumented, the __cov_XXX variables must be global
        configuration.files.src.forEach(fileName => {
            let srcPath = `tmp/coverage/instrument/${fileName}`,
                instrumentedLines = fs.readFileSync(srcPath).toString().split("\n"),
                coverageVariableLine = instrumentedLines[coverageVariablePos];
            if (coverageVariableLine.startsWith(varPrefix)) {
                instrumentedLines[coverageVariablePos] = `global.${coverageVariableLine.substr(varPrefix.length)}`;
                fs.writeFileSync(srcPath, instrumentedLines.join("\n"));
                console.log(`${fileName} updated`);
            }
        });
    });

    let coverageTasks = [
        "instrument",
        "fixInstrument",
        "copy:instrumentSourcesJson",
        "connectIf",
        "mochaTest:coverage",
        "storeCoverage"

    ].concat(getHosts()
        .filter(host => host !== "browser")
        .map(host => host === "phantomjs" ? "phantom" : host)
        .map(host => `exec:test${tools.capitalize(host)}Coverage`)
    );

    // Prefer chrome if possible
    if (configuration.browsers.chrome) {
        coverageTasks.push("exec:testChromeCoverage");
    } else {
        let browser = Object.keys(configuration.browsers).shift(); // or take the first
        if (browser) {
            coverageTasks.push(`exec:test${tools.capitalize(browser)}Coverage`);
        }
    }

    coverageTasks.push("mergeCoverage", "makeReport", "coverage");

    grunt.registerTask("istanbul", coverageTasks);
};
<|endoftext|>


<commit_before>var ajaxManager = (function() {
    var requests = [];
    var retry = 0;
	var idleCb = null;
    return {
        dump: function(opt) {
            alert("retry is " + retry);
            if (requests.length == 0) {
                alert("Dumped empty ajaxManager");
            }
            else {
                alert("DUMP ajaxManager");
                for (var i=0; i<requests.length; i++) {
                    console.log(requests[i]);
                }
            }
        },
        addReq: function(opt) {
            requests.push(opt);
        },
        removeReq:  function(opt) {
            if ($.inArray(opt, requests) > -1){
                requests.splice($.inArray(opt, requests), 1);
            }
        },
        retry: function() {
            ////console.log('requests.length => ' + requests.length)
            $('#retryMessage').hide();
            if (retry >= 3) {
                $("#fatalErrorModal").modal({
                    keyboard: false,
                    backdrop: 'static'
                });
            }
            else {
                retry++;
                this.run();
            }

        },
        run: function() {
            var self = this;
            var oriSuc;
            var oriErr;
            var oriBef;

            if (requests.length) {
                $('#loadingMessageStatusTop').show();
                if (retry==0) {
                    oriSuc = requests[0].success; // complete
                    oriErr = requests[0].error;
                    oriBef = requests[0].beforeSend;

                    requests[0].success = function(data) { // complete
                         try {

                             $('#loadingMessageStatusTop').hide();
                             if (typeof oriSuc === 'function') {
                                 try {
									 oriSuc(data);
                                 }
								 catch (error) {
                                 	alert("KISS AJAX MANAGER ERROR (100) " + error);
                                 }
                             }
                             requests.shift();
                             self.run.apply(self, []);
                             retry = 0; // reset
                         }
                         catch (error) {
                             console.log(" " + error);
                         }
                    };

                    requests[0].error = function(data){ // onError
                        try {

                            if (data.status == '403') {
                                // full overlay
                                $("#loggedOutModal").modal({
                                    keyboard: false,
                                    backdrop: 'static'
                                });
                            }
                            if (data.status == '500') {
                                alert("500 - INTERNAL SERVER ERROR")
                            }
							else {
                                $('#loadingMessageStatusTop').hide();
                                $('#retryMessage').show();
                            }

                            if (typeof oriErr === 'function') {
                                 oriErr(data);
                            }
                        }
                        catch (error) {
                            console.log(" " + error);
                        }
                    };

                    requests[0].beforeSend = function(data, settings) { // onBeforeSend
                         try {

                             $('#loadingMessageStatusTop').show();
                             if (typeof oriBef === 'function') {
                                 oriBef(data, settings);
                             }
                         }
                         catch (error) {
                             console.log(" " + error);
                         }
                    };
                }
                $.ajax(requests[0]);
            }
            else {
				// is there an idle callback set? call it if so.
				if (typeof idleCb == "function" ) {
					idleCb();
				}

                self.tid = setTimeout(function() {
                    self.run.apply(self, []);
                }, 50); //1000, 100 => 10Hz Current settings, refresh queue at 20 Hz
            }
        },
        stop:  function() {
            requests = [];
            clearTimeout(this.tid);
        },
        setIdleCallback: function(opt) {
        	idleCb = opt;
        },
     };
}());

<commit_msg>modified .stop() method to reset idle callback<commit_after>var ajaxManager = (function() {
    var requests = [];
    var retry = 0;
	var idleCb = null;
    return {
        dump: function(opt) {
            alert("retry is " + retry);
            if (requests.length == 0) {
                alert("Dumped empty ajaxManager");
            }
            else {
                alert("DUMP ajaxManager");
                for (var i=0; i<requests.length; i++) {
                    console.log(requests[i]);
                }
            }
        },
        addReq: function(opt) {
            requests.push(opt);
        },
        removeReq:  function(opt) {
            if ($.inArray(opt, requests) > -1){
                requests.splice($.inArray(opt, requests), 1);
            }
        },
        retry: function() {
            ////console.log('requests.length => ' + requests.length)
            $('#retryMessage').hide();
            if (retry >= 3) {
                $("#fatalErrorModal").modal({
                    keyboard: false,
                    backdrop: 'static'
                });
            }
            else {
                retry++;
                this.run();
            }

        },
        run: function() {
            var self = this;
            var oriSuc;
            var oriErr;
            var oriBef;

            if (requests.length) {
                $('#loadingMessageStatusTop').show();
                if (retry==0) {
                    oriSuc = requests[0].success; // complete
                    oriErr = requests[0].error;
                    oriBef = requests[0].beforeSend;

                    requests[0].success = function(data) { // complete
                         try {

                             $('#loadingMessageStatusTop').hide();
                             if (typeof oriSuc === 'function') {
                                 try {
									 oriSuc(data);
                                 }
								 catch (error) {
                                 	alert("KISS AJAX MANAGER ERROR (100) " + error);
                                 }
                             }
                             requests.shift();
                             self.run.apply(self, []);
                             retry = 0; // reset
                         }
                         catch (error) {
                             console.log(" " + error);
                         }
                    };

                    requests[0].error = function(data){ // onError
                        try {

                            if (data.status == '403') {
                                // full overlay
                                $("#loggedOutModal").modal({
                                    keyboard: false,
                                    backdrop: 'static'
                                });
                            }
                            if (data.status == '500') {
                                alert("500 - INTERNAL SERVER ERROR")
                            }
							else {
                                $('#loadingMessageStatusTop').hide();
                                $('#retryMessage').show();
                            }

                            if (typeof oriErr === 'function') {
                                 oriErr(data);
                            }
                        }
                        catch (error) {
                            console.log(" " + error);
                        }
                    };

                    requests[0].beforeSend = function(data, settings) { // onBeforeSend
                         try {

                             $('#loadingMessageStatusTop').show();
                             if (typeof oriBef === 'function') {
                                 oriBef(data, settings);
                             }
                         }
                         catch (error) {
                             console.log(" " + error);
                         }
                    };
                }
                $.ajax(requests[0]);
            }
            else {
				// is there an idle callback set? call it if so.
				if (typeof idleCb == "function" ) {
					idleCb();
				}

                self.tid = setTimeout(function() {
                    self.run.apply(self, []);
                }, 50); //1000, 100 => 10Hz Current settings, refresh queue at 20 Hz
            }
        },
        stop:  function() {
            requests = [];
			idleCb = null;
            clearTimeout(this.tid);
        },
        setIdleCallback: function(opt) {
        	idleCb = opt;
        },
     };
}());

<|endoftext|>


<commit_before>/// <reference path="S:\Delivery\Aspectize.core\AspectizeIntellisenseLibrary.js" />

Aspectize.Extend("GoogleMapPlaceInput", {
    Properties: { Longitude: '', Latitude: '', FullAdress: '', StreetNumber: '', Route: '', City: '', Zip: '', Country: '' },
    Events: ['OnLongitudeChanged', 'OnLatitudeChanged', 'OnFullAdressChanged', 'OnStreetNumberChanged', 'OnRouteChanged', 'OnCityChanged', 'OnZipChanged', 'OnCountryChanged'],
    Init: function (elem) {
        var autocomplete = new google.maps.places.Autocomplete(elem);

        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                //window.alert("Autocomplete's returned place contains no geometry");
                return;
            }

            if (place.geometry.location) {
                Aspectize.UiExtensions.ChangeProperty(elem, 'Longitude', place.geometry.location.lng());
                Aspectize.UiExtensions.ChangeProperty(elem, 'Latitude', place.geometry.location.lat());
            }

            Aspectize.UiExtensions.ChangeProperty(elem, 'FullAdress', place.formatted_address);

            var address = '';
            if (place.address_components) {

                for (var i = 0; i < place.address_components.length; i++) {
                    var adressElement = place.address_components[i];

                    for (var j = 0; j < adressElement.types.length; j++) {
                        var type = adressElement.types[j];
                        var property;
                        if (type === "postal_code") {
                            property = "Zip";
                        } else if (type == "country") {
                            property = "Country";
                        } else if (type == "locality") {
                            property = "City";
                        } else if (type == "street_number") {
                            property = "StreetNumber";
                        } else if (type == "route") {
                            property = "Route";
                        } else continue;

                        value = adressElement.long_name;
                        Aspectize.UiExtensions.ChangeProperty(elem, property, value);
                        break;
                    }
                }
            }
        });
    }
});
<commit_msg>Google Place<commit_after>/// <reference path="S:\Delivery\Aspectize.core\AspectizeIntellisenseLibrary.js" />

Aspectize.Extend("GoogleMapPlaceInput", {
    Properties: { Longitude: '', Latitude: '', FullAdress: '', StreetNumber: '', Route: '', City: '', Zip: '', Country: '' },
    Events: ['OnLongitudeChanged', 'OnLatitudeChanged', 'OnFullAdressChanged', 'OnStreetNumberChanged', 'OnRouteChanged', 'OnCityChanged', 'OnZipChanged', 'OnCountryChanged'],
    Init: function (elem) {
        var autocomplete = new google.maps.places.Autocomplete(elem);

        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                return;
            }

            if (place.geometry.location) {
                Aspectize.UiExtensions.ChangeProperty(elem, 'Longitude', place.geometry.location.lng());
                Aspectize.UiExtensions.ChangeProperty(elem, 'Latitude', place.geometry.location.lat());
            }

            Aspectize.UiExtensions.ChangeProperty(elem, 'FullAdress', place.formatted_address);

            var address = '';
            if (place.address_components) {

                for (var i = 0; i < place.address_components.length; i++) {
                    var adressElement = place.address_components[i];

                    for (var j = 0; j < adressElement.types.length; j++) {
                        var type = adressElement.types[j];
                        var property;
                        if (type === "postal_code") {
                            property = "Zip";
                        } else if (type == "country") {
                            property = "Country";
                        } else if (type == "locality") {
                            property = "City";
                        } else if (type == "street_number") {
                            property = "StreetNumber";
                        } else if (type == "route") {
                            property = "Route";
                        } else continue;

                        value = adressElement.long_name;
                        Aspectize.UiExtensions.ChangeProperty(elem, property, value);
                        break;
                    }
                }
            }
        });

        Aspectize.UiExtensions.AddMergedPropertyChangeObserver(elem, function (sender, arg) {
            if ('FullAdress' in arg) {
                $(elem).val(arg.FullAdress);
            }
        });
    }
});
<|endoftext|>


<commit_before>const fs = require("fs");
const path = require("path");
const SourceMapConsumer = require("source-map").SourceMapConsumer;

const cssString = fs.readFileSync(path.join(__dirname, "lib", "./style.css"), "utf8");
const jsString = fs.readFileSync(path.join(__dirname, "lib", "./pluginmain.js"), "utf8");

const PLUGIN_PREFIX = "\u0000";

module.exports = function(opts) {
  opts = opts || {};
  var filename = opts.filename || "stats.html";
  var useSourceMap = !!opts.sourcemap;

  return {
    ongenerate(args, rendered) {
      var bundle = args.bundle;

      var root = {
        name: "root",
        children: []
      };

      if (useSourceMap) {
        addMinifiedSizesToModules(bundle, rendered);
      }

      bundle.modules.forEach(module => {
        var name = module.id;
        var m = {
          //dependencies: module.dependencies,
          size: useSourceMap ? module.minifiedSize || 0 : Buffer.byteLength(module.code, "utf8"),
          originalSize: Buffer.byteLength(module.originalCode, "utf8")
        };

        if (name.indexOf(PLUGIN_PREFIX) === 0) {
          addToPath(root, [name], m);
        } else {
          addToPath(root, name.split(path.sep), m);
        }
      });
      flattenTree(root);

      var html = `<!doctype html>
          <title>RollUp Visualizer</title>
          <meta charset="utf-8">

RollUp Visualizer

                  of bundle size

      `;
      fs.writeFileSync(filename, html);
    }
  };
};

function getDeepMoreThenOneChild(tree) {
  if (tree.children && tree.children.length === 1) {
    return getDeepMoreThenOneChild(tree.children[0]);
  }
  return tree;
}
// if root children have only on child we can flatten this
function flattenTree(root) {
  var newChildren = [];
  root.children.forEach(child => {
    var commonParent = getDeepMoreThenOneChild(child);
    newChildren = newChildren.concat(commonParent.children);
  });
  root.children = newChildren;
}

function addToPath(tree, p, value) {
  if (p[0] === "") {
    p.shift();
  }

  var child = tree.children.filter(c => c.name === p[0])[0];
  if (!child) {
    child = {
      name: p[0],
      children: []
    };
    tree.children.push(child);
  }
  if (p.length === 1) {
    Object.assign(child, value);
    return;
  }
  p.shift();
  addToPath(child, p, value);
}

function getBytesPerFileUsingSourceMap(rendered) {
  var map = new SourceMapConsumer(rendered.map);
  var lines = rendered.code.split(/[\r\n]/);

  var bytesPerFile = {};

  // For every byte in the minified code, do a sourcemap lookup.
  for (var line = 0; line < lines.length; line++) {
    for (var col = 0; col < lines[line].length; col++) {
      var result = map.originalPositionFor({ line: line + 1, column: col });
      var source = result.source || "root";
      if (!bytesPerFile[source]) {
        bytesPerFile[source] = 0;
      }
      bytesPerFile[source]++;
    }
  }
  return Object.keys(bytesPerFile).map(file => ({ file: path.resolve(file), bytes: bytesPerFile[file] }));
}

// Given a file C:/path/to/file/on/filesystem.js
// - remove extension
// - strip filesystem root
// - return path segments, starting from the tail and working backwards
// segments('C:/path/to/file/on/filesystem.js') === ['filesystem', 'on', 'file', 'to', 'path']
function segments(filepath) {
  var parsed = path.parse(filepath);
  var dirWithoutRoot = parsed.dir.substring(parsed.root.length);

  return dirWithoutRoot.split(path.sep).concat(parsed.name).reverse();
}

// Adds a .minifiedSize property to each module in the bundle (using sourcemap data)
// If the minified size could not be computed, no property is added.
// Module id are mapped to sources by finding the best match.
// Matching is done by removing the file extensions and comparing path segments
function addMinifiedSizesToModules(bundle, rendered) {
  var fileSizes = getBytesPerFileUsingSourceMap(rendered);

  const findBestMatchingModule = filename => {
    var filenameSegments = segments(filename);

    for (var i = 1; i <= filenameSegments.length; i++) {
      var leftVals = filenameSegments.slice(0, i);

      var matches = bundle.modules.filter(module => {
        var moduleSegments = segments(module.id);
        var rightVals = moduleSegments.slice(0, i);
        if (rightVals.length !== leftVals.length) {
          return false;
        }
        return rightVals.every((rightVal, i) => rightVal === leftVals[i]);
      });

      if (matches.length === 1) {
        return matches[0];
      }
    }

    return null;
  };

  fileSizes.forEach(tuple => {
    var module = findBestMatchingModule(tuple.file);
    if (module) {
      module.minifiedSize = tuple.bytes;
    }
  });
}
<commit_msg>Add option to customize title<commit_after>const fs = require("fs");
const path = require("path");
const SourceMapConsumer = require("source-map").SourceMapConsumer;

const cssString = fs.readFileSync(path.join(__dirname, "lib", "./style.css"), "utf8");
const jsString = fs.readFileSync(path.join(__dirname, "lib", "./pluginmain.js"), "utf8");

const PLUGIN_PREFIX = "\u0000";

module.exports = function(opts) {
  opts = opts || {};
  var filename = opts.filename || "stats.html";
  var title = opts.title || "RollUp Visualizer";
  var useSourceMap = !!opts.sourcemap;

  return {
    ongenerate(args, rendered) {
      var bundle = args.bundle;

      var root = {
        name: "root",
        children: []
      };

      if (useSourceMap) {
        addMinifiedSizesToModules(bundle, rendered);
      }

      bundle.modules.forEach(module => {
        var name = module.id;
        var m = {
          //dependencies: module.dependencies,
          size: useSourceMap ? module.minifiedSize || 0 : Buffer.byteLength(module.code, "utf8"),
          originalSize: Buffer.byteLength(module.originalCode, "utf8")
        };

        if (name.indexOf(PLUGIN_PREFIX) === 0) {
          addToPath(root, [name], m);
        } else {
          addToPath(root, name.split(path.sep), m);
        }
      });
      flattenTree(root);

      var html = `<!doctype html>
          <title>${title}</title>
          <meta charset="utf-8">

${title}

                  of bundle size

      `;
      fs.writeFileSync(filename, html);
    }
  };
};

function getDeepMoreThenOneChild(tree) {
  if (tree.children && tree.children.length === 1) {
    return getDeepMoreThenOneChild(tree.children[0]);
  }
  return tree;
}
// if root children have only on child we can flatten this
function flattenTree(root) {
  var newChildren = [];
  root.children.forEach(child => {
    var commonParent = getDeepMoreThenOneChild(child);
    newChildren = newChildren.concat(commonParent.children);
  });
  root.children = newChildren;
}

function addToPath(tree, p, value) {
  if (p[0] === "") {
    p.shift();
  }

  var child = tree.children.filter(c => c.name === p[0])[0];
  if (!child) {
    child = {
      name: p[0],
      children: []
    };
    tree.children.push(child);
  }
  if (p.length === 1) {
    Object.assign(child, value);
    return;
  }
  p.shift();
  addToPath(child, p, value);
}

function getBytesPerFileUsingSourceMap(rendered) {
  var map = new SourceMapConsumer(rendered.map);
  var lines = rendered.code.split(/[\r\n]/);

  var bytesPerFile = {};

  // For every byte in the minified code, do a sourcemap lookup.
  for (var line = 0; line < lines.length; line++) {
    for (var col = 0; col < lines[line].length; col++) {
      var result = map.originalPositionFor({ line: line + 1, column: col });
      var source = result.source || "root";
      if (!bytesPerFile[source]) {
        bytesPerFile[source] = 0;
      }
      bytesPerFile[source]++;
    }
  }
  return Object.keys(bytesPerFile).map(file => ({ file: path.resolve(file), bytes: bytesPerFile[file] }));
}

// Given a file C:/path/to/file/on/filesystem.js
// - remove extension
// - strip filesystem root
// - return path segments, starting from the tail and working backwards
// segments('C:/path/to/file/on/filesystem.js') === ['filesystem', 'on', 'file', 'to', 'path']
function segments(filepath) {
  var parsed = path.parse(filepath);
  var dirWithoutRoot = parsed.dir.substring(parsed.root.length);

  return dirWithoutRoot.split(path.sep).concat(parsed.name).reverse();
}

// Adds a .minifiedSize property to each module in the bundle (using sourcemap data)
// If the minified size could not be computed, no property is added.
// Module id are mapped to sources by finding the best match.
// Matching is done by removing the file extensions and comparing path segments
function addMinifiedSizesToModules(bundle, rendered) {
  var fileSizes = getBytesPerFileUsingSourceMap(rendered);

  const findBestMatchingModule = filename => {
    var filenameSegments = segments(filename);

    for (var i = 1; i <= filenameSegments.length; i++) {
      var leftVals = filenameSegments.slice(0, i);

      var matches = bundle.modules.filter(module => {
        var moduleSegments = segments(module.id);
        var rightVals = moduleSegments.slice(0, i);
        if (rightVals.length !== leftVals.length) {
          return false;
        }
        return rightVals.every((rightVal, i) => rightVal === leftVals[i]);
      });

      if (matches.length === 1) {
        return matches[0];
      }
    }

    return null;
  };

  fileSizes.forEach(tuple => {
    var module = findBestMatchingModule(tuple.file);
    if (module) {
      module.minifiedSize = tuple.bytes;
    }
  });
}
<|endoftext|>


<commit_before>var format = require("util").format;

module.exports = {
    init: function (client, imports) {
        const requiresAdmin = imports.admin.requiresAdmin;
        const requiresAdminHelp = "Requires admin privileges.";

        return {
            handlers: {
                "!join": requiresAdmin(function (command) {
                    if (command.args[0]) {
                        client.notice(format("PluginControl", "Joining %s - requested by %s", command.channel, command.prefix));
                        client.join(command.args.join(" "));
                    }

                }),

                "!part": requiresAdmin(function (command) {
                    var channel;

                    if (command.args[0]) {
                        channel = command.args[0];
                    } else if (!command.isQuery) {
                        channel = command.channel;
                    } else {
                        return;
                    }

                    client.notice(format("PluginControl", "Parting %s - requested by %s", channel, command.prefix));
                    client.part(channel);
                }),

                "!quit": requiresAdmin(function (command) {
                    client.notice(format("PluginControl", "Quitting network - requested by %s", command.prefix));

                    var reason = command.args.join(" ");
                    if (/^\s*$/.test(reason)) {
                        reason = format("Requested by %s", command.nickname);
                    }

                    client.quit(reason);
                }),

                "!nick": requiresAdmin(function (command) {
                    if (command.args[0]) {
                        client.notice(format("PluginControl", "Changing nickname to %s - requested by %s", command.args[0], command.prefix));
                        client.nick(command.args[0]);
                    }
                }),

                "!say": requiresAdmin(function (command) {
                    return {
                        target: command.args[0],
                        message: command.args.slice(1).join(" ")
                    };
                }),

                "!act": requiresAdmin(function (command) {
                    return {
                        target: command.args[0],
                        intent: "act",
                        message: command.args.slice(1).join(" ")
                    };
                }),

                "!ctcp": requiresAdmin(function (command) {
                    return {
                        target: command.args[0],
                        intent: "ctcp",
                        message: [command.args[1], command.args.slice(2).join(" ")]
                    };
                }),

                "!notice": requiresAdmin(function (command) {
                    return {
                        target: command.args[0],
                        intent: "notice",
                        message: command.args.slice(1).join(" ")
                    };
                }),

                "!mode": requiresAdmin(function (command) {
                    if (command.args.length < 2) {
                        return {
                            query: true,
                            intent: "say",
                            message: "Error: mode command sent without enought parameters."
                        };
                    } else if (command.args.length === 1) {
                        client.rawf("MODE %s %s", command.args[0], command.args[1]);
                    } else {
                        client.rawf("MODE %s :%s", command.args[0], command.args[1], command.args.slice(2).join(" "));
                    }
                })
            },

            help: {
                "join": [
                    "{{!}}join <channel>",
                    " ",
                    "Join specifed channel.",
                    requiresAdminHelp
                ],
                "part": [
                    "{{!}}part [<channel>]",
                    " ",
                    "Part specified channel.",
                    "If no channel is given, parts channel message was sent in.",
                    requiresAdminHelp
                ],
                "quit": [
                    "{{!}}quit [<reason>]",
                    " ",
                    "Quit from network with given reason.",
                    requiresAdminHelp
                ],
                "nick": [
                    "{{!}}nick <newnick>",
                    " ",
                    "Change bot\"s nickname to the new nickname.",
                    requiresAdminHelp
                ],
                "say": [
                    "{{!}}say <target> <message>",
                    " ",
                    "Send a message to the target.",
                    requiresAdminHelp
                ],
                "act": [
                    "{{!}}act <target> <action>",
                    " ",
                    "Perform the action to the target.",
                    requiresAdminHelp
                ],
                "ctcp": [
                    "{{!}}ctcp <target> <ctcpType> <ctcpBody>",
                    " ",
                    "Send a CTCP of ctcpType to target with specified body.",
                    requiresAdminHelp
                ],
                "notice": [
                    "{{!}}notice <target> <message>",
                    " ",
                    "Send a notice to the target.",
                    requiresAdminHelp
                ],
                "mode": [
                    "{{!}}mode <target> <mode changes> <parameters>",
                    " ",
                    "Perform the mode changes.",
                    "Acts like /mode in your client.",
                    requiresAdminHelp
                ]
            },

            commands: ["join", "part", "quit", "nick", "say", "act", "ctcp", "notice"]
        }
    },

    requiresRoles: ["admin"]
};<commit_msg>Style: Missing semicolon.<commit_after>var format = require("util").format;

module.exports = {
    init: function (client, imports) {
        const requiresAdmin = imports.admin.requiresAdmin;
        const requiresAdminHelp = "Requires admin privileges.";

        return {
            handlers: {
                "!join": requiresAdmin(function (command) {
                    if (command.args[0]) {
                        client.notice(format("PluginControl", "Joining %s - requested by %s", command.channel, command.prefix));
                        client.join(command.args.join(" "));
                    }

                }),

                "!part": requiresAdmin(function (command) {
                    var channel;

                    if (command.args[0]) {
                        channel = command.args[0];
                    } else if (!command.isQuery) {
                        channel = command.channel;
                    } else {
                        return;
                    }

                    client.notice(format("PluginControl", "Parting %s - requested by %s", channel, command.prefix));
                    client.part(channel);
                }),

                "!quit": requiresAdmin(function (command) {
                    client.notice(format("PluginControl", "Quitting network - requested by %s", command.prefix));

                    var reason = command.args.join(" ");
                    if (/^\s*$/.test(reason)) {
                        reason = format("Requested by %s", command.nickname);
                    }

                    client.quit(reason);
                }),

                "!nick": requiresAdmin(function (command) {
                    if (command.args[0]) {
                        client.notice(format("PluginControl", "Changing nickname to %s - requested by %s", command.args[0], command.prefix));
                        client.nick(command.args[0]);
                    }
                }),

                "!say": requiresAdmin(function (command) {
                    return {
                        target: command.args[0],
                        message: command.args.slice(1).join(" ")
                    };
                }),

                "!act": requiresAdmin(function (command) {
                    return {
                        target: command.args[0],
                        intent: "act",
                        message: command.args.slice(1).join(" ")
                    };
                }),

                "!ctcp": requiresAdmin(function (command) {
                    return {
                        target: command.args[0],
                        intent: "ctcp",
                        message: [command.args[1], command.args.slice(2).join(" ")]
                    };
                }),

                "!notice": requiresAdmin(function (command) {
                    return {
                        target: command.args[0],
                        intent: "notice",
                        message: command.args.slice(1).join(" ")
                    };
                }),

                "!mode": requiresAdmin(function (command) {
                    if (command.args.length < 2) {
                        return {
                            query: true,
                            intent: "say",
                            message: "Error: mode command sent without enought parameters."
                        };
                    } else if (command.args.length === 1) {
                        client.rawf("MODE %s %s", command.args[0], command.args[1]);
                    } else {
                        client.rawf("MODE %s :%s", command.args[0], command.args[1], command.args.slice(2).join(" "));
                    }
                })
            },

            help: {
                "join": [
                    "{{!}}join <channel>",
                    " ",
                    "Join specifed channel.",
                    requiresAdminHelp
                ],
                "part": [
                    "{{!}}part [<channel>]",
                    " ",
                    "Part specified channel.",
                    "If no channel is given, parts channel message was sent in.",
                    requiresAdminHelp
                ],
                "quit": [
                    "{{!}}quit [<reason>]",
                    " ",
                    "Quit from network with given reason.",
                    requiresAdminHelp
                ],
                "nick": [
                    "{{!}}nick <newnick>",
                    " ",
                    "Change bot\"s nickname to the new nickname.",
                    requiresAdminHelp
                ],
                "say": [
                    "{{!}}say <target> <message>",
                    " ",
                    "Send a message to the target.",
                    requiresAdminHelp
                ],
                "act": [
                    "{{!}}act <target> <action>",
                    " ",
                    "Perform the action to the target.",
                    requiresAdminHelp
                ],
                "ctcp": [
                    "{{!}}ctcp <target> <ctcpType> <ctcpBody>",
                    " ",
                    "Send a CTCP of ctcpType to target with specified body.",
                    requiresAdminHelp
                ],
                "notice": [
                    "{{!}}notice <target> <message>",
                    " ",
                    "Send a notice to the target.",
                    requiresAdminHelp
                ],
                "mode": [
                    "{{!}}mode <target> <mode changes> <parameters>",
                    " ",
                    "Perform the mode changes.",
                    "Acts like /mode in your client.",
                    requiresAdminHelp
                ]
            },

            commands: ["join", "part", "quit", "nick", "say", "act", "ctcp", "notice"]
        };
    },

    requiresRoles: ["admin"]
};<|endoftext|>


<commit_before>const { promisify } = require('util')
const pSetTimeout = promisify(setTimeout)

module.exports = {
  async onSuccess({ utils: { status: { show } } }) {
    await pSetTimeout(6e4)
    show({ summary: 'Test' })
  }
}
<commit_msg>Revert "Test"<commit_after>module.exports = {
  onPostBuild({ utils: { status: { show } } }) {
    show({ summary: 'Test' })
  }
}
<|endoftext|>


<commit_before>
var extendable = require('extendable')
var _ = require('underscore')
var async = require('async')

var methodBlacklist = ['constructor', 'initialize', 'run']

var Plugin = function(Class, args) {
  var methods = {}
  for (var key in this) {
    if (key.charAt(0) != '_' && !~methodBlacklist.indexOf(key) && typeof this[key] == 'function')
      methods[key] = this[key]
  }
  _.extend(Class.prototype, methods)
  this.initialize.apply(this, args)
}

// Instance members

_.extend(Plugin.prototype, {

  // Called once for each instace of the plugin.
  // Almost always before the extended Class is initialized
  initialize: function() {},

  // Called once for each instance of the extended Class
  // in the context of that instance
  run: function(instance, callback) { callback() }

})

// Class Members

_.extend(Plugin, {

  extend: extendable,

  makePluggable: makePluggable

})

function makePluggable(Class, plugins) {
  plugins = [].concat(plugins || [])

  // The instance methods added to
  // a Class that is made 'pluggable'
  _.extend(Class.prototype, {
    runPlugins: function(callback) {
      if (typeof callback != 'function') throw new Error('Callback not provided or not a function')
      var instance = this
      async.forEachSeries(plugins, function(plugin, cb) {
        plugin.run(instance, cb)
      }, callback)
    }
  })

  // The Class methods added to a
  // Class that is made 'pluggable'
  _.extend(Class, {
    addPlugin: function(PluginClass) {
      plugins.push(new PluginClass(Class, _.rest(arguments)))
    }
  })

  Class.extend = function(inst, cls) {
    var SubClass = extendable.call(Class, inst, cls)
    makePluggable(SubClass, plugins)
    return SubClass
  }
}

module.exports = Plugin
<commit_msg>return plugin on addPlugin<commit_after>
var extendable = require('extendable')
var _ = require('underscore')
var async = require('async')

var methodBlacklist = ['constructor', 'initialize', 'run']

var Plugin = function(Class, args) {
  var methods = {}
  for (var key in this) {
    if (key.charAt(0) != '_' && !~methodBlacklist.indexOf(key) && typeof this[key] == 'function')
      methods[key] = this[key]
  }
  _.extend(Class.prototype, methods)
  this.initialize.apply(this, args)
}

// Instance members

_.extend(Plugin.prototype, {

  // Called once for each instace of the plugin.
  // Almost always before the extended Class is initialized
  initialize: function() {},

  // Called once for each instance of the extended Class
  // in the context of that instance
  run: function(instance, callback) { callback() }

})

// Class Members

_.extend(Plugin, {

  extend: extendable,

  makePluggable: makePluggable

})

function makePluggable(Class, plugins) {
  plugins = [].concat(plugins || [])

  // The instance methods added to
  // a Class that is made 'pluggable'
  _.extend(Class.prototype, {
    runPlugins: function(callback) {
      if (typeof callback != 'function') throw new Error('Callback not provided or not a function')
      var instance = this
      async.forEachSeries(plugins, function(plugin, cb) {
        plugin.run(instance, cb)
      }, callback)
    }
  })

  // The Class methods added to a
  // Class that is made 'pluggable'
  _.extend(Class, {
    addPlugin: function(PluginClass) {
      var plugin = new PluginClass(Class, _.rest(arguments))
      plugins.push(plugin)
      return plugin
    }
  })

  Class.extend = function(inst, cls) {
    var SubClass = extendable.call(Class, inst, cls)
    makePluggable(SubClass, plugins)
    return SubClass
  }
}

module.exports = Plugin
<|endoftext|>


<commit_before>'use strict';
var Mocha = require('mocha');
var colors = require('colors');
var build = require('./build.js');
var mocha = new Mocha({ui: 'bdd', reporter: 'list'});

mocha.addFile('test/test-jpegtran-path.js');

mocha.run(function (failures) {
	if (failures > 0) {
		build();
	} else {
		console.log('pre-build test passed successfully, skipping build'.green);
	}
});
<commit_msg>Improve message on failing prebuild tests<commit_after>'use strict';
var Mocha = require('mocha');
var colors = require('colors');
var build = require('./build.js');
var mocha = new Mocha({ui: 'bdd', reporter: 'min'});

mocha.addFile('test/test-jpegtran-path.js');

mocha.run(function (failures) {
	if (failures > 0) {
		console.log('pre-build test failed, compiling from source...'.red);
		build();
	} else {
		console.log('pre-build test passed successfully, skipping build...'.green);
	}
});
<|endoftext|>


<commit_before>// Copyright (c) 2015, Fujana Solutions - Moritz Maleck. All rights reserved.
// For licensing, see LICENSE.md

CKEDITOR.plugins.add( 'imageuploader', {
    init: function( editor ) {
        editor.config.filebrowserUploadUrl = 'ckeditor/plugins/imageuploader/imgupload.php';
        editor.config.filebrowserBrowseUrl = 'ckeditor/plugins/imageuploader/imgbrowser.php';
    }
});<commit_msg>Removed upload button from image panel<commit_after>// Copyright (c) 2015, Fujana Solutions - Moritz Maleck. All rights reserved.
// For licensing, see LICENSE.md

CKEDITOR.plugins.add( 'imageuploader', {
    init: function( editor ) {
        editor.config.filebrowserBrowseUrl = 'ckeditor/plugins/imageuploader/imgbrowser.php';
    }
});
<|endoftext|>


<commit_before>CKEDITOR.plugins.add('droploader', {
	init: function (editor) {

		var pluginDirectory = this.path;
		editor.addContentsCss(pluginDirectory + 'styles/droploader.css');

		function handleUpload(originalFilename, url) {
			if (isImg.test(url)) {
				var img = editor.document.$.querySelector(
					'[data-filename="' + originalFilename + '"]');
				img.setAttribute('src', url);
				img = new CKEDITOR.dom.element(img);
				img.removeClass('placeholder');
			} else if (isAnotherSupportedType.test(url)) {
				var link = new CKEDITOR.dom.element('a');
				link.setAttribute('href', url);
				link.textContents = url;
				editor.insertElement(link);
			}
		}

		var isImg = /.*\.(png|jpe?g|gif)$/;
		var isAnotherSupportedType = /\.(pdf)$/;

		function hasFiles (event) {
			// in Webkit types is an array, DOMStringList elsewhere
			var types = event.data.$.dataTransfer.types
			return ((types.indexOf && types.indexOf('Files') > -1) ||
					(types.contains && types.contains('Files'))
			)
		}

		editor.on('contentDom', function () {
			// this prevents page reload when dropping on empty document in Chrome
			editor.document.on('dragover', function(e) {
				if (hasFiles(e) &&
					e.data.getTarget().$.tagName == 'HTML') {
					e.data.$.preventDefault();
				}
				console.log(e.data.$.target.tagName);
			});

			var lastTarget;

			editor.document.on('dragenter', function(e) {
				if (hasFiles(e)) {
					e.data.stopPropagation();
					editor.document.getBody().addClass('droploader-dragover');
					lastTarget = e.data.$.target;
				};
			});

			editor.document.on('dragleave', function(e) {
				if (hasFiles(e)) {
					e.data.stopPropagation();
					if (lastTarget == e.data.$.target) {
						editor.document.getBody().removeClass('droploader-dragover');
					}
				};
			})

			editor.document.on('drop', function (e) {
				editor.document.getBody().removeClass('droploader-dragover');
				// Prepare dropped file for upload
				if (e.data.$.dataTransfer.files.length > 0) {
					e.data.$.preventDefault();
					var files = e.data.$.dataTransfer.files;
					var fd = new FormData();
				    // var filesToUpload = [];
					for (var i=0; i<files.length; i++) {
						var fileIsImage = isImg.test(files[i].name);
						var fileIsSupportedType = isAnotherSupportedType.test(files[i].name);
						if ( fileIsImage || fileIsSupportedType ) {
							fd.append('upload', files[i]);
							// filesToUpload.push(files[i].name);
						}
						if (fileIsImage) {
							var placeholder = new CKEDITOR.dom.element('img');
							placeholder.addClass('placeholder');
							placeholder.setAttribute('data-filename', files[i].name);
							editor.insertElement(placeholder);
							var fr = new FileReader();
							fr.onload = function(e) {
								placeholder.setAttribute('src', fr.result);
							}
							fr.onerror = function(e) {
								throw new Error('Cannot load file: ' + files[i].name);
							}
							fr.readAsDataURL(files[i]);

						}
						// make a handler which remembers the original filename
						// and tell CKEditor to store it for execution
						fileUploadedHandler = CKEDITOR.tools.addFunction(
							handleUpload.bind(null, files[i].name));

						var xhr = new XMLHttpRequest();
						xhr.open('POST', editor.config.filebrowserUploadUrl +
							'?CKEditorFuncNum=' + fileUploadedHandler);
						xhr.responseType = 'document';
						xhr.onload = function (e) {
							if (this.status == 200) {
								//  run the callback returned as script tag
								callbackScript = this.response.getElementsByTagName('script');
								if (callbackScript.length > 0) {
									var responseCallback = new Function("", callbackScript[0].innerHTML);
									responseCallback();
								}
							}
						}
						xhr.send(fd);
					}
				}
			});
		});
	}
});
<commit_msg>Remove unused code<commit_after>CKEDITOR.plugins.add('droploader', {
	init: function (editor) {

		var pluginDirectory = this.path;
		editor.addContentsCss(pluginDirectory + 'styles/droploader.css');

		function handleUpload(originalFilename, url) {
			if (isImg.test(url)) {
				var img = editor.document.$.querySelector(
					'[data-filename="' + originalFilename + '"]');
				img.setAttribute('src', url);
				img = new CKEDITOR.dom.element(img);
				img.removeClass('placeholder');
			} else if (isAnotherSupportedType.test(url)) {
				var link = new CKEDITOR.dom.element('a');
				link.setAttribute('href', url);
				link.textContents = url;
				editor.insertElement(link);
			}
		}

		var isImg = /.*\.(png|jpe?g|gif)$/;
		var isAnotherSupportedType = /\.(pdf)$/;

		function hasFiles (event) {
			// in Webkit types is an array, DOMStringList elsewhere
			var types = event.data.$.dataTransfer.types
			return ((types.indexOf && types.indexOf('Files') > -1) ||
					(types.contains && types.contains('Files'))
			)
		}

		editor.on('contentDom', function () {
			// this prevents page reload when dropping on empty document in Chrome
			editor.document.on('dragover', function(e) {
				if (hasFiles(e) &&
					e.data.getTarget().$.tagName == 'HTML') {
					e.data.$.preventDefault();
				}
				console.log(e.data.$.target.tagName);
			});

			var lastTarget;

			editor.document.on('dragenter', function(e) {
				if (hasFiles(e)) {
					e.data.stopPropagation();
					editor.document.getBody().addClass('droploader-dragover');
					lastTarget = e.data.$.target;
				};
			});

			editor.document.on('dragleave', function(e) {
				if (hasFiles(e)) {
					e.data.stopPropagation();
					if (lastTarget == e.data.$.target) {
						editor.document.getBody().removeClass('droploader-dragover');
					}
				};
			})

			editor.document.on('drop', function (e) {
				editor.document.getBody().removeClass('droploader-dragover');
				// Prepare dropped file for upload
				if (e.data.$.dataTransfer.files.length > 0) {
					e.data.$.preventDefault();
					var files = e.data.$.dataTransfer.files;
					var fd = new FormData();
					for (var i=0; i<files.length; i++) {
						var fileIsImage = isImg.test(files[i].name);
						var fileIsSupportedType = isAnotherSupportedType.test(files[i].name);
						if ( fileIsImage || fileIsSupportedType ) {
							fd.append('upload', files[i]);
						}
						if (fileIsImage) {
							var placeholder = new CKEDITOR.dom.element('img');
							placeholder.addClass('placeholder');
							placeholder.setAttribute('data-filename', files[i].name);
							editor.insertElement(placeholder);
							var fr = new FileReader();
							fr.onload = function(e) {
								placeholder.setAttribute('src', fr.result);
							}
							fr.onerror = function(e) {
								throw new Error('Cannot load file: ' + files[i].name);
							}
							fr.readAsDataURL(files[i]);

						}
						// make a handler which remembers the original filename
						// and tell CKEditor to store it for execution
						fileUploadedHandler = CKEDITOR.tools.addFunction(
							handleUpload.bind(null, files[i].name));

						var xhr = new XMLHttpRequest();
						xhr.open('POST', editor.config.filebrowserUploadUrl +
							'?CKEditorFuncNum=' + fileUploadedHandler);
						xhr.responseType = 'document';
						xhr.onload = function (e) {
							if (this.status == 200) {
								//  run the callback returned as script tag
								callbackScript = this.response.getElementsByTagName('script');
								if (callbackScript.length > 0) {
									var responseCallback = new Function("", callbackScript[0].innerHTML);
									responseCallback();
								}
							}
						}
						xhr.send(fd);
					}
				}
			});
		});
	}
});
<|endoftext|>


<commit_before>'use babel'

const fs = require('fs-plus')
const path = require('path')
const temp = require('temp')
const Git = require('nodegit')
const CompositeDisposable = require('event-kit').CompositeDisposable

temp.track()

const GitRepositoryAsync = require('../src/git-repository-async')

function openFixture(fixture) {
  return GitRepositoryAsync.open(path.join(__dirname, 'fixtures', 'git', fixture))
}

function copyRepository() {
  let workingDirPath = temp.mkdirSync('atom-working-dir')
  fs.copySync(path.join(__dirname, 'fixtures', 'git', 'working-dir'), workingDirPath)
  fs.renameSync(path.join(workingDirPath, 'git.git'), path.join(workingDirPath, '.git'))
  return fs.realpathSync(workingDirPath)
}

function asyncIt(name, fn) {
  it(name, () => {
    waitsForPromise(fn)
  })
}

function xasyncIt(name, fn) {
  xit(name, () => {
    waitsForPromise(fn)
  })
}

fdescribe('GitRepositoryAsync-js', () => {
  let repo

  afterEach(() => {
    if (repo != null) repo.destroy()
  })

  describe('@open(path)', () => {
    asyncIt('repo is null when no repository is found', async () => {
      repo = GitRepositoryAsync.open(path.join(temp.dir, 'nogit.txt'))

      let threw = false
      try {
        await repo.repoPromise
      } catch(e) {
        threw = true
      }

      expect(threw).toBeTruthy()
      expect(repo.repo).toBe(null)
    })
  })

  describe('.getPath()', () => {
    xit('returns the repository path for a .git directory path')

    asyncIt('returns the repository path for a repository path', async () => {
      repo = openFixture('master.git')
      let repoPath = await repo.getPath()
      expect(repoPath).toBe(path.join(__dirname, 'fixtures', 'git', 'master.git'))
    })
  })

  describe('.isPathIgnored(path)', () => {
    asyncIt('resolves true for an ignored path', async () => {
      repo = openFixture('ignore.git')
      let ignored = await repo.isPathIgnored('a.txt')
      expect(ignored).toBeTruthy()
    })

    asyncIt('resolves false for a non-ignored path', async () => {
      repo = openFixture('ignore.git')
      let ignored = await repo.isPathIgnored('b.txt')
      expect(ignored).toBeFalsy()
    })
  })

  describe('.isPathModified(path)', () => {
    let filePath, newPath, emptyPath

    beforeEach(() => {
      let workingDirPath = copyRepository()
      repo = GitRepositoryAsync.open(workingDirPath)
      filePath = path.join(workingDirPath, 'a.txt')
      newPath = path.join(workingDirPath, 'new-path.txt')
      fs.writeFileSync(newPath, "i'm new here")
      emptyPath = path.join(workingDirPath, 'empty-path.txt')
    })

    describe('when the path is unstaged', () => {
      asyncIt('resolves false if the path has not been modified', async () => {
        let modified = await repo.isPathModified(filePath)
        expect(modified).toBeFalsy()
      })

      asyncIt('resolves true if the path is modified', async () => {
        fs.writeFileSync(filePath, "change")
        let modified = await repo.isPathModified(filePath)
        expect(modified).toBeTruthy()
      })

      asyncIt('resolves false if the path is new', async () => {
        let modified = await repo.isPathModified(newPath)
        expect(modified).toBeFalsy()
      })

      asyncIt('resolves false if the path is invalid', async () => {
        let modified = await repo.isPathModified(emptyPath)
        expect(modified).toBeFalsy()
      })
    })
  })

  describe('.isPathNew(path)', () => {
    let filePath, newPath

    beforeEach(() => {
      let workingDirPath = copyRepository()
      repo = GitRepositoryAsync.open(workingDirPath)
      filePath = path.join(workingDirPath, 'a.txt')
      newPath = path.join(workingDirPath, 'new-path.txt')
      fs.writeFileSync(newPath, "i'm new here")
    })

    describe('when the path is unstaged', () => {
      asyncIt('returns true if the path is new', async () => {
        let isNew = await repo.isPathNew(newPath)
        expect(isNew).toBeTruthy()
      })

      asyncIt("returns false if the path isn't new", async () => {
        let modified = await repo.isPathModified(newPath)
        expect(modified).toBeFalsy()
      })
    })
  })

  describe('.checkoutHead(path)', () => {
    let filePath

    beforeEach(() => {
      let workingDirPath = copyRepository()
      repo = GitRepositoryAsync.open(workingDirPath)
      filePath = path.join(workingDirPath, 'a.txt')
    })

    asyncIt('no longer reports a path as modified after checkout', async () => {
      let modified = await repo.isPathModified(filePath)
      expect(modified).toBeFalsy()

      fs.writeFileSync(filePath, 'ch ch changes')

      modified = await repo.isPathModified(filePath)
      expect(modified).toBeTruthy()

      await repo.checkoutHead(filePath)

      modified = await repo.isPathModified(filePath)
      expect(modified).toBeFalsy()
    })

    asyncIt('restores the contents of the path to the original text', async () => {
      fs.writeFileSync(filePath, 'ch ch changes')
      await repo.checkoutHead(filePath)
      expect(fs.readFileSync(filePath, 'utf8')).toBe('')
    })

    asyncIt('fires a did-change-status event if the checkout completes successfully', async () => {
      fs.writeFileSync(filePath, 'ch ch changes')

      await repo.getPathStatus(filePath)

      let statusHandler = jasmine.createSpy('statusHandler')
      repo.onDidChangeStatus(statusHandler)

      await repo.checkoutHead(filePath)

      expect(statusHandler.callCount).toBe(1)
      expect(statusHandler.argsForCall[0][0]).toEqual({path: filePath, pathStatus: 0})

      await repo.checkoutHead(filePath)
      expect(statusHandler.callCount).toBe(1)
    })
  })

  xdescribe('.checkoutHeadForEditor(editor)', () => {
    let filePath, editor

    beforeEach(() => {
      let workingDirPath = copyRepository()
      repo = GitRepositoryAsync.open(workingDirPath)
      filePath = path.join(workingDirPath, 'a.txt')
      fs.writeFileSync(filePath, 'ch ch changes')

      waitsForPromise(() => atom.workspace.open(filePath))
      runs(() => editor = atom.workspace.getActiveTextEditor())
    })

    xit('displays a confirmation dialog by default', () => {
      spyOn(atom, 'confirm').andCallFake(buttons, () => buttons[0].OK())
      atom.config.set('editor.confirmCheckoutHeadRevision', true)

      waitsForPromise(() => repo.checkoutHeadForEditor(editor))
      runs(() => expect(fs.readFileSync(filePath, 'utf8')).toBe(''))
    })

    xit('does not display a dialog when confirmation is disabled', () => {
      spyOn(atom, 'confirm')
      atom.config.set('editor.confirmCheckoutHeadRevision', false)

      waitsForPromise(() => repo.checkoutHeadForEditor(editor))
      runs(() => {
        expect(fs.readFileSync(filePath, 'utf8')).toBe('')
        expect(atom.confirm).not.toHaveBeenCalled()
      })
    })
  })

  describe('.getPathStatus(path)', () => {
    let filePath

    beforeEach(() => {
      let workingDirectory = copyRepository()
      repo = GitRepositoryAsync.open(workingDirectory)
      filePath = path.join(workingDirectory, 'file.txt')
    })

    asyncIt('trigger a status-changed event when the new status differs from the last cached one', async () => {
      let statusHandler = jasmine.createSpy("statusHandler")
      repo.onDidChangeStatus(statusHandler)
      fs.writeFileSync(filePath, '')

      await repo.getPathStatus(filePath)

      expect(statusHandler.callCount).toBe(1)
      let status = Git.Status.STATUS.WT_MODIFIED
      expect(statusHandler.argsForCall[0][0]).toEqual({path: filePath, pathStatus: status})
      fs.writeFileSync(filePath, 'abc')

      await repo.getPathStatus(filePath)
      expect(statusHandler.callCount).toBe(1)
    })
  })

  describe('.getDirectoryStatus(path)', () => {
    let directoryPath, filePath

    beforeEach(() => {
      let workingDirectory = copyRepository()
      repo = GitRepositoryAsync.open(workingDirectory)
      directoryPath = path.join(workingDirectory, 'dir')
      filePath = path.join(directoryPath, 'b.txt')
    })

    asyncIt('gets the status based on the files inside the directory', async () => {
      await repo.checkoutHead(filePath)

      let result = await repo.getDirectoryStatus(directoryPath)
      expect(repo.isStatusModified(result)).toBe(false)

      fs.writeFileSync(filePath, 'abc')

      result = await repo.getDirectoryStatus(directoryPath)
      expect(repo.isStatusModified(result)).toBe(true)
    })
  })

  describe('.refreshStatus()', () => {
    let newPath, modifiedPath, cleanPath, originalModifiedPathText

    beforeEach(() => {
      let workingDirectory = copyRepository()
      repo = GitRepositoryAsync.open(workingDirectory)
      modifiedPath = path.join(workingDirectory, 'file.txt')
      newPath = path.join(workingDirectory, 'untracked.txt')
      cleanPath = path.join(workingDirectory, 'other.txt')
      fs.writeFileSync(cleanPath, 'Full of text')
      fs.writeFileSync(newPath, '')
      newPath = fs.absolute(newPath) // specs could be running under symbol path.
    })

    asyncIt('returns status information for all new and modified files', async () => {
      fs.writeFileSync(modifiedPath, 'making this path modified')
      await repo.refreshStatus()

      expect(await repo.getCachedPathStatus(cleanPath)).toBeUndefined()
      expect(repo.isStatusNew(await repo.getCachedPathStatus(newPath))).toBeTruthy()
      expect(repo.isStatusModified(await repo.getCachedPathStatus(modifiedPath))).toBeTruthy()
    })
  })

  describe('buffer events', () => {
    beforeEach(() => {
      // This is sync, should be fine in a beforeEach
      atom.project.setPaths([copyRepository()])
    })

    asyncIt('emits a status-changed event when a buffer is saved', async () => {
      let editor = await atom.workspace.open('other.txt')

      editor.insertNewline()

      let repository = atom.project.getRepositories()[0].async
      let called
      repository.onDidChangeStatus(c => called = c)
      editor.save()

      waitsFor(() => Boolean(called))
      runs(() => expect(called).toEqual({path: editor.getPath(), pathStatus: 256}))
    })

    asyncIt('emits a status-changed event when a buffer is reloaded', async () => {
      let statusHandler = jasmine.createSpy('statusHandler')
      let reloadHandler = jasmine.createSpy('reloadHandler')

      let editor = await atom.workspace.open('other.txt')

      fs.writeFileSync(editor.getPath(), 'changed')

      let repository = atom.project.getRepositories()[0].async
      repository.onDidChangeStatus(statusHandler)
      editor.getBuffer().reload()

      waitsFor(() => statusHandler.callCount > 0)
      runs(() => {
        expect(statusHandler.callCount).toBe(1)
        expect(statusHandler).toHaveBeenCalledWith({path: editor.getPath(), pathStatus: 256})

        let buffer = editor.getBuffer()
        buffer.onDidReload(reloadHandler)
        buffer.reload()

        waitsFor(() => reloadHandler.callCount > 0)
        runs(() => expect(statusHandler.callCount).toBe(1))
      })
    })

    asyncIt("emits a status-changed event when a buffer's path changes", async () => {
      let editor = await atom.workspace.open('other.txt')

      fs.writeFileSync(editor.getPath(), 'changed')

      let statusHandler = jasmine.createSpy('statusHandler')
      let repository = atom.project.getRepositories()[0].async
      repository.onDidChangeStatus(statusHandler)
      editor.getBuffer().emitter.emit('did-change-path')
      waitsFor(() => statusHandler.callCount > 0)
      runs(() => {
        expect(statusHandler.callCount).toBe(1)
        expect(statusHandler).toHaveBeenCalledWith({path: editor.getPath(), pathStatus: 256})

        let pathHandler = jasmine.createSpy('pathHandler')
        let buffer = editor.getBuffer()
        buffer.onDidChangePath(pathHandler)
        buffer.emitter.emit('did-change-path')

        waitsFor(() => pathHandler.callCount > 0)
        runs(() => expect(statusHandler.callCount).toBe(1))
      })
    })

    xasyncIt('stops listening to the buffer when the repository is destroyed (regression)', async () => {
      let editor = await atom.workspace.open('other.txt')
      atom.project.getRepositories()[0].destroy()
      expect(() => editor.save()).not.toThrow()
    })
  })

  xdescribe('GitRepositoryAsync::relativize(filePath)')

})
<commit_msg>Revert "await getCachedPathStatus in specs"<commit_after>'use babel'

const fs = require('fs-plus')
const path = require('path')
const temp = require('temp')
const Git = require('nodegit')
const CompositeDisposable = require('event-kit').CompositeDisposable

temp.track()

const GitRepositoryAsync = require('../src/git-repository-async')

function openFixture(fixture) {
  return GitRepositoryAsync.open(path.join(__dirname, 'fixtures', 'git', fixture))
}

function copyRepository() {
  let workingDirPath = temp.mkdirSync('atom-working-dir')
  fs.copySync(path.join(__dirname, 'fixtures', 'git', 'working-dir'), workingDirPath)
  fs.renameSync(path.join(workingDirPath, 'git.git'), path.join(workingDirPath, '.git'))
  return fs.realpathSync(workingDirPath)
}

function asyncIt(name, fn) {
  it(name, () => {
    waitsForPromise(fn)
  })
}

function xasyncIt(name, fn) {
  xit(name, () => {
    waitsForPromise(fn)
  })
}

fdescribe('GitRepositoryAsync-js', () => {
  let repo

  afterEach(() => {
    if (repo != null) repo.destroy()
  })

  describe('@open(path)', () => {
    asyncIt('repo is null when no repository is found', async () => {
      repo = GitRepositoryAsync.open(path.join(temp.dir, 'nogit.txt'))

      let threw = false
      try {
        await repo.repoPromise
      } catch(e) {
        threw = true
      }

      expect(threw).toBeTruthy()
      expect(repo.repo).toBe(null)
    })
  })

  describe('.getPath()', () => {
    xit('returns the repository path for a .git directory path')

    asyncIt('returns the repository path for a repository path', async () => {
      repo = openFixture('master.git')
      let repoPath = await repo.getPath()
      expect(repoPath).toBe(path.join(__dirname, 'fixtures', 'git', 'master.git'))
    })
  })

  describe('.isPathIgnored(path)', () => {
    asyncIt('resolves true for an ignored path', async () => {
      repo = openFixture('ignore.git')
      let ignored = await repo.isPathIgnored('a.txt')
      expect(ignored).toBeTruthy()
    })

    asyncIt('resolves false for a non-ignored path', async () => {
      repo = openFixture('ignore.git')
      let ignored = await repo.isPathIgnored('b.txt')
      expect(ignored).toBeFalsy()
    })
  })

  describe('.isPathModified(path)', () => {
    let filePath, newPath, emptyPath

    beforeEach(() => {
      let workingDirPath = copyRepository()
      repo = GitRepositoryAsync.open(workingDirPath)
      filePath = path.join(workingDirPath, 'a.txt')
      newPath = path.join(workingDirPath, 'new-path.txt')
      fs.writeFileSync(newPath, "i'm new here")
      emptyPath = path.join(workingDirPath, 'empty-path.txt')
    })

    describe('when the path is unstaged', () => {
      asyncIt('resolves false if the path has not been modified', async () => {
        let modified = await repo.isPathModified(filePath)
        expect(modified).toBeFalsy()
      })

      asyncIt('resolves true if the path is modified', async () => {
        fs.writeFileSync(filePath, "change")
        let modified = await repo.isPathModified(filePath)
        expect(modified).toBeTruthy()
      })

      asyncIt('resolves false if the path is new', async () => {
        let modified = await repo.isPathModified(newPath)
        expect(modified).toBeFalsy()
      })

      asyncIt('resolves false if the path is invalid', async () => {
        let modified = await repo.isPathModified(emptyPath)
        expect(modified).toBeFalsy()
      })
    })
  })

  describe('.isPathNew(path)', () => {
    let filePath, newPath

    beforeEach(() => {
      let workingDirPath = copyRepository()
      repo = GitRepositoryAsync.open(workingDirPath)
      filePath = path.join(workingDirPath, 'a.txt')
      newPath = path.join(workingDirPath, 'new-path.txt')
      fs.writeFileSync(newPath, "i'm new here")
    })

    describe('when the path is unstaged', () => {
      asyncIt('returns true if the path is new', async () => {
        let isNew = await repo.isPathNew(newPath)
        expect(isNew).toBeTruthy()
      })

      asyncIt("returns false if the path isn't new", async () => {
        let modified = await repo.isPathModified(newPath)
        expect(modified).toBeFalsy()
      })
    })
  })

  describe('.checkoutHead(path)', () => {
    let filePath

    beforeEach(() => {
      let workingDirPath = copyRepository()
      repo = GitRepositoryAsync.open(workingDirPath)
      filePath = path.join(workingDirPath, 'a.txt')
    })

    asyncIt('no longer reports a path as modified after checkout', async () => {
      let modified = await repo.isPathModified(filePath)
      expect(modified).toBeFalsy()

      fs.writeFileSync(filePath, 'ch ch changes')

      modified = await repo.isPathModified(filePath)
      expect(modified).toBeTruthy()

      await repo.checkoutHead(filePath)

      modified = await repo.isPathModified(filePath)
      expect(modified).toBeFalsy()
    })

    asyncIt('restores the contents of the path to the original text', async () => {
      fs.writeFileSync(filePath, 'ch ch changes')
      await repo.checkoutHead(filePath)
      expect(fs.readFileSync(filePath, 'utf8')).toBe('')
    })

    asyncIt('fires a did-change-status event if the checkout completes successfully', async () => {
      fs.writeFileSync(filePath, 'ch ch changes')

      await repo.getPathStatus(filePath)

      let statusHandler = jasmine.createSpy('statusHandler')
      repo.onDidChangeStatus(statusHandler)

      await repo.checkoutHead(filePath)

      expect(statusHandler.callCount).toBe(1)
      expect(statusHandler.argsForCall[0][0]).toEqual({path: filePath, pathStatus: 0})

      await repo.checkoutHead(filePath)
      expect(statusHandler.callCount).toBe(1)
    })
  })

  xdescribe('.checkoutHeadForEditor(editor)', () => {
    let filePath, editor

    beforeEach(() => {
      let workingDirPath = copyRepository()
      repo = GitRepositoryAsync.open(workingDirPath)
      filePath = path.join(workingDirPath, 'a.txt')
      fs.writeFileSync(filePath, 'ch ch changes')

      waitsForPromise(() => atom.workspace.open(filePath))
      runs(() => editor = atom.workspace.getActiveTextEditor())
    })

    xit('displays a confirmation dialog by default', () => {
      spyOn(atom, 'confirm').andCallFake(buttons, () => buttons[0].OK())
      atom.config.set('editor.confirmCheckoutHeadRevision', true)

      waitsForPromise(() => repo.checkoutHeadForEditor(editor))
      runs(() => expect(fs.readFileSync(filePath, 'utf8')).toBe(''))
    })

    xit('does not display a dialog when confirmation is disabled', () => {
      spyOn(atom, 'confirm')
      atom.config.set('editor.confirmCheckoutHeadRevision', false)

      waitsForPromise(() => repo.checkoutHeadForEditor(editor))
      runs(() => {
        expect(fs.readFileSync(filePath, 'utf8')).toBe('')
        expect(atom.confirm).not.toHaveBeenCalled()
      })
    })
  })

  describe('.getPathStatus(path)', () => {
    let filePath

    beforeEach(() => {
      let workingDirectory = copyRepository()
      repo = GitRepositoryAsync.open(workingDirectory)
      filePath = path.join(workingDirectory, 'file.txt')
    })

    asyncIt('trigger a status-changed event when the new status differs from the last cached one', async () => {
      let statusHandler = jasmine.createSpy("statusHandler")
      repo.onDidChangeStatus(statusHandler)
      fs.writeFileSync(filePath, '')

      await repo.getPathStatus(filePath)

      expect(statusHandler.callCount).toBe(1)
      let status = Git.Status.STATUS.WT_MODIFIED
      expect(statusHandler.argsForCall[0][0]).toEqual({path: filePath, pathStatus: status})
      fs.writeFileSync(filePath, 'abc')

      await repo.getPathStatus(filePath)
      expect(statusHandler.callCount).toBe(1)
    })
  })

  describe('.getDirectoryStatus(path)', () => {
    let directoryPath, filePath

    beforeEach(() => {
      let workingDirectory = copyRepository()
      repo = GitRepositoryAsync.open(workingDirectory)
      directoryPath = path.join(workingDirectory, 'dir')
      filePath = path.join(directoryPath, 'b.txt')
    })

    asyncIt('gets the status based on the files inside the directory', async () => {
      await repo.checkoutHead(filePath)

      let result = await repo.getDirectoryStatus(directoryPath)
      expect(repo.isStatusModified(result)).toBe(false)

      fs.writeFileSync(filePath, 'abc')

      result = await repo.getDirectoryStatus(directoryPath)
      expect(repo.isStatusModified(result)).toBe(true)
    })
  })

  describe('.refreshStatus()', () => {
    let newPath, modifiedPath, cleanPath, originalModifiedPathText

    beforeEach(() => {
      let workingDirectory = copyRepository()
      repo = GitRepositoryAsync.open(workingDirectory)
      modifiedPath = path.join(workingDirectory, 'file.txt')
      newPath = path.join(workingDirectory, 'untracked.txt')
      cleanPath = path.join(workingDirectory, 'other.txt')
      fs.writeFileSync(cleanPath, 'Full of text')
      fs.writeFileSync(newPath, '')
      newPath = fs.absolute(newPath) // specs could be running under symbol path.
    })

    asyncIt('returns status information for all new and modified files', async () => {
      fs.writeFileSync(modifiedPath, 'making this path modified')
      await repo.refreshStatus()

      expect(repo.getCachedPathStatus(cleanPath)).toBeUndefined()
      expect(repo.isStatusNew(repo.getCachedPathStatus(newPath))).toBeTruthy()
      expect(repo.isStatusModified(repo.getCachedPathStatus(modifiedPath))).toBeTruthy()
    })
  })

  describe('buffer events', () => {
    beforeEach(() => {
      // This is sync, should be fine in a beforeEach
      atom.project.setPaths([copyRepository()])
    })

    asyncIt('emits a status-changed event when a buffer is saved', async () => {
      let editor = await atom.workspace.open('other.txt')

      editor.insertNewline()

      let repository = atom.project.getRepositories()[0].async
      let called
      repository.onDidChangeStatus(c => called = c)
      editor.save()

      waitsFor(() => Boolean(called))
      runs(() => expect(called).toEqual({path: editor.getPath(), pathStatus: 256}))
    })

    asyncIt('emits a status-changed event when a buffer is reloaded', async () => {
      let statusHandler = jasmine.createSpy('statusHandler')
      let reloadHandler = jasmine.createSpy('reloadHandler')

      let editor = await atom.workspace.open('other.txt')

      fs.writeFileSync(editor.getPath(), 'changed')

      let repository = atom.project.getRepositories()[0].async
      repository.onDidChangeStatus(statusHandler)
      editor.getBuffer().reload()

      waitsFor(() => statusHandler.callCount > 0)
      runs(() => {
        expect(statusHandler.callCount).toBe(1)
        expect(statusHandler).toHaveBeenCalledWith({path: editor.getPath(), pathStatus: 256})

        let buffer = editor.getBuffer()
        buffer.onDidReload(reloadHandler)
        buffer.reload()

        waitsFor(() => reloadHandler.callCount > 0)
        runs(() => expect(statusHandler.callCount).toBe(1))
      })
    })

    asyncIt("emits a status-changed event when a buffer's path changes", async () => {
      let editor = await atom.workspace.open('other.txt')

      fs.writeFileSync(editor.getPath(), 'changed')

      let statusHandler = jasmine.createSpy('statusHandler')
      let repository = atom.project.getRepositories()[0].async
      repository.onDidChangeStatus(statusHandler)
      editor.getBuffer().emitter.emit('did-change-path')
      waitsFor(() => statusHandler.callCount > 0)
      runs(() => {
        expect(statusHandler.callCount).toBe(1)
        expect(statusHandler).toHaveBeenCalledWith({path: editor.getPath(), pathStatus: 256})

        let pathHandler = jasmine.createSpy('pathHandler')
        let buffer = editor.getBuffer()
        buffer.onDidChangePath(pathHandler)
        buffer.emitter.emit('did-change-path')

        waitsFor(() => pathHandler.callCount > 0)
        runs(() => expect(statusHandler.callCount).toBe(1))
      })
    })

    xasyncIt('stops listening to the buffer when the repository is destroyed (regression)', async () => {
      let editor = await atom.workspace.open('other.txt')
      atom.project.getRepositories()[0].destroy()
      expect(() => editor.save()).not.toThrow()
    })
  })

  xdescribe('GitRepositoryAsync::relativize(filePath)')

})
<|endoftext|>


<commit_before>describe("Dropdown: ", function() {
  beforeEach(function() {
    loadFixtures('dropdown_fixture.html');
    locastyle.dropdown.init();
  });

  describe("Dropdown toggle", function() {
    describe('when click on a dropdown trigger', function() {
      it("should activate a disabled related dropdown module", function() {
        // Added as pending because the tests broke while I was testing other functionality
        $("#dropdown-test > a:first-child").trigger("click");
        expect($("#dropdown-test").hasClass("ls-active")).toEqual(true);
      });

      it("should disable an active related dropdown module", function() {
        // Added as pending because the tests broke while I was testing other functionality
        $("#dropdown-test-2 > a:first-child").trigger("click");
        expect($("#dropdown-test-2").hasClass("ls-active")).toEqual(false);
      });

      it("should prevent default event on dropdown module", function() {
        // Added as pending because the tests broke while I was testing other functionality
        var spyEvent = spyOnEvent('#dropdown-test > a:first-child', 'click');
        $("#dropdown-test > a:first-child").trigger("click");
        expect(spyEvent).toHaveBeenPrevented();
      });

      it("should close any opened dropdown", function() {
        // Added as pending because the tests broke while I was testing other functionality
        $("#dropdown-test-4 #dropdown-default > a:first-child").trigger("click");
        expect($("#dropdown-test-4 #dropdown-active").hasClass("ls-active")).toEqual(false);
      });

    });

    describe("When click outside dropdown click", function() {
      it("should close opened dropdown", function() {
        $("#fake-body").trigger("click");
        expect($("#dropdown-test-3").hasClass("ls-active")).toEqual(false);
      });
    });

    describe("When dropdown is disabled", function() {
      it("the parent should not have .ls-active", function() {
        $("#dropdown-test-5 .ls-btn-primary").trigger("click");
        expect($("#dropdown-test-5").hasClass("ls-active")).toEqual(false);
      });
    });

  });

  describe("Unbind:", function() {
    describe("when unbind is called in module init", function() {
      it("should prevent toggleDropdown from being called twice or more times", function() {
        // Added as pending because the tests broke while I was testing other functionality
        var spy = spyOn(locastyle.dropdown, "toggleDropdown");
        locastyle.dropdown.init();
        locastyle.dropdown.init();
        $("#dropdown-test > a:first-child").trigger("click");
        expect(locastyle.dropdown.toggleDropdown.calls.count()).toEqual(1);
      });

      it("should prevent closeDropdown from being called twice or more times", function() {
        var spy = spyOn(locastyle.dropdown, "closeDropdown");
        locastyle.dropdown.init();
        locastyle.dropdown.init();
        $("#fake-body").trigger("click");
        expect(locastyle.dropdown.closeDropdown.calls.count()).toEqual(1);
      });

      it("should NOT unbind common events handled by other code", function() {
        window.test = {
          method: function(){
            //my fake function
          }
        };
        var spy = spyOn(window.test, "method");
        $("#dropdown-test > a:first-child").on("click", function () {
          window.test.method();
        });
        locastyle.dropdown.unbind();
        $("#dropdown-test > a:first-child").trigger("click");
        expect(window.test.method).toHaveBeenCalled();
      });
    });
  });

  describe("Dropdown with waia-ria", function() {
    it("Button should has attr role with value combobox", function() {
      expect($('#dropdown-test-6 > .ls-btn-primary').attr('role')).toEqual('combobox');
    });

    it("Links should has attr role with value option", function() {
      expect($('#dropdown-test-6 > .ls-dropdown-nav').find('a').attr('role')).toEqual('option');
    });

    it("Button should has attr aria-expanded with value false", function() {
      expect($('#dropdown-test-6 > .ls-btn-primary').attr('aria-expanded')).toEqual('false');
    });

    it("Nav links should has attr aria-hidden with value true", function() {
      expect($('.ls-dropdown-nav').attr('aria-hidden')).toEqual('true');
    });

    it("When click the button should has attr aria-expanded with value true", function() {
      $('.ls-dropdown').find('.ls-btn-primary').trigger('click');
      expect($('#dropdown-test-6 > .ls-btn-primary').attr('aria-expanded')).toEqual('true');
    });

    it("When click the nav links should has attr aria-hidden with value false", function() {
      $('#dropdown-test-6').find('.ls-btn-primary').trigger('click');
      expect($('#dropdown-test-6 > .ls-dropdown-nav').attr('aria-hidden')).toEqual('false');
    });

    it("When click in dropdown should has attr aria-hidden with value true in others dropdowns", function() {
      $('#dropdown-test-6').find('.ls-btn-primary').trigger('click');
      expect($('#dropdown-test-5 > .ls-dropdown-nav').attr('aria-hidden')).toEqual('true');
    });

    it("When click in dropdown should has attr aria-expanded with value false in others dropdowns", function() {
      $('#dropdown-test-6').find('.ls-btn-primary').trigger('click');
      expect($('#dropdown-test-5 > .ls-btn-primary').attr('aria-expanded')).toEqual('false');
    });
  });

});
<commit_msg>split dropdown tests in contexts opened/closed<commit_after>describe("Dropdown: ", function() {
  beforeEach(function() {
    loadFixtures('dropdown_fixture.html');
    locastyle.dropdown.init();
  });

  describe("Dropdown toggle", function() {
    describe('when click on a dropdown trigger', function() {
      it("should prevent default event on dropdown module", function() {
        // Added as pending because the tests broke while I was testing other functionality
        var spyEvent = spyOnEvent('#dropdown-test > a:first-child', 'click');
        $("#dropdown-test > a:first-child").trigger("click");
        expect(spyEvent).toHaveBeenPrevented();
      });

      describe('And dropdown is closed', function() {
        it("should activate a disabled related dropdown module", function() {
          // Added as pending because the tests broke while I was testing other functionality
          $("#dropdown-test > a:first-child").trigger("click");
          expect($("#dropdown-test").hasClass("ls-active")).toEqual(true);
        });
      });

      describe("And dropdown is opened", function() {
        it("should disable an active related dropdown module", function() {
          // Added as pending because the tests broke while I was testing other functionality
          $("#dropdown-test-2 > a:first-child").trigger("click");
          expect($("#dropdown-test-2").hasClass("ls-active")).toEqual(false);
        });

        it("should close any opened dropdown", function() {
          // Added as pending because the tests broke while I was testing other functionality
          $("#dropdown-test-4 #dropdown-default > a:first-child").trigger("click");
          expect($("#dropdown-test-4 #dropdown-active").hasClass("ls-active")).toEqual(false);
        });
      });
    });

    describe("When click outside dropdown click", function() {
      it("should close opened dropdown", function() {
        $("#fake-body").trigger("click");
        expect($("#dropdown-test-3").hasClass("ls-active")).toEqual(false);
      });
    });

    describe("When dropdown is disabled", function() {
      it("the parent should not have .ls-active", function() {
        $("#dropdown-test-5 .ls-btn-primary").trigger("click");
        expect($("#dropdown-test-5").hasClass("ls-active")).toEqual(false);
      });
    });

  });

  describe("Unbind:", function() {
    describe("when unbind is called in module init", function() {
      it("should prevent toggleDropdown from being called twice or more times", function() {
        // Added as pending because the tests broke while I was testing other functionality
        var spy = spyOn(locastyle.dropdown, "toggleDropdown");
        locastyle.dropdown.init();
        locastyle.dropdown.init();
        $("#dropdown-test > a:first-child").trigger("click");
        expect(locastyle.dropdown.toggleDropdown.calls.count()).toEqual(1);
      });

      it("should prevent closeDropdown from being called twice or more times", function() {
        var spy = spyOn(locastyle.dropdown, "closeDropdown");
        locastyle.dropdown.init();
        locastyle.dropdown.init();
        $("#fake-body").trigger("click");
        expect(locastyle.dropdown.closeDropdown.calls.count()).toEqual(1);
      });

      it("should NOT unbind common events handled by other code", function() {
        window.test = {
          method: function(){
            //my fake function
          }
        };
        var spy = spyOn(window.test, "method");
        $("#dropdown-test > a:first-child").on("click", function () {
          window.test.method();
        });
        locastyle.dropdown.unbind();
        $("#dropdown-test > a:first-child").trigger("click");
        expect(window.test.method).toHaveBeenCalled();
      });
    });
  });

  describe("Dropdown with waia-ria", function() {
    it("Button should has attr role with value combobox", function() {
      expect($('#dropdown-test-6 > .ls-btn-primary').attr('role')).toEqual('combobox');
    });

    it("Links should has attr role with value option", function() {
      expect($('#dropdown-test-6 > .ls-dropdown-nav').find('a').attr('role')).toEqual('option');
    });

    it("Button should has attr aria-expanded with value false", function() {
      expect($('#dropdown-test-6 > .ls-btn-primary').attr('aria-expanded')).toEqual('false');
    });

    it("Nav links should has attr aria-hidden with value true", function() {
      expect($('.ls-dropdown-nav').attr('aria-hidden')).toEqual('true');
    });

    it("When click the button should has attr aria-expanded with value true", function() {
      $('.ls-dropdown').find('.ls-btn-primary').trigger('click');
      expect($('#dropdown-test-6 > .ls-btn-primary').attr('aria-expanded')).toEqual('true');
    });

    it("When click the nav links should has attr aria-hidden with value false", function() {
      $('#dropdown-test-6').find('.ls-btn-primary').trigger('click');
      expect($('#dropdown-test-6 > .ls-dropdown-nav').attr('aria-hidden')).toEqual('false');
    });

    it("When click in dropdown should has attr aria-hidden with value true in others dropdowns", function() {
      $('#dropdown-test-6').find('.ls-btn-primary').trigger('click');
      expect($('#dropdown-test-5 > .ls-dropdown-nav').attr('aria-hidden')).toEqual('true');
    });

    it("When click in dropdown should has attr aria-expanded with value false in others dropdowns", function() {
      $('#dropdown-test-6').find('.ls-btn-primary').trigger('click');
      expect($('#dropdown-test-5 > .ls-btn-primary').attr('aria-expanded')).toEqual('false');
    });
  });

});
<|endoftext|>


<commit_before>/*
 * printThis v1.10.0
 * @desc Printing plug-in for jQuery
 * @author Jason Day
 *
 * Resources (based on) :
 *              jPrintArea: http://plugins.jquery.com/project/jPrintArea
 *              jqPrint: https://github.com/permanenttourist/jquery.jqprint
 *              Ben Nadal: http://www.bennadel.com/blog/1591-Ask-Ben-Print-Part-Of-A-Web-Page-With-jQuery.htm
 *
 * Licensed under the MIT licence:
 *              http://www.opensource.org/licenses/mit-license.php
 *
 * (c) Jason Day 2015
 *
 * Usage:
 *
 *  $("#mySelector").printThis({
 *      debug: false,               // show the iframe for debugging
 *      importCSS: true,            // import page CSS
 *      importStyle: false,         // import style tags
 *      printContainer: true,       // grab outer container as well as the contents of the selector
 *      loadCSS: "path/to/my.css",  // path to additional css file - us an array [] for multiple
 *      pageTitle: "",              // add title to print page
 *      removeInline: false,        // remove all inline styles from print elements
 *      printDelay: 333,            // variable print delay
 *      header: null,               // prefix to html
 *      footer: null,               // postfix to html
 *      base: false,                // preserve the BASE tag, or accept a string for the URL
 *      formValues: true,           // preserve input/form values
 *      canvas: false,              // copy canvas elements (experimental)
 *      doctypeString: '...',       // enter a different doctype for older markup
 *      removeScripts: false        // remove script tags from print content
 *  });
 *
 * Notes:
 *  - the loadCSS will load additional css (with or without @media print) into the iframe, adjusting layout
 */
;
(function($) {

    function appendContent($el, content) {
        if (!content) return;

        // Simple test for a jQuery element
        $el.append(content.jquery ? content.clone() : content);
    }

    function appendBody($body, $element, opt) {
        // Clone for safety and convenience
        // Calls clone(withDataAndEvents = true) to copy form values.
        var $content = $element.clone(opt.formValues);

        if (opt.formValues) {
            // Copy original select and textarea values to their cloned counterpart
            // Makes up for inability to clone select and textarea values with clone(true)
            copyValues($element, $content, 'select, textarea');
        }

        if (opt.removeScripts) {
            $content.find('script').remove();
        }

        if (opt.printContainer) {
            // grab $.selector as container
            $content.appendTo($body);
        } else {
            // otherwise just print interior elements of container
            $content.each(function() {
                $(this).children().appendTo($body)
            });
        }
    }

    // Copies values from origin to clone for passed in elementSelector
    function copyValues(origin, clone, elementSelector) {
        var $originalElements = origin.find(elementSelector);

        clone.find(elementSelector).each(function(index, item) {
            item.value = $originalElements.eq(index).val();
        });
    }

    var opt;
    $.fn.printThis = function(options) {
        opt = $.extend({}, $.fn.printThis.defaults, options);
        var $element = this instanceof jQuery ? this : $(this);

        var strFrameName = "printThis-" + (new Date()).getTime();

        if (window.location.hostname !== document.domain && navigator.userAgent.match(/msie/i)) {
            // Ugly IE hacks due to IE not inheriting document.domain from parent
            // checks if document.domain is set by comparing the host name against document.domain
            var iframeSrc = "javascript:document.write(\"