<commit_before>var db = require('./../db_actions');
var android = require('./deploy');
var sync = jxcore.utils.cmdSync;
var tester = require('../internal/tester');
var exec = require('child_process').exec;
var path = require('path');
var fs = require('fs');

var eopts = {
  encoding: 'utf8',
  timeout: 0,
  maxBuffer: 1e9,
  killSignal: 'SIGTERM'
};

var serverChild = null;
var taskerBusy = false;
var lastStartTime = 0;
var taskerReset = false;
var activeJob = null;
var taskCounter = 0;
var iosChild;

function runIos(job, cb) {
  logme("iOS test task is running", 'yellow')
  var job64 = new Buffer(JSON.stringify(job), "").toString("base64");

  return exec("cd " + __dirname + "; jx ios.js " + job64, eopts, function (err, stdout, stderr) {
    if (err) {
      tester.report(job, "ios", err + stdout + stderr, false);
    } else {
      tester.report(job, "ios", false, true);
    }
    logme("iOS test task FINISHED");
    cb(1);
  });
}

// ios callback returns 1, android 2
// if itemTotal == total test numbers, then do not wait for integration server to shutdown
var itemTotal = 0;

var runTask = function (job) {
  var cb = function (itemNumber) {
    if (itemNumber)
      itemTotal -= itemNumber;

    taskCounter--;
    if (taskCounter <= 0 || itemTotal == 0) {
      taskCounter = 0;
      if (!activeJob) return;
      logme("Test " + activeJob.uqID + " has finished", "green");
      taskerReset = true;
      // rebooting nodes give some time

      if (serverChild) {
        serverChild.killing = true;
        logme("Killing IS child");
        sync("cd " + process.cwd() + "/tasker;ssh pi@192.168.1.150 'bash -s' < pkill.sh");
      }

      setTimeout(function () {
        logme("Cleaning up");
        // test is finished
        taskerBusy = false;
        taskerReset = false;
        db.removeJob(activeJob);

        sync("cd " + __dirname + ";rm -rf results/" + activeJob.uqID + "/; rm -rf ../builder/builds/" + activeJob.uqID);

        tester.commitLog(activeJob.uqID);
        activeJob = null;
      }, 5000);
    }
  };

  var res = sync("cd " + __dirname + ";rm -rf results/" + job.uqID + "/;mkdir -p results/" + job.uqID);
  if (res.exitCode) {
    logme("Error while creating the logs folder: ", err, stdout, stderr, "red");
    process.exit(1);
  }

  // it's important delay==1 if there is no server script to run
  // see delay setTimeout below for details
  var delay = 1;

  if (job.config.serverScript && job.config.serverScript.length) {
    delay = 4000;
    var p = path.join(process.cwd(), "builder/builds/server_" + job.uqID);

    if (job.config.serverScript[job.config.serverScript.length-1] != '/')
      job.config.serverScript += "/";

    var ijs_location = path.join(p , job.config.serverScript, "index.js");
    if (!fs.existsSync(ijs_location)) {
      tester.report(job, 'server', "Integration server application folder doesn't have an index.js file.\n\n"
        + "Location:`" + ijs_location + "`"
        + "\n\nTerminating the test.", false);
      cb();
      return;
    }

    var rs_path = process.cwd() + "/tasker/runServerRemote__.sh";
    var rs_final = process.cwd() + "/tasker/runServerRemote.sh";
    var sloc = path.join("server_" + job.uqID + "/", job.config.serverScript);

    p += " pi@192.168.1.150:~/Test/" + sloc;

    var src = fs.readFileSync(rs_path) + "";
    src = src.replace("{{SERVER_LOCATION}}", sloc);
    src = src.replace("{{TARGET}}", job.target);

    fs.writeFileSync(rs_final, src);

    logme("IS Args:", p);
    serverChild = exec("cd " + process.cwd() + "/tasker;chmod +x ./runServer.sh;./runServer.sh " + p,
      eopts, function (err, stdout, stderr) {
      if (err && !serverChild.killing) {
        tester.report(job, 'server', err + stdout + stderr, false);
        if (taskCounter >= 0) {
          if (job.target == "all") {
            iosChild && iosChild.kill();
            android && android.leave();
          } else {
            if (job.target == "ios") {
              iosChild && iosChild.kill();
            } else {
              android && android.leave();
            }
          }
        }
      } else {
        tester.report(job, 'server', stdout + stderr, true);
      }
      serverChild = null;

      logme("IS exiting");

      sync("rm " + rs_final);
      sync("cd " + process.cwd() + "/tasker; ssh pi@192.168.1.150 'bash -s' < cleanupServer.sh");
      sync("rm -rf " + p);
    });
  }

  setTimeout(function () {
    itemTotal = 0;
    if (delay > 1 && serverChild == null) {
      // serverScript task has failed. do not run tests
      logme("serverChild execution has failed", "red");
      cb();
    } else {
      if (job.target == "all" || job.target == "ios") {
        taskCounter++;
        itemTotal += 1;
        iosChild = runIos(job, cb);
      }

      if (job.target == "all" || job.target == "android") {
        taskCounter++;
        itemTotal += 2;
        android.test(job, 0, cb);
      }
    }
  }, delay);
};

var testTask = function () {
  if (taskerBusy) {
    // a build operation can not take longer than 40 minutes
    if (Date.now() - lastStartTime > 2400000) {
      if (taskerReset)
        return;

      taskerReset = true;
      if (serverChild) {
        serverChild.killing = true;
        sync("cd " + process.cwd() + "/tasker;ssh pi@192.168.1.150 'bash -s' < pkill.sh");
      }
      android.leave();
      if (iosChild)
        iosChild.kill();
    }
    return;
  }

  // anything in the queue ?
  var job = db.getJob(false);

  if (!job || job.noJob) return;

  // start VM from snapshot
  taskerBusy = true;
  activeJob = job;

  var delay = 45000; // phones were rebooting
  // randomly also restart the raspberries
  sync("cd " + __dirname + ";./clean_nodes.sh");
  lastStartTime = Date.now() + delay;

  setTimeout(function() {
    // run task
    runTask(job);
  }, delay);
};

setInterval(testTask, 3000);<commit_msg>Extend delay for tests so that server is started<commit_after>var db = require('./../db_actions');
var android = require('./deploy');
var sync = jxcore.utils.cmdSync;
var tester = require('../internal/tester');
var exec = require('child_process').exec;
var path = require('path');
var fs = require('fs');

var eopts = {
  encoding: 'utf8',
  timeout: 0,
  maxBuffer: 1e9,
  killSignal: 'SIGTERM'
};

var serverChild = null;
var taskerBusy = false;
var lastStartTime = 0;
var taskerReset = false;
var activeJob = null;
var taskCounter = 0;
var iosChild;

function runIos(job, cb) {
  logme("iOS test task is running", 'yellow')
  var job64 = new Buffer(JSON.stringify(job), "").toString("base64");

  return exec("cd " + __dirname + "; jx ios.js " + job64, eopts, function (err, stdout, stderr) {
    if (err) {
      tester.report(job, "ios", err + stdout + stderr, false);
    } else {
      tester.report(job, "ios", false, true);
    }
    logme("iOS test task FINISHED");
    cb(1);
  });
}

// ios callback returns 1, android 2
// if itemTotal == total test numbers, then do not wait for integration server to shutdown
var itemTotal = 0;

var runTask = function (job) {
  var cb = function (itemNumber) {
    if (itemNumber)
      itemTotal -= itemNumber;

    taskCounter--;
    if (taskCounter <= 0 || itemTotal == 0) {
      taskCounter = 0;
      if (!activeJob) return;
      logme("Test " + activeJob.uqID + " has finished", "green");
      taskerReset = true;
      // rebooting nodes give some time

      if (serverChild) {
        serverChild.killing = true;
        logme("Killing IS child");
        sync("cd " + process.cwd() + "/tasker;ssh pi@192.168.1.150 'bash -s' < pkill.sh");
      }

      setTimeout(function () {
        logme("Cleaning up");
        // test is finished
        taskerBusy = false;
        taskerReset = false;
        db.removeJob(activeJob);

        sync("cd " + __dirname + ";rm -rf results/" + activeJob.uqID + "/; rm -rf ../builder/builds/" + activeJob.uqID);

        tester.commitLog(activeJob.uqID);
        activeJob = null;
      }, 5000);
    }
  };

  var res = sync("cd " + __dirname + ";rm -rf results/" + job.uqID + "/;mkdir -p results/" + job.uqID);
  if (res.exitCode) {
    logme("Error while creating the logs folder: ", err, stdout, stderr, "red");
    process.exit(1);
  }

  // it's important delay==1 if there is no server script to run
  // see delay setTimeout below for details
  var delay = 1;

  if (job.config.serverScript && job.config.serverScript.length) {
    delay = 180000;  // just to make sure server scripts are copied and server is started
    var p = path.join(process.cwd(), "builder/builds/server_" + job.uqID);

    if (job.config.serverScript[job.config.serverScript.length-1] != '/')
      job.config.serverScript += "/";

    var ijs_location = path.join(p , job.config.serverScript, "index.js");
    if (!fs.existsSync(ijs_location)) {
      tester.report(job, 'server', "Integration server application folder doesn't have an index.js file.\n\n"
        + "Location:`" + ijs_location + "`"
        + "\n\nTerminating the test.", false);
      cb();
      return;
    }

    var rs_path = process.cwd() + "/tasker/runServerRemote__.sh";
    var rs_final = process.cwd() + "/tasker/runServerRemote.sh";
    var sloc = path.join("server_" + job.uqID + "/", job.config.serverScript);

    p += " pi@192.168.1.150:~/Test/" + sloc;

    var src = fs.readFileSync(rs_path) + "";
    src = src.replace("{{SERVER_LOCATION}}", sloc);
    src = src.replace("{{TARGET}}", job.target);

    fs.writeFileSync(rs_final, src);

    logme("IS Args:", p);
    serverChild = exec("cd " + process.cwd() + "/tasker;chmod +x ./runServer.sh;./runServer.sh " + p,
      eopts, function (err, stdout, stderr) {
      if (err && !serverChild.killing) {
        tester.report(job, 'server', err + stdout + stderr, false);
        if (taskCounter >= 0) {
          if (job.target == "all") {
            iosChild && iosChild.kill();
            android && android.leave();
          } else {
            if (job.target == "ios") {
              iosChild && iosChild.kill();
            } else {
              android && android.leave();
            }
          }
        }
      } else {
        tester.report(job, 'server', stdout + stderr, true);
      }
      serverChild = null;

      logme("IS exiting");

      sync("rm " + rs_final);
      sync("cd " + process.cwd() + "/tasker; ssh pi@192.168.1.150 'bash -s' < cleanupServer.sh");
      sync("rm -rf " + p);
    });
  }

  setTimeout(function () {
    itemTotal = 0;
    if (delay > 1 && serverChild == null) {
      // serverScript task has failed. do not run tests
      logme("serverChild execution has failed", "red");
      cb();
    } else {
      if (job.target == "all" || job.target == "ios") {
        taskCounter++;
        itemTotal += 1;
        iosChild = runIos(job, cb);
      }

      if (job.target == "all" || job.target == "android") {
        taskCounter++;
        itemTotal += 2;
        android.test(job, 0, cb);
      }
    }
  }, delay);
};

