<commit_before>'use strict';

module.exports = function(config) {
    var browsers,
        reporters = ['dots'];

    if (process.env.KARMA_BROWSERS) {
        browsers = process.env.KARMA_BROWSERS.split(',');
    }

    config.set({
        frameworks: ['jasmine'],
        browsers: browsers,
        files: [
            'dist/loud.js',
            require.resolve('es5-shim'),
            require.resolve('html5shiv/dist/html5shiv'),
            'test/**/*.js'
        ]
    });

    if (process.env.CI && process.env.SAUCE_ACCESS_KEY) {
        var customLaunchers = {
            sauceLabsChrome: {
                base: 'SauceLabs',
                browserName: 'chrome',
                browserVersion: '79.0',
                platformName: 'Windows 10'
            },
            sauceLabsEdge: {
                base: 'SauceLabs',
                browserName: 'MicrosoftEdge',
                browserVersion: '18.17763',
                platformName: 'Windows 10'
            },
            sauceLabsSafari: {
                base: 'SauceLabs',
                browserName: 'safari',
                browserVersion: '13.0',
                platformName: 'macOS 10.13'
            },
            sauceLabsIOs: {
                base: 'SauceLabs',
                browserName: 'Safari',
                deviceName: 'iPhone X Simulator',
                platformVersion: '13.0',
                platformName: 'iOS'
            },
            sauceLabsAndroid: {
                base: 'SauceLabs',
                browserName: 'Chrome',
                deviceName: 'Android GoogleAPI Emulator',
                platformVersion: '9.0',
                platformName: 'Android'
            }
        };

        reporters.push('saucelabs');
        config.set({
            browsers: browsers.concat(Object.keys(customLaunchers)),
            captureTimeout: 120000,
            sauceLabs: {
                testName: 'Loud'
            },
            customLaunchers: customLaunchers
        });
    }

    if (process.env.KARMA_COVERAGE) {
        reporters.push('coverage');
        config.set({
            preprocessors: {
                'dist/loud.js': ['sourcemap'],
                'lib/*.js': ['coverage']
            },
            coverageReporter: {
                type: process.env.KARMA_COVERAGE,
                dir: 'coverage/'
            }
        });
    }

    config.set({
        reporters: reporters
    });
};
<commit_msg>Downgrade testing in Safari<commit_after>'use strict';

module.exports = function(config) {
    var browsers,
        reporters = ['dots'];

    if (process.env.KARMA_BROWSERS) {
        browsers = process.env.KARMA_BROWSERS.split(',');
    }

    config.set({
        frameworks: ['jasmine'],
        browsers: browsers,
        files: [
            'dist/loud.js',
            require.resolve('es5-shim'),
            require.resolve('html5shiv/dist/html5shiv'),
            'test/**/*.js'
        ]
    });

    if (process.env.CI && process.env.SAUCE_ACCESS_KEY) {
        var customLaunchers = {
            sauceLabsChrome: {
                base: 'SauceLabs',
                browserName: 'chrome',
                browserVersion: '79.0',
                platformName: 'Windows 10'
            },
            sauceLabsEdge: {
                base: 'SauceLabs',
                browserName: 'MicrosoftEdge',
                browserVersion: '18.17763',
                platformName: 'Windows 10'
            },
            sauceLabsSafari: {
                base: 'SauceLabs',
                browserName: 'safari',
                browserVersion: '11.0',
                platformName: 'macOS 10.12'
            },
            sauceLabsIOs: {
                base: 'SauceLabs',
                browserName: 'Safari',
                deviceName: 'iPhone X Simulator',
                platformVersion: '13.0',
                platformName: 'iOS'
            },
            sauceLabsAndroid: {
                base: 'SauceLabs',
                browserName: 'Chrome',
                deviceName: 'Android GoogleAPI Emulator',
                platformVersion: '9.0',
                platformName: 'Android'
            }
        };

        reporters.push('saucelabs');
        config.set({
            browsers: browsers.concat(Object.keys(customLaunchers)),
            captureTimeout: 120000,
            sauceLabs: {
                testName: 'Loud'
            },
            customLaunchers: customLaunchers
        });
    }

    if (process.env.KARMA_COVERAGE) {
        reporters.push('coverage');
        config.set({
            preprocessors: {
                'dist/loud.js': ['sourcemap'],
                'lib/*.js': ['coverage']
            },
            coverageReporter: {
                type: process.env.KARMA_COVERAGE,
                dir: 'coverage/'
            }
        });
    }

    config.set({
        reporters: reporters
    });
};
<|endoftext|>


<commit_before>import bufferStream from 'simple-bufferstream';
import chip from 'child_process';
import fs from 'fs';
import multistream from 'multistream';

const prepend = '(function(process, require, console) {\n';
const append = '\n})'; // dont remove \n
const boundary = 4096;

const script = `
  var stdin = new Buffer(0);
  process.stdin.on('data', function (data) {
    // TODO compare it with concat-stream approach
    stdin = Buffer.concat([ stdin, data ]);
  });
  process.stdin.on('end', function (data) {
    var vm = require('vm');
    var s = new vm.Script(stdin, {
      produceCachedData: true,
      sourceless: true
    });
    if (!s.cachedDataProduced) {
      console.error('Pkg: Cached data not produced.');
      process.exit(2);
    }
    var sentinel = new Buffer(16);
    sentinel.writeInt32LE(0x26e0c928, 0);
    sentinel.writeInt32LE(0x41f32b66, 4);
    sentinel.writeInt32LE(0x3ea13ccf, 8);
    sentinel.writeInt32LE(s.cachedData.length, 12);
    var boundary = ${boundary};
    var size = sentinel.length + s.cachedData.length;
    var remainder = size % boundary;
    var padding = (remainder === 0 ? 0 : boundary - remainder);
    process.stdout.write(sentinel);
    process.stdout.write(s.cachedData);
    process.stdout.write(new Buffer(padding));
  });
  process.stdin.resume();
`;

function paddingBuffer (size) {
  const remainder = size % boundary;
  const padding = (remainder === 0 ? 0 : boundary - remainder);
  return Buffer.alloc(padding);
}

function bakeryFromOptions (options) {
  const parts = [];
  for (let i = 0; i < options.length; i += 1) {
    parts.push(Buffer.from(options[i]));
    parts.push(Buffer.alloc(1));
  }
  parts.push(Buffer.alloc(1));
  const bakery = Buffer.concat(parts);

  const sentinel = new Buffer(16);
  sentinel.writeInt32LE(0x4818c4df, 0);
  sentinel.writeInt32LE(0x7ac30670, 4);
  sentinel.writeInt32LE(0x56558a76, 8);
  sentinel.writeInt32LE(bakery.length, 12);
  const size = sentinel.length + bakery.length;
  return Buffer.concat([ sentinel, bakery,
    paddingBuffer(size) ]);
}

export default function ({ stripe, options, target }) {
  return new Promise((resolve, reject) => {
    const { size } = fs.statSync(target.binaryPath);

    multistream([
      fs.createReadStream(target.binaryPath),
      () => bufferStream(paddingBuffer(size)),
      () => bufferStream(bakeryFromOptions(options)),
      () => {
        // TODO streams? from packer?
        // using multistream factory?
        stripe = stripe.join('');
        const cmd = target.fabricator.binaryPath;
        const child = chip.spawn(
          cmd, [ '-e', script, '--runtime' ].concat(options),
          { stdio: [ 'pipe', 'pipe', 'inherit' ] }
        );

        child.on('error', (error) => {
          reject(error);
        }).on('close', (code) => {
          if (code !== 0) {
            return reject(new Error(`${cmd} failed with code ${code}`));
          }
          resolve();
        });

        child.stdin.on('error', (error) => {
          if (error.code === 'EPIPE') {
            return reject(new Error(`Was not able to compile for '${JSON.stringify(target)}'`));
          }
          reject(error);
        });

        child.stdin.write(prepend);
        child.stdin.write(stripe);
        child.stdin.write(append);
        child.stdin.end();
        return child.stdout;
      }
    ]).pipe(
      fs.createWriteStream(target.output)
    ).on('error', (error) => {
      reject(error);
    });
  });
}
<commit_msg>more clear about second padding [prepare for discrete]<commit_after>import bufferStream from 'simple-bufferstream';
import chip from 'child_process';
import fs from 'fs';
import multistream from 'multistream';

const prepend = '(function(process, require, console) {\n';
const append = '\n})'; // dont remove \n
const boundary = 4096;

const script = `
  var stdin = new Buffer(0);
  process.stdin.on('data', function (data) {
    // TODO compare it with concat-stream approach
    stdin = Buffer.concat([ stdin, data ]);
  });
  process.stdin.on('end', function (data) {
    var vm = require('vm');
    var s = new vm.Script(stdin, {
      produceCachedData: true,
      sourceless: true
    });
    if (!s.cachedDataProduced) {
      console.error('Pkg: Cached data not produced.');
      process.exit(2);
    }
    var sentinel = new Buffer(16);
    sentinel.writeInt32LE(0x26e0c928, 0);
    sentinel.writeInt32LE(0x41f32b66, 4);
    sentinel.writeInt32LE(0x3ea13ccf, 8);
    sentinel.writeInt32LE(s.cachedData.length, 12);
    var boundary = ${boundary};
    var size = sentinel.length + s.cachedData.length;
    var remainder = size % boundary;
    var padding = (remainder === 0 ? 0 : boundary - remainder);
    process.stdout.write(sentinel);
    process.stdout.write(s.cachedData);
    process.stdout.write(new Buffer(padding));
  });
  process.stdin.resume();
`;

