<commit_before>var util     = require('util')
    ,qs      = require('querystring')
    ,request = require('request');

API = '/api/json';
NEWJOB = '%s/createItem/?name=%s';
DELETE = '%s/job/%s/doDelete';
BUILD = '%s/job/%s/build' + API;
DISABLE = '%s/job/%s/disable';
ENABLE = '%s/job/%s/enable';
BUILDWITHPARAMS = '%s/job/%s/buildWithParameters';
CONFIG = '%s/job/%s/config.xml';
JOBINFO = '%s/job/%s' + API;
LIST = '%s' + API;
LAST_SUCCESS = '%s/job/%s/lastSuccessfulBuild' + API;
TEST_REPORT = '%s/job/%s/lastSuccessfulBuild/testReport' + API;
LAST_BUILD = '%s/job/%s/lastBuild' + API;
LAST_COMPLETED_BUILD = '%s/job/%s/lastCompletedBuild' + API;
LAST_REPORT = '%s/job/%s/lastBuild/testReport' + API;
QUEUE = '%s/queue' + API;
COMPUTERS = '%s/computer' + API;
JOB_OUTPUT = '%s/job/%s/consoleText' + API;

var init = exports.init = function(host) {

    //Jenkin variables
    var host = host;

    //Helper Functions
    var build_url = function(command) {
        /*
        Builds REST url to Jenkins
        */

        // Create the url using the format function
        var url = util.format.call(this, command, host);

        // if command is the only arg, we are done
        if (arguments.length == 1) return url;

        // Grab the arguments except for the first (command)
        var args = Array.prototype.slice.call(arguments).slice(1);

        // Append url to front of args array
        args.unshift(url);

        // Create full url with all the arguments
        url = util.format.apply(this, args);

        return url;

    }
    return {
        build: function(jobname, params, callback) {
            /*
            Trigger Jenkins to build.
            */
            if (typeof params === 'function') {
                buildurl = build_url(BUILD, jobname)
                callback = params;
            } else {
                buildurl = build_url(BUILDWITHPARAMS+"?"+qs.stringify(params), jobname)
            }

            request({method: 'POST', url: buildurl }, function(error, response, body) {
                if ( error || (response.statusCode !== 201 && response.statusCode !== 302) ) {
                    callback(error || true, response);
                    return;
                }
                data = "job is executed"
                callback(null, data);
            });
        },
        all_jobs: function(callback) {
            /*
            Return a list of object literals containing the name and color of all jobs on the Jenkins server
            */
            request({method: 'GET', url: build_url(LIST)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString()).jobs;
                callback(null, data);
            });
        },
        job_info: function(jobname, callback) {
            /*
            Get all information for a job
            */
            request({method: 'GET', url: build_url(JOBINFO, jobname)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString());
                callback(null, data);
            });
        },
        last_build_info: function(jobname, callback) {
            /*
            Get information for the last build of a job
            */
            request({method: 'GET', url: build_url(LAST_BUILD, jobname)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString());
                callback(null, data);
            });
        },
        last_completed_build_info: function(jobname, callback) {
            /*
            Get information for the last completed build of a job
            */
            request({method: 'GET', url: build_url(LAST_COMPLETED_BUILD, jobname)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString());
                callback(null, data);
            });
        },
        build_info: function(jobname, number, callback) {
            /*
            Get information for the build number of a job
            */
            request({method: 'GET', url: build_url(BUILD, jobname, number)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString());
                callback(null, data);
            });
        },
        last_build_report: function(jobname, callback) {
            /*
            Get the last build report for a job
            */
            request({method: 'GET', url: build_url(LAST_REPORT, jobname)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString());
                callback(null, data);
            });
        },
        get_config_xml: function(jobname, callback) {
            /*
            Get the config xml for a job
            */
            request({method: 'GET', url: build_url(CONFIG, jobname)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = body;
                callback(null, data);
            });
        },
        create_job: function(jobname, job_config, callback) {
            /*
           Create a new job based on a job_config string
            */

            request(
                {method: 'POST'
                ,url: build_url(NEWJOB, jobname)
                ,body: job_config
                ,headers: { "content-type": "application/xml"}
                },

                function(error, response, body) {
                    if ( error || response.statusCode !== 200 ) {
                        callback(error || true, response);
                        return;
                    }
                    data = body;
                    callback(null, data);
                }
            );
        },
        copy_job: function(jobname, new_job, modifyfunction, callback) {
            /*
            Copies a job and allows you to pass in a function to modify the configuration
            of the job you would like to copy
            */

            var self = this;
            self.get_config_xml(jobname, function(error, data) {
                if (error) {
                    callback(error, data);
                    return;
                }
                self.create_job(new_job, modifyfunction(data), function(error, data) {
                    if (error) {
                        callback(error, data);
                        return;
                    }
                    callback(null, data);
                });
            });

        },
        delete_job: function(jobname, callback) {
            /*
            Deletes a job
            */
            request({method: 'POST', url: build_url(DELETE, jobname)}, function(error, response, body) {
                if ( error || response.statusCode === 404 ) {
                    callback(error || true, response);
                    return;
                }
                callback(null, body);
            });

        },
        disable_job: function(jobname, callback) {
            /*
            Disables a job
            */
            request({method: 'POST', url: build_url(DISABLE, jobname)}, function(error, response, body) {
                if ( error || response.statusCode === 404 ) {
                    callback(error || true, response);
                    return;
                }
                callback(null, body);
            });
        },
        enable_job: function(jobname, callback) {
            /*
            Enables a job
            */
            request({method: 'POST', url: build_url(ENABLE, jobname)}, function(error, response, body) {
                if ( error || response.statusCode === 404 ) {
                    callback(error || true, response);
                    return;
                }
                callback(null, body);
            });
        },
        last_success: function(jobname, callback) {
            /*
            Get the last build report for a job
            */
            request({method: 'POST', url: build_url(LAST_SUCCESS, jobname)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body);
                callback(null, data);
            });

        },
        last_result: function(jobname, callback) {
            /*
            Get the last result for a job
            */
            self = this;
            self.job_info(jobname, function(error, data) {
                last_result_url = data['lastBuild']['url'];

                request({method: 'GET', url: build_url(last_result_url + API, jobname)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                        callback(error || true, response);
                        return;
                    }
                    data = JSON.parse(body);
                    callback(null, data);
                });
            });

        },
        queue: function(callback) {
            /*
             Get all queued items
             */
            request({method: 'GET', url: build_url(QUEUE)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString());
                callback(null, data);
            });
        },
        computers: function(callback) {
            /*
             Get details about all jenkins workers including currently executing jobs
             */
            request({method: 'GET', url: build_url(COMPUTERS + '?depth=1')}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString());
                callback(null, data);
            });
        },
        job_output: function(jobname, buildname, callback) {
            /*
            Get the output for a job's build
            */
            request({method: 'POST', url: build_url(JOB_OUTPUT, jobname + '/' + buildname)}, function(error, response, body) {
                if (response.statusCode != 200 || error) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.stringify({"output": body});
                data = JSON.parse(data);
                callback(null, data);
            });
        }

    }

}

if (!module.parent) {
}
<commit_msg>error should never be true<commit_after>var util     = require('util')
    ,qs      = require('querystring')
    ,request = require('request');

API = '/api/json';
NEWJOB = '%s/createItem/?name=%s';
DELETE = '%s/job/%s/doDelete';
BUILD = '%s/job/%s/build' + API;
DISABLE = '%s/job/%s/disable';
ENABLE = '%s/job/%s/enable';
BUILDWITHPARAMS = '%s/job/%s/buildWithParameters';
CONFIG = '%s/job/%s/config.xml';
JOBINFO = '%s/job/%s' + API;
LIST = '%s' + API;
LAST_SUCCESS = '%s/job/%s/lastSuccessfulBuild' + API;
TEST_REPORT = '%s/job/%s/lastSuccessfulBuild/testReport' + API;
LAST_BUILD = '%s/job/%s/lastBuild' + API;
LAST_COMPLETED_BUILD = '%s/job/%s/lastCompletedBuild' + API;
LAST_REPORT = '%s/job/%s/lastBuild/testReport' + API;
QUEUE = '%s/queue' + API;
COMPUTERS = '%s/computer' + API;
JOB_OUTPUT = '%s/job/%s/consoleText' + API;