var testTask = function () {
  if (taskerBusy) {
    // a build operation can not take longer than 40 minutes
    if (Date.now() - lastStartTime > 2400000) {
      if (taskerReset)
        return;

      taskerReset = true;
      if (serverChild) {
        serverChild.killing = true;
        sync("cd " + process.cwd() + "/tasker;ssh pi@192.168.1.150 'bash -s' < pkill.sh");
      }
      android.leave();
      if (iosChild)
        iosChild.kill();
    }
    return;
  }

  // anything in the queue ?
  var job = db.getJob(false);

  if (!job || job.noJob) return;

  // start VM from snapshot
  taskerBusy = true;
  activeJob = job;

  var delay = 45000; // phones were rebooting
  // randomly also restart the raspberries
  sync("cd " + __dirname + ";./clean_nodes.sh");
  lastStartTime = Date.now() + delay;

  setTimeout(function() {
    // run task
    runTask(job);
  }, delay);
};

setInterval(testTask, 3000);
<|endoftext|>


<commit_before>var db = require('./../db_actions');
var android = require('./deploy');
var sync = jxcore.utils.cmdSync;
var tester = require('../internal/tester');
var exec = require('child_process').exec;
var path = require('path');
var fs = require('fs');

var eopts = {
  encoding: 'utf8',
  timeout: 0,
  maxBuffer: 1e9,
  killSignal: 'SIGTERM'
};

var serverChild = null;
var taskerBusy = false;
var lastStartTime = 0;
var taskerReset = false;
var activeJob = null;
var taskCounter = 0;
var iosChild;

function runIos(job, cb) {
  logme("iOS test task is running", 'yellow')
  var job64 = new Buffer(JSON.stringify(job), "").toString("base64");

  return exec("cd " + __dirname + "; jx ios.js " + job64, eopts, function (err, stdout, stderr) {
    if (err) {
      tester.report(job, "ios", err + stdout + stderr, false);
    } else {
      tester.report(job, "ios", false, true);
    }
    logme("iOS test task FINISHED");
    cb(1);
  });
}

// ios callback returns 1, android 2
// if itemTotal == total test numbers, then do not wait for integration server to shutdown
var itemTotal = 0;

var runTask = function (job) {
  var cb = function (itemNumber) {
    if (itemNumber)
      itemTotal -= itemNumber;

    taskCounter--;
    if (taskCounter <= 0 || itemTotal == 0) {
      taskCounter = 0;
      if (!activeJob) return;
      logme("Test " + activeJob.uqID + " has finished", "green");
      taskerReset = true;
      // rebooting nodes give some time

      if (serverChild) {
        serverChild.killing = true;
        logme("Killing IS child");
        sync("cd " + process.cwd() + "/tasker;ssh pi@192.168.1.150 'bash -s' < pkill.sh");
      }

      setTimeout(function () {
        logme("Cleaning up");
        // test is finished
        taskerBusy = false;
        taskerReset = false;
        db.removeJob(activeJob);

        sync("cd " + __dirname + ";rm -rf results/" + activeJob.uqID + "/; rm -rf ../builder/builds/" + activeJob.uqID);

        tester.commitLog(activeJob.uqID);
        activeJob = null;
      }, 5000);
    }
  };

  var res = sync("cd " + __dirname + ";rm -rf results/" + job.uqID + "/;mkdir -p results/" + job.uqID);
  if (res.exitCode) {
    logme("Error while creating the logs folder: ", err, stdout, stderr, "red");
    process.exit(1);
  }

  // it's important delay==1 if there is no server script to run
  // see delay setTimeout below for details
  var delay = 1;

  if (job.config.serverScript && job.config.serverScript.length) {
    delay = 4000;
    var p = path.join(process.cwd(), "builder/builds/server_" + job.uqID);

    if (job.config.serverScript[job.config.serverScript.length-1] != '/')
      job.config.serverScript += "/";

    var ijs_location = path.join(p , job.config.serverScript, "index.js");
    if (!fs.existsSync(ijs_location)) {
      tester.report(job, 'server', "Integration server application folder doesn't have an index.js file.\n\n"
        + "Location:`" + ijs_location + "`"
        + "\n\nTerminating the test.", false);
      cb();
      return;
    }

    var rs_path = process.cwd() + "/tasker/runServerRemote__.sh";
    var rs_final = process.cwd() + "/tasker/runServerRemote.sh";
    var sloc = path.join("server_" + job.uqID + "/", job.config.serverScript);

    p += " pi@192.168.1.150:~/Test/" + sloc;

    var src = fs.readFileSync(rs_path) + "";
    src = src.replace("{{SERVER_LOCATION}}", sloc);
    src = src.replace("{{TARGET}}", job.target);

    fs.writeFileSync(rs_final, src);

    logme("IS Args:", p);
    serverChild = exec("cd " + process.cwd() + "/tasker;chmod +x ./runServer.sh;./runServer.sh " + p,
      eopts, function (err, stdout, stderr) {
      if (err && !serverChild.killing) {
        tester.report(job, 'server', err + stdout + stderr, false);
        if (taskCounter >= 0) {
          if (job.target == "all") {
            iosChild.kill();
            android.leave();
          } else {
            if (job.target == "ios") {
              iosChild.kill();
            } else {
              android.leave();
            }
          }
        }
      } else {
        tester.report(job, 'server', stdout + stderr, true);
      }
      serverChild = null;

      logme("IS exiting");

      sync("rm " + rs_final);
      sync("cd " + process.cwd() + "/tasker; ssh pi@192.168.1.150 'bash -s' < cleanupServer.sh");
      sync("rm -rf " + p);
    });
  }

  setTimeout(function () {
    itemTotal = 0;
    if (delay > 1 && serverChild == null) {
      // serverScript task has failed. do not run tests
      logme("serverChild execution has failed", "red");
      cb();
    } else {
      if (job.target == "all" || job.target == "ios") {
        taskCounter++;
        itemTotal += 1;
        iosChild = runIos(job, cb);
      }

      if (job.target == "all" || job.target == "android") {
        taskCounter++;
        itemTotal += 2;
        android.test(job, 0, cb);
      }
    }
  }, delay);
};

var testTask = function () {
  if (taskerBusy) {
    // a build operation can not take longer than 40 minutes
    if (Date.now() - lastStartTime > 2400000) {
      if (taskerReset)
        return;

      taskerReset = true;
      if (serverChild) {
        serverChild.killing = true;
        sync("cd " + process.cwd() + "/tasker;ssh pi@192.168.1.150 'bash -s' < pkill.sh");
      }
      android.leave();
      if (iosChild)
        iosChild.kill();
    }
    return;
  }

  // anything in the queue ?
  var job = db.getJob(false);

  if (!job || job.noJob) return;

  // start VM from snapshot
  taskerBusy = true;
  activeJob = job;

  var delay = 45000; // phones were rebooting
  // randomly also restart the raspberries
  sync("cd " + __dirname + ";./clean_nodes.sh");
  lastStartTime = Date.now() + delay;

  setTimeout(function() {
    // run task
    runTask(job);
  }, delay);
};

setInterval(testTask, 3000);<commit_msg>Guard for undefined reference<commit_after>var db = require('./../db_actions');
var android = require('./deploy');
var sync = jxcore.utils.cmdSync;
var tester = require('../internal/tester');
var exec = require('child_process').exec;
var path = require('path');
var fs = require('fs');

var eopts = {
  encoding: 'utf8',
  timeout: 0,
  maxBuffer: 1e9,
  killSignal: 'SIGTERM'
};

var serverChild = null;
var taskerBusy = false;
var lastStartTime = 0;
var taskerReset = false;
var activeJob = null;
var taskCounter = 0;
var iosChild;

function runIos(job, cb) {
  logme("iOS test task is running", 'yellow')
  var job64 = new Buffer(JSON.stringify(job), "").toString("base64");

  return exec("cd " + __dirname + "; jx ios.js " + job64, eopts, function (err, stdout, stderr) {
    if (err) {
      tester.report(job, "ios", err + stdout + stderr, false);
    } else {
      tester.report(job, "ios", false, true);
    }
    logme("iOS test task FINISHED");
    cb(1);
  });
}

// ios callback returns 1, android 2
// if itemTotal == total test numbers, then do not wait for integration server to shutdown
var itemTotal = 0;