function paddingBuffer (size) {
  const remainder = size % boundary;
  const padding = (remainder === 0 ? 0 : boundary - remainder);
  return Buffer.alloc(padding);
}

function bakeryFromOptions (options) {
  const parts = [];
  for (let i = 0; i < options.length; i += 1) {
    parts.push(Buffer.from(options[i]));
    parts.push(Buffer.alloc(1));
  }
  parts.push(Buffer.alloc(1));
  const bakery = Buffer.concat(parts);

  const sentinel = new Buffer(16);
  sentinel.writeInt32LE(0x4818c4df, 0);
  sentinel.writeInt32LE(0x7ac30670, 4);
  sentinel.writeInt32LE(0x56558a76, 8);
  sentinel.writeInt32LE(bakery.length, 12);
  return Buffer.concat([ sentinel, bakery ]);
}

export default function ({ stripe, options, target }) {
  return new Promise((resolve, reject) => {
    const { size } = fs.statSync(target.binaryPath);
    const bakery = bakeryFromOptions(options);

    multistream([
      fs.createReadStream(target.binaryPath),
      () => bufferStream(paddingBuffer(size)),
      () => bufferStream(bakery),
      () => bufferStream(paddingBuffer(bakery.length)),
      () => {
        // TODO streams? from packer?
        // using multistream factory?
        stripe = stripe.join('');
        const cmd = target.fabricator.binaryPath;
        const child = chip.spawn(
          cmd, [ '-e', script, '--runtime' ].concat(options),
          { stdio: [ 'pipe', 'pipe', 'inherit' ] }
        );

        child.on('error', (error) => {
          reject(error);
        }).on('close', (code) => {
          if (code !== 0) {
            return reject(new Error(`${cmd} failed with code ${code}`));
          }
          resolve();
        });

        child.stdin.on('error', (error) => {
          if (error.code === 'EPIPE') {
            return reject(new Error(`Was not able to compile for '${JSON.stringify(target)}'`));
          }
          reject(error);
        });

        child.stdin.write(prepend);
        child.stdin.write(stripe);
        child.stdin.write(append);
        child.stdin.end();
        return child.stdout;
      }
    ]).pipe(
      fs.createWriteStream(target.output)
    ).on('error', (error) => {
      reject(error);
    });
  });
}
<|endoftext|>


<commit_before>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 */
if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}

define(["require"], function (require) {
return function(deep)
{
    if (typeof requirejs !== 'undefined')
        requirejs.onError = function (err) {
            console.log('requirejs OnError : ' + err);
            console.log(err.requireType);
            if (err.requireType === 'timeout')
                console.log('modules: ' + err.requireModules);
            //throw err;
    };
     /**
     * get or assign protocol
     */
    deep.protocol = function (name, ctrl) {
        if(ctrl)
        {
            deep.protocols[name] = ctrl;
            return ctrl;
        }
        return deep.protocols[name];
    };
    //_______________________________________________________________________________ GET/GET ALL  REQUESTS

    deep.protocol.getStoreHandler = function(protocol, opt)
    {
        var handler = {
            method:"get",
            store:null
        };
        opt = opt || {};

        if(protocol._deep_ocm_)
            protocol = protocol();
        if(typeof protocol === 'object')
            handler.store = protocol;
        else if(deep.protocols[protocol])
            handler.store = deep.protocols[protocol];
        else
        {
            var splitted = protocol.split(".");
            handler.store = deep.protocols[splitted.shift()];
            if(!handler.store)
                return deep.when(deep.errors.Store("no store found with : "+protocol));
            handler.method = splitted.shift();
            if(!handler.store[handler.method])
                return deep.when(deep.errors.Store("no method found in store with : "+protocol));
        }
        if(handler.store._deep_ocm_ && !opt.ignoreOCM)
            handler.store = handler.store();
        if(typeof handler.store === 'function')
            handler.store = {
                _deep_store_:true,
                get:handler.store
            };
        if(handler.store.init && !opt.ignoreInit)
            return deep.when(handler.store.init())
            .done(function(){
                return handler;
            });
        return deep.when(handler);
    };

    /**
     * parse 'retrievable' string request (e.g. "json::test.json")
     * @for deep
     * @method parseRequest
     * @static
     * @param  {String} request
     * @return {Object} infos an object containing parsing result
     */
    deep.utils.parseRequest = function (request, options) {
		if(!request)
			throw deep.errors.Error(500, "request parsing error : request undefined");
        var protoIndex = request.substring(0,50).indexOf("::");
        var protoc = null;
        var uri = request;
        var store = null;
        if (protoIndex > -1) {
            protoc = request.substring(0, protoIndex);
            uri = request.substring(protoIndex + 2);
        }
        var range = null;
        if(protoc)
        {
            var argsPresence = protoc.indexOf("(");
            if(argsPresence > -1)
            {
                var parenthesisRes = deep.utils.catchParenthesis(protoc.substring(argsPresence));
                protoc = protoc.substring(0,argsPresence);
                if(parenthesisRes)
                {
                    var rangeSplit = parenthesisRes.value.split(",");
                    range = { start:parseInt(rangeSplit[0]), end:parseInt(rangeSplit[1]) };
                }
            }
        }
        if (request[0] == '#' || protoc == "first" || protoc == "last" || protoc == "this") {
            store = deep.protocol.getStoreHandler(deep.protocols.dq);
        } else if (!protoc) {
            var founded = deep.extensions.some(function (storez)
            {
                if (!storez.extensions)
                    return false;
                for (var j = 0; j < storez.extensions.length; ++j)
                {
                    var extension = storez.extensions[j];
                    if (uri.match(extension)) {
                        store = storez.store;
                        break;
                    }
                }
                if (store)
                    return true;
                return false;
            });
            if(founded)
                store = deep.protocol.getStoreHandler(store);
        }
        else
            store = deep.protocol.getStoreHandler(protoc);
        var res = {
            _deep_request_: true,
            request: request,
            store: store,
            protocol: protoc,
            uri: uri,
            range:range
        };
        return res;
    };

    /**
     * retrieve an array of retrievable strings (e.g. "json::test.json")
     * if request is not a string : will just return request
     * @for deep
     * @static
     * @method getAll
     * @param  {String} requests a array of strings to retrieve
     * @param  {Object} options (optional)
     * @return {deep.Chain} a handler that hold result
     */
    deep.getAll = function (requests, options) {
        var alls = [];
        requests.forEach(function (request) {
            //console.log("get all : ", request, options);
            alls.push(deep.get(request, options));
        });
        return deep.all(alls);
    };

    /**
     * retrieve request (if string in retrievable format) (e.g. "json::test.json")
     * perform an http get
     * if request is not a string : will just return request
     * @for deep
     * @static
     * @method get
     * @param  {String} request a string to retrieve
     * @param  {Object} options (optional)
     * @return {deep.Chain} a handler that hold result
     */
    deep.get = function (request, options) {
        if (!request || (typeof request !== "string" && !request._deep_request_))
            return deep.when(request);
        options = options || {};
        var infos = request;
        if (typeof infos === 'string')
            infos = deep.utils.parseRequest(request, options);
        var res = null;
        if (!infos.store && !infos.protocol)
            return deep.when(request);
        return deep.when(infos.store)
        .done(function(storeHandler){
            var res = null;
            if(infos.range)
            {
                if(!storeHandler.store.range)
                    return deep.errors.Store("no range in store !.", infos);
                res = storeHandler.store.range(infos.range.start, infos.range.end, infos.uri, options);
            }
            else
                res = storeHandler.store[storeHandler.method](infos.uri, options);
            if (options.wrap)
            {
                return deep.when(res)
                .done(function (res) {
                    if (options.wrap.result) {
                        if (typeof options.wrap.result.push === 'function')
                            options.wrap.result.push(res);
                        else
                            options.wrap.result = [].concat(options.wrap.result);
                    } else
                        options.wrap.result = res;
                    return options.wrap;
                });
            }
            else
                return res;
        });
    };
    // ___________________________________________________________________________ BASICAL PROTOCOLES
    deep.protocols = {
        /**
         * deep-query protocol :
         * for code-sheet usage.
         *
         * options must contain the entry from where start query
         * @param  {[type]} request [description]
         * @param  {[type]} options [description]
         * @return {[type]}         [description]
         */
        dq:{
            get: function dqGet(request, options) {
                var entry = options.entry;
                if(!entry)
                    return undefined;
                var root = entry.root || entry;
                var infos = request;
                if (typeof infos === 'string')
                    infos = deep.utils.parseRequest(infos);
                if (infos.uri[0] == '#')
                    infos.uri = infos.uri.substring(1);
                var res = null;
                options = options || {};
                options.keepCache = false;
                if (infos.uri.substring(0, 3) == "../") {
                    infos.uri = ((entry.path != "/") ? (entry.path + "/") : "") + infos.uri;
                    res = deep.query(root, infos.uri, options);
                } else if (infos.uri[0] == '/')
                    res = deep.query(root, infos.uri, options);
                else
                    res = deep.query(entry, infos.uri, options);
                return res;
            }
        },
        js: function (path, options) {
            if (typeof path === 'object')
                path = path.uri;
            var def = deep.Deferred();
            try {
                require([path], function (obj) {
                    def.resolve(obj);
                }, function (err) {
                    def.reject(err);
                });
            } catch (e) {
                def.reject(e);
            }
            return def.promise();
        },
        instance: function (path, options) {
            return deep.protocols.js(path, options)
                .done(function (Cl) {
                if (typeof Cl === 'function')
                    return new Cl();
                return deep.errors.Internal("deep.protocols.instance  : could not instanciate : " + JSON.stringify(path));
            });
        }
    };
};
});