var init = exports.init = function(host) {

    //Jenkin variables
    var host = host;

    //Helper Functions
    var build_url = function(command) {
        /*
        Builds REST url to Jenkins
        */

        // Create the url using the format function
        var url = util.format.call(this, command, host);

        // if command is the only arg, we are done
        if (arguments.length == 1) return url;

        // Grab the arguments except for the first (command)
        var args = Array.prototype.slice.call(arguments).slice(1);

        // Append url to front of args array
        args.unshift(url);

        // Create full url with all the arguments
        url = util.format.apply(this, args);

        return url;

    }
    return {
        build: function(jobname, params, callback) {
            /*
            Trigger Jenkins to build.
            */
            if (typeof params === 'function') {
                buildurl = build_url(BUILD, jobname)
                callback = params;
            } else {
                buildurl = build_url(BUILDWITHPARAMS+"?"+qs.stringify(params), jobname)
            }

            request({method: 'POST', url: buildurl }, function(error, response, body) {
                if ( error || (response.statusCode !== 201 && response.statusCode !== 302) ) {
                    callback(error, response);
                    return;
                }
                data = "job is executed"
                callback(null, data);
            });
        },
        all_jobs: function(callback) {
            /*
            Return a list of object literals containing the name and color of all jobs on the Jenkins server
            */
            request({method: 'GET', url: build_url(LIST)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString()).jobs;
                callback(null, data);
            });
        },
        job_info: function(jobname, callback) {
            /*
            Get all information for a job
            */
            request({method: 'GET', url: build_url(JOBINFO, jobname)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString());
                callback(null, data);
            });
        },
        last_build_info: function(jobname, callback) {
            /*
            Get information for the last build of a job
            */
            request({method: 'GET', url: build_url(LAST_BUILD, jobname)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString());
                callback(null, data);
            });
        },
        last_completed_build_info: function(jobname, callback) {
            /*
            Get information for the last completed build of a job
            */
            request({method: 'GET', url: build_url(LAST_COMPLETED_BUILD, jobname)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString());
                callback(null, data);
            });
        },
        build_info: function(jobname, number, callback) {
            /*
            Get information for the build number of a job
            */
            request({method: 'GET', url: build_url(BUILD, jobname, number)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString());
                callback(null, data);
            });
        },
        last_build_report: function(jobname, callback) {
            /*
            Get the last build report for a job
            */
            request({method: 'GET', url: build_url(LAST_REPORT, jobname)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString());
                callback(null, data);
            });
        },
        get_config_xml: function(jobname, callback) {
            /*
            Get the config xml for a job
            */
            request({method: 'GET', url: build_url(CONFIG, jobname)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = body;
                callback(null, data);
            });
        },
        create_job: function(jobname, job_config, callback) {
            /*
           Create a new job based on a job_config string
            */

            request(
                {method: 'POST'
                ,url: build_url(NEWJOB, jobname)
                ,body: job_config
                ,headers: { "content-type": "application/xml"}
                },

                function(error, response, body) {
                    if ( error || response.statusCode !== 200 ) {
                        callback(error || true, response);
                        return;
                    }
                    data = body;
                    callback(null, data);
                }
            );
        },
        copy_job: function(jobname, new_job, modifyfunction, callback) {
            /*
            Copies a job and allows you to pass in a function to modify the configuration
            of the job you would like to copy
            */

            var self = this;
            self.get_config_xml(jobname, function(error, data) {
                if (error) {
                    callback(error, data);
                    return;
                }
                self.create_job(new_job, modifyfunction(data), function(error, data) {
                    if (error) {
                        callback(error, data);
                        return;
                    }
                    callback(null, data);
                });
            });

        },
        delete_job: function(jobname, callback) {
            /*
            Deletes a job
            */
            request({method: 'POST', url: build_url(DELETE, jobname)}, function(error, response, body) {
                if ( error || response.statusCode === 404 ) {
                    callback(error || true, response);
                    return;
                }
                callback(null, body);
            });

        },
        disable_job: function(jobname, callback) {
            /*
            Disables a job
            */
            request({method: 'POST', url: build_url(DISABLE, jobname)}, function(error, response, body) {
                if ( error || response.statusCode === 404 ) {
                    callback(error || true, response);
                    return;
                }
                callback(null, body);
            });
        },
        enable_job: function(jobname, callback) {
            /*
            Enables a job
            */
            request({method: 'POST', url: build_url(ENABLE, jobname)}, function(error, response, body) {
                if ( error || response.statusCode === 404 ) {
                    callback(error || true, response);
                    return;
                }
                callback(null, body);
            });
        },
        last_success: function(jobname, callback) {
            /*
            Get the last build report for a job
            */
            request({method: 'POST', url: build_url(LAST_SUCCESS, jobname)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body);
                callback(null, data);
            });

        },
        last_result: function(jobname, callback) {
            /*
            Get the last result for a job
            */
            self = this;
            self.job_info(jobname, function(error, data) {
                last_result_url = data['lastBuild']['url'];

                request({method: 'GET', url: build_url(last_result_url + API, jobname)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                        callback(error || true, response);
                        return;
                    }
                    data = JSON.parse(body);
                    callback(null, data);
                });
            });

        },
        queue: function(callback) {
            /*
             Get all queued items
             */
            request({method: 'GET', url: build_url(QUEUE)}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString());
                callback(null, data);
            });
        },
        computers: function(callback) {
            /*
             Get details about all jenkins workers including currently executing jobs
             */
            request({method: 'GET', url: build_url(COMPUTERS + '?depth=1')}, function(error, response, body) {
                if ( error || response.statusCode !== 200 ) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.parse(body.toString());
                callback(null, data);
            });
        },
        job_output: function(jobname, buildname, callback) {
            /*
            Get the output for a job's build
            */
            request({method: 'POST', url: build_url(JOB_OUTPUT, jobname + '/' + buildname)}, function(error, response, body) {
                if (response.statusCode != 200 || error) {
                    callback(error || true, response);
                    return;
                }
                data = JSON.stringify({"output": body});
                data = JSON.parse(data);
                callback(null, data);
            });
        }

    }

}

if (!module.parent) {
}
<|endoftext|>


<commit_before>'use strict'

const FS = require('fs')
const Path = require('path')
const StreamPromise = require('sb-stream-promise')
const Helpers = require('./helpers')
const BasePlugin = require('../plugins/base.js')
const Anymatch = require('anymatch')

let LessJS

class UCompiler {
  constructor() {
    this.plugins = []
  }
  addPlugin(Plugin, priority, extensions) {
    if (!Plugin) throw new Error('Invalid Plugin provided')
    if (!(extensions instanceof Array)) throw new Error('Invalid Extensions provided')
    priority = priority || 100
    this.plugins.push({plugin: new Plugin(this), priority, extensions})
  }
  compileFile(filePath, options) {
    filePath = Path.resolve(filePath)
    options = Helpers.validateParameters(filePath, options)
    return StreamPromise.create(FS.createReadStream(filePath)).then(function(contents) {
      return this.compileContents(contents, options)
    }.bind(this)).then(function(contents) {
      return {options, contents}
    })
  }
  compileDirectory(dirPath, options, resultsHandler, ignored, recursive) {
    dirPath = Path.resolve(dirPath)

    recursive = Boolean(recursive)
    ignored = Anymatch(ignored || /[\/\\]\./)
    resultsHandler = resultsHandler || UCompiler.defaultOutput
    return new Promise(function(resolve, reject) {
      const contents = FS.readdirSync(dirPath)
      const promises = []
      contents.forEach(function(entry) {
        const fullPath = Path.join(dirPath, entry)
        if (ignored(fullPath) || ignored(entry))
          return
        const stat = FS.statSync(fullPath)
        if (stat.isFile()) {
          promises.push(this.compileFile(fullPath, options).then(resultsHandler))
        } else if (stat.isDirectory() && recursive) {
          promises.push(this.compileDirectory(fullPath, options, resultsHandler, ignored, recursive))
        }
      }.bind(this))
      resolve(Promise.all(promises))
    }.bind(this))
  }
  compile(path, options, resultsHandler, ignored, recursive) {
    path = Path.resolve(path)
    return new Promise(function(resolve, reject) {
      const stat = FS.statSync(path)
      if (stat.isFile()) {
        resolve(this.compileFile(path, options).then(resultsHandler))
      } else if (stat.isDirectory()) {
        resolve(this.compileDirectory(path, options, resultsHandler, ignored, recursive))
      } else reject(new Error('Unknown File Type'))
    }.bind(this))
  }

  // Don't use this directly unless you know what you're doing
  compileContents(contents, options) {
    return this.plugins.sort(function(a, b) {
      return a.priority - b.priority
    }).filter(function(entry) {
      return entry.extensions.indexOf(options.internal.file.extension) !== -1 || entry.extensions.indexOf('*') !== -1
    }).reduce(function(promise, entry) {
      return promise.then(function(updatedContents) {
        return entry.plugin.compile(updatedContents, options)
      })
    }, Promise.resolve(contents))
  }
  static defaultOutput(Output) {
    const Options = Output.options
    Output = Output.contents
    if(Options.Output){
      FS.writeFileSync(Options.Output, Output)
    } else {
      process.stdout.write(Output)
    }
  }
  static defaultError(error) {
    let col = 0, line = 0, trace = ''
    if (error.loc) {
      line = error.loc.line || error.loc.row || 0
      col = error.loc.column || error.loc.col || error.loc.index || 0
    } else if (error.location) {
      line = error.location.line || error.location.row || 0
      col = error.location.column || error.location.col || error.location.index || 0
    } else if (error.position) {
      line = error.position.line || error.position.row || 0
      col = error.position.column || error.position.col || error.position.index || 0
    }

    line = line || error.line || error.row || 0
    col = col || error.col ||  error.column || error.index || 0
    trace = trace || error.codeFrame || error.trace || ''
    file = error.file || error.fileName || error.filename || null

    console.error('Error caught on line', line, 'col', col, (file ? 'in file ' + file : ''), ':', error.message, "\n" + trace)
  }
}