var runTask = function (job) {
  var cb = function (itemNumber) {
    if (itemNumber)
      itemTotal -= itemNumber;

    taskCounter--;
    if (taskCounter <= 0 || itemTotal == 0) {
      taskCounter = 0;
      if (!activeJob) return;
      logme("Test " + activeJob.uqID + " has finished", "green");
      taskerReset = true;
      // rebooting nodes give some time

      if (serverChild) {
        serverChild.killing = true;
        logme("Killing IS child");
        sync("cd " + process.cwd() + "/tasker;ssh pi@192.168.1.150 'bash -s' < pkill.sh");
      }

      setTimeout(function () {
        logme("Cleaning up");
        // test is finished
        taskerBusy = false;
        taskerReset = false;
        db.removeJob(activeJob);

        sync("cd " + __dirname + ";rm -rf results/" + activeJob.uqID + "/; rm -rf ../builder/builds/" + activeJob.uqID);

        tester.commitLog(activeJob.uqID);
        activeJob = null;
      }, 5000);
    }
  };

  var res = sync("cd " + __dirname + ";rm -rf results/" + job.uqID + "/;mkdir -p results/" + job.uqID);
  if (res.exitCode) {
    logme("Error while creating the logs folder: ", err, stdout, stderr, "red");
    process.exit(1);
  }

  // it's important delay==1 if there is no server script to run
  // see delay setTimeout below for details
  var delay = 1;

  if (job.config.serverScript && job.config.serverScript.length) {
    delay = 4000;
    var p = path.join(process.cwd(), "builder/builds/server_" + job.uqID);

    if (job.config.serverScript[job.config.serverScript.length-1] != '/')
      job.config.serverScript += "/";

    var ijs_location = path.join(p , job.config.serverScript, "index.js");
    if (!fs.existsSync(ijs_location)) {
      tester.report(job, 'server', "Integration server application folder doesn't have an index.js file.\n\n"
        + "Location:`" + ijs_location + "`"
        + "\n\nTerminating the test.", false);
      cb();
      return;
    }

    var rs_path = process.cwd() + "/tasker/runServerRemote__.sh";
    var rs_final = process.cwd() + "/tasker/runServerRemote.sh";
    var sloc = path.join("server_" + job.uqID + "/", job.config.serverScript);

    p += " pi@192.168.1.150:~/Test/" + sloc;

    var src = fs.readFileSync(rs_path) + "";
    src = src.replace("{{SERVER_LOCATION}}", sloc);
    src = src.replace("{{TARGET}}", job.target);

    fs.writeFileSync(rs_final, src);

    logme("IS Args:", p);
    serverChild = exec("cd " + process.cwd() + "/tasker;chmod +x ./runServer.sh;./runServer.sh " + p,
      eopts, function (err, stdout, stderr) {
      if (err && !serverChild.killing) {
        tester.report(job, 'server', err + stdout + stderr, false);
        if (taskCounter >= 0) {
          if (job.target == "all") {
            iosChild && iosChild.kill();
            android && android.leave();
          } else {
            if (job.target == "ios") {
              iosChild && iosChild.kill();
            } else {
              android && android.leave();
            }
          }
        }
      } else {
        tester.report(job, 'server', stdout + stderr, true);
      }
      serverChild = null;

      logme("IS exiting");

      sync("rm " + rs_final);
      sync("cd " + process.cwd() + "/tasker; ssh pi@192.168.1.150 'bash -s' < cleanupServer.sh");
      sync("rm -rf " + p);
    });
  }

  setTimeout(function () {
    itemTotal = 0;
    if (delay > 1 && serverChild == null) {
      // serverScript task has failed. do not run tests
      logme("serverChild execution has failed", "red");
      cb();
    } else {
      if (job.target == "all" || job.target == "ios") {
        taskCounter++;
        itemTotal += 1;
        iosChild = runIos(job, cb);
      }

      if (job.target == "all" || job.target == "android") {
        taskCounter++;
        itemTotal += 2;
        android.test(job, 0, cb);
      }
    }
  }, delay);
};

var testTask = function () {
  if (taskerBusy) {
    // a build operation can not take longer than 40 minutes
    if (Date.now() - lastStartTime > 2400000) {
      if (taskerReset)
        return;

      taskerReset = true;
      if (serverChild) {
        serverChild.killing = true;
        sync("cd " + process.cwd() + "/tasker;ssh pi@192.168.1.150 'bash -s' < pkill.sh");
      }
      android.leave();
      if (iosChild)
        iosChild.kill();
    }
    return;
  }

  // anything in the queue ?
  var job = db.getJob(false);

  if (!job || job.noJob) return;

  // start VM from snapshot
  taskerBusy = true;
  activeJob = job;

  var delay = 45000; // phones were rebooting
  // randomly also restart the raspberries
  sync("cd " + __dirname + ";./clean_nodes.sh");
  lastStartTime = Date.now() + delay;

  setTimeout(function() {
    // run task
    runTask(job);
  }, delay);
};

setInterval(testTask, 3000);<|endoftext|>


<commit_before>module.exports = function(grunt) {

  /**
   * Define "composer" tasks.
   *
   * Dynamically adds a Composer install task if a composer.json file
   * exists in the project directory.
   */
  var config = grunt.config.get('config');
  if (require('fs').existsSync('./composer.json')) {
    grunt.loadNpmTasks('grunt-composer');
    var Help = require('../lib/help')(grunt);

    grunt.config(['composer', 'install'], {});

    Help.add({
      task: 'composer',
      group: 'Dependency Management',
      description: 'Install dependencies defined in this project\'s composer.json file.'
    });
  }
};
<commit_msg>Improve performance and cacheability of composer install.<commit_after>module.exports = function(grunt) {

  /**
   * Define "composer" tasks.
   *
   * Dynamically adds a Composer install task if a composer.json file
   * exists in the project directory.
   */
  var config = grunt.config.get('config');
  if (require('fs').existsSync('./composer.json')) {
    grunt.loadNpmTasks('grunt-composer');
    var Help = require('../lib/help')(grunt);

    grunt.config(['composer', 'install'], {
      options: {
        flags: [
          'no-interaction',
          'no-progress',
          'prefer-dist'
        ],
      }
    });

    Help.add({
      task: 'composer',
      group: 'Dependency Management',
      description: 'Install dependencies defined in this project\'s composer.json file.'
    });
  }
};
<|endoftext|>


<commit_before>//     keymaster.js
//     (c) 2011 Thomas Fuchs
//     keymaster.js may be freely distributed under the MIT license.
(function(a){function h(a,b){var c=a.length;while(c--)if(a[c]===b)return c;return-1}function i(a){var b,g,i,j,k,m;g=(a.target||a.srcElement).tagName,b=a.keyCode;if(b==93||b==224)b=91;if(b in d){d[b]=!0;for(j in f)f[j]==b&&(l[j]=!0);return}if(g=="INPUT"||g=="SELECT"||g=="TEXTAREA")return;if(!(b in c))return;for(k=0;k<c[b].length;k++){i=c[b][k];if(i.scope==e||i.scope=="all"){m=i.mods.length>0;for(j in d)if(!d[j]&&h(i.mods,+j)>-1||d[j]&&h(i.mods,+j)==-1)m=!1;(i.mods.length==0&&!d[16]&&!d[18]&&!d[17]&&!d[91]||m)&&i.method(a,i)===!1&&(a.preventDefault?a.preventDefault():a.returnValue=!1,a.stopPropagation&&a.stopPropagation(),a.cancelBubble&&(a.cancelBubble=!0))}}}function j(a){var b=a.keyCode,c;if(b==93||b==224)b=91;if(b in d){d[b]=!1;for(c in f)f[c]==b&&(l[c]=!1)}}function k(){for(b in d)d[b]=!1;for(b in f)l[b]=!1}function l(a,b,d){var e,h,i,j;d===undefined&&(d=b,b="all"),a=a.replace(/\s/g,""),e=a.split(","),e[e.length-1]==""&&(e[e.length-2]+=",");for(i=0;i<e.length;i++){h=[],a=e[i].split("+");if(a.length>1){h=a.slice(0,a.length-1);for(j=0;j<h.length;j++)h[j]=f[h[j]];a=[a[a.length-1]]}a=a[0],a=g[a]||a.toUpperCase().charCodeAt(0),a in c||(c[a]=[]),c[a].push({shortcut:e[i],scope:b,method:d,key:e[i],mods:h})}}function m(a){e=a||"all"}function n(a,b,c){a.addEventListener?a.addEventListener(b,c,!1):a.attachEvent&&a.attachEvent("on"+b,function(){c(window.event)})}var b,c={},d={16:!1,18:!1,17:!1,91:!1},e="all",f={"⇧":16,shift:16,"⌥":18,alt:18,option:18,"⌃":17,ctrl:17,control:17,"⌘":91,command:91},g={backspace:8,tab:9,clear:12,enter:13,"return":13,esc:27,escape:27,space:32,left:37,up:38,right:39,down:40,del:46,"delete":46,home:36,end:35,pageup:33,pagedown:34,",":188,".":190,"/":191,"`":192,"-":189,"=":187,";":186,"'":222,"[":219,"]":221,"\\":220};for(b=1;b<20;b++)f["f"+b]=111+b;for(b in f)l[b]=!1;n(document,"keydown",i),n(document,"keyup",j),n(window,"focus",k),a.key=l,a.key.setScope=m,typeof module!="undefined"&&(module.exports=key)})(this)<commit_msg>update minified version<commit_after>//     keymaster.js
//     (c) 2011 Thomas Fuchs
//     keymaster.js may be freely distributed under the MIT license.
(function(a){function h(a,b){var c=a.length;while(c--)if(a[c]===b)return c;return-1}function i(a){var b,g,i,j,k,m;g=(a.target||a.srcElement).tagName,b=a.keyCode;if(b==93||b==224)b=91;if(b in d){d[b]=!0;for(j in f)f[j]==b&&(l[j]=!0);return}if(g=="INPUT"||g=="SELECT"||g=="TEXTAREA")return;if(!(b in c))return;for(k=0;k<c[b].length;k++){i=c[b][k];if(i.scope==e||i.scope=="all"){m=i.mods.length>0;for(j in d)if(!d[j]&&h(i.mods,+j)>-1||d[j]&&h(i.mods,+j)==-1)m=!1;(i.mods.length==0&&!d[16]&&!d[18]&&!d[17]&&!d[91]||m)&&i.method(a,i)===!1&&(a.preventDefault?a.preventDefault():a.returnValue=!1,a.stopPropagation&&a.stopPropagation(),a.cancelBubble&&(a.cancelBubble=!0))}}}function j(a){var b=a.keyCode,c;if(b==93||b==224)b=91;if(b in d){d[b]=!1;for(c in f)f[c]==b&&(l[c]=!1)}}function k(){for(b in d)d[b]=!1;for(b in f)l[b]=!1}function l(a,b,d){var e,h,i,j;d===undefined&&(d=b,b="all"),a=a.replace(/\s/g,""),e=a.split(","),e[e.length-1]==""&&(e[e.length-2]+=",");for(i=0;i<e.length;i++){h=[],a=e[i].split("+");if(a.length>1){h=a.slice(0,a.length-1);for(j=0;j<h.length;j++)h[j]=f[h[j]];a=[a[a.length-1]]}a=a[0],a=g[a]||a.toUpperCase().charCodeAt(0),a in c||(c[a]=[]),c[a].push({shortcut:e[i],scope:b,method:d,key:e[i],mods:h})}}function m(a){e=a||"all"}function n(){return e||"all"}function o(a,b,c){a.addEventListener?a.addEventListener(b,c,!1):a.attachEvent&&a.attachEvent("on"+b,function(){c(window.event)})}var b,c={},d={16:!1,18:!1,17:!1,91:!1},e="all",f={"⇧":16,shift:16,"⌥":18,alt:18,option:18,"⌃":17,ctrl:17,control:17,"⌘":91,command:91},g={backspace:8,tab:9,clear:12,enter:13,"return":13,esc:27,escape:27,space:32,left:37,up:38,right:39,down:40,del:46,"delete":46,home:36,end:35,pageup:33,pagedown:34,",":188,".":190,"/":191,"`":192,"-":189,"=":187,";":186,"'":222,"[":219,"]":221,"\\":220};for(b=1;b<20;b++)f["f"+b]=111+b;for(b in f)l[b]=!1;o(document,"keydown",i),o(document,"keyup",j),o(window,"focus",k),a.key=l,a.key.setScope=m,a.key.getScope=n,typeof module!="undefined"&&(module.exports=key)})(this)<|endoftext|>