<commit_msg>add dumpError when requirejs failed<commit_after>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 */
if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}

define(["require"], function (require) {
return function(deep)
{
    if (typeof requirejs !== 'undefined')
        requirejs.onError = function (err) {
            //console.error('requirejs OnError : ', err);
            deep.utils.dumpError(err);
            console.log(err.requireType);
            if (err.requireType === 'timeout')
                console.log('modules: ' + err.requireModules);
            //throw err;
    };
     /**
     * get or assign protocol
     */
    deep.protocol = function (name, ctrl) {
        if(ctrl)
        {
            deep.protocols[name] = ctrl;
            return ctrl;
        }
        return deep.protocols[name];
    };
    //_______________________________________________________________________________ GET/GET ALL  REQUESTS

    deep.protocol.getStoreHandler = function(protocol, opt)
    {
        var handler = {
            method:"get",
            store:null
        };
        opt = opt || {};

        if(protocol._deep_ocm_)
            protocol = protocol();
        if(typeof protocol === 'object')
            handler.store = protocol;
        else if(deep.protocols[protocol])
            handler.store = deep.protocols[protocol];
        else
        {
            var splitted = protocol.split(".");
            handler.store = deep.protocols[splitted.shift()];
            if(!handler.store)
                return deep.when(deep.errors.Store("no store found with : "+protocol));
            handler.method = splitted.shift();
            if(!handler.store[handler.method])
                return deep.when(deep.errors.Store("no method found in store with : "+protocol));
        }
        if(handler.store._deep_ocm_ && !opt.ignoreOCM)
            handler.store = handler.store();
        if(typeof handler.store === 'function')
            handler.store = {
                _deep_store_:true,
                get:handler.store
            };
        if(handler.store.init && !opt.ignoreInit)
            return deep.when(handler.store.init())
            .done(function(){
                return handler;
            });
        return deep.when(handler);
    };

    /**
     * parse 'retrievable' string request (e.g. "json::test.json")
     * @for deep
     * @method parseRequest
     * @static
     * @param  {String} request
     * @return {Object} infos an object containing parsing result
     */
    deep.utils.parseRequest = function (request, options) {
		if(!request)
			throw deep.errors.Error(500, "request parsing error : request undefined");
        var protoIndex = request.substring(0,50).indexOf("::");
        var protoc = null;
        var uri = request;
        var store = null;
        if (protoIndex > -1) {
            protoc = request.substring(0, protoIndex);
            uri = request.substring(protoIndex + 2);
        }
        var range = null;
        if(protoc)
        {
            var argsPresence = protoc.indexOf("(");
            if(argsPresence > -1)
            {
                var parenthesisRes = deep.utils.catchParenthesis(protoc.substring(argsPresence));
                protoc = protoc.substring(0,argsPresence);
                if(parenthesisRes)
                {
                    var rangeSplit = parenthesisRes.value.split(",");
                    range = { start:parseInt(rangeSplit[0]), end:parseInt(rangeSplit[1]) };
                }
            }
        }
        if (request[0] == '#' || protoc == "first" || protoc == "last" || protoc == "this") {
            store = deep.protocol.getStoreHandler(deep.protocols.dq);
        } else if (!protoc) {
            var founded = deep.extensions.some(function (storez)
            {
                if (!storez.extensions)
                    return false;
                for (var j = 0; j < storez.extensions.length; ++j)
                {
                    var extension = storez.extensions[j];
                    if (uri.match(extension)) {
                        store = storez.store;
                        break;
                    }
                }
                if (store)
                    return true;
                return false;
            });
            if(founded)
                store = deep.protocol.getStoreHandler(store);
        }
        else
            store = deep.protocol.getStoreHandler(protoc);
        var res = {
            _deep_request_: true,
            request: request,
            store: store,
            protocol: protoc,
            uri: uri,
            range:range
        };
        return res;
    };

    /**
     * retrieve an array of retrievable strings (e.g. "json::test.json")
     * if request is not a string : will just return request
     * @for deep
     * @static
     * @method getAll
     * @param  {String} requests a array of strings to retrieve
     * @param  {Object} options (optional)
     * @return {deep.Chain} a handler that hold result
     */
    deep.getAll = function (requests, options) {
        var alls = [];
        requests.forEach(function (request) {
            //console.log("get all : ", request, options);
            alls.push(deep.get(request, options));
        });
        return deep.all(alls);
    };

    /**
     * retrieve request (if string in retrievable format) (e.g. "json::test.json")
     * perform an http get
     * if request is not a string : will just return request
     * @for deep
     * @static
     * @method get
     * @param  {String} request a string to retrieve
     * @param  {Object} options (optional)
     * @return {deep.Chain} a handler that hold result
     */
    deep.get = function (request, options) {
        if (!request || (typeof request !== "string" && !request._deep_request_))
            return deep.when(request);
        options = options || {};
        var infos = request;
        if (typeof infos === 'string')
            infos = deep.utils.parseRequest(request, options);
        var res = null;
        if (!infos.store && !infos.protocol)
            return deep.when(request);
        return deep.when(infos.store)
        .done(function(storeHandler){
            var res = null;
            if(infos.range)
            {
                if(!storeHandler.store.range)
                    return deep.errors.Store("no range in store !.", infos);
                res = storeHandler.store.range(infos.range.start, infos.range.end, infos.uri, options);
            }
            else
                res = storeHandler.store[storeHandler.method](infos.uri, options);
            if (options.wrap)
            {
                return deep.when(res)
                .done(function (res) {
                    if (options.wrap.result) {
                        if (typeof options.wrap.result.push === 'function')
                            options.wrap.result.push(res);
                        else
                            options.wrap.result = [].concat(options.wrap.result);
                    } else
                        options.wrap.result = res;
                    return options.wrap;
                });
            }
            else
                return res;
        });
    };
    // ___________________________________________________________________________ BASICAL PROTOCOLES
    deep.protocols = {
        /**
         * deep-query protocol :
         * for code-sheet usage.
         *
         * options must contain the entry from where start query
         * @param  {[type]} request [description]
         * @param  {[type]} options [description]
         * @return {[type]}         [description]
         */
        dq:{
            get: function dqGet(request, options) {
                var entry = options.entry;
                if(!entry)
                    return undefined;
                var root = entry.root || entry;
                var infos = request;
                if (typeof infos === 'string')
                    infos = deep.utils.parseRequest(infos);
                if (infos.uri[0] == '#')
                    infos.uri = infos.uri.substring(1);
                var res = null;
                options = options || {};
                options.keepCache = false;
                if (infos.uri.substring(0, 3) == "../") {
                    infos.uri = ((entry.path != "/") ? (entry.path + "/") : "") + infos.uri;
                    res = deep.query(root, infos.uri, options);
                } else if (infos.uri[0] == '/')
                    res = deep.query(root, infos.uri, options);
                else
                    res = deep.query(entry, infos.uri, options);
                return res;
            }
        },
        js: function (path, options) {
            if (typeof path === 'object')
                path = path.uri;
            var def = deep.Deferred();
            try {
                require([path], function (obj) {
                    def.resolve(obj);
                }, function (err) {
                    def.reject(err);
                });
            } catch (e) {
                def.reject(e);
            }
            return def.promise();
        },
        instance: function (path, options) {
            return deep.protocols.js(path, options)
                .done(function (Cl) {
                if (typeof Cl === 'function')
                    return new Cl();
                return deep.errors.Internal("deep.protocols.instance  : could not instanciate : " + JSON.stringify(path));
            });
        }
    };
};
});

<|endoftext|>


<commit_before>/**
 * Describes the question model for use in the core.
 */

var _ = require('underscore');
var ParameterError = require('./ParameterError');
var MultipleCorrectAnswersError = require('./MultipleCorrectAnswersError');
var Answer = require('./answer');

var Question = function (text, answers, difficulty) {
  if (typeof text !== 'string') {
    throw new ParameterError("Question text must be present as a string.");
  } else {
    this.text = text;
  }

  if (!_.isNumber(difficulty) || _.isNaN(difficulty)) {
    throw new ParameterError("Questions must have a numeric difficulty.");
  }
  if (difficulty > 10 || difficulty < 0) {
    throw new RangeError("Difficulty must be between 0 and 10 (inclusive)");
  }
  this.difficulty = difficulty;

  // Check if there are at least 2 answers in the array.
  if (!_.isArray(answers) || answers.length < 2) {
    throw new ParameterError("The answers parameter must be an array with at least two entries.");
  }
  // Check if it is an array of answers and if there is more than one correct answer.
  var correctCount = 0;
  _.each(answers, function (answer) {
     if (!(answer instanceof Answer)) {
       throw new ParameterError("The answers array, must contain answer objects.");
     }
     if (answer.correct) {
       correctCount++;
     }
  });
  if (correctCount > 1) {
    throw new MultipleCorrectAnswersError("Only one correct answer is allowed.");
  }

  this.answers = answers;

};

Question.prototype.checkAnswer = function (answer){
  var selectedAns = _.find(this.answers, function (ans) {
    return ans == answer;
  });
  return selectedAns.isCorrect();
};

module.exports = Question;

<commit_msg>Fixes equality operation.<commit_after>/**
 * Describes the question model for use in the core.
 */

var _ = require('underscore');
var ParameterError = require('./ParameterError');
var MultipleCorrectAnswersError = require('./MultipleCorrectAnswersError');
var Answer = require('./answer');