module.exports = UCompiler
module.exports.BasePlugin = BasePlugin
<commit_msg>:bug: Fix an undefined variable<commit_after>'use strict'

const FS = require('fs')
const Path = require('path')
const StreamPromise = require('sb-stream-promise')
const Helpers = require('./helpers')
const BasePlugin = require('../plugins/base.js')
const Anymatch = require('anymatch')

let LessJS

class UCompiler {
  constructor() {
    this.plugins = []
  }
  addPlugin(Plugin, priority, extensions) {
    if (!Plugin) throw new Error('Invalid Plugin provided')
    if (!(extensions instanceof Array)) throw new Error('Invalid Extensions provided')
    priority = priority || 100
    this.plugins.push({plugin: new Plugin(this), priority, extensions})
  }
  compileFile(filePath, options) {
    filePath = Path.resolve(filePath)
    options = Helpers.validateParameters(filePath, options)
    return StreamPromise.create(FS.createReadStream(filePath)).then(function(contents) {
      return this.compileContents(contents, options)
    }.bind(this)).then(function(contents) {
      return {options, contents}
    })
  }
  compileDirectory(dirPath, options, resultsHandler, ignored, recursive) {
    dirPath = Path.resolve(dirPath)

    recursive = Boolean(recursive)
    ignored = Anymatch(ignored || /[\/\\]\./)
    resultsHandler = resultsHandler || UCompiler.defaultOutput
    return new Promise(function(resolve, reject) {
      const contents = FS.readdirSync(dirPath)
      const promises = []
      contents.forEach(function(entry) {
        const fullPath = Path.join(dirPath, entry)
        if (ignored(fullPath) || ignored(entry))
          return
        const stat = FS.statSync(fullPath)
        if (stat.isFile()) {
          promises.push(this.compileFile(fullPath, options).then(resultsHandler))
        } else if (stat.isDirectory() && recursive) {
          promises.push(this.compileDirectory(fullPath, options, resultsHandler, ignored, recursive))
        }
      }.bind(this))
      resolve(Promise.all(promises))
    }.bind(this))
  }
  compile(path, options, resultsHandler, ignored, recursive) {
    path = Path.resolve(path)
    return new Promise(function(resolve, reject) {
      const stat = FS.statSync(path)
      if (stat.isFile()) {
        resolve(this.compileFile(path, options).then(resultsHandler))
      } else if (stat.isDirectory()) {
        resolve(this.compileDirectory(path, options, resultsHandler, ignored, recursive))
      } else reject(new Error('Unknown File Type'))
    }.bind(this))
  }

  // Don't use this directly unless you know what you're doing
  compileContents(contents, options) {
    return this.plugins.sort(function(a, b) {
      return a.priority - b.priority
    }).filter(function(entry) {
      return entry.extensions.indexOf(options.internal.file.extension) !== -1 || entry.extensions.indexOf('*') !== -1
    }).reduce(function(promise, entry) {
      return promise.then(function(updatedContents) {
        return entry.plugin.compile(updatedContents, options)
      })
    }, Promise.resolve(contents))
  }
  static defaultOutput(Output) {
    const Options = Output.options
    Output = Output.contents
    if(Options.Output){
      FS.writeFileSync(Options.Output, Output)
    } else {
      process.stdout.write(Output)
    }
  }
  static defaultError(error) {
    let col = 0, line = 0, trace = '', file = ''
    if (error.loc) {
      line = error.loc.line || error.loc.row || 0
      col = error.loc.column || error.loc.col || error.loc.index || 0
    } else if (error.location) {
      line = error.location.line || error.location.row || 0
      col = error.location.column || error.location.col || error.location.index || 0
    } else if (error.position) {
      line = error.position.line || error.position.row || 0
      col = error.position.column || error.position.col || error.position.index || 0
    }

    line = line || error.line || error.row || 0
    col = col || error.col ||  error.column || error.index || 0
    trace = trace || error.codeFrame || error.trace || ''
    file = error.file || error.fileName || error.filename || null

    console.error('Error caught on line', line, 'col', col, (file ? 'in file ' + file : ''), ':', error.message, "\n" + trace)
  }
}

module.exports = UCompiler
module.exports.BasePlugin = BasePlugin
<|endoftext|>


<commit_before>'use babel'
const FS = require('fs')
const Path = require('path')
const View = require('./view')
import {exec} from './helper'

window.__sb_package_deps = window.__sb_package_deps || []

export function install(packageName, enablePackages = true) {
  if (!packageName) throw new Error('packageName is required')

  const packageDeps = atom.packages.getLoadedPackage(packageName).metadata['package-deps'] || []
  const packagesToInstall = []
  packageDeps.forEach(function(name) {
    if (__sb_package_deps.indexOf(name) === -1) {
      __sb_package_deps.push(name)
      if (!atom.packages.resolvePackagePath(name)) {
        packagesToInstall.push(name)
      } else if(!atom.packages.getActivePackage(name) && enablePackages) {
        atom.packages.enablePackage(name)
        atom.packages.activatePackage(name)
      }
    }
  })
  if (packagesToInstall.length) {
    return installPackage(packageName, packagesToInstall)
  } else return Promise.resolve()
}

export function installPackage(packageName, packageNames) {
  const APMPath = atom.packages.getApmPath()
  const promises = []
  const view = new View(packageName, packageNames)
  return view.createNotification().then(() => {
    packageNames.forEach(function(name) {
      promises.push(exec(APMPath, ['install', name]))
    })
    return Promise.all(promises)
  }).then(function(outputs){
    outputs.forEach(function(output, index) {
      const name = packageNames[index]
      if (output.indexOf('✓') === -1 && output.indexOf('[32mdone') === -1) {
        view.markErrored(name, output)
      } else {
        atom.packages.enablePackage(name)
        atom.packages.activatePackage(name)
        view.markFinished()
      }
    })
  })
}
<commit_msg>:art: Specify production when installing packages<commit_after>'use babel'
const FS = require('fs')
const Path = require('path')
const View = require('./view')
import {exec} from './helper'

window.__sb_package_deps = window.__sb_package_deps || []

export function install(packageName, enablePackages = true) {
  if (!packageName) throw new Error('packageName is required')

  const packageDeps = atom.packages.getLoadedPackage(packageName).metadata['package-deps'] || []
  const packagesToInstall = []
  packageDeps.forEach(function(name) {
    if (__sb_package_deps.indexOf(name) === -1) {
      __sb_package_deps.push(name)
      if (!atom.packages.resolvePackagePath(name)) {
        packagesToInstall.push(name)
      } else if(!atom.packages.getActivePackage(name) && enablePackages) {
        atom.packages.enablePackage(name)
        atom.packages.activatePackage(name)
      }
    }
  })
  if (packagesToInstall.length) {
    return installPackage(packageName, packagesToInstall)
  } else return Promise.resolve()
}

export function installPackage(packageName, packageNames) {
  const APMPath = atom.packages.getApmPath()
  const promises = []
  const view = new View(packageName, packageNames)
  return view.createNotification().then(() => {
    packageNames.forEach(function(name) {
      promises.push(exec(APMPath, ['install', name, '--production']))
    })
    return Promise.all(promises)
  }).then(function(outputs){
    outputs.forEach(function(output, index) {
      const name = packageNames[index]
      if (output.indexOf('✓') === -1 && output.indexOf('[32mdone') === -1) {
        view.markErrored(name, output)
      } else {
        atom.packages.enablePackage(name)
        atom.packages.activatePackage(name)
        view.markFinished()
      }
    })
  })
}
<|endoftext|>


<commit_before>var fs = require('fs'),
    WritableStream = require('readable-stream').Writable,
    inherits = require('util').inherits;

var utils = require('./utils');

function Busboy(opts) {
  if (!(this instanceof Busboy))
    return new Busboy(opts);
  if (opts.highWaterMark !== undefined)
    WritableStream.call(this, { highWaterMark: opts.highWaterMark });
  else
    WritableStream.call(this);

  var self = this;
  this._parser = undefined;

  if (opts.headers && opts.headers['content-type'] !== undefined)
    this.parseHeaders(opts.headers);
  this.limits = opts.limits;
  this.once('finish', function() {
    self._parser.end();
  });
}
inherits(Busboy, WritableStream);