<commit_before>/*
 * grunt-easy-rpm
 * https://github.com/panitw/easy-rpm
 *
 * Copyright (c) 2013 Panit Wechasil
 * Licensed under the MIT license.
 */

'use strict';

var shortid = require("shortid");
var path = require("path");

function writeSpecFile(grunt, files, options) {

    var pkgName = options.name+"-"+options.version+"-"+options.buildArch;
    var specFilepath = path.join(options.tempDir, "SPECS", pkgName+".spec");

    var b = [];
    var i = 0;
    b.push("%define   _topdir "+path.resolve(options.tempDir));
    b.push("");
    b.push("Name: "+options.name);
    b.push("Version: "+options.version);
    b.push("Release: "+options.release);
    b.push("Summary: "+options.summary);
    b.push("License: "+options.license);
    b.push("BuildArch: "+options.buildArch);

    if (options.dependencies.length > 0) {
      b.push("Requires: "+ options.dependencies.join(","));
    }

    b.push("");
    b.push("%description");
    b.push(options.description);
    b.push("");
    b.push("%files");
    for (i=0;i<files.length;i++) {
      b.push("\""+files[i]+"\"");
    }
    b.push("");
    b.push("%pre");
    for (i=0;i<options.preInstallScript.length;i++) {
      b.push(options.preInstallScript[i]);
    }
    b.push("");
    b.push("%post");
    for (i=0;i<options.postInstallScript.length;i++) {
      b.push(options.postInstallScript[i]);
    }
    b.push("");
    b.push("%preun");
    for (i=0;i<options.preUninstallScript.length;i++) {
      b.push(options.preUninstallScript[i]);
    }
    b.push("");
    b.push("%postun");
    for (i=0;i<options.postUninstallScript.length;i++) {
      b.push(options.postUninstallScript[i]);
    }

    var specFileContent = b.join("\n");
    grunt.file.write(specFilepath, specFileContent);

    return specFilepath;
}

module.exports = function(grunt) {

  grunt.registerMultiTask("easy_rpm", "Easily create RPM package to install files/directories", function() {

    var done = this.async();

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      name: "noname",
      summary: "No Summary",
      description: "No Description",
      version: "0.1.0",
      release: "1",
      license: "MIT",
      vendor: "Vendor",
      group: "Development/Tools",
      buildArch: "noarch",
      dependencies: [],
      preInstallScript: [],
      postInstallScript: [],
      preUninstallScript: [],
      postUninstallScript: [],
      tempDir: "tmp-"+shortid.generate(),
      keepTemp: false
    });

    var tmpDir = path.resolve(options.tempDir);
    var buildRoot = tmpDir + "/BUILDROOT/";
    var rpmStructure = ["BUILD","BUILDROOT","RPMS","SOURCES","SPECS","SRPMS"];

    //If the tmpDir exists (probably from previous build), delete it first
    if (grunt.file.exists(tmpDir)) {
      grunt.log.writeln("Deleting old tmp dir");
      grunt.file.delete(tmpDir);
    }

    //Create RPM build folder structure
    grunt.log.writeln("Creating RPM folder structure at "+tmpDir);
    for (var i=0;i<rpmStructure.length;i++) {
      grunt.file.mkdir(tmpDir+"/"+rpmStructure[i]);
    }

    //Copy source to the BUILDROOT folder
    grunt.log.writeln("Copying files to tmp directory");
    var fileBasket = [];
    this.files.forEach(function(file) {

      //All file entry should have both "src" and "dest"
      if (!file.src || !file.dest) {
        grunt.log.error("All file entries must have both 'src' and 'dest' property");
        done(false);
      }

      file.src.filter(function(srcPath) {
        var actualSrcPath = srcPath;

        //If the CWD option is specified, look for each file from CWD path
        if (file.cwd) {
          actualSrcPath = path.join(file.cwd, srcPath);
        }

        //Copy file to the BUILDROOT directory and store the actual target path
        //for generating the SPEC file
        if (!grunt.file.isDir(actualSrcPath)) {
          grunt.verbose.writeln("Copying: " + actualSrcPath);
          var copyTargetPath = path.join(buildRoot, file.dest, srcPath);
          grunt.file.copy(actualSrcPath, copyTargetPath);

          //Generate actualTargetPath and save to filebasket for later use
          var actualTargetPath = path.join(file.dest, srcPath);
          fileBasket.push(actualTargetPath);

          //If "mode" property is defined, then add the post install script to change
          //the mode of the file
          if (file.mode) {
            options.postInstallScript.push("chmod "+file.mode+" '"+actualTargetPath+"'");
          }

          //If "owner" property is defined, then add the post install script to change
          //the owner of the file
          if (file.owner) {
            options.postInstallScript.push("chown "+file.owner+" '"+actualTargetPath+"'");
          }

          //If "group" property is defined, then add the post install script to change
          //the group of the file
          if (file.group) {
            options.postInstallScript.push("chgrp "+file.group+" '"+actualTargetPath+"'");
          }
        }
      });
    });

    //Generate SPEC file
    grunt.log.writeln("Generating RPM spec file");
    var specFilepath = writeSpecFile(grunt, fileBasket, options);

    //Build RPM
    grunt.log.writeln("Building RPM package");
    grunt.util.async.series([

      //spawn rpmbuilt tool
      function(callback) {
        var buildCmd = "rpmbuild";
        var buildArgs = [
          "-bb",
          "--buildroot",
          buildRoot,
          specFilepath
        ];
        grunt.log.writeln("Execute: "+buildCmd+" "+buildArgs.join(" "));
        grunt.util.spawn({
          cmd: buildCmd,
          args: buildArgs,
        }, callback);
      },
      function(callback) {
        //Copy the build output to the current directory
        var outputFilename = options.name+"-"+options.version+"-"+options.release+"."+options.buildArch+".rpm";
        var outputFilepath = path.join(tmpDir, "RPMS", options.buildArch, outputFilename);
        grunt.log.writeln("Copy output RPM package to the current directory: "+outputFilepath);
        grunt.file.copy(outputFilepath,"./"+outputFilename);

        //Delete temp folder
        if (!options.keepTemp) {
          grunt.log.writeln("Deleting tmp folder "+tmpDir);
          grunt.file.delete(tmpDir);
        }
      }
    ],
    function (err) {
      if (!err) {
        done();
      } else {
        grunt.log.error(err);
        done(false);
      }
    });

  });
};

<commit_msg>add an option to exclude files<commit_after>/*
 * grunt-easy-rpm
 * https://github.com/panitw/easy-rpm
 *
 * Copyright (c) 2013 Panit Wechasil
 * Licensed under the MIT license.
 */

'use strict';

var shortid = require("shortid");
var path = require("path");

function writeSpecFile(grunt, files, options) {

    var pkgName = options.name+"-"+options.version+"-"+options.buildArch;
    var specFilepath = path.join(options.tempDir, "SPECS", pkgName+".spec");

    var b = [];
    var i = 0;
    b.push("%define   _topdir "+path.resolve(options.tempDir));
    b.push("");
    b.push("Name: "+options.name);
    b.push("Version: "+options.version);
    b.push("Release: "+options.release);
    b.push("Summary: "+options.summary);
    b.push("License: "+options.license);
    b.push("BuildArch: "+options.buildArch);

    if (options.dependencies.length > 0) {
      b.push("Requires: "+ options.dependencies.join(","));
    }

    b.push("");
    b.push("%description");
    b.push(options.description);
    b.push("");
    b.push("%files");
    for (i=0;i<files.length;i++) {
      b.push("\""+files[i]+"\"");
    }
    b.push("");
    b.push("%pre");
    for (i=0;i<options.preInstallScript.length;i++) {
      b.push(options.preInstallScript[i]);
    }
    b.push("");
    b.push("%post");
    for (i=0;i<options.postInstallScript.length;i++) {
      b.push(options.postInstallScript[i]);
    }
    b.push("");
    b.push("%preun");
    for (i=0;i<options.preUninstallScript.length;i++) {
      b.push(options.preUninstallScript[i]);
    }
    b.push("");
    b.push("%postun");
    for (i=0;i<options.postUninstallScript.length;i++) {
      b.push(options.postUninstallScript[i]);
    }

    var specFileContent = b.join("\n");
    grunt.file.write(specFilepath, specFileContent);

    return specFilepath;
}