var Question = function (text, answers, difficulty) {
  if (typeof text !== 'string') {
    throw new ParameterError("Question text must be present as a string.");
  } else {
    this.text = text;
  }

  if (!_.isNumber(difficulty) || _.isNaN(difficulty)) {
    throw new ParameterError("Questions must have a numeric difficulty.");
  }
  if (difficulty > 10 || difficulty < 0) {
    throw new RangeError("Difficulty must be between 0 and 10 (inclusive)");
  }
  this.difficulty = difficulty;

  // Check if there are at least 2 answers in the array.
  if (!_.isArray(answers) || answers.length < 2) {
    throw new ParameterError("The answers parameter must be an array with at least two entries.");
  }
  // Check if it is an array of answers and if there is more than one correct answer.
  var correctCount = 0;
  _.each(answers, function (answer) {
     if (!(answer instanceof Answer)) {
       throw new ParameterError("The answers array, must contain answer objects.");
     }
     if (answer.correct) {
       correctCount++;
     }
  });
  if (correctCount > 1) {
    throw new MultipleCorrectAnswersError("Only one correct answer is allowed.");
  }

  this.answers = answers;

};

Question.prototype.checkAnswer = function (answer){
  var selectedAns = _.find(this.answers, function (ans) {
    return ans === answer;
  });
  return selectedAns.isCorrect();
};

module.exports = Question;

<|endoftext|>


<commit_before>var util = require('../../util');

module.exports = function(req, res, next) {
	util.parseFileToJson(req.rules.head && req.rules.head.url,
			function(err, data) {
		if (data) {
			var tmp = req.rules.head.req = {};
			if (data.req) {
				tmp.headers = req;
			}

			tmp = req.rules.head.res = {};
			if (data.statusCode) {
				tmp.statusCode = data.statusCode;
			}

			if (data.body) {
				tmp.body = tmp.body;
			}

			if (data.res) {
				tmp.headers = data.res;
			}

		}
		next();
	});
};<commit_msg>add head<commit_after>var util = require('../../util');

module.exports = function(req, res, next) {
	util.parseFileToJson(req.rules.head && req.rules.head.url,
			function(err, data) {
		if (data) {
			var reqRule = req.rules.head.req = {};
			if (data.req) {
				reqRule.headers = req;
			}

			var resRule = req.rules.head.res = {};
			if (data.statusCode) {
				resRule.statusCode = data.statusCode;
			}

			if (data.body) {
				resRule.body = data.body;
			}

			if (data.res) {
				resRule.headers = data.res;
			}

		}
		next();
	});
};<|endoftext|>


<commit_before>admins = ["CrazyByDefault", "Siddhartha1234", "Gouthamve"]
<commit_msg>rm siddhartha from admins<commit_after>admins = ["CrazyByDefault", "Gouthamve"]
<|endoftext|>


<commit_before>'use babel';