Busboy.prototype.parseHeaders = function(headers) {
  this._parser = undefined;
  if (headers['content-type']) {
    var parsed = utils.parseParams(headers['content-type']),
        matched, type;
    for (var i = 0; i < TYPES_LEN; ++i) {
      type = TYPES[i];
      if (typeof type.detect === 'function')
        matched = type.detect(parsed);
      else
        matched = type.detect.test(parsed[0]);
      if (matched)
        break;
    }
    if (matched) {
      this._parser = new type(this, this.limits, headers, parsed);
      return;
    }
  }
  throw new Error('Unsupported content type: ' + headers['content-type']);
};

Busboy.prototype._write = function(chunk, encoding, cb) {
  this._parser.write(chunk);
  cb();
};

var TYPES = [], TYPES_LEN = 0;
fs.readdirSync(__dirname + '/types').forEach(function(type) {
  var typemod = require(__dirname + '/types/' + type);
  if (typemod.detect) {
    TYPES.push(typemod);
    ++TYPES_LEN;
  }
});

module.exports = Busboy;
<commit_msg>main: modify content-type check<commit_after>var fs = require('fs'),
    WritableStream = require('readable-stream').Writable,
    inherits = require('util').inherits;

var utils = require('./utils');

function Busboy(opts) {
  if (!(this instanceof Busboy))
    return new Busboy(opts);
  if (opts.highWaterMark !== undefined)
    WritableStream.call(this, { highWaterMark: opts.highWaterMark });
  else
    WritableStream.call(this);

  var self = this;
  this._parser = undefined;

  if (opts.headers && typeof opts.headers['content-type'] === 'string')
    this.parseHeaders(opts.headers);
  this.limits = opts.limits;
  this.once('finish', function() {
    self._parser.end();
  });
}
inherits(Busboy, WritableStream);

Busboy.prototype.parseHeaders = function(headers) {
  this._parser = undefined;
  if (headers['content-type']) {
    var parsed = utils.parseParams(headers['content-type']),
        matched, type;
    for (var i = 0; i < TYPES_LEN; ++i) {
      type = TYPES[i];
      if (typeof type.detect === 'function')
        matched = type.detect(parsed);
      else
        matched = type.detect.test(parsed[0]);
      if (matched)
        break;
    }
    if (matched) {
      this._parser = new type(this, this.limits, headers, parsed);
      return;
    }
  }
  throw new Error('Unsupported content type: ' + headers['content-type']);
};

Busboy.prototype._write = function(chunk, encoding, cb) {
  this._parser.write(chunk);
  cb();
};

var TYPES = [], TYPES_LEN = 0;
fs.readdirSync(__dirname + '/types').forEach(function(type) {
  var typemod = require(__dirname + '/types/' + type);
  if (typemod.detect) {
    TYPES.push(typemod);
    ++TYPES_LEN;
  }
});

module.exports = Busboy;
<|endoftext|>


<commit_before>'use strict'

const childProcess = require('child_process')
const fs = require('fs')
const path = require('path')
const util = require('util')

const promisify = require('promisify-node')
const rimraf = promisify(require('rimraf'))
const yaml = require('js-yaml')

promisify(fs)

const logger = require('./logging').logger
const parseArguments = require('./arguments').parseArguments

function main () {
  const pkg = require('../package')
  const defaults = {
    name: pkg.name,
    version: pkg.version,
    description: pkg.description,
    logLevel: 'info'
  }
  const program = parseArguments(defaults, process.argv)
  logger.level = program.logLevel

  logger.info('%s v%s', pkg.name, pkg.version)

  const travisFile = path.join(process.cwd(), '.travis.yml')
  if (!fs.existsSync(travisFile)) {
    logger.error('Travis file not found: %s', travisFile)
    return 1
  }

  const travisConfig = yaml.safeLoad(fs.readFileSync(travisFile))
  if (typeof travisConfig.node_js === 'undefined') {
    logger.error('language field not found in travis configuration')
    return 1
  }

  if (travisConfig.language !== 'node_js') {
    logger.error(
      'Unexpected language in travis configuration: %s', travisConfig.language)
    return 1
  }

  if (typeof travisConfig.node_js === 'undefined') {
    logger.error('node_js field not found in travis configuration')
    return 1
  }
  logger.info('Node versions to use for testing: %s', travisConfig.node_js)

  const outputDir = '.' + pkg.name
  return rimraf(outputDir)
    .then(function () {
      logger.debug('Directory removed: %s', outputDir)
      return fs.mkdir(outputDir)
    }).then(function () {
      logger.debug('Directory created: %s', outputDir)

      return Promise.all(travisConfig.node_js.map(function (version) {
        return runTests(outputDir, version)
      }))
    }).then(function () {
      logger.info('Done!')
      return Promise.resolve(0)
    })
}

function runTests (outputDir, version) {
  const versionDir = path.join(outputDir, String(version))
  return fs.mkdir(versionDir)
    .then(function () {
      logger.debug('Directory created: %s', versionDir)
      return childProcess.exec(util.format('git clone . %s', versionDir))
    }).then(function () {
      logger.debug('[%s] Source code cloned', version)
      const command = util.format(
          'source %s/nvm.sh && nvm use %s && npm install && npm test',
          process.env.NVM_DIR, version)
      logger.debug('[%s] command: %s', version, command)
      return new Promise(function (resolve, reject) {
        childProcess.exec(
          command,
          {shell: '/bin/bash'},
          function (err, stdout, stderr) {
            logger.debug('[%s] stdout:\n%s', version, stdout)
            logger.debug('[%s] stderr:\n%s', version, stderr)
            if (err) {
              reject(err)
            } else {
              resolve()
            }
          }
        )
      })
    }).then(function () {
      logger.info('[%s] Test case execution success', version)
      return Promise.resolve(0)
    }).catch(function (err) {
      logger.error('[%s] %s', version, err.message)
      return Promise.resolve(err.code)
    })
}

module.exports = main
<commit_msg>Log which versions failed when that happens<commit_after>'use strict'

const childProcess = require('child_process')
const fs = require('fs')
const path = require('path')
const util = require('util')

const promisify = require('promisify-node')
const rimraf = promisify(require('rimraf'))
const yaml = require('js-yaml')

promisify(fs)

const logger = require('./logging').logger
const parseArguments = require('./arguments').parseArguments

function main () {
  const pkg = require('../package')
  const defaults = {
    name: pkg.name,
    version: pkg.version,
    description: pkg.description,
    logLevel: 'info'
  }
  const program = parseArguments(defaults, process.argv)
  logger.level = program.logLevel

  logger.info('%s v%s', pkg.name, pkg.version)

  const travisFile = path.join(process.cwd(), '.travis.yml')
  if (!fs.existsSync(travisFile)) {
    logger.error('Travis file not found: %s', travisFile)
    return 1
  }

  const travisConfig = yaml.safeLoad(fs.readFileSync(travisFile))
  if (typeof travisConfig.node_js === 'undefined') {
    logger.error('language field not found in travis configuration')
    return 1
  }

  if (travisConfig.language !== 'node_js') {
    logger.error(
      'Unexpected language in travis configuration: %s', travisConfig.language)
    return 1
  }

  if (typeof travisConfig.node_js === 'undefined') {
    logger.error('node_js field not found in travis configuration')
    return 1
  }
  logger.info('Node versions to use for testing: %s', travisConfig.node_js)

  const outputDir = '.' + pkg.name
  return rimraf(outputDir)
    .then(function () {
      logger.debug('Directory removed: %s', outputDir)
      return fs.mkdir(outputDir)
    }).then(function () {
      logger.debug('Directory created: %s', outputDir)

      return Promise.all(travisConfig.node_js.map(function (version) {
        return runTests(outputDir, version)
      }))
    }).then(function (results) {
      const failures = results.filter(result => result.code !== 0)
      if (failures) {
        logger.error(
          'Test execution failed for: %s',
          failures.map(result => result.version)
        )
        return Promise.resolve(1)
      }

      logger.info('Test execution success')
      return Promise.resolve(0)
    })
}

function runTests (outputDir, version) {
  const versionDir = path.join(outputDir, String(version))
  return fs.mkdir(versionDir)
    .then(function () {
      logger.debug('Directory created: %s', versionDir)
      return childProcess.exec(util.format('git clone . %s', versionDir))
    }).then(function () {
      logger.debug('[%s] Source code cloned', version)
      const command = util.format(
          'source %s/nvm.sh && nvm use %s && npm install && npm test',
          process.env.NVM_DIR, version)
      logger.debug('[%s] command: %s', version, command)
      return new Promise(function (resolve, reject) {
        childProcess.exec(
          command,
          {shell: '/bin/bash'},
          function (err, stdout, stderr) {
            logger.debug('[%s] stdout:\n%s', version, stdout)
            logger.debug('[%s] stderr:\n%s', version, stderr)
            if (err) {
              reject(err)
            } else {
              resolve()
            }
          }
        )
      })
    }).then(function () {
      logger.info('[%s] Test case execution success', version)
      return Promise.resolve({version, returnCode: 0})
    }).catch(function (err) {
      logger.error('[%s] %s', version, err.message)
      return Promise.resolve({version, returnCode: err.code})
    })
}