module.exports = function(grunt) {

  grunt.registerMultiTask("easy_rpm", "Easily create RPM package to install files/directories", function() {

    var done = this.async();

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      name: "noname",
      summary: "No Summary",
      description: "No Description",
      version: "0.1.0",
      release: "1",
      license: "MIT",
      vendor: "Vendor",
      group: "Development/Tools",
      buildArch: "noarch",
      dependencies: [],
      preInstallScript: [],
      postInstallScript: [],
      preUninstallScript: [],
      postUninstallScript: [],
      tempDir: "tmp-"+shortid.generate(),
      keepTemp: false
    });

    var tmpDir = path.resolve(options.tempDir);
    var buildRoot = tmpDir + "/BUILDROOT/";
    var rpmStructure = ["BUILD","BUILDROOT","RPMS","SOURCES","SPECS","SRPMS"];

    //If the tmpDir exists (probably from previous build), delete it first
    if (grunt.file.exists(tmpDir)) {
      grunt.log.writeln("Deleting old tmp dir");
      grunt.file.delete(tmpDir);
    }

    //Create RPM build folder structure
    grunt.log.writeln("Creating RPM folder structure at "+tmpDir);
    for (var i=0;i<rpmStructure.length;i++) {
      grunt.file.mkdir(tmpDir+"/"+rpmStructure[i]);
    }

	//Files to exclude
	var filesToExclude = [];
    if (this.data.excludeFiles) {
      filesToExclude = grunt.file.expand(this.data.excludeFiles).map(function (fileName) {
        return path.normalize(fileName);
      });
    }

    //Copy source to the BUILDROOT folder
    grunt.log.writeln("Copying files to tmp directory");
    var fileBasket = [];
    this.files.forEach(function(file) {

      //All file entry should have both "src" and "dest"
      if (!file.src || !file.dest) {
        grunt.log.error("All file entries must have both 'src' and 'dest' property");
        done(false);
      }

      file.src.filter(function(srcPath) {
        var actualSrcPath = srcPath;

        //check whether to ignore this file
        if (filesToExclude.indexOf(actualSrcPath) >= 0) {
          return false;
        }

        //If the CWD option is specified, look for each file from CWD path
        if (file.cwd) {
          actualSrcPath = path.join(file.cwd, srcPath);
        }

        //Copy file to the BUILDROOT directory and store the actual target path
        //for generating the SPEC file
        if (!grunt.file.isDir(actualSrcPath)) {
          grunt.verbose.writeln("Copying: " + actualSrcPath);
          var copyTargetPath = path.join(buildRoot, file.dest, srcPath);
          grunt.file.copy(actualSrcPath, copyTargetPath);

          //Generate actualTargetPath and save to filebasket for later use
          var actualTargetPath = path.join(file.dest, srcPath);
          fileBasket.push(actualTargetPath);

          //If "mode" property is defined, then add the post install script to change
          //the mode of the file
          if (file.mode) {
            options.postInstallScript.push("chmod "+file.mode+" '"+actualTargetPath+"'");
          }

          //If "owner" property is defined, then add the post install script to change
          //the owner of the file
          if (file.owner) {
            options.postInstallScript.push("chown "+file.owner+" '"+actualTargetPath+"'");
          }

          //If "group" property is defined, then add the post install script to change
          //the group of the file
          if (file.group) {
            options.postInstallScript.push("chgrp "+file.group+" '"+actualTargetPath+"'");
          }
        }
      });
    });

    //Generate SPEC file
    grunt.log.writeln("Generating RPM spec file");
    var specFilepath = writeSpecFile(grunt, fileBasket, options);

    //Build RPM
    grunt.log.writeln("Building RPM package");
    grunt.util.async.series([

      //spawn rpmbuilt tool
      function(callback) {
        var buildCmd = "rpmbuild";
        var buildArgs = [
          "-bb",
          "--buildroot",
          buildRoot,
          specFilepath
        ];
        grunt.log.writeln("Execute: "+buildCmd+" "+buildArgs.join(" "));
        grunt.util.spawn({
          cmd: buildCmd,
          args: buildArgs,
        }, callback);
      },
      function(callback) {
        //Copy the build output to the current directory
        var outputFilename = options.name+"-"+options.version+"-"+options.release+"."+options.buildArch+".rpm";
        var outputFilepath = path.join(tmpDir, "RPMS", options.buildArch, outputFilename);
        grunt.log.writeln("Copy output RPM package to the current directory: "+outputFilepath);
        grunt.file.copy(outputFilepath,"./"+outputFilename);

        //Delete temp folder
        if (!options.keepTemp) {
          grunt.log.writeln("Deleting tmp folder "+tmpDir);
          grunt.file.delete(tmpDir);
        }
      }
    ],
    function (err) {
      if (!err) {
        done();
      } else {
        grunt.log.error(err);
        done(false);
      }
    });

  });
};

<|endoftext|>