/**
 * Copyright (C) 2016 Ivan Kravets. All rights reserved.
 *
 * This source file is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

import fs from 'fs';
import child_process from 'child_process';
import https from 'https';
import temp from 'temp';
import path from 'path';
import shell from 'shell';
import tarball from 'tarball-extract';
import rimraf from 'rimraf';
import {useBuiltinPlatformIO, getPythonExecutable, findFileByName, runAtomCommand} from '../utils';
import {InstallPlatformIOView} from './view';
import {CACHE_DIR, ENV_DIR, ENV_BIN_DIR} from '../config';

// Install PlatformIO
export function command() {
  if (useBuiltinPlatformIO()) {
    const stateKey = 'platformio-ide:install-state';
    const updateProgress = (state) => {
      state.step += 1;
      if (state.view) {
        state.view.setProgress(Math.floor(state.step / state.total * 100));
      }
    };
    // Each task should take state as an argument and eventually return it
    // (directly or within a promise), so following task can use it).
    // Tasks will be executed in the order they are declared.
    const tasks = [
      (state) => {  // Check virtualenv existence
        return new Promise((resolve) => {
          fs.stat(ENV_BIN_DIR, (err) => {
            state.envDirExists = !err;
            resolve(state);
          });
        });
      },

      (state) => {  // Check cacne dir existence
        return new Promise((resolve) => {
          fs.stat(CACHE_DIR, (err) => {
            if (err) {
              fs.mkdir(CACHE_DIR, (err) => {
                if (err) {
                  throw new Error("Cannot create cache directory");
                }
                resolve(state);
              });
            }
            resolve(state);
          });
        });
      },

      (state) => {  // Ensure python is available
        return new Promise((resolve) => {
          state.pythonWorks = false;
          let msg = 'PlatformIO is written in Python and depends on it.' +
                    ' However, "python" command has not been found in ' +
                    'your system PATH. Please install Python 2.7 and ' +
                    'don\'t forget to "Add python.exe to Path" on the ' +
                    '"Customize" stage.';
          while (!state.pythonWorks && !state.canceled) {
            const check = child_process.spawnSync(getPythonExecutable(), ['--version']);
            state.pythonWorks = 0 === check.status;
            if (!state.pythonWorks) {
              atom.confirm({
                message: 'PlaftormIO: Unable to run python.',
                detailedMessage: msg,
                buttons: {
                  'Install Python': () => shell.openExternal('https://www.python.org/downloads/'),
                  'Try again': () => {},
                  'Abort PlatformIO IDE Installation': () => state.canceled = true,
                }
              });
            }
          }
          resolve(state);
        });
      },

      (state) => {  // Check if the virtualenv is cached
        return new Promise((resolve) => {
          const archivePath = path.join(CACHE_DIR, 'virtualenv.tar.gz');
          state.virtualenvArchivePath = archivePath;
          fs.stat(archivePath, (err) => {
            if (err && state.virtualenvArchiveExists) {
              delete state.virtualenvArchiveExists;
            }
            resolve(state);
          });
        });
      },

      (state) => {  // Initialize the view
        if (!state.envDirExists && state.pythonWorks) {
          state.view = new InstallPlatformIOView();
          state.view.handleCancel = () => state.canceled = true;
          state.panel = atom.workspace.addModalPanel({item: state.view.getElement()});
        }
        return state;
      },

      (state) => {  // Find the virtualenv download URL
        if (!state.envDirExists && state.view && !state.virtualenvArchiveExists && !state.virtualenvDownloadUrl) {
          return new Promise((resolve, reject) => {
            https.get('https://pypi.python.org/pypi/virtualenv/json', (res) => {
              var rawResponse = '';
              res.on('data', (chunk) => rawResponse += chunk);
              res.on('end', () => {
                const response = JSON.parse(rawResponse);
                response.urls.forEach((obj) => {
                  if ('source' === obj.python_version) {
                    state.virtualenvDownloadUrl = obj.url;
                    resolve(state);
                  }
                });
                if (!state.virtualenvDownloadUrl) {
                  atom.notifications.addError(
                    'PlatformIO: Unable to find the virtualenv download URL',
                    {dismissable: true});
                  reject(state);
                }
              });
            });
          });
        } else {
          return state;
        }
      },

      (state) => {  // Download the virtualenv source code archive
        if (!state.envDirExists && !state.virtualenvArchiveExists && state.virtualenvArchivePath) {
          return new Promise((resolve, reject) => {
            let file = fs.createWriteStream(state.virtualenvArchivePath);
            https.get(state.virtualenvDownloadUrl, (res) => {
              res.pipe(file);
            });
            file.on('error', () => reject(state));
            file.on('finish', () => {
              state.virtualenvArchiveExists = true;
              resolve(state);
            });
          });
        } else {
          return state;
        }
      },

      (state) => {  // Extract the virtualenv source code archive
        if (!state.envDirExists && state.virtualenvArchiveExists) {
          return new Promise((resolve, reject) => {
            const tmpDirPath = temp.mkdirSync({prefix: 'virtualenv-'});
            tarball.extractTarball(state.virtualenvArchivePath, tmpDirPath, (err) => {
              if (err) {
                let title = 'PlaftormIO: Failed to extract virtualenv.';
                atom.notifications.addError(title, {detail: err, dismissable: true});
                console.error(title);
                console.error('' + err);
                reject(state);
              }
              state.virtualenvExtractedInto = tmpDirPath;
              resolve(state);
            });
          });
        } else {
          return state;
        }
      },

      (state) => {  // Install the virtualenv into a temporary directory
        if (!state.envDirExists && state.virtualenvExtractedInto) {
          return new Promise((resolve, reject) => {
            state.virtualenvRoot = temp.mkdirSync({prefix: 'virtualenv-root'});
            const installArgs = ['setup.py', 'install', '--root', state.virtualenvRoot];
            const installOptions = {cwd: path.join(state.virtualenvExtractedInto, fs.readdirSync(state.virtualenvExtractedInto)[0])};
            const installProcess = child_process.spawn(getPythonExecutable(), installArgs, installOptions);
            installProcess.on('close', (code) => {
              state.virtualenvInstalled = 0 === code;
              if (!state.virtualenvInstalled) {
                let title = 'PlaftormIO: Unable to install the virtualenv.';
                atom.notifications.addError(
                  title, {detail: installProcess.stderr, dismissable: true});
                console.error(title);
                console.error('' + installProcess.stderr);
                reject(state);
              }
              resolve(state);
            });
          });
        } else {
          state.virtualenvInstalled = false;
          return state;
        }
      },

      (state) => {  // Make a virtualenv
        if (state.virtualenvInstalled) {
          return new Promise((resolve, reject) => {
            const virtualenvScript = findFileByName('virtualenv.py', state.virtualenvRoot);
            if (-1 === virtualenvScript) {
              let title = 'PlaftormIO: Cannot find the virtualenv.py script.';
              atom.notifications.addError(title, {dismissable: true});
              console.error(title);
              reject(state);
            }
            const makeEnvProcess = child_process.spawn(getPythonExecutable(), [virtualenvScript, ENV_DIR]);
            var makeEnvProcessStderr = '';
            makeEnvProcess.stderr.on('data', (chunk) => makeEnvProcessStderr += chunk);
            makeEnvProcess.on('close', (code) => {
              state.virtualenvCreated = 0 === code;
              if (!state.virtualenvCreated) {
                let title = 'PlaftormIO: Unable to create a virtualenv.';
                atom.notifications.addError(
                  title, {detail: makeEnvProcess.stderr, dismissable: true});
                console.error(title);
                console.error('' + makeEnvProcess.stderr);
              }
              resolve(state);
            });
          });
        } else {
          state.virtualenvCreated = false;
          return state;
        }
      },

      (state) => {  // Install the PlatformIO
        if (state.virtualenvCreated) {
          return new Promise((resolve) => {
            const args = ['install', 'platformio'];
            const executable = path.join(ENV_BIN_DIR, 'pip');
            const installResult = child_process.spawn(executable, args);
            var installResultStderr = '';
            installResult.stderr.on('data', (chunk) => installResultStderr += chunk);
            installResult.on('close', (code) => {
              state.platformioInstalled = 0 === code;
              if (!state.platformioInstalled) {
                atom.notifications.addError('Failed to install PlatformIO!', {
                  detail: installResultStderr,
                  dismissable: true,
                });
                console.error(installResultStderr);
                resolve(state);
              } else {
                if (state.restored) {
                  // Installing not for the first time
                  const apm = atom.packages.getApmPath();
                  for (let packageName of ['linter-clang', 'ult-terminal']) {
                    child_process.spawnSync(apm, ['uninstall', packageName]);
                  }
                }
                if (state.panel) state.panel.hide();
                require('atom-package-deps').install('platformio-ide', true).then(() => {
                  atom.config.set('tool-bar.position', 'Left');

                  atom.confirm({
                    message: 'PlatformIO IDE has been successfully installed!',
                    detailedMessage: 'However, some of its components will only become ' +
                                     'available after Atom window reload. You can ' +
                                     'click "Reload now" button below to perform reload ' +
                                     'immediately, or click "Reload later" and perform reload' +
                                     ' yourself with "View > Reload" command whenever ' +
                                     'you\'re ready.',
                    buttons: {
                      'Reload now': () => runAtomCommand('window:reload'),
                      'Reload later': () => {},
                    }
                  });
                  resolve(state);
                });
              }
            });
          });
        } else {
          return state;
        }
      },
    ];

    let chain = new Promise((resolve) => {
      // Retrieve the state object from localStorage
      let state;
      try {
        state = JSON.parse(localStorage.getItem(stateKey) || '{}');
        state.restored = true;
      } catch(err) {
        console.error(err);
        state = {};
      }

      // Necessary for progress display
      state.step = 0;
      state.total = tasks.length + 1;

      resolve(state);
    });

    // Chain tasks
    for (let i = 0; i < tasks.length; i++) {
      chain = chain.then((state) => {
        updateProgress(state);

        if (state.canceled) {
          // Skip task, return the state right away
          return state;
        }

        return tasks[i](state);
      });
    }

    // Catch Cancel
    chain = chain.then((state) => {
      if (state.canceled) {
        delete state.canceled;
        return new Promise((resolve) => {
          rimraf(ENV_DIR, () => resolve(state));
        });
      } else {
        return state;
      }
    });

    // Save the state
    chain = chain.then((state) => {
      if (state.panel) {
        state.panel.destroy();
        delete state.panel;
      }
      if (state.view) {
        delete state.view;
      }

      localStorage.setItem(stateKey, JSON.stringify(state));
    });

    return chain;

  } else {
    return new Promise((resolve, reject) => {
      // Just check if platformio is available globally
      var pioVersionProcessStderr = '';
      const pioVersionProcess = child_process.spawn("platformio");
      pioVersionProcess.stderr.on('data', (chunk) => pioVersionProcessStderr += chunk);
      pioVersionProcess.on('close', (code) => {
        if (0 !== code) {
          let title = 'PlaftormIO tool is not available.';
          let msg = 'Can not find `platformio` command. Please install it' +
                    ' using `pip install platformio` or enable built-in PlatformIO tool in' +
                    ' `platformio-ide` package settings.\nDetails:\n' +
                    pioVersionProcessStderr;
          atom.notifications.addError(title, {detail: msg, dismissable: true});
          console.error(title);
          console.error(pioVersionProcessStderr);
          reject();
        }
        resolve();
      });
    });
  }
}

export function reinstallPlatformIO(useDevelop) {
  const executable = path.join(ENV_BIN_DIR, 'pip');

  // try to uninstall previous PlatformIO if exists
  child_process.spawnSync(executable, ['uninstall', '-y' ,'platformio']);

  const args = ['install'];
  if (useDevelop) {
      args.push('https://github.com/platformio/platformio/archive/develop.zip');
  }
  else {
    args.push('platformio');
  }

  const result = child_process.spawnSync(executable, args);
  if (0 !== result.status) {
    let title = 'PlaftormIO: Failed to install PlatformIO!';
    let msg = '' + result.stderr;
    atom.notifications.addError(title, {detail: msg, dismissable: true});
    console.error(title);
    console.error(msg);
    return;
  }
  return true;
}
<commit_msg>Always check if dependencies are installed<commit_after>'use babel';

/**
 * Copyright (C) 2016 Ivan Kravets. All rights reserved.
 *
 * This source file is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

import fs from 'fs';
import child_process from 'child_process';
import https from 'https';
import temp from 'temp';
import path from 'path';
import shell from 'shell';
import tarball from 'tarball-extract';
import rimraf from 'rimraf';
import {useBuiltinPlatformIO, getPythonExecutable, findFileByName, runAtomCommand} from '../utils';
import {InstallPlatformIOView} from './view';
import {CACHE_DIR, ENV_DIR, ENV_BIN_DIR} from '../config';

// Install PlatformIO
export function command() {
  if (useBuiltinPlatformIO()) {
    const stateKey = 'platformio-ide:install-state';
    const updateProgress = (state) => {
      state.step += 1;
      if (state.view) {
        state.view.setProgress(Math.floor(state.step / state.total * 100));
      }
    };
    // Each task should take state as an argument and eventually return it
    // (directly or within a promise), so following task can use it).
    // Tasks will be executed in the order they are declared.
    const tasks = [
      (state) => {  // Check virtualenv existence
        return new Promise((resolve) => {
          fs.stat(ENV_BIN_DIR, (err) => {
            state.envDirExists = !err;
            resolve(state);
          });
        });
      },

      (state) => {  // Check cacne dir existence
        return new Promise((resolve) => {
          fs.stat(CACHE_DIR, (err) => {
            if (err) {
              fs.mkdir(CACHE_DIR, (err) => {
                if (err) {
                  throw new Error("Cannot create cache directory");
                }
                resolve(state);
              });
            }
            resolve(state);
          });
        });
      },

      (state) => {  // Ensure python is available
        return new Promise((resolve) => {
          state.pythonWorks = false;
          let msg = 'PlatformIO is written in Python and depends on it.' +
                    ' However, "python" command has not been found in ' +
                    'your system PATH. Please install Python 2.7 and ' +
                    'don\'t forget to "Add python.exe to Path" on the ' +
                    '"Customize" stage.';
          while (!state.pythonWorks && !state.canceled) {
            const check = child_process.spawnSync(getPythonExecutable(), ['--version']);
            state.pythonWorks = 0 === check.status;
            if (!state.pythonWorks) {
              atom.confirm({
                message: 'PlaftormIO: Unable to run python.',
                detailedMessage: msg,
                buttons: {
                  'Install Python': () => shell.openExternal('https://www.python.org/downloads/'),
                  'Try again': () => {},
                  'Abort PlatformIO IDE Installation': () => state.canceled = true,
                }
              });
            }
          }
          resolve(state);
        });
      },

      (state) => {  // Check if the virtualenv is cached
        return new Promise((resolve) => {
          const archivePath = path.join(CACHE_DIR, 'virtualenv.tar.gz');
          state.virtualenvArchivePath = archivePath;
          fs.stat(archivePath, (err) => {
            if (err && state.virtualenvArchiveExists) {
              delete state.virtualenvArchiveExists;
            }
            resolve(state);
          });
        });
      },

      (state) => {  // Initialize the view
        if (!state.envDirExists && state.pythonWorks) {
          state.view = new InstallPlatformIOView();
          state.view.handleCancel = () => state.canceled = true;
          state.panel = atom.workspace.addModalPanel({item: state.view.getElement()});
        }
        return state;
      },

      (state) => {  // Find the virtualenv download URL
        if (!state.envDirExists && state.view && !state.virtualenvArchiveExists && !state.virtualenvDownloadUrl) {
          return new Promise((resolve, reject) => {
            https.get('https://pypi.python.org/pypi/virtualenv/json', (res) => {
              var rawResponse = '';
              res.on('data', (chunk) => rawResponse += chunk);
              res.on('end', () => {
                const response = JSON.parse(rawResponse);
                response.urls.forEach((obj) => {
                  if ('source' === obj.python_version) {
                    state.virtualenvDownloadUrl = obj.url;
                    resolve(state);
                  }
                });
                if (!state.virtualenvDownloadUrl) {
                  atom.notifications.addError(
                    'PlatformIO: Unable to find the virtualenv download URL',
                    {dismissable: true});
                  reject(state);
                }
              });
            });
          });
        } else {
          return state;
        }
      },

      (state) => {  // Download the virtualenv source code archive
        if (!state.envDirExists && !state.virtualenvArchiveExists && state.virtualenvArchivePath) {
          return new Promise((resolve, reject) => {
            let file = fs.createWriteStream(state.virtualenvArchivePath);
            https.get(state.virtualenvDownloadUrl, (res) => {
              res.pipe(file);
            });
            file.on('error', () => reject(state));
            file.on('finish', () => {
              state.virtualenvArchiveExists = true;
              resolve(state);
            });
          });
        } else {
          return state;
        }
      },

      (state) => {  // Extract the virtualenv source code archive
        if (!state.envDirExists && state.virtualenvArchiveExists) {
          return new Promise((resolve, reject) => {
            const tmpDirPath = temp.mkdirSync({prefix: 'virtualenv-'});
            tarball.extractTarball(state.virtualenvArchivePath, tmpDirPath, (err) => {
              if (err) {
                let title = 'PlaftormIO: Failed to extract virtualenv.';
                atom.notifications.addError(title, {detail: err, dismissable: true});
                console.error(title);
                console.error('' + err);
                reject(state);
              }
              state.virtualenvExtractedInto = tmpDirPath;
              resolve(state);
            });
          });
        } else {
          return state;
        }
      },

      (state) => {  // Install the virtualenv into a temporary directory
        if (!state.envDirExists && state.virtualenvExtractedInto) {
          return new Promise((resolve, reject) => {
            state.virtualenvRoot = temp.mkdirSync({prefix: 'virtualenv-root'});
            const installArgs = ['setup.py', 'install', '--root', state.virtualenvRoot];
            const installOptions = {cwd: path.join(state.virtualenvExtractedInto, fs.readdirSync(state.virtualenvExtractedInto)[0])};
            const installProcess = child_process.spawn(getPythonExecutable(), installArgs, installOptions);
            installProcess.on('close', (code) => {
              state.virtualenvInstalled = 0 === code;
              if (!state.virtualenvInstalled) {
                let title = 'PlaftormIO: Unable to install the virtualenv.';
                atom.notifications.addError(
                  title, {detail: installProcess.stderr, dismissable: true});
                console.error(title);
                console.error('' + installProcess.stderr);
                reject(state);
              }
              resolve(state);
            });
          });
        } else {
          state.virtualenvInstalled = false;
          return state;
        }
      },

      (state) => {  // Make a virtualenv
        if (state.virtualenvInstalled) {
          return new Promise((resolve, reject) => {
            const virtualenvScript = findFileByName('virtualenv.py', state.virtualenvRoot);
            if (-1 === virtualenvScript) {
              let title = 'PlaftormIO: Cannot find the virtualenv.py script.';
              atom.notifications.addError(title, {dismissable: true});
              console.error(title);
              reject(state);
            }
            const makeEnvProcess = child_process.spawn(getPythonExecutable(), [virtualenvScript, ENV_DIR]);
            var makeEnvProcessStderr = '';
            makeEnvProcess.stderr.on('data', (chunk) => makeEnvProcessStderr += chunk);
            makeEnvProcess.on('close', (code) => {
              state.virtualenvCreated = 0 === code;
              if (!state.virtualenvCreated) {
                let title = 'PlaftormIO: Unable to create a virtualenv.';
                atom.notifications.addError(
                  title, {detail: makeEnvProcess.stderr, dismissable: true});
                console.error(title);
                console.error('' + makeEnvProcess.stderr);
              }
              resolve(state);
            });
          });
        } else {
          state.virtualenvCreated = false;
          return state;
        }
      },

      (state) => {  // Install the PlatformIO
        delete state.platformioInstalled;
        if (state.virtualenvCreated) {
          return new Promise((resolve) => {
            const args = ['install', 'platformio'];
            const executable = path.join(ENV_BIN_DIR, 'pip');
            const installResult = child_process.spawn(executable, args);
            var installResultStderr = '';
            installResult.stderr.on('data', (chunk) => installResultStderr += chunk);
            installResult.on('close', (code) => {
              state.platformioInstalled = 0 === code;
              if (!state.platformioInstalled) {
                atom.notifications.addError('Failed to install PlatformIO!', {
                  detail: installResultStderr,
                  dismissable: true,
                });
                console.error(installResultStderr);
              }
              resolve(state);
            });
          });
        } else {
          return state;
        }
      },

      (state) => {  // Install the package dependencies
        return new Promise((resolve) => {
          if (state.restored) {
            // Installing not for the first time
            const apm = atom.packages.getApmPath();
            for (let packageName of ['linter-clang', 'ult-terminal']) {
              child_process.spawnSync(apm, ['uninstall', packageName]);
            }
          }
          if (state.panel) state.panel.hide();
          require('atom-package-deps')
            .install('platformio-ide', true)
            .then(
              () => resolve(state),
              () => {
                console.warn('Failed to install dependencies');
                resolve(state);
              }
            );
        });
      },

      (state) => {  // Notify user
        if (state.platformioInstalled) {
          atom.notifications.addSuccess(
            'PlatformIO IDE has been successfully installed!',
            {dismissable: true}
          );
        }
        return state;
      },

      (state) => {  // Adjust the toolbar position
        if (!state.restored) {
          atom.config.set('tool-bar.position', 'Left');
        }
        return state;
      }
    ];

    let chain = new Promise((resolve) => {
      // Retrieve the state object from localStorage
      let state;
      try {
        state = JSON.parse(localStorage.getItem(stateKey) || '{}');
        state.restored = true;
      } catch(err) {
        console.error(err);
        state = {};
      }

      // Necessary for progress display
      state.step = 0;
      state.total = tasks.length + 1;

      resolve(state);
    });

    // Chain tasks
    for (let i = 0; i < tasks.length; i++) {
      chain = chain.then((state) => {
        updateProgress(state);

        if (state.canceled) {
          // Skip task, return the state right away
          return state;
        }

        return tasks[i](state);
      });
    }

    // Catch Cancel
    chain = chain.then((state) => {
      if (state.canceled) {
        delete state.canceled;
        return new Promise((resolve) => {
          rimraf(ENV_DIR, () => resolve(state));
        });
      } else {
        return state;
      }
    });

    // Save the state
    chain = chain.then((state) => {
      if (state.panel) {
        state.panel.destroy();
        delete state.panel;
      }
      if (state.view) {
        delete state.view;
      }

      localStorage.setItem(stateKey, JSON.stringify(state));
    });

    return chain;

  } else {
    return new Promise((resolve, reject) => {
      // Just check if platformio is available globally
      var pioVersionProcessStderr = '';
      const pioVersionProcess = child_process.spawn("platformio");
      pioVersionProcess.stderr.on('data', (chunk) => pioVersionProcessStderr += chunk);
      pioVersionProcess.on('close', (code) => {
        if (0 !== code) {
          let title = 'PlaftormIO tool is not available.';
          let msg = 'Can not find `platformio` command. Please install it' +
                    ' using `pip install platformio` or enable built-in PlatformIO tool in' +
                    ' `platformio-ide` package settings.\nDetails:\n' +
                    pioVersionProcessStderr;
          atom.notifications.addError(title, {detail: msg, dismissable: true});
          console.error(title);
          console.error(pioVersionProcessStderr);
          reject();
        }
        resolve();
      });
    });
  }
}

export function reinstallPlatformIO(useDevelop) {
  const executable = path.join(ENV_BIN_DIR, 'pip');

  // try to uninstall previous PlatformIO if exists
  child_process.spawnSync(executable, ['uninstall', '-y' ,'platformio']);

  const args = ['install'];
  if (useDevelop) {
      args.push('https://github.com/platformio/platformio/archive/develop.zip');
  }
  else {
    args.push('platformio');
  }

  const result = child_process.spawnSync(executable, args);
  if (0 !== result.status) {
    let title = 'PlaftormIO: Failed to install PlatformIO!';
    let msg = '' + result.stderr;
    atom.notifications.addError(title, {detail: msg, dismissable: true});
    console.error(title);
    console.error(msg);
    return;
  }
  return true;
}
<|endoftext|>


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

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

var fs = require('fs');
var colors = require("colors");
var UserAgent = require('useragent');
var path = require('path');
var XMLWriter = require('xml-writer');

/**
 *
 * @param reportObj includes all information about testSessions, wsSessions and the test report itself
 * @constructor
 */