module.exports = main
<|endoftext|>


<commit_before>import Ember from 'ember';
import { moduleFor, test } from 'ember-qunit';
import { pilasMock, interpreterFactoryMock, interpreteMock, actividadMock } from '../../helpers/mocks';
import sinon from 'sinon';

moduleFor('component:pilas-blockly', 'Unit | Components | pilas-blockly', {
  // Specify the other units that are required for this test.
  // needs: ['controller:foo']
  setup() {
    this.register('service:interpreterFactory', interpreterFactoryMock);
    let ctrl = this.subject();
    ctrl.pilas = pilasMock; //TODO: Injectar como service
    ctrl.descargar = sinon.spy();
    ctrl.set('modelActividad', actividadMock);
    sinon.resetHistory();
  }
});

//TODO: Ver de agrupar en modules
test('Al ejecutar se encuentra ejecutando y ejecuta el intérprete', function(assert) {
  let ctrl = this.subject();
  ctrl.send('ejecutar');

  assert.ok(ctrl.get('ejecutando'));
  assert.notOk(ctrl.get('pausadoEnBreakpoint'));
  assert.ok(interpreteMock.run.called);
});

test('Ejecutar paso a paso bloquea la ejecución', function(assert) {
  let ctrl = this.subject();
  ctrl.send('ejecutar', true);
  //TODO: Test 'step'

  Ember.run.later(() => {
    assert.ok(interpreteMock.run.calledOnce);
    assert.ok(ctrl.get('pausadoEnBreakpoint'));
  });
});

test('Luego de ejecutar termina de ejecutar', function(assert) {
  let ctrl = this.subject();
  ctrl.send('ejecutar');

  Ember.run.later(() => {
    assert.notOk(ctrl.get('ejecutando'));
    assert.ok(ctrl.get('terminoDeEjecutar'));
    assert.notOk(ctrl.get('highlightedBlock'));
  });
});

test('Al resolver el problema muestra el fin del desafío', function(assert) {
  let ctrl = this.subject();
  ctrl.set('debeMostrarFinDeDesafio', true);
  ctrl.send('ejecutar');

  Ember.run.later(() => {
    assert.ok(ctrl.get('mostrarDialogoFinDesafio'));
  });
});

test('Al reiniciar settea flags y reinicia la escena de pilas', function(assert) {
  let ctrl = this.subject();
  ctrl.send('reiniciar');

  assert.notOk(ctrl.get('highlightedBlock'));
  assert.notOk(ctrl.get('ejecutando'));
  assert.notOk(ctrl.get('terminoDeEjecutar'));
  assert.notOk(ctrl.get('errorDeActividad'));
  assert.ok(pilasMock.reiniciarEscenaCompleta.called);
});

test('Al guardar solución hace una descarga con la solución', function(assert) {
  let ctrl = this.subject();
  ctrl.send('guardarSolucion');

  assert.ok(ctrl.descargar.calledWith(
    JSON.stringify({version:1, actividad:"Actividad_Mock", solucion:""}),
    'Actividad_Mock.spbq',
    'application/octet-stream'
  ));
});<commit_msg>Testing step<commit_after>import Ember from 'ember';
import { moduleFor, test } from 'ember-qunit';
import { pilasMock, interpreterFactoryMock, interpreteMock, actividadMock } from '../../helpers/mocks';
import sinon from 'sinon';

moduleFor('component:pilas-blockly', 'Unit | Components | pilas-blockly', {
  // Specify the other units that are required for this test.
  // needs: ['controller:foo']
  setup() {
    this.register('service:interpreterFactory', interpreterFactoryMock);
    let ctrl = this.subject();
    ctrl.pilas = pilasMock; //TODO: Injectar como service
    ctrl.descargar = sinon.spy();
    ctrl.set('modelActividad', actividadMock);
    sinon.resetHistory();
  }
});

//TODO: Ver de agrupar en modules
test('Al ejecutar se encuentra ejecutando y ejecuta el intérprete', function(assert) {
  let ctrl = this.subject();
  ctrl.send('ejecutar');

  assert.ok(ctrl.get('ejecutando'));
  assert.notOk(ctrl.get('pausadoEnBreakpoint'));
  assert.ok(interpreteMock.run.called);
});

test('Ejecutar paso a paso bloquea la ejecución', function(assert) {
  let ctrl = this.subject();
  ctrl.send('ejecutar', true);

  Ember.run.later(() => {
    assert.ok(interpreteMock.run.calledOnce);
    assert.ok(ctrl.get('pausadoEnBreakpoint'));
  });
});

test('Step desbloquea el breakpoint', function(assert) {
  let ctrl = this.subject();
  ctrl.send('ejecutar', true);

  Ember.run.later(() => {
    assert.ok(ctrl.get('pausadoEnBreakpoint'));
    ctrl.send('step');
    assert.notOk(ctrl.get('pausadoEnBreakpoint'));
  });
});

test('Luego de ejecutar termina de ejecutar', function(assert) {
  let ctrl = this.subject();
  ctrl.send('ejecutar');

  Ember.run.later(() => {
    assert.notOk(ctrl.get('ejecutando'));
    assert.ok(ctrl.get('terminoDeEjecutar'));
    assert.notOk(ctrl.get('highlightedBlock'));
  });
});

test('Al resolver el problema muestra el fin del desafío', function(assert) {
  let ctrl = this.subject();
  ctrl.set('debeMostrarFinDeDesafio', true);
  ctrl.send('ejecutar');

  Ember.run.later(() => {
    assert.ok(ctrl.get('mostrarDialogoFinDesafio'));
  });
});

test('Al reiniciar settea flags y reinicia la escena de pilas', function(assert) {
  let ctrl = this.subject();
  ctrl.send('reiniciar');

  assert.notOk(ctrl.get('highlightedBlock'));
  assert.notOk(ctrl.get('ejecutando'));
  assert.notOk(ctrl.get('terminoDeEjecutar'));
  assert.notOk(ctrl.get('errorDeActividad'));
  assert.ok(pilasMock.reiniciarEscenaCompleta.called);
});

test('Al guardar solución hace una descarga con la solución', function(assert) {
  let ctrl = this.subject();
  ctrl.send('guardarSolucion');

  assert.ok(ctrl.descargar.calledWith(
    JSON.stringify({version:1, actividad:"Actividad_Mock", solucion:""}),
    'Actividad_Mock.spbq',
    'application/octet-stream'
  ));
});<|endoftext|>