<commit_before>/*
 * grunt-smoothie
 * https://github.com/hayesmaker/grunt-smoothie
 *
 * Copyright (c) 2015 @hayes_maker
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

	// Please see the Grunt documentation for more information regarding task
	// creation: http://gruntjs.com/creating-tasks
	grunt.registerMultiTask('testsmoothie', 'Test delicious smoothie made modules for your javascript projects.', function () {
		//grunt.task.requires('prompt:smoothie');
		var config = require('./helpers/config');
		var change = require('change-case');
		var c = config(grunt);
		// Merge task-specific and/or target-specific options with these defaults.
		var options = this.options({

		});

		var done = this.async();
		var compile = function() {
			var dest = options.dest;
			if (dest) {
				var template = c.getTemplate(options.moduleType, options.flavour);
				var content = grunt.template.process(template.call(this, options), { data: options });

				grunt.file.write(dest + ".js", content);

				if (options.spec === true) {
					var testTemplate = c.getSpec(options.moduleType, options.flavour);
					var testContent = grunt.template.process(testTemplate.call(this, options), {data: options});
					grunt.file.write(dest + "Spec.js", testContent);
				}

				grunt.log.writeln('smoothie served: "' + dest + '" ... delicious test!');
				done();
			}
		};

		compile();
	});

	grunt.registerMultiTask('smoothie', 'Mix delicious smoothie modules for your javascript projects', function() {
		var inquirer = require("inquirer");
		var config = require('./helpers/config');
		var change = require('change-case');
		var c = config(grunt);

		var options = this.options({
			moduleName: 'Example'
		});

		var done = this.async();

		var moduleSrc = "";
		var prefixLen = options.src.split('/').length;
		for (var i = 0; i < prefixLen - 1; i++) {
			moduleSrc+="../";
		}
		options.moduleSrc = moduleSrc + options.src;

		var compile = function(answers) {
			if (answers.moduleName) {
				options.moduleName = answers.moduleName;
			}

			options.package = answers.package || '';

			var srcDest = options.src + options.package + options.moduleName;
			var testDest = options.test + options.package + options.moduleName;

			var template = c.getTemplate(options.moduleType, options.flavour, options.moduleTemplate);
			var content = grunt.template.process(template.call(this, options), { data: options });

			grunt.file.write(srcDest + ".js", content);

			if (options.spec === true) {
				var testTemplate = c.getSpec(options.moduleType, options.flavour, options.specTemplate);
				var testContent = grunt.template.process(testTemplate.call(this, options), {data: options});
				grunt.file.write(testDest + "Spec.js", testContent);
			}

			grunt.log.writeln('smoothie served: "' + srcDest + '" ... delicious!');
			done();
		};

		var questions = [
			{
				type: 'input',
				name: 'moduleName',
				message: 'Name your node / browserify module',
				default: 'Spaces Allowed',
				filter: function (value) {
					return change.pascalCase(value);
				},
				validate: function (value) {
					if (value.length) {
						return true;
					}
				},
				when: function () {
					return true;
				}
			},
			{
				type: 'list',
				name: 'package',
				message: 'Choose package',
				choices: options.packageMap.map(function(item) {
					if(typeof item === 'string') {
						item = {
							name: change.ucFirst(item),
							value: change.lower(item) + '/'
						}
					}
					return item;
				}),
				default: '',
				when: function() {
					options.package = '';
					return options.packageMap && options.packageMap.length > 0;
				}
			}
		];

		inquirer.prompt(questions, compile);
	});
};
<commit_msg>Fix - map error if packageMap not present<commit_after>/*
 * grunt-smoothie
 * https://github.com/hayesmaker/grunt-smoothie
 *
 * Copyright (c) 2015 @hayes_maker
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

	// Please see the Grunt documentation for more information regarding task
	// creation: http://gruntjs.com/creating-tasks
	grunt.registerMultiTask('testsmoothie', 'Test delicious smoothie made modules for your javascript projects.', function () {
		//grunt.task.requires('prompt:smoothie');
		var config = require('./helpers/config');
		var change = require('change-case');
		var c = config(grunt);
		// Merge task-specific and/or target-specific options with these defaults.
		var options = this.options({

		});

		var done = this.async();
		var compile = function() {
			var dest = options.dest;
			if (dest) {
				var template = c.getTemplate(options.moduleType, options.flavour);
				var content = grunt.template.process(template.call(this, options), { data: options });

				grunt.file.write(dest + ".js", content);

				if (options.spec === true) {
					var testTemplate = c.getSpec(options.moduleType, options.flavour);
					var testContent = grunt.template.process(testTemplate.call(this, options), {data: options});
					grunt.file.write(dest + "Spec.js", testContent);
				}

				grunt.log.writeln('smoothie served: "' + dest + '" ... delicious test!');
				done();
			}
		};

		compile();
	});

	grunt.registerMultiTask('smoothie', 'Mix delicious smoothie modules for your javascript projects', function() {
		var inquirer = require("inquirer");
		var config = require('./helpers/config');
		var change = require('change-case');
		var c = config(grunt);

		var options = this.options({
			moduleName: 'Example'
		});

		options.packageMap = options.packageMap || [];

		var done = this.async();

		var moduleSrc = "";
		var prefixLen = options.src.split('/').length;
		for (var i = 0; i < prefixLen - 1; i++) {
			moduleSrc+="../";
		}
		options.moduleSrc = moduleSrc + options.src;

		var compile = function(answers) {
			if (answers.moduleName) {
				options.moduleName = answers.moduleName;
			}

			options.package = answers.package || '';

			var srcDest = options.src + options.package + options.moduleName;
			var testDest = options.test + options.package + options.moduleName;

			var template = c.getTemplate(options.moduleType, options.flavour, options.moduleTemplate);
			var content = grunt.template.process(template.call(this, options), { data: options });

			grunt.file.write(srcDest + ".js", content);

			if (options.spec === true) {
				var testTemplate = c.getSpec(options.moduleType, options.flavour, options.specTemplate);
				var testContent = grunt.template.process(testTemplate.call(this, options), {data: options});
				grunt.file.write(testDest + "Spec.js", testContent);
			}

			grunt.log.writeln('smoothie served: "' + srcDest + '" ... delicious!');
			done();
		};

		var questions = [
			{
				type: 'input',
				name: 'moduleName',
				message: 'Name your node / browserify module',
				default: 'Spaces Allowed',
				filter: function (value) {
					return change.pascalCase(value);
				},
				validate: function (value) {
					if (value.length) {
						return true;
					}
				},
				when: function () {
					return true;
				}
			},
			{
				type: 'list',
				name: 'package',
				message: 'Choose package',
				choices: options.packageMap.map(function(item) {
					if(typeof item === 'string') {
						item = {
							name: change.ucFirst(item),
							value: change.lower(item) + '/'
						}
					}
					return item;
				}),
				default: '',
				when: function() {
					options.package = '';
					return options.packageMap && options.packageMap.length > 0;
				}
			}
		];

		inquirer.prompt(questions, compile);
	});
};
<|endoftext|>


<commit_before>const childProcess = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');

const chai = require('chai');
chai.use(require('chai-diff'));
const expect = chai.expect;

const testCases = [
  {
    binInputParameters: ['-a', 'spec/artifacts/empty.handlebars'],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.amd.js'
  },
  {
    binInputParameters: [
      '-a',
      '-f',
      'TEST_OUTPUT',
      'spec/artifacts/empty.handlebars'
    ],
    outputLocation: 'TEST_OUTPUT',
    expectedOutputSpec: './spec/expected/empty.amd.js'
  },
  {
    binInputParameters: [
      '-a',
      '-n',
      'CustomNamespace.templates',
      'spec/artifacts/empty.handlebars'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.amd.namespace.js'
  },
  {
    binInputParameters: [
      '-a',
      '--namespace',
      'CustomNamespace.templates',
      'spec/artifacts/empty.handlebars'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.amd.namespace.js'
  },
  {
    binInputParameters: ['-a', '-s', 'spec/artifacts/empty.handlebars'],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.amd.simple.js'
  },
  {
    binInputParameters: ['-a', '-m', 'spec/artifacts/empty.handlebars'],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.amd.min.js'
  },
  {
    binInputParameters: [
      'spec/artifacts/known.helpers.handlebars',
      '-a',
      '-k',
      'someHelper',
      '-k',
      'anotherHelper',
      '-o'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/non.empty.amd.known.helper.js'
  },
  {
    binInputParameters: ['--help'],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/help.menu.txt'
  },
  {
    binInputParameters: ['-v'],
    outputLocation: 'stdout',
    expectedOutput: require('../package.json').version
  },
  {
    binInputParameters: [
      '-a',
      '-e',
      'hbs',
      './spec/artifacts/non.default.extension.hbs'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/non.default.extension.amd.js'
  },
  {
    binInputParameters: [
      '-a',
      '-p',
      './spec/artifacts/partial.template.handlebars'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/partial.template.js'
  },
  {
    binInputParameters: ['spec/artifacts/empty.handlebars', '-c'],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.common.js'
  },
  {
    binInputParameters: [
      'spec/artifacts/empty.handlebars',
      'spec/artifacts/empty.handlebars',
      '-a',
      '-n',
      'someNameSpace'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/namespace.amd.js'
  },
  {
    binInputParameters: [
      'spec/artifacts/empty.handlebars',
      '-h',
      'some-path/',
      '-a'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/handlebar.path.amd.js'
  },
  {
    binInputParameters: [
      'spec/artifacts/partial.template.handlebars',
      '-r',
      'spec',
      '-a'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.root.amd.js'
  },
  {
    binInputParameters: [
      '-i',
      '
1
',
      '-i',
      '
2
',
      '-N',
      'firstTemplate',
      '-N',
      'secondTemplate',
      '-a'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.name.amd.js'
  },
  {
    binInputParameters: [
      '-i',
      '
1
',
      '-a',
      '-m',
      '-N',
      'test',
      '--map',
      './spec/tmp/source.map.amd.txt'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/source.map.amd.js'
  },
  {
    binInputParameters: ['./spec/artifacts/bom.handlebars', '-b', '-a'],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/bom.amd.js'
  }
];

module.exports = function(grunt) {
  grunt.registerTask('test:bin', function() {
    testCases.forEach(
      ({
        binInputParameters,
        outputLocation,
        expectedOutputSpec,
        expectedOutput
      }) => {
        const stdout = executeBinHandlebars(...binInputParameters);

        if (!expectedOutput && expectedOutputSpec) {
          expectedOutput = fs.readFileSync(expectedOutputSpec, 'utf-8');
        }

        const useStdout = outputLocation === 'stdout';
        const normalizedOutput = normalizeCrlf(
          useStdout ? stdout : fs.readFileSync(outputLocation, 'utf-8')
        );
        const normalizedExpectedOutput = normalizeCrlf(expectedOutput);

        if (!useStdout) {
          fs.unlinkSync(outputLocation);
        }

        expect(normalizedOutput).not.to.be.differentFrom(
          normalizedExpectedOutput,
          {
            relaxedSpace: true
          }
        );
      }
    );
  });
};

// helper functions

function executeBinHandlebars(...args) {
  if (os.platform() === 'win32') {
    // On Windows, the executable handlebars.js file cannot be run directly
    const nodeJs = process.argv[0];
    return execFilesSyncUtf8(nodeJs, ['./bin/handlebars'].concat(args));
  }
  return execFilesSyncUtf8('./bin/handlebars', args);
}

function execFilesSyncUtf8(command, args) {
  const env = process.env;
  env.PATH = addPathToNodeJs(env.PATH);
  return childProcess.execFileSync(command, args, { encoding: 'utf-8', env });
}

function addPathToNodeJs(pathEnvironment) {
  return path.dirname(process.argv0) + path.delimiter + pathEnvironment;
}

function normalizeCrlf(string) {
  if (typeof string === 'string') {
    return string.replace(/\r\n/g, '\n');
  }
  return string;
}
<commit_msg>tests: added failing test for issue #1673<commit_after>const childProcess = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');

const chai = require('chai');
chai.use(require('chai-diff'));
const expect = chai.expect;

const testCases = [
  {
    binInputParameters: ['-a', 'spec/artifacts/empty.handlebars'],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.amd.js'
  },
  {
    binInputParameters: [
      '-a',
      '-f',
      'TEST_OUTPUT',
      'spec/artifacts/empty.handlebars'
    ],
    outputLocation: 'TEST_OUTPUT',
    expectedOutputSpec: './spec/expected/empty.amd.js'
  },
  {
    binInputParameters: [
      '-a',
      '-n',
      'CustomNamespace.templates',
      'spec/artifacts/empty.handlebars'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.amd.namespace.js'
  },
  {
    binInputParameters: [
      '-a',
      '--namespace',
      'CustomNamespace.templates',
      'spec/artifacts/empty.handlebars'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.amd.namespace.js'
  },
  {
    binInputParameters: ['-a', '-s', 'spec/artifacts/empty.handlebars'],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.amd.simple.js'
  },
  {
    binInputParameters: ['-a', '-m', 'spec/artifacts/empty.handlebars'],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.amd.min.js'
  },
  {
    binInputParameters: [
      'spec/artifacts/known.helpers.handlebars',
      '-a',
      '-k',
      'someHelper',
      '-k',
      'anotherHelper',
      '-o'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/non.empty.amd.known.helper.js'
  },
  {
    binInputParameters: ['--help'],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/help.menu.txt'
  },
  {
    binInputParameters: ['-v'],
    outputLocation: 'stdout',
    expectedOutput: require('../package.json').version
  },
  {
    binInputParameters: [
      '-a',
      '-e',
      'hbs',
      './spec/artifacts/non.default.extension.hbs'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/non.default.extension.amd.js'
  },
  {
    binInputParameters: [
      '-a',
      '-p',
      './spec/artifacts/partial.template.handlebars'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/partial.template.js'
  },
  {
    binInputParameters: ['spec/artifacts/empty.handlebars', '-c'],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.common.js'
  },
  {
    binInputParameters: [
      'spec/artifacts/empty.handlebars',
      'spec/artifacts/empty.handlebars',
      '-a',
      '-n',
      'someNameSpace'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/namespace.amd.js'
  },
  {
    binInputParameters: [
      'spec/artifacts/empty.handlebars',
      '-h',
      'some-path/',
      '-a'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/handlebar.path.amd.js'
  },
  {
    binInputParameters: [
      'spec/artifacts/partial.template.handlebars',
      '-r',
      'spec',
      '-a'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.root.amd.js'
  },
  {
    binInputParameters: [
      '-i',
      '
1
',
      '-i',
      '
2
',
      '-N',
      'firstTemplate',
      '-N',
      'secondTemplate',
      '-a'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.name.amd.js'
  },
  {
    binInputParameters: [
      '-i',
      '
1
',
      '-a',
      '-m',
      '-N',
      'test',
      '--map',
      './spec/tmp/source.map.amd.txt'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/source.map.amd.js'
  },
  {
    binInputParameters: ['./spec/artifacts/bom.handlebars', '-b', '-a'],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/bom.amd.js'
  },
  // Issue #1673
  {
    binInputParameters: [
      '--amd',
      '--no-amd',
      'spec/artifacts/empty.handlebars'
    ],
    outputLocation: 'stdout',
    expectedOutputSpec: './spec/expected/empty.common.js'
  }
];

module.exports = function(grunt) {
  grunt.registerTask('test:bin', function() {
    testCases.forEach(
      ({
        binInputParameters,
        outputLocation,
        expectedOutputSpec,
        expectedOutput
      }) => {
        const stdout = executeBinHandlebars(...binInputParameters);

        if (!expectedOutput && expectedOutputSpec) {
          expectedOutput = fs.readFileSync(expectedOutputSpec, 'utf-8');
        }

        const useStdout = outputLocation === 'stdout';
        const normalizedOutput = normalizeCrlf(
          useStdout ? stdout : fs.readFileSync(outputLocation, 'utf-8')
        );
        const normalizedExpectedOutput = normalizeCrlf(expectedOutput);

        if (!useStdout) {
          fs.unlinkSync(outputLocation);
        }

        expect(normalizedOutput).not.to.be.differentFrom(
          normalizedExpectedOutput,
          {
            relaxedSpace: true
          }
        );
      }
    );
  });
};

// helper functions

function executeBinHandlebars(...args) {
  if (os.platform() === 'win32') {
    // On Windows, the executable handlebars.js file cannot be run directly
    const nodeJs = process.argv[0];
    return execFilesSyncUtf8(nodeJs, ['./bin/handlebars'].concat(args));
  }
  return execFilesSyncUtf8('./bin/handlebars', args);
}

function execFilesSyncUtf8(command, args) {
  const env = process.env;
  env.PATH = addPathToNodeJs(env.PATH);
  return childProcess.execFileSync(command, args, { encoding: 'utf-8', env });
}

function addPathToNodeJs(pathEnvironment) {
  return path.dirname(process.argv0) + path.delimiter + pathEnvironment;
}

function normalizeCrlf(string) {
  if (typeof string === 'string') {
    return string.replace(/\r\n/g, '\n');
  }
  return string;
}
<|endoftext|>


<commit_before>function changeTextAreaFont() {
    var elements = document.getElementsByTagName('textarea');
    for(var i = 0; i < elements.length; i++) {
        elements[i].style.fontFamily = 'monospace';
    }
}

function resizeFirstTextAreaHeight(size) {
    var elements = document.getElementsByTagName('textarea');
    if (elements.length > 0) {
        var height = parseInt(elements[0].style.height);
        elements[0].style.height = (height + size) + "px";
    }
}

function insertText(text) {
    var elem = document.activeElement;
    var startPos = elem.selectionStart;
    var endPos = elem.selectionEnd;
    var caretPos = startPos + text.length;
    elem.value = elem.value.substring(0, startPos) + text + elem.value.substring(endPos, elem.value.length);
    lem.setSelectionRange(caretPos, caretPos);
}

function addHidden(theForm, key, value) {
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = key;
    input.value = value;
    theForm.appendChild(input);
}

function saveAsWIP() {
    var form = document.getElementById("post_form");
    addHidden(form, 'save_as_wip', 'Save as WIP');
    form.submit();
}

function shipIt() {
    var form = document.getElementById("post_form");
    addHidden(form, 'save_as_lgtm', 'Ship It!');
    form.submit();
}
<commit_msg>fix typo<commit_after>function changeTextAreaFont() {
    var elements = document.getElementsByTagName('textarea');
    for(var i = 0; i < elements.length; i++) {
        elements[i].style.fontFamily = 'monospace';
    }
}

function resizeFirstTextAreaHeight(size) {
    var elements = document.getElementsByTagName('textarea');
    if (elements.length > 0) {
        var height = parseInt(elements[0].style.height);
        elements[0].style.height = (height + size) + "px";
    }
}

function insertText(text) {
    var elem = document.activeElement;
    var startPos = elem.selectionStart;
    var endPos = elem.selectionEnd;
    var caretPos = startPos + text.length;
    elem.value = elem.value.substring(0, startPos) + text + elem.value.substring(endPos, elem.value.length);
    elem.setSelectionRange(caretPos, caretPos);
}

function addHidden(theForm, key, value) {
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = key;
    input.value = value;
    theForm.appendChild(input);
}

function saveAsWIP() {
    var form = document.getElementById("post_form");
    addHidden(form, 'save_as_wip', 'Save as WIP');
    form.submit();
}

function shipIt() {
    var form = document.getElementById("post_form");
    addHidden(form, 'save_as_lgtm', 'Ship It!');
    form.submit();
}
<|endoftext|>


<commit_before>const Client             = require('../../base/client');
const BinarySocket       = require('../../base/socket');
const getDecimalPlaces   = require('../../common/currency').getDecimalPlaces;
const getPaWithdrawalLimit = require('../../common/currency').getPaWithdrawalLimit;
const FormManager        = require('../../common/form_manager');
const validEmailToken    = require('../../common/form_validation').validEmailToken;
const localize           = require('../../../_common/localize').localize;
const getHashValue       = require('../../../_common/url').getHashValue;

const PaymentAgentWithdraw = (() => {
    const view_ids  = {
        error  : '#viewError',
        notice : '#viewNotice',
        success: '#viewSuccess',
        confirm: '#viewConfirm',
        form   : '#viewForm',
    };
    const field_ids = {
        ddl_agents: '#ddlAgents',
        txt_amount: '#txtAmount',
        txt_desc  : '#txtDescription',
    };

    let $views,
        agent_name,
        currency;

    // -----------------------
    // ----- Agents List -----
    // -----------------------
    const populateAgentsList = (response) => {
        const $ddl_agents = $(field_ids.ddl_agents);
        $ddl_agents.empty();
        const pa_list = (response.paymentagent_list || {}).list;
        if (pa_list.length > 0) {
            checkToken($ddl_agents, pa_list);
        } else {
            showPageError(localize('Payment Agent services are not available in your country or in your preferred currency.'));
        }
    };

    const checkToken = ($ddl_agents, pa_list) => {
        const token = getHashValue('token');
        if (!token) {
            BinarySocket.send({ verify_email: Client.get('email'), type: 'paymentagent_withdraw' });
            setActiveView(view_ids.notice);
        } else if (!validEmailToken(token)) {
            showPageError('token_error');
        } else {
            insertListOption($ddl_agents, localize('Please select a payment agent'), '');
            for (let i = 0; i < pa_list.length; i++) {
                insertListOption($ddl_agents, pa_list[i].name, pa_list[i].paymentagent_loginid);
            }
            setActiveView(view_ids.form);

            const form_id        = `#${$(view_ids.form).find('form').attr('id')}`;
            const min_withdrawal = getPaWithdrawalLimit(currency, 'max');
            const max_withdrawal = getPaWithdrawalLimit(currency, 'min');

            $(form_id).find('label[for="txtAmount"]').text(`${localize('Amount')} ${currency}`);
            FormManager.init(form_id, [
                { selector: field_ids.ddl_agents,        validations: ['req'], request_field: 'paymentagent_loginid' },
                { selector: field_ids.txt_amount,        validations: ['req', ['number', { type: 'float', decimals: getDecimalPlaces(currency), min_withdrawal, max_withdrawal }], ['custom', { func: () => +Client.get('balance') >= +$(field_ids.txt_amount).val(), message: localize('Insufficient balance.') }]], request_field: 'amount' },
                { selector: field_ids.txt_desc,          validations: ['general'], request_field: 'description' },

                { request_field: 'currency',              value: currency },
                { request_field: 'paymentagent_withdraw', value: 1 },
                { request_field: 'dry_run',               value: 1 },
            ], true);

            FormManager.handleSubmit({
                form_selector       : form_id,
                fnc_response_handler: withdrawResponse,
                fnc_additional_check: setAgentName,
                enable_button       : true,
            });
        }
    };

    const insertListOption = ($ddl_object, item_text, item_value) => {
        $ddl_object.append($('<option/>', { value: item_value, text: item_text }));
    };

    // ----------------------------
    // ----- Withdraw Process -----
    // ----------------------------
    const withdrawResponse = (response) => {
        const request = response.echo_req;
        switch (response.paymentagent_withdraw) {
            case 2: { // dry_run success: showing the confirmation page
                setActiveView(view_ids.confirm);

                $('#lblAgentName').text(agent_name);
                $('#lblCurrency').text(request.currency);
                $('#lblAmount').text(request.amount);

                FormManager.init(view_ids.confirm, [
                    { request_field: 'paymentagent_loginid',  value: request.paymentagent_loginid },
                    { request_field: 'amount',                value: request.amount },
                    { request_field: 'description',           value: request.description },
                    { request_field: 'currency',              value: request.currency },
                    { request_field: 'paymentagent_withdraw', value: 1 },
                ], true);

                FormManager.handleSubmit({
                    form_selector       : view_ids.confirm,
                    fnc_response_handler: withdrawResponse,
                });

                $(`${view_ids.confirm} #btnBack`).click(() => {
                    setActiveView(view_ids.form);
                });
                break;
            }
            case 1: // withdrawal success
                setActiveView(view_ids.success);
                $('#successMessage').css('display', '')
                    .attr('class', 'success-msg')
                    .html($('
', { class: 'checked' }).append($('
', { text: localize('Your request to withdraw [_1] [_2] from your account [_3] to Payment Agent [_4] account has been successfully processed.', [request.currency, request.amount, Client.get('loginid'), agent_name]) })));
                break;

            default: // error
                if (response.echo_req.dry_run === 1) {
                    setActiveView(view_ids.form);
                    $('#formMessage').setVisibility(1).html(response.error.message);
                } else if (response.error.code === 'InvalidToken') {
                    showPageError(localize('Your token has expired or is invalid. Please click [_1]here[_2] to restart the verification process.', ['', '']));
                } else {
                    showPageError(response.error.message);
                }
                break;
        }
    };

    // -----------------------------
    // ----- Message Functions -----
    // -----------------------------
    const showPageError = (err_msg, id) => {
        const $error = $(view_ids.error);
        $error.find(' > p').setVisibility(0);
        if (id) {
            $error.find(`#${id}`).setVisibility(1);
        } else {
            $error.find('#custom-error').html(err_msg).setVisibility(1);
        }
        setActiveView(view_ids.error);
    };

    // ----- View Control -----
    const setActiveView = (view_id) => {
        $views.setVisibility(0);
        $(view_id).setVisibility(1);
    };

    const onLoad = () => {
        BinarySocket.wait('get_account_status').then((data) => {
            $views = $('#paymentagent_withdrawal').find('.viewItem');
            $views.setVisibility(0);

            if (/(withdrawal|cashier)_locked/.test(data.get_account_status.status)) {
                showPageError('', 'withdrawal-locked-error');
            } else {
                currency = Client.get('currency');
                BinarySocket.send({
                    paymentagent_list: Client.get('residence'),
                    currency,
                })
                    .then(response => populateAgentsList(response));
            }
        });
    };

    const setAgentName = () => {
        agent_name = $(field_ids.ddl_agents).find('option:selected').text();
        return true;
    };

    return {
        onLoad,
    };
})();

module.exports = PaymentAgentWithdraw;
<commit_msg>align imports<commit_after>const Client               = require('../../base/client');
const BinarySocket         = require('../../base/socket');
const getDecimalPlaces     = require('../../common/currency').getDecimalPlaces;
const getPaWithdrawalLimit = require('../../common/currency').getPaWithdrawalLimit;
const FormManager          = require('../../common/form_manager');
const validEmailToken      = require('../../common/form_validation').validEmailToken;
const localize             = require('../../../_common/localize').localize;
const getHashValue         = require('../../../_common/url').getHashValue;

const PaymentAgentWithdraw = (() => {
    const view_ids  = {
        error  : '#viewError',
        notice : '#viewNotice',
        success: '#viewSuccess',
        confirm: '#viewConfirm',
        form   : '#viewForm',
    };
    const field_ids = {
        ddl_agents: '#ddlAgents',
        txt_amount: '#txtAmount',
        txt_desc  : '#txtDescription',
    };

    let $views,
        agent_name,
        currency;

    // -----------------------
    // ----- Agents List -----
    // -----------------------
    const populateAgentsList = (response) => {
        const $ddl_agents = $(field_ids.ddl_agents);
        $ddl_agents.empty();
        const pa_list = (response.paymentagent_list || {}).list;
        if (pa_list.length > 0) {
            checkToken($ddl_agents, pa_list);
        } else {
            showPageError(localize('Payment Agent services are not available in your country or in your preferred currency.'));
        }
    };

    const checkToken = ($ddl_agents, pa_list) => {
        const token = getHashValue('token');
        if (!token) {
            BinarySocket.send({ verify_email: Client.get('email'), type: 'paymentagent_withdraw' });
            setActiveView(view_ids.notice);
        } else if (!validEmailToken(token)) {
            showPageError('token_error');
        } else {
            insertListOption($ddl_agents, localize('Please select a payment agent'), '');
            for (let i = 0; i < pa_list.length; i++) {
                insertListOption($ddl_agents, pa_list[i].name, pa_list[i].paymentagent_loginid);
            }
            setActiveView(view_ids.form);

            const form_id        = `#${$(view_ids.form).find('form').attr('id')}`;
            const min_withdrawal = getPaWithdrawalLimit(currency, 'max');
            const max_withdrawal = getPaWithdrawalLimit(currency, 'min');

            $(form_id).find('label[for="txtAmount"]').text(`${localize('Amount')} ${currency}`);
            FormManager.init(form_id, [
                { selector: field_ids.ddl_agents,        validations: ['req'], request_field: 'paymentagent_loginid' },
                { selector: field_ids.txt_amount,        validations: ['req', ['number', { type: 'float', decimals: getDecimalPlaces(currency), min_withdrawal, max_withdrawal }], ['custom', { func: () => +Client.get('balance') >= +$(field_ids.txt_amount).val(), message: localize('Insufficient balance.') }]], request_field: 'amount' },
                { selector: field_ids.txt_desc,          validations: ['general'], request_field: 'description' },

                { request_field: 'currency',              value: currency },
                { request_field: 'paymentagent_withdraw', value: 1 },
                { request_field: 'dry_run',               value: 1 },
            ], true);

            FormManager.handleSubmit({
                form_selector       : form_id,
                fnc_response_handler: withdrawResponse,
                fnc_additional_check: setAgentName,
                enable_button       : true,
            });
        }
    };

    const insertListOption = ($ddl_object, item_text, item_value) => {
        $ddl_object.append($('<option/>', { value: item_value, text: item_text }));
    };

    // ----------------------------
    // ----- Withdraw Process -----
    // ----------------------------
    const withdrawResponse = (response) => {
        const request = response.echo_req;
        switch (response.paymentagent_withdraw) {
            case 2: { // dry_run success: showing the confirmation page
                setActiveView(view_ids.confirm);

                $('#lblAgentName').text(agent_name);
                $('#lblCurrency').text(request.currency);
                $('#lblAmount').text(request.amount);

                FormManager.init(view_ids.confirm, [
                    { request_field: 'paymentagent_loginid',  value: request.paymentagent_loginid },
                    { request_field: 'amount',                value: request.amount },
                    { request_field: 'description',           value: request.description },
                    { request_field: 'currency',              value: request.currency },
                    { request_field: 'paymentagent_withdraw', value: 1 },
                ], true);

                FormManager.handleSubmit({
                    form_selector       : view_ids.confirm,
                    fnc_response_handler: withdrawResponse,
                });

                $(`${view_ids.confirm} #btnBack`).click(() => {
                    setActiveView(view_ids.form);
                });
                break;
            }
            case 1: // withdrawal success
                setActiveView(view_ids.success);
                $('#successMessage').css('display', '')
                    .attr('class', 'success-msg')
                    .html($('
', { class: 'checked' }).append($('
', { text: localize('Your request to withdraw [_1] [_2] from your account [_3] to Payment Agent [_4] account has been successfully processed.', [request.currency, request.amount, Client.get('loginid'), agent_name]) })));
                break;

            default: // error
                if (response.echo_req.dry_run === 1) {
                    setActiveView(view_ids.form);
                    $('#formMessage').setVisibility(1).html(response.error.message);
                } else if (response.error.code === 'InvalidToken') {
                    showPageError(localize('Your token has expired or is invalid. Please click [_1]here[_2] to restart the verification process.', ['', '']));
                } else {
                    showPageError(response.error.message);
                }
                break;
        }
    };

    // -----------------------------
    // ----- Message Functions -----
    // -----------------------------
    const showPageError = (err_msg, id) => {
        const $error = $(view_ids.error);
        $error.find(' > p').setVisibility(0);
        if (id) {
            $error.find(`#${id}`).setVisibility(1);
        } else {
            $error.find('#custom-error').html(err_msg).setVisibility(1);
        }
        setActiveView(view_ids.error);
    };

    // ----- View Control -----
    const setActiveView = (view_id) => {
        $views.setVisibility(0);
        $(view_id).setVisibility(1);
    };

    const onLoad = () => {
        BinarySocket.wait('get_account_status').then((data) => {
            $views = $('#paymentagent_withdrawal').find('.viewItem');
            $views.setVisibility(0);

            if (/(withdrawal|cashier)_locked/.test(data.get_account_status.status)) {
                showPageError('', 'withdrawal-locked-error');
            } else {
                currency = Client.get('currency');
                BinarySocket.send({
                    paymentagent_list: Client.get('residence'),
                    currency,
                })
                    .then(response => populateAgentsList(response));
            }
        });
    };

    const setAgentName = () => {
        agent_name = $(field_ids.ddl_agents).find('option:selected').text();
        return true;
    };

    return {
        onLoad,
    };
})();

module.exports = PaymentAgentWithdraw;
<|endoftext|>


<commit_before>/* Copyright (c) 2009 Mustafa OZCAN (http://www.mustafaozcan.net)
 * Released under the MIT license
 * Version: 1.0.2
 * Requires: jquery.1.3+
 */