function ReportManager(reportObj) {
    var stats;

    //checking if we need to do colorless reporting.
    if (global.color === false) {
        colors.mode = "none";
    }
    try {
        if (reportObj.arrTestSessions) {
            this.testSessions = reportObj.arrTestSessions;
        } else {
            this.testSessions = [];
        }

        if (reportObj.arrWDSessions) {
            this.wdSessions = reportObj.arrWDSessions;
        } else {
            this.wdSessions = [];
        }
        this.reportObj = reportObj;
        if (reportObj.reportFolder) {
            stats = fs.lstatSync(reportObj.reportFolder);
            if (stats.isDirectory()) {
                this.reportFolder = reportObj.reportFolder;
            }
        }
    } catch (ex) {
        //console.log(ex);
    }
}

ReportManager.prototype.showReportOnConsole = function (result, verbose) {

    var lastSuite, suite, k, k1, test, msg, m, browser,
        log = console.log;

    log("");
    browser = result.ua;
    if (result.failed) {
        log("Failed ".red +  result.name.blue + " on"  + browser);
    } else {
        log("Passed ".green + result.name.blue + " on"  + browser);
    }
    log((result.passed + " Passed").green + ", " + (result.failed + " Failed ").red + ", " + (result.ignored + " skipped ").grey);
    if (result.failed) {
        for (k in result) {
            suite = result[k];
            if ("object" === typeof suite) {
                if (suite.failed) {
                    for (k1 in suite) {
                        test = suite[k1];
                        if ("object" === typeof test) {
                            if ("fail" === test.result) {
                                if (!lastSuite || lastSuite !== suite.name) {
                                    log(" in " +  suite.name.bold);
                                    lastSuite = suite.name;
                                }
                                msg = test.message.split('\n');
                                log(" " +  test.name.bold.red + ":" +  msg[0]);
                                for (m = 1; m < msg.length; m = m + 1) {
                                    log(" " + msg[m]);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    log("");
};

ReportManager.prototype.writeReports = function () {

    var i, j, k, strJunitReport, strReport, rep, results, testJson, yuiUserAgent, yuiSuiteName, browser, descTestName, sessionId, yuiTestCaseName, timePerTest,
        className, testName, totalTimeTaken, errorCount, testSuiteName, arrReport, xmlReportName, jsonReportName, errorRep,
        self = this,
        wdSessions = self.wdSessions,
        testSessions = self.testSessions,
        passCount = 0,
        failCount = 0,
        skipCount = 0,
        timeCount = 0,
        totalCount = 0,
        jsonReport = {},
        log = console.log,
        resultPresent = false,
        missingErrorCount = 0,
        currentUrl,
        xw = new XMLWriter(),
        xwRoot = new XMLWriter();

    function writeFile(fileName, data) {
        fs.writeFileSync(fileName, data, 'utf8');
        log(("Report Created: " + fileName).inverse);
    }

    function addProperty(name, val) {
        if (val) {
            val += '';  // convert to string, since XMLWriter is picky
            xw.startElement('property');
            xw.writeAttribute('name', name);
            xw.writeAttribute('value', val);
            xw.endElement();
        }
    }
    function addTest(time, className, name, failureMessage) {
        xw.startElement('testcase');
        xw.writeAttribute('time', (time / 1000).toFixed(2));
        xw.writeAttribute('classname', className);
        xw.writeAttribute('name', name);

        if (failureMessage) {
            if (failureMessage === "skip") {
                xw.writeAttribute('executed', 'false');
                xw.endElement();
            } else {
                xw.startElement('failure');
                xw.text("<![CDATA[" + failureMessage + "]]>");
                xw.endElement();
                xw.endElement();
            }
        } else {
            xw.endElement();
        }
    }

    function parseYUIResults(testJson, dtName) {
        var l, m, errorRep;

        yuiUserAgent = testJson.ua;
        yuiSuiteName = testJson.name;
        browser = UserAgent.parse(yuiUserAgent).toAgent();
        if (browser === "Other 0.0.0") {
            browser = "NodeJS";
        }
        descTestName = dtName;
        sessionId = testJson.sessionId;
        currentUrl = testJson.currentUrl;
        for (l in testJson) {
            if (testJson[l]) {
                if (testJson[l].type === "testcase") {
                    yuiTestCaseName = testJson[l].name;
                    timePerTest = testJson[l].duration / testJson[l].total;
                    passCount += testJson[l].passed;
                    failCount += testJson[l].failed;
                    skipCount += testJson[l].ignored;
                    timeCount += testJson[l].duration;
                    totalCount += testJson[l].total;

                    for (m in testJson[l]) {
                        if (testJson[l][m].type === "test") {
                            className = browser + "." + descTestName;
                            testName = yuiSuiteName + "::" + yuiTestCaseName + "::" + testJson[l][m].name;
                            if (testJson[l][m].result === "fail") {
                                addTest(timePerTest, className, testName, testJson[l][m].message + "." + "\n" + " URL :" + currentUrl);
                            } else if (testJson[l][m].result === "pass") {
                                addTest(timePerTest, className, testName);
                            } else if (testJson[l][m].result === "ignore") {
                                addTest(timePerTest, className, testName, "skip");
                            }
                        }
                    }
                }
            }
        }
    }
    xw.startElement("properties");
    addProperty("descriptor", this.reportObj.descriptor);
    addProperty("parallel", this.reportObj.parallel);
    addProperty("driver", this.reportObj.driver);
    addProperty("browser", this.reportObj.browser);
    addProperty("reuseSession", this.reportObj.reuseSession);
    addProperty("activeSeleniumSessionCount", wdSessions.length);
    addProperty("seleniumSessionIds", wdSessions.join());
    addProperty("group", this.reportObj.group);
    addProperty("testName", this.reportObj.testName);
    addProperty("reportFolder", this.reportObj.reportFolder);
    xw.endElement();

    for (i = 0; i < testSessions.length; i = i + 1) {
        rep = testSessions[i].driver.getReports();

        if (rep.scenario) {
            arrReport = rep.scenario;
        } else {
            arrReport = rep.results;
        }

        resultPresent = false;

        for (j = 0; j < arrReport.length; j = j + 1) {
            if (rep.scenario) {
                results = arrReport[j].results;
                for (k = 0; k < results.length; k = k + 1) {
                    testJson =  results[k];
                    if (testJson.type === "report") {
                        resultPresent = true;
                        parseYUIResults(testJson, testSessions[i].driver.testName);
                    }
                }
            } else {
                testJson = arrReport[j];
                if (testJson.type === "report") {
                    resultPresent = true;
                    parseYUIResults(testJson, testSessions[i].driver.testName);
                }
            }
        }
        if (!resultPresent) {
            missingErrorCount = missingErrorCount + 1;
            errorRep = arrReport[arrReport.length - 1];

            if (errorRep.results) {
                //console.log("Error :" + errorRep.results[0].error);
                addTest(0, "Error." +  testSessions[i].driver.testName, "Error", errorRep.results[0].error);

            } else if (errorRep.error) {
                // console.log("Error : " +errorRep.error)
                addTest(0, "Error." +  testSessions[i].driver.testName, "Error", errorRep.error);
            } else {
                console.log("Error : UNKOWN");
            }
        }
    }

    totalCount = totalCount + missingErrorCount;
    failCount = failCount + missingErrorCount;

    log();
    log("Test Report Summary".bold.magenta.toString());
    log();
    log(("Total Number of Executed Tests: " + totalCount).blue.toString());
    log(("Total Number of Passed Tests: " + passCount).green.toString());
    log(("Total Number of Failed Tests: " + failCount).red.toString());
    log(("Total Number of Skipped Tests: " + skipCount).cyan.toString());
    log();
    log(("Total Test Execution Time Inside Browser: " + (timeCount / 1000).toFixed(2) + " seconds").green.bold.toString());
    totalTimeTaken = Date.now() - global.startTime;
    log(("Total Test Execution Time:" + (totalTimeTaken / 1000).toFixed(2) + " seconds").green.bold.toString());
    log();

    errorCount = totalCount - passCount - failCount - skipCount;

    testSuiteName = "";
    if (this.reportObj.testSuiteName) {
        testSuiteName = this.reportObj.testSuiteName;
    } else {
        testSuiteName = "TestSuite";
    }
    //console.log(totalCount + ":" + failCount + ":" + missingErrorCount + ":" + skipCount);
    //collecting all report
    strReport = xw.toString();

    //starting report root
    xwRoot.startDocument();
    xwRoot.startElement("testsuite");
    xwRoot.writeAttribute('failures', failCount.toString());
    xwRoot.writeAttribute('time', (totalTimeTaken / 1000).toFixed(2).toString());
    xwRoot.writeAttribute('errors', errorCount.toString());
    xwRoot.writeAttribute('skipped', skipCount.toString());
    xwRoot.writeAttribute('tests', totalCount.toString());
    xwRoot.writeAttribute('name', testSuiteName.toString());
    xwRoot.text("$$report$$");
    xwRoot.endElement();
    xwRoot.endDocument();

    strJunitReport = xwRoot.toString().replace("$$report$$", strReport);

    if (this.reportObj.descriptor) {

        xmlReportName = this.reportObj.descriptor.split(".")[0] + "-report.xml";
        jsonReportName = this.reportObj.descriptor.split(".")[0] + "-report.json";
    } else {
        xmlReportName = "report.xml";
        jsonReportName = "report.json";
    }

    if (self.reportFolder) {
        xmlReportName = self.reportFolder  + xmlReportName;
        jsonReportName = self.reportFolder  + jsonReportName;
    }
    writeFile(xmlReportName, strJunitReport);

    //writing json file
    for (i = 0; i < testSessions.length; i = i + 1) {
        jsonReport[testSessions[i].driver.testName] = JSON.parse(JSON.stringify(testSessions[i].driver.getReports()));
    }
    jsonReport.testSuiteName =  testSuiteName;
    writeFile(jsonReportName, JSON.stringify(jsonReport));

    return path.resolve(xmlReportName);
};

module.exports = ReportManager;
<commit_msg>fixing "--color=false" breaking report formatting issue<commit_after>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/

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

var fs = require('fs');
var colors = require("colors");
var UserAgent = require('useragent');
var path = require('path');
var XMLWriter = require('xml-writer');

/**
 *
 * @param reportObj includes all information about testSessions, wsSessions and the test report itself
 * @constructor
 */
function ReportManager(reportObj) {
    var stats;

    //checking if we need to do colorless reporting.
    if (global.color === false) {
        colors.mode = "none";
    }
    try {
        if (reportObj.arrTestSessions) {
            this.testSessions = reportObj.arrTestSessions;
        } else {
            this.testSessions = [];
        }

        if (reportObj.arrWDSessions) {
            this.wdSessions = reportObj.arrWDSessions;
        } else {
            this.wdSessions = [];
        }
        this.reportObj = reportObj;
        if (reportObj.reportFolder) {
            stats = fs.lstatSync(reportObj.reportFolder);
            if (stats.isDirectory()) {
                this.reportFolder = reportObj.reportFolder;
            }
        }
    } catch (ex) {
        //console.log(ex);
    }
}

ReportManager.prototype.showReportOnConsole = function (result, verbose) {

    var lastSuite, suite, k, k1, test, msg, m, browser,
        log = console.log;

    log("");
    browser = result.ua;
    if (result.failed) {
        log("Failed ".red +  result.name.blue + " on"  + browser);
    } else {
        log("Passed ".green + result.name.blue + " on"  + browser);
    }
    log((result.passed + " Passed").green + ", " + (result.failed + " Failed ").red + ", " + (result.ignored + " skipped ").grey);
    if (result.failed) {
        for (k in result) {
            suite = result[k];
            if ("object" === typeof suite) {
                if (suite.failed) {
                    for (k1 in suite) {
                        test = suite[k1];
                        if ("object" === typeof test) {
                            if ("fail" === test.result) {
                                if (!lastSuite || lastSuite !== suite.name) {
                                    log(" in " +  suite.name.bold);
                                    lastSuite = suite.name;
                                }
                                msg = test.message.split('\n');
                                log(" " +  test.name.bold.red + ":" +  msg[0]);
                                for (m = 1; m < msg.length; m = m + 1) {
                                    log(" " + msg[m]);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    log("");
};

ReportManager.prototype.writeReports = function () {

    var i, j, k, strJunitReport, strReport, rep, results, testJson, yuiUserAgent, yuiSuiteName, browser, descTestName, sessionId, yuiTestCaseName, timePerTest,
        className, testName, totalTimeTaken, errorCount, testSuiteName, arrReport, xmlReportName, jsonReportName, errorRep,
        self = this,
        wdSessions = self.wdSessions,
        testSessions = self.testSessions,
        passCount = 0,
        failCount = 0,
        skipCount = 0,
        timeCount = 0,
        totalCount = 0,
        jsonReport = {},
        log = console.log,
        resultPresent = false,
        missingErrorCount = 0,
        currentUrl,
        xw = new XMLWriter(),
        xwRoot = new XMLWriter();

    function writeFile(fileName, data) {
        fs.writeFileSync(fileName, data, 'utf8');
        log(("Report Created: " + fileName).inverse.toString());
    }

    function addProperty(name, val) {
        if (val) {
            val += '';  // convert to string, since XMLWriter is picky
            xw.startElement('property');
            xw.writeAttribute('name', name);
            xw.writeAttribute('value', val);
            xw.endElement();
        }
    }
    function addTest(time, className, name, failureMessage) {
        xw.startElement('testcase');
        xw.writeAttribute('time', (time / 1000).toFixed(2));
        xw.writeAttribute('classname', className);
        xw.writeAttribute('name', name);

        if (failureMessage) {
            if (failureMessage === "skip") {
                xw.writeAttribute('executed', 'false');
                xw.endElement();
            } else {
                xw.startElement('failure');
                xw.text("<![CDATA[" + failureMessage + "]]>");
                xw.endElement();
                xw.endElement();
            }
        } else {
            xw.endElement();
        }
    }

    function parseYUIResults(testJson, dtName) {
        var l, m, errorRep;

        yuiUserAgent = testJson.ua;
        yuiSuiteName = testJson.name;
        browser = UserAgent.parse(yuiUserAgent).toAgent();
        if (browser === "Other 0.0.0") {
            browser = "NodeJS";
        }
        descTestName = dtName;
        sessionId = testJson.sessionId;
        currentUrl = testJson.currentUrl;
        for (l in testJson) {
            if (testJson[l]) {
                if (testJson[l].type === "testcase") {
                    yuiTestCaseName = testJson[l].name;
                    timePerTest = testJson[l].duration / testJson[l].total;
                    passCount += testJson[l].passed;
                    failCount += testJson[l].failed;
                    skipCount += testJson[l].ignored;
                    timeCount += testJson[l].duration;
                    totalCount += testJson[l].total;

                    for (m in testJson[l]) {
                        if (testJson[l][m].type === "test") {
                            className = browser + "." + descTestName;
                            testName = yuiSuiteName + "::" + yuiTestCaseName + "::" + testJson[l][m].name;
                            if (testJson[l][m].result === "fail") {
                                addTest(timePerTest, className, testName, testJson[l][m].message + "." + "\n" + " URL :" + currentUrl);
                            } else if (testJson[l][m].result === "pass") {
                                addTest(timePerTest, className, testName);
                            } else if (testJson[l][m].result === "ignore") {
                                addTest(timePerTest, className, testName, "skip");
                            }
                        }
                    }
                }
            }
        }
    }
    xw.startElement("properties");
    addProperty("descriptor", this.reportObj.descriptor);
    addProperty("parallel", this.reportObj.parallel);
    addProperty("driver", this.reportObj.driver);
    addProperty("browser", this.reportObj.browser);
    addProperty("reuseSession", this.reportObj.reuseSession);
    addProperty("activeSeleniumSessionCount", wdSessions.length);
    addProperty("seleniumSessionIds", wdSessions.join());
    addProperty("group", this.reportObj.group);
    addProperty("testName", this.reportObj.testName);
    addProperty("reportFolder", this.reportObj.reportFolder);
    xw.endElement();

    for (i = 0; i < testSessions.length; i = i + 1) {
        rep = testSessions[i].driver.getReports();

        if (rep.scenario) {
            arrReport = rep.scenario;
        } else {
            arrReport = rep.results;
        }

        resultPresent = false;

        for (j = 0; j < arrReport.length; j = j + 1) {
            if (rep.scenario) {
                results = arrReport[j].results;
                for (k = 0; k < results.length; k = k + 1) {
                    testJson =  results[k];
                    if (testJson.type === "report") {
                        resultPresent = true;
                        parseYUIResults(testJson, testSessions[i].driver.testName);
                    }
                }
            } else {
                testJson = arrReport[j];
                if (testJson.type === "report") {
                    resultPresent = true;
                    parseYUIResults(testJson, testSessions[i].driver.testName);
                }
            }
        }
        if (!resultPresent) {
            missingErrorCount = missingErrorCount + 1;
            errorRep = arrReport[arrReport.length - 1];

            if (errorRep.results) {
                //console.log("Error :" + errorRep.results[0].error);
                addTest(0, "Error." +  testSessions[i].driver.testName, "Error", errorRep.results[0].error);

            } else if (errorRep.error) {
                // console.log("Error : " +errorRep.error)
                addTest(0, "Error." +  testSessions[i].driver.testName, "Error", errorRep.error);
            } else {
                console.log("Error : UNKOWN");
            }
        }
    }

    totalCount = totalCount + missingErrorCount;
    failCount = failCount + missingErrorCount;

    log();
    log("Test Report Summary".bold.magenta.toString());
    log();
    log(("Total Number of Executed Tests: " + totalCount).blue.toString());
    log(("Total Number of Passed Tests: " + passCount).green.toString());
    log(("Total Number of Failed Tests: " + failCount).red.toString());
    log(("Total Number of Skipped Tests: " + skipCount).cyan.toString());
    log();
    log(("Total Test Execution Time Inside Browser: " + (timeCount / 1000).toFixed(2) + " seconds").green.bold.toString());
    totalTimeTaken = Date.now() - global.startTime;
    log(("Total Test Execution Time:" + (totalTimeTaken / 1000).toFixed(2) + " seconds").green.bold.toString());
    log();

    errorCount = totalCount - passCount - failCount - skipCount;

    testSuiteName = "";
    if (this.reportObj.testSuiteName) {
        testSuiteName = this.reportObj.testSuiteName;
    } else {
        testSuiteName = "TestSuite";
    }
    //console.log(totalCount + ":" + failCount + ":" + missingErrorCount + ":" + skipCount);
    //collecting all report
    strReport = xw.toString();

    //starting report root
    xwRoot.startDocument();
    xwRoot.startElement("testsuite");
    xwRoot.writeAttribute('failures', failCount.toString());
    xwRoot.writeAttribute('time', (totalTimeTaken / 1000).toFixed(2).toString());
    xwRoot.writeAttribute('errors', errorCount.toString());
    xwRoot.writeAttribute('skipped', skipCount.toString());
    xwRoot.writeAttribute('tests', totalCount.toString());
    xwRoot.writeAttribute('name', testSuiteName.toString());
    xwRoot.text("$$report$$");
    xwRoot.endElement();
    xwRoot.endDocument();

    strJunitReport = xwRoot.toString().replace("$$report$$", strReport);

    if (this.reportObj.descriptor) {

        xmlReportName = this.reportObj.descriptor.split(".")[0] + "-report.xml";
        jsonReportName = this.reportObj.descriptor.split(".")[0] + "-report.json";
    } else {
        xmlReportName = "report.xml";
        jsonReportName = "report.json";
    }

    if (self.reportFolder) {
        xmlReportName = self.reportFolder  + xmlReportName;
        jsonReportName = self.reportFolder  + jsonReportName;
    }
    writeFile(xmlReportName, strJunitReport);

    //writing json file
    for (i = 0; i < testSessions.length; i = i + 1) {
        jsonReport[testSessions[i].driver.testName] = JSON.parse(JSON.stringify(testSessions[i].driver.getReports()));
    }
    jsonReport.testSuiteName =  testSuiteName;
    writeFile(jsonReportName, JSON.stringify(jsonReport));

    return path.resolve(xmlReportName);
};

module.exports = ReportManager;
<|endoftext|>