<commit_before>GRUNT.Testing = (function() {
    // initialise variables
    var testSuites = {};

    var module = GRUNT.newModule({
        id: "grunt.test",
        requires: ["grunt.core"],

        STATUS: {
            notrun: 0,
            running: 1,
            waiting: 2,
            readyToContinue: 3
        },

        /* reporting functions */

        reportProgress: function(message) {
            SLICK.Log.info("TEST FRAMEWORK: " + message);
        },

        reportException: function(error) {
            SLICK.Log.exception(error);
        },

        /* Test Definition */

        Test: function(params) {
            params = GRUNT.extend({
                title: "Untitled Test",
                autoReady: false,
                runner: null
            }, params);

            // define self
            var self = {
                status: module.STATUS.notrun,

                run: function(testData) {
                    if (params.runner) {
                        self.status = module.STATUS.running;
                        try {
                            module.reportProgress("Running test " + self.title);
                            params.runner(self, testData);
                        }
                        catch (e) {
                            module.reportException(e);
                        }
                        finally {
                            self.status = module.STATUS.waiting;
                        } // try..finally
                    } // if

                    // if the test style is
                    if (params.autoReady) {
                        self.ready();
                    } // if
                },

                ready: function() {
                    self.status = module.STATUS.readyToContinue;
                }
            };

            return self;
        },

        /* test suite */

        registerSuite: function(id, suite) {
            if (id) {
                testSuites[id] = suite;
            } // if
        },

        runSuite: function(id) {
            if (id && testSuites[id]) {
                testSuites[id].run();
            } // if
        },

        Suite: function(params) {
            params = GRUNT.extend({
                id: "untitled.suite",
                description: "",
                tests: [],
                testData: {},
                setup: null,
                teardown: null
            }, params);

            var testQueue = [];
            var activeTest = null;
            var runInterval = 0;

            // define self
            var self = {
                /**
                The queue function is used to queue a new test for execution in the current test module.
                */
                add: function(test) {
                    testQueue.push(test);
                },

                run: function() {
                    // if we have an active test, then returm
                    if (activeTest) {
                        throw new Error("Test Suite already running");
                    } // if

                    // if we have a setup method, then set it up
                    if (params.setup) {
                        params.setup();
                    } // if

                    var ii = 0;

                    // start the run loop
                    runInterval = setInterval(function() {
                        // while we have tests to complete, run
                        if (ii < testQueue.length) {
                            // update the active test
                            activeTest = testQueue[ii];

                            // skip null tests (just in case)
                            if (! activeTest) {
                                ii++;
                            }
                            // execute the test
                            else {
                                if (activeTest.status == module.STATUS.notrun) {
                                    activeTest.run(params.testData);
                                } // if

                                // if the current test is ready to continue, the increment the index
                                if (activeTest.status == module.STATUS.readyToContinue) {
                                    ii++;
                                } // if
                            } // if..else
                        }
                        else {
                            self.stop();
                        } // if..else
                    }, 200);
                },

                stop: function() {
                    if (activeTest) {
                        // clear the interval
                        clearInterval(runInterval);

                        // if we have a teardown task
                        if (params.teardown) {
                            params.teardown();
                        } // if
                    } // if
                }
            }; // self

            // iterate through the tests defined in the parameters, and add them
            for (var ii = 0; ii < params.tests.length; ii++) {
                self.add(new module.Test(params.tests[ii]));
            } // for

            // register the test suite
            module.registerSuite(params.id, self);

            return self;
        }
    });

    return module;
})();<commit_msg>Added test framework reporting functions<commit_after>GRUNT.Testing = (function() {
    // initialise variables
    var testSuites = {};

    var module = GRUNT.newModule({
        id: "grunt.test",
        requires: ["grunt.core"],

        STATUS: {
            notrun: 0,
            running: 1,
            waiting: 2,
            readyToContinue: 3
        },

        /* reporting functions */

        reportProgress: function(message) {
            GRUNT.Log.info("TEST FRAMEWORK: " + message);
        },

        reportException: function(error) {
            GRUNT.Log.exception(error);
        },

        /* Test Definition */

        Test: function(params) {
            params = GRUNT.extend({
                title: "Untitled Test",
                autoReady: false,
                runner: null
            }, params);

            // define self
            var self = {
                status: module.STATUS.notrun,

                run: function(testData) {
                    if (params.runner) {
                        self.status = module.STATUS.running;
                        try {
                            module.reportProgress("Running test " + self.title);
                            params.runner(self, testData);
                        }
                        catch (e) {
                            module.reportException(e);
                        }
                        finally {
                            self.status = module.STATUS.waiting;
                        } // try..finally
                    } // if

                    // if the test style is
                    if (params.autoReady) {
                        self.ready();
                    } // if
                },

                ready: function() {
                    self.status = module.STATUS.readyToContinue;
                }
            };

            return self;
        },

        /* test suite */

        registerSuite: function(id, suite) {
            if (id) {
                testSuites[id] = suite;
            } // if
        },

        runSuite: function(id) {
            if (id && testSuites[id]) {
                testSuites[id].run();
            } // if
        },

        Suite: function(params) {
            params = GRUNT.extend({
                id: "untitled.suite",
                description: "",
                tests: [],
                testData: {},
                setup: null,
                teardown: null
            }, params);

            var testQueue = [];
            var activeTest = null;
            var runInterval = 0;

            // define self
            var self = {
                /**
                The queue function is used to queue a new test for execution in the current test module.
                */
                add: function(test) {
                    testQueue.push(test);
                },

                run: function() {
                    // if we have an active test, then returm
                    if (activeTest) {
                        throw new Error("Test Suite already running");
                    } // if

                    // if we have a setup method, then set it up
                    if (params.setup) {
                        params.setup();
                    } // if

                    var ii = 0;

                    // start the run loop
                    runInterval = setInterval(function() {
                        // while we have tests to complete, run
                        if (ii < testQueue.length) {
                            // update the active test
                            activeTest = testQueue[ii];

                            // skip null tests (just in case)
                            if (! activeTest) {
                                ii++;
                            }
                            // execute the test
                            else {
                                if (activeTest.status == module.STATUS.notrun) {
                                    activeTest.run(params.testData);
                                } // if

                                // if the current test is ready to continue, the increment the index
                                if (activeTest.status == module.STATUS.readyToContinue) {
                                    ii++;
                                } // if
                            } // if..else
                        }
                        else {
                            self.stop();
                        } // if..else
                    }, 200);
                },

                stop: function() {
                    if (activeTest) {
                        // clear the interval
                        clearInterval(runInterval);

                        // if we have a teardown task
                        if (params.teardown) {
                            params.teardown();
                        } // if
                    } // if
                }
            }; // self

            // iterate through the tests defined in the parameters, and add them
            for (var ii = 0; ii < params.tests.length; ii++) {
                self.add(new module.Test(params.tests[ii]));
            } // for

            // register the test suite
            module.registerSuite(params.id, self);

            return self;
        }
    });

    return module;
})();<|endoftext|>


<commit_before>import 'babel-polyfill'
import mount from '@conveyal/woonerf/mount'

import App from './common/containers/App'
import {initializeConfig} from './common/util/config'
import * as managerReducers from './manager/reducers'
import admin from './admin/reducers'
import alerts from './alerts/reducers'
import signs from './signs/reducers'

import * as gtfsPlusReducers from './gtfsplus/reducers'
import editor from './editor/reducers'
import gtfs from './gtfs/reducers'

initializeConfig()

mount({
  app: App,
  reducers: {
    ...managerReducers,
    admin,
    alerts,
    signs,
    ...gtfsPlusReducers,
    editor,
    gtfs
  }
})
<commit_msg>refactor(reducers): refactor certain reducer imports<commit_after>import 'babel-polyfill'
import mount from '@conveyal/woonerf/mount'

import App from './common/containers/App'
import {initializeConfig} from './common/util/config'
import managerReducers from './manager/reducers'
import admin from './admin/reducers'
import alerts from './alerts/reducers'
import signs from './signs/reducers'

import gtfsPlusReducers from './gtfsplus/reducers'
import editor from './editor/reducers'
import gtfs from './gtfs/reducers'

initializeConfig()

mount({
  app: App,
  reducers: {
    ...managerReducers,
    admin,
    alerts,
    signs,
    ...gtfsPlusReducers,
    editor,
    gtfs
  }
})
<|endoftext|>


<commit_before>"use strict";

var aws = require('aws-sdk');
var exec = require('child_process').exec;
var fs = require('fs');
var os = require('os');
var packageJson = require('./../package.json');
var path = require('path');

var Lambda = function() {
  this.version = packageJson.version;

  return this;
};

Lambda.prototype._createSampleFileFile = function( ) {
  var
  envfile = process.cwd() + "/.env",
  envexamplefile = __dirname + "/.env.example";

  if ( !fs.existsSync( envfile ) ) {
    console.log( ".env file successfully created" )
    fs.writeFileSync( envfile, fs.readFileSync( envexamplefile) );
  }

};

Lambda.prototype._createEventJsonFile = function( ) {
  var
  eventfile = process.cwd() + "/event.json",
  eventexamplefile = __dirname + "/event.json.example";

  if ( !fs.existsSync( eventfile ) ) {
    console.log( "event.json file successfully created" )
    fs.writeFileSync( eventfile, fs.readFileSync( eventexamplefile ) );
  }

};

Lambda.prototype.setup = function( ) {
  console.log( "Running setup." );
  this._createEnvFile( );
  this._createEventJsonFile( );
  console.log( "Setup done. Edit the .env and event.json files as needed." );
};

Lambda.prototype.run = function( program ) {
  this._createEventJsonFile( );

  var
  dir = program.directory,
  splitHandler = program.handler.split( "." ),
  filename = splitHandler[0] + ".js",
  handlername = splitHandler[1];

  var
  handler = require( process.cwd() + "/" + filename )[handlername],
  event = require( process.cwd() + "/event.json" );

  this._runHandler( handler, event );
}

Lambda.prototype._runHandler = function( handler, event ) {
  var context = {
    done: function( ) {
      process.exit(0);
    }
  }

  handler( event, context );
};

Lambda.prototype._zipfileTmpPath = function( program ) {
  var
  ms_since_epoch = +new Date,
  filename = program.functionName + "-" + ms_since_epoch + ".zip",
  zipfile = path.join( os.tmpDir(), filename );

  return zipfile;
};

Lambda.prototype._params = function( program, buffer ) {
  var params = {
    FunctionName: program.functionName + "-" + program.environment,
    FunctionZip: buffer,
    Handler: program.handler,
    Mode: program.mode,
    Role: program.role,
    Runtime: program.runtime,
    Description: program.description,
    MemorySize: program.memorySize,
    Timeout: program.timeout
  };

  return params;
};