jQuery.fn.fixedtableheader = function(options) { var settings = jQuery.extend({ headerrowsize: 1, highlightrow: false, highlightclass: "highlight" }, options); this.each(function(i) { var $tbl = $(this); var $tblhfixed = $tbl.find("tr:lt(" + settings.headerrowsize + ")"); var headerelement = "th"; if ($tblhfixed.find(headerelement).length == 0) headerelement = "td"; if ($tblhfixed.find(headerelement).length > 0) { $tblhfixed.find(headerelement).each(function() { $(this).css("width", $(this).width()); }); var $clonedTable = $tbl.clone().empty(); var tblwidth = GetTblWidth($tbl); $clonedTable.attr("id", "fixedtableheader" + i).css({ "position": "fixed", "top": "0", "left": $tbl.offset().left }).append($tblhfixed.clone()).width(tblwidth).hide().appendTo($("body")); if (settings.highlightrow) $("tr:gt(" + (settings.headerrowsize - 1) + ")", $tbl).hover(function() { $(this).addClass(settings.highlightclass); }, function() { $(this).removeClass(settings.highlightclass); }); $(window).scroll(function() { if (jQuery.browser.msie && jQuery.browser.version == "6.0") $clonedTable.css({ "position": "absolute", "top": $(window).scrollTop(), "left": $tbl.offset().left }); else $clonedTable.css({ "position": "fixed", "top": "0", "left": $tbl.offset().left - $(window).scrollLeft() }); var sctop = $(window).scrollTop(); var elmtop = $tblhfixed.offset().top; if (sctop > elmtop && sctop <= (elmtop + $tbl.height() - $tblhfixed.height())) $clonedTable.show(); else $clonedTable.hide(); }); $(window).resize(function() { if ($clonedTable.outerWidth() != $tbl.outerWidth()) { $tblhfixed.find(headerelement).each(function(index) { var w = $(this).width(); $(this).css("width", w); $clonedTable.find(headerelement).eq(index).css("width", w); }); $clonedTable.width($tbl.outerWidth()); } $clonedTable.css("left", $tbl.offset().left); }); } }); function GetTblWidth($tbl) { var tblwidth = $tbl.outerWidth(); return tblwidth; } };
<commit_msg>Compressed<commit_after>/* Copyright (c) 2009 Mustafa OZCAN (http://www.mustafaozcan.net)
 * Released under the MIT license
 * Version: 1.0.2
 * Requires: jquery.1.3+
 */