Lambda.prototype.deploy = function( program ) {
  this._createEnvFile( );

  aws.config.update({
    accessKeyId: program.accessKey,
    secretAccessKey: program.secretKey,
    region: program.region
  });

  var
  _this = this,
  lambda = new aws.Lambda( { apiVersion: "2014-11-11" } ),
  zipfile = _this._zipfileTmpPath( program );

  // zip up but ignore .git, .dotfiles, .log files, and the event.json file.
  console.log( "Generating zip file" );
  exec( "zip -roq " + zipfile + " * -x '.git' -x '*/\.*' -x '*/\*.log' -x 'event.json'", function( err, stdout, stderr ) {
    if ( err ) {
      throw err;
    }

    console.log( "Reading zip file to memory" );
    var
    buffer = fs.readFileSync( zipfile ),
    params = _this._params( program, buffer );

    console.log( "Uploading zip file to AWS Lambda with parameters:" );
    console.log( params );

    lambda.uploadFunction( params, function( err, data ) {
      if ( err ) {
        console.log( err );
      } else {
        console.log( "Zip file done uploading. Results follow:" );
        console.log( data );
      }
    } );

  } );
}

module.exports = new Lambda( );

<commit_msg>Refactor setup process<commit_after>"use strict";

var aws = require('aws-sdk');
var exec = require('child_process').exec;
var fs = require('fs');
var os = require('os');
var packageJson = require('./../package.json');
var path = require('path');

var Lambda = function() {
  this.version = packageJson.version;

  return this;
};

Lambda.prototype._createSampleFile = function(file) {
  var exampleFile = process.cwd() + '/' + file;
  var boilerplateFile = __dirname + '/' + file + '.example';

  if (!fs.existsSync(exampleFile)) {
    fs.writeFileSync(exampleFile, fs.readFileSync(boilerplateFile));
    console.log(exampleFile + ' file successfully created');
  }

};

Lambda.prototype.setup = function( ) {
  console.log('Running setup.');
  this._createSampleFile('.env');
  this._createSampleFile('event.json');
  console.log('Setup done. Edit the .env and event.json files as needed.');
};

Lambda.prototype.run = function( program ) {
  this._createEventJsonFile( );

  var
  dir = program.directory,
  splitHandler = program.handler.split( "." ),
  filename = splitHandler[0] + ".js",
  handlername = splitHandler[1];

  var
  handler = require( process.cwd() + "/" + filename )[handlername],
  event = require( process.cwd() + "/event.json" );

  this._runHandler( handler, event );
}

Lambda.prototype._runHandler = function( handler, event ) {
  var context = {
    done: function( ) {
      process.exit(0);
    }
  }

  handler( event, context );
};

Lambda.prototype._zipfileTmpPath = function( program ) {
  var
  ms_since_epoch = +new Date,
  filename = program.functionName + "-" + ms_since_epoch + ".zip",
  zipfile = path.join( os.tmpDir(), filename );

  return zipfile;
};

Lambda.prototype._params = function( program, buffer ) {
  var params = {
    FunctionName: program.functionName + "-" + program.environment,
    FunctionZip: buffer,
    Handler: program.handler,
    Mode: program.mode,
    Role: program.role,
    Runtime: program.runtime,
    Description: program.description,
    MemorySize: program.memorySize,
    Timeout: program.timeout
  };

  return params;
};

Lambda.prototype.deploy = function( program ) {
  this._createEnvFile( );

  aws.config.update({
    accessKeyId: program.accessKey,
    secretAccessKey: program.secretKey,
    region: program.region
  });

  var
  _this = this,
  lambda = new aws.Lambda( { apiVersion: "2014-11-11" } ),
  zipfile = _this._zipfileTmpPath( program );

  // zip up but ignore .git, .dotfiles, .log files, and the event.json file.
  console.log( "Generating zip file" );
  exec( "zip -roq " + zipfile + " * -x '.git' -x '*/\.*' -x '*/\*.log' -x 'event.json'", function( err, stdout, stderr ) {
    if ( err ) {
      throw err;
    }

    console.log( "Reading zip file to memory" );
    var
    buffer = fs.readFileSync( zipfile ),
    params = _this._params( program, buffer );

    console.log( "Uploading zip file to AWS Lambda with parameters:" );
    console.log( params );

    lambda.uploadFunction( params, function( err, data ) {
      if ( err ) {
        console.log( err );
      } else {
        console.log( "Zip file done uploading. Results follow:" );
        console.log( data );
      }
    } );

  } );
}

module.exports = new Lambda( );

<|endoftext|>


<commit_before>var _               = require('underscore'),
    request         = require('request'),
    querystring     = require('querystring'),
    async           = require('async');

// Globals
var apiBase = 'https://www.googleapis.com/language/translate/v2/',
    maxGetQueryLen = 1600, // Limit is actually 2000, but let's just be safe
    concurrentLimit = 10; // Max num concurrent requests. Can be overridden by passing a new limit when requiring module

////
//  SEND REQUEST
////

// Closure that returns a function for making a
// GET request to Google with an apiKey
var getRequestWithApi = function(apiKey) {
  return function(path, data, cb) {
    var url = apiBase + path + '?' + querystring.stringify(_.extend({ 'key': apiKey }, data));
    request.get(url, globalResponseHandler(cb));
  };
};

////
//   RESPONSE HANDLERS
////