jQuery.fn.fixedtableheader=function(a){function c(a){var b=a.outerWidth();return b}var b=jQuery.extend({headerrowsize:1,highlightrow:!1,highlightclass:"highlight"},a);this.each(function(a){var d=$(this),e=d.find("tr:lt("+b.headerrowsize+")"),f="th";if(0==e.find(f).length&&(f="td"),e.find(f).length>0){e.find(f).each(function(){$(this).css("width",$(this).width())});var g=d.clone().empty(),h=c(d);g.attr("id","fixedtableheader"+a).css({position:"fixed",top:"0",left:d.offset().left}).append(e.clone()).width(h).hide().appendTo($("body")),b.highlightrow&&$("tr:gt("+(b.headerrowsize-1)+")",d).hover(function(){$(this).addClass(b.highlightclass)},function(){$(this).removeClass(b.highlightclass)}),$(window).scroll(function(){jQuery.browser.msie&&"6.0"==jQuery.browser.version?g.css({position:"absolute",top:$(window).scrollTop(),left:d.offset().left}):g.css({position:"fixed",top:"0",left:d.offset().left-$(window).scrollLeft()});var a=$(window).scrollTop(),b=e.offset().top;a>b&&a<=b+d.height()-e.height()?g.show():g.hide()}),$(window).resize(function(){g.outerWidth()!=d.outerWidth()&&(e.find(f).each(function(a){var b=$(this).width();$(this).css("width",b),g.find(f).eq(a).css("width",b)}),g.width(d.outerWidth())),g.css("left",d.offset().left)})}})};
<|endoftext|>