var globalResponseHandler = function(cb) {
  return function(err, res, body) {
    if (!cb || !_.isFunction(cb) return;

    // Catch connection errors
    if (err || !res) {
      var returnErr = 'Error connecting to Google';
      if (err) returnErr += ': ' + err.code;
      err = returnErr;
    } else if (res.statusCode !== 200) {
      err = 'Something went wrong. Google responded with a ' + res.statusCode;
    }
    if (err) return cb(err, null);

    // Try to parse response
    try {
      body = JSON.parse(body);
    } catch(e) {
      err = 'Could not parse response from Google: ' + body;
      return cb(err, null);
    }

    // Return response
    cb(null, body);
  };
};

var parseTranslations = function(originalStrings, done) {
  return function(err, data) {
    if (err) return done(err, null);

    // Remove nesting
    data = data.data;
    data = data.translations ? data.translations : data;

    // Add originalText to response
    originalStrings.forEach(function(s, i){
      if (data[i]) _.extend(data[i], { originalText: s });
    });

    // Return nested languages array
    done(null, data);
  };
};

var parseAvailableLanguages = function(cb) {
  return function(err, data) {
    if (err) return cb(err, null);
    cb(null, data.data.languages);
  }
};

var parseLanguageDetections = function(originalStrings, done) {
  return function(err, data) {
    if (err) return done(err, null);

    // Remove nesting and parse
    data = data.data && data.data.detections ? data.data.detections : data;
    if (data.length > 1) {
      data = data.map(function(d){ return d[0]; });
    } else {
      data = data[0];
    }

    // Add originalText to response
    originalStrings.forEach(function(s, i){
      if (data[i]) _.extend(data[i], { originalText: s });
    });

    done(null, data);
  };
};

////
//  HELPERS
////

// Return array of arrays that are short enough for Google to handle
var splitArraysForGoogle = function(arr, result) {
  if (encodeURIComponent(arr.join(',')).length > maxGetQueryLen && arr.length !== 1) {
    var mid = Math.floor(arr.length / 2);
    splitArraysForGoogle(arr.slice(0,mid), result);
    splitArraysForGoogle(arr.slice(mid, arr.length), result);
  } else {
    result.push(arr)
  }
};

////
//   PUBLIC API
////

module.exports = function(apiKey, newConcurrentLimit) {

  // Set new concurrent limit for async calls if specified
  concurrentLimit = newConcurrentLimit || concurrentLimit;

  var get = getRequestWithApi(apiKey),
      api = {};

  // TRANSLATE

  api.translate = function(strings, sourceLang, targetLang, cb) {
    if (typeof strings !== 'string' && !Array.isArray(strings)) return cb('Input source must be a string or array of strings');
    if (typeof sourceLang !== 'string') return cb('No target language specified. Must be a string');

    // Make sourceLang optional
    if (!cb) {
      cb = targetLang;
      targetLang = sourceLang;
      sourceLang = null;
    }
    if (!_.isFunction(cb)) return console.log('No callback defined');

    // Split into multiple calls if string array is longer than allowed by Google (2k limit for GET, 5k for POST)
    var queries;
    if (Array.isArray(strings) && encodeURIComponent(strings.join(',')).length > maxGetQueryLen && strings.length !== 1) {
      var stringSets = [];
      splitArraysForGoogle(strings, stringSets);
    } else if (!Array.isArray(strings)) {
      stringSets = [[strings]];
    } else {
      stringSets = [strings];
    }

    // Request options
    var data = { target: targetLang };
    if (sourceLang) data.source = sourceLang;

    // Run queries async
    // TODO Make POST requests when query is greater than 2k. More efficient -- limit for POST is 5k, compared to 2k for GET
    async.parallelLimit(stringSets, concurrentLimit, function(stringSet, done) {

      get('', _.extend({ q: stringSet }, data), parseTranslations(stringSet, done));

    }, function(err, translations) {
      if (err) return cb(err);

      // Merge and return translation
      translations = _.flatten(translations);
      if (translations.length === 1) translations = translations[0];
      cb(null, translations);
    });

  };

  // GET AVAILABLE LANGUAGES

  api.getAvailableLanguages = function(data, cb) {
    // Data param is optional
    if (_.isFunction(data)) {
      cb = data;
      data = {};
    }
    if (!_.isFunction(cb)) return console.log('No callback defined');

    get('languages', data, parseAvailableLanguages(cb));
  };

  // DETECT LANGUAGES

  api.detectLanguage = function(strings, cb) {
    if (!cb) return console.log('No callback defined');
    if (typeof strings !== 'string' && !Array.isArray(strings)) return cb('Input source must be a string or array of strings');

    // Split into multiple calls if string array is longer than allowed by Google (2k limit for GET, 5k for POST)
    var queries;
    if (Array.isArray(strings) && encodeURIComponent(strings.join(',')).length > maxGetQueryLen && strings.length !== 1) {
      var stringSets = [];
      splitArraysForGoogle(strings, stringSets);
    } else {
      stringSets = [strings];
    }

    // Run queries async
    // TODO Make POST requests when query is greater than 2k. More efficient -- limit for POST is 5k, compared to 2k for GET
    async.parallelLimit(stringSets, concurrentLimit, function(stringSet, done) {

      get('detect', { q: stringSet }, parseLanguageDetections(stringSet, done));

    }, function(err, detections) {
      if (err) return cb(err);

      // Merge arrays and return detections
      cb(null, _.flatten(detections));
    });

  };

  ////
  //   RETURN API
  ////

  return {
    translate:                api.translate,
    getAvailableLanguages:    api.getAvailableLanguages,
    detectLanguage:           api.detectLanguage
  };

};
<commit_msg>Final bug fixes<commit_after>var _               = require('underscore'),
    request         = require('request'),
    querystring     = require('querystring'),
    async           = require('async');

// Globals
var apiBase = 'https://www.googleapis.com/language/translate/v2/',
    maxGetQueryLen = 1600, // Limit is actually 2000, but let's just be safe
    concurrentLimit = 10; // Max num concurrent requests. Can be overridden by passing a new limit when requiring module

////
//  SEND REQUEST
////

// Closure that returns a function for making a
// GET request to Google with an apiKey
var getRequestWithApi = function(apiKey) {
  return function(path, data, cb) {
    var url = apiBase + path + '?' + querystring.stringify(_.extend({ 'key': apiKey }, data));
    console.log(url)
    request.get(url, globalResponseHandler(cb));
  };
};

////
//   RESPONSE HANDLERS
////

var globalResponseHandler = function(cb) {
  return function(err, res, body) {
    if (!cb || !_.isFunction(cb)) return;

    // Catch connection errors
    if (err || !res) {
      var returnErr = 'Error connecting to Google';
      if (err) returnErr += ': ' + err.code;
      err = returnErr;
    } else if (res.statusCode !== 200) {
      err = 'Something went wrong. Google responded with a ' + res.statusCode;
    }
    if (err) return cb(err, null);

    // Try to parse response
    try {
      body = JSON.parse(body);
    } catch(e) {
      err = 'Could not parse response from Google: ' + body;
      return cb(err, null);
    }

    // Return response
    cb(null, body);
  };
};

var parseTranslations = function(originalStrings, done) {
  return function(err, data) {
    if (err) return done(err, null);

    // Remove nesting
    data = data.data;
    data = data.translations ? data.translations : data;

    // Add originalText to response
    originalStrings.forEach(function(s, i){
      if (data[i]) _.extend(data[i], { originalText: s });
    });

    // Return nested languages array
    done(null, data);
  };
};

var parseAvailableLanguages = function(cb) {
  return function(err, languages) {
    if (err) return cb(err, null);
    languages = languages.data.languages;;
    if (languages[0] && !languages[0].name) languages = _.pluck(languages, 'language');
    cb(null, languages);
  }
};

var parseLanguageDetections = function(originalStrings, done) {
  return function(err, data) {
    if (err) return done(err, null);

    // Remove nesting and parse
    data = data.data && data.data.detections ? data.data.detections : data;
    if (data.length > 1) {
      data = data.map(function(d){ return d[0]; });
    } else {
      data = data[0];
    }

    // Add originalText to response
    originalStrings.forEach(function(s, i){
      if (data[i]) _.extend(data[i], { originalText: s });
    });

    done(null, data);
  };
};

////
//  HELPERS
////

// Return array of arrays that are short enough for Google to handle
var splitArraysForGoogle = function(arr, result) {
  if (encodeURIComponent(arr.join(',')).length > maxGetQueryLen && arr.length !== 1) {
    var mid = Math.floor(arr.length / 2);
    splitArraysForGoogle(arr.slice(0,mid), result);
    splitArraysForGoogle(arr.slice(mid, arr.length), result);
  } else {
    result.push(arr)
  }
};

////
//   PUBLIC API
////

module.exports = function(apiKey, newConcurrentLimit) {

  // Set new concurrent limit for async calls if specified
  concurrentLimit = newConcurrentLimit || concurrentLimit;

  var get = getRequestWithApi(apiKey),
      api = {};

  // TRANSLATE

  api.translate = function(strings, sourceLang, targetLang, cb) {
    if (typeof strings !== 'string' && !Array.isArray(strings)) return cb('Input source must be a string or array of strings');
    if (typeof sourceLang !== 'string') return cb('No target language specified. Must be a string');

    // Make sourceLang optional
    if (!cb) {
      cb = targetLang;
      targetLang = sourceLang;
      sourceLang = null;
    }
    if (!_.isFunction(cb)) return console.log('No callback defined');

    // Split into multiple calls if string array is longer than allowed by Google (2k limit for GET, 5k for POST)
    var queries;
    if (Array.isArray(strings) && encodeURIComponent(strings.join(',')).length > maxGetQueryLen && strings.length !== 1) {
      var stringSets = [];
      splitArraysForGoogle(strings, stringSets);
    } else if (!Array.isArray(strings)) {
      stringSets = [[strings]];
    } else {
      stringSets = [strings];
    }

    // Request options
    var data = { target: targetLang };
    if (sourceLang) data.source = sourceLang;

    // Run queries async
    // TODO Make POST requests when query is greater than 2k. More efficient -- limit for POST is 5k, compared to 2k for GET
    async.mapLimit(stringSets, concurrentLimit, function(stringSet, done) {

      get('', _.extend({ q: stringSet }, data), parseTranslations(stringSet, done));

    }, function(err, translations) {
      if (err) return cb(err);

      // Merge and return translation
      translations = _.flatten(translations);
      if (translations.length === 1) translations = translations[0];
      cb(null, translations);
    });

  };

  // GET AVAILABLE LANGUAGES

  api.getAvailableLanguages = function(target, cb) {
    // Data param is optional
    if (_.isFunction(target)) {
      cb = target;
      target = {};
    } else {
      target = { target: target };
    }
    if (!_.isFunction(cb)) return console.log('No callback defined');

    get('languages', target, parseAvailableLanguages(cb));
  };

  // DETECT LANGUAGES

  api.detectLanguage = function(strings, cb) {
    if (!cb) return console.log('No callback defined');
    if (typeof strings !== 'string' && !Array.isArray(strings)) return cb('Input source must be a string or array of strings');

    // Split into multiple calls if string array is longer than allowed by Google (2k limit for GET, 5k for POST)
    var queries;
    if (Array.isArray(strings) && encodeURIComponent(strings.join(',')).length > maxGetQueryLen && strings.length !== 1) {
      var stringSets = [];
      splitArraysForGoogle(strings, stringSets);
    } else if (!Array.isArray(strings)) {
      stringSets = [[strings]];
    } else {
      stringSets = [strings];
    }

    // Run queries async
    // TODO Make POST requests when query is greater than 2k. More efficient -- limit for POST is 5k, compared to 2k for GET
    async.mapLimit(stringSets, concurrentLimit, function(stringSet, done) {

      get('detect', { q: stringSet }, parseLanguageDetections(stringSet, done));

    }, function(err, detections) {
      if (err) return cb(err);

      // Merge arrays and return detections
      detections = _.flatten(detections);
      if (detections.length === 1) detections = detections[0];
      cb(null, detections);

    });

  };

  ////
  //   RETURN API
  ////

  return {
    translate:                api.translate,
    getAvailableLanguages:    api.getAvailableLanguages,
    detectLanguage:           api.detectLanguage
  };

};
<|endoftext|>